Twitter Direct

Remove t.co tracking links from Twitter

当前为 2021-05-19 提交的版本,查看 最新版本

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