package links import ( "net/url" "strings" "unicode/utf8" ) // trackingParams are query keys that only identify who shared a link or // which campaign it came from. No site needs them to find the content. var trackingParams = map[string]bool{ "igsh": true, "igshid": true, "jplx": true, "fbclid": true, "gclid": true, "dclid": true, "gbraid": true, "wbraid": true, "msclkid": true, "yclid": true, "twclid": true, "ttclid": true, "si": true, "mc_cid": true, "mc_eid": true, "mibextid": true, "ref_src": true, "ref_url": true, "_hsenc": true, "_hsmi": true, "feature": true, "share_id": true, "rdt": true, } // siteTracking are keys that are tracking on one site and meaningful on // others: "t" is a share token on X but a start time on YouTube. var siteTracking = map[string]map[string]bool{ "x.com": {"s": true, "t": true}, "twitter.com": {"s": true, "t": true}, "tiktok.com": {"is_from_webapp": true, "sender_device": true, "sender_web_id": true, "_t": true, "_r": true, "is_copy_url": true, "web_id": true}, } // isTracking reports whether a query key of a link to site is tracking. func isTracking(site, key string) bool { k := strings.ToLower(key) if strings.HasPrefix(k, "utm_") || trackingParams[k] { return true } for host, keys := range siteTracking { if (site == host || strings.HasSuffix(site, "."+host)) && keys[k] { return true } } return false } // Clean removes tracking parameters from a link and keeps everything a // site needs, such as v on YouTube. The order of the kept parameters does // not change. A link that does not parse is returned as it is. func Clean(raw string) string { u, err := url.Parse(raw) if err != nil { return raw } site := Site(raw) var kept []string for _, part := range strings.Split(u.RawQuery, "&") { if part == "" { continue } key, _, _ := strings.Cut(part, "=") if k, err := url.QueryUnescape(key); err == nil { key = k } if !isTracking(site, key) { kept = append(kept, part) } } u.RawQuery = strings.Join(kept, "&") u.ForceQuery = false return u.String() } // Short is a link written for people: no scheme, no "www.", no trailing // slash, cut to at most max characters with an ellipsis. func Short(raw string, max int) string { u, err := url.Parse(raw) if err != nil || u.Host == "" { return shortText(raw, max) } s := strings.TrimPrefix(strings.ToLower(u.Host), "www.") + u.EscapedPath() if u.RawQuery != "" { s += "?" + u.RawQuery } return shortText(strings.TrimSuffix(s, "/"), max) } func shortText(s string, max int) string { if max < 2 || utf8.RuneCountInString(s) <= max { return s } r := []rune(s) return string(r[:max-1]) + "…" }