Debian Codegraph @

gallery_dl/extractor/8chan.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 https://8chan.moe/"""
10
11 from .common import Extractor, Message
12 from .. import text, dt
13 import itertools
14
15 BASE_PATTERN = r"(?:https?://)?8chan\.(moe|se|cc)"
16
17
18 class _8chanExtractor(Extractor):
19 """Base class for 8chan extractors"""
20 category = "8chan"
21 root = "https://8chan.moe"
22
23 def __init__(self, match):
24 self.root = "https://8chan." + match[1]
25 Extractor.__init__(self, match)
26
27 def cookies_tos_name(self):
28 domain = "8chan." + self.groups[0]
29 for cookie in self.cookies:
30 if cookie.domain == domain and \
31 cookie.name.lower().startswith("tos"):
32 self.log.debug("TOS cookie name: %s", cookie.name)
33 return cookie.name
34
35 url = self.root + "/.static/pages/confirmed.html"
36 headers = {"Referer": self.root + "/.static/pages/disclaimer.html"}
37 response = self.request(url, headers=headers, allow_redirects=False)
38
39 for cookie in response.cookies:
40 if cookie.name.lower().startswith("tos"):
41 self.log.debug("TOS cookie name: %s", cookie.name)
42 return cookie.name
43
44 self.log.error("Unable to determin TOS cookie name")
45 return "TOS20250418"
46
47 def cookies_prepare(self):
48 # fetch captcha cookies
49 # (necessary to download without getting interrupted)
50 now = dt.now()
51 url = self.root + "/captcha.js"
52 params = {"d": now.strftime("%a %b %d %Y %H:%M:%S GMT+0000 (UTC)")}
53 self.request(url, params=params).content
54
55 # adjust cookies
56 # - remove 'expires' timestamp
57 # - move 'captchaexpiration' value forward by 1 month
58 domain = self.root.rpartition("/")[2]
59 for cookie in self.cookies:
60 if cookie.domain.endswith(domain):
61 cookie.expires = None
62 if cookie.name == "captchaexpiration":
63 cookie.value = (now + dt.timedelta(30, 300)).strftime(
64 "%a, %d %b %Y %H:%M:%S GMT")
65
66 return self.cookies
67
68
69 class _8chanThreadExtractor(_8chanExtractor):
70 """Extractor for 8chan threads"""
71 subcategory = "thread"
72 directory_fmt = ("{category}", "{boardUri}",
73 "{threadId} {subject[:50]}")
74 filename_fmt = "{postId}{num:?-//} {filename[:200]}.{extension}"
75 archive_fmt = "{boardUri}_{postId}_{num}"
76 pattern = BASE_PATTERN + r"/([^/?#]+)/(?:res|last)/(\d+)"
77 example = "https://8chan.moe/a/res/12345.html"
78
79 def items(self):
80 _, board, thread = self.groups
81 tos = self.cache(self.cookies_tos_name, _key=None)
82 self.cookies.set(tos, "1", domain=self.root[8:])
83
84 # fetch thread data
85 url = f"{self.root}/{board}/res/{thread}."
86 self.session.headers["Referer"] = url + "html"
87 thread = self.request_json(url + "json")
88 thread["postId"] = thread["threadId"]
89 thread["_http_headers"] = {"Referer": url + "html"}
90
91 try:
92 self.cookies = self.cache(self.cookies_prepare, _key=None)
93 except Exception as exc:
94 self.log.debug("Failed to fetch captcha cookies: %s: %s",
95 exc.__class__.__name__, exc, exc_info=exc)
96
97 # download files
98 posts = thread.pop("posts", ())
99 yield Message.Directory, "", thread
100 for post in itertools.chain((thread,), posts):
101 files = post.pop("files", ())
102 if not files:
103 continue
104 thread.update(post)
105 for num, file in enumerate(files):
106 file.update(thread)
107 file["num"] = num
108 file["_http_validate"] = _validate
109 text.nameext_from_url(file["originalName"], file)
110 yield Message.Url, self.root + file["path"], file
111
112
113 class _8chanBoardExtractor(_8chanExtractor):
114 """Extractor for 8chan boards"""
115 subcategory = "board"
116 pattern = BASE_PATTERN + r"/([^/?#]+)/(?:(\d+)\.html)?$"
117 example = "https://8chan.moe/a/"
118
119 def items(self):
120 _, board, pnum = self.groups
121 tos = self.cache(self.cookies_tos_name, _key=None)
122 self.cookies.set(tos, "1", domain=self.root[8:])
123
124 pnum = text.parse_int(pnum, 1)
125 url = f"{self.root}/{board}/{pnum}.json"
126 data = self.request_json(url)
127 threads = data["threads"]
128
129 while True:
130 for thread in threads:
131 thread["_extractor"] = _8chanThreadExtractor
132 url = f"{self.root}/{board}/res/{thread['threadId']}.html"
133 yield Message.Queue, url, thread
134
135 pnum += 1
136 if pnum > data["pageCount"]:
137 return
138 url = f"{self.root}/{board}/{pnum}.json"
139 threads = self.request_json(url)["threads"]
140
141
142 def _validate(response):
143 hget = response.headers.get
144 return not (
145 hget("expires") == "0" and
146 hget("content-length") == "166" and
147 hget("content-type") == "image/png"
148 )