Debian Codegraph @

gallery_dl/extractor/pixeldrain.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2023-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://pixeldrain.com/"""
10
11 from .common import Extractor, Message
12 from .. import text, util
13
14 BASE_PATTERN = r"(?:https?://)?pixeldrain\.(?:com|net)"
15
16
17 class PixeldrainExtractor(Extractor):
18 """Base class for pixeldrain extractors"""
19 category = "pixeldrain"
20 root = "https://pixeldrain.com"
21 archive_fmt = "{id}"
22
23 def _init(self):
24 if api_key := self.config("api-key"):
25 self.session.auth = util.HTTPBasicAuth("", api_key)
26
27 def _available(self, file):
28 if not file.get("availability"):
29 return True
30
31 self.status |= 1
32 self.log.debug(file["availability"])
33 self.log.warning(
34 "%s: '%s'", file["name"], file["availability_message"])
35 return False
36
37
38 class PixeldrainFileExtractor(PixeldrainExtractor):
39 """Extractor for pixeldrain files"""
40 subcategory = "file"
41 filename_fmt = "{filename[:230]} ({id}).{extension}"
42 pattern = BASE_PATTERN + r"/(?:u|api/file)/(\w+)"
43 example = "https://pixeldrain.com/u/abcdefgh"
44
45 def __init__(self, match):
46 Extractor.__init__(self, match)
47 self.file_id = match[1]
48
49 def items(self):
50 url = f"{self.root}/api/file/{self.file_id}"
51 file = self.request_json(url + "/info")
52
53 file["url"] = url + "?download"
54 file["date"] = self.parse_datetime_iso(file["date_upload"])
55
56 text.nameext_from_name(file["name"], file)
57 yield Message.Directory, "", file
58 if file.get("availability"):
59 self.status |= 1
60 self.log.debug(file["availability"])
61 self.log.error("'%s'", file["availability_message"])
62 else:
63 yield Message.Url, file["url"], file
64
65
66 class PixeldrainAlbumExtractor(PixeldrainExtractor):
67 """Extractor for pixeldrain albums"""
68 subcategory = "album"
69 directory_fmt = ("{category}",
70 "{album[date]:%Y-%m-%d} {album[title]} ({album[id]})")
71 filename_fmt = "{num:>03} {filename[:230]} ({id}).{extension}"
72 pattern = BASE_PATTERN + r"/(?:l|api/list)/(\w+)(?:#item=(\d+))?"
73 example = "https://pixeldrain.com/l/abcdefgh"
74
75 def __init__(self, match):
76 Extractor.__init__(self, match)
77 self.album_id = match[1]
78 self.file_index = match[2]
79
80 def items(self):
81 url = f"{self.root}/api/list/{self.album_id}"
82 album = self.request_json(url)
83 album["date"] = self.parse_datetime_iso(album["date_created"])
84
85 if self.config("zip", False):
86 self.directory_fmt = ("{category}",)
87 self.filename_fmt = "{filename[:230]} ({id}).{extension}"
88 del album["files"]
89 album["count"] = 1
90 url += "/zip"
91
92 file = {
93 "id" : album["id"],
94 "url" : url,
95 "num" : 0,
96 "count": 1,
97 "name" : album["title"] + ".zip",
98 "date" : album["date"],
99 "album": album,
100 "filename" : album["title"],
101 "extension": "zip",
102 }
103
104 yield Message.Directory, "", file
105 yield Message.Url, url, file
106 return
107
108 files = album.pop("files")
109 album["count"] = album.pop("file_count")
110 if self.file_index:
111 idx = text.parse_int(self.file_index)
112 try:
113 files = (files[idx],)
114 except LookupError:
115 files = ()
116 else:
117 idx = 0
118
119 yield Message.Directory, "", {"album": album}
120 for num, file in enumerate(files, idx+1):
121 if not self._available(file):
122 continue
123 file["album"] = album
124 file["num"] = num
125 file["url"] = url = f"{self.root}/api/file/{file['id']}?download"
126 file["date"] = self.parse_datetime_iso(file["date_upload"])
127 text.nameext_from_name(file["name"], file)
128 yield Message.Url, url, file
129
130
131 class PixeldrainFolderExtractor(PixeldrainExtractor):
132 """Extractor for pixeldrain filesystem files and directories"""
133 subcategory = "folder"
134 filename_fmt = "{filename[:230]}.{extension}"
135 archive_fmt = "{path}_{num}"
136 pattern = BASE_PATTERN + r"/(?:d|api/filesystem)/([^?]+)"
137 example = "https://pixeldrain.com/d/abcdefgh"
138
139 def metadata(self, data):
140 return {
141 "type" : data["type"],
142 "path" : data["path"],
143 "name" : data["name"],
144 "mime_type" : data["file_type"],
145 "size" : data["file_size"],
146 "hash_sha256": data["sha256_sum"],
147 "date" : self.parse_datetime_iso(data["created"]),
148 }
149
150 def items(self):
151 recursive = self.config("recursive", True)
152
153 url = f"{self.root}/api/filesystem/{self.groups[0]}"
154 stat = self.request_json(url + "?stat")
155
156 paths = stat["path"]
157 path = paths[stat["base_index"]]
158 if path["type"] == "dir":
159 children = [
160 child
161 for child in stat["children"]
162 if child["name"] != ".search_index.gz"
163 ]
164 else:
165 children = (path,)
166
167 folder = self.metadata(path)
168 folder["id"] = paths[0]["id"]
169
170 yield Message.Directory, "", folder
171
172 num = 0
173 for child in children:
174 if child["type"] == "file":
175 num += 1
176 if not self._available(child):
177 continue
178 url = f"{self.root}/api/filesystem{child['path']}?attach"
179 share_url = f"{self.root}/d{child['path']}"
180 data = self.metadata(child)
181 data.update({
182 "id" : folder["id"],
183 "num" : num,
184 "url" : url,
185 "share_url": share_url,
186 })
187 data["filename"], _, data["extension"] = \
188 child["name"].rpartition(".")
189 yield Message.Url, url, data
190
191 elif child["type"] == "dir":
192 if recursive:
193 url = f"{self.root}/d{child['path']}"
194 child["_extractor"] = PixeldrainFolderExtractor
195 yield Message.Queue, url, child
196
197 else:
198 self.log.debug("'%s' is of unknown type (%s)",
199 child.get("name"), child["type"])