Debian Codegraph @

gallery_dl/extractor/imgbb.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2019-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://imgbb.com/"""
10
11 from .common import Extractor, Message
12 from .. import text, util
13
14
15 class ImgbbExtractor(Extractor):
16 """Base class for imgbb extractors"""
17 category = "imgbb"
18 directory_fmt = ("{category}", "{user[name]:?//}{user[id]:? (/)/}",
19 "{album[title]} ({album[id]})")
20 filename_fmt = "{title} ({id}).{extension}"
21 archive_fmt = "{user[id]} {id}"
22 cookies_domain = ".imgbb.com"
23 cookies_names = ("PHPSESSID", "LID")
24 root = "https://ibb.co"
25
26 def items(self):
27 self.login()
28
29 for image in self.posts():
30 url = image["url"]
31 text.nameext_from_url(url, image)
32 yield Message.Directory, "", image
33 yield Message.Url, url, image
34
35 def login(self):
36 if self.cookies_check(self.cookies_names):
37 return
38
39 username, password = self._get_auth_info()
40 if username:
41 return self.cookies_update(self.cache(
42 self._login_impl, username, password,
43 _exp=365*86400, _mem=False))
44
45 def _login_impl(self, username, password):
46 self.log.info("Logging in as %s", username)
47
48 url = "https://imgbb.com/login"
49 page = self.request(url).text
50 token = text.extr(page, 'name="auth_token" value="', '"')
51
52 headers = {
53 "Referer": url,
54 }
55 data = {
56 "auth_token" : token,
57 "login-subject": username,
58 "password" : password,
59 }
60 response = self.request(url, method="POST", headers=headers, data=data)
61
62 if not response.history:
63 raise self.exc.AuthenticationError()
64 return self.cookies
65
66 def _pagination(self, page, url, params):
67 seek, pos = text.extract(page, 'data-seek="', '"')
68 tokn, pos = text.extract(page, 'PF.obj.config.auth_token="', '"', pos)
69 resc, pos = text.extract(page, "CHV.obj.resource=", "};", pos)
70 self.kwdict["user"] = util.json_loads(resc + "}").get("user")
71
72 data = None
73 while True:
74 for obj in text.extract_iter(page, "data-object='", "'"):
75 post = util.json_loads(text.unquote(obj))
76 image = post["image"]
77 image["filename"], image["name"] = \
78 image["name"], image["filename"]
79 image["id"] = post["id_encoded"]
80 image["title"] = post["title"]
81 image["width"] = text.parse_int(post["width"])
82 image["height"] = text.parse_int(post["height"])
83 image["size"] = text.parse_int(image["size"])
84 yield image
85
86 if data:
87 if not data["seekEnd"] or params["seek"] == data["seekEnd"]:
88 return
89 params["seek"] = data["seekEnd"]
90 params["page"] += 1
91 elif not seek or 'class="pagination-next"' not in page:
92 return
93 else:
94 params["action"] = "list"
95 params["page"] = 2
96 params["seek"] = seek
97 params["auth_token"] = tokn
98
99 headers = {
100 "Accept": "application/json, text/javascript, */*; q=0.01",
101 "X-Requested-With": "XMLHttpRequest",
102 }
103
104 data = self.request_json(
105 url, method="POST", headers=headers, data=params)
106 page = data["html"]
107
108
109 class ImgbbAlbumExtractor(ImgbbExtractor):
110 """Extractor for imgbb albums"""
111 subcategory = "album"
112 pattern = r"(?:https?://)?ibb\.co/album/([^/?#]+)/?(?:\?([^#]+))?"
113 example = "https://ibb.co/album/ID"
114
115 def posts(self):
116 album_id, qs = self.groups
117 url = f"{self.root}/album/{album_id}"
118 params = text.parse_query(qs)
119 page = self.request(url, params=params).text
120 extr = text.extract_from(page)
121
122 self.kwdict["album"] = album = {
123 "url": extr(
124 'property="og:url" content="', '"'),
125 "title": text.unescape(extr(
126 'property="og:title" content="', '"')),
127 "description": text.unescape(extr(
128 'property="og:description" content="', '"')),
129 "id": extr(
130 'data-text="album-name" href="https://ibb.co/album/', '"'),
131 "count": text.parse_int(extr(
132 'data-text="image-count">', "<")),
133 }
134
135 url = self.root + "/json"
136 params["pathname"] = "/album/" + album["id"]
137 return self._pagination(page, url, params)
138
139
140 class ImgbbImageExtractor(ImgbbExtractor):
141 subcategory = "image"
142 pattern = r"(?:https?://)?ibb\.co/([^/?#]+)"
143 example = "https://ibb.co/ID"
144
145 def posts(self):
146 url = f"{self.root}/{self.groups[0]}"
147 page = self.request(url).text
148 extr = text.extract_from(page)
149
150 image = {
151 "id" : extr('property="og:url" content="https://ibb.co/', '"'),
152 "title" : text.unescape(extr(
153 '"og:title" content="', ' hosted at ImgBB"')),
154 "url" : extr('"og:image" content="', '"'),
155 "width" : text.parse_int(extr('"og:image:width" content="', '"')),
156 "height": text.parse_int(extr('"og:image:height" content="', '"')),
157 "album" : extr("Added to <a", "</a>"),
158 "date" : self.parse_datetime_iso(extr('<span title="', '"')),
159 "user" : util.json_loads(extr(
160 "CHV.obj.resource=", "};") + "}").get("user"),
161 }
162
163 if album := image["album"]:
164 image["album"] = {
165 "id" : text.extr(album, "/album/", '"'),
166 "title": text.unescape(album.rpartition(">")[2]),
167 }
168 else:
169 image["album"] = None
170
171 return (image,)
172
173
174 class ImgbbUserExtractor(ImgbbExtractor):
175 """Extractor for imgbb user profiles"""
176 subcategory = "user"
177 directory_fmt = ("{category}", "{user[name]} ({user[id]})")
178 pattern = r"(?:https?://)?([\w-]+)\.imgbb\.com/?(?:\?([^#]+))?"
179 example = "https://USER.imgbb.com"
180
181 def posts(self):
182 user, qs = self.groups
183 url = f"https://{user}.imgbb.com/"
184 params = text.parse_query(qs)
185 response = self.request(url, params=params, allow_redirects=False)
186
187 if response.status_code < 300:
188 params["pathname"] = "/"
189 return self._pagination(response.text, url + "json", params)
190
191 if response.status_code == 301:
192 raise self.exc.NotFoundError("user")
193 redirect = "HTTP redirect to " + response.headers.get("Location", "")
194 if response.status_code == 302:
195 raise self.exc.AuthRequired(
196 ("username & password", "authenticated cookies"),
197 "profile", redirect)
198 raise self.exc.AbortExtraction(redirect)