omnipython-applibs 0.1.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. appkit/__init__.py +52 -0
  2. appkit/__init__.pyi +17 -0
  3. appkit/data.py +149 -0
  4. appkit/data.pyi +25 -0
  5. appkit/foreground.py +357 -0
  6. appkit/foreground.pyi +45 -0
  7. appkit/home.py +19 -0
  8. appkit/home.pyi +8 -0
  9. appkit/hover.py +59 -0
  10. appkit/hover.pyi +13 -0
  11. appkit/index.py +199 -0
  12. appkit/index.pyi +30 -0
  13. appkit/launcher.py +1075 -0
  14. appkit/launcher.pyi +96 -0
  15. appkit/manifest.py +75 -0
  16. appkit/manifest.pyi +8 -0
  17. appkit/net.py +167 -0
  18. appkit/net.pyi +34 -0
  19. appkit/places.py +202 -0
  20. appkit/places.pyi +39 -0
  21. appkit/py.typed +0 -0
  22. appkit/scope.py +636 -0
  23. appkit/scope.pyi +110 -0
  24. appkit/shell.py +121 -0
  25. appkit/shell.pyi +32 -0
  26. appkit/worker.py +409 -0
  27. appkit/worker.pyi +83 -0
  28. controlkit/__init__.py +19 -0
  29. controlkit/__init__.pyi +10 -0
  30. controlkit/_draw.py +88 -0
  31. controlkit/_safe.py +29 -0
  32. controlkit/dotmatrix.py +101 -0
  33. controlkit/dotmatrix.pyi +23 -0
  34. controlkit/encoder.py +297 -0
  35. controlkit/encoder.pyi +55 -0
  36. controlkit/font5x7.py +22 -0
  37. controlkit/font5x7.pyi +11 -0
  38. controlkit/lamp_button.py +92 -0
  39. controlkit/lamp_button.pyi +40 -0
  40. controlkit/meter.py +86 -0
  41. controlkit/meter.pyi +30 -0
  42. controlkit/mock.py +116 -0
  43. controlkit/mock.pyi +35 -0
  44. controlkit/pad_grid.py +113 -0
  45. controlkit/pad_grid.pyi +41 -0
  46. controlkit/py.typed +0 -0
  47. controlkit/slider.py +185 -0
  48. controlkit/slider.pyi +49 -0
  49. controlkit/sprites.py +279 -0
  50. controlkit/sprites.pyi +22 -0
  51. controlkit/theme.py +120 -0
  52. controlkit/theme.pyi +15 -0
  53. deskkit/__init__.py +74 -0
  54. deskkit/__init__.pyi +18 -0
  55. deskkit/forecast.py +261 -0
  56. deskkit/forecast.pyi +40 -0
  57. deskkit/localtime.py +215 -0
  58. deskkit/localtime.pyi +33 -0
  59. deskkit/py.typed +0 -0
  60. deskkit/shell.py +113 -0
  61. deskkit/shell.pyi +33 -0
  62. omnipython_applibs-0.1.2.dist-info/METADATA +90 -0
  63. omnipython_applibs-0.1.2.dist-info/RECORD +143 -0
  64. omnipython_applibs-0.1.2.dist-info/WHEEL +5 -0
  65. omnipython_applibs-0.1.2.dist-info/licenses/LICENSE +21 -0
  66. omnipython_applibs-0.1.2.dist-info/top_level.txt +9 -0
  67. programkit/__init__.py +27 -0
  68. programkit/__init__.pyi +8 -0
  69. programkit/board.py +56 -0
  70. programkit/board.pyi +20 -0
  71. programkit/press.py +63 -0
  72. programkit/press.pyi +17 -0
  73. programkit/py.typed +0 -0
  74. programkit/rows.py +149 -0
  75. programkit/rows.pyi +34 -0
  76. sayso/__init__.py +109 -0
  77. sayso/__init__.pyi +124 -0
  78. sayso/auth.py +811 -0
  79. sayso/auth.pyi +102 -0
  80. sayso/client.py +1286 -0
  81. sayso/client.pyi +138 -0
  82. sayso/keepalive.py +371 -0
  83. sayso/keepalive.pyi +53 -0
  84. sayso/local.py +85 -0
  85. sayso/local.pyi +28 -0
  86. sayso/object_specs.py +706 -0
  87. sayso/object_specs.pyi +8 -0
  88. sayso/objects.py +411 -0
  89. sayso/objects.pyi +854 -0
  90. sayso/py.typed +0 -0
  91. sayso/schema_coverage.py +210 -0
  92. sayso/schema_coverage.pyi +13 -0
  93. sayso/transport.py +426 -0
  94. sayso/transport.pyi +47 -0
  95. songmodel/__init__.py +30 -0
  96. songmodel/__init__.pyi +9 -0
  97. songmodel/link.py +189 -0
  98. songmodel/link.pyi +53 -0
  99. songmodel/model.py +238 -0
  100. songmodel/model.pyi +40 -0
  101. songmodel/page.html +225 -0
  102. songmodel/page_data.py +236 -0
  103. songmodel/page_data.pyi +6 -0
  104. songmodel/py.typed +0 -0
  105. soundmodule/__init__.py +7 -0
  106. soundmodule/__init__.pyi +6 -0
  107. soundmodule/engine.py +1001 -0
  108. soundmodule/engine.pyi +196 -0
  109. soundmodule/names.py +298 -0
  110. soundmodule/names.pyi +30 -0
  111. soundmodule/pipes.py +105 -0
  112. soundmodule/pipes.pyi +31 -0
  113. soundmodule/py.typed +0 -0
  114. soundmodule/run.py +249 -0
  115. soundmodule/run.pyi +49 -0
  116. spectrum/__init__.py +72 -0
  117. spectrum/__init__.pyi +30 -0
  118. spectrum/analyzer.py +231 -0
  119. spectrum/analyzer.pyi +67 -0
  120. spectrum/fake_music.py +201 -0
  121. spectrum/fake_music.pyi +36 -0
  122. spectrum/pump_levels.py +126 -0
  123. spectrum/pump_levels.pyi +46 -0
  124. spectrum/py.typed +0 -0
  125. spectrum/spectrum_view.py +403 -0
  126. spectrum/spectrum_view.pyi +80 -0
  127. touchkit/__init__.py +4 -0
  128. touchkit/__init__.pyi +4 -0
  129. touchkit/cam.py +146 -0
  130. touchkit/cam.pyi +35 -0
  131. touchkit/clock.py +18 -0
  132. touchkit/clock.pyi +6 -0
  133. touchkit/ecp.py +134 -0
  134. touchkit/ecp.pyi +28 -0
  135. touchkit/net.py +347 -0
  136. touchkit/net.pyi +27 -0
  137. touchkit/py.typed +0 -0
  138. touchkit/settings.py +85 -0
  139. touchkit/settings.pyi +17 -0
  140. touchkit/shell.py +268 -0
  141. touchkit/shell.pyi +42 -0
  142. touchkit/ui.py +167 -0
  143. touchkit/ui.pyi +53 -0
sayso/auth.py ADDED
@@ -0,0 +1,811 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ import time
6
+
7
+ from .transport import TransportError, post_form_json, query_string, unquote_plus
8
+
9
+
10
+ TOKEN_URL = "https://accounts.spotify.com/api/token"
11
+ AUTHORIZE_URL = "https://accounts.spotify.com/authorize"
12
+
13
+
14
+ class SpotifyAuthError(Exception):
15
+ pass
16
+
17
+
18
+ class TokenCache:
19
+ def __init__(self, path="tokens.json"):
20
+ self.path = path
21
+
22
+ def load(self):
23
+ try:
24
+ import json
25
+ except ImportError:
26
+ return {}
27
+
28
+ try:
29
+ with open(self.path) as file:
30
+ return json.load(file)
31
+ except OSError:
32
+ return {}
33
+
34
+ def save(self, data):
35
+ try:
36
+ import json
37
+ except ImportError:
38
+ return False
39
+
40
+ with open(self.path, "w") as file:
41
+ json.dump(data, file)
42
+
43
+ return True
44
+
45
+ def load_auth(self, auth):
46
+ data = self.load()
47
+ auth.access_token = data.get("access_token")
48
+ auth.expires_at = data.get("expires_at", 0)
49
+
50
+ if data.get("refresh_token") is not None:
51
+ auth.refresh_token = data["refresh_token"]
52
+
53
+ if data.get("redirect_uri") is not None:
54
+ auth.redirect_uri = data["redirect_uri"]
55
+
56
+ if data.get("scope") is not None and auth.scope is None:
57
+ auth.scope = data["scope"]
58
+
59
+ return auth
60
+
61
+ def save_auth(self, auth):
62
+ data = {
63
+ "access_token": auth.access_token,
64
+ "expires_at": auth.expires_at,
65
+ "refresh_token": auth.refresh_token,
66
+ }
67
+
68
+ redirect_uri = getattr(auth, "redirect_uri", None)
69
+ if redirect_uri is not None:
70
+ data["redirect_uri"] = redirect_uri
71
+
72
+ scope = getattr(auth, "scope", None)
73
+ if scope is not None:
74
+ if isinstance(scope, str):
75
+ data["scope"] = scope
76
+ else:
77
+ data["scope"] = " ".join(scope)
78
+
79
+ return self.save(data)
80
+
81
+
82
+ class ClientCredentialsAuth:
83
+ def __init__(self, client_id, client_secret):
84
+ self.client_id = client_id
85
+ self.client_secret = client_secret
86
+ self.access_token = None
87
+ self.expires_at = 0
88
+
89
+ def token(self):
90
+ if self.access_token is None or time.time() >= self.expires_at:
91
+ self.refresh()
92
+ return self.access_token
93
+
94
+ def refresh(self):
95
+ data = post_oauth_token(
96
+ self.client_id,
97
+ self.client_secret,
98
+ {"grant_type": "client_credentials"},
99
+ )
100
+
101
+ self.access_token = data["access_token"]
102
+ self.expires_at = time.time() + int(data.get("expires_in", 0)) - 60
103
+ return self.access_token
104
+
105
+
106
+ class AuthorizationCodeAuth:
107
+ def __init__(
108
+ self,
109
+ client_id,
110
+ client_secret,
111
+ redirect_uri,
112
+ scope=None,
113
+ refresh_token=None,
114
+ code_verifier=None,
115
+ token_cache=None,
116
+ ):
117
+ self.client_id = client_id
118
+ self.client_secret = client_secret
119
+ self.redirect_uri = redirect_uri
120
+ self.scope = scope
121
+ self.refresh_token = refresh_token
122
+ self.code_verifier = code_verifier
123
+ self.token_cache = token_cache
124
+ self.access_token = None
125
+ self.expires_at = 0
126
+
127
+ if self.token_cache is not None:
128
+ self.token_cache.load_auth(self)
129
+
130
+ def authorize_url(self, state=None, show_dialog=None, code_challenge=None, code_challenge_method=None):
131
+ if code_challenge is None and self.code_verifier is not None:
132
+ code_challenge = code_challenge_s256(self.code_verifier)
133
+ code_challenge_method = "S256"
134
+
135
+ return authorization_url(
136
+ self.client_id,
137
+ self.redirect_uri,
138
+ scope=self.scope,
139
+ state=state,
140
+ show_dialog=show_dialog,
141
+ code_challenge=code_challenge,
142
+ code_challenge_method=code_challenge_method,
143
+ )
144
+
145
+ def token(self):
146
+ if self.access_token is None or time.time() >= self.expires_at:
147
+ self.refresh()
148
+ return self.access_token
149
+
150
+ def exchange_code(self, code):
151
+ data = {
152
+ "grant_type": "authorization_code",
153
+ "code": code,
154
+ "redirect_uri": self.redirect_uri,
155
+ }
156
+ if self.code_verifier is not None:
157
+ data["code_verifier"] = self.code_verifier
158
+
159
+ return self._update_tokens(self._post_token(data))
160
+
161
+ def exchange_callback_url(self, callback_url, expected_state=None):
162
+ values = parse_callback_url(callback_url)
163
+ state = values.get("state")
164
+
165
+ if expected_state is not None and state != expected_state:
166
+ raise SpotifyAuthError("OAuth state mismatch")
167
+
168
+ error = values.get("error")
169
+ if error is not None:
170
+ raise SpotifyAuthError("OAuth callback error: " + error)
171
+
172
+ code = values.get("code")
173
+ if code is None:
174
+ raise SpotifyAuthError("OAuth callback did not include a code")
175
+
176
+ return self.exchange_code(code)
177
+
178
+ def refresh(self):
179
+ if self.refresh_token is None:
180
+ raise SpotifyAuthError("A refresh_token or authorization code is required")
181
+
182
+ return self._update_tokens(
183
+ self._post_token(
184
+ {
185
+ "grant_type": "refresh_token",
186
+ "refresh_token": self.refresh_token,
187
+ }
188
+ )
189
+ )
190
+
191
+ def _post_token(self, data):
192
+ return post_oauth_token(self.client_id, self.client_secret, data)
193
+
194
+ def _update_tokens(self, data):
195
+ self.access_token = data["access_token"]
196
+ self.expires_at = time.time() + int(data.get("expires_in", 0)) - 60
197
+
198
+ if data.get("refresh_token") is not None:
199
+ self.refresh_token = data["refresh_token"]
200
+
201
+ if self.token_cache is not None:
202
+ self.token_cache.save_auth(self)
203
+
204
+ return self.access_token
205
+
206
+
207
+ def post_oauth_token(client_id, client_secret, data):
208
+ try:
209
+ return post_form_json(
210
+ TOKEN_URL,
211
+ data,
212
+ headers={"Authorization": "Basic " + basic_token(client_id, client_secret)},
213
+ )
214
+ except TransportError as error:
215
+ raise oauth_error_from_transport(error) from error
216
+
217
+
218
+ def oauth_error_from_transport(error):
219
+ data = error.data
220
+ if isinstance(data, dict):
221
+ oauth_error = data.get("error")
222
+ if oauth_error is not None:
223
+ message = "Spotify OAuth error: " + str(oauth_error)
224
+ description = data.get("error_description")
225
+ if description:
226
+ message += " (" + str(description) + ")"
227
+ return SpotifyAuthError(message)
228
+
229
+ if error.status is not None:
230
+ return SpotifyAuthError("Spotify OAuth request failed with HTTP status {}".format(error.status))
231
+
232
+ return SpotifyAuthError(str(error))
233
+
234
+
235
+ def authorization_url(
236
+ client_id,
237
+ redirect_uri,
238
+ scope=None,
239
+ state=None,
240
+ show_dialog=None,
241
+ code_challenge=None,
242
+ code_challenge_method=None,
243
+ ):
244
+ query = {
245
+ "response_type": "code",
246
+ "client_id": client_id,
247
+ "redirect_uri": redirect_uri,
248
+ }
249
+ add_query(query, "scope", join_scope(scope))
250
+ add_query(query, "state", state)
251
+ add_query(query, "show_dialog", bool_string(show_dialog))
252
+ add_query(query, "code_challenge", code_challenge)
253
+ add_query(query, "code_challenge_method", code_challenge_method)
254
+
255
+ return AUTHORIZE_URL + "?" + query_string(query)
256
+
257
+
258
+ def parse_callback_url(callback_url):
259
+ query = callback_url
260
+ question = query.find("?")
261
+ if question >= 0:
262
+ query = query[question + 1:]
263
+
264
+ fragment = query.find("#")
265
+ if fragment >= 0:
266
+ query = query[:fragment]
267
+
268
+ values = {}
269
+ if not query:
270
+ return values
271
+
272
+ for part in query.split("&"):
273
+ if not part:
274
+ continue
275
+
276
+ equal = part.find("=")
277
+ if equal < 0:
278
+ key = part
279
+ value = ""
280
+ else:
281
+ key = part[:equal]
282
+ value = part[equal + 1:]
283
+
284
+ values[unquote_plus(key)] = unquote_plus(value)
285
+
286
+ return values
287
+
288
+
289
+ def generate_code_verifier(length=64):
290
+ if length < 43 or length > 128:
291
+ raise SpotifyAuthError("PKCE code verifier length must be between 43 and 128")
292
+
293
+ random_bytes = random_bytes_for_verifier(length)
294
+ verifier = base64_urlsafe(random_bytes)
295
+
296
+ if len(verifier) < length:
297
+ return generate_code_verifier(length)
298
+
299
+ return verifier[:length]
300
+
301
+
302
+ def code_challenge_s256(code_verifier):
303
+ try:
304
+ import hashlib
305
+ except ImportError:
306
+ raise SpotifyAuthError("hashlib is required for PKCE S256 code challenges")
307
+
308
+ digest = hashlib.sha256(code_verifier.encode("ascii")).digest()
309
+ return base64_urlsafe(digest)
310
+
311
+
312
+ def pkce_pair(length=64):
313
+ verifier = generate_code_verifier(length)
314
+ return verifier, code_challenge_s256(verifier)
315
+
316
+
317
+ def random_bytes_for_verifier(length):
318
+ try:
319
+ import os
320
+ return os.urandom(length)
321
+ except (AttributeError, ImportError):
322
+ try:
323
+ import urandom
324
+ return bytes(urandom.getrandbits(8) for _ in range(length))
325
+ except ImportError:
326
+ raise SpotifyAuthError("A random byte source is required for PKCE code verifier generation")
327
+
328
+
329
+ def base64_urlsafe(data):
330
+ try:
331
+ import base64
332
+ except ImportError:
333
+ raise SpotifyAuthError("base64 is required for PKCE helpers")
334
+
335
+ encoded = base64.b64encode(data).decode("ascii")
336
+ encoded = encoded.rstrip("=")
337
+ encoded = encoded.replace("+", "-")
338
+ encoded = encoded.replace("/", "_")
339
+ return encoded
340
+
341
+
342
+ def join_scope(scope):
343
+ if scope is None:
344
+ return None
345
+ if isinstance(scope, str):
346
+ return scope
347
+ return " ".join(scope)
348
+
349
+
350
+ def bool_string(value):
351
+ if value is None:
352
+ return None
353
+ if value:
354
+ return "true"
355
+ return "false"
356
+
357
+
358
+ def add_query(query, key, value):
359
+ if value is not None:
360
+ query[key] = value
361
+
362
+
363
+ def basic_token(client_id, client_secret):
364
+ raw = (client_id + ":" + client_secret).encode("utf-8")
365
+
366
+ try:
367
+ import base64
368
+ return base64.b64encode(raw).decode("ascii")
369
+ except ImportError:
370
+ import binascii
371
+ return binascii.b2a_base64(raw).strip().decode("ascii")
372
+
373
+
374
+ DEFAULT_CONFIG_PATH = "sayso.local.json"
375
+ DEFAULT_TOKEN_CACHE_PATH = "tokens.json"
376
+ DEFAULT_REDIRECT_URI = "http://127.0.0.1:8080"
377
+
378
+
379
+ USER_PROFILE_SCOPES = (
380
+ "user-read-email",
381
+ )
382
+
383
+ LIBRARY_READ_SCOPES = (
384
+ "user-library-read",
385
+ )
386
+
387
+ LIBRARY_WRITE_SCOPES = (
388
+ "user-library-modify",
389
+ )
390
+
391
+ PLAYLIST_READ_SCOPES = (
392
+ "playlist-read-private",
393
+ )
394
+
395
+ PLAYLIST_WRITE_SCOPES = (
396
+ "playlist-modify-private",
397
+ "playlist-modify-public",
398
+ "ugc-image-upload",
399
+ )
400
+
401
+ PLAYBACK_READ_SCOPES = (
402
+ "user-read-playback-state",
403
+ "user-read-currently-playing",
404
+ "user-read-recently-played",
405
+ "user-top-read",
406
+ )
407
+
408
+ PLAYBACK_WRITE_SCOPES = (
409
+ "user-modify-playback-state",
410
+ )
411
+
412
+ FOLLOW_WRITE_SCOPES = (
413
+ "user-follow-modify",
414
+ )
415
+
416
+ EXAMPLE_SCOPES = (
417
+ USER_PROFILE_SCOPES
418
+ + LIBRARY_READ_SCOPES
419
+ + LIBRARY_WRITE_SCOPES
420
+ + PLAYLIST_READ_SCOPES
421
+ + PLAYLIST_WRITE_SCOPES
422
+ + PLAYBACK_READ_SCOPES
423
+ + PLAYBACK_WRITE_SCOPES
424
+ + FOLLOW_WRITE_SCOPES
425
+ )
426
+
427
+
428
+ class SpotifyConfigError(SpotifyAuthError):
429
+ pass
430
+
431
+
432
+ def load_config(path=None):
433
+ config_path = path or DEFAULT_CONFIG_PATH
434
+
435
+ try:
436
+ import json
437
+ except ImportError:
438
+ raise SpotifyConfigError("json is required to load sayso.local.json")
439
+
440
+ try:
441
+ with open(config_path) as file:
442
+ data = json.load(file)
443
+ except OSError as error:
444
+ raise SpotifyConfigError(
445
+ "Create {} from sayso.local.json.example and add your Spotify app credentials".format(
446
+ config_path
447
+ )
448
+ ) from error
449
+
450
+ if not isinstance(data, dict):
451
+ raise SpotifyConfigError("{} must contain a JSON object".format(config_path))
452
+
453
+ return data
454
+
455
+
456
+ def save_config(data, path=None):
457
+ config_path = path or DEFAULT_CONFIG_PATH
458
+
459
+ try:
460
+ import json
461
+ except ImportError:
462
+ return False
463
+
464
+ with open(config_path, "w") as file:
465
+ json.dump(data, file, indent=2)
466
+ file.write("\n")
467
+
468
+ return True
469
+
470
+
471
+ def config_available(path=None):
472
+ try:
473
+ config = load_config(path)
474
+ except SpotifyConfigError:
475
+ return False
476
+
477
+ client_id = config.get("client_id")
478
+ client_secret = config.get("client_secret")
479
+ return bool(client_id and client_secret)
480
+
481
+
482
+ def credentials_from_config(config):
483
+ client_id = config.get("client_id")
484
+ client_secret = config.get("client_secret")
485
+
486
+ if not client_id or not client_secret:
487
+ raise SpotifyConfigError(
488
+ "sayso.local.json must include client_id and client_secret"
489
+ )
490
+
491
+ return client_id, client_secret
492
+
493
+
494
+ def redirect_uri_from_config(config, cached=None):
495
+ value = config.get("redirect_uri")
496
+ if value:
497
+ return value
498
+
499
+ if cached is not None and cached.get("redirect_uri"):
500
+ return cached["redirect_uri"]
501
+
502
+ return DEFAULT_REDIRECT_URI
503
+
504
+
505
+ def scopes_from_config(config, cached=None):
506
+ value = config.get("scopes")
507
+ if value:
508
+ if isinstance(value, str):
509
+ return value.split()
510
+ return list(value)
511
+
512
+ if cached is not None:
513
+ scope = cached.get("scope")
514
+ if scope:
515
+ if isinstance(scope, str):
516
+ return scope.split()
517
+ return list(scope)
518
+
519
+ return list(EXAMPLE_SCOPES)
520
+
521
+
522
+ def token_cache_from_config(config):
523
+ path = config.get("token_cache", DEFAULT_TOKEN_CACHE_PATH)
524
+ return TokenCache(path)
525
+
526
+
527
+ def config_value(config, key, default=None):
528
+ value = config.get(key)
529
+ if value is None:
530
+ return default
531
+ return value
532
+
533
+
534
+ def auth_from_config(
535
+ config_path=None,
536
+ scope=None,
537
+ authenticate_if_needed=True,
538
+ auth_state="sayso",
539
+ ):
540
+ config = load_config(config_path)
541
+ client_id, client_secret = credentials_from_config(config)
542
+ cache = token_cache_from_config(config)
543
+ cached = cache.load()
544
+ redirect_uri = redirect_uri_from_config(config, cached)
545
+ refresh_token = cached.get("refresh_token")
546
+
547
+ if scope is None:
548
+ scope = scopes_from_config(config, cached)
549
+
550
+ if refresh_token:
551
+ return AuthorizationCodeAuth(
552
+ client_id,
553
+ client_secret,
554
+ redirect_uri,
555
+ scope=scope,
556
+ refresh_token=refresh_token,
557
+ token_cache=cache,
558
+ )
559
+
560
+ if not authenticate_if_needed:
561
+ raise SpotifyConfigError(
562
+ "No refresh token in {}. Run an example to authenticate in the browser first.".format(
563
+ cache.path
564
+ )
565
+ )
566
+
567
+ code_verifier = generate_code_verifier()
568
+ auth = AuthorizationCodeAuth(
569
+ client_id,
570
+ client_secret,
571
+ redirect_uri,
572
+ scope=scope,
573
+ code_verifier=code_verifier,
574
+ token_cache=cache,
575
+ )
576
+ authorize_with_local_server(
577
+ auth,
578
+ redirect_uri=redirect_uri,
579
+ state=auth_state,
580
+ message="Spotify authorization received. You can close this window.",
581
+ )
582
+ return auth
583
+
584
+
585
+ def authorize_with_local_server(
586
+ auth,
587
+ redirect_uri,
588
+ state="sayso",
589
+ message="Spotify authorization received. You can close this window.",
590
+ open_browser=True,
591
+ ):
592
+ host, port = redirect_uri_host_port(redirect_uri)
593
+ url = auth.authorize_url(state=state, show_dialog=True)
594
+
595
+ print_authorize_instructions(url, redirect_uri, open_browser=open_browser)
596
+ callback_url = wait_for_oauth_callback(host, port, message, redirect_uri)
597
+ access_token = auth.exchange_callback_url(callback_url, expected_state=state)
598
+
599
+ print()
600
+ print("Authorization complete. Saved tokens for future runs.")
601
+ return access_token
602
+
603
+
604
+ def print_authorize_instructions(url, redirect_uri, open_browser=True):
605
+ print()
606
+ print("=" * 72)
607
+ print("Spotify login required")
608
+ print("=" * 72)
609
+ print()
610
+ print("Complete these steps:")
611
+ print(" 1. Open the authorize URL below in your browser.")
612
+ print(" 2. Log in to Spotify and approve access.")
613
+ print(" 3. Leave this terminal running until the callback is received.")
614
+ print()
615
+ print("Authorize URL:")
616
+ print(url)
617
+ print()
618
+
619
+ opened = False
620
+ if open_browser and not running_on_wsl():
621
+ opened = try_open_browser(url)
622
+
623
+ if opened:
624
+ print("Opened your browser automatically.")
625
+ elif running_on_wsl():
626
+ print("WSL cannot open a browser automatically.")
627
+ print("Copy the authorize URL above into a browser on Windows.")
628
+ else:
629
+ print("Could not open a browser automatically.")
630
+ print("Copy the authorize URL above into your browser.")
631
+
632
+ print()
633
+ print("Waiting for Spotify to redirect to {} ...".format(redirect_uri))
634
+ print()
635
+
636
+
637
+ def try_open_browser(url):
638
+ try:
639
+ import webbrowser
640
+ except ImportError:
641
+ return False
642
+
643
+ suppress_stderr = _stderr_suppressor()
644
+ if suppress_stderr is None:
645
+ try:
646
+ return webbrowser.open(url)
647
+ except Exception:
648
+ return False
649
+
650
+ old_stderr = suppress_stderr[0]
651
+ devnull = suppress_stderr[1]
652
+ try:
653
+ try:
654
+ return webbrowser.open(url)
655
+ except Exception:
656
+ return False
657
+ finally:
658
+ _restore_stderr(old_stderr, devnull)
659
+
660
+
661
+ def wait_for_oauth_callback(host, port, message, redirect_uri):
662
+ try:
663
+ from http.server import BaseHTTPRequestHandler, HTTPServer
664
+ except ImportError:
665
+ return wait_for_oauth_callback_socket(host, port, message, redirect_uri)
666
+
667
+ class CallbackHandler(BaseHTTPRequestHandler):
668
+ callback_url = None
669
+
670
+ def do_GET(self):
671
+ CallbackHandler.callback_url = "http://{}:{}{}".format(host, port, self.path)
672
+ self.send_response(200)
673
+ self.send_header("Content-Type", "text/plain")
674
+ self.end_headers()
675
+ self.wfile.write(message.encode("utf-8"))
676
+
677
+ def log_message(self, format, *args):
678
+ pass
679
+
680
+ server = HTTPServer((host, port), CallbackHandler)
681
+
682
+ try:
683
+ server.handle_request()
684
+ finally:
685
+ server.server_close()
686
+
687
+ if CallbackHandler.callback_url is None:
688
+ raise SpotifyAuthError(
689
+ "No OAuth callback was received at {}. "
690
+ "If the browser could not reach localhost, copy the full redirect URL "
691
+ "into sayso.local.json as callback_url and run "
692
+ "examples/authorization_code_pkce_exchange.py.".format(redirect_uri)
693
+ )
694
+
695
+ return CallbackHandler.callback_url
696
+
697
+
698
+ def wait_for_oauth_callback_socket(host, port, message, redirect_uri):
699
+ try:
700
+ import socket as socket_mod
701
+ except ImportError:
702
+ try:
703
+ import usocket as socket_mod
704
+ except ImportError as error:
705
+ raise SpotifyAuthError(
706
+ "Interactive OAuth requires http.server or socket, which is not "
707
+ "available on this runtime"
708
+ ) from error
709
+
710
+ callback_url = None
711
+ addr = socket_mod.getaddrinfo(host, port)[0][-1]
712
+ sock = socket_mod.socket()
713
+ sock.setsockopt(socket_mod.SOL_SOCKET, socket_mod.SO_REUSEADDR, 1)
714
+ sock.bind(addr)
715
+ sock.listen(1)
716
+
717
+ try:
718
+ conn, _addr = sock.accept()
719
+ try:
720
+ request = conn.recv(2048)
721
+ if request:
722
+ first_line = request.split(b"\r\n", 1)[0]
723
+ parts = first_line.split(b" ")
724
+ if len(parts) >= 2:
725
+ path = parts[1].decode()
726
+ callback_url = "http://{}:{}{}".format(host, port, path)
727
+ body = message.encode("utf-8")
728
+ response = (
729
+ "HTTP/1.0 200 OK\r\n"
730
+ "Content-Type: text/plain\r\n"
731
+ "Content-Length: {}\r\n"
732
+ "\r\n"
733
+ ).format(len(body)).encode() + body
734
+ conn.send(response)
735
+ finally:
736
+ conn.close()
737
+ finally:
738
+ sock.close()
739
+
740
+ if callback_url is None:
741
+ raise SpotifyAuthError(
742
+ "No OAuth callback was received at {}. "
743
+ "If the browser could not reach localhost, copy the full redirect URL "
744
+ "into sayso.local.json as callback_url and run "
745
+ "examples/authorization_code_pkce_exchange.py.".format(redirect_uri)
746
+ )
747
+
748
+ return callback_url
749
+
750
+
751
+ def running_on_wsl():
752
+ import os
753
+
754
+ environ = getattr(os, "environ", None)
755
+ if environ is not None and environ.get("WSL_DISTRO_NAME"):
756
+ return True
757
+
758
+ try:
759
+ with open("/proc/version") as file:
760
+ return "microsoft" in file.read().lower()
761
+ except OSError:
762
+ return False
763
+
764
+
765
+ def _stderr_suppressor():
766
+ import os
767
+ import sys
768
+
769
+ try:
770
+ devnull = open(os.devnull, "w")
771
+ except OSError:
772
+ return None
773
+
774
+ return sys.stderr, devnull
775
+
776
+
777
+ def _restore_stderr(old_stderr, devnull):
778
+ import sys
779
+
780
+ sys.stderr = old_stderr
781
+ devnull.close()
782
+
783
+
784
+ def redirect_uri_host_port(redirect_uri):
785
+ if redirect_uri.startswith("http://"):
786
+ rest = redirect_uri[7:]
787
+ default_port = 80
788
+ elif redirect_uri.startswith("https://"):
789
+ rest = redirect_uri[8:]
790
+ default_port = 443
791
+ else:
792
+ raise SpotifyAuthError("redirect_uri must start with http:// or https://")
793
+
794
+ slash = rest.find("/")
795
+ if slash >= 0:
796
+ authority = rest[:slash]
797
+ else:
798
+ authority = rest
799
+
800
+ if not authority:
801
+ raise SpotifyAuthError("redirect_uri is missing a host")
802
+
803
+ colon = authority.rfind(":")
804
+ if colon >= 0:
805
+ host = authority[:colon]
806
+ port = int(authority[colon + 1:])
807
+ else:
808
+ host = authority
809
+ port = default_port
810
+
811
+ return host, port