Debian Codegraph @

gallery_dl/extractor/utils/twitter_transaction_id.py

raw
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/home").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 if not ondemand_s:
50 extractor.log.error("Failed to extract 'ondemand.s.…a.js' key")
51
52 indices = extractor.cache(
53 self._extract_indices, ondemand_s, extractor, _mem=False)
54 if not indices:
55 extractor.log.error("Failed to extract KEY_BYTE indices")
56
57 frames = self._extract_frames(homepage)
58 if not frames:
59 extractor.log.error("Failed to extract animation frame data")
60
61 self.key_bytes = key_bytes = util.b64rdecode(key)
62 self.animation_key = self._calculate_animation_key(
63 frames, indices[0], key_bytes, indices[1:])
64
65 def _extract_verification_key(self, homepage):
66 pos = homepage.find('name="twitter-site-verification"')
67 beg = homepage.rfind("<", None, pos)
68 end = homepage.find(">", pos)
69 return text.extr(homepage[beg:end], 'content="', '"')
70
71 def _extract_indices(self, ondemand_s, extractor):
72 url = (f"https://abs.twimg.com/responsive-web/client-web"
73 f"/ondemand.s.{ondemand_s}a.js")
74 page = extractor.request(url).text
75 pattern = util.re_compile(r"\(\w\[(\d\d?)\],\s*16\)")
76 return [int(i) for i in pattern.findall(page)]
77
78 def _extract_frames(self, homepage):
79 return list(text.extract_iter(
80 homepage, 'id="loading-x-anim-', "</svg>"))
81
82 def _calculate_animation_key(self, frames, row_index, key_bytes,
83 key_bytes_indices, total_time=4096):
84 frame = frames[key_bytes[5] % 4]
85 array = self._generate_2d_array(frame)
86 frame_row = array[key_bytes[row_index] % 16]
87
88 frame_time = 1
89 for index in key_bytes_indices:
90 frame_time *= key_bytes[index] % 16
91 frame_time = round_js(frame_time / 10) * 10
92 target_time = frame_time / total_time
93
94 return self.animate(frame_row, target_time)
95
96 def _generate_2d_array(self, frame):
97 split = util.re_compile(r"[^\d]+").split
98 return [
99 [int(x) for x in split(path) if x]
100 for path in text.extr(
101 frame, '</path><path d="', '"')[9:].split("C")
102 ]
103
104 def animate(self, frames, target_time):
105 curve = [scale(float(frame), is_odd(index), 1.0, False)
106 for index, frame in enumerate(frames[7:])]
107 cubic = cubic_value(curve, target_time)
108
109 color_a = (float(frames[0]), float(frames[1]), float(frames[2]))
110 color_b = (float(frames[3]), float(frames[4]), float(frames[5]))
111 color = interpolate_list(cubic, color_a, color_b)
112 color = [0.0 if c <= 0.0 else 255.0 if c >= 255.0 else c
113 for c in color]
114
115 rotation_a = 0.0
116 rotation_b = scale(float(frames[6]), 60.0, 360.0, True)
117 rotation = interpolate_value(cubic, rotation_a, rotation_b)
118 matrix = rotation_matrix_2d(rotation)
119
120 result = (
121 hex(round(color[0]))[2:],
122 hex(round(color[1]))[2:],
123 hex(round(color[2]))[2:],
124 float_to_hex(abs(round(matrix[0], 2))),
125 float_to_hex(abs(round(matrix[1], 2))),
126 float_to_hex(abs(round(matrix[2], 2))),
127 float_to_hex(abs(round(matrix[3], 2))),
128 "00",
129 )
130 return "".join(result).replace(".", "").replace("-", "")
131
132 def generate_transaction_id(self, method, path,
133 keyword="obfiowerehiring", rndnum=3):
134 bytes_key = self.key_bytes
135
136 nowf = time.time()
137 nowi = int(nowf)
138 now = nowi - 1682924400
139 bytes_time = (
140 (now ) & 0xFF, # noqa: E202
141 (now >> 8) & 0xFF, # noqa: E222
142 (now >> 16) & 0xFF,
143 (now >> 24) & 0xFF,
144 )
145
146 payload = f"{method}!{path}!{now}{keyword}{self.animation_key}"
147 bytes_hash = hashlib.sha256(payload.encode()).digest()[:16]
148
149 num = (random.randrange(16) << 4) + int((nowf - nowi) * 16.0)
150 result = bytes(
151 byte ^ num
152 for byte in itertools.chain(
153 (0,), bytes_key, bytes_time, bytes_hash, (rndnum,))
154 )
155 return util.b64rencode(result)
156
157
158 # Cubic Curve
159
160 def cubic_value(curve, t):
161 if t <= 0.0:
162 if curve[0] > 0.0:
163 value = curve[1] / curve[0]
164 elif curve[1] == 0.0 and curve[2] > 0.0:
165 value = curve[3] / curve[2]
166 else:
167 value = 0.0
168 return value * t
169
170 if t >= 1.0:
171 if curve[2] < 1.0:
172 value = (curve[3] - 1.0) / (curve[2] - 1.0)
173 elif curve[2] == 1.0 and curve[0] < 1.0:
174 value = (curve[1] - 1.0) / (curve[0] - 1.0)
175 else:
176 value = 0.0
177 return 1.0 + value * (t - 1.0)
178
179 start = 0.0
180 end = 1.0
181 while start < end:
182 mid = (start + end) / 2.0
183 est = cubic_calculate(curve[0], curve[2], mid)
184 if abs(t - est) < 0.00001:
185 return cubic_calculate(curve[1], curve[3], mid)
186 if est < t:
187 start = mid
188 else:
189 end = mid
190 return cubic_calculate(curve[1], curve[3], mid)
191
192
193 def cubic_calculate(a, b, m):
194 m1 = 1.0 - m
195 return 3.0*a*m1*m1*m + 3.0*b*m1*m*m + m*m*m
196
197
198 # Interpolation
199
200 def interpolate_list(x, a, b):
201 return [
202 interpolate_value(x, a[i], b[i])
203 for i in range(len(a))
204 ]
205
206
207 def interpolate_value(x, a, b):
208 if isinstance(a, bool):
209 return a if x <= 0.5 else b
210 return a * (1.0 - x) + b * x
211
212
213 # Rotation
214
215 def rotation_matrix_2d(deg):
216 rad = math.radians(deg)
217 cos = math.cos(rad)
218 sin = math.sin(rad)
219 return [cos, -sin, sin, cos]
220
221
222 # Utilities
223
224 def float_to_hex(numf):
225 numi = int(numf)
226
227 fraction = numf - numi
228 if not fraction:
229 return hex(numi)[2:]
230
231 result = ["."]
232 while fraction > 0.0:
233 fraction *= 16.0
234 integer = int(fraction)
235 fraction -= integer
236 result.append(chr(integer + 87) if integer > 9 else str(integer))
237 return hex(numi)[2:] + "".join(result)
238
239
240 def is_odd(num):
241 return -1.0 if num % 2 else 0.0
242
243
244 def round_js(num):
245 floor = math.floor(num)
246 return floor if (num - floor) < 0.5 else math.ceil(num)
247
248
249 def scale(value, value_min, value_max, rounding):
250 result = value * (value_max-value_min) / 255.0 + value_min
251 return math.floor(result) if rounding else round(result, 2)