mopidy-invidious 0.1.0__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.
- mopidy_invidious/__init__.py +41 -0
- mopidy_invidious/backend.py +62 -0
- mopidy_invidious/client.py +153 -0
- mopidy_invidious/ext.conf +28 -0
- mopidy_invidious/library.py +206 -0
- mopidy_invidious/playback.py +67 -0
- mopidy_invidious/ranking.py +87 -0
- mopidy_invidious/translator.py +166 -0
- mopidy_invidious/uris.py +79 -0
- mopidy_invidious-0.1.0.dist-info/METADATA +111 -0
- mopidy_invidious-0.1.0.dist-info/RECORD +15 -0
- mopidy_invidious-0.1.0.dist-info/WHEEL +5 -0
- mopidy_invidious-0.1.0.dist-info/entry_points.txt +2 -0
- mopidy_invidious-0.1.0.dist-info/licenses/LICENSE +202 -0
- mopidy_invidious-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import pathlib
|
|
4
|
+
from importlib.metadata import version
|
|
5
|
+
|
|
6
|
+
from mopidy import config, ext
|
|
7
|
+
|
|
8
|
+
__version__ = version("mopidy-invidious")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Extension(ext.Extension):
|
|
12
|
+
dist_name = "mopidy-invidious"
|
|
13
|
+
ext_name = "invidious"
|
|
14
|
+
version = __version__
|
|
15
|
+
|
|
16
|
+
def get_default_config(self) -> str:
|
|
17
|
+
return config.read(pathlib.Path(__file__).parent / "ext.conf")
|
|
18
|
+
|
|
19
|
+
def get_config_schema(self) -> config.ConfigSchema:
|
|
20
|
+
schema = super().get_config_schema()
|
|
21
|
+
schema["base_url"] = config.String()
|
|
22
|
+
schema["public_url"] = config.String(optional=True)
|
|
23
|
+
schema["timeout"] = config.Integer(minimum=1, maximum=120)
|
|
24
|
+
schema["search_track_results"] = config.Integer(minimum=0, maximum=200)
|
|
25
|
+
# Deprecated alias of search_track_results; still honoured if set.
|
|
26
|
+
schema["search_results"] = config.Integer(optional=True, minimum=0, maximum=200)
|
|
27
|
+
schema["search_playlist_results"] = config.Integer(minimum=0, maximum=20)
|
|
28
|
+
schema["search_channel_results"] = config.Integer(minimum=0, maximum=20)
|
|
29
|
+
schema["search_playlists"] = config.Deprecated()
|
|
30
|
+
schema["search_channels"] = config.Deprecated()
|
|
31
|
+
schema["audio_itags"] = config.List()
|
|
32
|
+
schema["parse_titles"] = config.Boolean()
|
|
33
|
+
schema["playlists"] = config.List(optional=True)
|
|
34
|
+
schema["channels"] = config.List(optional=True)
|
|
35
|
+
schema["cache_ttl"] = config.Integer(minimum=0)
|
|
36
|
+
return schema
|
|
37
|
+
|
|
38
|
+
def setup(self, registry: ext.Registry) -> None:
|
|
39
|
+
from .backend import InvidiousBackend
|
|
40
|
+
|
|
41
|
+
registry.add("backend", InvidiousBackend)
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from typing import TYPE_CHECKING, ClassVar
|
|
5
|
+
|
|
6
|
+
import pykka
|
|
7
|
+
from mopidy import backend, httpclient
|
|
8
|
+
from mopidy.types import UriScheme
|
|
9
|
+
|
|
10
|
+
from . import Extension
|
|
11
|
+
from .client import InvidiousClient, InvidiousError
|
|
12
|
+
from .library import InvidiousLibraryProvider
|
|
13
|
+
from .playback import InvidiousPlaybackProvider
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from mopidy.audio import AudioProxy
|
|
17
|
+
from mopidy.config import Config
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class InvidiousBackend(pykka.ThreadingActor, backend.Backend):
|
|
23
|
+
uri_schemes: ClassVar[list[UriScheme]] = [UriScheme("invidious")]
|
|
24
|
+
|
|
25
|
+
def __init__(self, config: Config, audio: AudioProxy) -> None:
|
|
26
|
+
super().__init__()
|
|
27
|
+
ext_config = config["invidious"]
|
|
28
|
+
|
|
29
|
+
self.client = InvidiousClient(
|
|
30
|
+
ext_config["base_url"],
|
|
31
|
+
timeout=ext_config["timeout"],
|
|
32
|
+
user_agent=httpclient.format_user_agent(
|
|
33
|
+
f"{Extension.dist_name}/{Extension.version}"
|
|
34
|
+
),
|
|
35
|
+
proxy=httpclient.format_proxy(config["proxy"]),
|
|
36
|
+
cache_ttl=ext_config["cache_ttl"],
|
|
37
|
+
)
|
|
38
|
+
self.library = InvidiousLibraryProvider(backend=self, config=ext_config)
|
|
39
|
+
self.playback = InvidiousPlaybackProvider(
|
|
40
|
+
audio=audio, backend=self, config=ext_config
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
def on_start(self) -> None:
|
|
44
|
+
try:
|
|
45
|
+
stats = self.client.stats()
|
|
46
|
+
except InvidiousError as exc:
|
|
47
|
+
# Invidious may simply be starting up; requests will be retried
|
|
48
|
+
# lazily, so don't take the whole of Mopidy down.
|
|
49
|
+
logger.warning(
|
|
50
|
+
"Invidious at %s not reachable: %s", self.client.base_url, exc
|
|
51
|
+
)
|
|
52
|
+
return
|
|
53
|
+
software = stats.get("software", {})
|
|
54
|
+
logger.info(
|
|
55
|
+
"Connected to %s %s at %s",
|
|
56
|
+
software.get("name", "Invidious"),
|
|
57
|
+
software.get("version", "?"),
|
|
58
|
+
self.client.base_url,
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
def on_stop(self) -> None:
|
|
62
|
+
self.client.close()
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""Thin, thread-safe wrapper around the Invidious REST API (/api/v1)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
import urllib.parse
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
# Invidious returns up to ~200 videos per playlist page; stop eventually.
|
|
16
|
+
MAX_PLAYLIST_PAGES = 10
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class InvidiousError(Exception):
|
|
20
|
+
pass
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class _TTLCache:
|
|
24
|
+
def __init__(self, ttl: int, max_size: int = 2048) -> None:
|
|
25
|
+
self._ttl = ttl
|
|
26
|
+
self._max_size = max_size
|
|
27
|
+
self._data: dict[str, tuple[float, Any]] = {}
|
|
28
|
+
self._lock = threading.Lock()
|
|
29
|
+
|
|
30
|
+
def get(self, key: str) -> Any | None:
|
|
31
|
+
with self._lock:
|
|
32
|
+
entry = self._data.get(key)
|
|
33
|
+
if entry is None:
|
|
34
|
+
return None
|
|
35
|
+
expires, value = entry
|
|
36
|
+
if expires < time.monotonic():
|
|
37
|
+
del self._data[key]
|
|
38
|
+
return None
|
|
39
|
+
return value
|
|
40
|
+
|
|
41
|
+
def set(self, key: str, value: Any) -> None:
|
|
42
|
+
if self._ttl <= 0:
|
|
43
|
+
return
|
|
44
|
+
with self._lock:
|
|
45
|
+
if len(self._data) >= self._max_size:
|
|
46
|
+
# Drop the oldest-inserted entry; good enough for this workload.
|
|
47
|
+
self._data.pop(next(iter(self._data)))
|
|
48
|
+
self._data[key] = (time.monotonic() + self._ttl, value)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class InvidiousClient:
|
|
52
|
+
def __init__(
|
|
53
|
+
self,
|
|
54
|
+
base_url: str,
|
|
55
|
+
*,
|
|
56
|
+
timeout: float = 15,
|
|
57
|
+
user_agent: str | None = None,
|
|
58
|
+
proxy: str | None = None,
|
|
59
|
+
cache_ttl: int = 3600,
|
|
60
|
+
) -> None:
|
|
61
|
+
self.base_url = base_url.rstrip("/")
|
|
62
|
+
self._http = httpx.Client(
|
|
63
|
+
base_url=f"{self.base_url}/api/v1",
|
|
64
|
+
timeout=timeout,
|
|
65
|
+
headers={"User-Agent": user_agent} if user_agent else None,
|
|
66
|
+
proxy=proxy,
|
|
67
|
+
follow_redirects=True,
|
|
68
|
+
)
|
|
69
|
+
self._cache = _TTLCache(cache_ttl)
|
|
70
|
+
|
|
71
|
+
def close(self) -> None:
|
|
72
|
+
self._http.close()
|
|
73
|
+
|
|
74
|
+
def _get(self, path: str, **params: Any) -> Any:
|
|
75
|
+
params = {k: v for k, v in params.items() if v is not None}
|
|
76
|
+
try:
|
|
77
|
+
response = self._http.get(path, params=params)
|
|
78
|
+
response.raise_for_status()
|
|
79
|
+
return response.json()
|
|
80
|
+
except httpx.HTTPStatusError as exc:
|
|
81
|
+
detail = _error_detail(exc.response)
|
|
82
|
+
msg = f"Invidious {path} returned {exc.response.status_code}: {detail}"
|
|
83
|
+
raise InvidiousError(msg) from exc
|
|
84
|
+
except (httpx.HTTPError, ValueError) as exc:
|
|
85
|
+
msg = f"Invidious {path} failed: {exc}"
|
|
86
|
+
raise InvidiousError(msg) from exc
|
|
87
|
+
|
|
88
|
+
def _cached(self, key: str, path: str, **params: Any) -> Any:
|
|
89
|
+
value = self._cache.get(key)
|
|
90
|
+
if value is None:
|
|
91
|
+
value = self._get(path, **params)
|
|
92
|
+
self._cache.set(key, value)
|
|
93
|
+
return value
|
|
94
|
+
|
|
95
|
+
def stats(self) -> dict[str, Any]:
|
|
96
|
+
return self._get("/stats")
|
|
97
|
+
|
|
98
|
+
def search(
|
|
99
|
+
self, query: str, *, type: str = "video", page: int = 1
|
|
100
|
+
) -> list[dict[str, Any]]:
|
|
101
|
+
return self._get("/search", q=query, type=type, page=page)
|
|
102
|
+
|
|
103
|
+
def video(self, video_id: str) -> dict[str, Any]:
|
|
104
|
+
return self._cached(f"video:{video_id}", f"/videos/{video_id}", local="true")
|
|
105
|
+
|
|
106
|
+
def playlist(self, playlist_id: str) -> dict[str, Any]:
|
|
107
|
+
key = f"playlist:{playlist_id}"
|
|
108
|
+
if (cached := self._cache.get(key)) is not None:
|
|
109
|
+
return cached
|
|
110
|
+
|
|
111
|
+
result = self._get(f"/playlists/{playlist_id}")
|
|
112
|
+
videos = list(result.get("videos", []))
|
|
113
|
+
seen = {v.get("videoId") for v in videos}
|
|
114
|
+
total = result.get("videoCount") or 0
|
|
115
|
+
page = 2
|
|
116
|
+
while len(videos) < total and page <= MAX_PLAYLIST_PAGES:
|
|
117
|
+
more = self._get(f"/playlists/{playlist_id}", page=page).get("videos", [])
|
|
118
|
+
new = [v for v in more if v.get("videoId") not in seen]
|
|
119
|
+
if not new:
|
|
120
|
+
break
|
|
121
|
+
videos.extend(new)
|
|
122
|
+
seen.update(v.get("videoId") for v in new)
|
|
123
|
+
page += 1
|
|
124
|
+
result["videos"] = videos
|
|
125
|
+
|
|
126
|
+
self._cache.set(key, result)
|
|
127
|
+
return result
|
|
128
|
+
|
|
129
|
+
def channel(self, channel_id: str) -> dict[str, Any]:
|
|
130
|
+
return self._cached(f"channel:{channel_id}", f"/channels/{channel_id}")
|
|
131
|
+
|
|
132
|
+
def channel_videos(self, channel_id: str) -> list[dict[str, Any]]:
|
|
133
|
+
result = self._cached(
|
|
134
|
+
f"channel_videos:{channel_id}", f"/channels/{channel_id}/videos"
|
|
135
|
+
)
|
|
136
|
+
return result.get("videos", [])
|
|
137
|
+
|
|
138
|
+
def stream_url(self, video_id: str, itag: str) -> str:
|
|
139
|
+
"""Stable, non-expiring audio URL.
|
|
140
|
+
|
|
141
|
+
``/latest_version`` resolves a fresh signed stream on every request and
|
|
142
|
+
redirects to it; ``local=true`` makes Invidious proxy the bytes, so
|
|
143
|
+
GStreamer never talks to googlevideo.com directly.
|
|
144
|
+
"""
|
|
145
|
+
query = urllib.parse.urlencode({"id": video_id, "itag": itag, "local": "true"})
|
|
146
|
+
return f"{self.base_url}/latest_version?{query}"
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _error_detail(response: httpx.Response) -> str:
|
|
150
|
+
try:
|
|
151
|
+
return str(response.json().get("error", response.text))[:200]
|
|
152
|
+
except ValueError:
|
|
153
|
+
return response.text[:200]
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[invidious]
|
|
2
|
+
enabled = true
|
|
3
|
+
# Invidious URL as seen from the Mopidy host/container (API + audio streams)
|
|
4
|
+
base_url = http://invidious-app:3000
|
|
5
|
+
# Invidious URL as seen from Mopidy clients (used for cover art);
|
|
6
|
+
# defaults to base_url when empty
|
|
7
|
+
public_url =
|
|
8
|
+
# HTTP timeout in seconds
|
|
9
|
+
timeout = 15
|
|
10
|
+
# Max songs (videos) returned by a search
|
|
11
|
+
search_track_results = 20
|
|
12
|
+
# Deprecated alias of search_track_results; overrides it when set
|
|
13
|
+
search_results =
|
|
14
|
+
# Max playlists (as albums) and channels (as artists) shown above the tracks;
|
|
15
|
+
# only official/album playlists and channels named like the query qualify.
|
|
16
|
+
# 0 disables them.
|
|
17
|
+
search_playlist_results = 5
|
|
18
|
+
search_channel_results = 3
|
|
19
|
+
# Preferred audio formats, first available wins:
|
|
20
|
+
# 251 = Opus ~160k, 140 = AAC 128k, 250 = Opus ~70k, 249 = Opus ~50k
|
|
21
|
+
audio_itags = 251, 140, 250, 249
|
|
22
|
+
# Split "Artist - Title" video titles into artist and track name
|
|
23
|
+
parse_titles = true
|
|
24
|
+
# Playlist IDs (PL...) and channel IDs (UC...) shown when browsing
|
|
25
|
+
playlists =
|
|
26
|
+
channels =
|
|
27
|
+
# Seconds to cache video/playlist/channel metadata
|
|
28
|
+
cache_ttl = 3600
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from collections.abc import Iterable
|
|
5
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
6
|
+
from typing import TYPE_CHECKING, Any
|
|
7
|
+
|
|
8
|
+
from mopidy import backend
|
|
9
|
+
from mopidy.models import Image, Ref, SearchResult, Track
|
|
10
|
+
|
|
11
|
+
from . import ranking, translator
|
|
12
|
+
from . import uris as iuris
|
|
13
|
+
from .client import InvidiousError
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from mopidy.types import Query, SearchField, Uri
|
|
17
|
+
|
|
18
|
+
from .backend import InvidiousBackend
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
# Invidious returns ~20 videos per search page.
|
|
23
|
+
SEARCH_PAGE_SIZE = 20
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class InvidiousLibraryProvider(backend.LibraryProvider):
|
|
27
|
+
root_directory = Ref.directory(uri=iuris.ROOT, name="Invidious")
|
|
28
|
+
|
|
29
|
+
def __init__(self, backend: InvidiousBackend, config: dict[str, Any]) -> None:
|
|
30
|
+
super().__init__(backend)
|
|
31
|
+
self.client = backend.client
|
|
32
|
+
self.config = config
|
|
33
|
+
self.parse_titles = config["parse_titles"]
|
|
34
|
+
self.public_url = config["public_url"] or config["base_url"]
|
|
35
|
+
self.track_limit = config["search_track_results"]
|
|
36
|
+
if config.get("search_results") is not None:
|
|
37
|
+
logger.warning(
|
|
38
|
+
"invidious/search_results is deprecated, "
|
|
39
|
+
"use invidious/search_track_results instead"
|
|
40
|
+
)
|
|
41
|
+
self.track_limit = config["search_results"]
|
|
42
|
+
self._pool = ThreadPoolExecutor(max_workers=3, thread_name_prefix="invidious")
|
|
43
|
+
|
|
44
|
+
# -- browse -------------------------------------------------------------
|
|
45
|
+
|
|
46
|
+
def browse(self, uri: Uri) -> list[Ref]:
|
|
47
|
+
try:
|
|
48
|
+
parsed = iuris.parse(uri)
|
|
49
|
+
if parsed.kind == "root":
|
|
50
|
+
return self._browse_root()
|
|
51
|
+
if uri == iuris.PLAYLISTS_DIR:
|
|
52
|
+
return self._browse_playlists()
|
|
53
|
+
if uri == iuris.CHANNELS_DIR:
|
|
54
|
+
return self._browse_channels()
|
|
55
|
+
if parsed.kind in (iuris.PLAYLIST, iuris.CHANNEL):
|
|
56
|
+
return [translator.track_ref(t) for t in self.lookup(uri)]
|
|
57
|
+
except (ValueError, InvidiousError) as exc:
|
|
58
|
+
logger.warning("Failed to browse %s: %s", uri, exc)
|
|
59
|
+
return []
|
|
60
|
+
|
|
61
|
+
def _browse_root(self) -> list[Ref]:
|
|
62
|
+
refs = []
|
|
63
|
+
if self.config["playlists"]:
|
|
64
|
+
refs.append(Ref.directory(uri=iuris.PLAYLISTS_DIR, name="Playlists"))
|
|
65
|
+
if self.config["channels"]:
|
|
66
|
+
refs.append(Ref.directory(uri=iuris.CHANNELS_DIR, name="Channels"))
|
|
67
|
+
return refs
|
|
68
|
+
|
|
69
|
+
def _browse_playlists(self) -> list[Ref]:
|
|
70
|
+
refs = []
|
|
71
|
+
for playlist_id in self.config["playlists"]:
|
|
72
|
+
try:
|
|
73
|
+
playlist = self.client.playlist(playlist_id)
|
|
74
|
+
except InvidiousError as exc:
|
|
75
|
+
logger.warning("Skipping playlist %s: %s", playlist_id, exc)
|
|
76
|
+
continue
|
|
77
|
+
refs.append(translator.album_ref(translator.playlist_to_album(playlist)))
|
|
78
|
+
return refs
|
|
79
|
+
|
|
80
|
+
def _browse_channels(self) -> list[Ref]:
|
|
81
|
+
refs = []
|
|
82
|
+
for channel_id in self.config["channels"]:
|
|
83
|
+
try:
|
|
84
|
+
channel = self.client.channel(channel_id)
|
|
85
|
+
except InvidiousError as exc:
|
|
86
|
+
logger.warning("Skipping channel %s: %s", channel_id, exc)
|
|
87
|
+
continue
|
|
88
|
+
refs.append(translator.artist_ref(translator.channel_to_artist(channel)))
|
|
89
|
+
return refs
|
|
90
|
+
|
|
91
|
+
# -- lookup -------------------------------------------------------------
|
|
92
|
+
|
|
93
|
+
def lookup(self, uri: Uri) -> list[Track]:
|
|
94
|
+
try:
|
|
95
|
+
parsed = iuris.parse(uri)
|
|
96
|
+
if parsed.kind == iuris.VIDEO:
|
|
97
|
+
track = translator.video_to_track(
|
|
98
|
+
self.client.video(parsed.id), parse_titles=self.parse_titles
|
|
99
|
+
)
|
|
100
|
+
return [track] if track else []
|
|
101
|
+
if parsed.kind == iuris.PLAYLIST:
|
|
102
|
+
return translator.playlist_to_tracks(
|
|
103
|
+
self.client.playlist(parsed.id), parse_titles=self.parse_titles
|
|
104
|
+
)
|
|
105
|
+
if parsed.kind == iuris.CHANNEL:
|
|
106
|
+
tracks = (
|
|
107
|
+
translator.video_to_track(v, parse_titles=self.parse_titles)
|
|
108
|
+
for v in self.client.channel_videos(parsed.id)
|
|
109
|
+
)
|
|
110
|
+
return [t for t in tracks if t is not None]
|
|
111
|
+
except (ValueError, InvidiousError) as exc:
|
|
112
|
+
logger.warning("Failed to look up %s: %s", uri, exc)
|
|
113
|
+
return []
|
|
114
|
+
|
|
115
|
+
# -- search -------------------------------------------------------------
|
|
116
|
+
|
|
117
|
+
def search(
|
|
118
|
+
self,
|
|
119
|
+
query: Query[SearchField],
|
|
120
|
+
uris: Iterable[Uri] | None = None,
|
|
121
|
+
exact: bool = False,
|
|
122
|
+
) -> SearchResult | None:
|
|
123
|
+
terms = [
|
|
124
|
+
str(value)
|
|
125
|
+
for field in ("any", "artist", "albumartist", "track_name", "album")
|
|
126
|
+
for value in query.get(field, ())
|
|
127
|
+
]
|
|
128
|
+
if not terms:
|
|
129
|
+
return None
|
|
130
|
+
q = " ".join(terms)
|
|
131
|
+
|
|
132
|
+
playlist_limit = self.config["search_playlist_results"]
|
|
133
|
+
channel_limit = self.config["search_channel_results"]
|
|
134
|
+
|
|
135
|
+
videos = self._pool.submit(self._search_videos, q)
|
|
136
|
+
playlists = (
|
|
137
|
+
self._pool.submit(self._search, q, "playlist") if playlist_limit else None
|
|
138
|
+
)
|
|
139
|
+
channels = (
|
|
140
|
+
self._pool.submit(self._search, q, "channel") if channel_limit else None
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
return SearchResult(
|
|
144
|
+
uri=iuris.search(q),
|
|
145
|
+
tracks=tuple(videos.result()),
|
|
146
|
+
albums=tuple(
|
|
147
|
+
translator.playlist_to_album(p)
|
|
148
|
+
for p in ranking.pick_playlists(
|
|
149
|
+
playlists.result() if playlists else [], q, playlist_limit
|
|
150
|
+
)
|
|
151
|
+
),
|
|
152
|
+
artists=tuple(
|
|
153
|
+
translator.channel_to_artist(c)
|
|
154
|
+
for c in ranking.pick_channels(
|
|
155
|
+
channels.result() if channels else [], q, channel_limit
|
|
156
|
+
)
|
|
157
|
+
),
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
def _search(self, q: str, type: str, page: int = 1) -> list[dict[str, Any]]:
|
|
161
|
+
try:
|
|
162
|
+
return self.client.search(q, type=type, page=page)
|
|
163
|
+
except InvidiousError as exc:
|
|
164
|
+
logger.warning("Invidious %s search for %r failed: %s", type, q, exc)
|
|
165
|
+
return []
|
|
166
|
+
|
|
167
|
+
def _search_videos(self, q: str) -> list[Track]:
|
|
168
|
+
limit = self.track_limit
|
|
169
|
+
tracks: list[Track] = []
|
|
170
|
+
page = 1
|
|
171
|
+
while len(tracks) < limit:
|
|
172
|
+
results = self._search(q, "video", page)
|
|
173
|
+
if not results:
|
|
174
|
+
break
|
|
175
|
+
for video in results:
|
|
176
|
+
track = translator.video_to_track(video, parse_titles=self.parse_titles)
|
|
177
|
+
if track is not None:
|
|
178
|
+
tracks.append(track)
|
|
179
|
+
if len(results) < SEARCH_PAGE_SIZE:
|
|
180
|
+
break
|
|
181
|
+
page += 1
|
|
182
|
+
return tracks[:limit]
|
|
183
|
+
|
|
184
|
+
# -- images -------------------------------------------------------------
|
|
185
|
+
|
|
186
|
+
def get_images(self, uris: Iterable[Uri]) -> dict[Uri, list[Image]]:
|
|
187
|
+
result: dict[Uri, list[Image]] = {}
|
|
188
|
+
for uri in uris:
|
|
189
|
+
try:
|
|
190
|
+
parsed = iuris.parse(uri)
|
|
191
|
+
if parsed.kind == iuris.VIDEO:
|
|
192
|
+
result[uri] = translator.video_images(parsed.id, self.public_url)
|
|
193
|
+
elif parsed.kind == iuris.PLAYLIST:
|
|
194
|
+
playlist = self.client.playlist(parsed.id)
|
|
195
|
+
thumb = playlist.get("playlistThumbnail")
|
|
196
|
+
result[uri] = translator.thumbnails_to_images(
|
|
197
|
+
[{"url": thumb}] if thumb else [], self.public_url
|
|
198
|
+
)
|
|
199
|
+
elif parsed.kind == iuris.CHANNEL:
|
|
200
|
+
channel = self.client.channel(parsed.id)
|
|
201
|
+
result[uri] = translator.thumbnails_to_images(
|
|
202
|
+
channel.get("authorThumbnails", []), self.public_url
|
|
203
|
+
)
|
|
204
|
+
except (ValueError, InvidiousError) as exc:
|
|
205
|
+
logger.debug("No images for %s: %s", uri, exc)
|
|
206
|
+
return result
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from typing import TYPE_CHECKING, Any
|
|
5
|
+
|
|
6
|
+
from mopidy import backend
|
|
7
|
+
from mopidy.types import Uri
|
|
8
|
+
|
|
9
|
+
from . import uris
|
|
10
|
+
from .client import InvidiousError
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from mopidy.audio import AudioProxy
|
|
14
|
+
|
|
15
|
+
from .backend import InvidiousBackend
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class InvidiousPlaybackProvider(backend.PlaybackProvider):
|
|
21
|
+
def __init__(
|
|
22
|
+
self, audio: AudioProxy, backend: InvidiousBackend, config: dict[str, Any]
|
|
23
|
+
) -> None:
|
|
24
|
+
super().__init__(audio, backend)
|
|
25
|
+
self.client = backend.client
|
|
26
|
+
self.preferred_itags = [str(i) for i in config["audio_itags"]]
|
|
27
|
+
|
|
28
|
+
def translate_uri(self, uri: Uri) -> Uri | None:
|
|
29
|
+
try:
|
|
30
|
+
parsed = uris.parse(uri)
|
|
31
|
+
except ValueError:
|
|
32
|
+
logger.warning("Cannot play %s: invalid URI", uri)
|
|
33
|
+
return None
|
|
34
|
+
if parsed.kind != uris.VIDEO:
|
|
35
|
+
return None
|
|
36
|
+
|
|
37
|
+
try:
|
|
38
|
+
video = self.client.video(parsed.id)
|
|
39
|
+
except InvidiousError as exc:
|
|
40
|
+
# Don't give up: latest_version can still work for the usual itag.
|
|
41
|
+
logger.warning("Metadata for %s unavailable (%s), guessing", uri, exc)
|
|
42
|
+
return Uri(self.client.stream_url(parsed.id, self.preferred_itags[0]))
|
|
43
|
+
|
|
44
|
+
if video.get("liveNow") and video.get("hlsUrl"):
|
|
45
|
+
return Uri(video["hlsUrl"])
|
|
46
|
+
|
|
47
|
+
itag = self._pick_itag(video)
|
|
48
|
+
if itag is None:
|
|
49
|
+
logger.warning("No audio stream found for %s", uri)
|
|
50
|
+
return None
|
|
51
|
+
logger.debug("Playing %s using itag %s", uri, itag)
|
|
52
|
+
return Uri(self.client.stream_url(parsed.id, itag))
|
|
53
|
+
|
|
54
|
+
def _pick_itag(self, video: dict[str, Any]) -> str | None:
|
|
55
|
+
available = [
|
|
56
|
+
str(f.get("itag"))
|
|
57
|
+
for f in video.get("adaptiveFormats", [])
|
|
58
|
+
if str(f.get("type", "")).startswith("audio/")
|
|
59
|
+
]
|
|
60
|
+
for itag in self.preferred_itags:
|
|
61
|
+
if itag in available:
|
|
62
|
+
return itag
|
|
63
|
+
if available:
|
|
64
|
+
return available[0]
|
|
65
|
+
# Muxed audio+video stream as the last resort (itag 18 = 360p mp4).
|
|
66
|
+
muxed = [str(f.get("itag")) for f in video.get("formatStreams", [])]
|
|
67
|
+
return muxed[0] if muxed else None
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Pick the few channels and playlists worth showing above search tracks.
|
|
2
|
+
|
|
3
|
+
Invidious returns ~20 channels and ~20 playlists per search, mostly fan
|
|
4
|
+
uploads and namesakes. We keep only results whose channel name is (part of)
|
|
5
|
+
what the user typed, e.g. "daft punk" keeps "Daft Punk" and "DaftPunkVEVO"
|
|
6
|
+
but not "Daft Spunky" or "Daft Punk Live Covers".
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from .translator import TOPIC_SUFFIX
|
|
15
|
+
|
|
16
|
+
_TOKEN = re.compile(r"\w+")
|
|
17
|
+
_NAME_NOISE = ("vevo", "official", "music")
|
|
18
|
+
# Unverified channels below this are almost always namesakes, not artists.
|
|
19
|
+
MIN_SUBSCRIBERS = 1000
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _tokens(text: str) -> list[str]:
|
|
23
|
+
return _TOKEN.findall(text.casefold())
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _squash(tokens: list[str]) -> str:
|
|
27
|
+
joined = "".join(tokens)
|
|
28
|
+
for noise in _NAME_NOISE:
|
|
29
|
+
if joined.endswith(noise) and len(joined) > len(noise):
|
|
30
|
+
joined = joined.removesuffix(noise)
|
|
31
|
+
return joined
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def name_matches_query(name: str, query: str) -> bool:
|
|
35
|
+
"""True if ``name`` equals a contiguous run of words in ``query``.
|
|
36
|
+
|
|
37
|
+
Spacing and a trailing "VEVO"/"Official"/"Music" are ignored, so
|
|
38
|
+
"DaftPunkVEVO" matches the query "daft punk one more time".
|
|
39
|
+
"""
|
|
40
|
+
name_key = _squash(_tokens(name.removesuffix(TOPIC_SUFFIX)))
|
|
41
|
+
if len(name_key) < 2:
|
|
42
|
+
return False
|
|
43
|
+
words = _tokens(query)
|
|
44
|
+
return any(
|
|
45
|
+
"".join(words[i:j]) == name_key
|
|
46
|
+
for i in range(len(words))
|
|
47
|
+
for j in range(i + 1, len(words) + 1)
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def pick_channels(
|
|
52
|
+
channels: list[dict[str, Any]], query: str, limit: int
|
|
53
|
+
) -> list[dict[str, Any]]:
|
|
54
|
+
candidates = [
|
|
55
|
+
c
|
|
56
|
+
for c in channels
|
|
57
|
+
if c.get("type") == "channel"
|
|
58
|
+
and c.get("authorId")
|
|
59
|
+
# Topic channels can't list their videos (Invidious returns HTTP 500).
|
|
60
|
+
and not (c.get("author") or "").endswith(TOPIC_SUFFIX)
|
|
61
|
+
and (c.get("authorVerified") or (c.get("subCount") or 0) >= MIN_SUBSCRIBERS)
|
|
62
|
+
and name_matches_query(c.get("author") or "", query)
|
|
63
|
+
]
|
|
64
|
+
# Stable sort: verified first, otherwise keep YouTube's relevance order.
|
|
65
|
+
candidates.sort(key=lambda c: not c.get("authorVerified"))
|
|
66
|
+
|
|
67
|
+
picked, seen = [], set()
|
|
68
|
+
for channel in candidates:
|
|
69
|
+
key = _squash(_tokens(channel["author"]))
|
|
70
|
+
if key not in seen:
|
|
71
|
+
seen.add(key)
|
|
72
|
+
picked.append(channel)
|
|
73
|
+
return picked[:limit]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def pick_playlists(
|
|
77
|
+
playlists: list[dict[str, Any]], query: str, limit: int
|
|
78
|
+
) -> list[dict[str, Any]]:
|
|
79
|
+
official, albums = [], []
|
|
80
|
+
for playlist in playlists:
|
|
81
|
+
if playlist.get("type") != "playlist" or not playlist.get("playlistId"):
|
|
82
|
+
continue
|
|
83
|
+
if name_matches_query(playlist.get("author") or "", query):
|
|
84
|
+
official.append(playlist)
|
|
85
|
+
elif "album" in (playlist.get("title") or "").casefold():
|
|
86
|
+
albums.append(playlist)
|
|
87
|
+
return (official + albums)[:limit]
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""Convert Invidious API JSON into Mopidy models."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import datetime
|
|
6
|
+
import re
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from mopidy.models import Album, Artist, Image, Ref, Track
|
|
10
|
+
from mopidy.types import DurationMs, ReleaseDate, Uri
|
|
11
|
+
|
|
12
|
+
from . import uris
|
|
13
|
+
|
|
14
|
+
TOPIC_SUFFIX = " - Topic"
|
|
15
|
+
_TITLE_SEPARATORS = re.compile(r"\s+[-–—]\s+") # noqa: RUF001 - hyphen, en/em dash
|
|
16
|
+
_TITLE_NOISE = re.compile(
|
|
17
|
+
r"\s*[\(\[](official\s+(music\s+)?(video|audio|lyric\s+video|visualizer)|"
|
|
18
|
+
r"lyrics?|audio|hd|hq|4k|remastered(\s+\d{4})?)[\)\]]\s*",
|
|
19
|
+
re.IGNORECASE,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def clean_author(author: str) -> str:
|
|
24
|
+
"""'Daft Punk - Topic' (YouTube Music auto channel) -> 'Daft Punk'."""
|
|
25
|
+
return author.removesuffix(TOPIC_SUFFIX)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def split_title(title: str, author: str, *, parse: bool = True) -> tuple[str, str]:
|
|
29
|
+
"""Return ``(artist, track_name)`` for a video.
|
|
30
|
+
|
|
31
|
+
Auto-generated "<artist> - Topic" channels already have a clean title and
|
|
32
|
+
a reliable artist. Otherwise try the common "Artist - Title" convention and
|
|
33
|
+
fall back to the channel name.
|
|
34
|
+
"""
|
|
35
|
+
artist = clean_author(author)
|
|
36
|
+
if not parse or author.endswith(TOPIC_SUFFIX):
|
|
37
|
+
return artist, title
|
|
38
|
+
|
|
39
|
+
parts = _TITLE_SEPARATORS.split(title, maxsplit=1)
|
|
40
|
+
if len(parts) == 2 and all(p.strip() for p in parts):
|
|
41
|
+
artist, title = parts
|
|
42
|
+
title = _TITLE_NOISE.sub(" ", title).strip() or title
|
|
43
|
+
return artist.strip(), title.strip()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _release_date(published: int | None) -> ReleaseDate | None:
|
|
47
|
+
if not published:
|
|
48
|
+
return None
|
|
49
|
+
date = datetime.datetime.fromtimestamp(published, tz=datetime.UTC).date()
|
|
50
|
+
return ReleaseDate(date.isoformat())
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def video_to_track(
|
|
54
|
+
video: dict[str, Any],
|
|
55
|
+
*,
|
|
56
|
+
album: Album | None = None,
|
|
57
|
+
track_no: int | None = None,
|
|
58
|
+
parse_titles: bool = True,
|
|
59
|
+
) -> Track | None:
|
|
60
|
+
video_id = video.get("videoId")
|
|
61
|
+
if not video_id or video.get("type", "video") != "video":
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
author = video.get("author") or ""
|
|
65
|
+
artist_name, name = split_title(
|
|
66
|
+
video.get("title") or video_id, author, parse=parse_titles
|
|
67
|
+
)
|
|
68
|
+
channel_uri = uris.channel(video["authorId"]) if video.get("authorId") else None
|
|
69
|
+
# Only link the artist to the channel when the artist *is* the channel.
|
|
70
|
+
artist = Artist(
|
|
71
|
+
uri=channel_uri if artist_name == clean_author(author) else None,
|
|
72
|
+
name=artist_name or None,
|
|
73
|
+
)
|
|
74
|
+
length = video.get("lengthSeconds")
|
|
75
|
+
|
|
76
|
+
return Track(
|
|
77
|
+
uri=uris.video(video_id),
|
|
78
|
+
name=name,
|
|
79
|
+
artists=frozenset({artist}) if artist.name else frozenset(),
|
|
80
|
+
album=album,
|
|
81
|
+
track_no=track_no,
|
|
82
|
+
genre=video.get("genre") or None,
|
|
83
|
+
length=DurationMs(length * 1000) if length else None,
|
|
84
|
+
date=_release_date(video.get("published")),
|
|
85
|
+
comment=f"https://www.youtube.com/watch?v={video_id}",
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def playlist_to_album(playlist: dict[str, Any]) -> Album:
|
|
90
|
+
author = playlist.get("author")
|
|
91
|
+
return Album(
|
|
92
|
+
uri=uris.playlist(playlist["playlistId"]),
|
|
93
|
+
name=playlist.get("title"),
|
|
94
|
+
artists=frozenset({Artist(name=clean_author(author))})
|
|
95
|
+
if author
|
|
96
|
+
else frozenset(),
|
|
97
|
+
num_tracks=playlist.get("videoCount") or None,
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def playlist_to_tracks(
|
|
102
|
+
playlist: dict[str, Any], *, parse_titles: bool = True
|
|
103
|
+
) -> list[Track]:
|
|
104
|
+
album = playlist_to_album(playlist)
|
|
105
|
+
tracks = (
|
|
106
|
+
video_to_track(v, album=album, track_no=i, parse_titles=parse_titles)
|
|
107
|
+
for i, v in enumerate(playlist.get("videos", []), start=1)
|
|
108
|
+
)
|
|
109
|
+
return [t for t in tracks if t is not None]
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def channel_to_artist(channel: dict[str, Any]) -> Artist:
|
|
113
|
+
return Artist(
|
|
114
|
+
uri=uris.channel(channel["authorId"]),
|
|
115
|
+
name=clean_author(channel.get("author") or channel["authorId"]),
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def track_ref(track: Track) -> Ref:
|
|
120
|
+
return Ref.track(uri=track.uri, name=_display_name(track))
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def album_ref(album: Album) -> Ref:
|
|
124
|
+
assert album.uri is not None
|
|
125
|
+
return Ref.album(uri=album.uri, name=album.name)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def artist_ref(artist: Artist) -> Ref:
|
|
129
|
+
assert artist.uri is not None
|
|
130
|
+
return Ref.artist(uri=artist.uri, name=artist.name)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _display_name(track: Track) -> str | None:
|
|
134
|
+
artists = ", ".join(sorted(a.name for a in track.artists if a.name))
|
|
135
|
+
return f"{artists} - {track.name}" if artists else track.name
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def thumbnails_to_images(
|
|
139
|
+
thumbnails: list[dict[str, Any]], base_url: str
|
|
140
|
+
) -> list[Image]:
|
|
141
|
+
images = []
|
|
142
|
+
for thumb in thumbnails:
|
|
143
|
+
url = thumb.get("url")
|
|
144
|
+
if not url:
|
|
145
|
+
continue
|
|
146
|
+
if url.startswith("//"):
|
|
147
|
+
url = f"https:{url}"
|
|
148
|
+
elif url.startswith("/"):
|
|
149
|
+
url = f"{base_url.rstrip('/')}{url}"
|
|
150
|
+
images.append(
|
|
151
|
+
Image(
|
|
152
|
+
uri=Uri(url),
|
|
153
|
+
width=thumb.get("width") or None,
|
|
154
|
+
height=thumb.get("height") or None,
|
|
155
|
+
)
|
|
156
|
+
)
|
|
157
|
+
return images
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def video_images(video_id: str, base_url: str) -> list[Image]:
|
|
161
|
+
"""Thumbnails served by Invidious' /vi/ proxy, without an API round trip."""
|
|
162
|
+
base = base_url.rstrip("/")
|
|
163
|
+
return [
|
|
164
|
+
Image(uri=Uri(f"{base}/vi/{video_id}/mqdefault.jpg"), width=320, height=180),
|
|
165
|
+
Image(uri=Uri(f"{base}/vi/{video_id}/hqdefault.jpg"), width=480, height=360),
|
|
166
|
+
]
|
mopidy_invidious/uris.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Mopidy URI scheme for Invidious.
|
|
2
|
+
|
|
3
|
+
invidious:root browse root
|
|
4
|
+
invidious:directory:playlists configured playlists
|
|
5
|
+
invidious:directory:channels configured channels
|
|
6
|
+
invidious:video:<videoId> a single video -> Track
|
|
7
|
+
invidious:playlist:<playlistId> a playlist -> Album
|
|
8
|
+
invidious:channel:<channelId> a channel -> Artist
|
|
9
|
+
invidious:search:<query> search result
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import re
|
|
15
|
+
import urllib.parse
|
|
16
|
+
from typing import NamedTuple
|
|
17
|
+
|
|
18
|
+
from mopidy.types import Uri
|
|
19
|
+
|
|
20
|
+
SCHEME = "invidious"
|
|
21
|
+
|
|
22
|
+
ROOT = Uri(f"{SCHEME}:root")
|
|
23
|
+
PLAYLISTS_DIR = Uri(f"{SCHEME}:directory:playlists")
|
|
24
|
+
CHANNELS_DIR = Uri(f"{SCHEME}:directory:channels")
|
|
25
|
+
|
|
26
|
+
VIDEO = "video"
|
|
27
|
+
PLAYLIST = "playlist"
|
|
28
|
+
CHANNEL = "channel"
|
|
29
|
+
DIRECTORY = "directory"
|
|
30
|
+
SEARCH = "search"
|
|
31
|
+
|
|
32
|
+
_ID_PATTERNS = {
|
|
33
|
+
VIDEO: re.compile(r"^[A-Za-z0-9_-]{11}$"),
|
|
34
|
+
PLAYLIST: re.compile(r"^[A-Za-z0-9_-]{10,64}$"),
|
|
35
|
+
CHANNEL: re.compile(r"^UC[A-Za-z0-9_-]{22}$"),
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ParsedUri(NamedTuple):
|
|
40
|
+
kind: str
|
|
41
|
+
id: str
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def video(video_id: str) -> Uri:
|
|
45
|
+
return Uri(f"{SCHEME}:{VIDEO}:{video_id}")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def playlist(playlist_id: str) -> Uri:
|
|
49
|
+
return Uri(f"{SCHEME}:{PLAYLIST}:{playlist_id}")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def channel(channel_id: str) -> Uri:
|
|
53
|
+
return Uri(f"{SCHEME}:{CHANNEL}:{channel_id}")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def search(query: str) -> Uri:
|
|
57
|
+
return Uri(f"{SCHEME}:{SEARCH}:{urllib.parse.quote(query)}")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def parse(uri: str) -> ParsedUri:
|
|
61
|
+
"""Split an ``invidious:`` URI into its kind and ID.
|
|
62
|
+
|
|
63
|
+
Raises ``ValueError`` for anything that is not a well-formed URI.
|
|
64
|
+
"""
|
|
65
|
+
scheme, _, rest = uri.partition(":")
|
|
66
|
+
kind, _, ident = rest.partition(":")
|
|
67
|
+
if scheme != SCHEME or not kind:
|
|
68
|
+
msg = f"Not an {SCHEME} URI: {uri!r}"
|
|
69
|
+
raise ValueError(msg)
|
|
70
|
+
if kind == "root" and not ident:
|
|
71
|
+
return ParsedUri(kind, "")
|
|
72
|
+
pattern = _ID_PATTERNS.get(kind)
|
|
73
|
+
if pattern is not None and not pattern.match(ident):
|
|
74
|
+
msg = f"Invalid {kind} ID in URI: {uri!r}"
|
|
75
|
+
raise ValueError(msg)
|
|
76
|
+
if kind not in (*_ID_PATTERNS, DIRECTORY, SEARCH):
|
|
77
|
+
msg = f"Unknown {SCHEME} URI kind: {uri!r}"
|
|
78
|
+
raise ValueError(msg)
|
|
79
|
+
return ParsedUri(kind, ident)
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mopidy-invidious
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Mopidy extension for playing music from a self-hosted Invidious instance
|
|
5
|
+
Author-email: Lukas Heinz <94646007+lukasheinz92@users.noreply.github.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/lukasheinz92/mopidy-invidious
|
|
8
|
+
Project-URL: Repository, https://github.com/lukasheinz92/mopidy-invidious
|
|
9
|
+
Project-URL: Issues, https://github.com/lukasheinz92/mopidy-invidious/issues
|
|
10
|
+
Classifier: Environment :: No Input/Output (Daemon)
|
|
11
|
+
Classifier: Intended Audience :: End Users/Desktop
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Topic :: Multimedia :: Sound/Audio :: Players
|
|
14
|
+
Requires-Python: >=3.13
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: mopidy>=4.0.0
|
|
18
|
+
Requires-Dist: pykka>=4.1
|
|
19
|
+
Requires-Dist: httpx>=0.28
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
22
|
+
Requires-Dist: ruff>=0.6; extra == "dev"
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# Mopidy-Invidious
|
|
26
|
+
|
|
27
|
+
A [Mopidy](https://mopidy.com/) 4 extension for searching, browsing and playing
|
|
28
|
+
music from a self-hosted [Invidious](https://invidious.io/) instance.
|
|
29
|
+
|
|
30
|
+
Its content shows up in any Mopidy client under Browse → Invidious and in search results.
|
|
31
|
+
|
|
32
|
+
> **Note:** This is a personal hobby project, built for a self-hosted home setup
|
|
33
|
+
> and intended for private, non-commercial use. It is provided as is, without
|
|
34
|
+
> warranty or support. It does not download or redistribute any content; it only
|
|
35
|
+
> talks to an Invidious instance you run yourself. You are responsible for
|
|
36
|
+
> complying with the terms of service of the services you use and with the laws
|
|
37
|
+
> of your country. This project is not affiliated with YouTube, Google or Invidious.
|
|
38
|
+
|
|
39
|
+
## Features
|
|
40
|
+
|
|
41
|
+
- **Search**: videos (as tracks), playlists (as albums) and channels (as artists)
|
|
42
|
+
- **Browse**: a curated list of playlists and channels (`playlists`, `channels`)
|
|
43
|
+
- **Playback**: audio is streamed through Invidious (`local=true`), so Mopidy never
|
|
44
|
+
talks to YouTube directly, and stream URLs never expire
|
|
45
|
+
- **Lightweight**: no dependencies beyond Mopidy 4 itself
|
|
46
|
+
|
|
47
|
+
## Requirements
|
|
48
|
+
|
|
49
|
+
- Mopidy >= 4.0, Python >= 3.13
|
|
50
|
+
- An Invidious instance reachable from Mopidy (with invidious-companion)
|
|
51
|
+
- GStreamer plugins for Opus/WebM and AAC/MP4 (`gstreamer1.0-plugins-good`,
|
|
52
|
+
`-bad`)
|
|
53
|
+
|
|
54
|
+
## Installation
|
|
55
|
+
|
|
56
|
+
```sh
|
|
57
|
+
pip install mopidy-invidious
|
|
58
|
+
# or the latest development version from GitHub
|
|
59
|
+
pip install git+https://github.com/lukasheinz92/mopidy-invidious
|
|
60
|
+
# or from a local checkout
|
|
61
|
+
pip install /path/to/mopidy-invidious
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Configuration
|
|
65
|
+
|
|
66
|
+
```ini
|
|
67
|
+
[invidious]
|
|
68
|
+
enabled = true
|
|
69
|
+
# Invidious as seen from Mopidy (API + audio)
|
|
70
|
+
base_url = http://invidious-app:3000
|
|
71
|
+
# Invidious as seen from Mopidy clients (cover art); defaults to base_url
|
|
72
|
+
public_url = https://invidious.example.org
|
|
73
|
+
timeout = 15
|
|
74
|
+
# Max songs (videos) per search; `search_results` is a deprecated alias
|
|
75
|
+
search_track_results = 20
|
|
76
|
+
# Max playlists (as albums) / channels (as artists) above the tracks; only
|
|
77
|
+
# official/album playlists and channels named like the query. 0 disables.
|
|
78
|
+
search_playlist_results = 5
|
|
79
|
+
search_channel_results = 3
|
|
80
|
+
# Preferred audio formats, first available wins:
|
|
81
|
+
# 251 = Opus ~160k, 140 = AAC 128k, 250 = Opus ~70k, 249 = Opus ~50k
|
|
82
|
+
audio_itags = 251, 140, 250, 249
|
|
83
|
+
# Split "Artist - Title" video titles into artist and track name
|
|
84
|
+
parse_titles = true
|
|
85
|
+
# Shown under Browse > Invidious
|
|
86
|
+
playlists = PLxxxxxxxxxxxxxxxx, PLyyyyyyyyyyyyyyyy
|
|
87
|
+
channels = UCxxxxxxxxxxxxxxxxxxxxxx
|
|
88
|
+
cache_ttl = 3600
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Architecture
|
|
92
|
+
|
|
93
|
+
See [ARCHITECTURE.md](ARCHITECTURE.md) for the design.
|
|
94
|
+
|
|
95
|
+
## Development
|
|
96
|
+
|
|
97
|
+
Unit tests and an end-to-end test run on the Docker host, inside the same
|
|
98
|
+
image as production Mopidy, without touching the running instance:
|
|
99
|
+
|
|
100
|
+
```sh
|
|
101
|
+
dev/remote.sh test # pytest in a throwaway mopidy:latest container
|
|
102
|
+
dev/remote.sh e2e # isolated Mopidy + extension: search, play, seek
|
|
103
|
+
dev/remote.sh logs
|
|
104
|
+
dev/remote.sh down
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Override `HOST`, `IMAGE` or `NETWORK` via environment variables.
|
|
108
|
+
|
|
109
|
+
## License
|
|
110
|
+
|
|
111
|
+
Apache-2.0
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
mopidy_invidious/__init__.py,sha256=kPdCsiSDfGxZOn9klyt_mC9mGitSBUBEA5zhh3GFCpg,1632
|
|
2
|
+
mopidy_invidious/backend.py,sha256=JNCZDftsdjBw5O70lzbLmJ5wQpYfzra0X26h4jiMaWE,2023
|
|
3
|
+
mopidy_invidious/client.py,sha256=JeDjiaEeN91yeL2igfchu3eRAacncXAlETQWpnQ0La0,5157
|
|
4
|
+
mopidy_invidious/ext.conf,sha256=iAI90KPP0s_E7hOwqG1JGw2AYNWIkjq6-kt6C8QWBuU,1065
|
|
5
|
+
mopidy_invidious/library.py,sha256=39PABBqgeMQ1q7x-PZyuhmwI5y_6Xs0vQANKM5bWAZ4,7971
|
|
6
|
+
mopidy_invidious/playback.py,sha256=2ePsfuuLAtxDvgUuKjAbJY7PKXPqCcbv2P0G3NfisC4,2257
|
|
7
|
+
mopidy_invidious/ranking.py,sha256=BZxcyXO5JhnNaWYdbhyT8ixXtaz_xBDmrFaHdHPwA7o,2904
|
|
8
|
+
mopidy_invidious/translator.py,sha256=FYmloF-FXCa-Fy7tMbVyZnt9LQvfE5yR9-1TRECL098,5275
|
|
9
|
+
mopidy_invidious/uris.py,sha256=t9O54d0YkJYK6hK8OxAI4fwNcNrfQ5-8SCXP0oVMsVc,2185
|
|
10
|
+
mopidy_invidious-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
11
|
+
mopidy_invidious-0.1.0.dist-info/METADATA,sha256=nZbj2DzCwXbfFmmXQ5HFkfhdffH72I_GWikAXG6x6YU,3992
|
|
12
|
+
mopidy_invidious-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
13
|
+
mopidy_invidious-0.1.0.dist-info/entry_points.txt,sha256=RF6Vvex62s6YItp9_2fwxtNNZpKZjX5shALKRhoxnIE,52
|
|
14
|
+
mopidy_invidious-0.1.0.dist-info/top_level.txt,sha256=nfySMDp18G35Br4l5yke083taLQiZUu_qJsCdFvdCxQ,17
|
|
15
|
+
mopidy_invidious-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
mopidy_invidious
|