mirror of
https://github.com/RustyRaptor/doge_cogs.git
synced 2026-12-03 15:55:21 -07:00
Fetch MusicBrainz-missing songs from YouTube or skip them
Playlist reviews mixed "artist absent from MusicBrainz" with genuine album ambiguity, so requesters had no path forward for artists the catalogue lacks. Report that reason separately, keep album matching (including the manual picker) to the Spotify artist so tribute/cover releases are never monitored, and add `importplaylist youtube` (yt-dlp search or a pasted link, downloaded into the Jellyfin music folder) plus `importplaylist ignore` for a permanent skip. Failed downloads and ignored songs stop counting as review. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
1 parent
1084a822e7
commit
85eab7bb16
11 files changed
+1378
-93
No files matched your search
@@ -352,17 +352,38 @@ song is actually available there. Title, credited artist and duration must
|
||||
match uniquely. Unresolved tracks produce a **finished with gaps** result,
|
||||
not an all-added message.
|
||||
|
||||
Songs that cannot be matched become **review** tracks with a reason: no unique
|
||||
artist/album match, unavailable public album metadata, an unavailable source
|
||||
track, or a catalogue lookup that failed three times. A single failing lookup
|
||||
no longer stalls every later song in the import. `importplaylist status` groups
|
||||
reviewed songs by reason, and `importplaylist retry [playlist name]` looks up
|
||||
reviewed or unresolved songs again without disturbing matched albums; if the
|
||||
catalogue or Lidarr has caught up since, the import finishes and pings normally.
|
||||
Songs that cannot be matched become **review** tracks with a reason: **artist
|
||||
not in MusicBrainz**, no unique artist/album match, unavailable public album
|
||||
metadata, an unavailable source track, or a catalogue lookup that failed three
|
||||
times. An artist absent from MusicBrainz is reported separately because no
|
||||
album lookup can ever succeed for it. Album choices are restricted to albums
|
||||
credited to the Spotify artist, so a tribute, cover or same-titled release by
|
||||
another artist is never monitored. A single failing lookup no longer stalls
|
||||
every later song in the import. `importplaylist status` groups reviewed songs by
|
||||
reason, and `importplaylist retry [playlist name]` looks up reviewed or
|
||||
unresolved songs again without disturbing matched albums; if the catalogue or
|
||||
Lidarr has caught up since, the import finishes and pings normally.
|
||||
`importplaylist match <song>` searches Lidarr by title and artist and lets the
|
||||
requester pick the album from a select menu; it monitors an existing album or
|
||||
adds the missing one, submits a targeted `AlbumSearch`, and the playlist fills
|
||||
when the album downloads. Both commands only see the caller's own imports.
|
||||
when the album downloads. All of these commands only see the caller's own
|
||||
imports.
|
||||
|
||||
For a song MusicBrainz does not have, `importplaylist youtube <song>` searches
|
||||
YouTube with `yt-dlp` and offers up to five videos, and
|
||||
`importplaylist youtube <song> <url>` uses a link the requester supplies. The
|
||||
audio is downloaded into the configured music folder, Jellyfin is asked to
|
||||
index it, and the exact new item joins the playlist once it appears. A download
|
||||
that fails is reported and **skipped for good**: it is not retried and no longer
|
||||
counts as review. `importplaylist ignore <song>` skips any reviewed song the
|
||||
same way, without downloading anything.
|
||||
|
||||
`yt-dlp` needs ffmpeg and a writable view of the music library. Set
|
||||
`PLAYLIST_YTDLP` (binary, default `yt-dlp`), `PLAYLIST_YOUTUBE_DIR` (the folder
|
||||
the bot writes, default `/music/YouTube Imports`) and
|
||||
`PLAYLIST_YOUTUBE_JELLYFIN_DIR` (the same folder as Jellyfin indexes it, default
|
||||
identical). Only YouTube links are accepted, output is confined to that folder,
|
||||
and downloads never run through a shell.
|
||||
|
||||
A write whose acknowledgement is uncertain stops for owner verification,
|
||||
avoiding blindly repeated creates/searches. Seven-day unresolved jobs report
|
||||
|
||||
@@ -5,6 +5,7 @@ import json
|
||||
from collections.abc import AsyncGenerator
|
||||
from contextlib import asynccontextmanager
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
import httpx
|
||||
@@ -26,6 +27,9 @@ class MusicEdge:
|
||||
creations: int = 0
|
||||
after_lookup: Any = None
|
||||
lookup_available: bool = True
|
||||
artist_missing: bool = False
|
||||
path_items: dict[str, str] = field(default_factory=dict)
|
||||
scans: list[str] = field(default_factory=list)
|
||||
|
||||
async def http(self, request: web.Request) -> web.Response:
|
||||
"""Use the actual API routes and JSON casing."""
|
||||
@@ -38,8 +42,29 @@ class MusicEdge:
|
||||
!= 'MediaBrowser Token="test-key"'
|
||||
):
|
||||
return web.Response(status=401)
|
||||
if request.path == "/Library/Media/Updated":
|
||||
body = await request.json()
|
||||
self.scans.extend(
|
||||
update["Path"]
|
||||
for update in body.get("Updates", [])
|
||||
)
|
||||
return web.Response(status=204)
|
||||
if request.path == "/Items":
|
||||
title = request.query.get("searchTerm", "")
|
||||
if request.query.get("fields") == "Path":
|
||||
items = [
|
||||
{"Id": item_id, "Path": path}
|
||||
for path, item_id in (
|
||||
self.path_items.items()
|
||||
)
|
||||
if Path(path).stem == title
|
||||
]
|
||||
return web.json_response(
|
||||
{
|
||||
"Items": items,
|
||||
"TotalRecordCount": len(items),
|
||||
}
|
||||
)
|
||||
items = (
|
||||
[
|
||||
{
|
||||
@@ -68,6 +93,17 @@ class MusicEdge:
|
||||
"""Persist albums and targeted searches."""
|
||||
path = request.path.removeprefix("/api/v1/")
|
||||
body = await request.json() if request.can_read_body else {}
|
||||
if path == "artist/lookup":
|
||||
if self.artist_missing:
|
||||
return web.json_response([])
|
||||
return web.json_response(
|
||||
[
|
||||
{
|
||||
"artistName": "Depeche Mode",
|
||||
"foreignArtistId": "mb-artist",
|
||||
}
|
||||
]
|
||||
)
|
||||
if path == "album/lookup":
|
||||
if self.after_lookup:
|
||||
await self.after_lookup()
|
||||
|
||||
@@ -245,6 +245,155 @@ async def test_repeated_lookup_failures_become_review_tracks(
|
||||
)
|
||||
|
||||
|
||||
async def test_an_artist_missing_from_musicbrainz_is_named(
|
||||
config: Config, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""Catch blaming album ambiguity for an artist the catalogue lacks."""
|
||||
from music_helpers import import_environment
|
||||
|
||||
class UnknownArtist(MusicEdge):
|
||||
async def arr(self, request: web.Request) -> web.Response:
|
||||
if request.path.endswith("/album/lookup"):
|
||||
return web.json_response([])
|
||||
return await super().arr(request)
|
||||
|
||||
edge = UnknownArtist(artist_missing=True)
|
||||
async with import_environment(config, monkeypatch, edge) as (
|
||||
engine,
|
||||
_saved,
|
||||
_allowed,
|
||||
):
|
||||
job = music_job()
|
||||
await engine.prepare(job)
|
||||
assert {t["review"] for t in job["tracks"]} == {
|
||||
"Artist not in MusicBrainz"
|
||||
}
|
||||
assert edge.albums == []
|
||||
|
||||
|
||||
async def test_a_known_artist_without_its_album_stays_generic(
|
||||
config: Config, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""Catch calling every missing album an unknown artist."""
|
||||
from music_helpers import import_environment
|
||||
|
||||
class NoAlbum(MusicEdge):
|
||||
async def arr(self, request: web.Request) -> web.Response:
|
||||
if request.path.endswith("/album/lookup"):
|
||||
return web.json_response([])
|
||||
return await super().arr(request)
|
||||
|
||||
edge = NoAlbum()
|
||||
async with import_environment(config, monkeypatch, edge) as (
|
||||
engine,
|
||||
_saved,
|
||||
_allowed,
|
||||
):
|
||||
job = music_job()
|
||||
await engine.prepare(job)
|
||||
assert {t["review"] for t in job["tracks"]} == {
|
||||
"No unique artist/album match"
|
||||
}
|
||||
|
||||
|
||||
async def test_another_artists_album_is_never_monitored(
|
||||
config: Config, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""Catch adopting a same-titled tribute album for the artist."""
|
||||
from music_helpers import import_environment
|
||||
|
||||
class Tribute(MusicEdge):
|
||||
async def arr(self, request: web.Request) -> web.Response:
|
||||
if request.path.endswith("/album/lookup"):
|
||||
return web.json_response(
|
||||
[
|
||||
{
|
||||
"title": "Violator",
|
||||
"foreignAlbumId": (
|
||||
"tribute"
|
||||
),
|
||||
"artist": {
|
||||
"artistName": "Tribute", # noqa: E501
|
||||
"foreignArtistId": "other", # noqa: E501
|
||||
},
|
||||
"releases": [],
|
||||
"images": [],
|
||||
}
|
||||
]
|
||||
)
|
||||
return await super().arr(request)
|
||||
|
||||
edge = Tribute()
|
||||
async with import_environment(config, monkeypatch, edge) as (
|
||||
engine,
|
||||
_saved,
|
||||
_allowed,
|
||||
):
|
||||
job = music_job()
|
||||
await engine.prepare(job)
|
||||
assert {t["review"] for t in job["tracks"]} == {
|
||||
"No unique artist/album match"
|
||||
}
|
||||
assert edge.albums == []
|
||||
assert edge.searches == []
|
||||
|
||||
|
||||
async def test_a_skipped_song_settles_the_import(
|
||||
config: Config, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""Catch skipped songs counting as review forever."""
|
||||
from music_helpers import import_environment
|
||||
|
||||
edge = MusicEdge()
|
||||
async with import_environment(config, monkeypatch, edge) as (
|
||||
engine,
|
||||
_saved,
|
||||
_allowed,
|
||||
):
|
||||
job = music_job()
|
||||
job["tracks"] = job["tracks"][:1]
|
||||
row = job["tracks"][0]
|
||||
row.update(resolved=True, review="Artist not in MusicBrainz")
|
||||
await engine.skip(job, row)
|
||||
assert row["skipped"] is True
|
||||
assert "review" not in row
|
||||
await engine.refresh(job)
|
||||
assert job["stage"] == "attention"
|
||||
assert job["ready"] == 0
|
||||
|
||||
|
||||
async def test_a_youtube_file_is_attached_by_its_jellyfin_item(
|
||||
config: Config, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""Catch searching by Spotify duration for a longer video file."""
|
||||
from music_helpers import import_environment
|
||||
|
||||
path = "/mnt/MediaDisk/Music/YouTube Imports/Depeche Mode/Halo.opus"
|
||||
edge = MusicEdge(path_items={path: "yt-1"})
|
||||
async with import_environment(config, monkeypatch, edge) as (
|
||||
engine,
|
||||
saved,
|
||||
_allowed,
|
||||
):
|
||||
job = music_job()
|
||||
job["tracks"] = job["tracks"][:1]
|
||||
row = job["tracks"][0]
|
||||
row.update(
|
||||
resolved=False,
|
||||
youtube_path=path,
|
||||
review="Artist not in MusicBrainz",
|
||||
)
|
||||
await engine.prepare(job)
|
||||
assert row["item_id"] == "yt-1"
|
||||
assert row["resolved"] is True
|
||||
assert "review" not in row
|
||||
assert saved["tracks"][0]["item_id"] == "yt-1"
|
||||
await engine.refresh(job)
|
||||
assert job["ready"] == 1
|
||||
assert job["stage"] == "complete"
|
||||
assert edge.playlist["Ids"] == ["yt-1"]
|
||||
|
||||
|
||||
async def test_a_ready_track_loses_its_review_label(
|
||||
config: Config, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
|
||||
@@ -42,6 +42,52 @@ def test_only_one_canonical_album_for_the_credited_artist_is_selected() -> None:
|
||||
)
|
||||
|
||||
|
||||
def test_album_matches_never_come_from_another_artist() -> None:
|
||||
"""Catch adopting a tribute or cover album with the right title."""
|
||||
from watch.music import choose_album
|
||||
|
||||
candidates = [
|
||||
{
|
||||
"id": 4,
|
||||
"foreignAlbumId": "tribute",
|
||||
"title": "Violator",
|
||||
"artist": {"artistName": "Some Tribute Band"},
|
||||
}
|
||||
]
|
||||
assert (
|
||||
choose_album(
|
||||
{"title": "Violator", "artist": "Depeche Mode"},
|
||||
candidates,
|
||||
)
|
||||
is None
|
||||
)
|
||||
candidates.append(
|
||||
{
|
||||
"id": 7,
|
||||
"foreignAlbumId": "right",
|
||||
"title": "Violator",
|
||||
"artist": {"artistName": "Depeche Mode"},
|
||||
}
|
||||
)
|
||||
assert (
|
||||
choose_album(
|
||||
{"title": "Violator", "artist": "Depeche Mode"},
|
||||
candidates,
|
||||
)
|
||||
== candidates[1]
|
||||
)
|
||||
|
||||
|
||||
def test_a_featured_artist_still_counts_as_a_credited_artist() -> None:
|
||||
"""Catch dropping collaborations that Spotify credits by name."""
|
||||
from watch.music import appears_on
|
||||
|
||||
album = {"artist": {"artistName": "Depeche Mode"}}
|
||||
assert appears_on("Depeche Mode, Martin Gore", album)
|
||||
assert appears_on("Depeche Mode", album)
|
||||
assert not appears_on("Beyoncé", album)
|
||||
|
||||
|
||||
def test_audio_match_requires_unique_artist_title_and_length() -> None:
|
||||
"""Reject wrong artists, versions and ambiguity."""
|
||||
from watch.music import find_audio
|
||||
|
||||
@@ -694,6 +694,288 @@ async def test_match_cancelled_album_choice_changes_nothing(
|
||||
assert edge.searches == []
|
||||
|
||||
|
||||
async def test_status_offers_youtube_or_ignoring_a_missing_artist(
|
||||
playlist_command: CommandCase,
|
||||
) -> None:
|
||||
"""Catch naming a dead end without the two ways out of it."""
|
||||
cog, ctx, _edge, _channel, _bot = playlist_command
|
||||
cog.background()
|
||||
await cog.config.pending_jobs.set(
|
||||
{
|
||||
"1:playlist:mine": {
|
||||
"owner": 1,
|
||||
"kind": "playlist",
|
||||
"name": "Own mix",
|
||||
"stage": "attention",
|
||||
"ready": 0,
|
||||
"tracks": [
|
||||
{
|
||||
"title": "Halo",
|
||||
"artist": "Depeche Mode",
|
||||
"resolved": True,
|
||||
"review": (
|
||||
"Artist not in "
|
||||
"MusicBrainz"
|
||||
),
|
||||
}
|
||||
],
|
||||
}
|
||||
}
|
||||
)
|
||||
await Watch.playlist_status.callback(cog, ctx)
|
||||
text = ctx.texts[0]
|
||||
assert "Artist not in MusicBrainz (1)" in text
|
||||
assert "importplaylist youtube" in text
|
||||
assert "importplaylist ignore" in text
|
||||
assert text.endswith("to try reviewed songs again.")
|
||||
|
||||
|
||||
async def test_ignore_skips_the_song_and_retry_leaves_it_alone(
|
||||
playlist_command: CommandCase,
|
||||
) -> None:
|
||||
"""Catch a skipped song coming back on every retry."""
|
||||
cog, ctx, edge, _channel, _bot = playlist_command
|
||||
key = "1:playlist:7kRUsOsraSiY4fyDcu7Bnb"
|
||||
await cog.config.pending_jobs.set(
|
||||
{
|
||||
key: {
|
||||
"owner": 1,
|
||||
"kind": "playlist",
|
||||
"name": "My mix",
|
||||
"username": "doge",
|
||||
"user_id": "user-1",
|
||||
"stage": "attention",
|
||||
"ready": 0,
|
||||
"notified": True,
|
||||
"tracks": [
|
||||
{
|
||||
"title": "Halo",
|
||||
"artist": "Depeche Mode",
|
||||
"resolved": True,
|
||||
"review": (
|
||||
"Artist not in "
|
||||
"MusicBrainz"
|
||||
),
|
||||
}
|
||||
],
|
||||
}
|
||||
}
|
||||
)
|
||||
await Watch.playlist_ignore.callback(cog, ctx, song="Halo")
|
||||
await asyncio.gather(*cog._pollers)
|
||||
job = (await cog.config.pending_jobs())[key]
|
||||
assert job["tracks"][0]["skipped"] is True
|
||||
assert "review" not in job["tracks"][0]
|
||||
assert any("skip" in text.lower() for text in ctx.texts)
|
||||
edge.lookup_available = True
|
||||
await Watch.playlist_retry.callback(cog, ctx, target="My mix")
|
||||
await asyncio.gather(*cog._pollers)
|
||||
job = (await cog.config.pending_jobs())[key]
|
||||
assert job["tracks"][0]["skipped"] is True
|
||||
assert edge.albums == []
|
||||
assert any("no songs" in text.lower() for text in ctx.texts)
|
||||
|
||||
|
||||
async def test_youtube_download_joins_the_playlist(
|
||||
playlist_command: CommandCase, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""Catch a fetched song that never reaches the playlist."""
|
||||
import watch.jobs as job_module
|
||||
|
||||
cog, ctx, edge, channel, _bot = playlist_command
|
||||
key = "1:playlist:7kRUsOsraSiY4fyDcu7Bnb"
|
||||
jellyfin_path = (
|
||||
"/mnt/MediaDisk/Music/YouTube Imports/Depeche Mode/Halo.opus"
|
||||
)
|
||||
edge.path_items = {jellyfin_path: "yt-1"}
|
||||
await cog.config.pending_jobs.set(
|
||||
{
|
||||
key: {
|
||||
"owner": 1,
|
||||
"username": "doge",
|
||||
"channel": 10,
|
||||
"user_id": "user-1",
|
||||
"kind": "playlist",
|
||||
"name": "My mix",
|
||||
"stage": "attention",
|
||||
"ready": 0,
|
||||
"notified": True,
|
||||
"partial": False,
|
||||
"tracks": [
|
||||
{
|
||||
"id": "6kwEU2hLQpMToj1PHsBrOE",
|
||||
"title": "Halo",
|
||||
"artist": "Depeche Mode",
|
||||
"duration": 270186,
|
||||
"resolved": True,
|
||||
"review": (
|
||||
"Artist not in "
|
||||
"MusicBrainz"
|
||||
),
|
||||
}
|
||||
],
|
||||
}
|
||||
}
|
||||
)
|
||||
monkeypatch.setenv("PLAYLIST_YOUTUBE_DIR", "/yt")
|
||||
monkeypatch.setenv(
|
||||
"PLAYLIST_YOUTUBE_JELLYFIN_DIR",
|
||||
"/mnt/MediaDisk/Music/YouTube Imports",
|
||||
)
|
||||
|
||||
class FakeYoutube:
|
||||
def __init__(self, *_args: object, **_kwargs: object) -> None:
|
||||
pass
|
||||
|
||||
async def ready(self) -> str | None:
|
||||
return None
|
||||
|
||||
async def download(
|
||||
self, _url: str, _artist: str, _title: str
|
||||
) -> object:
|
||||
from pathlib import Path
|
||||
|
||||
return Path("/yt/Depeche Mode/Halo.opus")
|
||||
|
||||
monkeypatch.setattr(job_module, "Youtube", FakeYoutube)
|
||||
await Watch.playlist_youtube.callback(
|
||||
cog,
|
||||
ctx,
|
||||
song="Halo https://youtu.be/dQw4w9WgXcQ",
|
||||
)
|
||||
results = await asyncio.gather(*cog._pollers, return_exceptions=True)
|
||||
assert all(result is None for result in results)
|
||||
job = (await cog.config.pending_jobs())[key]
|
||||
assert job["tracks"][0]["item_id"] == "yt-1"
|
||||
assert "review" not in job["tracks"][0]
|
||||
assert job["stage"] == "complete"
|
||||
assert edge.scans == [jellyfin_path]
|
||||
assert edge.playlist["Ids"] == ["yt-1"]
|
||||
assert any("Halo" in text for text, _ in channel.sent)
|
||||
|
||||
|
||||
async def test_youtube_leaves_review_alone_when_not_deployed(
|
||||
playlist_command: CommandCase, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""Catch skipping a song forever because yt-dlp is missing."""
|
||||
import watch.jobs as job_module
|
||||
|
||||
cog, ctx, _edge, _channel, _bot = playlist_command
|
||||
key = "1:playlist:7kRUsOsraSiY4fyDcu7Bnb"
|
||||
await cog.config.pending_jobs.set(
|
||||
{
|
||||
key: {
|
||||
"owner": 1,
|
||||
"username": "doge",
|
||||
"user_id": "user-1",
|
||||
"kind": "playlist",
|
||||
"name": "My mix",
|
||||
"stage": "attention",
|
||||
"ready": 0,
|
||||
"notified": True,
|
||||
"tracks": [
|
||||
{
|
||||
"title": "Halo",
|
||||
"artist": "Depeche Mode",
|
||||
"resolved": True,
|
||||
"review": (
|
||||
"Artist not in "
|
||||
"MusicBrainz"
|
||||
),
|
||||
}
|
||||
],
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
class MissingYoutube:
|
||||
def __init__(self, *_args: object, **_kwargs: object) -> None:
|
||||
pass
|
||||
|
||||
async def ready(self) -> str | None:
|
||||
return "yt-dlp is not installed"
|
||||
|
||||
monkeypatch.setattr(job_module, "Youtube", MissingYoutube)
|
||||
await Watch.playlist_youtube.callback(
|
||||
cog,
|
||||
ctx,
|
||||
song="Halo https://youtu.be/dQw4w9WgXcQ",
|
||||
)
|
||||
job = (await cog.config.pending_jobs())[key]
|
||||
row = job["tracks"][0]
|
||||
assert row["review"] == "Artist not in MusicBrainz"
|
||||
assert "skipped" not in row
|
||||
assert cog._pollers == set()
|
||||
assert any("not available" in text for text in ctx.texts)
|
||||
|
||||
|
||||
async def test_a_failed_youtube_download_is_skipped_for_good(
|
||||
playlist_command: CommandCase, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""Catch retrying a video the downloader cannot fetch."""
|
||||
import watch.jobs as job_module
|
||||
from watch.youtube import YoutubeError
|
||||
|
||||
cog, ctx, edge, channel, _bot = playlist_command
|
||||
key = "1:playlist:7kRUsOsraSiY4fyDcu7Bnb"
|
||||
await cog.config.pending_jobs.set(
|
||||
{
|
||||
key: {
|
||||
"owner": 1,
|
||||
"username": "doge",
|
||||
"channel": 10,
|
||||
"user_id": "user-1",
|
||||
"kind": "playlist",
|
||||
"name": "My mix",
|
||||
"stage": "attention",
|
||||
"ready": 0,
|
||||
"notified": True,
|
||||
"tracks": [
|
||||
{
|
||||
"title": "Halo",
|
||||
"artist": "Depeche Mode",
|
||||
"resolved": True,
|
||||
"review": (
|
||||
"Artist not in "
|
||||
"MusicBrainz"
|
||||
),
|
||||
}
|
||||
],
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
class BrokenYoutube:
|
||||
def __init__(self, *_args: object, **_kwargs: object) -> None:
|
||||
pass
|
||||
|
||||
async def ready(self) -> str | None:
|
||||
return None
|
||||
|
||||
async def download(
|
||||
self, _url: str, _artist: str, _title: str
|
||||
) -> object:
|
||||
message = "ERROR: Video unavailable"
|
||||
raise YoutubeError(message)
|
||||
|
||||
monkeypatch.setattr(job_module, "Youtube", BrokenYoutube)
|
||||
await Watch.playlist_youtube.callback(
|
||||
cog,
|
||||
ctx,
|
||||
song="Halo https://youtu.be/dQw4w9WgXcQ",
|
||||
)
|
||||
await asyncio.gather(*cog._pollers)
|
||||
job = (await cog.config.pending_jobs())[key]
|
||||
assert job["tracks"][0]["skipped"] is True
|
||||
assert job["tracks"][0]["review"] == "YouTube download failed"
|
||||
assert edge.playlist == {}
|
||||
assert len(channel.sent) == 1
|
||||
await Watch.playlist_retry.callback(cog, ctx, target="My mix")
|
||||
await asyncio.gather(*cog._pollers)
|
||||
job = (await cog.config.pending_jobs())[key]
|
||||
assert job["tracks"][0]["skipped"] is True
|
||||
|
||||
|
||||
async def test_retry_only_touches_the_callers_imports(
|
||||
playlist_command: CommandCase,
|
||||
) -> None:
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
"""Test the YouTube fallback that fetches music the catalogue does not have."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from watch.youtube import Youtube, YoutubeError, youtube_url
|
||||
|
||||
|
||||
def test_a_pasted_link_is_recognised_and_separated_from_the_song() -> None:
|
||||
"""Catch accepting links for other sites or losing the song name."""
|
||||
assert (
|
||||
youtube_url("Halo https://youtu.be/dQw4w9WgXcQ")
|
||||
== "https://youtu.be/dQw4w9WgXcQ"
|
||||
)
|
||||
assert (
|
||||
youtube_url("Halo https://www.youtube.com/watch?v=dQw4w9WgXcQ.")
|
||||
== "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
|
||||
)
|
||||
assert youtube_url("Halo https://example.com/watch") is None
|
||||
assert youtube_url("Just Halo") is None
|
||||
|
||||
|
||||
async def test_ready_reports_a_missing_folder(tmp_path: Path) -> None:
|
||||
"""Catch committing a song to a fallback that is not deployed."""
|
||||
youtube = Youtube(binary="yt-dlp", folder=tmp_path / "missing")
|
||||
assert await youtube.ready() == (
|
||||
"the YouTube music folder is not mounted"
|
||||
)
|
||||
assert (
|
||||
await Youtube(
|
||||
binary="definitely-not-yt-dlp", folder=tmp_path
|
||||
).ready()
|
||||
== "yt-dlp is not installed"
|
||||
)
|
||||
|
||||
|
||||
async def test_search_reads_youtube_results_without_downloading(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Catch a picker built from unchecked or missing yt-dlp output."""
|
||||
calls: list[list[str]] = []
|
||||
|
||||
async def runner(
|
||||
args: list[str], _timeout: float
|
||||
) -> tuple[int, str, str]:
|
||||
calls.append(args)
|
||||
return (
|
||||
0,
|
||||
json.dumps(
|
||||
{
|
||||
"entries": [
|
||||
{
|
||||
"id": "abc123",
|
||||
"title": (
|
||||
"Depeche Mode"
|
||||
" - Halo"
|
||||
),
|
||||
"uploader": (
|
||||
"Depeche Mode"
|
||||
),
|
||||
"duration": 271,
|
||||
}
|
||||
]
|
||||
}
|
||||
),
|
||||
"",
|
||||
)
|
||||
|
||||
youtube = Youtube(binary="yt-dlp", folder=tmp_path, runner=runner)
|
||||
results = await youtube.search("Halo Depeche Mode")
|
||||
assert calls[0][-1].startswith("ytsearch")
|
||||
assert results == [
|
||||
{
|
||||
"url": "https://www.youtube.com/watch?v=abc123",
|
||||
"title": "Depeche Mode - Halo",
|
||||
"uploader": "Depeche Mode",
|
||||
"duration": 271,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
async def test_download_writes_inside_the_music_folder(tmp_path: Path) -> None:
|
||||
"""Catch accepting a path outside the library or another site."""
|
||||
seen: list[list[str]] = []
|
||||
target = tmp_path / "Depeche Mode" / "Halo.opus"
|
||||
|
||||
async def runner(
|
||||
args: list[str], _timeout: float
|
||||
) -> tuple[int, str, str]:
|
||||
seen.append(args)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(b"audio")
|
||||
return 0, str(target) + "\n", ""
|
||||
|
||||
youtube = Youtube(binary="yt-dlp", folder=tmp_path, runner=runner)
|
||||
path = await youtube.download(
|
||||
"https://www.youtube.com/watch?v=abc123",
|
||||
"Depeche Mode",
|
||||
"Halo",
|
||||
)
|
||||
assert path == target
|
||||
assert "--no-playlist" in seen[0]
|
||||
assert str(tmp_path) in str(path)
|
||||
|
||||
|
||||
async def test_download_refuses_links_from_other_sites(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Catch yt-dlp being pointed at an arbitrary URL by a user."""
|
||||
youtube = Youtube(binary="yt-dlp", folder=tmp_path)
|
||||
with pytest.raises(YoutubeError, match="YouTube"):
|
||||
await youtube.download("https://example.com/x", "A", "B")
|
||||
|
||||
|
||||
async def test_download_failure_and_escaping_output_are_reported(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Catch treating a broken download or a foreign path as success."""
|
||||
|
||||
async def broken(
|
||||
_args: list[str], _timeout: float
|
||||
) -> tuple[int, str, str]:
|
||||
return 1, "", "ERROR: Video unavailable"
|
||||
|
||||
youtube = Youtube(binary="yt-dlp", folder=tmp_path, runner=broken)
|
||||
with pytest.raises(YoutubeError, match="unavailable"):
|
||||
await youtube.download("https://youtu.be/dQw4w9WgXcQ", "A", "B")
|
||||
|
||||
async def escaping(
|
||||
_args: list[str], _timeout: float
|
||||
) -> tuple[int, str, str]:
|
||||
outside = tmp_path.parent / "escape.opus"
|
||||
outside.write_bytes(b"audio")
|
||||
return 0, str(outside), ""
|
||||
|
||||
youtube = Youtube(binary="yt-dlp", folder=tmp_path, runner=escaping)
|
||||
with pytest.raises(YoutubeError, match="outside"):
|
||||
await youtube.download("https://youtu.be/dQw4w9WgXcQ", "A", "B")
|
||||
@@ -113,6 +113,46 @@ class Jellyfin:
|
||||
body={"Ids": ids},
|
||||
)
|
||||
|
||||
async def scan(self, paths: list[str]) -> None:
|
||||
"""Ask Jellyfin to index newly written files."""
|
||||
await self.call(
|
||||
"Library/Media/Updated",
|
||||
method="POST",
|
||||
body={
|
||||
"Updates": [
|
||||
{
|
||||
"Path": path,
|
||||
"UpdateType": "Created",
|
||||
}
|
||||
for path in paths
|
||||
]
|
||||
},
|
||||
)
|
||||
|
||||
async def audio_at(self, path: str, user_id: str) -> str | None:
|
||||
"""Resolve the indexed item for one exact downloaded file."""
|
||||
filename = path.replace("\\", "/").rsplit("/", 1)[-1]
|
||||
stem = filename.rsplit(".", 1)[0]
|
||||
result = await self.call(
|
||||
"Items",
|
||||
params={
|
||||
"userId": user_id,
|
||||
"includeItemTypes": "Audio",
|
||||
"recursive": "true",
|
||||
"searchTerm": stem,
|
||||
"fields": "Path",
|
||||
"limit": "100",
|
||||
},
|
||||
)
|
||||
matches = [
|
||||
item
|
||||
for item in result.get("Items", [])
|
||||
if str(item.get("Path", ""))
|
||||
.replace("\\", "/")
|
||||
.endswith("/" + filename)
|
||||
]
|
||||
return str(matches[0]["Id"]) if len(matches) == 1 else None
|
||||
|
||||
async def audio(
|
||||
self, track: dict[str, Any], user_id: str
|
||||
) -> str | None:
|
||||
|
||||
+109
-1
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import UTC, datetime
|
||||
from functools import partial
|
||||
@@ -18,6 +19,7 @@ from .music import MusicImporter
|
||||
from .notify import completion_ping
|
||||
from .spec import is_finished
|
||||
from .spotify import SpotifyPublic
|
||||
from .youtube import Youtube, YoutubeError
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import AsyncGenerator, Awaitable, Callable
|
||||
@@ -217,6 +219,112 @@ class Jobs:
|
||||
await engine.prepare(job)
|
||||
await engine.refresh(job)
|
||||
|
||||
def youtube(self) -> Youtube:
|
||||
"""Build the yt-dlp downloader from the deployment settings."""
|
||||
return Youtube(
|
||||
binary=os.environ.get("PLAYLIST_YTDLP", "yt-dlp"),
|
||||
folder=os.environ.get(
|
||||
"PLAYLIST_YOUTUBE_DIR",
|
||||
"/music/YouTube Imports",
|
||||
),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def jellyfin_path(path: str) -> str:
|
||||
"""Translate the bot path into the path Jellyfin indexes."""
|
||||
source = os.environ.get(
|
||||
"PLAYLIST_YOUTUBE_DIR", "/music/YouTube Imports"
|
||||
).rstrip("/")
|
||||
target = os.environ.get(
|
||||
"PLAYLIST_YOUTUBE_JELLYFIN_DIR", source
|
||||
).rstrip("/")
|
||||
text = str(path)
|
||||
if source and text.startswith(source):
|
||||
return target + text[len(source) :]
|
||||
return text
|
||||
|
||||
async def fetch_youtube(self, key: str, index: int, url: str) -> None:
|
||||
"""Download one reviewed song from YouTube and attach it."""
|
||||
job = (await self.config.pending_jobs()).get(key)
|
||||
if not job or not 0 <= index < len(job.get("tracks", [])):
|
||||
return
|
||||
row = job["tracks"][index]
|
||||
title = discord.utils.escape_markdown(
|
||||
str(row.get("title", "song"))
|
||||
)
|
||||
try:
|
||||
async with self._importer(key, job) as engine:
|
||||
path = await self.youtube().download(
|
||||
url,
|
||||
str(row.get("artist", "Unknown")),
|
||||
str(row.get("title", "song")),
|
||||
)
|
||||
target = self.jellyfin_path(str(path))
|
||||
await engine.jellyfin.scan([target])
|
||||
row.update(
|
||||
youtube_path=target,
|
||||
youtube_url=url,
|
||||
resolved=False,
|
||||
)
|
||||
for field in ("review", "attempts", "skipped"):
|
||||
row.pop(field, None)
|
||||
job["stage"] = "waiting"
|
||||
job["notified"] = False
|
||||
job.pop("finished", None)
|
||||
job["created"] = datetime.now(UTC).timestamp()
|
||||
await self.save(key, job)
|
||||
await self.run_once(key)
|
||||
except PermissionError:
|
||||
job["stage"] = "cancelled"
|
||||
await self.save(key, job)
|
||||
return
|
||||
except YoutubeError as exc:
|
||||
row.update(
|
||||
resolved=True,
|
||||
skipped=True,
|
||||
review="YouTube download failed",
|
||||
)
|
||||
job["stage"] = "waiting"
|
||||
job["notified"] = False
|
||||
job.pop("finished", None)
|
||||
await self.save(key, job)
|
||||
await completion_ping(
|
||||
self.cog.bot,
|
||||
job.get("channel", 0),
|
||||
job["owner"],
|
||||
f"Couldn't fetch **{title}** from YouTube "
|
||||
f"({exc}). I skipped it for good.",
|
||||
)
|
||||
return
|
||||
await completion_ping(
|
||||
self.cog.bot,
|
||||
job.get("channel", 0),
|
||||
job["owner"],
|
||||
f"Fetched **{title}** from YouTube. It joins the "
|
||||
"playlist once Jellyfin indexes it.",
|
||||
)
|
||||
|
||||
async def skip(self, key: str, index: int) -> str:
|
||||
"""Leave one reviewed song out of an import permanently."""
|
||||
job = (await self.config.pending_jobs()).get(key)
|
||||
if not job:
|
||||
msg = "That playlist import no longer exists."
|
||||
raise PreloadError(msg)
|
||||
if job.get("mutation"):
|
||||
msg = "An earlier write needs owner verification."
|
||||
raise PreloadError(msg)
|
||||
if not 0 <= index < len(job.get("tracks", [])):
|
||||
msg = "That reviewed song is no longer in the import."
|
||||
raise PreloadError(msg)
|
||||
row = job["tracks"][index]
|
||||
async with self._importer(key, job) as engine:
|
||||
await engine.skip(job, row)
|
||||
job["notified"] = False
|
||||
job.pop("finished", None)
|
||||
job["created"] = datetime.now(UTC).timestamp()
|
||||
await self.save(key, job)
|
||||
return str(row.get("title", "song"))
|
||||
|
||||
async def assign_album(
|
||||
self, key: str, index: int, match: dict[str, Any]
|
||||
) -> str:
|
||||
@@ -377,7 +485,7 @@ class Jobs:
|
||||
return
|
||||
if await completion_ping(
|
||||
self.cog.bot,
|
||||
job["channel"],
|
||||
job.get("channel", 0),
|
||||
job["owner"],
|
||||
self.message(job),
|
||||
send=send,
|
||||
|
||||
+129
-45
@@ -18,6 +18,12 @@ log = logging.getLogger("red.doge_cogs.watch.music")
|
||||
# than retrying silently forever or wedging every later track.
|
||||
RETRY_ATTEMPTS = 3
|
||||
|
||||
# The requester can act on these differently: the first artist is absent from
|
||||
# MusicBrainz, so only a YouTube copy (or skipping) can help.
|
||||
MISSING_ARTIST = "Artist not in MusicBrainz"
|
||||
NO_ALBUM = "No unique artist/album match"
|
||||
CREDITS = re.compile(r"\s*(?:,|&|feat\.?|featuring)\s*", re.IGNORECASE)
|
||||
|
||||
|
||||
def normalized(value: str) -> str:
|
||||
"""Normalize punctuation and Unicode presentation."""
|
||||
@@ -46,15 +52,30 @@ def album_title(value: str) -> str:
|
||||
return normalized(value)
|
||||
|
||||
|
||||
def artist_credits(artist: str) -> set[str]:
|
||||
"""Split Spotify's credited-artist list into comparable names."""
|
||||
return {
|
||||
name
|
||||
for name in (normalized(part) for part in CREDITS.split(artist))
|
||||
if name
|
||||
}
|
||||
|
||||
|
||||
def appears_on(artist: str, album: dict[str, Any]) -> bool:
|
||||
"""Require the album to be credited to the Spotify artist."""
|
||||
return normalized(
|
||||
album.get("artist", {}).get("artistName", "")
|
||||
) in artist_credits(artist)
|
||||
|
||||
|
||||
def choose_album(
|
||||
source: dict[str, str], candidates: list[dict[str, Any]]
|
||||
) -> dict[str, Any] | None:
|
||||
"""Require one canonical release group with matching artist/title."""
|
||||
"""Require one canonical release group by the credited artist."""
|
||||
matches = [
|
||||
a
|
||||
for a in candidates
|
||||
if normalized(a.get("artist", {}).get("artistName", ""))
|
||||
== normalized(source["artist"].split(",")[0])
|
||||
if appears_on(source["artist"], a)
|
||||
and album_title(a["title"]) == album_title(source["title"])
|
||||
]
|
||||
ids = {a["foreignAlbumId"] for a in matches}
|
||||
@@ -135,17 +156,35 @@ class MusicImporter:
|
||||
await self.save(job)
|
||||
return result
|
||||
|
||||
async def _artist_known(self, job: dict[str, Any], artist: str) -> bool:
|
||||
"""Check MusicBrainz once per artist and remember the answer."""
|
||||
name = artist.split(",")[0].strip()
|
||||
cache = job.setdefault("artist_checks", {})
|
||||
key = normalized(name)
|
||||
if key not in cache:
|
||||
found = await self.arr(
|
||||
"artist/lookup", params={"term": name}
|
||||
)
|
||||
cache[key] = any(
|
||||
normalized(a.get("artistName", "")) == key
|
||||
for a in found or []
|
||||
)
|
||||
await self.save(job)
|
||||
return bool(cache[key])
|
||||
|
||||
async def _album(
|
||||
self, job: dict[str, Any], source: dict[str, str]
|
||||
) -> int | None:
|
||||
"""Monitor one album without changing other choices."""
|
||||
) -> tuple[int | None, str]:
|
||||
"""Monitor one album, or name why no album was chosen."""
|
||||
candidates = await self.arr(
|
||||
"album/lookup", params={"term": source["title"]}
|
||||
)
|
||||
match = choose_album(source, candidates)
|
||||
if match is None:
|
||||
return None
|
||||
return await self._ensure_album(job, match)
|
||||
if match is not None:
|
||||
return await self._ensure_album(job, match), ""
|
||||
if not await self._artist_known(job, source["artist"]):
|
||||
return None, MISSING_ARTIST
|
||||
return None, NO_ALBUM
|
||||
|
||||
async def _ensure_album(
|
||||
self, job: dict[str, Any], match: dict[str, Any]
|
||||
@@ -293,6 +332,20 @@ class MusicImporter:
|
||||
"""Resolve one source row without losing saved progress."""
|
||||
albums = job.setdefault("albums", {})
|
||||
metadata = job.setdefault("track_albums", {})
|
||||
if row.get("youtube_path"):
|
||||
item = await self.jellyfin.audio_at(
|
||||
str(row["youtube_path"]), job["user_id"]
|
||||
)
|
||||
if item:
|
||||
row.update(
|
||||
resolved=True,
|
||||
item_id=item,
|
||||
youtube_item=item,
|
||||
)
|
||||
row.pop("review", None)
|
||||
row.pop("attempts", None)
|
||||
await self.save(job)
|
||||
return
|
||||
found = await self.jellyfin.audio(row, job["user_id"])
|
||||
if found:
|
||||
row.update(resolved=True, item_id=found)
|
||||
@@ -315,12 +368,17 @@ class MusicImporter:
|
||||
)
|
||||
metadata[row["id"]] = details
|
||||
sid = details["id"]
|
||||
if sid not in albums:
|
||||
albums[sid] = await self._album(job, details)
|
||||
if albums[sid] is None:
|
||||
row["review"] = "No unique artist/album match"
|
||||
if sid not in albums or albums[sid] is None:
|
||||
album_id, reason = await self._album(
|
||||
job, details
|
||||
)
|
||||
albums[sid] = album_id
|
||||
else:
|
||||
row["album_id"] = albums[sid]
|
||||
album_id, reason = albums[sid], ""
|
||||
if album_id is None:
|
||||
row["review"] = reason or NO_ALBUM
|
||||
else:
|
||||
row["album_id"] = album_id
|
||||
row.pop("review", None)
|
||||
row.pop("attempts", None)
|
||||
except ValueError:
|
||||
@@ -328,6 +386,22 @@ class MusicImporter:
|
||||
row["resolved"] = True
|
||||
await self.save(job)
|
||||
|
||||
async def skip(self, job: dict[str, Any], row: dict[str, Any]) -> None:
|
||||
"""Leave one song out permanently, at the requester's choice."""
|
||||
self._certain(job)
|
||||
row.update(resolved=True, skipped=True)
|
||||
for field in (
|
||||
"review",
|
||||
"attempts",
|
||||
"album_id",
|
||||
"item_id",
|
||||
"youtube_path",
|
||||
"youtube_item",
|
||||
):
|
||||
row.pop(field, None)
|
||||
job["stage"] = "waiting"
|
||||
await self.save(job)
|
||||
|
||||
async def prepare(self, job: dict[str, Any]) -> None:
|
||||
"""Resolve songs and search only their selected albums.
|
||||
|
||||
@@ -374,29 +448,13 @@ class MusicImporter:
|
||||
)
|
||||
await self.save(job)
|
||||
|
||||
async def refresh(self, job: dict[str, Any]) -> None:
|
||||
"""Publish songs and verify complete availability."""
|
||||
self._certain(job)
|
||||
ids = []
|
||||
review = 0
|
||||
cache = {}
|
||||
for row in job["tracks"]:
|
||||
key = (row.get("id"), row["title"], row["artist"])
|
||||
if key not in cache:
|
||||
cache[key] = await self.jellyfin.audio(
|
||||
row, job["user_id"]
|
||||
)
|
||||
found = cache[key]
|
||||
if found:
|
||||
ids.append(found)
|
||||
row.pop("review", None)
|
||||
row.pop("attempts", None)
|
||||
elif row.get("review"):
|
||||
review += 1
|
||||
job["ready"] = len(ids)
|
||||
if not job.get("playlist_id") and (
|
||||
ids or review < len(job["tracks"])
|
||||
):
|
||||
async def _publish(
|
||||
self, job: dict[str, Any], ids: list[str], review: int
|
||||
) -> None:
|
||||
"""Create the playlist or replace its contents in order."""
|
||||
if not job.get("playlist_id"):
|
||||
if not ids and review >= len(job["tracks"]):
|
||||
return
|
||||
name = f"{job['username']} - {job['name']}"[:250]
|
||||
job["playlist_id"] = await self._write(
|
||||
job,
|
||||
@@ -410,17 +468,43 @@ class MusicImporter:
|
||||
result_key="playlist_id",
|
||||
)
|
||||
job["playlist_items"] = ids
|
||||
elif job.get("playlist_id") and ids != job.get(
|
||||
"playlist_items"
|
||||
):
|
||||
await self.authorize()
|
||||
await self.jellyfin.update_playlist(
|
||||
job["playlist_id"], ids
|
||||
)
|
||||
job["playlist_items"] = ids
|
||||
return
|
||||
if ids == job.get("playlist_items"):
|
||||
return
|
||||
await self.authorize()
|
||||
await self.jellyfin.update_playlist(job["playlist_id"], ids)
|
||||
job["playlist_items"] = ids
|
||||
|
||||
async def refresh(self, job: dict[str, Any]) -> None:
|
||||
"""Publish songs and verify complete availability."""
|
||||
self._certain(job)
|
||||
ids = []
|
||||
review = 0
|
||||
skipped = 0
|
||||
cache: dict[tuple[Any, ...], str | None] = {}
|
||||
for row in job["tracks"]:
|
||||
if row.get("youtube_item"):
|
||||
ids.append(str(row["youtube_item"]))
|
||||
continue
|
||||
key = (row.get("id"), row["title"], row["artist"])
|
||||
if key not in cache:
|
||||
cache[key] = await self.jellyfin.audio(
|
||||
row, job["user_id"]
|
||||
)
|
||||
found = cache[key]
|
||||
if found:
|
||||
ids.append(found)
|
||||
row.pop("review", None)
|
||||
row.pop("attempts", None)
|
||||
elif row.get("skipped"):
|
||||
skipped += 1
|
||||
elif row.get("review"):
|
||||
review += 1
|
||||
job["ready"] = len(ids)
|
||||
await self._publish(job, ids, review)
|
||||
if len(ids) == len(job["tracks"]):
|
||||
job["stage"] = "complete"
|
||||
elif len(ids) + review == len(job["tracks"]):
|
||||
elif len(ids) + review + skipped == len(job["tracks"]):
|
||||
job["stage"] = "attention"
|
||||
else:
|
||||
job["stage"] = "waiting"
|
||||
|
||||
+217
-39
@@ -53,6 +53,7 @@ from .spec import (
|
||||
split_query,
|
||||
)
|
||||
from .spotify import SpotifyPublic, playlist_id
|
||||
from .youtube import YoutubeError, youtube_url
|
||||
|
||||
log = logging.getLogger("red.doge_cogs.watch")
|
||||
|
||||
@@ -105,6 +106,17 @@ def album_choice_label(album: dict[str, Any]) -> str:
|
||||
return discord.utils.escape_markdown(label)[:100]
|
||||
|
||||
|
||||
def video_label(video: dict[str, Any]) -> str:
|
||||
"""Name a YouTube candidate with its channel and duration."""
|
||||
seconds = int(video.get("duration") or 0)
|
||||
length = f"{seconds // 60}:{seconds % 60:02d}" if seconds else "?"
|
||||
label = (
|
||||
f"{video.get('title', 'Untitled')} · "
|
||||
f"{video.get('uploader', 'unknown')} · {length}"
|
||||
)
|
||||
return discord.utils.escape_markdown(label)[:100]
|
||||
|
||||
|
||||
def review_summary(
|
||||
tracks: list[dict[str, Any]], *, limit: int = 5
|
||||
) -> list[str]:
|
||||
@@ -1475,6 +1487,7 @@ class Watch(commands.Cog):
|
||||
return
|
||||
lines = []
|
||||
needs_retry = False
|
||||
missing = False
|
||||
for job in own[-5:]:
|
||||
name = discord.utils.escape_markdown(job["name"])
|
||||
ready = job.get("ready", 0)
|
||||
@@ -1483,8 +1496,20 @@ class Watch(commands.Cog):
|
||||
f"**{name}** · {job['stage']} · "
|
||||
f"{ready}/{count} songs ready"
|
||||
)
|
||||
reviewed = [r for r in job["tracks"] if r.get("review")]
|
||||
reviewed = [
|
||||
r
|
||||
for r in job["tracks"]
|
||||
if r.get("review") and not r.get("skipped")
|
||||
]
|
||||
skipped = sum(
|
||||
1 for r in job["tracks"] if r.get("skipped")
|
||||
)
|
||||
lines.extend(review_summary(reviewed))
|
||||
if skipped:
|
||||
lines.append(
|
||||
f"{skipped} song(s) skipped at your "
|
||||
"request."
|
||||
)
|
||||
if job.get("mutation"):
|
||||
lines.append(
|
||||
"An earlier write needs owner "
|
||||
@@ -1492,12 +1517,25 @@ class Watch(commands.Cog):
|
||||
)
|
||||
if reviewed:
|
||||
needs_retry = True
|
||||
hint = (
|
||||
f"Use `{ctx.clean_prefix}importplaylist "
|
||||
"retry <name>` to try reviewed songs again."
|
||||
if needs_retry
|
||||
else ""
|
||||
)
|
||||
missing = any(
|
||||
r.get("review") == "Artist not in "
|
||||
"MusicBrainz"
|
||||
for r in reviewed
|
||||
)
|
||||
prefix = ctx.clean_prefix
|
||||
hints = []
|
||||
if needs_retry and missing:
|
||||
hints.append(
|
||||
f"For artists MusicBrainz lacks, use "
|
||||
f"`{prefix}importplaylist youtube <song>` or "
|
||||
f"`{prefix}importplaylist ignore <song>`."
|
||||
)
|
||||
if needs_retry:
|
||||
hints.append(
|
||||
f"Use `{prefix}importplaylist retry <name>` "
|
||||
"to try reviewed songs again."
|
||||
)
|
||||
hint = "\n".join(hints)
|
||||
body = "\n".join(lines)
|
||||
if hint:
|
||||
body = body[: 1900 - len(hint) - 1]
|
||||
@@ -1525,7 +1563,11 @@ class Watch(commands.Cog):
|
||||
f"{track.get('title', '')} "
|
||||
f"{track.get('artist', '')}"
|
||||
).casefold()
|
||||
if track.get("review") and query in haystack:
|
||||
if (
|
||||
track.get("review")
|
||||
and not track.get("skipped")
|
||||
and query in haystack
|
||||
):
|
||||
found.append((key, index, job, track))
|
||||
return found
|
||||
|
||||
@@ -1537,6 +1579,65 @@ class Watch(commands.Cog):
|
||||
name = job.get("name", "playlist")
|
||||
return f"{title} · {artist} · {name}"
|
||||
|
||||
async def _reviewed_choice(
|
||||
self, ctx: commands.Context, query: str
|
||||
) -> tuple[str, int, dict[str, Any], dict[str, Any]] | None:
|
||||
"""Choose one of the caller's reviewed songs by ``query``."""
|
||||
found = self._reviewed_tracks(
|
||||
ctx.author.id,
|
||||
query,
|
||||
await self.config.pending_jobs(),
|
||||
)
|
||||
if not found:
|
||||
await ctx.send(f"No reviewed song matches `{query}`.")
|
||||
return None
|
||||
if len(found) == 1:
|
||||
return found[0]
|
||||
pick = await self._download_choice(
|
||||
ctx,
|
||||
f"{len(found)} reviewed songs match:",
|
||||
[
|
||||
(str(i), self._review_label(job, track))
|
||||
for i, (_key, _index, job, track) in (
|
||||
enumerate(found[:24])
|
||||
)
|
||||
],
|
||||
)
|
||||
return None if pick is None else found[int(pick)]
|
||||
|
||||
async def _youtube_choice(
|
||||
self, ctx: commands.Context, jobs: Jobs, track: dict[str, Any]
|
||||
) -> str | None:
|
||||
"""Let the requester choose from matching YouTube videos."""
|
||||
title = discord.utils.escape_markdown(
|
||||
str(track.get("title", "song"))
|
||||
)
|
||||
try:
|
||||
results = await jobs.youtube().search(
|
||||
f"{track.get('title', '')} "
|
||||
f"{track.get('artist', '')}".strip()
|
||||
)
|
||||
except YoutubeError as exc:
|
||||
await ctx.send(f"YouTube search failed: {exc}")
|
||||
return None
|
||||
if not results:
|
||||
await ctx.send(
|
||||
f"YouTube found no video for **{title}**. "
|
||||
f"Paste a link with "
|
||||
f"`{ctx.clean_prefix}importplaylist youtube "
|
||||
f"{title} <url>`.",
|
||||
allowed_mentions=discord.AllowedMentions.none(),
|
||||
)
|
||||
return None
|
||||
return await self._download_choice(
|
||||
ctx,
|
||||
f"Which video is **{title}**?",
|
||||
[
|
||||
(str(video["url"]), video_label(video))
|
||||
for video in results
|
||||
],
|
||||
)
|
||||
|
||||
async def _lidarr_album(
|
||||
self, ctx: commands.Context, track: dict[str, Any]
|
||||
) -> dict[str, Any] | None:
|
||||
@@ -1604,34 +1705,9 @@ class Watch(commands.Cog):
|
||||
)
|
||||
return
|
||||
jobs = self.background()
|
||||
found = self._reviewed_tracks(
|
||||
ctx.author.id,
|
||||
query,
|
||||
await self.config.pending_jobs(),
|
||||
)
|
||||
if not found:
|
||||
await ctx.send(
|
||||
f"No reviewed song matches `{song.strip()}`."
|
||||
)
|
||||
choice = await self._reviewed_choice(ctx, query)
|
||||
if choice is None:
|
||||
return
|
||||
choice = found[0]
|
||||
if len(found) > 1:
|
||||
pick = await self._download_choice(
|
||||
ctx,
|
||||
f"{len(found)} reviewed songs match:",
|
||||
[
|
||||
(
|
||||
str(i),
|
||||
self._review_label(job, track),
|
||||
)
|
||||
for i, (_key, _index, job, track) in (
|
||||
enumerate(found[:24])
|
||||
)
|
||||
],
|
||||
)
|
||||
if pick is None:
|
||||
return
|
||||
choice = found[int(pick)]
|
||||
key, index, job, track = choice
|
||||
if job.get("mutation"):
|
||||
await ctx.send(
|
||||
@@ -1664,6 +1740,100 @@ class Watch(commands.Cog):
|
||||
)
|
||||
self._spawn(jobs.run_once(key))
|
||||
|
||||
@playlist.command(name="youtube")
|
||||
async def playlist_youtube(
|
||||
self, ctx: commands.Context, *, song: str = ""
|
||||
) -> None:
|
||||
"""Fetch a reviewed song from YouTube (or a link you paste)."""
|
||||
if not await self.can_download(ctx.author):
|
||||
await ctx.send(
|
||||
"Download permission is required; ask "
|
||||
"the owner to use `request allow`."
|
||||
)
|
||||
return
|
||||
url = youtube_url(song)
|
||||
query = song.replace(url, " ") if url else song
|
||||
query = query.strip().casefold()
|
||||
if len(query) < 2: # noqa: PLR2004 (a useful search)
|
||||
await ctx.send(
|
||||
f"Use `{ctx.clean_prefix}importplaylist "
|
||||
"youtube <song>` (`youtube <song> <link>` to "
|
||||
"choose the video yourself)."
|
||||
)
|
||||
return
|
||||
jobs = self.background()
|
||||
choice = await self._reviewed_choice(ctx, query)
|
||||
if choice is None:
|
||||
return
|
||||
key, index, job, track = choice
|
||||
if job.get("mutation"):
|
||||
await ctx.send(
|
||||
"An earlier write needs owner verification "
|
||||
"before fetching. Use `importplaylist verify`."
|
||||
)
|
||||
return
|
||||
if key in jobs.active:
|
||||
await ctx.send(
|
||||
"That import is still being checked; try "
|
||||
"again in a minute."
|
||||
)
|
||||
return
|
||||
title = discord.utils.escape_markdown(
|
||||
str(track.get("title", "song"))
|
||||
)
|
||||
problem = await jobs.youtube().ready()
|
||||
if problem is not None:
|
||||
await ctx.send(
|
||||
"The YouTube fallback is not available: "
|
||||
f"{problem}. The song stays in review."
|
||||
)
|
||||
return
|
||||
if url is None:
|
||||
picked = await self._youtube_choice(ctx, jobs, track)
|
||||
if picked is None:
|
||||
return
|
||||
url = picked
|
||||
await ctx.send(
|
||||
f"Downloading **{title}** from YouTube...",
|
||||
allowed_mentions=discord.AllowedMentions.none(),
|
||||
)
|
||||
self._spawn(jobs.fetch_youtube(key, index, url))
|
||||
|
||||
@playlist.command(name="ignore")
|
||||
async def playlist_ignore(
|
||||
self, ctx: commands.Context, *, song: str = ""
|
||||
) -> None:
|
||||
"""Skip a reviewed song permanently, without retrying it."""
|
||||
if not await self.can_download(ctx.author):
|
||||
await ctx.send(
|
||||
"Download permission is required; ask "
|
||||
"the owner to use `request allow`."
|
||||
)
|
||||
return
|
||||
query = song.strip().casefold()
|
||||
if len(query) < 2: # noqa: PLR2004 (a useful search)
|
||||
await ctx.send(
|
||||
f"Use `{ctx.clean_prefix}importplaylist "
|
||||
"ignore <song>`."
|
||||
)
|
||||
return
|
||||
jobs = self.background()
|
||||
choice = await self._reviewed_choice(ctx, query)
|
||||
if choice is None:
|
||||
return
|
||||
key, index, _job, track = choice
|
||||
try:
|
||||
name = await jobs.skip(key, index)
|
||||
except (PreloadError, PermissionError) as exc:
|
||||
await ctx.send(f"Couldn't skip that song: {exc}")
|
||||
return
|
||||
await ctx.send(
|
||||
f"Skipped **{discord.utils.escape_markdown(name)}**; "
|
||||
"it won't be retried or counted again.",
|
||||
allowed_mentions=discord.AllowedMentions.none(),
|
||||
)
|
||||
self._spawn(jobs.run_once(key))
|
||||
|
||||
@playlist.command(name="retry")
|
||||
async def playlist_retry(
|
||||
self, ctx: commands.Context, *, target: str = ""
|
||||
@@ -1690,8 +1860,11 @@ class Watch(commands.Cog):
|
||||
if job.get("owner") == ctx.author.id
|
||||
and job.get("kind") == "playlist"
|
||||
and any(
|
||||
not track.get("resolved")
|
||||
or track.get("review")
|
||||
(
|
||||
not track.get("resolved")
|
||||
or track.get("review")
|
||||
)
|
||||
and not track.get("skipped")
|
||||
for track in job.get("tracks", [])
|
||||
)
|
||||
and (
|
||||
@@ -1736,8 +1909,13 @@ class Watch(commands.Cog):
|
||||
rows = [
|
||||
track
|
||||
for track in job["tracks"]
|
||||
if not track.get("resolved")
|
||||
or track.get("review")
|
||||
if (
|
||||
not track.get(
|
||||
"resolved"
|
||||
)
|
||||
or track.get("review")
|
||||
)
|
||||
and not track.get("skipped")
|
||||
]
|
||||
for row in rows:
|
||||
for field in (
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
"""Fetch a reviewed song from YouTube when MusicBrainz has no artist."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
from collections.abc import Awaitable, Callable
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
LINK = re.compile(r"https?://\S+")
|
||||
YOUTUBE_HOSTS = {
|
||||
"youtube.com",
|
||||
"www.youtube.com",
|
||||
"m.youtube.com",
|
||||
"music.youtube.com",
|
||||
"youtu.be",
|
||||
}
|
||||
|
||||
|
||||
class YoutubeError(Exception):
|
||||
"""A search or download the user can be told about."""
|
||||
|
||||
|
||||
def is_youtube(url: str) -> bool:
|
||||
"""Accept only YouTube links, never arbitrary downloader input."""
|
||||
parts = urlsplit(url)
|
||||
return parts.scheme == "https" and parts.netloc in YOUTUBE_HOSTS
|
||||
|
||||
|
||||
def youtube_url(text: str) -> str | None:
|
||||
"""Return a pasted YouTube link without its trailing punctuation."""
|
||||
for match in LINK.finditer(text):
|
||||
url = match[0].rstrip(".,;:)]}")
|
||||
if is_youtube(url):
|
||||
return url
|
||||
return None
|
||||
|
||||
|
||||
def _safe(value: str) -> str:
|
||||
"""Keep one path component for the artist and title folders."""
|
||||
cleaned = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "", value).strip(" .")
|
||||
return (cleaned or "Unknown")[:120]
|
||||
|
||||
|
||||
def _inside(path: Path, folder: Path) -> bool:
|
||||
"""Reject output that escaped the configured music folder."""
|
||||
try:
|
||||
path.resolve().relative_to(folder.resolve())
|
||||
except ValueError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _reason(stderr: str) -> str:
|
||||
"""Keep yt-dlp's last error line without dumping its whole log."""
|
||||
lines = [line.strip() for line in stderr.splitlines() if line.strip()]
|
||||
if not lines:
|
||||
return "yt-dlp failed."
|
||||
return lines[-1].removeprefix("ERROR: ")[:300]
|
||||
|
||||
|
||||
async def _run(args: list[str], limit: float) -> tuple[int, str, str]:
|
||||
"""Run yt-dlp without a shell and bound how long it may take."""
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
*args,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
try:
|
||||
stdout, stderr = await asyncio.wait_for(
|
||||
process.communicate(), limit
|
||||
)
|
||||
except TimeoutError:
|
||||
process.kill()
|
||||
await process.wait()
|
||||
msg = "yt-dlp timed out."
|
||||
raise YoutubeError(msg) from None
|
||||
return (
|
||||
process.returncode or 0,
|
||||
stdout.decode(errors="replace"),
|
||||
stderr.decode(errors="replace"),
|
||||
)
|
||||
|
||||
|
||||
Runner = Callable[[list[str], float], Awaitable[tuple[int, str, str]]]
|
||||
|
||||
|
||||
class Youtube:
|
||||
"""Search and download audio into the Jellyfin music folder."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
binary: str = "yt-dlp",
|
||||
folder: str | os.PathLike[str] = "/music/YouTube Imports",
|
||||
runner: Runner | None = None,
|
||||
) -> None:
|
||||
"""Use the deployed yt-dlp unless a test injects a runner."""
|
||||
self.binary = binary
|
||||
self.folder = Path(folder)
|
||||
self.runner = runner or _run
|
||||
|
||||
async def ready(self) -> str | None:
|
||||
"""Name what is missing before a track is committed to it."""
|
||||
if not await asyncio.to_thread(self.folder.is_dir):
|
||||
return "the YouTube music folder is not mounted"
|
||||
found = await asyncio.to_thread(shutil.which, self.binary)
|
||||
if found is None:
|
||||
return "yt-dlp is not installed"
|
||||
return None
|
||||
|
||||
async def search(
|
||||
self, query: str, limit: int = 5
|
||||
) -> list[dict[str, object]]:
|
||||
"""List candidate videos without downloading anything."""
|
||||
code, stdout, stderr = await self.runner(
|
||||
[
|
||||
self.binary,
|
||||
"--dump-single-json",
|
||||
"--flat-playlist",
|
||||
f"ytsearch{limit}:{query}",
|
||||
],
|
||||
120,
|
||||
)
|
||||
if code:
|
||||
raise YoutubeError(_reason(stderr))
|
||||
try:
|
||||
data = json.loads(stdout)
|
||||
except ValueError:
|
||||
msg = "YouTube search returned no usable results."
|
||||
raise YoutubeError(msg) from None
|
||||
results = []
|
||||
for entry in data.get("entries") or []:
|
||||
video = str(entry.get("id") or "")
|
||||
if not video:
|
||||
continue
|
||||
results.append(
|
||||
{
|
||||
"url": str(
|
||||
entry.get("webpage_url")
|
||||
or "https://www.youtube.com/"
|
||||
f"watch?v={video}"
|
||||
),
|
||||
"title": str(
|
||||
entry.get("title") or "Untitled"
|
||||
),
|
||||
"uploader": str(
|
||||
entry.get("uploader")
|
||||
or entry.get("channel")
|
||||
or "unknown channel"
|
||||
),
|
||||
"duration": entry.get("duration") or 0,
|
||||
}
|
||||
)
|
||||
return results[:limit]
|
||||
|
||||
async def download(self, url: str, artist: str, title: str) -> Path:
|
||||
"""Download one video's audio as a Jellyfin-readable file."""
|
||||
if not is_youtube(url):
|
||||
msg = "Use a YouTube link for this fallback."
|
||||
raise YoutubeError(msg)
|
||||
template = (
|
||||
self.folder
|
||||
/ _safe(artist)
|
||||
/ (f"{_safe(title)}.%(ext)s")
|
||||
)
|
||||
code, stdout, stderr = await self.runner(
|
||||
[
|
||||
self.binary,
|
||||
"--no-playlist",
|
||||
"--extract-audio",
|
||||
"--audio-format",
|
||||
"opus",
|
||||
"--audio-quality",
|
||||
"0",
|
||||
"--no-progress",
|
||||
"--print",
|
||||
"after_move:filepath",
|
||||
"--output",
|
||||
str(template),
|
||||
url,
|
||||
],
|
||||
900,
|
||||
)
|
||||
if code:
|
||||
raise YoutubeError(_reason(stderr))
|
||||
lines = [line.strip() for line in stdout.splitlines()]
|
||||
lines = [line for line in lines if line]
|
||||
if not lines:
|
||||
msg = "yt-dlp did not report a downloaded file."
|
||||
raise YoutubeError(msg)
|
||||
path = Path(lines[-1])
|
||||
if not _inside(path, self.folder):
|
||||
msg = "yt-dlp wrote outside the music folder."
|
||||
raise YoutubeError(msg)
|
||||
if not await asyncio.to_thread(path.is_file):
|
||||
msg = "The downloaded audio file is missing."
|
||||
raise YoutubeError(msg)
|
||||
return path
|
||||
Reference in new issue
Block a user