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/client.pyi ADDED
@@ -0,0 +1,138 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ from collections.abc import Iterable, Sequence
5
+ from typing import Any, Literal, Protocol, TypeVar
6
+
7
+ from .auth import ClientCredentialsAuth as ClientCredentialsAuth
8
+ from .local import EarfulAdapter as EarfulAdapter
9
+ from .objects import Page, SpotifyObject, Album as Album, AlbumPage as AlbumPage, Artist as Artist, ArtistCursorPage as ArtistCursorPage, ArtistPage as ArtistPage, AudioAnalysis as AudioAnalysis, AudioFeatures as AudioFeatures, Audiobook as Audiobook, AudiobookPage as AudiobookPage, Category as Category, CategoryPage as CategoryPage, Chapter as Chapter, ChapterPage as ChapterPage, CurrentlyPlaying as CurrentlyPlaying, Device as Device, Episode as Episode, EpisodePage as EpisodePage, FeaturedPlaylists as FeaturedPlaylists, Image as Image, PlayHistoryCursorPage as PlayHistoryCursorPage, Playlist as Playlist, PlaylistPage as PlaylistPage, PlaylistTrackPage as PlaylistTrackPage, PrivateUser as PrivateUser, Queue as Queue, Recommendations as Recommendations, SavedAlbumPage as SavedAlbumPage, SavedEpisodePage as SavedEpisodePage, SavedShowPage as SavedShowPage, SavedTrackPage as SavedTrackPage, SearchResults as SearchResults, Show as Show, SnapshotResult as SnapshotResult, Track as Track, TrackPage as TrackPage, User as User, set_client as set_client
10
+ from .transport import API_BASE_URL as API_BASE_URL, TransportError as TransportError, build_url as build_url, delete_json as delete_json, get_json as get_json, post_json as post_json, put_body as put_body, put_json as put_json
11
+
12
+ _P = TypeVar('_P', bound=Page[Any])
13
+ _Ids = str | Iterable[str | SpotifyObject]
14
+ _Uris = str | Iterable[str | SpotifyObject]
15
+
16
+ class _Auth(Protocol):
17
+ access_token: str | None
18
+ def token(self) -> str | None: ...
19
+ def refresh(self) -> str | None: ...
20
+
21
+ class SpotifyClientError(Exception):
22
+ """A request was made without a usable access token."""
23
+
24
+ class SpotifyClient:
25
+ """Spotify Web API client; each method is one endpoint."""
26
+
27
+ API_BASE_URL: str
28
+ access_token: str | None
29
+ auth: _Auth | None
30
+ local: EarfulAdapter | None
31
+ def __init__(self, access_token: str | None = None, client_id: str | None = None, client_secret: str | None = None, auth: _Auth | None = None, auto_set: bool = True, config_path: str | None = None, scope: str | Iterable[str] | None = None, authenticate_if_needed: bool = True, auth_state: str = 'sayso', local_device: Any | None = None) -> None: ...
32
+ def next_page(self, page: _P) -> _P | None: ...
33
+ def previous_page(self, page: _P) -> _P | None: ...
34
+ def track(self, object_id: str, market: str | None = None) -> Track: ...
35
+ def tracks(self, ids: _Ids, market: str | None = None) -> list[Track]: ...
36
+ def album(self, object_id: str, market: str | None = None) -> Album: ...
37
+ def albums(self, ids: _Ids, market: str | None = None) -> list[Album]: ...
38
+ def album_tracks(self, object_id: str, market: str | None = None, limit: int | None = None, offset: int | None = None) -> TrackPage: ...
39
+ def artist(self, object_id: str) -> Artist: ...
40
+ def artists(self, ids: _Ids) -> list[Artist]: ...
41
+ def artist_albums(self, object_id: str, include_groups: str | None = None, market: str | None = None, limit: int | None = None, offset: int | None = None) -> AlbumPage: ...
42
+ def artist_top_tracks(self, object_id: str, market: str | None = None) -> Sequence[Track]: ...
43
+ def artist_related_artists(self, object_id: str) -> Sequence[Artist]: ...
44
+ def playlist(self, object_id: str, market: str | None = None, fields: str | None = None, additional_types: str | None = None) -> Playlist: ...
45
+ def create_playlist(self, user_id: str, name: str, public: bool | None = None, collaborative: bool | None = None, description: str | None = None) -> Playlist: ...
46
+ def create_current_user_playlist(self, name: str, public: bool | None = None, collaborative: bool | None = None, description: str | None = None) -> Playlist: ...
47
+ def update_playlist_details(self, object_id: str, name: str | None = None, public: bool | None = None, collaborative: bool | None = None, description: str | None = None) -> Any: ...
48
+ def playlist_items(self, object_id: str, market: str | None = None, fields: str | None = None, limit: int | None = None, offset: int | None = None, additional_types: str | None = None) -> PlaylistTrackPage: ...
49
+ def playlist_tracks(self, object_id: str, market: str | None = None, fields: str | None = None, limit: int | None = None, offset: int | None = None, additional_types: str | None = None) -> PlaylistTrackPage: ...
50
+ def add_playlist_items(self, object_id: str, uris: _Uris, position: int | None = None) -> SnapshotResult | None: ...
51
+ def add_playlist_tracks(self, object_id: str, uris: _Uris, position: int | None = None) -> SnapshotResult | None: ...
52
+ def remove_playlist_items(self, object_id: str, uris: _Uris, snapshot_id: str | None = None) -> SnapshotResult | None: ...
53
+ def remove_playlist_tracks(self, object_id: str, uris: _Uris, snapshot_id: str | None = None) -> SnapshotResult | None: ...
54
+ def replace_playlist_items(self, object_id: str, uris: _Uris) -> SnapshotResult | None: ...
55
+ def replace_playlist_tracks(self, object_id: str, uris: _Uris) -> SnapshotResult | None: ...
56
+ def reorder_playlist_items(self, object_id: str, range_start: int, insert_before: int, range_length: int | None = None, snapshot_id: str | None = None) -> SnapshotResult | None: ...
57
+ def reorder_playlist_tracks(self, object_id: str, range_start: int, insert_before: int, range_length: int | None = None, snapshot_id: str | None = None) -> SnapshotResult | None: ...
58
+ def follow_playlist(self, object_id: str, public: bool | None = None) -> Any: ...
59
+ def unfollow_playlist(self, object_id: str) -> Any: ...
60
+ def playlist_followers_contains(self, object_id: str, ids: _Ids) -> tuple[bool, ...]: ...
61
+ def episode(self, object_id: str, market: str | None = None) -> Episode: ...
62
+ def episodes(self, ids: _Ids, market: str | None = None) -> list[Episode]: ...
63
+ def show(self, object_id: str, market: str | None = None) -> Show: ...
64
+ def shows(self, ids: _Ids, market: str | None = None) -> list[Show]: ...
65
+ def show_episodes(self, object_id: str, market: str | None = None, limit: int | None = None, offset: int | None = None) -> EpisodePage: ...
66
+ def audiobook(self, object_id: str, market: str | None = None) -> Audiobook: ...
67
+ def audiobooks(self, ids: _Ids, market: str | None = None) -> list[Audiobook]: ...
68
+ def audiobook_chapters(self, object_id: str, market: str | None = None, limit: int | None = None, offset: int | None = None) -> ChapterPage: ...
69
+ def chapter(self, object_id: str, market: str | None = None) -> Chapter: ...
70
+ def chapters(self, ids: _Ids, market: str | None = None) -> list[Chapter]: ...
71
+ def audio_features(self, object_id: str) -> AudioFeatures: ...
72
+ def audio_features_many(self, ids: _Ids) -> list[AudioFeatures]: ...
73
+ def audio_analysis(self, object_id: str) -> AudioAnalysis: ...
74
+ def recommendations(self, seed_artists: _Ids | None = None, seed_genres: _Ids | None = None, seed_tracks: _Ids | None = None, limit: int | None = None, market: str | None = None, **kwargs: Any) -> Recommendations: ...
75
+ def category(self, object_id: str, country: str | None = None, locale: str | None = None) -> Category: ...
76
+ def categories(self, country: str | None = None, locale: str | None = None, limit: int | None = None, offset: int | None = None) -> CategoryPage: ...
77
+ def category_playlists(self, category_id: str, limit: int | None = None, offset: int | None = None) -> PlaylistPage: ...
78
+ def featured_playlists(self, country: str | None = None, locale: str | None = None, timestamp: str | None = None, limit: int | None = None, offset: int | None = None) -> FeaturedPlaylists: ...
79
+ def new_releases(self, country: str | None = None, limit: int | None = None, offset: int | None = None) -> AlbumPage: ...
80
+ def search(self, q: str, item_types: str | Iterable[str], market: str | None = None, limit: int | None = None, offset: int | None = None, include_external: str | None = None) -> SearchResults: ...
81
+ def me(self) -> PrivateUser: ...
82
+ def user(self, object_id: str) -> User: ...
83
+ def current_playback(self, market: str | None = None, additional_types: str | None = None) -> CurrentlyPlaying: ...
84
+ def currently_playing(self, market: str | None = None, additional_types: str | None = None) -> CurrentlyPlaying: ...
85
+ def queue(self) -> Queue: ...
86
+ def transfer_playback(self, device_ids: str | Iterable[str], play: bool | None = None) -> Any: ...
87
+ def play(self, device_id: str | None = None, context_uri: str | None = None, uris: _Uris | None = None, offset: int | dict[str, Any] | None = None, position_ms: int | None = None) -> Any: ...
88
+ def pause(self, device_id: str | None = None) -> Any: ...
89
+ def next_track(self, device_id: str | None = None) -> Any: ...
90
+ def previous_track(self, device_id: str | None = None) -> Any: ...
91
+ def seek(self, position_ms: int, device_id: str | None = None) -> Any: ...
92
+ def repeat(self, state: Literal['track', 'context', 'off'], device_id: str | None = None) -> Any: ...
93
+ def shuffle(self, state: bool, device_id: str | None = None) -> Any: ...
94
+ def volume(self, volume_percent: int, device_id: str | None = None) -> Any: ...
95
+ def add_to_queue(self, uri: str | SpotifyObject, device_id: str | None = None) -> Any: ...
96
+ def devices(self) -> list[Device]: ...
97
+ def recently_played(self, limit: int | None = None, after: int | None = None, before: int | None = None) -> PlayHistoryCursorPage: ...
98
+ def current_user_playlists(self, limit: int | None = None, offset: int | None = None) -> PlaylistPage: ...
99
+ def user_playlists(self, object_id: str, limit: int | None = None, offset: int | None = None) -> PlaylistPage: ...
100
+ def saved_albums(self, market: str | None = None, limit: int | None = None, offset: int | None = None) -> SavedAlbumPage: ...
101
+ def saved_tracks(self, market: str | None = None, limit: int | None = None, offset: int | None = None) -> SavedTrackPage: ...
102
+ def saved_episodes(self, market: str | None = None, limit: int | None = None, offset: int | None = None) -> SavedEpisodePage: ...
103
+ def saved_shows(self, limit: int | None = None, offset: int | None = None) -> SavedShowPage: ...
104
+ def saved_audiobooks(self, limit: int | None = None, offset: int | None = None) -> AudiobookPage: ...
105
+ def contains_saved_albums(self, ids: _Ids) -> tuple[bool, ...]: ...
106
+ def save_albums(self, ids: _Ids) -> Any: ...
107
+ def remove_saved_albums(self, ids: _Ids) -> Any: ...
108
+ def contains_saved_tracks(self, ids: _Ids) -> tuple[bool, ...]: ...
109
+ def save_tracks(self, ids: _Ids) -> Any: ...
110
+ def remove_saved_tracks(self, ids: _Ids) -> Any: ...
111
+ def contains_saved_episodes(self, ids: _Ids) -> tuple[bool, ...]: ...
112
+ def save_episodes(self, ids: _Ids) -> Any: ...
113
+ def remove_saved_episodes(self, ids: _Ids) -> Any: ...
114
+ def contains_saved_shows(self, ids: _Ids) -> tuple[bool, ...]: ...
115
+ def save_shows(self, ids: _Ids) -> Any: ...
116
+ def remove_saved_shows(self, ids: _Ids) -> Any: ...
117
+ def contains_saved_audiobooks(self, ids: _Ids) -> tuple[bool, ...]: ...
118
+ def save_audiobooks(self, ids: _Ids) -> Any: ...
119
+ def remove_saved_audiobooks(self, ids: _Ids) -> Any: ...
120
+ def library_contains(self, uris: _Uris) -> tuple[bool, ...]: ...
121
+ def save_library_items(self, uris: _Uris) -> Any: ...
122
+ def remove_library_items(self, uris: _Uris) -> Any: ...
123
+ def followed_artists(self, after: str | None = None, limit: int | None = None) -> ArtistCursorPage: ...
124
+ def follows_artists(self, ids: _Ids) -> tuple[bool, ...]: ...
125
+ def follows_users(self, ids: _Ids) -> tuple[bool, ...]: ...
126
+ def follow_artists(self, ids: _Ids) -> Any: ...
127
+ def follow_users(self, ids: _Ids) -> Any: ...
128
+ def unfollow_artists(self, ids: _Ids) -> Any: ...
129
+ def unfollow_users(self, ids: _Ids) -> Any: ...
130
+ def top_artists(self, time_range: Literal['short_term', 'medium_term', 'long_term'] | None = None, limit: int | None = None, offset: int | None = None) -> ArtistPage: ...
131
+ def top_tracks(self, time_range: Literal['short_term', 'medium_term', 'long_term'] | None = None, limit: int | None = None, offset: int | None = None) -> TrackPage: ...
132
+ def playlist_cover_image(self, object_id: str) -> list[Image]: ...
133
+ def set_playlist_cover_image(self, object_id: str, base64_jpeg: str | bytes) -> Any: ...
134
+ def available_markets(self) -> Sequence[str]: ...
135
+ def recommendation_genres(self) -> Sequence[str]: ...
136
+
137
+ def bool_string(value: object) -> str: ...
138
+ def snapshot_id(result: SnapshotResult | dict[str, Any] | None) -> str | None: ...
sayso/keepalive.py ADDED
@@ -0,0 +1,371 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """A small HTTP/1.1 client that keeps its TLS connections open.
6
+
7
+ MicroPython's ``requests`` opens a new TCP connection and does a new TLS
8
+ handshake for every request. On an ESP32-S3 that handshake is most of a
9
+ second or more of CPU, so every tap in a remote cost one, and the remote felt
10
+ stuck. This keeps one connection per host and reuses it until the server
11
+ closes it, which is what a browser or a phone app does.
12
+
13
+ Only what sayso needs: GET/POST/PUT/DELETE with a body, ``Content-Length``
14
+ or chunked responses, and one transparent retry when a reused connection turns
15
+ out to have been closed by the server while idle.
16
+ """
17
+
18
+ import json
19
+ import socket
20
+
21
+ try:
22
+ import ssl
23
+ except ImportError:
24
+ try:
25
+ import tls as ssl # MicroPython's built-in; ssl is a micropython-lib wrapper
26
+ except ImportError: # pragma: no cover
27
+ ssl = None
28
+
29
+ try:
30
+ import _thread
31
+
32
+ def _lock():
33
+ return _thread.allocate_lock()
34
+
35
+ _MAIN_THREAD = _thread.get_ident()
36
+ except ImportError:
37
+ _thread = None
38
+ _MAIN_THREAD = None
39
+
40
+ class _NoLock:
41
+ def acquire(self, *_a):
42
+ return True
43
+
44
+ def release(self):
45
+ pass
46
+
47
+ def _lock():
48
+ return _NoLock()
49
+
50
+
51
+ TIMEOUT_S = 20
52
+
53
+
54
+ def _let_others_run():
55
+ """On a MicroPython worker thread, hand the GIL over for a moment.
56
+
57
+ The VM passes the GIL on only every 32 backward jumps, so a loop of a few
58
+ long C calls (json.loads of one item) would hold it throughout. Sleeping
59
+ releases it; the main (UI) thread never needs to.
60
+ """
61
+ if _thread is not None and _sleep_ms is not None and _thread.get_ident() != _MAIN_THREAD:
62
+ _sleep_ms(1)
63
+
64
+
65
+ try:
66
+ from time import sleep_ms as _sleep_ms
67
+ except ImportError: # CPython: its GIL switches by time, no help needed
68
+ _sleep_ms = None
69
+
70
+ # Bodies at least this large with an "items" array are parsed an item at a
71
+ # time (see _loads_paged). json.loads runs ~11 ms per KB on an ESP32-S3, GIL
72
+ # held: a 24 KB playlist page was a 270 ms UI stall at a 32 KB threshold.
73
+ SPLIT_BYTES = 8 * 1024
74
+ # Largest single read: one read(n) decrypts all n bytes in C, GIL held.
75
+ READ_CHUNK = 4096
76
+
77
+
78
+ def _loads_paged(data):
79
+ """json.loads for a large paging object, one item at a time.
80
+
81
+ json.loads is one C call, and holds the GIL for all of it: 2.1 s for the
82
+ 325 KB of /me/albums?limit=30 (every album carries its track list) on an
83
+ ESP32-S3, with the UI thread frozen that long behind the worker thread.
84
+ Parsed item by item, the interpreter can switch threads between items
85
+ (~70 ms each). The result is the same as json.loads(data); anything that
86
+ does not split cleanly is parsed whole.
87
+ """
88
+ i = data.find(b'"items"')
89
+ j = data.find(b"[", i) if i >= 0 else -1
90
+ close = data.rfind(b"]")
91
+ if j < 0 or close <= j or data[i + 7:j].strip() != b":":
92
+ return json.loads(data)
93
+ k = j + 1
94
+ while k < close and data[k] in b" \t\r\n":
95
+ k += 1
96
+ q = data.find(b'"', k)
97
+ if data[k:k + 1] != b"{" or q < 0 or data[k + 1:q].strip():
98
+ return json.loads(data)
99
+ # Each item starts with the first item's first key.
100
+ needle = data[q:data.find(b'"', q + 1) + 1]
101
+ starts = [k]
102
+ at = data.find(needle, q + len(needle))
103
+ while 0 <= at < close:
104
+ s = data.rfind(b"{", k, at)
105
+ if s > starts[-1] and not data[s + 1:at].strip():
106
+ starts.append(s)
107
+ at = data.find(needle, at + len(needle))
108
+ starts.append(close)
109
+ try:
110
+ items = []
111
+ for n in range(len(starts) - 1):
112
+ part = data[starts[n]:starts[n + 1]].rstrip()
113
+ if part.endswith(b","):
114
+ part = part[:-1]
115
+ items.append(json.loads(part))
116
+ _let_others_run()
117
+ # The array may sit at any depth ({"artists": {"items": [...]}}):
118
+ # parse the rest around a marker, then put the items where it is.
119
+ page = json.loads(data[:j + 1] + _MARK + data[close:])
120
+ except ValueError:
121
+ return json.loads(data)
122
+ if not _put_items(page, items):
123
+ return json.loads(data)
124
+ return page
125
+
126
+
127
+ _MARK_TEXT = "__sayso_items_marker__"
128
+ _MARK = b'"' + _MARK_TEXT.encode() + b'"'
129
+
130
+
131
+ def _put_items(node, items):
132
+ """Replace the one-element marker list inside node with items."""
133
+ if isinstance(node, dict):
134
+ children = node.values()
135
+ elif isinstance(node, list):
136
+ if len(node) == 1 and node[0] == _MARK_TEXT:
137
+ node[0:1] = items
138
+ return True
139
+ children = node
140
+ else:
141
+ return False
142
+ for child in children:
143
+ if isinstance(child, (dict, list)) and _put_items(child, items):
144
+ return True
145
+ return False
146
+
147
+
148
+ class Response:
149
+ def __init__(self, status_code, headers, content):
150
+ self.status_code = status_code
151
+ self.headers = headers
152
+ self.content = content
153
+
154
+ @property
155
+ def text(self):
156
+ return self.content.decode("utf-8")
157
+
158
+ def json(self):
159
+ if len(self.content) >= SPLIT_BYTES:
160
+ return _loads_paged(self.content)
161
+ return json.loads(self.content)
162
+
163
+ def close(self):
164
+ pass
165
+
166
+
167
+ class _Conn:
168
+ def __init__(self, host, port):
169
+ self.host = host
170
+ self.port = port
171
+ self.sock = None
172
+ self.used = 0
173
+
174
+ def open(self):
175
+ ai = socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM)[0]
176
+ s = socket.socket(ai[0], socket.SOCK_STREAM, ai[2])
177
+ try:
178
+ s.settimeout(TIMEOUT_S)
179
+ s.connect(ai[-1])
180
+ if hasattr(ssl, "SSLContext"):
181
+ ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
182
+ ctx.verify_mode = ssl.CERT_NONE
183
+ if hasattr(ctx, "check_hostname"):
184
+ ctx.check_hostname = False
185
+ s = ctx.wrap_socket(s, server_hostname=self.host)
186
+ else:
187
+ s = ssl.wrap_socket(s, server_hostname=self.host)
188
+ except Exception:
189
+ s.close()
190
+ raise
191
+ self.sock = s
192
+ self.used = 0
193
+
194
+ def close(self):
195
+ if self.sock is not None:
196
+ try:
197
+ self.sock.close()
198
+ except OSError:
199
+ pass
200
+ self.sock = None
201
+
202
+
203
+ def _split_url(url):
204
+ if url.startswith("https://"):
205
+ rest = url[8:]
206
+ port = 443
207
+ else:
208
+ raise ValueError("keepalive handles https:// only: " + url)
209
+ slash = rest.find("/")
210
+ hostport, path = (rest, "/") if slash < 0 else (rest[:slash], rest[slash:])
211
+ if ":" in hostport:
212
+ host, p = hostport.split(":", 1)
213
+ port = int(p)
214
+ else:
215
+ host = hostport
216
+ return host, port, path
217
+
218
+
219
+ class _Reader:
220
+ """Framed reads. MicroPython's stream read(n) waits for all n bytes, so
221
+ headers come a line at a time and bodies by their exact length."""
222
+
223
+ def __init__(self, sock):
224
+ self.sock = sock
225
+
226
+ def line(self):
227
+ data = self.sock.readline()
228
+ if not data:
229
+ raise OSError("connection closed")
230
+ if data.endswith(b"\r\n"):
231
+ return data[:-2]
232
+ return data.rstrip(b"\n")
233
+
234
+ def exact(self, n):
235
+ parts = []
236
+ while n > 0:
237
+ data = self.sock.read(n if n < READ_CHUNK else READ_CHUNK)
238
+ if not data:
239
+ raise OSError("connection closed")
240
+ parts.append(data)
241
+ n -= len(data)
242
+ if n > 0:
243
+ _let_others_run()
244
+ return b"".join(parts)
245
+
246
+ def rest(self):
247
+ parts = []
248
+ while True:
249
+ try:
250
+ d = self.sock.read(4096)
251
+ except OSError:
252
+ break
253
+ if not d:
254
+ break
255
+ parts.append(d)
256
+ return b"".join(parts)
257
+
258
+
259
+ class Session:
260
+ def __init__(self):
261
+ self._conns = {}
262
+ self._lock = _lock()
263
+ self._holder = None # the thread inside request(), while one is
264
+
265
+ def _conn(self, host, port):
266
+ key = (host, port)
267
+ c = self._conns.get(key)
268
+ if c is None:
269
+ c = _Conn(host, port)
270
+ self._conns[key] = c
271
+ return c
272
+
273
+ def close(self):
274
+ for c in self._conns.values():
275
+ c.close()
276
+ self._conns = {}
277
+
278
+ def request(self, method, url, data=None, headers=None):
279
+ host, port, path = _split_url(url)
280
+ if isinstance(data, str):
281
+ data = data.encode("utf-8")
282
+ head = ["%s %s HTTP/1.1" % (method, path), "Host: " + host,
283
+ "Connection: keep-alive"]
284
+ if headers:
285
+ for k, v in headers.items():
286
+ if k.lower() in ("host", "connection", "content-length"):
287
+ continue
288
+ head.append("%s: %s" % (k, v))
289
+ if data is not None or method in ("POST", "PUT", "PATCH", "DELETE"):
290
+ head.append("Content-Length: %d" % (len(data) if data else 0))
291
+ req = ("\r\n".join(head) + "\r\n\r\n").encode("utf-8")
292
+ me = _thread.get_ident() if _thread is not None else None
293
+ if me is not None and self._holder == me:
294
+ # A timer or other scheduled callback, run part way through this
295
+ # thread's own request: waiting for the lock would wait for ever.
296
+ raise RuntimeError("a request from a callback inside another request on the same thread")
297
+ self._lock.acquire()
298
+ self._holder = me
299
+ try:
300
+ c = self._conn(host, port)
301
+ for attempt in (0, 1):
302
+ reused = c.sock is not None
303
+ if not reused:
304
+ c.open()
305
+ got_any = [False]
306
+ try:
307
+ return self._exchange(c, req, data, got_any)
308
+ except OSError:
309
+ c.close()
310
+ # A reused connection the server had already closed fails
311
+ # before any byte of a response: that request was never
312
+ # seen, so ask once more on a fresh connection.
313
+ if attempt == 0 and reused and not got_any[0]:
314
+ continue
315
+ raise
316
+ finally:
317
+ self._holder = None
318
+ self._lock.release()
319
+
320
+ def _exchange(self, c, req, data, got_any):
321
+ s = c.sock
322
+ s.write(req) if hasattr(s, "write") else s.sendall(req)
323
+ if data:
324
+ s.write(data) if hasattr(s, "write") else s.sendall(data)
325
+ r = _Reader(s)
326
+ status_line = r.line()
327
+ got_any[0] = True
328
+ parts = status_line.split(None, 2)
329
+ status = int(parts[1])
330
+ headers = {}
331
+ while True:
332
+ line = r.line()
333
+ if not line:
334
+ break
335
+ k, _, v = line.partition(b":")
336
+ headers[k.strip().lower().decode()] = v.strip().decode()
337
+ if status in (204, 304) or 100 <= status < 200:
338
+ body = b""
339
+ elif headers.get("transfer-encoding", "").lower() == "chunked":
340
+ chunks = []
341
+ while True:
342
+ size = int(r.line().split(b";")[0], 16)
343
+ if size == 0:
344
+ while r.line():
345
+ pass
346
+ break
347
+ chunks.append(r.exact(size))
348
+ r.line()
349
+ body = b"".join(chunks)
350
+ elif "content-length" in headers:
351
+ body = r.exact(int(headers["content-length"]))
352
+ else:
353
+ # No length: the body runs to the end of the connection.
354
+ body = r.rest()
355
+ headers["connection"] = "close"
356
+ c.used += 1
357
+ if headers.get("connection", "").lower() == "close":
358
+ c.close()
359
+ return Response(status, headers, body)
360
+
361
+ def get(self, url, headers=None):
362
+ return self.request("GET", url, None, headers)
363
+
364
+ def post(self, url, data=None, headers=None):
365
+ return self.request("POST", url, data, headers)
366
+
367
+ def put(self, url, data=None, headers=None):
368
+ return self.request("PUT", url, data, headers)
369
+
370
+ def delete(self, url, data=None, headers=None):
371
+ return self.request("DELETE", url, data, headers)
sayso/keepalive.pyi ADDED
@@ -0,0 +1,53 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """A small HTTP/1.1 client that keeps its TLS connections open."""
5
+
6
+ from typing import Any
7
+
8
+ class _NoLock:
9
+ def acquire(self, *_a: Any) -> bool: ...
10
+ def release(self) -> None: ...
11
+
12
+ TIMEOUT_S: int
13
+ SPLIT_BYTES: int
14
+ READ_CHUNK: int
15
+
16
+ class Response:
17
+ """A finished response: status, lowercase header names, body bytes."""
18
+
19
+ status_code: int
20
+ headers: dict[str, str]
21
+ content: bytes
22
+ def __init__(self, status_code: int, headers: dict[str, str], content: bytes) -> None: ...
23
+ @property
24
+ def text(self) -> str: ...
25
+ def json(self) -> Any: ...
26
+ def close(self) -> None: ...
27
+
28
+ class _Conn:
29
+ host: str
30
+ port: int
31
+ sock: Any
32
+ used: int
33
+ def __init__(self, host: str, port: int) -> None: ...
34
+ def open(self) -> None: ...
35
+ def close(self) -> None: ...
36
+
37
+ class _Reader:
38
+ sock: Any
39
+ def __init__(self, sock: Any) -> None: ...
40
+ def line(self) -> bytes: ...
41
+ def exact(self, n: int) -> bytes: ...
42
+ def rest(self) -> bytes: ...
43
+
44
+ class Session:
45
+ """Keeps one connection per host and reuses it until the server closes it."""
46
+
47
+ def __init__(self) -> None: ...
48
+ def close(self) -> None: ...
49
+ def request(self, method: str, url: str, data: str | bytes | None = None, headers: dict[str, str] | None = None) -> Response: ...
50
+ def get(self, url: str, headers: dict[str, str] | None = None) -> Response: ...
51
+ def post(self, url: str, data: str | bytes | None = None, headers: dict[str, str] | None = None) -> Response: ...
52
+ def put(self, url: str, data: str | bytes | None = None, headers: dict[str, str] | None = None) -> Response: ...
53
+ def delete(self, url: str, data: str | bytes | None = None, headers: dict[str, str] | None = None) -> Response: ...
sayso/local.py ADDED
@@ -0,0 +1,85 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """Optional same-interpreter adapter for an earful Connect device.
6
+
7
+ Importing this module never starts earful and never reads credentials. A
8
+ caller supplies the already-created earful Device instance, or calls
9
+ ``discover`` to use a module-level ``device``/``current_device`` if an
10
+ application has exposed one.
11
+ """
12
+
13
+
14
+ class EarfulAdapter:
15
+ def __init__(self, device):
16
+ self.device = device
17
+
18
+ @property
19
+ def device_id(self):
20
+ return getattr(self.device, "device_id", None) or getattr(self.device, "name", None)
21
+
22
+ @property
23
+ def name(self):
24
+ return getattr(self.device, "name", None) or self.device_id
25
+
26
+ def play(self, context_uri=None, uris=None, position_ms=None):
27
+ # earful.Device.play uses Connect-shaped keyword arguments. Passing
28
+ # a context as the positional URI would request a single track and
29
+ # silently lose the playlist; position_ms maps to its ``position``
30
+ # argument so a local play has the same seek semantics as Web API.
31
+ position = 0 if position_ms is None else int(position_ms)
32
+ if uris is not None:
33
+ if len(uris) != 1:
34
+ raise ValueError("earful local playback accepts one URI; use context_uri for a queue")
35
+ return self.device.play(uri=uris[0], position=position)
36
+ if context_uri is not None:
37
+ return self.device.play(context=context_uri, position=position)
38
+ return self.device.play(position=position)
39
+
40
+ def pause(self):
41
+ return self.device.pause()
42
+
43
+ def resume(self):
44
+ method = getattr(self.device, "resume", None)
45
+ return method() if method is not None else self.device.play()
46
+
47
+ def next(self):
48
+ return self.device.next()
49
+
50
+ def previous(self):
51
+ method = getattr(self.device, "prev", None)
52
+ return method() if method is not None else self.device.previous()
53
+
54
+ def seek(self, position_ms):
55
+ return self.device.seek(position_ms)
56
+
57
+ def set_volume(self, volume_percent):
58
+ self.device.volume = volume_percent
59
+ return None
60
+
61
+ def state(self):
62
+ return {
63
+ "device_id": self.device_id,
64
+ "name": self.name,
65
+ "is_active": bool(getattr(self.device, "active", True)),
66
+ "is_playing": bool(getattr(self.device, "playing", False)),
67
+ "volume_percent": getattr(self.device, "volume", None),
68
+ "track": getattr(self.device, "track", None),
69
+ "position_ms": getattr(self.device, "position", None),
70
+ "duration_ms": getattr(self.device, "duration", None),
71
+ "context": getattr(self.device, "playlist", None),
72
+ }
73
+
74
+
75
+ def discover(module=None):
76
+ """Return an adapter only when an application has exposed an earful device."""
77
+ if module is None:
78
+ try:
79
+ import earful as module
80
+ except ImportError:
81
+ return None
82
+ device = getattr(module, "current_device", None) or getattr(module, "device", None)
83
+ if device is None:
84
+ return None
85
+ return EarfulAdapter(device)
sayso/local.pyi ADDED
@@ -0,0 +1,28 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """Optional same-interpreter adapter for an earful Connect device."""
5
+
6
+ from types import ModuleType
7
+ from typing import Any
8
+
9
+ class EarfulAdapter:
10
+ """Wraps an earful device so a SpotifyClient can control it locally."""
11
+
12
+ device: Any
13
+ def __init__(self, device: Any) -> None: ...
14
+ @property
15
+ def device_id(self) -> str | None: ...
16
+ @property
17
+ def name(self) -> str | None: ...
18
+ def play(self, context_uri: str | None = None, uris: list[str] | tuple[str, ...] | None = None, position_ms: int | None = None) -> Any: ...
19
+ def pause(self) -> Any: ...
20
+ def resume(self) -> Any: ...
21
+ def next(self) -> Any: ...
22
+ def previous(self) -> Any: ...
23
+ def seek(self, position_ms: int) -> Any: ...
24
+ def set_volume(self, volume_percent: int) -> None: ...
25
+ def state(self) -> dict[str, Any]: ...
26
+
27
+ def discover(module: ModuleType | None = None) -> EarfulAdapter | None:
28
+ """Return an adapter only when an application has exposed an earful device."""