Debian Codegraph @

gallery_dl/extractor/hentaifoundry.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2015-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://www.hentai-foundry.com/"""
10
11 from .common import Extractor, Message, Dispatch
12 from .. import text, util
13
14 BASE_PATTERN = r"(https?://)?(?:www\.)?hentai-foundry\.com"
15
16
17 class HentaifoundryExtractor(Extractor):
18 """Base class for hentaifoundry extractors"""
19 category = "hentaifoundry"
20 directory_fmt = ("{category}", "{user}")
21 filename_fmt = "{category}_{index}_{title}.{extension}"
22 archive_fmt = "{index}"
23 cookies_domain = "www.hentai-foundry.com"
24 root = "https://www.hentai-foundry.com"
25 per_page = 25
26
27 def __init__(self, match):
28 self.root = (match[1] or "https://") + "www.hentai-foundry.com"
29 self.user = match[2]
30 Extractor.__init__(self, match)
31 self.page_url = ""
32 self.start_post = 0
33 self.start_page = 1
34
35 def _init(self):
36 if self.config("descriptions") == "html":
37 self._process_description = self._process_description_html
38
39 def items(self):
40 self._init_site_filters()
41 data = self.metadata()
42
43 for post_url in util.advance(self.posts(), self.start_post):
44 image = self._parse_post(post_url)
45 image.update(data)
46 yield Message.Directory, "", image
47 yield Message.Url, image["src"], image
48
49 def skip_files(self, num):
50 pages, posts = divmod(num, self.per_page)
51 self.start_page += pages
52 self.start_post += posts
53 return num
54
55 def metadata(self):
56 return {"user": self.user}
57
58 def posts(self):
59 return self._pagination(self.page_url)
60
61 def _pagination(self, url, begin='thumbTitle"><a href="', end='"'):
62 num = self.start_page
63
64 while True:
65 page = self.request(f"{url}/page/{num}").text
66 yield from text.extract_iter(page, begin, end)
67
68 if 'class="pager"' not in page or 'class="last hidden"' in page:
69 return
70 num += 1
71
72 def _parse_post(self, path):
73 """Collect url and metadata from an image post"""
74 url = text.urljoin(self.root, path)
75 page = self.request(url).text
76 extr = text.extract_from(page, page.index('id="picBox"'))
77
78 data = {
79 "index" : text.parse_int(path.rsplit("/", 2)[1]),
80 "title" : text.unescape(extr('class="imageTitle">', '<')),
81 "artist" : text.unescape(extr('/profile">', '<')),
82 "_body" : extr(
83 '<div class="boxbody"', '<div class="boxfooter"'),
84 "description": self._process_description(extr(
85 "<div class='picDescript'>", '</section>')
86 .replace("\r\n", "\n")),
87 "ratings" : [text.unescape(r) for r in text.extract_iter(extr(
88 "class='ratings_box'", "</div>"), "title='", "'")],
89 "categories" : self._extract_categories(extr),
90 "date" : self.parse_datetime_iso(extr("datetime='", "'")),
91 "views" : text.parse_int(extr(">Views</span>", "<")),
92 "score" : text.parse_int(extr(">Vote Score</span>", "<")),
93 "media" : text.unescape(extr(">Media</span>", "<").strip()),
94 "tags" : text.split_html(extr(
95 ">Tags </span>", "</div>")),
96 }
97
98 body = data["_body"]
99 if "<object " in body:
100 data["src"] = text.urljoin(self.root, text.unescape(text.extr(
101 body, 'name="movie" value="', '"')))
102 data["width"] = text.parse_int(text.extr(
103 body, "name='width' value='", "'"))
104 data["height"] = text.parse_int(text.extr(
105 body, "name='height' value='", "'"))
106 else:
107 data["src"] = text.urljoin(self.root, text.unescape(text.extr(
108 body, 'src="', '"')))
109 data["width"] = text.parse_int(text.extr(body, 'width="', '"'))
110 data["height"] = text.parse_int(text.extr(body, 'height="', '"'))
111
112 return text.nameext_from_url(data["src"], data)
113
114 def _process_description(self, description):
115 return text.unescape(text.remove_html(description, "", ""))
116
117 def _process_description_html(self, description):
118 pos1 = description.rfind('</div') # picDescript
119 pos2 = description.rfind('</div', None, pos1) # boxBody
120 return str.strip(description[0:pos2])
121
122 def _parse_story(self, html):
123 """Collect url and metadata for a story"""
124 extr = text.extract_from(html)
125 data = {
126 "user" : self.user,
127 "title" : text.unescape(extr(
128 "<div class='titlebar'>", "</a>").rpartition(">")[2]),
129 "author" : text.unescape(extr('alt="', '"')),
130 "date" : self.parse_datetime(extr(
131 ">Updated<", "</span>").rpartition(">")[2], "%B %d, %Y"),
132 "status" : extr("class='indent'>", "<"),
133 }
134
135 for c in ("Chapters", "Words", "Comments", "Views", "Rating"):
136 data[c.lower()] = text.parse_int(extr(
137 f">{c}:</span>", "<").replace(",", ""))
138
139 data["description"] = text.unescape(extr(
140 "class='storyDescript'>", '<div class="storyRead">')).replace(
141 "\r\n", "\n")
142 path = extr('class="pdfLink" href="', '"')
143 data["src"] = self.root + path
144 data["index"] = text.parse_int(path.rsplit("/", 2)[1])
145 data["categories"] = self._extract_categories(extr)
146 data["ratings"] = [text.unescape(r) for r in text.extract_iter(extr(
147 "class='ratings_box'", "</div>"), "title='", "'")]
148
149 return text.nameext_from_url(data["src"], data)
150
151 def _extract_categories(self, extr):
152 return [text.unescape(text.extr(c, ">", "<"))
153 for c in extr('class="categoryBreadcrumbs">', "</span>")
154 .split("&raquo;")]
155
156 def _request_check(self, url, **kwargs):
157 self.request = self._request_original
158
159 # check for Enter button / front page
160 # and update PHPSESSID and content filters if necessary
161 response = self.request(url, **kwargs)
162 content = response.content
163 if len(content) < 5000 and \
164 b'<div id="entryButtonContainer"' in content:
165 self._init_site_filters(False)
166 response = self.request(url, **kwargs)
167 return response
168
169 def _init_site_filters(self, check_cookies=True):
170 """Set site-internal filters to show all images"""
171 if check_cookies and self.cookies.get(
172 "PHPSESSID", domain=self.cookies_domain):
173 self._request_original = self.request
174 self.request = self._request_check
175 return
176
177 url = self.root + "/?enterAgree=1"
178 self.request(url, method="HEAD")
179
180 csrf_token = self.cookies.get(
181 "YII_CSRF_TOKEN", domain=self.cookies_domain)
182 if not csrf_token:
183 self.log.warning("Unable to update site content filters")
184 return
185
186 url = self.root + "/site/filters"
187 data = {
188 "rating_nudity" : "3",
189 "rating_violence" : "3",
190 "rating_profanity": "3",
191 "rating_racism" : "3",
192 "rating_sex" : "3",
193 "rating_spoilers" : "3",
194 "rating_yaoi" : "1",
195 "rating_yuri" : "1",
196 "rating_teen" : "1",
197 "rating_guro" : "1",
198 "rating_furry" : "1",
199 "rating_beast" : "1",
200 "rating_male" : "1",
201 "rating_female" : "1",
202 "rating_futa" : "1",
203 "rating_other" : "1",
204 "rating_scat" : "1",
205 "rating_incest" : "1",
206 "rating_rape" : "1",
207 "filter_order" : "date_new",
208 "filter_type" : "0",
209 "YII_CSRF_TOKEN" : text.unquote(text.extr(
210 csrf_token, "%22", "%22")),
211 }
212 self.request(url, method="POST", data=data)
213
214
215 class HentaifoundryUserExtractor(Dispatch, HentaifoundryExtractor):
216 """Extractor for a hentaifoundry user profile"""
217 pattern = BASE_PATTERN + r"/user/([^/?#]+)/profile"
218 example = "https://www.hentai-foundry.com/user/USER/profile"
219
220 def items(self):
221 root = self.root
222 user = "/user/" + self.user
223 return self._dispatch_extractors((
224 (HentaifoundryPicturesExtractor, f"{root}/pictures{user}"),
225 (HentaifoundryScrapsExtractor , f"{root}/pictures{user}/scraps"),
226 (HentaifoundryStoriesExtractor , f"{root}/stories{user}"),
227 (HentaifoundryFavoriteExtractor, f"{root}{user}/faves/pictures"),
228 ), ("pictures",))
229
230
231 class HentaifoundryPicturesExtractor(HentaifoundryExtractor):
232 """Extractor for all pictures of a hentaifoundry user"""
233 subcategory = "pictures"
234 pattern = BASE_PATTERN + r"/pictures/user/([^/?#]+)(?:/page/(\d+))?/?$"
235 example = "https://www.hentai-foundry.com/pictures/user/USER"
236
237 def __init__(self, match):
238 HentaifoundryExtractor.__init__(self, match)
239 self.page_url = f"{self.root}/pictures/user/{self.user}"
240
241
242 class HentaifoundryScrapsExtractor(HentaifoundryExtractor):
243 """Extractor for scraps of a hentaifoundry user"""
244 subcategory = "scraps"
245 directory_fmt = ("{category}", "{user}", "Scraps")
246 pattern = BASE_PATTERN + r"/pictures/user/([^/?#]+)/scraps"
247 example = "https://www.hentai-foundry.com/pictures/user/USER/scraps"
248
249 def __init__(self, match):
250 HentaifoundryExtractor.__init__(self, match)
251 self.page_url = f"{self.root}/pictures/user/{self.user}/scraps"
252
253
254 class HentaifoundryFavoriteExtractor(HentaifoundryExtractor):
255 """Extractor for favorite images of a hentaifoundry user"""
256 subcategory = "favorite"
257 directory_fmt = ("{category}", "{user}", "Favorites")
258 archive_fmt = "f_{user}_{index}"
259 pattern = BASE_PATTERN + r"/user/([^/?#]+)/faves/pictures"
260 example = "https://www.hentai-foundry.com/user/USER/faves/pictures"
261
262 def __init__(self, match):
263 HentaifoundryExtractor.__init__(self, match)
264 self.page_url = f"{self.root}/user/{self.user}/faves/pictures"
265
266
267 class HentaifoundryTagExtractor(HentaifoundryExtractor):
268 """Extractor for tag searches on hentaifoundry.com"""
269 subcategory = "tag"
270 directory_fmt = ("{category}", "{search_tags}")
271 archive_fmt = "t_{search_tags}_{index}"
272 pattern = BASE_PATTERN + r"/pictures/tagged/([^/?#]+)"
273 example = "https://www.hentai-foundry.com/pictures/tagged/TAG"
274
275 def __init__(self, match):
276 HentaifoundryExtractor.__init__(self, match)
277 self.page_url = f"{self.root}/pictures/tagged/{self.user}"
278
279 def metadata(self):
280 return {"search_tags": self.user}
281
282
283 class HentaifoundryRecentExtractor(HentaifoundryExtractor):
284 """Extractor for 'Recent Pictures' on hentaifoundry.com"""
285 subcategory = "recent"
286 directory_fmt = ("{category}", "Recent Pictures", "{date}")
287 archive_fmt = "r_{index}"
288 pattern = BASE_PATTERN + r"/pictures/recent/(\d\d\d\d-\d\d-\d\d)"
289 example = "https://www.hentai-foundry.com/pictures/recent/1970-01-01"
290
291 def __init__(self, match):
292 HentaifoundryExtractor.__init__(self, match)
293 self.page_url = f"{self.root}/pictures/recent/{self.user}"
294
295 def metadata(self):
296 return {"date": self.user}
297
298
299 class HentaifoundryPopularExtractor(HentaifoundryExtractor):
300 """Extractor for popular images on hentaifoundry.com"""
301 subcategory = "popular"
302 directory_fmt = ("{category}", "Popular Pictures")
303 archive_fmt = "p_{index}"
304 pattern = BASE_PATTERN + r"/pictures/popular()"
305 example = "https://www.hentai-foundry.com/pictures/popular"
306
307 def __init__(self, match):
308 HentaifoundryExtractor.__init__(self, match)
309 self.page_url = self.root + "/pictures/popular"
310
311
312 class HentaifoundryImageExtractor(HentaifoundryExtractor):
313 """Extractor for a single image from hentaifoundry.com"""
314 subcategory = "image"
315 skip_files = None
316 pattern = (r"(https?://)?(?:www\.|pictures\.)?hentai-foundry\.com"
317 r"/(?:pictures/user|[^/?#])/([^/?#]+)/(\d+)")
318 example = "https://www.hentai-foundry.com/pictures/user/USER/12345/TITLE"
319
320 def __init__(self, match):
321 HentaifoundryExtractor.__init__(self, match)
322 self.index = match[3]
323
324 def items(self):
325 post_url = (f"{self.root}/pictures/user/{self.user}"
326 f"/{self.index}/?enterAgree=1")
327 image = self._parse_post(post_url)
328 image["user"] = self.user
329 yield Message.Directory, "", image
330 yield Message.Url, image["src"], image
331
332
333 class HentaifoundryStoriesExtractor(HentaifoundryExtractor):
334 """Extractor for stories of a hentaifoundry user"""
335 subcategory = "stories"
336 archive_fmt = "s_{index}"
337 pattern = BASE_PATTERN + r"/stories/user/([^/?#]+)(?:/page/(\d+))?/?$"
338 example = "https://www.hentai-foundry.com/stories/user/USER"
339
340 def items(self):
341 self._init_site_filters()
342 for story_html in util.advance(self.stories(), self.start_post):
343 story = self._parse_story(story_html)
344 yield Message.Directory, "", story
345 yield Message.Url, story["src"], story
346
347 def stories(self):
348 url = f"{self.root}/stories/user/{self.user}"
349 return self._pagination(url, '<div class="storyRow">', '</tr></table>')
350
351
352 class HentaifoundryStoryExtractor(HentaifoundryExtractor):
353 """Extractor for a hentaifoundry story"""
354 subcategory = "story"
355 archive_fmt = "s_{index}"
356 skip_files = None
357 pattern = BASE_PATTERN + r"/stories/user/([^/?#]+)/(\d+)"
358 example = "https://www.hentai-foundry.com/stories/user/USER/12345/TITLE"
359
360 def __init__(self, match):
361 HentaifoundryExtractor.__init__(self, match)
362 self.index = match[3]
363
364 def items(self):
365 story_url = (f"{self.root}/stories/user/{self.user}"
366 f"/{self.index}/x?enterAgree=1")
367 story = self._parse_story(self.request(story_url).text)
368 yield Message.Directory, "", story
369 yield Message.Url, story["src"], story