Twitter Direct

Remove t.co tracking links from Twitter

当前为 2020-10-01 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Twitter Direct
  3. // @description Remove t.co tracking links from Twitter
  4. // @author chocolateboy
  5. // @copyright chocolateboy
  6. // @version 0.7.0
  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@1.2.0/dist/index.umd.min.js
  15. // @require https://unpkg.com/just-safe-set@2.1.0/index.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.
  83. *
  84. * target paths can point directly to a URL node (string) or to an
  85. * array of objects. in the latter case, we find the URL object in the array
  86. * (obj.key === "card_url") and replace its URL node (obj.value.string_value)
  87. *
  88. * if the target path is an object containing a { url: path, expanded_url: path }
  89. * pair, it is expanded directly in the same way as scanned paths.
  90. */
  91. const QUERIES = [
  92. {
  93. uri: '/1.1/users/lookup.json',
  94. root: [], // returns self
  95. },
  96. {
  97. uri: /\/Conversation$/,
  98. root: 'data.conversation_timeline.instructions.*.moduleItems.*.item.itemContent.tweet.core.user.legacy',
  99. },
  100. {
  101. uri: /\/Conversation$/,
  102. root: 'data.conversation_timeline.instructions.*.entries.*.content.items.*.item.itemContent.tweet.core.user.legacy',
  103. },
  104. {
  105. uri: /\/Conversation$/,
  106. root: 'data.conversation_timeline.instructions.*.moduleItems.*.item.itemContent.tweet.legacy',
  107. scan: TWEET_PATHS,
  108. targets: ['card.binding_values', 'card.url'],
  109. },
  110. {
  111. uri: /\/Conversation$/,
  112. root: 'data.conversation_timeline.instructions.*.entries.*.content.items.*.item.itemContent.tweet.legacy',
  113. scan: TWEET_PATHS,
  114. targets: ['card.binding_values', 'card.url'],
  115. },
  116. {
  117. uri: /\/Following$/,
  118. root: 'data.user.following_timeline.timeline.instructions.*.entries.*.content.itemContent.user.legacy',
  119. },
  120. {
  121. uri: /\/Followers$/,
  122. root: 'data.user.followers_timeline.timeline.instructions.*.entries.*.content.itemContent.user.legacy',
  123. },
  124. {
  125. // used for hovercard data
  126. uri: /^\/graphql\/[^\/]+\/UserByScreenName$/,
  127. root: 'data.user.legacy',
  128. collect: Array.of,
  129. },
  130. { // DMs
  131. uri: ['/1.1/dm/inbox_initial_state.json', '/1.1/dm/user_updates.json'],
  132. root: 'inbox_initial_state.entries.*.message.message_data',
  133. scan: TWEET_PATHS,
  134. targets: [
  135. 'attachment.card.binding_values.card_url.string_value',
  136. 'attachment.card.url',
  137. ],
  138. },
  139. {
  140. root: 'globalObjects.tweets',
  141. scan: TWEET_PATHS,
  142. targets: [
  143. {
  144. url: 'card.binding_values.website_shortened_url.string_value',
  145. expanded_url: 'card.binding_values.website_url.string_value',
  146. },
  147. 'card.binding_values.card_url.string_value',
  148. 'card.url',
  149. ],
  150. },
  151. {
  152. root: 'globalObjects.tweets.*.card.users.*',
  153. },
  154. {
  155. root: 'globalObjects.users',
  156. },
  157. ]
  158.  
  159. /*
  160. * a pattern which matches the content-type header of responses we scan for
  161. * URLs: "application/json" or "application/json; charset=utf-8"
  162. */
  163. const CONTENT_TYPE = /^application\/json\b/
  164.  
  165. /*
  166. * the minimum size (in bytes) of documents we deem to be "not small"
  167. *
  168. * we log misses (i.e. no URLs ever found/replaced) in documents whose size is
  169. * greater than or equal to this value
  170. *
  171. * if we keep failing to find URLs in large documents, we may be able to speed
  172. * things up by blacklisting them, at least in theory
  173. *
  174. * (in practice, URL data is optional in most of the matched document types
  175. * (contained in arrays that can be empty), so an absence of URLs doesn't
  176. * necessarily mean URL data will never be included...)
  177. */
  178. const LOG_THRESHOLD = 1024
  179.  
  180. /*
  181. * used to keep track of which roots (don't) have matching URIs and which URIs
  182. * (don't) have matching roots
  183. */
  184. const STATS = { root: {}, uri: {} }
  185.  
  186. /*
  187. * a custom version of get-wild's `get` function which uses a simpler/faster
  188. * path parser since we don't use the extended syntax
  189. */
  190. const get = exports.getter({ split: '.' })
  191.  
  192. /**
  193. * a helper function which returns true if the supplied URL is tracked by
  194. * Twitter, false otherwise
  195. */
  196. function isTracked (url) {
  197. return (new URL(url)).hostname === TRACKING_DOMAIN
  198. }
  199.  
  200. /*
  201. * JSON.stringify helper used to serialize stats data
  202. */
  203. function replacer (key, value) {
  204. return (value instanceof Set) ? Array.from(value) : value
  205. }
  206.  
  207. /*
  208. * replace t.co URLs with the original URL in all locations in the document
  209. * which contain URLs
  210. */
  211. function transformLinks (json, uri) {
  212. let data, count = 0
  213.  
  214. if (!STATS.uri[uri]) {
  215. STATS.uri[uri] = new Set()
  216. }
  217.  
  218. try {
  219. data = JSON.parse(json)
  220. } catch (e) {
  221. console.error(`Can't parse JSON for ${uri}:`, e)
  222. return
  223. }
  224.  
  225. for (const query of QUERIES) {
  226. if (query.uri) {
  227. const uris = [].concat(query.uri)
  228. const match = uris.some(want => {
  229. return (typeof want === 'string')
  230. ? (uri === want)
  231. : want.test(uri)
  232. })
  233.  
  234. if (!match) {
  235. continue
  236. }
  237. }
  238.  
  239. if (!STATS.root[query.root]) {
  240. STATS.root[query.root] = new Set()
  241. }
  242.  
  243. const root = get(data, query.root)
  244.  
  245. // may be an array (e.g. lookup.json)
  246. if (!root || typeof root !== 'object') {
  247. continue
  248. }
  249.  
  250. const updateStats = () => {
  251. ++count
  252. STATS.uri[uri].add(query.root)
  253. STATS.root[query.root].add(uri)
  254. }
  255.  
  256. const {
  257. collect = Object.values,
  258. scan = USER_PATHS,
  259. targets = NONE,
  260. } = query
  261.  
  262. const cache = new Map()
  263. const contexts = collect(root)
  264.  
  265. for (const context of contexts) {
  266. if (!context) {
  267. continue
  268. }
  269.  
  270. // scan the context nodes for { url, expanded_url } pairs, replace
  271. // each t.co URL with its expansion, and add the mappings to the
  272. // cache
  273. for (const path of scan) {
  274. const items = get(context, path, NONE)
  275.  
  276. for (const item of items) {
  277. if (item.url && item.expanded_url) {
  278. if (isTracked(item.url)) {
  279. cache.set(item.url, item.expanded_url)
  280. item.url = item.expanded_url
  281. updateStats()
  282. }
  283. } else {
  284. console.warn("can't find url/expanded_url pair for:", { uri, root: query.root, path })
  285. }
  286. }
  287. }
  288. }
  289.  
  290. if (!targets.length) {
  291. continue
  292. }
  293.  
  294. // do a separate pass for targets because some nested card URLs are
  295. // expanded in other (earlier) tweets under the same root
  296. for (const context of contexts) {
  297. // pinpoint isolated URLs in the context which don't have a
  298. // corresponding expansion, and replace them using the mappings
  299. // we collected during the scan
  300. for (const targetPath of targets) {
  301. // this is similar to the url/expanded_url pairs handled in the
  302. // scan, but with custom property names (paths)
  303. if (targetPath && typeof targetPath === 'object') {
  304. const { url: urlPath, expanded_url: expandedUrlPath } = targetPath
  305. const url = get(context, urlPath)
  306. const expandedUrl = get(context, expandedUrlPath)
  307.  
  308. if (url && expandedUrl && isTracked(url)) {
  309. cache.set(url, expandedUrl)
  310. exports.set(context, urlPath, expandedUrl)
  311. updateStats()
  312. }
  313.  
  314. continue
  315. }
  316.  
  317. let url, $context = context, $targetPath = targetPath
  318.  
  319. const node = get(context, targetPath)
  320.  
  321. // if the target points to an array rather than a string, locate
  322. // the URL object within the array automatically
  323. if (Array.isArray(node)) {
  324. if ($context = node.find(it => it.key === 'card_url')) {
  325. $targetPath = 'value.string_value'
  326. url = get(context, $targetPath)
  327. }
  328. } else {
  329. url = node
  330. }
  331.  
  332. if (typeof url === 'string' && isTracked(url)) {
  333. const expandedUrl = cache.get(url)
  334.  
  335. if (expandedUrl) {
  336. exports.set($context, $targetPath, expandedUrl)
  337. updateStats()
  338. } else {
  339. console.warn(`can't find expanded URL for ${url} in ${uri}`)
  340. }
  341. }
  342. }
  343. }
  344. }
  345.  
  346. return { count, data }
  347. }
  348.  
  349. /*
  350. * replacement for Twitter's default response handler. we transform the response
  351. * if it's a) JSON and b) contains URL data; otherwise, we leave it unchanged
  352. */
  353. function onResponse (xhr, uri) {
  354. const contentType = xhr.getResponseHeader('Content-Type')
  355.  
  356. if (!CONTENT_TYPE.test(contentType)) {
  357. return
  358. }
  359.  
  360. const url = new URL(uri)
  361.  
  362. // exclude e.g. the config-<date>.json file from pbs.twimg.com, which is the
  363. // second biggest document (~500K) after home_latest.json (~700K)
  364. if (url.hostname !== TWITTER_API) {
  365. return
  366. }
  367.  
  368. const json = xhr.responseText
  369. const size = json.length
  370.  
  371. // fold URIs which differ only in the user ID, e.g.:
  372. // /2/timeline/profile/1234.json -> /2/timeline/profile.json
  373. const path = url.pathname.replace(/\/\d+\.json$/, '.json')
  374.  
  375. const oldStats = JSON.stringify(STATS, replacer)
  376. const transformed = transformLinks(json, path)
  377.  
  378. let count
  379.  
  380. if (transformed && (count = transformed.count)) {
  381. const descriptor = { value: JSON.stringify(transformed.data) }
  382. const clone = GMCompat.export(descriptor)
  383.  
  384. GMCompat.unsafeWindow.Object.defineProperty(xhr, 'responseText', clone)
  385. }
  386.  
  387. if (count) {
  388. const newStats = JSON.stringify(STATS, replacer)
  389.  
  390. if (newStats !== oldStats) {
  391. const replacements = 'replacement' + (count === 1 ? '' : 's')
  392. console.debug(`${count} ${replacements} in ${path} (${size} B)`)
  393. console.log(JSON.parse(newStats))
  394. }
  395. } else if (STATS.uri[path].size === 0 && size >= LOG_THRESHOLD) {
  396. console.debug(`no replacements in ${path} (${size} B)`)
  397. }
  398. }
  399.  
  400. /*
  401. * replace the built-in XHR#send method with our custom version which swaps in
  402. * our custom response handler. once done, we delegate to the original handler
  403. * (this.onreadystatechange)
  404. */
  405. function hookXHRSend (oldSend) {
  406. return function send () {
  407. const oldOnReadyStateChange = this.onreadystatechange
  408.  
  409. this.onreadystatechange = function () {
  410. if (this.readyState === this.DONE && this.responseURL && this.status === 200) {
  411. onResponse(this, this.responseURL)
  412. }
  413.  
  414. return oldOnReadyStateChange.apply(this, arguments)
  415. }
  416.  
  417. return oldSend.apply(this, arguments)
  418. }
  419. }
  420.  
  421. /*
  422. * replace the default XHR#send with our custom version, which scans responses
  423. * for tweets and expands their URLs
  424. */
  425. GMCompat.unsafeWindow.XMLHttpRequest.prototype.send = GMCompat.export(
  426. hookXHRSend(XMLHttpRequest.prototype.send)
  427. )