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