-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtelevize.py
More file actions
executable file
·209 lines (161 loc) · 6.41 KB
/
televize.py
File metadata and controls
executable file
·209 lines (161 loc) · 6.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#!/usr/bin/env python3
"""Play Czech television stream in custom player.
Usage: televize.py [options] channels
televize.py [options] live <channel>
televize.py [options] ivysilani <url>
televize.py -h | --help
televize.py --version
Subcommands:
channels print a list of available channels
live play live channel
ivysilani play video from ivysilani archive
Options:
-h, --help show this help message and exit
--version show program's version number and exit
-q, --quality=QUAL select stream quality [default: 540p]. Commonly available are 180p, 360p, 540p, 720p and 1080p.
-p, --player=PLAYER player command [default: mpv]
-d, --debug print debug messages
"""
import logging
import re
import shlex
import subprocess
import sys
from collections.abc import Iterable
from dataclasses import dataclass
from typing import Any, Optional, cast
from urllib.parse import urljoin, urlsplit
import requests
from docopt import docopt
__version__ = "0.6.0"
################################################################################
# Channels API
CHANNELS_LINK = "https://ct24.ceskatelevize.cz/api/live"
@dataclass
class Channel:
"""Represents a TV channel.
Attributes:
id: Channel ID
name: Channel name
slug: Channel slug
title: Current or next programme title
"""
id: str
name: str
slug: str
title: Optional[str] = None
def get_channels() -> Iterable[Channel]:
"""Iterate over available channels."""
response = requests.get(CHANNELS_LINK, timeout=10)
logging.debug("Channels response[%s]: %s", response.status_code, response.text)
response.raise_for_status()
for channel_data in response.json()["data"]:
if not channel_data.get("__typename") == "LiveBroadcast":
# Skip non-live channels
continue
if current := channel_data.get("current"):
name = current["channelSettings"]["channelName"]
slug = current["slug"]
title = current["title"]
elif next := channel_data.get("next"):
name = next["channelSettings"]["channelName"]
slug = next["slug"]
title = next["title"]
else:
name = ""
slug = ""
title = None
yield Channel(id=channel_data["id"], name=name, slug=slug, title=title)
def print_channels(channels: Iterable[Channel]) -> None:
"""List available channels."""
for channel in channels:
print(f"{channel.slug}: {channel.name} - {channel.title}")
################################################################################
# Playlist functions
LIVE_PLAYLIST_LINK = "https://api.ceskatelevize.cz/video/v1/playlist-live/v1/stream-data/channel/"
def get_live_playlist(channel: str, quality: str) -> str:
"""Return playlist URL for live CT channel.
@param channel: Channel slug
@param quality: Requested quality
"""
channels = {c.slug: c for c in get_channels()}
if channel not in channels:
raise ValueError(f"Channel {channel} not found.")
channel_obj = channels[channel]
data = {"quality": quality}
response = requests.get(urljoin(LIVE_PLAYLIST_LINK, channel_obj.id), data, timeout=10)
logging.debug("Live playlist response[%s]: %s", response.status_code, response.text)
response.raise_for_status()
playlist_data = response.json()
return cast(str, playlist_data["streamUrls"]["main"])
IVYSILANI_PLAYLIST_LINK = "https://api.ceskatelevize.cz/video/v1/playlist-vod/v1/stream-data/media/external/"
def get_ivysilani_playlist(program_id: str, quality: str) -> str:
"""Return playlist URL for ivysilani.
@param program_id: Program ID
@param quality: Requested quality
"""
data = {"quality": quality}
response = requests.get(urljoin(IVYSILANI_PLAYLIST_LINK, program_id), data, timeout=10)
logging.debug("Ivysilani playlist response[%s]: %s", response.status_code, response.text)
response.raise_for_status()
playlist_data = response.json()
return cast(str, playlist_data["streams"][0]["url"])
################################################################################
def run_player(playlist: str, player_cmd: str) -> None:
"""Run the video player.
@param playlist: Playlist URL to be played
@param player_cmd: Player command
"""
cmd = shlex.split(player_cmd) + [playlist]
logging.debug("Player cmd: %s", cmd)
subprocess.call(cmd) # noqa: S101, S603
def play_live(options: dict[str, Any]) -> None:
"""Play live channel."""
playlist = get_live_playlist(options["<channel>"], options["--quality"])
run_player(playlist, options["--player"])
PORADY_PATH_PATTERN = re.compile(r"^/porady/[^/]+/(?P<playlist_id>\d+)(-[^/]*)?/?$")
def play_ivysilani(options: dict[str, Any]) -> None:
"""Play live channel.
Raises:
ValueError: Program not found.
"""
# Porady pages have playlist ID in URL
split = urlsplit(options["<url>"])
match = PORADY_PATH_PATTERN.match(split.path)
if match:
playlist_id = match.group("playlist_id")
playlist = get_ivysilani_playlist(playlist_id, options["--quality"])
run_player(playlist, options["--player"])
if not match:
# TODO: Fetch porady page and play the most recent video.
raise ValueError("Video not found.")
def main() -> None: # pragma: no cover
"""Play Czech television stream in custom player."""
options = docopt(__doc__, version=__version__)
# Set up logging
if options["--debug"]:
level = logging.DEBUG
else:
level = logging.WARNING
logging.basicConfig(stream=sys.stderr, level=level, format="%(asctime)s %(levelname)s:%(funcName)s: %(message)s")
logging.getLogger("iso8601").setLevel(logging.WARN)
try:
channels = get_channels()
if options["channels"]:
print_channels(channels)
elif options["live"]:
play_live(options)
else:
assert options["ivysilani"] # noqa: S101
play_ivysilani(options)
except Exception as error:
if level == logging.DEBUG:
logging.exception("An error occured:")
else:
logging.warning("An error occured: %s", error)
exit(1)
except KeyboardInterrupt:
# User killed the program, silence the exception
exit(0)
if __name__ == "__main__": # pragma: no cover
main()