Twitter Direct

Remove t.co tracking links from Twitter

当前为 2020-09-16 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Twitter Direct
  3. // @description Remove t.co tracking links from Twitter
  4. // @author chocolateboy
  5. // @copyright chocolateboy
  6. // @version 0.5.1
  7. // @namespace https://github.com/chocolateboy/userscripts
  8. // @license GPL: https://www.gnu.org/copyleft/gpl.html
  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/@chocolateboy/uncommonjs@2.0.1/index.min.js
  14. // @require https://unpkg.com/get-wild@0.0.1/dist/index.umd.min.js
  15. // @require https://cdn.jsdelivr.net/npm/just-safe-set@2.1.0/index.min.js
  16. // @require https://cdn.jsdelivr.net/gh/chocolateboy/gm-compat@a26896b85770aa853b2cdaf2ff79029d8807d0c0/index.min.js
  17. // @run-at document-start
  18. // @inject-into auto
  19. // ==/UserScript==
  20.  
  21. /*
  22. * the domain we expect data (JSON) to come from. responses that aren't from
  23. * this domain are ignored.
  24. */
  25. const TWITTER_API = 'api.twitter.com'
  26.  
  27. /*
  28. * the domain intercepted links are routed through
  29. *
  30. * not all links are intercepted. exceptions include links to twitter (e.g.
  31. * https://twitter.com) and card URIs (e.g. card://123456)
  32. */
  33. const TRACKING_DOMAIN = 't.co'
  34.  
  35. /*
  36. * default locations to search for URL metadata (arrays of objects) within tweet
  37. * nodes
  38. */
  39. const TWEET_PATHS = [
  40. 'entities.media',
  41. 'entities.urls',
  42. 'extended_entities.media',
  43. 'extended_entities.urls',
  44. ]
  45.  
  46. /*
  47. * default locations to search for URL metadata (arrays of objects) within
  48. * user/profile nodes
  49. */
  50. const USER_PATHS = [
  51. 'entities.description.urls',
  52. 'entities.url.urls',
  53. ]
  54.  
  55. /*
  56. * an immutable array used in various places as a way to indicate "no values".
  57. * static to avoid unnecessary allocations.
  58. */
  59. const NONE = []
  60.  
  61. /*
  62. * paths into the JSON data in which we can find context objects, i.e. objects
  63. * which have an `entities` (and/or `extended_entities`) property which contains
  64. * URL metadata
  65. *
  66. * options:
  67. *
  68. * - uri: optional URI filter: one or more strings (equality) or regexps (match)
  69. *
  70. * - root (required): a path (string or array of steps) into the document
  71. * under which to begin searching
  72. *
  73. * - collect (default: Object.values): a function which takes a root node and
  74. * turns it into an array of context nodes to scan for URL data
  75. *
  76. * - scan (default: USER_PATHS): an array of paths to probe for arrays of
  77. * { url, expanded_url } pairs in a context node
  78. *
  79. * - targets (default: NONE): an array of paths to standalone URLs (URLs that
  80. * don't have an accompanying expansion), e.g. for URLs in cards embedded in
  81. * tweets. these URLs are replaced by expanded URLs gathered during the
  82. * scan. target paths can point directly to a URL node (string) or to an
  83. * array of objects. in the latter case, we find the URL object in the array
  84. * (.key == "card_url") and replace its URL node (obj.value.string_value)
  85. */
  86. const QUERIES = [
  87. {
  88. uri: '/1.1/users/lookup.json',
  89. root: [], // returns self
  90. },
  91. {
  92. uri: /\/Conversation$/,
  93. root: 'data.conversation_timeline.instructions.*.moduleItems.*.item.itemContent.tweet.core.user.legacy',
  94. },
  95. {
  96. uri: /\/Conversation$/,
  97. root: 'data.conversation_timeline.instructions.*.entries.*.content.items.*.item.itemContent.tweet.core.user.legacy',
  98. },
  99. {
  100. uri: /\/Conversation$/,
  101. root: 'data.conversation_timeline.instructions.*.moduleItems.*.item.itemContent.tweet.legacy',
  102. scan: TWEET_PATHS,
  103. targets: ['card.binding_values', 'card.url'],
  104. },
  105. {
  106. uri: /\/Conversation$/,
  107. root: 'data.conversation_timeline.instructions.*.entries.*.content.items.*.item.itemContent.tweet.legacy',
  108. scan: TWEET_PATHS,
  109. targets: ['card.binding_values', 'card.url'],
  110. },
  111. {
  112. uri: /\/Following$/,
  113. root: 'data.user.following_timeline.timeline.instructions.*.entries.*.content.itemContent.user.legacy',
  114. },
  115. {
  116. uri: /\/Followers$/,
  117. root: 'data.user.followers_timeline.timeline.instructions.*.entries.*.content.itemContent.user.legacy',
  118. },
  119. {
  120. // used for hovercard data
  121. uri: /^\/graphql\/[^\/]+\/UserByScreenName$/,
  122. root: 'data.user.legacy',
  123. collect: Array.of,
  124. },
  125. { // DMs
  126. uri: ['/1.1/dm/inbox_initial_state.json', '/1.1/dm/user_updates.json'],
  127. root: 'inbox_initial_state.entries.*.message.message_data',
  128. scan: TWEET_PATHS,
  129. targets: [
  130. 'attachment.card.binding_values.card_url.string_value',
  131. 'attachment.card.url',
  132. ],
  133. },
  134. {
  135. root: 'globalObjects.tweets',
  136. scan: TWEET_PATHS,
  137. targets: ['card.binding_values.card_url.string_value', 'card.url'],
  138. },
  139. {
  140. root: 'globalObjects.users',
  141. },
  142. ]
  143.  
  144. /*
  145. * a pattern which matches the content-type header of responses we scan for
  146. * URLs: "application/json" or "application/json; charset=utf-8"
  147. */
  148. const CONTENT_TYPE = /^application\/json\b/
  149.  
  150. /*
  151. * the minimum size (in bytes) of documents we deem to be "not small"
  152. *
  153. * we log misses (i.e. no URLs ever found/replaced) in documents whose size is
  154. * greater than or equal to this value
  155. *
  156. * if we keep failing to find URLs in large documents, we may be able to speed
  157. * things up by blacklisting them, at least in theory
  158. *
  159. * (in practice, URL data is optional in most of the matched document types
  160. * (contained in arrays that can be empty), so an absence of URLs doesn't
  161. * necessarily mean URL data will never be included...)
  162. */
  163. const LOG_THRESHOLD = 1024
  164.  
  165. /*
  166. * used to keep track of which roots (don't) have matching URIs and which URIs
  167. * (don't) have matching roots
  168. */
  169. const STATS = { root: {}, uri: {} }
  170.  
  171. /*
  172. * JSON.stringify helper used to serialize stats data
  173. */
  174. function replacer (key, value) {
  175. return (value instanceof Set) ? Array.from(value) : value
  176. }
  177.  
  178. /*
  179. * replace t.co URLs with the original URL in all locations in the document
  180. * which contain URLs
  181. */
  182. function transformLinks (json, uri) {
  183. let data, count = 0
  184.  
  185. if (!STATS.uri[uri]) {
  186. STATS.uri[uri] = new Set()
  187. }
  188.  
  189. try {
  190. data = JSON.parse(json)
  191. } catch (e) {
  192. console.error(`Can't parse JSON for ${uri}:`, e)
  193. return
  194. }
  195.  
  196. for (const query of QUERIES) {
  197. if (query.uri) {
  198. const uris = [].concat(query.uri)
  199. const match = uris.some(want => {
  200. return (typeof want === 'string')
  201. ? (uri === want)
  202. : want.test(uri)
  203. })
  204.  
  205. if (!match) {
  206. continue
  207. }
  208. }
  209.  
  210. if (!STATS.root[query.root]) {
  211. STATS.root[query.root] = new Set()
  212. }
  213.  
  214. const root = exports.get(data, query.root)
  215.  
  216. // may be an array (e.g. lookup.json)
  217. if (!root || typeof root !== 'object') {
  218. continue
  219. }
  220.  
  221. const updateStats = () => {
  222. ++count
  223. STATS.uri[uri].add(query.root)
  224. STATS.root[query.root].add(uri)
  225. }
  226.  
  227. const {
  228. collect = Object.values,
  229. scan = USER_PATHS,
  230. targets = NONE,
  231. } = query
  232.  
  233. const cache = new Map()
  234. const contexts = collect(root)
  235.  
  236. for (const context of contexts) {
  237. // scan the context nodes for { url, expanded_url } pairs, replace
  238. // each t.co URL with its expansion, and add the mappings to the
  239. // cache
  240. for (const path of scan) {
  241. const items = exports.get(context, path, NONE)
  242.  
  243. for (const item of items) {
  244. cache.set(item.url, item.expanded_url)
  245. item.url = item.expanded_url
  246. updateStats()
  247. }
  248. }
  249. }
  250.  
  251. // do a separate pass for targets because some nested card URLs are
  252. // expanded in other (earlier) tweets under the same root
  253. if (targets.length) {
  254. for (const context of contexts) {
  255. // pinpoint isolated URLs in the context which don't have a
  256. // corresponding expansion, and replace them using the mappings
  257. // we collected during the scan
  258. for (const target of targets) {
  259. let url, $context = context, $target = target
  260.  
  261. const node = exports.get(context, target)
  262.  
  263. // if the target points to an array rather than a string, locate
  264. // the URL object within the array automatically
  265. if (Array.isArray(node)) {
  266. if ($context = node.find(it => it.key === 'card_url')) {
  267. $target = 'value.string_value'
  268. url = exports.get($context, $target)
  269. }
  270. } else {
  271. url = node
  272. }
  273.  
  274. if (typeof url === 'string') {
  275. const $url = new URL(url)
  276.  
  277. if ($url.hostname !== TRACKING_DOMAIN) {
  278. continue
  279. }
  280.  
  281. const expandedUrl = cache.get(url)
  282.  
  283. if (expandedUrl) {
  284. exports.set($context, $target, expandedUrl)
  285. updateStats()
  286. } else {
  287. console.warn(`can't find expanded URL for ${url} in ${uri}`)
  288. }
  289. }
  290. }
  291. }
  292. }
  293. }
  294.  
  295. return { count, data }
  296. }
  297.  
  298. /*
  299. * replacement for Twitter's default response handler. we transform the response
  300. * if it's a) JSON and b) contains URL data; otherwise, we leave it unchanged
  301. */
  302. function onResponse (xhr, uri) {
  303. const contentType = xhr.getResponseHeader('Content-Type')
  304.  
  305. if (!CONTENT_TYPE.test(contentType)) {
  306. return
  307. }
  308.  
  309. const url = new URL(uri)
  310.  
  311. // exclude e.g. the config-<date>.json file from pbs.twimg.com, which is the
  312. // second biggest document (~500K) after home_latest.json (~700K)
  313. if (url.hostname !== TWITTER_API) {
  314. return
  315. }
  316.  
  317. const json = xhr.responseText
  318. const size = json.length
  319.  
  320. // fold URIs which differ only in the user ID, e.g.:
  321. // /2/timeline/profile/1234.json -> /2/timeline/profile.json
  322. const path = url.pathname.replace(/\/\d+\.json$/, '.json')
  323.  
  324. const oldStats = JSON.stringify(STATS, replacer)
  325. const transformed = transformLinks(json, path)
  326.  
  327. let count
  328.  
  329. if (transformed && (count = transformed.count)) {
  330. const descriptor = { value: JSON.stringify(transformed.data) }
  331. const clone = GMCompat.export(descriptor)
  332.  
  333. GMCompat.unsafeWindow.Object.defineProperty(xhr, 'responseText', clone)
  334. }
  335.  
  336. if (count) {
  337. const newStats = JSON.stringify(STATS, replacer)
  338.  
  339. if (newStats !== oldStats) {
  340. const replacements = 'replacement' + (count === 1 ? '' : 's')
  341. console.debug(`${count} ${replacements} in ${path} (${size} B)`)
  342. console.log(JSON.parse(newStats))
  343. }
  344. } else if (STATS.uri[path].size === 0 && size >= LOG_THRESHOLD) {
  345. console.debug(`no replacements in ${path} (${size} B)`)
  346. }
  347. }
  348.  
  349. /*
  350. * replace the built-in XHR#send method with our custom version which swaps in
  351. * our custom response handler. once done, we delegate to the original handler
  352. * (this.onreadystatechange)
  353. */
  354. function hookXHRSend (oldSend) {
  355. return function send () {
  356. const oldOnReadyStateChange = this.onreadystatechange
  357.  
  358. this.onreadystatechange = function () {
  359. if (this.readyState === this.DONE && this.responseURL && this.status === 200) {
  360. onResponse(this, this.responseURL)
  361. }
  362.  
  363. return oldOnReadyStateChange.apply(this, arguments)
  364. }
  365.  
  366. return oldSend.apply(this, arguments)
  367. }
  368. }
  369.  
  370. /*
  371. * replace the default XHR#send with our custom version, which scans responses
  372. * for tweets and expands their URLs
  373. */
  374. GMCompat.unsafeWindow.XMLHttpRequest.prototype.send = GMCompat.export(
  375. hookXHRSend(XMLHttpRequest.prototype.send)
  376. )