Debian Codegraph @

gallery_dl/extractor/e621.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2014-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://e621.net/ and other e621 instances"""
10
11 from .common import Extractor, Message
12 from . import danbooru
13 from .. import text, util
14
15
16 class E621Extractor(danbooru.DanbooruExtractor):
17 """Base class for e621 extractors"""
18 basecategory = "E621"
19 page_limit = 750
20 page_start = None
21 per_page = 320
22 useragent = util.USERAGENT_GALLERYDL + " (by mikf)"
23 request_interval_min = 1.0
24
25 def items(self):
26 if includes := self.config("metadata") or ():
27 if isinstance(includes, str):
28 includes = includes.split(",")
29 elif not isinstance(includes, (list, tuple)):
30 includes = ("notes", "pools")
31
32 notes = ("notes" in includes)
33 pools = ("pools" in includes)
34
35 data = self.metadata()
36 for post in self.posts():
37 file = post["file"]
38
39 if not file["url"]:
40 md5 = file["md5"]
41 file["url"] = (f"https://static1.{self.root[8:]}/data"
42 f"/{md5[0:2]}/{md5[2:4]}/{md5}.{file['ext']}")
43
44 if notes and post.get("has_notes"):
45 post["notes"] = self._get_notes(post["id"])
46
47 if pools and post["pools"]:
48 post["pools"] = self.cache(
49 self._get_pools, ",".join(map(str, post["pools"])))
50
51 post["filename"] = file["md5"]
52 post["extension"] = file["ext"]
53 post["date"] = self.parse_datetime_iso(post["created_at"])
54
55 tags = []
56 for category, tags_cat in post["tags"].items():
57 post["tags_" + category] = tags_cat
58 tags.extend(tags_cat)
59 tags.sort()
60 post["tags"] = tags
61
62 post.update(data)
63 yield Message.Directory, "", post
64 yield Message.Url, file["url"], post
65
66 def items_artists(self):
67 for artist in self.artists():
68 artist["_extractor"] = E621TagExtractor
69 url = f"{self.root}/posts?tags={text.quote(artist['name'])}"
70 yield Message.Queue, url, artist
71
72 def import_blacklist(self):
73 url = f"{self.root}/users/{self._get_auth_info()[0]}.json"
74 return self.request_json(url)["blacklisted_tags"].splitlines()
75
76 def _get_notes(self, id):
77 return self.request_json(
78 f"{self.root}/notes.json?search[post_id]={id}")
79
80 def _get_pools(self, ids):
81 pools = self.request_json(
82 f"{self.root}/pools.json?search[id]={ids}")
83 for pool in pools:
84 pool["name"] = pool["name"].replace("_", " ")
85 return pools
86
87
88 BASE_PATTERN = E621Extractor.update({
89 "e621": {
90 "root": "https://e621.net",
91 "pattern": r"e621\.(?:net|cc)",
92 },
93 "e926": {
94 "root": "https://e926.net",
95 "pattern": r"e926\.net",
96 },
97 "e6ai": {
98 "root": "https://e6ai.net",
99 "pattern": r"e6ai\.net",
100 },
101 })
102
103
104 class E621TagExtractor(E621Extractor, danbooru.DanbooruTagExtractor):
105 """Extractor for e621 posts from tag searches"""
106 pattern = BASE_PATTERN + r"/posts?(?:\?[^#]*?tags=|/index/\d+/)([^&#]*)"
107 example = "https://e621.net/posts?tags=TAG"
108
109
110 class E621PoolExtractor(E621Extractor, danbooru.DanbooruPoolExtractor):
111 """Extractor for e621 pools"""
112 pattern = BASE_PATTERN + r"/pool(?:s|/show)/(\d+)"
113 example = "https://e621.net/pools/12345"
114
115 def posts(self):
116 self.log.info("Collecting posts of pool %s", self.pool_id)
117
118 id_to_post = {
119 post["id"]: post
120 for post in self._pagination(
121 "/posts.json", {"tags": "pool:" + self.pool_id})
122 }
123
124 posts = []
125 for num, pid in enumerate(self.post_ids, 1):
126 if pid in id_to_post:
127 post = id_to_post[pid]
128 post["num"] = num
129 posts.append(post)
130 else:
131 self.log.warning("Post %s is unavailable", pid)
132 return posts
133
134
135 class E621PostExtractor(E621Extractor, danbooru.DanbooruPostExtractor):
136 """Extractor for single e621 posts"""
137 pattern = BASE_PATTERN + r"/p(?:ost(?:s|/show)/(\d+)|/(\w+))"
138 example = "https://e621.net/posts/12345"
139
140 def posts(self):
141 pid = self.groups[-2] or int(self.groups[-1], 32)
142 url = f"{self.root}/posts/{pid}.json"
143 return (self.request_json(url)["post"],)
144
145
146 class E621PopularExtractor(E621Extractor, danbooru.DanbooruPopularExtractor):
147 """Extractor for popular images from e621"""
148 pattern = BASE_PATTERN + r"/explore/posts/popular(?:\?([^#]*))?"
149 example = "https://e621.net/explore/posts/popular"
150
151 def posts(self):
152 return self._pagination("/popular.json", self.params)
153
154
155 class E621ArtistExtractor(E621Extractor, danbooru.DanbooruArtistExtractor):
156 """Extractor for e621 artists"""
157 subcategory = "artist"
158 pattern = BASE_PATTERN + r"/artists/(\d+)"
159 example = "https://e621.net/artists/12345"
160
161 items = E621Extractor.items_artists
162
163
164 class E621ArtistSearchExtractor(E621Extractor,
165 danbooru.DanbooruArtistSearchExtractor):
166 """Extractor for e621 artist searches"""
167 subcategory = "artist-search"
168 pattern = BASE_PATTERN + r"/artists/?\?([^#]+)"
169 example = "https://e621.net/artists?QUERY"
170
171 items = E621Extractor.items_artists
172
173
174 class E621FavoriteExtractor(E621Extractor):
175 """Extractor for e621 favorites"""
176 subcategory = "favorite"
177 directory_fmt = ("{category}", "Favorites", "{user_id}")
178 archive_fmt = "f_{user_id}_{id}"
179 pattern = BASE_PATTERN + r"/favorites(?:\?([^#]*))?"
180 example = "https://e621.net/favorites"
181
182 def metadata(self):
183 self.query = text.parse_query(self.groups[-1])
184 return {"user_id": self.query.get("user_id", "")}
185
186 def posts(self):
187 return self._pagination("/favorites.json", self.query)
188
189
190 class E621FrontendExtractor(Extractor):
191 """Extractor for alternative e621 frontends"""
192 basecategory = "E621"
193 category = "e621"
194 subcategory = "frontend"
195 pattern = r"(?:https?://)?e621\.(?:cc/\?tags|anthro\.fr/\?q)=([^&#]*)"
196 example = "https://e621.cc/?tags=TAG"
197
198 def initialize(self):
199 pass
200
201 def items(self):
202 url = "https://e621.net/posts?tags=" + self.groups[0]
203 data = {"_extractor": E621TagExtractor}
204 yield Message.Queue, url, data