mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-03 14:35:09 +00:00
fix(import): keep the values a service set on exported tracks and export a song as a song
This commit is contained in:
@@ -1036,6 +1036,13 @@ An export with no manifest, for example a unidl export of whole media files, get
|
||||
tracks from those URLs. If such an export does not give the title a language, `orig` has no
|
||||
value: select the languages with `-l` and `-vl`.
|
||||
|
||||
Each exported track keeps the values that the service set on it, also when the import parses
|
||||
the manifest again: for example Atmos, the bit depth, the sample rate and the note at the end of
|
||||
its `--list` line. A track that the export does not hold shows only what the manifest gives. A
|
||||
song imports as a song, with its artist, album and track number. An export that an older
|
||||
unshackle wrote records a song as a movie. Its import then stops at the video selection, because
|
||||
a song has no video track. Export the song again.
|
||||
|
||||
An import uses only the content keys in the file and in your vaults. It never gets a licence
|
||||
from a CDM. When a track needs a content key that neither has, the import stops and names the
|
||||
KID. To fix this, export the title again with that track selected.
|
||||
|
||||
@@ -22,7 +22,7 @@ from unshackle.core.drm.clearkey import ClearKey
|
||||
from unshackle.core.drm.clearkey_cenc import ClearKeyCENC
|
||||
from unshackle.core.export_writer import ExportWriter
|
||||
from unshackle.core.import_service import ImportService
|
||||
from unshackle.core.titles import Movie
|
||||
from unshackle.core.titles import Album, Movie, Song
|
||||
from unshackle.core.tracks import Audio, Chapter, Subtitle, Video
|
||||
from unshackle.core.wire import drm_from_dict
|
||||
|
||||
@@ -570,3 +570,18 @@ def test_a_title_with_no_record_logs_that_nothing_was_exported(
|
||||
writer.log_title(second)
|
||||
|
||||
assert caplog.messages == ["Exported nothing for 'Example Movie' (2024)"]
|
||||
|
||||
|
||||
def test_a_song_stays_a_song_of_an_album_through_export_and_import(tmp_path: Path) -> None:
|
||||
writer = make_writer(tmp_path)
|
||||
title = Song(
|
||||
id_="song-1", service=StubService, name="Example Song", artist="Example Artist", album="Example Album", track=4
|
||||
)
|
||||
title.tracks.add(make_title().tracks.audio[0])
|
||||
writer.record(title, title.tracks.audio[0])
|
||||
|
||||
titles = ImportService(import_ctx(), "EXAMPLE", "song-1", str(written(writer))).get_titles()
|
||||
assert isinstance(titles, Album)
|
||||
assert [(type(t).__name__, t.artist, t.album, t.track) for t in titles] == [
|
||||
("Song", "Example Artist", "Example Album", 4)
|
||||
]
|
||||
|
||||
@@ -21,7 +21,8 @@ import requests
|
||||
|
||||
from unshackle.core.import_service import ImportService
|
||||
from unshackle.core.manifests import DASH
|
||||
from unshackle.core.tracks import Audio, Subtitle, Video
|
||||
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
|
||||
from unshackle.core.wire import track_to_dict
|
||||
|
||||
MPD_TEMPLATE = """<?xml version="1.0"?>
|
||||
<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="static" mediaPresentationDuration="PT10M">
|
||||
@@ -300,3 +301,45 @@ def test_a_file_row_can_name_its_codec_and_range_by_name(tmp_path: Path) -> None
|
||||
def test_a_file_row_marked_stereo_imports_as_a_3d_video(tmp_path: Path) -> None:
|
||||
service = file_export(tmp_path, [{**FILE_ROWS[0], "stereo": True}])
|
||||
assert service.get_tracks(next(iter(service.get_titles()))).videos[0].stereo
|
||||
|
||||
|
||||
MPD_SERVICE_VALUES = """<?xml version="1.0"?>
|
||||
<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="static" mediaPresentationDuration="PT10M">
|
||||
<Period id="1">
|
||||
<AdaptationSet contentType="audio" mimeType="audio/mp4" lang="en">
|
||||
<Representation id="a1" codecs="ec-3" bandwidth="640000" audioSamplingRate="48000">
|
||||
<BaseURL>a.mp4</BaseURL><SegmentBase indexRange="0-1"/>
|
||||
</Representation>
|
||||
</AdaptationSet>
|
||||
<AdaptationSet contentType="text" mimeType="application/mp4" lang="en">
|
||||
<Representation id="s1" codecs="stpp" bandwidth="1000"><BaseURL>s.mp4</BaseURL><SegmentBase indexRange="0-1"/></Representation>
|
||||
</AdaptationSet>
|
||||
</Period>
|
||||
</MPD>
|
||||
"""
|
||||
|
||||
SERVICE_VALUES = {"atmos": True, "bit_depth": 24, "sample_rate": 96000, "note": "EXAMPLE_TIER", "name": "Example Mix"}
|
||||
|
||||
|
||||
def import_with(tmp_path: Path, kind: str, drop: str = "", **values: Any) -> Tracks:
|
||||
"""Import the manifest with the export dict of its ``kind`` track, given the values a service set after the parse."""
|
||||
parsed = getattr(
|
||||
DASH.from_text(MPD_SERVICE_VALUES, "https://example.invalid/m.mpd").to_tracks(language="en"), kind
|
||||
)[0]
|
||||
exported = {k: v for k, v in json.loads(json.dumps(track_to_dict(parsed))).items() if k != drop}
|
||||
return get_tracks(make_service(tmp_path, "en", {exported["id"]: {**exported, **values}}), MPD_SERVICE_VALUES)
|
||||
|
||||
|
||||
def test_the_values_a_service_set_on_a_track_survive_the_reparse(tmp_path: Path) -> None:
|
||||
audio = import_with(tmp_path, "audio", **SERVICE_VALUES).audio
|
||||
assert [(t.atmos, t.bit_depth, t.sample_rate, t.note, t.name) for t in audio] == [tuple(SERVICE_VALUES.values())]
|
||||
assert audio[0].data.get("dash") is not None
|
||||
|
||||
|
||||
def test_a_value_an_older_export_does_not_record_keeps_the_manifest_value(tmp_path: Path) -> None:
|
||||
assert [t.sample_rate for t in import_with(tmp_path, "audio", drop="sample_rate").audio] == [48000]
|
||||
|
||||
|
||||
def test_a_subtitle_keeps_the_manifest_codec_its_download_converted(tmp_path: Path) -> None:
|
||||
subtitles = import_with(tmp_path, "subtitles", codec="TimedTextMarkupLang", sdh=True).subtitles
|
||||
assert [(t.codec, t.sdh) for t in subtitles] == [(Subtitle.Codec.fTTML, True)]
|
||||
|
||||
@@ -758,14 +758,19 @@ def test_export_movie_meta() -> None:
|
||||
|
||||
|
||||
def test_export_meta_of_another_title_is_a_movie_named_by_str() -> None:
|
||||
assert title_to_meta(song()) == {
|
||||
"id": "song-0001",
|
||||
"language": "en",
|
||||
assert title_to_meta(OtherTitle()) == {
|
||||
"id": "other-0001",
|
||||
"language": None,
|
||||
"type": "movie",
|
||||
"name": "Example Artist - Example Album (2022) / 03. Example Song",
|
||||
"name": "Other Thing",
|
||||
}
|
||||
|
||||
|
||||
def test_export_song_meta_rebuilds_the_song_the_rest_form_rebuilds() -> None:
|
||||
rebuilt = title_fields(build_title(json_copy(title_to_meta(song())), "EXAMPLE", "fallback-id"))
|
||||
assert rebuilt == title_fields(build_title(json_copy(REST_SONG), "EXAMPLE", "fallback-id"))
|
||||
|
||||
|
||||
def test_build_title_from_rest_episode() -> None:
|
||||
assert title_fields(build_title(json_copy(REST_EPISODE), "EXAMPLE", "fallback-id")) == EPISODE_FIELDS
|
||||
|
||||
|
||||
@@ -26,13 +26,13 @@ from unshackle.core.remote_protocol import APIErrorCode, coded
|
||||
from unshackle.core.remote_service import resolve_proxy_arg, segment_uri_filter
|
||||
from unshackle.core.session import failure_response, record_requests
|
||||
from unshackle.core.title_source import KeyArrival, TitleSource
|
||||
from unshackle.core.titles import Episode, Movies, Series, Title_T, Titles_T, remap_titles
|
||||
from unshackle.core.titles import Album, Episode, Movies, Series, Song, Title_T, Titles_T, remap_titles
|
||||
from unshackle.core.tracks import Audio, Chapter, Chapters, Subtitle, Tracks, Video
|
||||
from unshackle.core.tracks.attachment import Attachment
|
||||
from unshackle.core.tracks.track import Track
|
||||
from unshackle.core.utils import run_proxy
|
||||
from unshackle.core.utils.collections import ci_get
|
||||
from unshackle.core.wire import build_title, drm_from_dict, track_from_dict
|
||||
from unshackle.core.wire import apply_track_dict, build_title, drm_from_dict, track_from_dict
|
||||
|
||||
log = logging.getLogger("import")
|
||||
E = TypeVar("E", bound=Enum)
|
||||
@@ -373,9 +373,13 @@ class ImportService(TitleSource):
|
||||
build_title(self.title_meta(entry), self.service_tag, fallback_id=title_id)
|
||||
for title_id, entry in self.titles_data.items()
|
||||
]
|
||||
self.titles = (
|
||||
Series(titles_list) if titles_list and isinstance(titles_list[0], Episode) else Movies(titles_list)
|
||||
)
|
||||
first = titles_list[0] if titles_list else None
|
||||
if isinstance(first, Episode):
|
||||
self.titles = Series(titles_list)
|
||||
elif isinstance(first, Song):
|
||||
self.titles = Album(titles_list)
|
||||
else:
|
||||
self.titles = Movies(titles_list)
|
||||
return self.titles
|
||||
|
||||
@staticmethod
|
||||
@@ -404,8 +408,10 @@ class ImportService(TitleSource):
|
||||
"""Reconstruct the title's tracks from the export.
|
||||
|
||||
DASH/ISM: re-fetch and re-parse ``manifest_url`` for the full ladder on that MPD (the importer
|
||||
picks quality with normal dl flags, and injects the keys by KID later), then merge in exported
|
||||
DASH/ISM tracks from other MPDs (e.g. a separate HEVC manifest) and direct-URL side-loads.
|
||||
picks quality with normal dl flags, and injects the keys by KID later). A re-parsed track takes
|
||||
the values its exported dict records, since the service can set them after the parse. Then
|
||||
merge in exported DASH/ISM tracks from other MPDs (e.g. a separate HEVC manifest) and direct-URL
|
||||
side-loads.
|
||||
A service side-loads its own subtitles when the manifest's are the worse copy, so any
|
||||
direct-URL subtitle in the export means unshackle drops the whole re-parsed subtitle
|
||||
set in favour of the exported one.
|
||||
@@ -461,6 +467,12 @@ class ImportService(TitleSource):
|
||||
f"Failed to parse the {manifest_type} manifest for '{title}': {e}"
|
||||
)
|
||||
for parsed_track in parsed:
|
||||
exported = tracks_map.get(str(parsed_track.id))
|
||||
if exported and exported.get("type") == type(parsed_track).__name__:
|
||||
try:
|
||||
apply_track_dict(parsed_track, exported)
|
||||
except Exception as e:
|
||||
self.log.warning(f"Keeping the manifest values of exported track {parsed_track.id!r}: {e}")
|
||||
tracks.add(parsed_track)
|
||||
parsed_ids = {str(t.id) for t in tracks}
|
||||
url_dicts = [t for t in tracks_map.values() if t.get("descriptor", "URL") == "URL"]
|
||||
|
||||
+27
-5
@@ -137,11 +137,8 @@ def serialize_title(title: Title_T, service: Any) -> dict[str, Any]:
|
||||
title.air_date.isoformat() if isinstance(title.air_date, date_) else str(title.air_date)
|
||||
)
|
||||
result.update(episode_flags(title))
|
||||
if is_song:
|
||||
for field in SONG_FIELDS:
|
||||
result[field] = getattr(title, field, None)
|
||||
metadata = song_metadata(title)
|
||||
result["music_data"] = {key: metadata[key] for key in MUSIC_DATA_KEYS if metadata.get(key) not in (None, "")}
|
||||
if isinstance(title, Song):
|
||||
result.update(song_fields(title))
|
||||
if isinstance(title, (Episode, Movie)) and getattr(title, "anime", None) is not None:
|
||||
result["anime"] = title.anime
|
||||
if isinstance(title, (Episode, Movie)) and getattr(title, "metadata_provider", None) is not None:
|
||||
@@ -170,6 +167,15 @@ def serialize_music(titles: Any) -> dict[str, Any]:
|
||||
return facts
|
||||
|
||||
|
||||
def song_fields(title: Song) -> dict[str, Any]:
|
||||
"""The Song fields and the music_data that both forms carry."""
|
||||
metadata = song_metadata(title)
|
||||
return {
|
||||
**{field: getattr(title, field, None) for field in SONG_FIELDS},
|
||||
"music_data": {key: metadata[key] for key in MUSIC_DATA_KEYS if metadata.get(key) not in (None, "")},
|
||||
}
|
||||
|
||||
|
||||
def title_to_meta(title: Title_T) -> dict[str, Any]:
|
||||
"""The export form of a title: the fields an import needs to rebuild it for output naming.
|
||||
|
||||
@@ -194,6 +200,8 @@ def title_to_meta(title: Title_T) -> dict[str, Any]:
|
||||
meta.update(episode_flags(title))
|
||||
elif isinstance(title, Movie):
|
||||
meta.update(type="movie", name=title.name, year=title.year)
|
||||
elif isinstance(title, Song):
|
||||
meta.update(type="song", name=title.name, year=title.year, **song_fields(title))
|
||||
else:
|
||||
meta.update(type="movie", name=str(title))
|
||||
if getattr(title, "anime", None) is not None:
|
||||
@@ -936,6 +944,20 @@ def track_to_dict(track: Track) -> dict[str, Any]:
|
||||
return data
|
||||
|
||||
|
||||
def apply_track_dict(track: Video | Audio | Subtitle, data: dict[str, Any]) -> None:
|
||||
"""Set on ``track`` the values its export form records, except its id, url and descriptor.
|
||||
|
||||
A field that an older export does not write keeps the value of ``track``. A subtitle also keeps its codec:
|
||||
the export records a subtitle after its download, which converts it to another codec.
|
||||
"""
|
||||
exported = track_from_dict({**data, "url": track.url})
|
||||
kept = {"type", "id", "url", "descriptor", "atmos", *(["codec"] if isinstance(track, Subtitle) else [])}
|
||||
for key in track_to_dict(exported).keys() & (data.keys() - kept):
|
||||
setattr(track, key, getattr(exported, key))
|
||||
if isinstance(exported, Audio) and exported.atmos:
|
||||
track.extra["atmos"] = True
|
||||
|
||||
|
||||
def track_from_dict(data: dict[str, Any]) -> Video | Audio | Subtitle:
|
||||
"""Reconstruct the correct Track subclass from its export form.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user