Debian Codegraph @

gallery_dl/extractor/utils/twitter_transaction_id.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2025-2026 Mike Fährmann
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License version 2 as
7 # published by the Free Software Foundation.
8
9 # Adapted from iSarabjitDhiman/XClientTransaction
10 # https://github.com/iSarabjitDhiman/XClientTransaction
11
12 # References:
13 # https://antibot.blog/posts/1741552025433
14 # https://antibot.blog/posts/1741552092462
15 # https://antibot.blog/posts/1741552163416
16
17 """Twitter 'x-client-transaction-id' header generation"""
18
19 import math
20 import time
21 import random
22 import hashlib
23 import itertools
24 from ... import text, util
25
26
27 class ClientTransaction():
28 __slots__ = ("key_bytes", "animation_key")
29
30 def __getstate__(self):
31 return (self.key_bytes, self.animation_key)
32
33 def __setstate__(self, state):
34 self.key_bytes, self.animation_key = state
35
36 def initialize(self, extractor, homepage=None):
37 if homepage is None:
38 homepage = extractor.request("https://x.com/").text
39
40 key = self._extract_verification_key(homepage)
41 if not key:
42 extractor.log.error(
43 "Failed to extract 'twitter-site-verification' key")
44
45 ondemand_pos = homepage.find('"ondemand.s"')
46 ondemand_key = text.rextr(homepage, ",", ':', ondemand_pos)
47 ondemand_s = text.extract(
48 homepage, ondemand_key + ':"', '"', ondemand_pos)[0]
49
50 indices = extractor.cache(
51 self._extract_indices, ondemand_s, extractor, _mem=False)
52 if not indices:
53 extractor.log.error("Failed to extract KEY_BYTE indices")
54
55 frames = self._extract_frames(homepage)
56 if not frames:
57 extractor.log.error("Failed to extract animation frame data")
58
59 self.key_bytes = key_bytes = util.b64rdecode(key)
60 self.animation_key = self._calculate_animation_key(
61 frames, indices[0], key_bytes, indices[1:])
62
63 def _extract_verification_key(self, homepage):
64 pos = homepage.find('name="twitter-site-verification"')
65 beg = homepage.rfind("<", None, pos)
66 end = homepage.find(">", pos)
67 return text.extr(homepage[beg:end], 'content="', '"')
68
69 def _extract_indices(self, ondemand_s, extractor):
70 url = (f"https://abs.twimg.com/responsive-web/client-web"
71 f"/ondemand.s.{ondemand_s}a.js")
72 page = extractor.request(url).text
73 pattern = util.re_compile(r"\(\w\[(\d\d?)\],\s*16\)")
74 return [int(i) for i in pattern.findall(page)]
75
76 def _extract_frames(self, homepage):
77 return list(text.extract_iter(
78 homepage, 'id="loading-x-anim-', "</svg>"))
79
80 def _calculate_animation_key(self, frames, row_index, key_bytes,
81 key_bytes_indices, total_time=4096):
82 frame = frames[key_bytes[5] % 4]
83 array = self._generate_2d_array(frame)
84 frame_row = array[key_bytes[row_index] % 16]
85
86 frame_time = 1
87 for index in key_bytes_indices:
88 frame_time *= key_bytes[index] % 16
89 frame_time = round_js(frame_time / 10) * 10
90 target_time = frame_time / total_time
91
92 return self.animate(frame_row, target_time)
93
94 def _generate_2d_array(self, frame):
95 split = util.re_compile(r"[^\d]+").split
96 return [
97 [int(x) for x in split(path) if x]
98 for path in text.extr(
99 frame, '</path><path d="', '"')[9:].split("C")
100 ]
101
102 def animate(self, frames, target_time):
103 curve = [scale(float(frame), is_odd(index), 1.0, False)
104 for index, frame in enumerate(frames[7:])]
105 cubic = cubic_value(curve, target_time)
106
107 color_a = (float(frames[0]), float(frames[1]), float(frames[2]))
108 color_b = (float(frames[3]), float(frames[4]), float(frames[5]))
109 color = interpolate_list(cubic, color_a, color_b)
110 color = [0.0 if c <= 0.0 else 255.0 if c >= 255.0 else c
111 for c in color]
112
113 rotation_a = 0.0
114 rotation_b = scale(float(frames[6]), 60.0, 360.0, True)
115 rotation = interpolate_value(cubic, rotation_a, rotation_b)
116 matrix = rotation_matrix_2d(rotation)
117
118 result = (
119 hex(round(color[0]))[2:],
120 hex(round(color[1]))[2:],
121 hex(round(color[2]))[2:],
122 float_to_hex(abs(round(matrix[0], 2))),
123 float_to_hex(abs(round(matrix[1], 2))),
124 float_to_hex(abs(round(matrix[2], 2))),
125 float_to_hex(abs(round(matrix[3], 2))),
126 "00",
127 )
128 return "".join(result).replace(".", "").replace("-", "")
129
130 def generate_transaction_id(self, method, path,
131 keyword="obfiowerehiring", rndnum=3):
132 bytes_key = self.key_bytes
133
134 nowf = time.time()
135 nowi = int(nowf)
136 now = nowi - 1682924400
137 bytes_time = (
138 (now ) & 0xFF, # noqa: E202
139 (now >> 8) & 0xFF, # noqa: E222
140 (now >> 16) & 0xFF,
141 (now >> 24) & 0xFF,
142 )
143
144 payload = f"{method}!{path}!{now}{keyword}{self.animation_key}"
145 bytes_hash = hashlib.sha256(payload.encode()).digest()[:16]
146
147 num = (random.randrange(16) << 4) + int((nowf - nowi) * 16.0)
148 result = bytes(
149 byte ^ num
150 for byte in itertools.chain(
151 (0,), bytes_key, bytes_time, bytes_hash, (rndnum,))
152 )
153 return util.b64rencode(result)
154
155
156 # Cubic Curve
157
158 def cubic_value(curve, t):
159 if t <= 0.0:
160 if curve[0] > 0.0:
161 value = curve[1] / curve[0]
162 elif curve[1] == 0.0 and curve[2] > 0.0:
163 value = curve[3] / curve[2]
164 else:
165 value = 0.0
166 return value * t
167
168 if t >= 1.0:
169 if curve[2] < 1.0:
170 value = (curve[3] - 1.0) / (curve[2] - 1.0)
171 elif curve[2] == 1.0 and curve[0] < 1.0:
172 value = (curve[1] - 1.0) / (curve[0] - 1.0)
173 else:
174 value = 0.0
175 return 1.0 + value * (t - 1.0)
176
177 start = 0.0
178 end = 1.0
179 while start < end:
180 mid = (start + end) / 2.0
181 est = cubic_calculate(curve[0], curve[2], mid)
182 if abs(t - est) < 0.00001:
183 return cubic_calculate(curve[1], curve[3], mid)
184 if est < t:
185 start = mid
186 else:
187 end = mid
188 return cubic_calculate(curve[1], curve[3], mid)
189
190
191 def cubic_calculate(a, b, m):
192 m1 = 1.0 - m
193 return 3.0*a*m1*m1*m + 3.0*b*m1*m*m + m*m*m
194
195
196 # Interpolation
197
198 def interpolate_list(x, a, b):
199 return [
200 interpolate_value(x, a[i], b[i])
201 for i in range(len(a))
202 ]
203
204
205 def interpolate_value(x, a, b):
206 if isinstance(a, bool):
207 return a if x <= 0.5 else b
208 return a * (1.0 - x) + b * x
209
210
211 # Rotation
212
213 def rotation_matrix_2d(deg):
214 rad = math.radians(deg)
215 cos = math.cos(rad)
216 sin = math.sin(rad)
217 return [cos, -sin, sin, cos]
218
219
220 # Utilities
221
222 def float_to_hex(numf):
223 numi = int(numf)
224
225 fraction = numf - numi
226 if not fraction:
227 return hex(numi)[2:]
228
229 result = ["."]
230 while fraction > 0.0:
231 fraction *= 16.0
232 integer = int(fraction)
233 fraction -= integer
234 result.append(chr(integer + 87) if integer > 9 else str(integer))
235 return hex(numi)[2:] + "".join(result)
236
237
238 def is_odd(num):
239 return -1.0 if num % 2 else 0.0
240
241
242 def round_js(num):
243 floor = math.floor(num)
244 return floor if (num - floor) < 0.5 else math.ceil(num)
245
246
247 def scale(value, value_min, value_max, rounding):
248 result = value * (value_max-value_min) / 255.0 + value_min
249 return math.floor(result) if rounding else round(result, 2)