Debian Codegraph @

gallery_dl/extractor/thehentaiworld.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Copyright 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://thehentaiworld.com/"""
10
11 from .common import Extractor, Message
12 from .. import text, util
13 import collections
14
15 BASE_PATTERN = r"(?:https?://)?(?:www\.)?thehentaiworld\.com"
16
17
18 class ThehentaiworldExtractor(Extractor):
19 """Base class for thehentaiworld extractors"""
20 category = "thehentaiworld"
21 root = "https://thehentaiworld.com"
22 filename_fmt = "{title} ({id}{num:?-//}).{extension}"
23 archive_fmt = "{id}_{num}"
24 request_interval = (0.5, 1.5)
25
26 def items(self):
27 for url in self.posts():
28 try:
29 post = self._extract_post(url)
30 except Exception as exc:
31 self.status |= 1
32 self.log.warning("Failed to extract post %s (%s: %s)",
33 url, exc.__class__.__name__, exc)
34 continue
35
36 if "file_urls" in post:
37 urls = post["file_urls"]
38 post["count"] = len(urls)
39 yield Message.Directory, "", post
40 for post["num"], url in enumerate(urls, 1):
41 text.nameext_from_url(url, post)
42 yield Message.Url, url, post
43 else:
44 yield Message.Directory, "", post
45 url = post["file_url"]
46 text.nameext_from_url(url, post)
47 yield Message.Url, url, post
48
49 def _extract_post(self, url):
50 extr = text.extract_from(self.request(url).text)
51
52 post = {
53 "num" : 0,
54 "count" : 1,
55 "title" : text.unescape(extr("<title>", "<").strip()),
56 "id" : text.parse_int(extr(" postid-", " ")),
57 "slug" : extr(" post-", '"'),
58 "tags" : extr('id="tagsHead">', "</ul>"),
59 "date" : self.parse_datetime_iso(extr("<li>Posted: ", "<")),
60 }
61
62 if (c := url[27]) == "v":
63 post["type"] = "video"
64 post["width"] = post["height"] = 0
65 post["votes"] = text.parse_int(extr("(<strong>", "</strong>"))
66 post["score"] = text.parse_float(extr("<strong>", "<"))
67 post["file_url"] = extr('<source src="', '"')
68 else:
69 post["type"] = ("animated" if c == "g" else
70 "3d cgi" if c == "3" else
71 "image")
72 post["width"] = text.parse_int(extr("<li>Size: ", " "))
73 post["height"] = text.parse_int(extr("x ", "<"))
74 post["file_url"] = extr('a href="', '"')
75 post["votes"] = text.parse_int(extr("(<strong>", "</strong>"))
76 post["score"] = text.parse_float(extr("<strong>", "<"))
77
78 if doujin := extr('<a id="prev-page"', "</div></div><"):
79 repl = text.re(r"-220x\d+\.").sub
80 post["file_urls"] = [
81 repl(".", url)
82 for url in text.extract_iter(
83 doujin, 'class="border" src="', '"')
84 ]
85
86 tags = collections.defaultdict(list)
87 pattern = text.re(r'<li><a class="([^"]*)" href="[^"]*">([^<]+)')
88 for tag_type, tag_name in pattern.findall(post["tags"]):
89 tags[tag_type].append(tag_name)
90 post["tags"] = tags_list = []
91 for key, value in tags.items():
92 tags_list.extend(value)
93 post["tags_" + key if key else "tags_general"] = value
94
95 return post
96
97 def _pagination(self, endpoint):
98 base = self.root + endpoint
99 pnum = self.page_start
100
101 while True:
102 url = base if pnum < 2 else f"{base}page/{pnum}/"
103 page = self.request(url).text
104
105 yield from text.extract_iter(text.extr(
106 page, 'id="thumbContainer"', "<script"), ' href="', '"')
107
108 if 'class="next"' not in page:
109 return
110 pnum += 1
111
112
113 class ThehentaiworldTagExtractor(ThehentaiworldExtractor):
114 subcategory = "tag"
115 per_page = 24
116 page_start = 1
117 post_start = 0
118 directory_fmt = ("{category}", "{search_tags}")
119 pattern = BASE_PATTERN + r"/tag/([^/?#]+)"
120 example = "https://thehentaiworld.com/tag/TAG/"
121
122 def posts(self):
123 self.kwdict["search_tags"] = tag = self.groups[0]
124 return util.advance(self._pagination(f"/tag/{tag}/"), self.post_start)
125
126 def skip_files(self, num):
127 pages, posts = divmod(num, self.per_page)
128 self.page_start += pages
129 self.post_start += posts
130 return num
131
132
133 class ThehentaiworldPostExtractor(ThehentaiworldExtractor):
134 subcategory = "post"
135 pattern = (BASE_PATTERN +
136 r"(/(?:video|(?:[\w-]+-)?hentai-image)s/([^/?#]+))")
137 example = "https://thehentaiworld.com/hentai-images/SLUG/"
138
139 def posts(self):
140 return (f"{self.root}{self.groups[0]}/",)