File size: 4,755 Bytes
5936c9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/**
 * Turn X GraphQL / SSR payloads into plain tweet objects.
 * Handles the modern `details` shape, the classic `legacy` shape and long
 * posts (`note_tweet`), and always returns *expanded* link targets.
 */
const UA =
  'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'

function unescapeJs(input) {
  let out = ''
  for (let i = 0; i < input.length; i += 1) {
    const ch = input[i]
    if (ch !== '\\') {
      out += ch
      continue
    }
    const next = input[i + 1]
    i += 1
    if (next === 'n') out += '\n'
    else if (next === 't') out += '\t'
    else if (next === 'r') out += '\r'
    else if (next === 'u') {
      out += String.fromCharCode(parseInt(input.slice(i + 1, i + 5), 16))
      i += 4
    } else out += next
  }
  return out
}

/** GraphQL payloads that x.com server-renders into its HTML. */
function extractPayloads(html) {
  const payloads = []
  const re = /value:"((?:[^"\\]|\\.)*)"/g
  let match
  while ((match = re.exec(html))) {
    if (!match[1].startsWith('{')) continue
    try {
      payloads.push(JSON.parse(unescapeJs(match[1])))
    } catch {
      /* not JSON */
    }
  }
  return payloads
}

function decodeEntities(input) {
  return String(input || '')
    .replace(/&gt;/g, '>')
    .replace(/&lt;/g, '<')
    .replace(/&amp;/g, '&')
}

function tweetFromNode(node) {
  const details = node.details || {}
  const legacy = node.legacy || {}
  const note = node.note_tweet?.note_tweet_results?.result || null
  let text = decodeEntities(note?.text || details.full_text || legacy.full_text || '')
  const id = String(node.rest_id || legacy.id_str || '')
  if (!id || !text) return null

  const ms = Number(details.created_at_ms || 0)
  const createdAt = ms ? Math.floor(ms / 1000) : Math.floor(Date.parse(legacy.created_at || '') / 1000)

  const user = node.core?.user_results?.result || {}
  const handle = user.core?.screen_name || user.legacy?.screen_name || null
  const name = user.core?.name || user.legacy?.name || null

  const media = (node.media_entities2 || legacy.extended_entities?.media || [])
    .filter((item) => item?.media_url_https || item?.media_url)
    .map((item) => ({ type: item.type || 'photo', url: item.media_url_https || item.media_url }))

  const urlEntities = [
    ...(legacy.entities?.urls || []),
    ...(details.url_entities || []),
    ...(note?.entity_set?.urls || []),
  ]
  const links = []
  const unresolved = []
  for (const item of urlEntities) {
    if (item?.expanded_url) {
      links.push(item.expanded_url)
      // Show the real address instead of t.co in the text.
      if (item.url) text = text.split(item.url).join(item.expanded_url)
    } else if (item?.url) unresolved.push(item.url)
  }
  // The trailing t.co that only points at attached photos/videos is noise.
  for (const item of legacy.entities?.media || legacy.extended_entities?.media || []) {
    if (item?.url) text = text.split(item.url).join('').trim()
  }
  // Card links (link previews) carry the target too.
  for (const value of node.card?.legacy?.binding_values || []) {
    if (value?.key === 'card_url' && value.value?.string_value) unresolved.push(value.value.string_value)
  }

  const counts = node.counts || {}
  return {
    id,
    text,
    created_at: Number.isFinite(createdAt) ? createdAt : 0,
    likes: Number(counts.favorite_count ?? legacy.favorite_count ?? 0),
    replies: Number(counts.reply_count ?? legacy.reply_count ?? 0),
    reposts: Number(counts.retweet_count ?? legacy.retweet_count ?? 0),
    views: Number(node.views?.count ?? 0),
    handle,
    name,
    media,
    links: [...new Set(links)],
    tco: [...new Set([...unresolved, ...(text.match(/https:\/\/t\.co\/[A-Za-z0-9]+/g) || [])])],
  }
}

/** Every distinct Tweet node in the payloads (retweets / quotes included). */
function tweetsFrom(payloads) {
  const found = new Map()
  const visit = (node, depth) => {
    if (!node || typeof node !== 'object' || depth > 40) return
    if (Array.isArray(node)) {
      for (const item of node) visit(item, depth + 1)
      return
    }
    const isTweet =
      node.__typename === 'Tweet' || (node.rest_id && (node.legacy?.id_str || node.details) && node.core?.user_results)
    if (isTweet && (node.details?.full_text || node.legacy?.full_text)) {
      const tweet = tweetFromNode(node)
      if (tweet && !found.has(tweet.id)) found.set(tweet.id, tweet)
    }
    for (const key of Object.keys(node)) visit(node[key], depth + 1)
  }
  for (const payload of payloads) visit(payload, 0)
  return [...found.values()].sort((a, b) => (BigInt(b.id) > BigInt(a.id) ? 1 : -1))
}

module.exports = { UA, extractPayloads, tweetsFrom, tweetFromNode, unescapeJs, decodeEntities }