Twitter Direct

Remove t.co tracking links from Twitter

当前为 2021-11-13 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Twitter Direct
  3. // @description Remove t.co tracking links from Twitter
  4. // @author chocolateboy
  5. // @copyright chocolateboy
  6. // @version 2.1.5
  7. // @namespace https://github.com/chocolateboy/userscripts
  8. // @license GPL
  9. // @include https://twitter.com/
  10. // @include https://twitter.com/*
  11. // @include https://mobile.twitter.com/
  12. // @include https://mobile.twitter.com/*
  13. // @require https://unpkg.com/gm-compat@1.1.0/dist/index.iife.min.js
  14. // @run-at document-start
  15. // ==/UserScript==
  16.  
  17. /*
  18. * a pattern which matches the content-type header of responses we scan for
  19. * URLs: "application/json" or "application/json; charset=utf-8"
  20. */
  21. const CONTENT_TYPE = /^application\/json\b/
  22.  
  23. /*
  24. * document keys under which t.co URL nodes can be found when the document is a
  25. * plain object. not used when the document is an array.
  26. *
  27. * some densely-populated top-level paths don't contain t.co URLs, e.g.
  28. * $.timeline.
  29. */
  30. const DOCUMENT_ROOTS = [
  31. 'data',
  32. 'globalObjects',
  33. 'inbox_initial_state',
  34. 'users',
  35. ]
  36.  
  37. /*
  38. * keys of "legacy" objects which URL data is known to be found in/under, e.g.
  39. * we're interested in legacy.user_refs.*, legacy.retweeted_status.* and
  40. * legacy.url, but not in legacy.created_at or legacy.reply_count.
  41. *
  42. * objects under the "legacy" key typically contain dozens of keys, but t.co
  43. * URLs only exist in a handful of these.
  44. *
  45. * typically this reduces the number of keys to iterate in a legacy object from
  46. * 30 on average (max 39) to 2 or 3
  47. */
  48. const LEGACY_KEYS = [
  49. 'binding_values',
  50. 'entities',
  51. 'extended_entities',
  52. 'quoted_status_permalink',
  53. 'retweeted_status',
  54. 'retweeted_status_result',
  55. 'user_refs',
  56. ]
  57.  
  58. /*
  59. * the minimum size (in bytes) of documents we deem to be "not small"
  60. *
  61. * we log (to the console) misses (i.e. no URLs ever found/replaced) in
  62. * documents whose size is greater than or equal to this value
  63. */
  64. const LOG_THRESHOLD = 1024
  65.  
  66. /*
  67. * nodes under these keys never contain t.co URLs so we can speed up traversal
  68. * by pruning (not descending) them
  69. */
  70. const PRUNE_KEYS = new Set([
  71. 'advertiser_account_service_levels',
  72. 'card_platform',
  73. 'clientEventInfo',
  74. 'ext',
  75. 'ext_media_color',
  76. 'features',
  77. 'feedbackInfo',
  78. 'hashtags',
  79. 'original_info',
  80. 'player_image_color',
  81. 'profile_banner_extensions',
  82. 'profile_banner_extensions_media_color',
  83. 'profile_image_extensions',
  84. 'profile_image_extensions_media_color',
  85. 'responseObjects',
  86. 'sizes',
  87. 'user_mentions',
  88. 'video_info',
  89. ])
  90.  
  91. /*
  92. * a map from URI paths (strings) to the replacement count for each path. used
  93. * to keep a running total of the number of replacements in each document type
  94. */
  95. const STATS = {}
  96.  
  97. /*
  98. * a pattern which matches the domain(s) we expect data (JSON) to come from.
  99. * responses which don't come from a matching domain are ignored.
  100. */
  101. const TWITTER_API = /^(?:(?:api|mobile)\.)?twitter\.com$/
  102.  
  103. /*
  104. * a list of document URIs (paths) which are known to not contain t.co URLs and
  105. * which therefore don't need to be processed
  106. */
  107. const URL_BLACKLIST = new Set([
  108. '/i/api/1.1/hashflags.json',
  109. '/i/api/2/badge_count/badge_count.json',
  110. '/i/api/graphql/articleNudgeDomains',
  111. '/i/api/graphql/TopicToFollowSidebar',
  112. ])
  113.  
  114. /*
  115. * object keys whose corresponding values may be t.co URLs
  116. */
  117. const URL_KEYS = new Set(['url', 'string_value'])
  118.  
  119. /*
  120. * return a truthy value (the URL itself) if the supplied value is a valid URL
  121. * (string), falsey otherwise
  122. */
  123. const checkUrl = (function () {
  124. // this is faster than using the URL constructor (in v8), which incurs
  125. // the overhead of using a try/catch block
  126. const urlPattern = /^https?:\/\/\w/i
  127.  
  128. // no need to coerce the value to a string as RegExp#test does that
  129. // automatically
  130. //
  131. // https://tc39.es/ecma262/#sec-regexp.prototype.test
  132. return value => urlPattern.test(value) && value
  133. })()
  134.  
  135. /*
  136. * replace the built-in XHR#send method with a custom version which swaps in our
  137. * custom response handler. once done, we delegate to the original handler
  138. * (this.onreadystatechange)
  139. */
  140. const hookXHRSend = oldSend => {
  141. return /** @this {XMLHttpRequest} */ function send (body = null) {
  142. const oldOnReadyStateChange = this.onreadystatechange
  143.  
  144. this.onreadystatechange = function (event) {
  145. if (this.readyState === this.DONE && this.responseURL && this.status === 200) {
  146. onResponse(this, this.responseURL)
  147. }
  148.  
  149. if (oldOnReadyStateChange) {
  150. oldOnReadyStateChange.call(this, event)
  151. }
  152. }
  153.  
  154. oldSend.call(this, body)
  155. }
  156. }
  157.  
  158. /*
  159. * return true if the supplied value is an array or plain object, false otherwise
  160. */
  161. const isObject = value => value && (typeof value === 'object')
  162.  
  163. /*
  164. * return true if the supplied value is a plain object, false otherwise
  165. *
  166. * only used with JSON data, so doesn't need to be foolproof
  167. */
  168. const isPlainObject = (function () {
  169. const toString = {}.toString
  170. return value => toString.call(value) === '[object Object]'
  171. })()
  172.  
  173. /*
  174. * return true if the supplied value is a t.co URL (string), false otherwise
  175. */
  176. const isTrackedUrl = (function () {
  177. // this is faster (in v8) than using the URL constructor (and a try/catch
  178. // block)
  179. const urlPattern = /^https?:\/\/t\.co\/\w+$/
  180.  
  181. // no need to coerce the value to a string as RegExp#test does that
  182. // automatically
  183. return value => urlPattern.test(value)
  184. })()
  185.  
  186. /*
  187. * replacement for Twitter's default handler for XHR requests. we transform the
  188. * response if it's a) JSON and b) contains URL data; otherwise, we leave it
  189. * unchanged
  190. */
  191. const onResponse = (xhr, uri) => {
  192. const contentType = xhr.getResponseHeader('Content-Type')
  193.  
  194. if (!CONTENT_TYPE.test(contentType)) {
  195. return
  196. }
  197.  
  198. const url = new URL(uri)
  199.  
  200. // exclude e.g. the config-<date>.json file from pbs.twimg.com, which is the
  201. // second biggest document (~500K) after home_latest.json (~700K)
  202. if (!TWITTER_API.test(url.hostname)) {
  203. return
  204. }
  205.  
  206. const json = xhr.responseText
  207. const size = json.length
  208.  
  209. // fold paths which differ only in the user or query ID, e.g.:
  210. //
  211. // /2/timeline/profile/1234.json -> /2/timeline/profile.json
  212. // /i/api/graphql/abc123/UserTweets -> /i/api/graphql/UserTweets
  213. //
  214. const path = url.pathname
  215. .replace(/\/\d+\.json$/, '.json')
  216. .replace(/^(.+?\/graphql\/)[^\/]+\/(.+)$/, '$1$2')
  217.  
  218. if (URL_BLACKLIST.has(path)) {
  219. return
  220. }
  221.  
  222. let data
  223.  
  224. try {
  225. data = JSON.parse(json)
  226. } catch (e) {
  227. console.error(`Can't parse JSON for ${uri}:`, e)
  228. return
  229. }
  230.  
  231. if (!isObject(data)) {
  232. return
  233. }
  234.  
  235. const newPath = !(path in STATS)
  236. const count = transform(data, path)
  237.  
  238. STATS[path] = (STATS[path] || 0) + count
  239.  
  240. if (!count) {
  241. if (!STATS[path] && size > LOG_THRESHOLD) {
  242. console.debug(`no replacements in ${path} (${size} B)`)
  243. }
  244.  
  245. return
  246. }
  247.  
  248. const descriptor = { value: JSON.stringify(data) }
  249. const clone = GMCompat.export(descriptor)
  250.  
  251. GMCompat.unsafeWindow.Object.defineProperty(xhr, 'responseText', clone)
  252.  
  253. const replacements = 'replacement' + (count === 1 ? '' : 's')
  254.  
  255. console.debug(`${count} ${replacements} in ${path} (${size} B)`)
  256.  
  257. if (newPath) {
  258. console.log(STATS)
  259. }
  260. }
  261.  
  262. /*
  263. * JSON.stringify +replace+ function used by +transform+ to traverse documents
  264. * and update their URL nodes in place.
  265. */
  266. const replacerFor = state => /** @this {any} */ function replacer (key, value) {
  267. // exclude subtrees which never contain t.co URLs
  268. if (PRUNE_KEYS.has(key)) {
  269. return 0 // a terminal value to stop traversal
  270. }
  271.  
  272. // we only care about the "card_url" property in binding_values
  273. // objects/arrays. exclude the other 24 properties
  274. if (key === 'binding_values') {
  275. if (Array.isArray(value)) {
  276. const found = value.find(it => it?.key === 'card_url')
  277. return found ? [found] : 0
  278. } else if (isPlainObject(value)) {
  279. return { card_url: (value.card_url || 0) }
  280. } else {
  281. return 0
  282. }
  283. }
  284.  
  285. // reduce the keys under this.legacy (typically around 30) to the handful we
  286. // care about
  287. if (key === 'legacy' && isPlainObject(value)) {
  288. // XXX don't expand legacy.url: leaving it unexpanded results in media
  289. // URLs (e.g. YouTube URLs) appearing as clickable links in the tweet
  290. // (which we want)
  291.  
  292. // we could use an array, but it doesn't appear to be faster (in v8)
  293. const filtered = {}
  294.  
  295. for (let i = 0; i < LEGACY_KEYS.length; ++i) {
  296. const key = LEGACY_KEYS[i]
  297.  
  298. if (key in value) {
  299. filtered[key] = value[key]
  300. }
  301. }
  302.  
  303. return filtered
  304. }
  305.  
  306. // expand t.co URL nodes in place
  307. if (URL_KEYS.has(key) && isTrackedUrl(value)) {
  308. const { seen, unresolved } = state
  309.  
  310. let expandedUrl
  311.  
  312. if ((expandedUrl = seen.get(value))) {
  313. this[key] = expandedUrl
  314. ++state.count
  315. } else if ((expandedUrl = checkUrl(this.expanded_url || this.expanded))) {
  316. seen.set(value, expandedUrl)
  317. this[key] = expandedUrl
  318. ++state.count
  319. } else {
  320. let targets = unresolved.get(value)
  321.  
  322. if (!targets) {
  323. unresolved.set(value, targets = [])
  324. }
  325.  
  326. targets.push({ target: this, key })
  327. }
  328.  
  329. return 0
  330. }
  331.  
  332. // shrink terminals (don't waste space/memory in the (discarded) JSON)
  333. return isObject(value) ? value : 0
  334. }
  335.  
  336. /*
  337. * replace t.co URLs with the original URL in all locations in the document
  338. * which may contain them
  339. *
  340. * returns the number of substituted URLs
  341. */
  342. const transform = (data, path) => {
  343. const seen = new Map()
  344. const unresolved = new Map()
  345. const state = { count: 0, seen, unresolved }
  346. const replacer = replacerFor(state)
  347.  
  348. // [1] top-level tweet or user data (e.g. /favorites/create.json)
  349. if (Array.isArray(data) || ('id_str' in data) /* [1] */) {
  350. JSON.stringify(data, replacer)
  351. } else {
  352. for (const key of DOCUMENT_ROOTS) {
  353. if (key in data) {
  354. JSON.stringify(data[key], replacer)
  355. }
  356. }
  357. }
  358.  
  359. for (const [url, targets] of unresolved) {
  360. const expandedUrl = seen.get(url)
  361.  
  362. if (expandedUrl) {
  363. for (const { target, key } of targets) {
  364. target[key] = expandedUrl
  365. ++state.count
  366. }
  367.  
  368. unresolved.delete(url)
  369. }
  370. }
  371.  
  372. if (unresolved.size) {
  373. console.warn(`unresolved URIs (${path}):`, Object.fromEntries(state.unresolved))
  374. }
  375.  
  376. return state.count
  377. }
  378.  
  379. /*
  380. * replace the default XHR#send with our custom version, which scans responses
  381. * for tweets and expands their URLs
  382. */
  383. const xhrProto = GMCompat.unsafeWindow.XMLHttpRequest.prototype
  384.  
  385. xhrProto.send = GMCompat.export(hookXHRSend(xhrProto.send))