Debian Codegraph @

gallery_dl/extractor/nitter.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2022-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 """Extractors for Nitter instances"""
10
11 from .common import BaseExtractor, Message
12 from .. import text, util
13
14
15 class NitterExtractor(BaseExtractor):
16 """Base class for nitter extractors"""
17 basecategory = "nitter"
18 directory_fmt = ("nitter", "{user[name]}")
19 filename_fmt = "{tweet_id}_{num}.{extension}"
20 archive_fmt = "{tweet_id}_{num}"
21 useragent = util.USERAGENT_GALLERYDL
22 request_interval = (0.5, 1.5)
23
24 def __init__(self, match):
25 self.cookies_domain = self.root.partition("://")[2]
26 BaseExtractor.__init__(self, match)
27
28 self.user = self.groups[-2]
29 self.user_id = self.groups[-1]
30 self.user_obj = None
31
32 def items(self):
33 retweets = self.config("retweets", False)
34 if videos := self.config("videos", True):
35 ytdl = (videos == "ytdl")
36 videos = True
37 self.cookies.set("hlsPlayback", "on", domain=self.cookies_domain)
38
39 for tweet in self.tweets():
40
41 if not retweets and tweet["retweet"]:
42 self.log.debug("Skipping %s (retweet)", tweet["tweet_id"])
43 continue
44
45 if attachments := tweet.pop("_attach", ""):
46 files = []
47 for url in text.extract_iter(
48 attachments, 'href="', '"'):
49
50 if "/i/broadcasts/" in url:
51 self.log.debug(
52 "Skipping unsupported broadcast '%s'", url)
53 continue
54
55 if "/enc/" in url:
56 name = util.b64decode(
57 url.rpartition("/")[2]).rpartition("/")[2]
58 else:
59 name = text.unquote(url.rpartition("%2F")[2])
60
61 if url[0] == "/":
62 url = self.root + url
63 file = text.nameext_from_url(
64 name, {"url": url, "_http_retry": _retry_on_404})
65 files.append(file)
66
67 if videos and not files:
68 if ytdl:
69 url = f"ytdl:{self.root}/i/status/{tweet['tweet_id']}"
70 files.append({"url": url, "extension": "mp4"})
71 else:
72 for url in text.extract_iter(
73 attachments, 'data-url="', '"'):
74
75 if "/enc/" in url:
76 name = util.b64decode(
77 url.rpartition("/")[2]).rpartition("/")[2]
78 else:
79 name = text.unquote(url.rpartition("%2F")[2])
80
81 if url[0] == "/":
82 url = self.root + url
83 files.append({
84 "url" : "ytdl:" + url,
85 "filename" : name.rpartition(".")[0],
86 "extension": "mp4",
87 })
88
89 for url in text.extract_iter(
90 attachments, '<source src="', '"'):
91 if url[0] == "/":
92 url = self.root + url
93 files.append(
94 text.nameext_from_url(url, {"url": url}))
95
96 else:
97 files = ()
98 tweet["count"] = len(files)
99
100 yield Message.Directory, "", tweet
101 for tweet["num"], file in enumerate(files, 1):
102 url = file["url"]
103 file.update(tweet)
104 yield Message.Url, url, file
105
106 def _tweet_from_html(self, html):
107 extr = text.extract_from(html)
108 author = {
109 "name": extr('class="fullname" href="/', '"'),
110 "nick": extr('title="', '"'),
111 }
112 extr('<span class="tweet-date', '')
113 link = extr('href="', '"')
114 return {
115 "author" : author,
116 "user" : self.user_obj or author,
117 "date" : self.parse_datetime(
118 extr('title="', '"'), "%b %d, %Y · %I:%M %p %Z"),
119 "tweet_id": link.rpartition("/")[2].partition("#")[0],
120 "content": extr('class="tweet-content', "</div").partition(">")[2],
121 "_attach" : extr('class="attachments', 'class="tweet-stats'),
122 "comments": text.parse_int(extr(
123 'class="icon-comment', '</div>').rpartition(">")[2]),
124 "retweets": text.parse_int(extr(
125 'class="icon-retweet', '</div>').rpartition(">")[2]),
126 "quotes" : text.parse_int(extr(
127 'class="icon-quote', '</div>').rpartition(">")[2]),
128 "likes" : text.parse_int(extr(
129 'class="icon-heart', '</div>').rpartition(">")[2]),
130 "retweet" : 'class="retweet-header' in html,
131 "quoted" : False,
132 }
133
134 def _tweet_from_quote(self, html):
135 extr = text.extract_from(html)
136 author = {
137 "name": extr('class="fullname" href="/', '"'),
138 "nick": extr('title="', '"'),
139 }
140 extr('<span class="tweet-date', '')
141 link = extr('href="', '"')
142 return {
143 "author" : author,
144 "user" : self.user_obj or author,
145 "date" : self.parse_datetime(
146 extr('title="', '"'), "%b %d, %Y · %I:%M %p %Z"),
147 "tweet_id": link.rpartition("/")[2].partition("#")[0],
148 "content" : extr('class="quote-text', "</div").partition(">")[2],
149 "_attach" : extr('class="attachments', '''
150 </div>'''),
151 "retweet" : False,
152 "quoted" : True,
153 }
154
155 def _user_from_html(self, html):
156 extr = text.extract_from(html, html.index('class="profile-tabs'))
157 banner = extr('class="profile-banner"><a href="', '"')
158
159 try:
160 if "/enc/" in banner:
161 uid = util.b64decode(banner.rpartition("/")[2]).split("/")[4]
162 else:
163 uid = banner.split("%2F")[4]
164 except Exception:
165 uid = 0
166
167 return {
168 "id" : uid,
169 "profile_banner" : self.root + banner if banner else "",
170 "profile_image" : self.root + extr(
171 'class="profile-card-avatar" href="', '"'),
172 "nick" : extr('title="', '"'),
173 "name" : extr('title="@', '"'),
174 "description" : extr('<p dir="auto">', '<'),
175 "date" : self.parse_datetime(
176 extr('class="profile-joindate"><span title="', '"'),
177 "%I:%M %p - %d %b %Y"),
178 "statuses_count" : text.parse_int(extr(
179 'class="profile-stat-num">', '<').replace(",", "")),
180 "friends_count" : text.parse_int(extr(
181 'class="profile-stat-num">', '<').replace(",", "")),
182 "followers_count" : text.parse_int(extr(
183 'class="profile-stat-num">', '<').replace(",", "")),
184 "favourites_count": text.parse_int(extr(
185 'class="profile-stat-num">', '<').replace(",", "")),
186 "verified" : 'title="Verified account"' in html,
187 }
188
189 def _extract_quote(self, html):
190 html, _, quote = html.partition('class="quote')
191 if quote:
192 quote, _, tail = quote.partition('class="tweet-published')
193 return (html + tail, quote)
194 return (html, None)
195
196 def _pagination(self, path):
197 more = None
198 tries = 0
199 retries = self.config("fallback-retries", 2) + 1
200 quoted = self.config("quoted", False)
201
202 if self.user_id:
203 self.user = self.request_location(
204 f"{self.root}/i/user/{self.user_id}", method="GET",
205 ).rpartition("/")[2]
206 base_url = url = f"{self.root}/{self.user}{path}"
207
208 while True:
209 tweets_html = self.request(url).text.split(
210 '<div class="timeline-item')
211
212 tlen = len(tweets_html)
213 if more is None and tlen == 1 or more is not None and \
214 tlen <= 2 and ">No more items</h2>" in tweets_html[-1]:
215 tries += 1
216 self.log.warning("Empty Tweet results (%s/%s)", tries, retries)
217 if tries >= retries:
218 break
219 continue
220
221 if self.user_obj is None:
222 self.user_obj = self._user_from_html(tweets_html[0])
223
224 del tweets_html[0]
225 for html, quote in map(self._extract_quote, tweets_html):
226 tweet = self._tweet_from_html(html)
227 if not tweet["date"]:
228 continue
229 yield tweet
230 if quoted and quote:
231 yield self._tweet_from_quote(quote)
232
233 more = text.extr(
234 tweets_html[-1], '<div class="show-more"><a href="?', '"')
235 if not more:
236 break
237 url = f"{base_url}?{text.unescape(more)}"
238 tries = 0
239
240
241 BASE_PATTERN = NitterExtractor.update({
242 "nitter.net": {
243 "root": "https://nitter.net",
244 "pattern": r"(?:www\.)?nitter\.net",
245 },
246 "nitter.space": {
247 "root": "https://nitter.space",
248 "pattern": r"(?:www\.)?nitter\.space",
249 },
250 "nitter.tiekoetter": {
251 "root": "https://nitter.tiekoetter",
252 "pattern": r"(?:www\.)?nitter\.tiekoetter\.com",
253 },
254 "xcancel": {
255 "root": "https://xcancel.com",
256 "pattern": r"(?:www\.)?xcancel\.com",
257 },
258 "lightbrd": {
259 "root": "https://lightbrd.com",
260 "pattern": r"(?:www\.)?lightbrd\.com",
261 },
262 })
263
264 USER_PATTERN = BASE_PATTERN + r"/(i(?:/user/|d:)(\d+)|[^/?#]+)"
265
266
267 class NitterTweetsExtractor(NitterExtractor):
268 subcategory = "tweets"
269 pattern = USER_PATTERN + r"(?:/tweets)?(?:$|\?|#)"
270 example = "https://nitter.net/USER"
271
272 def tweets(self):
273 return self._pagination("")
274
275
276 class NitterRepliesExtractor(NitterExtractor):
277 subcategory = "replies"
278 pattern = USER_PATTERN + r"/with_replies"
279 example = "https://nitter.net/USER/with_replies"
280
281 def tweets(self):
282 return self._pagination("/with_replies")
283
284
285 class NitterMediaExtractor(NitterExtractor):
286 subcategory = "media"
287 pattern = USER_PATTERN + r"/media"
288 example = "https://nitter.net/USER/media"
289
290 def tweets(self):
291 return self._pagination("/media")
292
293
294 class NitterSearchExtractor(NitterExtractor):
295 subcategory = "search"
296 pattern = USER_PATTERN + r"/search"
297 example = "https://nitter.net/USER/search"
298
299 def tweets(self):
300 return self._pagination("/search")
301
302
303 class NitterTweetExtractor(NitterExtractor):
304 """Extractor for nitter tweets"""
305 subcategory = "tweet"
306 directory_fmt = ("nitter", "{user[name]}")
307 filename_fmt = "{tweet_id}_{num}.{extension}"
308 archive_fmt = "{tweet_id}_{num}"
309 pattern = BASE_PATTERN + r"/(i/web|[^/?#]+)/status/(\d+())"
310 example = "https://nitter.net/USER/status/12345"
311
312 def tweets(self):
313 url = f"{self.root}/i/status/{self.user}"
314 html = text.extr(self.request(url).text, 'class="main-tweet', '''\
315 </div>
316 </div></div></div>''')
317 html, quote = self._extract_quote(html)
318 tweet = self._tweet_from_html(html)
319 if quote and self.config("quoted", False):
320 quoted = self._tweet_from_quote(quote)
321 quoted["user"] = tweet["user"]
322 return (tweet, quoted)
323 return (tweet,)
324
325
326 def _retry_on_404(response):
327 return response.status_code == 404