Debian Codegraph @

gallery_dl/extractor/wallhaven.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://wallhaven.cc/"""
10
11 from .common import Extractor, Message, Dispatch
12 from .. import text
13
14
15 class WallhavenExtractor(Extractor):
16 """Base class for wallhaven extractors"""
17 category = "wallhaven"
18 root = "https://wallhaven.cc"
19 filename_fmt = "{category}_{id}_{resolution}.{extension}"
20 archive_fmt = "{id}"
21 request_interval = 1.4
22
23 def _init(self):
24 self.api = WallhavenAPI(self)
25
26 def items(self):
27 metadata = self.metadata()
28 for wp in self.wallpapers():
29 self._transform(wp)
30 wp.update(metadata)
31 url = wp["url"]
32 yield Message.Directory, "", wp
33 yield Message.Url, url, text.nameext_from_url(url, wp)
34
35 def wallpapers(self):
36 """Return relevant 'wallpaper' objects"""
37
38 def metadata(self):
39 """Return general metadata"""
40 return ()
41
42 def _transform(self, wp):
43 wp["url"] = wp.pop("path")
44 if "tags" in wp:
45 wp["tags"] = [t["name"] for t in wp["tags"]]
46 wp["date"] = self.parse_datetime_iso(wp.pop("created_at"))
47 wp["width"] = wp.pop("dimension_x")
48 wp["height"] = wp.pop("dimension_y")
49 wp["wh_category"] = wp["category"]
50
51
52 class WallhavenSearchExtractor(WallhavenExtractor):
53 """Extractor for search results on wallhaven.cc"""
54 subcategory = "search"
55 directory_fmt = ("{category}", "{search[tags]}")
56 archive_fmt = "s_{search[q]}_{id}"
57 pattern = r"(?:https?://)?wallhaven\.cc/search(?:/?\?([^#]+))?"
58 example = "https://wallhaven.cc/search?q=QUERY"
59
60 def __init__(self, match):
61 WallhavenExtractor.__init__(self, match)
62 self.params = text.parse_query(match[1])
63
64 def wallpapers(self):
65 return self.api.search(self.params)
66
67 def metadata(self):
68 return {"search": self.params}
69
70
71 class WallhavenCollectionExtractor(WallhavenExtractor):
72 """Extractor for a collection on wallhaven.cc"""
73 subcategory = "collection"
74 directory_fmt = ("{category}", "{username}", "{collection_id}")
75 pattern = r"(?:https?://)?wallhaven\.cc/user/([^/?#]+)/favorites/(\d+)"
76 example = "https://wallhaven.cc/user/USER/favorites/12345"
77
78 def __init__(self, match):
79 WallhavenExtractor.__init__(self, match)
80 self.username, self.collection_id = match.groups()
81
82 def wallpapers(self):
83 return self.api.collection(self.username, self.collection_id)
84
85 def metadata(self):
86 return {"username": self.username, "collection_id": self.collection_id}
87
88
89 class WallhavenUserExtractor(Dispatch, WallhavenExtractor):
90 """Extractor for a wallhaven user"""
91 pattern = r"(?:https?://)?wallhaven\.cc/user/([^/?#]+)/?$"
92 example = "https://wallhaven.cc/user/USER"
93
94 def items(self):
95 base = f"{self.root}/user/{self.groups[0]}/"
96 return self._dispatch_extractors((
97 (WallhavenUploadsExtractor , base + "uploads"),
98 (WallhavenCollectionsExtractor, base + "favorites"),
99 ), ("uploads",))
100
101
102 class WallhavenCollectionsExtractor(WallhavenExtractor):
103 """Extractor for all collections of a wallhaven user"""
104 subcategory = "collections"
105 pattern = r"(?:https?://)?wallhaven\.cc/user/([^/?#]+)/favorites/?$"
106 example = "https://wallhaven.cc/user/USER/favorites"
107
108 def __init__(self, match):
109 WallhavenExtractor.__init__(self, match)
110 self.username = match[1]
111
112 def items(self):
113 base = f"{self.root}/user/{self.username}/favorites/"
114 for collection in self.api.collections(self.username):
115 collection["_extractor"] = WallhavenCollectionExtractor
116 url = base + str(collection["id"])
117 yield Message.Queue, url, collection
118
119
120 class WallhavenUploadsExtractor(WallhavenExtractor):
121 """Extractor for all uploads of a wallhaven user"""
122 subcategory = "uploads"
123 directory_fmt = ("{category}", "{username}")
124 archive_fmt = "u_{username}_{id}"
125 pattern = r"(?:https?://)?wallhaven\.cc/user/([^/?#]+)/uploads"
126 example = "https://wallhaven.cc/user/USER/uploads"
127
128 def __init__(self, match):
129 WallhavenExtractor.__init__(self, match)
130 self.username = match[1]
131
132 def wallpapers(self):
133 params = {"q": "@" + self.username}
134 return self.api.search(params)
135
136 def metadata(self):
137 return {"username": self.username}
138
139
140 class WallhavenImageExtractor(WallhavenExtractor):
141 """Extractor for individual wallpaper on wallhaven.cc"""
142 subcategory = "image"
143 pattern = (r"(?:https?://)?(?:wallhaven\.cc/w/|whvn\.cc/"
144 r"|w\.wallhaven\.cc/[a-z]+/\w\w/wallhaven-)(\w+)")
145 example = "https://wallhaven.cc/w/ID"
146
147 def __init__(self, match):
148 WallhavenExtractor.__init__(self, match)
149 self.wallpaper_id = match[1]
150
151 def wallpapers(self):
152 return (self.api.info(self.wallpaper_id),)
153
154
155 class WallhavenAPI():
156 """Interface for wallhaven's API
157
158 Ref: https://wallhaven.cc/help/api
159 """
160
161 def __init__(self, extractor):
162 self.extractor = extractor
163
164 key = extractor.config("api-key")
165 if key is None:
166 key = "25HYZenXTICjzBZXzFSg98uJtcQVrDs2"
167 extractor.log.debug("Using default API Key")
168 else:
169 extractor.log.debug("Using custom API Key")
170 self.headers = {"X-API-Key": key}
171
172 def info(self, wallpaper_id):
173 endpoint = "/v1/w/" + wallpaper_id
174 return self._call(endpoint)["data"]
175
176 def collection(self, username, collection_id):
177 endpoint = f"/v1/collections/{username}/{collection_id}"
178 return self._pagination(endpoint)
179
180 def collections(self, username):
181 endpoint = "/v1/collections/" + username
182 return self._pagination(endpoint, metadata=False)
183
184 def search(self, params):
185 endpoint = "/v1/search"
186 return self._pagination(endpoint, params)
187
188 def _call(self, endpoint, params=None):
189 url = "https://wallhaven.cc/api" + endpoint
190
191 while True:
192 response = self.extractor.request(
193 url, params=params, headers=self.headers, fatal=None)
194
195 if response.status_code < 400:
196 return response.json()
197 if response.status_code == 429:
198 self.extractor.wait(seconds=60)
199 continue
200
201 self.extractor.log.debug("Server response: %s", response.text)
202 raise self.extractor.exc.AbortExtraction(
203 f"API request failed "
204 f"({response.status_code} {response.reason})")
205
206 def _pagination(self, endpoint, params=None, metadata=None):
207 if params is None:
208 params_ptr = None
209 params = {}
210 else:
211 params_ptr = params
212 params = params.copy()
213 if metadata is None:
214 metadata = self.extractor.config("metadata")
215
216 while True:
217 data = self._call(endpoint, params)
218
219 meta = data.get("meta")
220 if params_ptr is not None:
221 if meta and "query" in meta:
222 query = meta["query"]
223 if isinstance(query, dict):
224 params_ptr["tags"] = query.get("tag")
225 params_ptr["tag_id"] = query.get("id")
226 else:
227 params_ptr["tags"] = query
228 params_ptr["tag_id"] = 0
229 params_ptr = None
230
231 if metadata:
232 for wp in data["data"]:
233 yield self.info(str(wp["id"]))
234 else:
235 yield from data["data"]
236
237 if not meta or meta["current_page"] >= meta["last_page"]:
238 return
239 params["page"] = meta["current_page"] + 1