Debian Codegraph @

gallery_dl/extractor/paheal.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2018-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://rule34.paheal.net/"""
10
11 from .common import Extractor, Message
12 from .. import text
13
14
15 class PahealExtractor(Extractor):
16 """Base class for paheal extractors"""
17 basecategory = "shimmie2"
18 category = "paheal"
19 filename_fmt = "{category}_{id}_{md5}.{extension}"
20 archive_fmt = "{id}"
21 root = "https://rule34.paheal.net"
22
23 def items(self):
24 self.cookies.set(
25 "ui-tnc-agreed", "true", domain="rule34.paheal.net")
26 data = self.get_metadata()
27
28 for post in self.get_posts():
29 post["id"] = text.parse_int(post["id"])
30 post["tags"] = text.unquote(post["tags"])
31 post["width"] = text.parse_int(post["width"])
32 post["height"] = text.parse_int(post["height"])
33 post.update(data)
34 yield Message.Directory, "", post
35 yield Message.Url, post["file_url"], post
36
37 def get_metadata(self):
38 """Return general metadata"""
39 return {}
40
41 def get_posts(self):
42 """Return an iterable containing data of all relevant posts"""
43
44 def _extract_post(self, post_id):
45 url = f"{self.root}/post/view/{post_id}"
46 extr = text.extract_from(self.request(url).text)
47
48 post = {
49 "id" : post_id,
50 "tags" : extr(": ", "<"),
51 "file_url": (extr("id='main_image' src='", "'") or
52 extr("<source src='", "'")),
53 "uploader": text.unquote(extr(
54 "class='username' href='/user/", "'")),
55 "date" : self.parse_datetime_iso(extr("datetime='", "'")),
56 "source" : text.unescape(text.extr(
57 extr(">Source Link<", "</td>"), "href='", "'")),
58 }
59
60 dimensions, size, ext = extr("Info</th><td>", "<").split(" // ")
61 post["md5"] = post["file_url"].rpartition("/")[2]
62 post["size"] = text.parse_bytes(size[:-1])
63 post["width"], _, height = dimensions.partition("x")
64 post["height"], _, duration = height.partition(", ")
65 post["duration"] = text.parse_float(duration[:-1])
66 post["filename"] = f"{post_id} - {post['tags']}"
67 post["extension"] = ext
68
69 return post
70
71
72 class PahealTagExtractor(PahealExtractor):
73 """Extractor for images from rule34.paheal.net by search-tags"""
74 subcategory = "tag"
75 directory_fmt = ("{category}", "{search_tags}")
76 pattern = (r"(?:https?://)?(?:rule34|rule63|cosplay)\.paheal\.net"
77 r"/post/list/([^/?#]+)")
78 example = "https://rule34.paheal.net/post/list/TAG/1"
79 page_start = 1
80 per_page = 70
81
82 def _init(self):
83 if self.config("metadata"):
84 self._extract_data = self._extract_data_ex
85
86 def skip_files(self, num):
87 pages = num // self.per_page
88 self.page_start += pages
89 return pages * self.per_page
90
91 def get_metadata(self):
92 return {"search_tags": text.unquote(self.groups[0])}
93
94 def get_posts(self):
95 pnum = self.page_start
96 base = f"{self.root}/post/list/{self.groups[0]}/"
97
98 while True:
99 try:
100 response = self.request(
101 base + str(pnum), allow_redirects=False)
102 if response.status_code >= 300:
103 pid = response.headers["location"].rpartition("/")[2]
104 yield self._extract_post(pid)
105 return
106 page = response.text
107 except self.exc.HttpError as exc:
108 if exc.status == 404:
109 return
110 raise
111
112 pos = page.find("id='image-list'")
113 for post in text.extract_iter(
114 page, "<img id='thumb_", "Only</a>", pos):
115 yield self._extract_data(post)
116
117 if ">Next<" not in page:
118 break
119 pnum += 1
120
121 def _extract_data(self, post):
122 pid , pos = text.extract(post, "", "'")
123 data, pos = text.extract(post, "title='", "'", pos)
124 url , pos = text.extract(post, "<a href='", "'", pos)
125
126 tags, data, date = data.split("\n")
127 dimensions, size, ext = data.split(" // ")
128 width, _, height = dimensions.partition("x")
129 height, _, duration = height.partition(", ")
130
131 return {
132 "id" : pid,
133 "md5" : url[url.rfind("/")+1:],
134 "file_url" : url,
135 "width" : width,
136 "height" : height,
137 "duration" : text.parse_float(duration[:-1]),
138 "tags" : text.unescape(tags),
139 "size" : text.parse_bytes(size[:-1]),
140 "date" : self.parse_datetime(date, "%B %d, %Y; %H:%M"),
141 "filename" : f"{pid} - {tags}",
142 "extension": ext,
143 }
144
145 def _extract_data_ex(self, post):
146 pid = post[:post.index("'")]
147 return self._extract_post(pid)
148
149
150 class PahealPostExtractor(PahealExtractor):
151 """Extractor for single images from rule34.paheal.net"""
152 subcategory = "post"
153 pattern = (r"(?:https?://)?(?:rule34|rule63|cosplay)\.paheal\.net"
154 r"/post/view/(\d+)")
155 example = "https://rule34.paheal.net/post/view/12345"
156
157 def get_posts(self):
158 try:
159 return (self._extract_post(self.groups[0]),)
160 except self.exc.HttpError as exc:
161 if exc.status == 404:
162 return ()
163 raise