Skip to content

Commit

Permalink
Add id parsing to YouTube caption track objects
Browse files Browse the repository at this point in the history
  • Loading branch information
Jon Betts committed Aug 2, 2023
1 parent 75a51d9 commit be9d15c
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 19 deletions.
38 changes: 19 additions & 19 deletions tests/unit/via/services/youtube_api/models_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,29 +30,29 @@ def test_from_v1_json(self, kind):
}
)

@pytest.mark.parametrize(
"caption_track,id_string",
CAPTION_TRACK_IDS = (
(CaptionTrack(language_code="en"), "en"),
(CaptionTrack(language_code="en", kind="asr"), "en.a"),
(CaptionTrack(language_code="en", name="Hello"), "en..SGVsbG8="),
(CaptionTrack(language_code="en", translated_language_code="fr"), "en...fr"),
# This combination isn't actually possible, but let's try everything at
# once
(
(CaptionTrack(language_code="en"), "en"),
(CaptionTrack(language_code="en", kind="asr"), "en.a"),
(CaptionTrack(language_code="en", name="Hello"), "en..SGVsbG8="),
(
CaptionTrack(language_code="en", translated_language_code="fr"),
"en...fr",
),
# This combination isn't actually possible, but let's try everything at
# once
(
CaptionTrack(
language_code="en-gb",
kind="asr",
name="Name",
translated_language_code="fr",
),
"en-gb.a.TmFtZQ==.fr",
CaptionTrack(
language_code="en-gb",
kind="asr",
name="Name",
translated_language_code="fr",
),
"en-gb.a.TmFtZQ==.fr",
),
)

@pytest.mark.parametrize("caption_track,id_string", CAPTION_TRACK_IDS)
def test_from_id(self, caption_track, id_string):
assert CaptionTrack.from_id(id_string) == caption_track

@pytest.mark.parametrize("caption_track,id_string", CAPTION_TRACK_IDS)
def test_id(self, caption_track, id_string):
assert caption_track.id == id_string

Expand Down
25 changes: 25 additions & 0 deletions via/services/youtube_api/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import base64
from copy import deepcopy
from dataclasses import dataclass, field
from itertools import zip_longest
from operator import attrgetter
from typing import List, Optional

Expand Down Expand Up @@ -43,6 +44,30 @@ def from_v1_json(cls, data: dict):
base_url=data["baseUrl"],
)

@classmethod
def from_id(cls, id_string: str):
"""Create a partially filled out track from and id string."""

data = dict(
zip_longest(
[
"language_code",
"auto_generated",
"name",
"translated_language_code",
],
[part or None for part in id_string.split(".")],
)
)

if name := data.get("name"):
data["name"] = base64.b64decode(name.encode("utf-8")).decode("utf-8")

if data.pop("auto_generated", None):
data["kind"] = "asr"

return cls(**data)

@property
def id(self) -> str: # pylint: disable=invalid-name
if self.name:
Expand Down

0 comments on commit be9d15c

Please sign in to comment.