-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathyt-backup.py
1855 lines (1685 loc) · 91 KB
/
yt-backup.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
# yt-backup command line utility to backup youtube channels easily
# Copyright (C) 2020 w0d4
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import argparse
import googleapiclient.discovery
import googleapiclient.errors
import json
import logging
import os
import pickle
import re
import requests
import shutil
import signal
import sqlalchemy
import subprocess
import sys
import time
from datetime import datetime
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from pathlib import Path
from random import randint
from sqlalchemy import func, or_
from time import sleep
from base import Session, engine, Base
from channel import Channel
from operation import Operation
from playlist import Playlist
from statistic import Statistic
from video import Video
api_service_name = "youtube"
api_version = "v3"
client_secrets_file = "client_secret.json"
SCOPES = ["https://www.googleapis.com/auth/youtube.readonly"]
Base.metadata.create_all(engine)
session = Session()
parser = argparse.ArgumentParser(description='yt-backup')
parser.add_argument("mode", action="store", type=str, help="Valid options: add_channel, get_playlists, get_video_infos, download_videos, run, toggle_channel_download, generate_statistics, verify_offline_videos, verify_channels, list_playlists, modify_playlist, modify_channel, add_video")
parser.add_argument("--channel_id", action="store", type=str, help="Defines a channel ID to work on. Required for modes: add_channel")
parser.add_argument("--username", action="store", type=str, help="Defines a channel name to work on. Required for modes: add_channel")
parser.add_argument("--playlist_id", action="store", type=str, help="Defines a playlist ID to work on. Optional for modes: get_video_infos, download_videos")
parser.add_argument("--playlist_name", action="store", type=str, help="Defines a playlist name. Optional for modes: add_playlist, modify_playlist")
parser.add_argument("--download_from", action="store", type=str, help="Defines a date from which videos should be downloaded for a playlist. Format: yyyy-mm-dd hh:mm:ss or all")
parser.add_argument("--retry-403", action="store_true", help="If this flag ist set, yt-backup will retry to download videos which were marked with 403 error during initial download.")
parser.add_argument("--statistics", action="store", type=str, help="Comma seperated list which statistics should be collected during statistics run. Supported types: archive_size,videos_monitored,videos_downloaded")
parser.add_argument("--enabled", action="store_true", help="Switch to control all modes which enables or disables things. Required for modes: toggle_channel_download")
parser.add_argument("--disabled", action="store_true", help="Switch to control all modes which enables or disables things. Required for modes: toggle_channel_download")
parser.add_argument("--monitored", action="store", type=int, help="Can be 1 or 0. Is used in modify_playlist context.")
parser.add_argument("--ignore_429_lock", action="store_true", help="Ignore whether an IP was 429 blocked and continue downloading with it.")
parser.add_argument("--reset_quota_exceeded_state", action="store_true", help="Resets the quota exceeded state in case something gone wrong during calculation")
parser.add_argument("--reset_429_state", action="store_true", help="Resets the last 429 state in case something gone wrong with 429 detection")
parser.add_argument("--all_meta", action="store_true", help="When adding a channel with --channel-id, all playlists and videos will be downloaded automatically.")
parser.add_argument("--video_id", action="store", type=str, help="When adding a video with add_video, this must be added as option")
parser.add_argument("--video_title", action="store", type=str, help="When adding a video with add_video, this could be added as option")
parser.add_argument("--video_upload_date", action="store", type=str, help="When adding a video with add_video, this could be added as option")
parser.add_argument("--video_description", action="store", type=str, help="When adding a video with add_video, this could be added as option")
parser.add_argument("--downloaded", action="store", type=str, help="When adding a video with add_video, this can be added as option")
parser.add_argument("--resolution", action="store", type=str, help="When adding a video with add_video, this can be added as option")
parser.add_argument("--size", action="store", type=str, help="When adding a video with add_video, this can be added as option")
parser.add_argument("--duration", action="store", type=str, help="When adding a video with add_video, this can be added as option")
parser.add_argument("--video_status", action="store", type=str, help="When adding a video with add_video, this can be added as option")
parser.add_argument("--print_quota", action="store_true", help="Print used quota information during run.")
parser.add_argument("--force_refresh", action="store_true", help="Forces the update of video data of playlists.")
parser.add_argument("--debug", action="store_true")
parser.add_argument("-V", action="version", version="%(prog)s 0.9.5")
args = parser.parse_args()
logger = logging.getLogger('yt-backup')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
fl = logging.FileHandler("/tmp/yt-backup.log".format())
if args.debug:
ch.setLevel(logging.DEBUG)
fl.setLevel(logging.DEBUG)
else:
ch.setLevel(logging.INFO)
fl.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
fl.setFormatter(formatter)
logger.addHandler(ch)
logger.addHandler(fl)
try:
with open('config.json', 'r') as f:
config = json.load(f)
except json.decoder.JSONDecodeError:
logger.error("Cannot parse the config.json file. Please double check your syntax.")
sys.exit(10)
# save used quota for every run
used_quota_this_run: int = 0
# Psave the parsed arguments for easier use
mode = args.mode
channel_id = args.channel_id
playlist_id = args.playlist_id
username = args.username
statistics = args.statistics
retry_403 = args.retry_403
enabled = args.enabled
disabled = args.disabled
ignore_429_lock = args.ignore_429_lock
download_from = args.download_from
all_meta = args.all_meta
video_id = args.video_id
downloaded = args.downloaded
resolution = args.resolution
size = args.size
duration = args.duration
param_video_status = args.video_status
monitored = args.monitored
playlist_name = args.playlist_name
video_title = args.video_title
video_description = args.video_description
video_upload_date = args.video_upload_date
print_quota = args.print_quota
force_refresh = args.force_refresh
reset_quota_exceeded_state = args.reset_quota_exceeded_state
reset_429_state = args.reset_429_state
# define video status
video_status = {"offline": 0, "online": 1, "http_403": 2, "hate_speech": 3, "unlisted": 4}
def get_current_timestamp():
ts = time.time()
return ts
def add_quota(quota_used: int):
global used_quota_this_run
used_quota_this_run = used_quota_this_run + quota_used
if print_quota:
logger.info("This API call costed " + str(quota_used) + " API quota. Totally used " + str(used_quota_this_run) + " this run.")
def persist_quota():
global used_quota_this_run
if used_quota_this_run == 0:
return None
stat_quota = Statistic()
stat_quota.statistic_type = "used_quota"
stat_quota.statistic_date = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
stat_quota.statistic_value = str(used_quota_this_run)
session.add(stat_quota)
session.commit()
if print_quota:
logger.info("Used " + str(used_quota_this_run) + " API Quota totally this run.")
print_quota_last_24_hours()
def commit_with_retry():
try:
session.commit()
except sqlalchemy.exc.OperationalError as e:
if "2006" in str(e):
try:
logger.error("Connection to database got lost. Trying to reconnect...")
sleep(3)
session.commit()
except:
raise
def print_quota_last_24_hours():
logger.debug("Will print the quota used in the last 24h if the user wants to.")
with engine.connect() as con:
try:
rs = con.execute("SELECT SUM(statistic_value) AS used_quota_last_24h FROM statistics WHERE statistics.statistic_type = 'used_quota' AND statistics.statistic_date > DATE_SUB(NOW(), INTERVAL 1 DAY);")
for row in rs:
logger.info("Used quota during last 24h: " + str(row[0]))
except:
logger.error("Problem during getting quota info from database.")
def signal_handler(sig, frame):
logger.info('Catched Ctrl+C!')
set_status("aborted")
if os.path.exists(config["base"]["download_lockfile"]):
logger.debug("Removing download lockfile")
os.remove(config["base"]["download_lockfile"])
sys.exit(0)
def sanititze_string(name: str):
if "/" in name:
name = name.replace('/', '_')
if "\"" in name:
name = name.replace('"', '\\"')
if "[" in name:
name = name.replace("[", "\\[")
if "]" in name:
name = name.replace("]", "\\]")
return name
def log_operation(duration, operation_type, operation_description):
operation = Operation()
operation.duration = duration
operation.operation_type = operation_type
operation.operation_description = operation_description
operation.operation_date = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
session.add(operation)
session.commit()
def set_status(new_status):
current_status = session.query(Statistic).filter(Statistic.statistic_type == "status").scalar()
if current_status is None:
current_status = Statistic()
current_status.statistic_type = "status"
current_status.statistic_date = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
current_status.statistic_value = new_status
session.add(current_status)
session.commit()
def set_currently_downloading(video_name):
currently_downloading = session.query(Statistic).filter(Statistic.statistic_type == "currently_downloading").scalar()
if currently_downloading is None:
currently_downloading = Statistic()
currently_downloading.statistic_type = "currently_downloading"
currently_downloading.statistic_date = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
currently_downloading.statistic_value = video_name
session.add(currently_downloading)
session.commit()
def set_http_429_state():
http_429_state = session.query(Statistic).filter(Statistic.statistic_type == "http_429_state").scalar()
if http_429_state is None:
http_429_state = Statistic()
http_429_state.statistic_type = "http_429_state"
http_429_state.statistic_date = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
http_429_state.statistic_value = get_current_ytdl_ip()
session.add(http_429_state)
session.commit()
def clear_http_429_state():
http_429_state = session.query(Statistic).filter(Statistic.statistic_type == "http_429_state").scalar()
if http_429_state is None:
http_429_state = Statistic()
http_429_state.statistic_type = "http_429_state"
http_429_state.statistic_date = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
http_429_state.statistic_value = ""
session.add(http_429_state)
session.commit()
def reset_http_429_state():
http_429_state = session.query(Statistic).filter(Statistic.statistic_type == "http_429_state").scalar()
if http_429_state is None:
return None
session.delete(http_429_state)
session.commit()
logger.info("HTTP 429 state has been deleted.")
def get_http_429_state():
http_429_state = session.query(Statistic).filter(Statistic.statistic_type == "http_429_state").scalar()
return http_429_state
def check_429_lock():
# if the ignore_429_lock flag is set, dont't check anything, just continue
if ignore_429_lock:
return False
http_429_state = get_http_429_state()
if http_429_state is None:
return False
else:
ytdl_ip_of_last_429 = http_429_state.statistic_value
logger.debug("Calculate difference since last 429")
if ytdl_ip_of_last_429 != get_current_ytdl_ip():
return False
date_of_last_429 = datetime.strptime(str(http_429_state.statistic_date), '%Y-%m-%d %H:%M:%S')
current_time = datetime.now()
delta = current_time - date_of_last_429
logger.debug("Delta seconds since last 429: " + str(delta.total_seconds()))
if delta.total_seconds() < 48 * 60 * 60:
return True
else:
clear_http_429_state()
return False
def set_quota_exceeded_state():
quota_exceeded_state = session.query(Statistic).filter(Statistic.statistic_type == "quota_exceeded_state").scalar()
if quota_exceeded_state is None:
quota_exceeded_state = Statistic()
quota_exceeded_state.statistic_type = "quota_exceeded_state"
quota_exceeded_state.statistic_date = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
quota_exceeded_state.statistic_value = "Quota exceeded"
session.add(quota_exceeded_state)
session.commit()
def clear_quota_exceeded_state():
quota_exceeded_state = session.query(Statistic).filter(Statistic.statistic_type == "quota_exceeded_state").scalar()
if quota_exceeded_state is None:
return None
session.delete(quota_exceeded_state)
session.commit()
def get_quota_exceeded_state():
quota_exceeded_state = session.query(Statistic).filter(Statistic.statistic_type == "quota_exceeded_state").scalar()
return quota_exceeded_state
def check_quota_exceeded_state():
quota_exceeded_state = get_quota_exceeded_state()
if quota_exceeded_state is None:
return False
else:
logger.debug("Calculate difference since last quota_exceeded error")
date_of_last_quota_exceeded_state = datetime.strptime(str(quota_exceeded_state.statistic_date), '%Y-%m-%d %H:%M:%S')
current_time = datetime.now()
delta = current_time - date_of_last_quota_exceeded_state
logger.debug("Delta seconds since last quota_exceeded_state: " + str(delta.total_seconds()))
if delta.total_seconds() < 48 * 60 * 60:
return True
else:
clear_quota_exceeded_state()
return False
def get_current_ytdl_ip():
for i in range(0, 100):
try:
if config["youtube-dl"]["proxy"] != "":
proxies = {"http": config["youtube-dl"]["proxy"], "https": config["youtube-dl"]["proxy"]}
r = requests.get("https://ipinfo.io", proxies=proxies)
else:
r = requests.get("https://ipinfo.io")
answer = json.loads(str(r.text))
current_ytdl_ip = answer["ip"]
except ConnectionError:
current_ytdl_ip = "0.0.0.0"
sleep(10)
continue
finally:
remove_download_lockfile()
break
return current_ytdl_ip
def log_statistic(statistic_type, statistic_value):
statistic = Statistic()
statistic.statistic_type = statistic_type
statistic.statistic_value = statistic_value
statistic.statistic_date = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
session.add(statistic)
session.commit()
def get_playlist_ids_from_google(local_channel_id):
# Check for exceeded google quota
if check_quota_exceeded_state():
logger.error("Cannot proceed with getting data from youtube API. Quota exceeded.")
return None
youtube = googleapiclient.discovery.build(api_service_name, api_version, credentials=get_google_api_credentials())
logger.debug("Excuting youtube API call for getting playlists")
request = youtube.channels().list(part="contentDetails", id=local_channel_id)
try:
response = request.execute()
add_quota(3)
except googleapiclient.errors.HttpError as error:
if "The request cannot be completed because you have exceeded your" in str(error):
set_quota_exceeded_state()
return None
return response
def get_playlist_name_from_google(local_playlist_id):
# Check for exceeded google quota
if check_quota_exceeded_state():
logger.error("Cannot proceed with getting data from youtube API. Quota exceeded.")
return None
youtube = googleapiclient.discovery.build(api_service_name, api_version, credentials=get_google_api_credentials())
logger.debug("Excuting youtube API call for getting playlists")
request = youtube.playlists().list(part="snippet", id=local_playlist_id)
try:
response = request.execute()
add_quota(3)
except googleapiclient.errors.HttpError as error:
if "The request cannot be completed because you have exceeded your" in str(error):
set_quota_exceeded_state()
return None
return response
def is_headless_machine():
while "the answer is invalid":
reply = str(input("Are you working on a headless machine?" + ' (Y/N): ')).lower().strip()
if reply[:1] == 'y':
return True
if reply[:1] == 'n':
return False
def get_google_api_credentials():
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(client_secrets_file, SCOPES)
if is_headless_machine():
creds = flow.run_console(authorization_prompt_message='Please visit this URL to authorize this application: {url}', authorization_code_message='Enter the authorization code: ')
else:
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
return creds
def get_channel_playlists(local_channel_id, monitored=1):
global playlist_id
logger.debug("Getting playlist IDs")
google_response = get_playlist_ids_from_google(local_channel_id)
if google_response is None:
logger.error("Got no answer from google. I will skip this.")
return None
for playlist in google_response['items'][0]['contentDetails']['relatedPlaylists']:
if playlist not in ["watchHistory", "watchLater", "favorites", "likes"]:
playlist_id = str(google_response['items'][0]['contentDetails']['relatedPlaylists'][playlist])
if session.query(Playlist).filter(Playlist.playlist_id == playlist_id).scalar() is not None:
logger.debug("Playlist is already in database")
continue
logger.debug(str("Found playlist " + playlist + " " + google_response['items'][0]['contentDetails']['relatedPlaylists'][playlist]))
playlist_obj = Playlist()
playlist_obj.playlist_id = str(google_response['items'][0]['contentDetails']['relatedPlaylists'][playlist])
playlist_obj.playlist_name = str(playlist)
playlist_obj.channel_id = session.query(Channel).filter(Channel.channel_id == local_channel_id).scalar().id
playlist_obj.monitored = monitored
session.add(playlist_obj)
session.commit()
if download_from is not None:
modify_playlist()
def get_channel_name_and_country_from_google(local_channel_id):
# Check for exceeded google quota
channel_name = None
channel_country = None
if check_quota_exceeded_state():
logger.error("Cannot proceed with getting data from youtube API. Quota exceeded.")
return None
youtube = googleapiclient.discovery.build(api_service_name, api_version, credentials=get_google_api_credentials())
logger.debug("Excuting youtube API call for getting channel name and country")
request = youtube.channels().list(part="brandingSettings", id=local_channel_id)
try:
response = request.execute()
add_quota(3)
except googleapiclient.errors.HttpError as error:
if "The request cannot be completed because you have exceeded your" in str(error):
set_quota_exceeded_state()
return None
try:
channel_name = str(response["items"][0]["brandingSettings"]["channel"]["title"])
except KeyError:
logger.error("No channel with this id could be found on youtube.")
return None
try:
channel_country = str(response["items"][0]["brandingSettings"]["channel"]["country"])
except KeyError:
logger.warning("This channel has no origin country information.")
logger.debug("Got channel name " + channel_name + " from google.")
return {"channel_name": channel_name, "channel_country": channel_country}
def get_channel_id_from_google(local_username):
# Check for exceeded google quota
if check_quota_exceeded_state():
logger.error("Cannot proceed with getting data from youtube API. Quota exceeded.")
return None
global channel_id
youtube = googleapiclient.discovery.build(api_service_name, api_version, credentials=get_google_api_credentials())
logger.debug("Excuting youtube API call for getting channel id by username")
request = youtube.channels().list(part="id", forUsername=local_username)
try:
response = request.execute()
add_quota(1)
except googleapiclient.errors.HttpError as error:
if "The request cannot be completed because you have exceeded your" in str(error):
set_quota_exceeded_state()
return None
logger.debug(str(response))
channel_id = str(response["items"][0]["id"])
logger.debug("Got channel name " + channel_id + " from google.")
return channel_id
def add_channel(local_channel_id):
# log start time
start_time = get_current_timestamp()
# Check if the channel is already in database
channel = session.query(Channel.channel_id).filter(Channel.channel_id == local_channel_id).scalar()
if channel is not None:
logger.error("This channel is already in database.")
return None
# create channel object
channel = Channel()
# get Channel details from youtube, in case no user defined name was detected
channel.channel_id = local_channel_id
if username is not None:
logger.info("Found custom channel name " + str(username) + ". Will not request official channel name from youtube API")
channel.channel_name = str(username)
else:
channel_name_and_country = get_channel_name_and_country_from_google(local_channel_id)
logger.debug(str(channel_name_and_country))
if channel_name_and_country is None:
logger.error("Got no answer from google. I will skip this.")
return None
channel_name = channel_name_and_country['channel_name']
channel_country = channel_name_and_country['channel_country']
if channel_name is None:
logger.error("Got no answer from google. I will skip this.")
return None
if "channel_naming" in config["base"] and config["base"]["channel_naming"] != "":
logger.debug("Found channel name template in config")
channel.channel_name = str(config["base"]["channel_naming"]).replace("%channel_name", channel_name).replace(
("%channel_id"), local_channel_id)
else:
channel.channel_name = channel_name
channel.channel_country = channel_country
# secure channel name
if "/" in channel.channel_name:
channel.channel_name = channel.channel_name.replace("/", "_")
logger.info("Replaced all / characters in channel name with _, since / is not a valid character in file and folder names.")
# add channel to channel table
if session.query(Channel).filter(Channel.channel_id == local_channel_id).scalar() is None:
logger.info("Added Channel " + channel.channel_name + " to database.")
try:
logger.info("Channel has origin country " + channel.channel_country)
except TypeError:
pass
session.add(channel)
session.commit()
else:
logger.info("Channel is already in database")
end_time = get_current_timestamp()
log_operation(end_time - start_time, "add_channel", "Added channel " + channel.channel_name)
add_uploads_playlist(channel)
if all_meta:
get_video_infos()
def add_uploads_playlist(channel):
logger.info("Adding default playlist uploads to the channel.")
channels_upload_playlist_id = list(channel.channel_id)
channels_upload_playlist_id[1] = 'U'
playlist = Playlist()
playlist.playlist_id = "".join(channels_upload_playlist_id)
logger.debug('uploads playlist ID is ' + str(playlist.playlist_id))
playlist.channel_id = channel.id
playlist.playlist_name = 'uploads'
if mode == "add_video":
playlist.monitored = 0
else:
playlist.monitored = 1
session.add(playlist)
session.commit()
def get_video_infos_for_one_video(video_id):
# Check for exceeded google quota
if check_quota_exceeded_state():
logger.error("Cannot proceed with getting data from youtube API. Quota exceeded.")
return None
youtube = googleapiclient.discovery.build(api_service_name, api_version, credentials=get_google_api_credentials())
logger.debug("Excuting youtube API call for getting channel id by video_id")
request = youtube.videos().list(part="snippet", id=video_id)
try:
response = request.execute()
add_quota(3)
except googleapiclient.errors.HttpError as error:
if "The request cannot be completed because you have exceeded your" in str(error):
set_quota_exceeded_state()
return None
return response
def get_geoblock_list_for_one_video(video_id):
# Check for exceeded google quota
if check_quota_exceeded_state():
logger.error("Cannot proceed with getting data from youtube API. Quota exceeded.")
return None
youtube = googleapiclient.discovery.build(api_service_name, api_version, credentials=get_google_api_credentials())
logger.debug("Excuting youtube API call for getting channel id by video_id")
request = youtube.videos().list(part="contentDetails", id=video_id)
try:
response = request.execute()
add_quota(3)
except googleapiclient.errors.HttpError as error:
if "The request cannot be completed because you have exceeded your" in str(error):
set_quota_exceeded_state()
return None
geoblock_list = []
logger.debug(str(response))
try:
for entry in response["items"][0]["contentDetails"]["regionRestriction"]["blocked"]:
geoblock_list.append(str(entry))
logger.debug("Found " + str(entry) + " in geoblock list of video " + str(geoblock_list) + ".")
return geoblock_list
except KeyError:
logger.error("No blocked countries were found.")
return None
def add_video(video_id, downloaded="", resolution="", size="", duration="", local_video_status="online"):
if video_id is None:
logger.error('You have to supply at least the video id with --video_id')
return None
video = session.query(Video).filter(Video.video_id == video_id).scalar()
if video is not None:
logger.error(f'Video with ID {video_id} is already in database. Cannot add it a second time.')
return None
video = Video()
video.video_id = video_id
if local_video_status != "offline":
video_infos = get_video_infos_for_one_video(video_id)
logger.debug(str(video_infos))
if local_video_status == "offline" or video_infos["pageInfo"]["totalResults"] == 0:
logger.error("Video with ID " + video_id + " is not available on youtube anymore")
local_video_status = "offline"
if video_title is None:
logger.error('When adding offline videos, a title must be specified with --video_title.')
return None
if video_description is None:
logger.error('When adding offline videos, a description must be specified with --video_description.')
return None
if playlist_id is None:
logger.error('When adding offline videos, a channel_id must be specified with --playlist_id.')
return None
title = video_title
description = video_description
upload_date = video_upload_date
video_playlist = session.query(Playlist.id).filter(Playlist.playlist_id == playlist_id)
else:
local_channel_id = str(video_infos["items"][0]["snippet"]["channelId"])
title = str(video_infos["items"][0]["snippet"]["title"])
description = str(video_infos["items"][0]["snippet"]["description"])
upload_date = str(video_infos["items"][0]["snippet"]["publishedAt"])
upload_date = datetime.strptime(str(upload_date)[0:19], '%Y-%m-%dT%H:%M:%S')
add_channel(local_channel_id)
internal_channel_id = session.query(Channel.id).filter(Channel.channel_id == local_channel_id).scalar()
video_playlist = session.query(Playlist.id).filter(Playlist.channel_id == internal_channel_id).filter(Playlist.playlist_name == "uploads")
video.playlist = video_playlist
video.title = title
video.description = description
video.downloaded = downloaded
video.resolution = resolution
video.size = size
video.runtime = duration
if local_video_status is None:
video.online = video_status["online"]
else:
video.online = video_status[local_video_status]
video.download_required = 1
video.upload_date = upload_date
session.add(video)
session.commit()
logger.info(f'Added video {video.video_id} - {video.title} to database.')
def add_user(local_username):
local_channel_id = get_channel_id_from_google(local_username)
add_channel(local_channel_id)
def get_playlists():
global playlist_id
channels = session.query(Channel).filter(Channel.offline == None)
save_playlist_id = playlist_id
if channel_id is not None:
channels = channels.filter(Channel.channel_id == channel_id)
for channel in channels:
start_time = get_current_timestamp()
logger.info("Getting Playlists for " + str(channel.channel_name))
get_channel_playlists(channel.channel_id)
end_time = get_current_timestamp()
log_operation(end_time - start_time, "get_playlists", "Got playlists for channel " + str(channel.channel_name))
playlist_id = save_playlist_id
if all_meta:
get_video_infos()
def get_videos_from_playlist_from_google(local_playlist_id, next_page_token):
# Check for exceeded google quota
if check_quota_exceeded_state():
logger.error("Cannot proceed with getting data from youtube API. Quota exceeded.")
return None
youtube = googleapiclient.discovery.build(api_service_name, api_version, credentials=get_google_api_credentials())
logger.debug("Excuting youtube API call for getting videos")
if next_page_token is None:
request = youtube.playlistItems().list(part="snippet,contentDetails", maxResults=50, playlistId=local_playlist_id)
else:
request = youtube.playlistItems().list(part="snippet,contentDetails", maxResults=50, playlistId=local_playlist_id, pageToken=next_page_token)
response = ""
try:
response = request.execute()
add_quota(5)
except googleapiclient.errors.HttpError as error:
if "The request cannot be completed because you have exceeded your" in str(error):
set_quota_exceeded_state()
return None
return response
def get_changed_playlists(playlists):
i = 0
j = 0
google_api_id_limit = 50
playlist_ids_to_check = ""
changed_playlists = []
while i < len(playlists):
if j != 0:
playlist_ids_to_check = playlist_ids_to_check + ","
playlist_ids_to_check = str(playlist_ids_to_check + playlists[i].playlist_id)
logger.debug("Found playlist ID " + str(playlists[i].playlist_id) + " in playlists.")
i += 1
j += 1
if j == google_api_id_limit or i == len(playlists):
j = 0
youtube = googleapiclient.discovery.build(api_service_name, api_version, credentials=get_google_api_credentials())
request = youtube.playlists().list(part="contentDetails", id=playlist_ids_to_check)
try:
response = request.execute()
add_quota(3)
except googleapiclient.errors.HttpError as error:
if "The request cannot be completed because you have exceeded your" in str(error):
set_quota_exceeded_state()
return None
logger.debug("Calling youtube API for playlist etags")
logger.debug("Got " + str(len(response["items"])) + " entries back")
logger.debug(str(response))
for entry in response["items"]:
plid = entry["id"]
etag = entry["etag"]
logger.debug("etag from google for playlist " + str(plid) + " is: " + str(etag))
playlist = session.query(Playlist).filter(Playlist.playlist_id == plid).scalar()
channel_name = session.query(Channel.channel_name).filter(Channel.id == playlist.channel_id).scalar()
if force_refresh:
logger.info("--force_refresh is set. Deleting etag on playlist " + str(playlist.playlist_name) + " of channel " + str(channel_name))
playlist.etag = None
else:
logger.debug("etag in database for playlist " + str(plid) + " is: " + str(etag))
if playlist.etag != etag:
playlist.etag = etag
logger.debug("Updated etag of playlist " + str(playlist.playlist_id) + " to " + str(etag))
changed_playlists.append(playlist)
session.add(playlist)
else:
logger.info("playlist " + str(playlist.playlist_name) + " of channel " + str(channel_name) + " has not changed since last check.")
playlist_ids_to_check = ""
session.commit()
num_changed_playlists = len(changed_playlists)
logger.info(f'{num_changed_playlists} playlists changed.')
return changed_playlists
def get_video_infos():
playlists = session.query(Playlist).filter(Playlist.monitored == 1)
if channel_id is not None:
internal_channel_id = session.query(Channel.id).filter(Channel.channel_id == channel_id)
playlists = playlists.filter(Playlist.channel_id == internal_channel_id)
if playlist_id is not None:
playlists = playlists.filter(Playlist.playlist_id == playlist_id)
changed_playlists = get_changed_playlists(playlists.all())
for playlist in changed_playlists:
parsed_from_api = 0
start_time = get_current_timestamp()
videos = []
videos_to_check_against = []
channel_name = session.query(Channel.channel_name).filter(Channel.id == playlist.channel_id).scalar()
logger.info("Getting all video metadata for playlist " + playlist.playlist_name + " for channel " + str(channel_name))
results = []
try:
result = get_videos_from_playlist_from_google(playlist.playlist_id, None)
if result is None:
logger.error("Got no answer from google. I will skip this.")
return None
except googleapiclient.errors.HttpError:
logger.error("Playlist " + playlist.playlist_name + " in Channel " + channel_name + " is not available")
continue
results.append(result)
videos_in_playlist = result["pageInfo"]["totalResults"]
logger.debug("Videos in Playlist: " + str(videos_in_playlist))
next_page_token = None
try:
next_page_token = str(result["nextPageToken"])
logger.debug("Next page token: " + next_page_token)
except KeyError:
logger.debug("Playlist " + playlist.playlist_name + " in Channel " + channel_name + " has only one page.")
while next_page_token is not None:
result = get_videos_from_playlist_from_google(playlist.playlist_id, next_page_token)
if result is None:
logger.error("Got no answer from google. I will skip this.")
return None
results.append(result)
try:
next_page_token = str(result["nextPageToken"])
except:
break
logger.debug("Next page token: " + next_page_token)
for entry in results:
for video_raw in entry["items"]:
# logger.debug(video_raw["contentDetails"]["videoId"] + " " + " - " + video_raw["snippet"]["title"])
# logger.debug("Description: " + video_raw["snippet"]["description"])
parsed_from_api = parsed_from_api + 1
video = Video()
video.video_id = video_raw["contentDetails"]["videoId"]
video.title = video_raw["snippet"]["title"]
video.description = video_raw["snippet"]["description"]
video.upload_date = video_raw["snippet"]["publishedAt"]
video.upload_date = datetime.strptime(str(video.upload_date)[0:19], '%Y-%m-%dT%H:%M:%S')
video.playlist = playlist.id
video.online = video_status["online"]
video.download_required = 1
if session.query(Video).filter(Video.video_id == video.video_id).scalar() is None:
videos.append(video)
videos_to_check_against.append(video)
logger.info("Added new video " + video.video_id + " to DB.")
else:
videos_to_check_against.append(video)
# If we get a video ID back from youtube, which is already in database,
# we will check if it was set to offline in DB.
# If it's offline in DB, we will it set online again
# It happens, that some video IDs are missing in youtube channels details, so we have false flag offline videos in DB
video = session.query(Video).filter(Video.video_id == video.video_id).scalar()
if video.online == video_status["offline"]:
logger.info("Marking video " + str(video.video_id) + " as online again.")
video.online = video_status["online"]
videos.append(video)
if video.upload_date is None:
logger.info("Adding upload date to video")
video.upload_date = datetime.strptime(str(video_raw["snippet"]["publishedAt"])[0:19], '%Y-%m-%dT%H:%M:%S')
videos.append(video)
logger.debug("Parsed " + str(parsed_from_api) + " videos from API.")
logger.debug(str(len(videos)))
session.add_all(videos)
session.commit()
end_time = get_current_timestamp()
log_operation(end_time - start_time, "get_video_infos", "Got video infos for playlist " + playlist.playlist_name + " of channel " + channel_name)
check_videos_online_state(videos_to_check_against, playlist.id)
def check_videos_online_state(videos_to_check_against, local_playlist_id):
start_time = get_current_timestamp()
logger.debug("Getting all videos for playlist_id " + str(local_playlist_id) + " from database for video offline checking.")
playlist_videos_in_db = session.query(Video).filter(Video.playlist == local_playlist_id).filter(Video.online == video_status["online"]).filter(Video.downloaded != None).all()
logger.debug(str(len(playlist_videos_in_db)) + " videos are in DB for playlist")
videos_to_check_against_ids = []
for video in videos_to_check_against:
videos_to_check_against_ids.append(video.video_id)
logger.debug("Added " + str(video.video_id) + "to check_Against list.")
logger.debug("Will be checked against " + str(len(videos_to_check_against_ids)))
logger.debug("Calculating the offline video ids")
offline_video_ids = []
for video in playlist_videos_in_db:
if str(video.video_id) not in videos_to_check_against_ids and video.online != video_status["unlisted"]:
offline_video_ids.append(str(video.video_id))
logger.debug("Adding " + str(video.video_id) + " to offline video list.")
logger.debug("Updating all video in offline video list to offline state")
if len(offline_video_ids) == 0:
return None
logger.debug(str(len(offline_video_ids)) + " Videos are offline now.")
for offline_video_id in offline_video_ids:
logger.info("Video " + str(offline_video_id) + " is not on youtube anymore. Setting offline now.")
video = session.query(Video).filter(Video.video_id == str(offline_video_id)).scalar()
video.online = video_status["offline"]
session.add(video)
end_time = get_current_timestamp()
log_operation(end_time - start_time, "check_online_state", "Checked online state for all videos of playlist_id " + str(local_playlist_id))
session.commit()
def remove_youtube_video_from_archive_file(local_video_id: str):
logger.debug("Trying to remove " + local_video_id + " from " + str(config["youtube-dl"]["download-archive"]))
with open(config["youtube-dl"]["download-archive"], "r") as f:
lines = f.readlines()
logger.debug("Read the file " + str(config["youtube-dl"]["download-archive"]))
with open(config["youtube-dl"]["download-archive"], "w") as f:
for line in lines:
if line.strip("\n") != "youtube " + str(local_video_id):
f.write(line)
else:
logger.info("Removed video id " + local_video_id + " from " + str(config["youtube-dl"]["download-archive"]))
def download_videos():
# Online States: 0 = offline, 1 = online, 2 = 403 error, 3 = blocked in countries because hate speech
if os.path.exists(config["base"]["download_lockfile"]):
logger.error("Download lockfile is exisiting. If this is from aborted process, please remove " + config["base"]["download_lockfile"])
return None
if check_429_lock():
logger.error("The current used IP is still HTTP 429 blocked. Cannot continue.")
return None
Path(config["base"]["download_lockfile"]).touch()
if os.path.exists(config["base"]["download_dir"]):
try:
shutil.rmtree(config["base"]["download_dir"])
except OSError:
logger.error('Could not delete download directory. Please make sure it is not in use at the moment.')
remove_download_lockfile()
current_country = get_current_country()
video_file = None
http_429_counter = 0
if playlist_id is None:
logger.debug("Playlist ID for downloading is None. Getting all videos.")
if retry_403:
videos_not_downloaded = session.query(Video).filter(Video.downloaded == None).filter(or_(Video.online == video_status["online"], Video.online == video_status["http_403"], Video.online == video_status["unlisted"])).filter(Video.download_required == 1)
else:
videos_not_downloaded = session.query(Video).filter(Video.downloaded == None).filter(or_(Video.online == video_status["online"], Video.online == video_status["unlisted"])).filter(Video.download_required == 1)
else:
logger.debug("Playlist ID for downloading is " + str(playlist_id))
playlist_internal_id = session.query(Playlist.id).filter(Playlist.playlist_id == playlist_id).scalar()
logger.debug("Got playlist internal ID " + str(playlist_internal_id))
if retry_403:
videos_not_downloaded = session.query(Video).filter(Video.downloaded == None).filter(Video.playlist == str(playlist_internal_id)).filter(or_(Video.online == video_status["online"], Video.online == video_status["http_403"], Video.online == video_status["hate_speech"], Video.online == video_status["unlisted"])).filter(Video.download_required == 1)
else:
videos_not_downloaded = session.query(Video).filter(Video.downloaded == None).filter(Video.playlist == playlist_internal_id).filter(or_(Video.online == video_status["online"], Video.online == video_status["hate_speech"], Video.online == video_status["unlisted"])).filter(Video.download_required == 1)
logger.info("I have " + str(len(videos_not_downloaded.all())) + " in download queue. Start downloading now.")
for video in videos_not_downloaded:
set_status("downloading")
if video.copyright is None:
pass
else:
if current_country + "," in video.copyright:
logger.info("This video is geoblocked in the following countries: " + video.copyright + ". Current Country: " + current_country)
continue
start_time = get_current_timestamp()
if os.path.exists(config["youtube-dl"]["download-archive"]):
with open(config["youtube-dl"]["download-archive"]) as download_archive_file:
if video.video_id in download_archive_file.read():
logger.debug("Video " + video.video_id + " found in youtube-dl archive file. Setting impossible download date to import to database.")
video.downloaded = "1972-01-01 23:23:23"
session.add(video)
commit_with_retry()
continue
# Get the playlist object of a video. If uploaded date is older than playlist download date, skip download and set download required to 0
playlist = session.query(Playlist).filter(Playlist.id == video.playlist).scalar()
if playlist.download_from_date is not None:
playlist_download_date = datetime.strptime(str(playlist.download_from_date), '%Y-%m-%d %H:%M:%S')
video_upload_date = datetime.strptime(str(video.upload_date), '%Y-%m-%d %H:%M:%S')
if playlist_download_date > video_upload_date:
video.download_required = 0
session.add(video)
commit_with_retry()
continue
logger.info("Video " + str(video.video_id) + " - " + video.title + " is not yet downloaded. Downloading now.")
local_channel_id = session.query(Playlist.channel_id).filter(Playlist.id == video.playlist).scalar()
logger.debug("Video belongs to playlist " + str(local_channel_id))
channel_name = session.query(Channel.channel_name).filter(Channel.id == local_channel_id).scalar()
logger.debug("Video belongs to channel " + str(channel_name))
# Download video and get Dwonload path of mkv file as return variable
set_currently_downloading(str(channel_name) + " - " + video.video_id + " - " + video.title)
video_file = download_video(video.video_id, channel_name)
if video_file == "copyright":
logger.info("This video is geoblocked on current country " + current_country + ". Will get complete geoblock list.")
video_geoblock_list = get_geoblock_list_for_one_video(video.video_id)
geoblock_list = ""
if video_geoblock_list is not None:
for entry in video_geoblock_list:
geoblock_list = geoblock_list + (str(entry) + ",")