Debian Codegraph @

gallery_dl/extractor/oauth.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2017-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 """Utility classes to setup OAuth and link accounts to gallery-dl"""
10
11 from .common import Extractor
12 from .. import text, oauth, util, config
13 from ..output import stdout_write
14
15 REDIRECT_URI_LOCALHOST = "http://localhost:6414/"
16 REDIRECT_URI_HTTPS = "https://mikf.github.io/gallery-dl/oauth-redirect.html"
17 NOOP = ((-1, "", None),)
18
19
20 class OAuthBase(Extractor):
21 """Base class for OAuth Helpers"""
22 category = "oauth"
23 redirect_uri = REDIRECT_URI_LOCALHOST
24
25 def __init__(self, match):
26 Extractor.__init__(self, match)
27 self.client = None
28
29 def _init(self):
30 from .. import cache
31 self._cache = config.get(("extractor", self.category), "cache", True)
32 if self._cache and cache.database() is None:
33 self.log.warning("cache file is not writeable")
34 self._cache = False
35
36 def oauth_config(self, key, default=None):
37 value = config.interpolate(("extractor", self.subcategory), key)
38 return value if value is not None else default
39
40 def recv(self):
41 """Open local HTTP server and recv callback parameters"""
42 import socket
43 stdout_write("Waiting for response. (Cancel with Ctrl+c)\n")
44 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
45 server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
46 server.bind((self.config("host", "localhost"),
47 self.config("port", 6414)))
48 server.listen(1)
49
50 # workaround for ctrl+c not working during server.accept on Windows
51 if util.WINDOWS:
52 server.settimeout(1.0)
53 while True:
54 try:
55 self.client = server.accept()[0]
56 break
57 except socket.timeout:
58 pass
59 server.close()
60
61 data = None
62 try:
63 data = self.client.recv(1024).decode()
64 path = data.split(" ", 2)[1]
65 return text.parse_query(path.partition("?")[2])
66 except Exception as exc:
67 if data is None:
68 msg = "Failed to receive"
69 elif not data:
70 exc = ""
71 msg = "Received empty"
72 else:
73 self.log.warning("Response: %r", data)
74 msg = "Received invalid"
75 if exc:
76 exc = f" ({exc.__class__.__name__}: {exc})"
77 raise self.exc.AbortExtraction(f"{msg} OAuth response{exc}")
78
79 def send(self, msg):
80 """Send 'msg' to the socket opened in 'recv()'"""
81 stdout_write(msg)
82 self.client.send(b"HTTP/1.1 200 OK\r\n\r\n" + msg.encode())
83 self.client.close()
84
85 def open(self, url, params, recv=None):
86 """Open 'url' in browser amd return response parameters"""
87 url = f"{url}?{text.build_query(params)}"
88
89 if browser := self.config("browser", True):
90 try:
91 import webbrowser
92 browser = webbrowser.get()
93 except Exception:
94 browser = None
95
96 if browser and browser.open(url):
97 if name := getattr(browser, "name", None):
98 self.log.info("Opening URL with %s:", name.capitalize())
99 else:
100 self.log.info("Please open this URL in your browser:")
101
102 stdout_write(f"\n{url}\n\n")
103 return (recv or self.recv)()
104
105 def error(self, msg):
106 return self.send(
107 f"Remote server reported an error:\n\n{msg}\n")
108
109 def _oauth1_authorization_flow(
110 self, default_key, default_secret,
111 request_token_url, authorize_url, access_token_url):
112 """Perform the OAuth 1.0a authorization flow"""
113
114 api_key = self.oauth_config("api-key") or default_key
115 api_secret = self.oauth_config("api-secret") or default_secret
116 self.session = oauth.OAuth1Session(api_key, api_secret)
117
118 self.log.info("Using %s %s API key (%s)",
119 "default" if api_key == default_key else "custom",
120 self.subcategory, api_key)
121
122 # get a request token
123 params = {"oauth_callback": self.redirect_uri}
124 data = self.request(request_token_url, params=params).text
125
126 data = text.parse_query(data)
127 self.session.auth.token_secret = data["oauth_token_secret"]
128
129 # get the user's authorization
130 params = {"oauth_token": data["oauth_token"], "perms": "read"}
131 data = self.open(authorize_url, params)
132
133 # exchange the request token for an access token
134 data = self.request(access_token_url, params=data).text
135 data = text.parse_query(data)
136 token = data["oauth_token"]
137 token_secret = data["oauth_token_secret"]
138
139 # write to cache
140 if self._cache:
141 key = (self.subcategory, self.session.auth.consumer_key)
142 self.cache_update(oauth._token_cache, key, (token, token_secret))
143 self.log.info("Writing tokens to cache")
144
145 # display tokens
146 self.send(self._generate_message(
147 ("access-token", "access-token-secret"),
148 (token, token_secret),
149 ))
150
151 def _oauth2_authorization_code_grant(
152 self, client_id, client_secret, default_id, default_secret,
153 auth_url, token_url, scope="read", duration="permanent",
154 key="refresh_token", auth=True, cache=None, instance=None,
155 code_challenge=False):
156 """Perform an OAuth2 authorization code grant"""
157
158 client_id = str(client_id) if client_id else default_id
159 client_secret = client_secret or default_secret
160
161 self.log.info("Using %s %s client ID (%s)",
162 "default" if client_id == default_id else "custom",
163 instance or self.subcategory, client_id)
164
165 state = f"gallery-dl_{self.subcategory}_{oauth.nonce(8)}"
166
167 auth_params = {
168 "client_id" : client_id,
169 "response_type": "code",
170 "state" : state,
171 "redirect_uri" : self.redirect_uri,
172 "duration" : duration,
173 "scope" : scope,
174 }
175
176 if code_challenge:
177 code_verifier = self._oauth2_code_challenge(auth_params)
178
179 # receive an authorization code
180 params = self.open(auth_url, auth_params)
181
182 # check authorization response
183 if state != params.get("state"):
184 self.send(f"'state' mismatch: expected {state}, "
185 f"got {params.get('state')}.\n")
186 return
187 if "error" in params:
188 return self.error(params)
189
190 # exchange authorization code for a token
191 data = {
192 "grant_type" : "authorization_code",
193 "code" : params["code"],
194 "redirect_uri": self.redirect_uri,
195 }
196
197 if code_challenge:
198 data["code_verifier"] = code_verifier
199
200 if auth:
201 auth = util.HTTPBasicAuth(client_id, client_secret)
202 else:
203 auth = None
204 data["client_id"] = client_id
205 data["client_secret"] = client_secret
206
207 data = self.request_json(
208 token_url, method="POST", data=data, auth=auth)
209
210 # check token response
211 if "error" in data:
212 return self.error(data)
213
214 token = data[key]
215 token_name = key.replace("_", "-")
216
217 # write to cache
218 if self._cache and cache:
219 self.cache_update(cache, instance or ("#" + str(client_id)), token)
220 self.log.info("Writing '%s' to cache", token_name)
221
222 # display token
223 self.send(self._generate_message(
224 (token_name,), (token,),
225 ))
226
227 def _oauth2_code_challenge(self, params):
228 import binascii
229 import hashlib
230
231 code_verifier = util.generate_token(32)
232 digest = hashlib.sha256(code_verifier.encode()).digest()
233 params["code_challenge_method"] = "S256"
234 params["code_challenge"] = binascii.b2a_base64(
235 digest)[:-2].replace(b"+", b"-").replace(b"/", b"_")
236
237 return code_verifier
238
239 def _generate_message(self, names, values):
240 _vh, _va, _is, _it = (
241 ("This value has", "this value", "is", "it")
242 if len(names) == 1 else
243 ("These values have", "these values", "are", "them")
244 )
245
246 key = " and ".join(f"'{n}'" for n in names)
247 val = "\n".join(values)
248 msg = f"\nYour {key} {_is}\n\n{val}\n\n"
249
250 opt = self.oauth_config(names[0])
251 if self._cache and (opt is None or opt == "cache"):
252 msg += _vh + " been cached and will automatically be used.\n"
253 else:
254 msg += f"Put {_va} into your configuration file as \n"
255 msg += " and\n".join(
256 f"'extractor.{self.subcategory}.{n}'"
257 for n in names
258 )
259 if self._cache:
260 msg = (f"{msg}\nor set\n'extractor."
261 f"{self.subcategory}.{names[0]}' to \"cache\"")
262 msg = f"{msg}\nto use {_it}.\n"
263
264 return msg
265
266
267 # --------------------------------------------------------------------
268 # OAuth 1.0a
269
270 class OAuthFlickr(OAuthBase):
271 subcategory = "flickr"
272 pattern = "oauth:flickr$"
273 example = "oauth:flickr"
274 redirect_uri = REDIRECT_URI_HTTPS
275
276 def items(self):
277 # from . import flickr
278
279 self._oauth1_authorization_flow(
280 # flickr.FlickrAPI.API_KEY,
281 # flickr.FlickrAPI.API_SECRET,
282 "",
283 "",
284 "https://www.flickr.com/services/oauth/request_token",
285 "https://www.flickr.com/services/oauth/authorize",
286 "https://www.flickr.com/services/oauth/access_token",
287 )
288 return iter(NOOP)
289
290
291 class OAuthSmugmug(OAuthBase):
292 subcategory = "smugmug"
293 pattern = "oauth:smugmug$"
294 example = "oauth:smugmug"
295
296 def items(self):
297 from . import smugmug
298
299 self._oauth1_authorization_flow(
300 smugmug.SmugmugAPI.API_KEY,
301 smugmug.SmugmugAPI.API_SECRET,
302 "https://api.smugmug.com/services/oauth/1.0a/getRequestToken",
303 "https://api.smugmug.com/services/oauth/1.0a/authorize",
304 "https://api.smugmug.com/services/oauth/1.0a/getAccessToken",
305 )
306 return iter(NOOP)
307
308
309 class OAuthTumblr(OAuthBase):
310 subcategory = "tumblr"
311 pattern = "oauth:tumblr$"
312 example = "oauth:tumblr"
313
314 def items(self):
315 from . import tumblr
316
317 self._oauth1_authorization_flow(
318 tumblr.TumblrAPI.API_KEY,
319 tumblr.TumblrAPI.API_SECRET,
320 "https://www.tumblr.com/oauth/request_token",
321 "https://www.tumblr.com/oauth/authorize",
322 "https://www.tumblr.com/oauth/access_token",
323 )
324 return iter(NOOP)
325
326
327 # --------------------------------------------------------------------
328 # OAuth 2.0
329
330 class OAuthDeviantart(OAuthBase):
331 subcategory = "deviantart"
332 pattern = "oauth:deviantart$"
333 example = "oauth:deviantart"
334 redirect_uri = REDIRECT_URI_HTTPS
335
336 def items(self):
337 from . import deviantart
338
339 self._oauth2_authorization_code_grant(
340 self.oauth_config("client-id"),
341 self.oauth_config("client-secret"),
342 deviantart.DeviantartOAuthAPI.CLIENT_ID,
343 deviantart.DeviantartOAuthAPI.CLIENT_SECRET,
344 "https://www.deviantart.com/oauth2/authorize",
345 "https://www.deviantart.com/oauth2/token",
346 code_challenge=True,
347 scope="browse user.manage",
348 cache=deviantart._refresh_token_cache,
349 )
350 return iter(NOOP)
351
352
353 class OAuthReddit(OAuthBase):
354 subcategory = "reddit"
355 pattern = "oauth:reddit$"
356 example = "oauth:reddit"
357
358 def items(self):
359 from . import reddit
360
361 self.session.headers["User-Agent"] = reddit.RedditAPI.USER_AGENT
362 self._oauth2_authorization_code_grant(
363 self.oauth_config("client-id"),
364 "",
365 reddit.RedditAPI.CLIENT_ID,
366 "",
367 "https://www.reddit.com/api/v1/authorize",
368 "https://www.reddit.com/api/v1/access_token",
369 scope="read history",
370 cache=reddit._refresh_token_cache,
371 )
372 return iter(NOOP)
373
374
375 class OAuthMastodon(OAuthBase):
376 subcategory = "mastodon"
377 pattern = "oauth:mastodon:(?:https?://)?([^/?#]+)"
378 example = "oauth:mastodon:mastodon.social"
379
380 def __init__(self, match):
381 OAuthBase.__init__(self, match)
382 self.instance = match[1]
383
384 def items(self):
385 from . import mastodon
386
387 for _, root, application in mastodon.MastodonExtractor.instances:
388 if self.instance == root.partition("://")[2]:
389 break
390 else:
391 application = self.cache(self._register, self.instance, _mem=False)
392
393 self._oauth2_authorization_code_grant(
394 application["client-id"],
395 application["client-secret"],
396 application["client-id"],
397 application["client-secret"],
398 f"https://{self.instance}/oauth/authorize",
399 f"https://{self.instance}/oauth/token",
400 instance=self.instance,
401 key="access_token",
402 cache=mastodon._access_token_cache,
403 )
404 return iter(NOOP)
405
406 def _register(self, instance):
407 self.log.info("Registering application for '%s'", instance)
408
409 url = f"https://{instance}/api/v1/apps"
410 data = {
411 "client_name": "gdl:" + oauth.nonce(8),
412 "redirect_uris": self.redirect_uri,
413 "scopes": "read",
414 }
415 data = self.request_json(url, method="POST", data=data)
416
417 if "client_id" not in data or "client_secret" not in data:
418 raise self.exc.AbortExtraction(
419 f"Failed to register new application: '{data}'")
420
421 data["client-id"] = data.pop("client_id")
422 data["client-secret"] = data.pop("client_secret")
423
424 self.log.info("client-id:\n%s", data["client-id"])
425 self.log.info("client-secret:\n%s", data["client-secret"])
426
427 return data
428
429
430 # --------------------------------------------------------------------
431
432 class OAuthPixiv(OAuthBase):
433 subcategory = "pixiv"
434 pattern = "oauth:pixiv$"
435 example = "oauth:pixiv"
436
437 def items(self):
438 from . import pixiv
439
440 url = "https://app-api.pixiv.net/web/v1/login"
441 params = {"client": "pixiv-android"}
442 code_verifier = self._oauth2_code_challenge(params)
443 code = self.open(url, params, self._input_code)
444
445 url = "https://oauth.secure.pixiv.net/auth/token"
446 headers = {
447 "User-Agent": "PixivAndroidApp/5.0.234 (Android 11; Pixel 5)",
448 }
449 data = {
450 "client_id" : self.oauth_config(
451 "client-id" , pixiv.PixivAppAPI.CLIENT_ID),
452 "client_secret" : self.oauth_config(
453 "client-secret", pixiv.PixivAppAPI.CLIENT_SECRET),
454 "code" : code,
455 "code_verifier" : code_verifier,
456 "grant_type" : "authorization_code",
457 "include_policy": "true",
458 "redirect_uri" : "https://app-api.pixiv.net"
459 "/web/v1/users/auth/pixiv/callback",
460 }
461 data = self.request_json(
462 url, method="POST", headers=headers, data=data)
463
464 if "error" in data:
465 stdout_write(f"\n{data}\n")
466 if data["error"] in {"invalid_request", "invalid_grant"}:
467 stdout_write("'code' expired, try again\n\n")
468 return
469
470 token = data["refresh_token"]
471 if self._cache:
472 username = self.oauth_config("username")
473 self.cache_update(pixiv._refresh_token_cache, username, token)
474 self.log.info("Writing 'refresh-token' to cache")
475
476 stdout_write(self._generate_message(("refresh-token",), (token,)))
477 return iter(NOOP)
478
479 def _input_code(self):
480 stdout_write("""\
481 1) Open your browser's Developer Tools (F12) and switch to the Network tab
482 2) Login
483 3) Select the last network monitor entry ('callback?state=...')
484 4) Copy its 'code' query parameter, paste it below, and press Enter
485
486 - This 'code' will expire 30 seconds after logging in.
487 - Copy-pasting more than just the 'code' value will work as well,
488 like the entire URL or several query parameters.
489
490 """)
491 code = self.input("code: ")
492 return code.rpartition("=")[2].strip()