-
Notifications
You must be signed in to change notification settings - Fork 12
/
mtv_dl.py
executable file
·1676 lines (1475 loc) · 63.5 KB
/
mtv_dl.py
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import hashlib
import http.client
import json
import logging
import lzma
import os
import re
import shlex
import shutil
import sqlite3
import subprocess
import sys
import tempfile
import time
import traceback
import urllib.error
import urllib.parse
import urllib.request
from collections.abc import Iterable
from collections.abc import Iterator
from contextlib import contextmanager
from contextlib import suppress
from datetime import datetime
from datetime import timedelta
from datetime import timezone
from io import BytesIO
from itertools import chain
from os import chdir
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import Annotated
from typing import Any
from typing import ClassVar
from typing import Literal
from typing import TypedDict
from xml.etree import ElementTree as Et
import certifi
import durationpy
import ijson
import iso8601
import typer
from bs4 import BeautifulSoup
from rich import box
from rich.console import Console
from rich.logging import RichHandler
from rich.progress import BarColumn
from rich.progress import Progress
from rich.progress import TextColumn
from rich.progress import TimeRemainingColumn
from rich.table import Table
__version__ = "0.0.0"
from typer_config import use_yaml_config
CHUNK_SIZE = 128 * 1024
if (default_config_file := Path("~/.mtv_dl.yml").expanduser()).exists():
CONFIG_FILE: Path | None = default_config_file
else:
CONFIG_FILE = None
HISTORY_DATABASE_FILE = ".History.sqlite"
FILMLISTE_DATABASE_FILE = f".Filmliste.{__version__}.sqlite"
# regex to find characters not allowed in file names
INVALID_FILENAME_CHARACTERS = re.compile("[{}]".format(re.escape('<>:"/\\|?*' + "".join(chr(i) for i in range(32)))))
# see https://res.mediathekview.de/akt.xml
# and https://forum.mediathekview.de/topic/3508/aktuelle-verteiler-und-filmlisten-server
FILMLISTE_URL = "https://liste.mediathekview.de/Filmliste-akt.xz"
# global state
HIDE_PROGRESSBAR = True
CAFILE: str | None = None
SHOWLIST: "Database"
logger = logging.getLogger("mtv_dl")
utc_zone = timezone.utc
now = datetime.now(tz=utc_zone).replace(second=0, microsecond=0)
# add timedelta database type
sqlite3.register_adapter(timedelta, lambda v: v.total_seconds())
sqlite3.register_converter("timedelta", lambda v: timedelta(seconds=int(v)))
# console handler for tables and progress bars
console = Console()
@contextmanager
def progress_bar() -> Iterator[Progress]:
progress_console = console
if HIDE_PROGRESSBAR:
progress_console = Console(file=open(os.devnull, "w")) # noqa
with Progress(
TextColumn("[bold blue]{task.description}", justify="right"),
BarColumn(bar_width=None),
"[progress.percentage]{task.percentage:>3.1f}%",
TimeRemainingColumn(),
refresh_per_second=4,
console=progress_console,
) as progress:
yield progress
class SqlRegexFunction:
"""A simple SQL function to use regular expressions in SQL statements.
This is a workaround for the missing REGEXP operator in sqlite3.
It will deduplicate the compiled regular expressions to avoid
recompiling the same expression over and over again. Also, it will
log warnings if the regular expression is invalid only once.
"""
last_error: str = ""
last_expression: str = ""
pattern: "re.Pattern[str]" = re.compile("")
def __call__(self, expr: str, item: str) -> bool:
try:
if self.last_expression != expr:
self.last_expression = expr
self.pattern = re.compile(expr, re.IGNORECASE)
except re.error as e:
if self.last_error != str(e):
self.last_error = str(e)
logger.warning("Invalid regular expression %r (using string match instead): %s", expr, e)
self.pattern = re.compile(re.escape(expr), re.IGNORECASE)
return self.pattern.search(item) is not None
class ConfigurationError(Exception):
pass
class RetryLimitExceededError(Exception):
pass
def serialize_for_json(obj: Any) -> str:
if isinstance(obj, datetime):
return obj.isoformat()
elif isinstance(obj, timedelta):
return str(obj)
else:
raise TypeError(f"{obj!r} is not JSON serializable")
def escape_path(s: str) -> str:
return INVALID_FILENAME_CHARACTERS.sub("_", s)
class Database:
# noinspection SpellCheckingInspection
TRANSLATION: ClassVar = {
"Beschreibung": "description",
"Datum": "date",
"DatumL": "start",
"Dauer": "duration",
"Geo": "region",
"Größe [MB]": "size",
"Sender": "channel",
"Thema": "topic",
"Titel": "title",
"Url": "url",
"Url HD": "url_hd",
"Url History": "url_history",
"Url Klein": "url_small",
"Url RTMP": "url_rtmp",
"Url RTMP HD": "url_rtmp_hd",
"Url RTMP Klein": "url_rtmp_small",
"Url Untertitel": "url_subtitles",
"Website": "website",
"Zeit": "time",
"neu": "new",
}
class Item(TypedDict):
hash: str
channel: str
description: str
region: str
size: int
title: str
topic: str
website: str
new: bool
url_http: str | None
url_http_hd: str | None
url_http_small: str | None
url_subtitles: str
start: datetime
duration: timedelta
age: timedelta
downloaded: datetime | None
season: int | None
episode: int | None
def database_file(self, schema: str = "main") -> Path:
cursor = self.connection.cursor()
database_index = {db[1]: db[2] for db in cursor.execute("PRAGMA database_list")}
if database_index.get(schema):
return Path(database_index[schema])
else:
raise ValueError(f"Database file for {schema!r} not found.")
@property
def filmliste_version(self) -> int:
cursor = self.connection.cursor()
return int(cursor.execute("PRAGMA main.user_version;").fetchone()[0])
def initialize_filmliste(self) -> None:
logger.debug("Initializing Filmliste database in %r.", self.database_file("main"))
cursor = self.connection.cursor()
try:
cursor.execute(
"""
CREATE TABlE main.show (
hash TEXT,
channel TEXT,
description TEXT,
region TEXT,
size INTEGER,
title TEXT,
topic TEXT,
website TEXT,
new BOOLEAN,
url_http TEXT,
url_http_hd TEXT,
url_http_small TEXT,
url_subtitles TEXT,
start TIMESTAMP,
duration TIMEDELTA,
age TIMEDELTA,
season INTEGER,
episode INTEGER
);
"""
)
except sqlite3.OperationalError:
cursor.execute("DELETE FROM main.show")
self.connection.commit()
def update_filmliste(self) -> None:
logger.debug("Updating Filmliste database in %r.", self.database_file("main"))
cursor = self.connection.cursor()
cursor.execute("DELETE FROM main.show")
cursor.executemany(
"""
INSERT INTO main.show
VALUES (
:hash,
:channel,
:description,
:region,
:size,
:title,
:topic,
:website,
:new,
:url_http,
:url_http_hd,
:url_http_small,
:url_subtitles,
:start,
:duration,
:age,
:season,
:episode
)
""",
self._get_shows(),
)
cursor.execute(f"PRAGMA user_version={int(now.timestamp())}")
self.connection.commit()
def update_if_old(self) -> None:
database_age = now - datetime.fromtimestamp(self.filmliste_version, tz=utc_zone)
if database_age > self.filmliste_refresh_after:
logger.debug("Database age is %s (too old).", database_age)
self.update_filmliste()
else:
logger.debug("Database age is %s.", database_age)
@property
def history_version(self) -> int:
cursor = self.connection.cursor()
return int(cursor.execute("PRAGMA history.user_version;").fetchone()[0])
def initialize_history(self) -> None:
if self.history_version == 0:
logger.info("Initializing History database in %r.", self.database_file("main"))
cursor = self.connection.cursor()
cursor.execute(
"""
CREATE TABlE history.downloaded (
hash TEXT,
channel TEXT,
description TEXT,
region TEXT,
size INTEGER,
title TEXT,
topic TEXT,
website TEXT,
start TIMESTAMP,
duration TIMEDELTA,
downloaded TIMESTAMP,
season INTEGER,
episode INTEGER,
UNIQUE (hash)
);
"""
)
cursor.execute("PRAGMA history.user_version=2")
elif self.history_version == 1:
logger.info("Upgrading history database schema, adding columns for season and episode")
# manually control transactions to make sure this schema upgrade is atomic
old_isolation_level = self.connection.isolation_level
self.connection.isolation_level = None
cursor = self.connection.cursor()
cursor.execute("BEGIN")
cursor.execute("ALTER TABLE history.downloaded ADD COLUMN season INTEGER")
cursor.execute("ALTER TABLE history.downloaded ADD COLUMN episode INTEGER")
cursor.execute("PRAGMA history.user_version=2")
cursor.execute("COMMIT")
self.connection.isolation_level = old_isolation_level
def __init__(self, filmliste: Path, history: Path, filmliste_refresh_after: timedelta = timedelta(hours=3)) -> None:
logger.debug("Opening Filmliste database %r.", filmliste)
self.connection = sqlite3.connect(
filmliste.absolute().as_posix(),
detect_types=sqlite3.PARSE_DECLTYPES,
timeout=10,
)
logger.debug("Opening History database %r.", history)
self.connection.cursor().execute("ATTACH ? AS history", (history.as_posix(),))
self.connection.row_factory = sqlite3.Row
self.connection.create_function("REGEXP", 2, SqlRegexFunction())
self.filmliste_refresh_after = filmliste_refresh_after
if self.filmliste_version == 0:
self.initialize_filmliste()
if self.history_version != 2:
self.initialize_history()
@staticmethod
def _qualify_url(basis: str, extension: str) -> str | None:
if extension:
if "|" in extension:
offset, text = extension.split("|", maxsplit=1)
return basis[: int(offset)] + text
else:
return basis + extension
else:
return None
@staticmethod
def _duration_in_seconds(duration: str) -> int:
if duration:
match = re.match(r"(?P<h>\d+):(?P<m>\d+):(?P<s>\d+)", duration)
if match:
parts = match.groupdict()
return int(
timedelta(
hours=int(parts["h"]),
minutes=int(parts["m"]),
seconds=int(parts["s"]),
).total_seconds()
)
return 0
@staticmethod
def _show_hash(channel: str, topic: str, title: str, size: int, start: datetime) -> str:
h = hashlib.sha1()
h.update(channel.encode())
h.update(topic.encode())
h.update(title.encode())
h.update(str(size).encode())
with suppress(OSError, OverflowError):
# This can happen on some platforms. In this case simply ignore the timestamp for the hash.
h.update(str(start.timestamp()).encode())
return h.hexdigest()
@contextmanager
def _showlist(self, retries: int = 3) -> Iterator[BytesIO]:
while retries:
retries -= 1
try:
logger.debug("Opening database from %r.", FILMLISTE_URL)
response: http.client.HTTPResponse = urllib.request.urlopen(FILMLISTE_URL, timeout=9, cafile=CAFILE)
total_size = int(response.getheader("content-length") or 0)
with BytesIO() as buffer:
with progress_bar() as progress:
bar_id = progress.add_task(total=total_size, description="Downloading database")
while True:
data = response.read(CHUNK_SIZE)
if not data:
break
else:
progress.update(bar_id, advance=len(data))
buffer.write(data)
buffer.seek(0)
yield buffer
except urllib.error.HTTPError as e:
if retries:
logger.debug("Database download failed (%d more retries): %s" % (retries, e))
else:
logger.error(f"Database download failed (no more retries): {e}")
raise RetryLimitExceededError("retry limit reached, giving up")
time.sleep(10)
else:
break
def _get_shows(self) -> Iterable["Database.Item"]:
meta: dict[str, Any] = {}
header: list[str] = []
channel, topic, region = "", "", ""
with self._showlist() as showlist_archive, lzma.open(showlist_archive, "rb") as fh:
logger.debug("Loading database items.")
# this will loop one time over the whole json for the sole purpose of counting
# items to be able to render the progressbar below
items_count = 0
if not HIDE_PROGRESSBAR:
items_count = sum(1 for _ in ijson.kvitems(fh, ""))
fh.seek(0)
with progress_bar() as progress:
bar_id = progress.add_task(total=items_count, description="Reading database items")
for p in ijson.kvitems(fh, ""):
progress.update(bar_id, advance=1)
if not meta and p[0] == "Filmliste":
meta = {
# p[1][0] is local date, p[1][1] is gmt date
"date": datetime.strptime(p[1][1], "%d.%m.%Y, %H:%M").replace(tzinfo=utc_zone),
"crawler_version": p[1][2],
"crawler_agent": p[1][3],
"list_id": p[1][4],
}
elif p[0] == "Filmliste":
if not header:
header = p[1]
for i, h in enumerate(header):
header[i] = self.TRANSLATION.get(h, h)
elif p[0] == "X":
show = dict(zip(header, p[1]))
channel = show.get("channel") or channel
topic = show.get("topic") or topic
region = show.get("region") or region
if show["start"] and show["url"]:
title = show["title"]
size = int(show["size"]) if show["size"] else 0
# this should work on all platforms.
# See https://github.com/fnep/mtv_dl/issues/42 or https://bugs.python.org/issue36439
start = datetime.fromtimestamp(0, tz=utc_zone) + timedelta(seconds=int(show["start"]))
duration = timedelta(seconds=self._duration_in_seconds(show["duration"]))
season, episode = _guess_series_details(title)
yield {
"hash": self._show_hash(channel, topic, title, size, start.replace(tzinfo=None)),
"channel": channel,
"description": show["description"],
"region": region,
"size": size,
"title": title,
"topic": topic,
"website": show["website"],
"new": show["new"] == "true",
"url_http": str(show["url"]) or None,
"url_http_hd": self._qualify_url(show["url"], show["url_hd"]),
"url_http_small": self._qualify_url(show["url"], show["url_small"]),
"url_subtitles": show["url_subtitles"],
"start": start.replace(tzinfo=None),
"duration": duration,
"age": now - start,
"season": season,
"episode": episode,
"downloaded": None,
}
def add_to_downloaded(self, show: "Database.Item") -> None:
cursor = self.connection.cursor()
with suppress(sqlite3.IntegrityError):
cursor.execute(
"""
INSERT INTO history.downloaded
VALUES(
:hash,
:channel,
:description,
:region,
:size,
:title,
:topic,
:website,
:start,
:duration,
CURRENT_TIMESTAMP,
:season,
:episode
)
""",
show,
)
self.connection.commit()
def purge_downloaded(self) -> None:
cursor = self.connection.cursor()
# noinspection SqlWithoutWhere
cursor.execute("DELETE FROM history.downloaded")
self.connection.commit()
def remove_from_downloaded(self, show_hash: str) -> bool:
if not len(show_hash) >= 10:
logger.warning("Show hash to ambiguous %s.", show_hash)
return False
cursor = self.connection.cursor()
cursor.execute("SELECT hash FROM history.downloaded WHERE hash LIKE ?", (show_hash + "%",))
found_shows = [r[0] for r in cursor.fetchall()]
if not found_shows:
logger.warning("Could not remove %s (not found).", show_hash)
return False
elif len(found_shows) > 1:
logger.warning("Could not remove %s (to ambiguous).", show_hash)
return False
else:
cursor.execute("DELETE FROM history.downloaded WHERE hash=?", (found_shows[0],))
self.connection.commit()
logger.info("Removed %s from history.", show_hash)
return True
@staticmethod
def read_filter_sets(sets_file_path: Path | None, default_filter: list[str]) -> Iterator[list[str]]:
if sets_file_path:
with sets_file_path.expanduser().open("r+", encoding="utf-8") as set_fh:
for line in set_fh:
if line.strip() and not re.match(r"^\s*#", line):
yield default_filter + shlex.split(line)
else:
yield default_filter
def filtered(
self,
rules: list[str],
include_future: bool = False,
limit: int | None = None,
) -> Iterator["Database.Item"]:
where = []
arguments: list[Any] = []
if rules:
logger.debug("Applying filter: %s (limit: %s)", ", ".join(rules), limit)
for f in rules:
match = re.match(r"^(?P<field>\w+)(?P<operator>(?:=|!=|\+|-|\W+))(?P<pattern>.*)$", f)
if match:
field, operator, pattern = (
match.group("field"),
match.group("operator"),
match.group("pattern"),
) # type: str, str, Any
# replace odd names
field = {"url": "url_http"}.get(field, field)
if field not in (
"description",
"region",
"size",
"channel",
"topic",
"title",
"hash",
"url_http",
"duration",
"age",
"start",
"dow",
"hour",
"minute",
"season",
"episode",
):
raise ConfigurationError(f"Invalid field {field!r}.")
if operator == "=":
if field in ("description", "region", "size", "channel", "topic", "title", "hash", "url_http"):
where.append(f"show.{field} REGEXP ?")
arguments.append(str(pattern))
elif field in ("duration", "age"):
where.append(f"show.{field}=?")
arguments.append(durationpy.from_str(pattern).total_seconds())
elif field in ("start",):
where.append(f"show.{field}=?")
arguments.append(iso8601.parse_date(pattern).isoformat())
elif field in ("dow"):
where.append("CAST(strftime('%w', show.start) AS INTEGER)=?")
arguments.append(int(pattern))
elif field in ("hour"):
where.append("CAST(strftime('%H', datetime(show.start, 'localtime')) AS INTEGER)=?")
arguments.append(int(pattern))
elif field in ("minute"):
where.append("CAST(strftime('%M', show.start) AS INTEGER)=?")
arguments.append(int(pattern))
elif field in ("season", "episode"):
where.append(f"show.{field}=?")
arguments.append(int(pattern))
else:
raise ConfigurationError(f"Invalid operator {operator!r} for {field!r}.")
elif operator == "!=":
if field in ("description", "region", "size", "channel", "topic", "title", "hash", "url_http"):
where.append(f"show.{field} NOT REGEXP ?")
arguments.append(str(pattern))
elif field in ("duration", "age"):
where.append(f"show.{field}!=?")
arguments.append(durationpy.from_str(pattern).total_seconds())
elif field in ("start",):
where.append(f"show.{field}!=?")
arguments.append(iso8601.parse_date(pattern).isoformat())
elif field in ("dow"):
where.append("CAST(strftime('%w', show.start) AS INTEGER)!=?")
arguments.append(int(pattern))
elif field in ("hour"):
where.append("CAST(strftime('%H', datetime(show.start, 'localtime')) AS INTEGER)!=?")
arguments.append(int(pattern))
elif field in ("minute"):
where.append("CAST(strftime('%M', show.start) AS INTEGER)!=?")
arguments.append(int(pattern))
elif field in ("season", "episode"):
where.append(f"show.{field}!=?")
arguments.append(int(pattern))
else:
raise ConfigurationError(f"Invalid operator {operator!r} for {field!r}.")
elif operator == "-":
if field in ("duration", "age"):
where.append(f"show.{field}<=?")
arguments.append(durationpy.from_str(pattern).total_seconds())
elif field in ("size", "season", "episode"):
where.append(f"show.{field}<=?")
arguments.append(int(pattern))
elif field == "start":
where.append(f"show.{field}<=?")
arguments.append(iso8601.parse_date(pattern))
elif field in ("dow"):
where.append("CAST(strftime('%w', show.start) AS INTEGER)<=?")
arguments.append(int(pattern))
elif field in ("hour"):
where.append("CAST(strftime('%H', datetime(show.start, 'localtime')) AS INTEGER)<=?")
arguments.append(int(pattern))
elif field in ("minute"):
where.append("CAST(strftime('%M', show.start) AS INTEGER)<=?")
arguments.append(int(pattern))
else:
raise ConfigurationError(f"Invalid operator {operator!r} for {field!r}.")
elif operator == "+":
if field in ("duration", "age"):
where.append(f"show.{field}>=?")
arguments.append(durationpy.from_str(pattern).total_seconds())
elif field in ("size", "season", "episode"):
where.append(f"show.{field}>=?")
arguments.append(int(pattern))
elif field == "start":
where.append(f"show.{field}>=?")
arguments.append(iso8601.parse_date(pattern))
elif field in ("dow"):
where.append("CAST(strftime('%w', show.start) AS INTEGER)>=?")
arguments.append(int(pattern))
elif field in ("hour"):
where.append("CAST(strftime('%H', datetime(show.start, 'localtime')) AS INTEGER)>=?")
arguments.append(int(pattern))
elif field in ("minute"):
where.append("CAST(strftime('%M', show.start) AS INTEGER)>=?")
arguments.append(int(pattern))
else:
raise ConfigurationError(f"Invalid operator {operator!r} for {field!r}.")
else:
raise ConfigurationError(f"Invalid operator: {operator!r}")
else:
raise ConfigurationError("Property and filter rule expected to be separated by an operator.")
if not include_future:
where.append("datetime(show.start) < datetime('now')")
query = """
SELECT show.*, downloaded.downloaded
FROM main.show AS show
LEFT JOIN history.downloaded ON main.show.hash = history.downloaded.hash
"""
if where:
query += f"WHERE {' AND '.join(where)} "
query += "ORDER BY show.start "
if limit:
query += f"LIMIT {limit} "
cursor = self.connection.cursor()
cursor.execute(query, arguments)
for row in cursor:
yield dict(row) # type: ignore
def downloaded(self) -> Iterator["Database.Item"]:
cursor = self.connection.cursor()
cursor.execute(
"""
SELECT *
FROM history.downloaded
ORDER BY downloaded
"""
)
for row in cursor:
yield dict(row) # type: ignore
def show_table(shows: Iterable[Database.Item]) -> None:
def _escape_cell(title: str, obj: Any) -> str:
if title == "hash":
return str(obj)[:11]
if title in ["episode", "season"] and obj is None:
# return empty string rather than "None" in these columns
return ""
elif isinstance(obj, datetime):
obj = obj.replace(tzinfo=utc_zone)
with suppress(OSError, OverflowError):
obj = obj.astimezone(None)
return obj.isoformat()
elif isinstance(obj, timedelta):
return str(re.sub(r"(\d+)", r" \1", durationpy.to_str(obj, extended=True)).strip())
else:
return str(obj)
headers = [
"hash",
"channel",
"title",
"topic",
"size",
"start",
"duration",
"age",
"region",
"downloaded",
"season",
"episode",
]
# noinspection PyTypeChecker
table = Table(box=box.MINIMAL_DOUBLE_HEAD)
for h in headers:
table.add_column(h)
for row in shows:
table.add_row(*[_escape_cell(t, row.get(t)) for t in headers])
console.print(table)
class Downloader:
"""Download a show from the internet."""
Quality = Literal["url_http", "url_http_hd", "url_http_small"]
def __init__(self, show: Database.Item):
self.show = show
@property
def label(self) -> str:
return "{title!r} ({channel}, {topic!r}, {start}, {hash:.11})".format(**self.show)
def _download_files(self, destination_dir_path: Path, target_urls: list[str]) -> Iterable[Path]:
file_sizes = []
with progress_bar() as progress:
bar_id = progress.add_task(description=f"Downloading {self.label}")
for url in target_urls:
response: http.client.HTTPResponse = urllib.request.urlopen(url, timeout=60, cafile=CAFILE)
# determine file size for progressbar
file_sizes.append(int(response.getheader("content-length") or 0))
progress.update(bar_id, total=sum(file_sizes) / len(file_sizes) * len(target_urls))
# determine file name and destination
destination_file_path = destination_dir_path / escape_path(Path(url).name or "unknown")
# actual download
with destination_file_path.open("wb") as fh:
while True:
data = response.read(CHUNK_SIZE)
if not data:
break
else:
progress.update(bar_id, advance=len(data))
fh.write(data)
yield destination_file_path
def _create_strm_files(self, destination_dir_path: Path, target_urls: list[str]) -> Iterable[Path]:
for url in target_urls:
file_name = Path(url).with_suffix(".strm").name
destination_file_path = destination_dir_path / file_name
with destination_file_path.open("w") as fh:
fh.write(url)
yield destination_file_path
def _move_to_user_target(
self,
source_path: Path,
target: Path,
file_name: str,
file_extension: str,
media_type: str,
) -> Literal[False] | Path:
posix_target = target.as_posix()
if "{ext}" not in posix_target:
posix_target += "{ext}"
escaped_show_details = {k: escape_path(str(v)) for k, v in self.show.items()}
escaped_show_details["season"] = "00" if self.show["season"] is None else f"{self.show['season']:02d}"
escaped_show_details["episode"] = "00" if self.show["episode"] is None else f"{self.show['episode']:02d}"
destination_file_path = Path(
posix_target.format(
dir=Path.cwd().as_posix(),
filename=file_name,
ext=file_extension,
date=self.show["start"].date().isoformat(),
time=self.show["start"].strftime("%H-%M"),
**escaped_show_details,
)
)
destination_file_path.parent.mkdir(parents=True, exist_ok=True)
try:
shutil.move(source_path.as_posix(), destination_file_path)
except OSError as e:
logger.warning("Skipped %s. Moving %r to %r failed: %s", self.label, source_path, destination_file_path, e)
else:
logger.info("Saved %s %s to %r.", media_type, self.label, destination_file_path)
return destination_file_path
return False
@staticmethod
def _get_m3u8_segments(base_url: str, m3u8_file_path: Path) -> Iterator[dict[str, Any]]:
with m3u8_file_path.open("r+", encoding="utf-8") as fh:
segment: dict[str, Any] = {}
for line in fh:
if not line:
continue
elif line.startswith("#EXT-X-STREAM-INF:"):
# see http://archive.is/Pe9Pt#section-4.3.4.2
segment = {m.group(1).lower(): m.group(2).strip() for m in re.finditer(r"([A-Z-]+)=([^,]+)", line)}
for key, value in segment.items():
if value[0] in ('"', "'") and value[0] == value[-1]:
segment[key] = value[1:-1]
else:
with suppress(ValueError):
segment[key] = int(value)
elif not line.startswith("#"):
segment["url"] = urllib.parse.urljoin(base_url, line.strip())
yield segment
segment = {}
def _download_hls_target(
self,
m3u8_segments: list[dict[str, Any]],
temp_dir_path: Path,
base_url: str,
quality_preference: tuple[str, str, str],
) -> Path:
hls_index_segments = sorted(
[s for s in m3u8_segments if "mp4a" not in s.get("codecs", {}) and s.get("bandwidth")],
key=lambda s: s.get("bandwidth", 0),
)
# select the wanted stream
if quality_preference[0] == "_hd":
designated_index_segment = hls_index_segments[-1]
elif quality_preference[0] == "_small":
designated_index_segment = hls_index_segments[0]
else:
designated_index_segment = hls_index_segments[len(hls_index_segments) // 2]
designated_index_file = next(iter(self._download_files(temp_dir_path, [designated_index_segment["url"]])))
logger.debug(
"Selected HLS bandwidth is %d (available: %s).",
designated_index_segment["bandwidth"],
", ".join(str(s["bandwidth"]) for s in hls_index_segments),
)
# get stream segments
hls_target_segments = list(self._get_m3u8_segments(base_url, designated_index_file))
hls_target_files = self._download_files(temp_dir_path, list(s["url"] for s in hls_target_segments))
logger.debug("%d HLS segments to download.", len(hls_target_segments))
# download and join the segment files
with NamedTemporaryFile(mode="wb", prefix=".tmp", dir=temp_dir_path, delete=False) as out_fh:
temp_file_path = Path(temp_dir_path) / out_fh.name
for segment_file_path in hls_target_files:
with segment_file_path.open("rb") as in_fh:
out_fh.write(in_fh.read())
# delete the segment file immediately to save disk space
segment_file_path.unlink()
return temp_file_path
def _download_m3u8_target(self, m3u8_segments: list[dict[str, Any]], temp_dir_path: Path) -> Path:
# get segments
hls_target_files = self._download_files(temp_dir_path, list(s["url"] for s in m3u8_segments))
logger.debug("%d m3u8 segments to download.", len(m3u8_segments))
# download and join the segment files
with NamedTemporaryFile(mode="wb", prefix=".tmp", dir=temp_dir_path, delete=False) as out_fh:
temp_file_path = Path(temp_dir_path) / out_fh.name
for segment_file_path in hls_target_files:
with segment_file_path.open("rb") as in_fh:
out_fh.write(in_fh.read())
# delete the segment file immediately to save disk space
segment_file_path.unlink()
return temp_file_path
@staticmethod
def _convert_subtitles_xml_to_srt(subtitles_xml_path: Path) -> Path:
subtitles_srt_path = subtitles_xml_path.parent / (subtitles_xml_path.stem + ".srt")
soup = BeautifulSoup(subtitles_xml_path.read_text(encoding="utf-8"), "html.parser")
colour_to_rgb = {
"textBlack": "#000000",
"textRed": "#FF0000",
"textGreen": "#00FF00",
"textYellow": "#FFFF00",
"textBlue": "#0000FF",
"textMagenta": "#FF00FF",
"textCyan": "#00FFFF",
"textWhite": "#FFFFFF",
"S1": "#000000",
"S2": "#FF0000",
"S3": "#00FF00",
"S4": "#FFFF00",
"S5": "#0000FF",
"S6": "#FF00FF",
"S7": "#00FFFF",
"S8": "#FFFFFF",
}
def font_colour(text: str, colour: str) -> str:
return f'<font color="{colour_to_rgb[colour]}">{text}</font>\n'
def convert_time(t: str) -> str:
t = t.replace(".", ",")
t = re.sub(r"^1", "0", t)
return t
with subtitles_srt_path.open("w", encoding="utf-8") as srt:
for p_tag in soup.findAll("tt:p"):
# noinspection PyBroadException
try:
srt.write(str(int(re.sub(r"\D", "", p_tag.get("xml:id"))) + 1) + "\n")
srt.write(f"{convert_time(p_tag['begin'])} --> {convert_time(p_tag['end'])}\n")
for span_tag in p_tag.findAll("tt:span"):
srt.write(font_colour(span_tag.text, span_tag.get("style")).replace("&apos", "'"))
srt.write("\n")
except Exception as e:
logger.debug("Unexpected data in subtitle xml tag %r: %s", p_tag, e)
return subtitles_srt_path
def download(
self,
quality: tuple[Quality, Quality, Quality],
target: Path,
*,
include_subtitles: bool = True,
include_nfo: bool = True,
set_file_modification_date: bool = False,
create_strm_files: bool = False,
series_mode: bool = False,
) -> Path | None:
temp_path = Path(tempfile.mkdtemp(prefix=".tmp"))
try:
# show url based on quality preference
show_url = self.show[quality[0]] or self.show[quality[1]] or self.show[quality[2]]