-
Notifications
You must be signed in to change notification settings - Fork 106
/
utils.py
4897 lines (3375 loc) · 146 KB
/
utils.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
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019-2024 A S Lewis
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at your option)
# 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Utility functions used by code copied from youtube-dl-gui."""
# Import Gtk modules
from gi.repository import Gtk, Gdk, GObject
# Import other modules
import datetime
import glob
import hashlib
import locale
import math
import os
import re
import requests
import shutil
import string
import subprocess
import sys
import time
from urllib.parse import urlparse, urljoin
# Import our modules
import classes
import formats
import mainapp
import media
# Use same gettext translations
from mainapp import _
# Functions
def add_links_to_entry_from_clipboard(app_obj, entry, duplicate_text=None,
drag_drop_text=None, no_modify_flag=None):
"""Called by various functions in mainWin.AddChannelDialogue and
mainwin.AddPlaylistDialogue.
Function to add valid URLs from the clipboard to a Gtk.Entry, ignoring
anything that is not a valid URL.
A duplicate URL can be specified, when the dialogue window's clipboard
monitoring is turned on; it prevents this function adding the same URL
that was added the previous time.
Args:
app_obj (mainapp.TartubeApp): The main application
entry (Gtk.Entry): The entry to which valis URLs should be added.
Only the first valid URL is added, replacing any previous contents
(unless the URL matches the specified duplicate
duplicate_text (str): If specified, ignore the clipboard contents, if
it matches this URL
drag_drop_text (str): If specified, use this text and ignore the
clipboard
no_modify_flag (bool): If True, the entry is not updated, instead,
the URL that would have been added to it is merely returned
Return values:
The URL added to the entry (or that would have been added to the entry)
or None if no valid and non-duplicate URL was found in the
clipboard
"""
if drag_drop_text is None:
# Get text from the system clipboard
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
cliptext = clipboard.wait_for_text()
else:
# Ignore the clipboard, and use the specified text
cliptext = drag_drop_text
# Eliminate empty lines and any lines that are not valid URLs (we assume
# that it's one URL per line)
# Use the first valid line that doesn't match the duplicate (if specified)
if cliptext is not None and cliptext != Gdk.SELECTION_CLIPBOARD:
for line in cliptext.splitlines():
# (Cope with multiple valid URLs on the same line, or a single
# valid URL with arbitrary text before and afterwards)
for item in line.split():
if check_url(item):
item = strip_whitespace(item)
if re.search(r'\S', item) \
and (duplicate_text is None or item != duplicate_text):
if not no_modify_flag:
entry.set_text(item)
return item
# No valid and non-duplicate URL found
return None
def add_links_to_textview(app_obj, link_list, textbuffer, mark_start=None,
mark_end=None, drag_drop_text=None):
"""Called by mainwin.AddVideoDialogue.__init__(),
.on_window_drag_data_received() and .clipboard_timer_callback().
Also called by utils.add_links_to_textview_from_clipboard().
Function to add valid URLs from the clipboard to a Gtk.TextView, ignoring
anything that is not a valid URL, and ignoring duplicate URLs.
If some text is supplied as an argument, uses that text rather than the
clipboard text
Args:
app_obj (mainapp.TartubeApp): The main application
link_list (list): List of URLs to add to the textview
textbuffer (Gtk.TextBuffer): The textbuffer to which valis URLs should
be added (unless they are duplicates)
mark_start, mark_end (Gtk.TextMark): The marks at the start/end of the
buffer (using marks rather than iters prevents Gtk errors)
drag_drop_text (str): If specified, use this text and ignore the
clipboard
"""
# Split each line by whitespace. This allows us to recognise multiple valid
# URLs on the same line, and also to interpret a line containing a URL
# and miscellaneous text
mod_link_list = []
for line in link_list:
for item in line.split():
mod_link_list.append(item)
# Eliminate empty lines and any lines that are not valid URLs (we assume
# that it's one URL per line)
# At the same time, trim initial/final whitespace
valid_list = []
for line in mod_link_list:
if check_url(line):
line = strip_whitespace(line)
if re.search(r'\S', line):
valid_list.append(line)
if valid_list:
# Some URLs survived the cull
# Get the contents of the buffer
if mark_start is None or mark_end is None:
# No Gtk.TextMarks supplied, we're forced to use iters
buffer_text = textbuffer.get_text(
textbuffer.get_start_iter(),
textbuffer.get_end_iter(),
# Don't include hidden characters
False,
)
else:
buffer_text = textbuffer.get_text(
textbuffer.get_iter_at_mark(mark_start),
textbuffer.get_iter_at_mark(mark_end),
False,
)
# Remove any URLs that already exist in the buffer
line_list = buffer_text.splitlines()
mod_list = []
for line in valid_list:
if not line in line_list:
mod_list.append(line)
# Add any surviving URLs to the buffer, first adding a newline
# character, if the buffer doesn't end in one
if mod_list:
if not re.search(r'\n\s*$', buffer_text) and buffer_text != '':
mod_list[0] = '\n' + mod_list[0]
textbuffer.insert(
textbuffer.get_end_iter(),
str.join('\n', mod_list) + '\n',
)
def add_links_to_textview_from_clipboard(app_obj, textbuffer, mark_start=None,
mark_end=None, drag_drop_text=None):
"""Called by mainwin.AddVideoDialogue.__init__(),
.on_window_drag_data_received() and .clipboard_timer_callback().
Function to add valid URLs from the clipboard to a Gtk.TextView, ignoring
anything that is not a valid URL, and ignoring duplicate URLs.
If some text is supplied as an argument, uses that text rather than the
clipboard text
Args:
app_obj (mainapp.TartubeApp): The main application
textbuffer (Gtk.TextBuffer): The textbuffer to which valis URLs should
be added (unless they are duplicates)
mark_start, mark_end (Gtk.TextMark): The marks at the start/end of the
buffer (using marks rather than iters prevents Gtk errors)
drag_drop_text (str): If specified, use this text and ignore the
clipboard
"""
if drag_drop_text is None:
# Get text from the system clipboard
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
cliptext = clipboard.wait_for_text()
else:
# Ignore the clipboard, and use the specified text
cliptext = drag_drop_text
# Pass the text on to the next function, first converting it into a list
if cliptext is not None:
add_links_to_textview(
app_obj,
cliptext.splitlines(),
textbuffer,
mark_start,
mark_end,
)
def check_day(this_day_num, target_day_str):
"""Can be called by anything.
formats.SPECIFIED_DAYS_DICT contains a set of strings representing one or
more days, e.g. 'every_day', 'monday'.
Check whether one of those strings matches a particular day.
Args:
this_day_num (int): Number in the range 0 (Monday) to 6 (Sunday),
usually representing today
target_day_str (str): One of the strings in formats.SPECIFIED_DAYS_DICT
Return values:
True if 'this_day_num' matches 'target_day_str', False otherwise
"""
if target_day_str != 'every_day':
if (target_day_str == 'weekdays' and this_day_num > 4) \
or (target_day_str == 'weekends' and this_day_num < 5) \
or (target_day_str == 'monday' and this_day_num != 0) \
or (target_day_str == 'tuesday' and this_day_num != 1) \
or (target_day_str == 'wednesday' and this_day_num != 2) \
or (target_day_str == 'thursday' and this_day_num != 3) \
or (target_day_str == 'friday' and this_day_num != 4) \
or (target_day_str == 'saturday' and this_day_num != 5) \
or (target_day_str == 'sunday' and this_day_num != 6):
return False
return True
def check_url(url):
"""Can be called by anything.
Checks for valid URLs.
Args:
url (str): The URL to check
Return values:
True if the URL is valid, False if invalid
"""
url = strip_whitespace(url)
# Based on various methods suggested by
# https://stackoverflow.com/questions/25259134/
# how-can-i-check-whether-a-url-is-valid-using-urlparse
try:
# Add a scheme, if the specified URL doesn't provide one
if not re.search(r'^[a-zA-Z]+://', url):
url = 'http://' + url
final_url = urlparse(urljoin(url, '/'))
is_valid = (
all([final_url.scheme, final_url.netloc, final_url.path])
and len(final_url.netloc.split('.')) > 1
and not re.search(r'\s', url)
)
return is_valid
except:
return False
def clip_add_to_db(app_obj, dest_obj, orig_video_obj, clip_title, \
clip_path=None):
"""Called by downloads.ClipDownloader.extract_stdout_data() and
process.ProcessManager.run().
Add the video clip to the Tartube database.
Args:
app_obj (mainapp.TartubeApp): The main application
dest_obj (media.Folder): The folder object into which the new video
object is to be created
orig_video_obj (media.Video): The original video, from which the video
clip has been split
clip_title (str): The clip title for the new video, matching its
filename
clip_path (str): Full path to the clip, if known (if not known, we
guess the path)
Return values:
The new media.Video object on success, or None of failure
"""
new_video_obj = app_obj.add_video(
dest_obj,
None, # No source
False, # Not a simulated download
True, # Don't sort the container's child list yet
)
if not new_video_obj:
return None
else:
source = orig_video_obj.source
if source is None or source == '':
source = _('No link')
new_video_obj.set_name(clip_title)
new_video_obj.set_nickname(clip_title)
new_video_obj.set_video_descrip(
app_obj,
_('Split from original video') + ' (' \
+ str(orig_video_obj.dbid) + ')\n' + orig_video_obj.name \
+ '\n' + orig_video_obj.source,
app_obj.main_win_obj.descrip_line_max_len,
)
if clip_path is not None:
# Use the supplied path (when called by downloads.ClipDownloader)
new_video_obj.set_file_from_path(clip_path)
else:
# Guess the path (when called by process.ProcessManager, it's safe
# to do that)
new_video_obj.set_file(clip_title, orig_video_obj.file_ext)
# Specifying the original video clones its .receive_time
new_video_obj.set_receive_time(orig_video_obj)
new_video_obj.set_upload_time(orig_video_obj.upload_time)
# (The video length and file size is set elsewhere)
# The video exists, so mark it as downloaded (even if only the original
# video was downloaded)
app_obj.mark_video_downloaded(new_video_obj, True)
# Copy the original video's thumbnail, if required
if app_obj.split_video_copy_thumb_flag:
thumb_path = find_thumbnail(app_obj, orig_video_obj)
if thumb_path:
new_video_path = new_video_obj.get_actual_path(app_obj)
thumb_name, thumb_ext = os.path.splitext(thumb_path)
video_name, video_ext = os.path.splitext(new_video_path)
new_thumb_path = video_name + thumb_ext
if not os.path.isfile(new_thumb_path):
try:
shutil.copyfile(thumb_path, new_thumb_path)
except:
pass
# Clips split off from an original use a different icon
new_video_obj.set_split_flag(True)
# Now the video's properties are fully updated, the parent containers
# can be sorted
dest_obj.sort_children(app_obj)
app_obj.fixed_all_folder.sort_children(app_obj)
# If the clips' parent media data object (a channel, playlist or
# folder) is selected in the Video Index, update the Video Catalogue
# for the clip
GObject.timeout_add(
0,
app_obj.main_win_obj.video_catalogue_update_video,
new_video_obj,
)
return new_video_obj
def clip_extract_data(stamp_list, clip_num):
"""Can be called by anything.
media.Video.stamp_list stores details for video clips in groups of three,
in the form
[start_stamp, stop_stamp, clip_title]
This function is called with a copy of media.Video.stamp_list (or some data
in the same format), and the index of one of those groups, corresponding to
a single video clip.
If 'stop_stamp' is not specified, then 'start_stamp' of the following
clip is used (unless that clip also starts at the same time, in which
case we use the next clip that does not start at the same time).
If there are no more clips, then this clip will end at the end of the
video.
Args:
stamp_list (list): The copy of a media.Video's .stamp_list IV
clip_num (int): The index of a group in stamp_list, the first clip is
#0. It is the calling function's responsibility to ensure that
clip_num is not outside the bounds of stamp_list
Return values:
Returns a list in the form
start_stamp, stop_stamp, clip_title
...in which 'stop_stamp' might have been modified, as described
above
"""
list_size = len(stamp_list)
mini_list = stamp_list[clip_num]
start_stamp = mini_list[0]
stop_stamp = mini_list[1]
clip_title = mini_list[2]
if stop_stamp is None and clip_num < (list_size - 1):
for i in range((clip_num + 1), list_size):
next_list = stamp_list[i]
if next_list[0] != start_stamp:
stop_stamp = next_list[0]
break
return start_stamp, stop_stamp, clip_title
def clip_prepare_title(app_obj, video_obj, clip_title_dict, clip_title,
clip_num, clip_max):
"""Called by downloads.ClipDownloader.do_download_clips_with_ffmpeg(), etc,
and by process.ProcessManager.run().
Before creating a video clip, decide what its clip title should be.
The title depends on various settings.
Args:
app_obj (mainapp.TartubeApp): The main application
video_obj (media.Video): The video to be sent to FFmpeg
clip_title_dict (dict): Dictionary of clip titles used when splitting a
video into clips), used to re-name duplicates
clip_title (str): When splitting a video, the title of this video clip
(if specified)
clip_num (int): When splitting a video, the number of video clips split
so far (including this one, so the first video clip is #1)
clip_max (int): The number of clips to be split from this video in
total
Return values:
The clip title
"""
# If 'clip_title' is not specified, use a generic clip title
# (The value is None only when not splitting a video)
if clip_title is None or clip_title == '':
clip_title = app_obj.split_video_custom_title
# All clips from the same video should be formatted with a fixed number of
# digits (so any list of files will appear in the correct order)
if clip_max > 99:
clip_str = "{:03d}".format(clip_num)
elif clip_max > 9:
clip_str = "{:02d}".format(clip_num)
else:
clip_str = str(clip_num)
# Set the video clip's filename, using the specified format
# Note that dummy media.Video objects might not have a .file_name set. In
# that case, we can use the .nickname (which is optionally set by the
# user, but which might also be None)
orig_name = video_obj.file_name
if orig_name is None \
and video_obj.dummy_flag \
and video_obj.nickname != app_obj.default_video_name:
orig_name = video_obj.nickname
if app_obj.split_video_name_mode == 'num':
mod_title = clip_str
elif app_obj.split_video_name_mode == 'clip':
mod_title = clip_title
elif app_obj.split_video_name_mode == 'num_clip':
mod_title = clip_str + ' ' + clip_title
elif app_obj.split_video_name_mode == 'clip_num':
mod_title = clip_title + ' ' + clip_str
elif app_obj.split_video_name_mode == 'orig':
if orig_name is None:
mod_title = app_obj.split_video_custom_title
else:
mod_title = orig_name
elif app_obj.split_video_name_mode == 'orig_num':
if orig_name is None:
mod_title = clip_str
else:
mod_title = orig_name + ' ' + clip_str
elif app_obj.split_video_name_mode == 'orig_clip':
if orig_name is None:
mod_title = clip_title
else:
mod_title = orig_name + ' ' + clip_title
elif app_obj.split_video_name_mode == 'orig_num_clip':
if orig_name is None:
mod_title = clip_str + ' ' + clip_title
else:
mod_title = orig_name + ' ' + clip_str + ' ' + clip_title
elif app_obj.split_video_name_mode == 'orig_clip_num':
if orig_name is None:
mod_title = clip_title + ' ' + clip_str
else:
mod_title = orig_name + ' ' + clip_title + ' ' + clip_str
# Failsafe
if mod_title is None:
mod_title = clip_title
# Ensure that we don't write multiple video clips with the same clip
# title (i.e. the same filename)
count = 0
this_title = mod_title
if video_obj.dummy_flag:
parent_dir = video_obj.dummy_dir
else:
parent_dir = video_obj.parent_obj.get_actual_dir(app_obj)
if video_obj.file_ext is None:
# (When launched from Classic Mode, we can't rely on the file name/
# extension being available; see the comments in
# mainapp.TartubeApp.download_manager_finished()
this_path = os.path.abspath(
os.path.join(
parent_dir,
this_title,
),
)
elif not app_obj.split_video_subdir_flag:
this_path = os.path.abspath(
os.path.join(
parent_dir,
this_title + video_obj.file_ext,
),
)
else:
this_path = os.path.abspath(
os.path.join(
parent_dir,
video_obj.file_name,
this_title + video_obj.file_ext,
),
)
while 1:
if not this_title in clip_title_dict and not os.path.isfile(this_path):
return this_title
else:
# (Proceed to the next iteration of the loop, adding a number
# to the end of the clip title until we get a file path that
# hasn't already been written)
count += 1
this_title = mod_title + '_' + str(count)
if video_obj.file_ext is None:
this_path = os.path.abspath(
os.path.join(
parent_dir,
this_title,
),
)
elif not app_obj.split_video_subdir_flag:
this_path = os.path.abspath(
os.path.join(
parent_dir,
this_title + video_obj.file_ext,
),
)
else:
this_path = os.path.abspath(
os.path.join(
parent_dir,
video_obj.file_name,
this_title + video_obj.file_ext,
),
)
def clip_prepare_chapter_output_template(app_obj, video_obj, dest_dir):
"""Called by downloads.ClipDownloader.do_download_clips_with_chapters().
A slimmed-down version of utils.clip_prepare_title(), used when downloading
all clips from a video at the same time (in which case, each clip is named
using a youtube-dl output template).
Args:
app_obj (mainapp.TartubeApp): The main application
video_obj (media.Video): The video to be sent to FFmpeg
dest_dir (str): Full path to the download destination directory
Return values:
The output template (including a full file path, unlike the return
value of utils.clip_prepare_title() )
"""
# Set the video clip's filename, using the specified format
# Note that dummy media.Video objects might not have a .file_name set
# (especially in an operation started in Classic Mode), so we have to
# take account of that
if app_obj.split_video_name_mode == 'num':
mod_title = '%(section_number)s'
elif app_obj.split_video_name_mode == 'clip':
mod_title = '%(section_title)s'
elif app_obj.split_video_name_mode == 'num_clip':
mod_title = '%(section_number)s %(section_title)s'
elif app_obj.split_video_name_mode == 'clip_num':
mod_title = '%(section_title)s %(section_number)s'
elif app_obj.split_video_name_mode == 'orig' \
or app_obj.split_video_name_mode == 'orig_num':
# N.B. We must have a unique clip name, so these two settings are
# combined
if video_obj.file_name is None:
mod_title = '%(section_number)s'
else:
mod_title = video_obj.file_name + ' %(section_number)s'
elif app_obj.split_video_name_mode == 'orig_clip':
if video_obj.file_name is None:
mod_title = '%(section_title)s'
else:
mod_title = video_obj.file_name + ' %(section_title)s'
elif app_obj.split_video_name_mode == 'orig_num_clip':
if video_obj.file_name is None:
mod_title = '%(section_number)s %(section_title)s'
else:
mod_title = video_obj.file_name \
+ ' %(section_number)s %(section_title)s'
elif app_obj.split_video_name_mode == 'orig_clip_num':
if video_obj.file_name is None:
mod_title = '%(section_title)s %(section_number)s'
else:
mod_title = video_obj.file_name \
+ ' %(section_title)s %(section_number)s'
# Failsafe
if mod_title is None:
mod_title = '%(section_number)s'
# Set the output template with its correct file path
if video_obj.file_ext is None:
return os.path.abspath(
os.path.join(
dest_dir,
mod_title + '.%(ext)s',
),
)
elif not app_obj.split_video_subdir_flag:
return os.path.abspath(
os.path.join(
dest_dir,
mod_title + video_obj.file_ext,
),
)
else:
return os.path.abspath(
os.path.join(
dest_dir,
video_obj.file_name,
mod_title + video_obj.file_ext,
),
)
def clip_set_destination(app_obj, video_obj):
"""Called by downloads.ClipDownloader.do_download() and
process.ProcessManager.run().
Sets the media.Folder and/or the filestem folder in which the video clips
will be created/downloaded.
Args:
app_obj (mainapp.TartubeApp): The main application
video_obj (media.Video): The video object whose video files is to be
split into clips
Return values:
A list in the form:
(
parent_folder_object, parent_directory,
destination_folder_object, destination_directory
)
...with all values set to None if there was an error
"""
# parent_obj is either the Video Clips folder, or the original video's
# container (which might be a channel, playlist or folder)
if app_obj.split_video_clips_dir_flag:
parent_obj = app_obj.fixed_clips_folder
else:
parent_obj = video_obj.parent_obj
parent_dir = parent_obj.get_actual_dir(app_obj)
# Now set the actual directory into which the video clips are to be
# created/downloaded
# Original and clip files in the same directory
if not app_obj.split_video_subdir_flag:
return parent_obj, parent_dir, parent_obj, parent_dir
# Otherwise, video clips are in a sub-directory of 'parent_dir'
if not isinstance(parent_obj, media.Folder) \
or not app_obj.split_video_add_db_flag:
# Cannot create a media.Folder inside a channel/playlist, so simply
# create a sub-directory in the filesystem. The video clips can be
# created there, but can't be added to the Tartube database
dest_dir = os.path.abspath(
os.path.join(
parent_obj.get_actual_dir(app_obj),
# Sub-directory is named after the video
video_obj.file_name,
),
)
if not os.path.isdir(dest_dir):
app_obj.make_directory(dest_dir)
return parent_obj, parent_dir, None, dest_dir
# Otherwise, we can create a media.Folder inside another media.Folder
if video_obj.dbid in app_obj.container_reg_dict:
# A media.Folder with the right name already exists
dest_obj = app_obj.media_reg_dict[video_obj.dbid]
if dest_obj.parent_obj != parent_obj:
# There is already a media.Folder with the same name, somewhere
# else in the database. This is a fatal error
return None, None, None, None
else:
# Use the existing media.Folder
dest_dir = dest_obj.get_actual_dir(app_obj)
return parent_obj, parent_dir, dest_obj, dest_dir
# The media.Folder corresponding to the directory doesn't exist yet
dest_obj = app_obj.add_folder(
video_obj.name, # The folder name
parent_obj,
False, # No simulated downloads
parent_obj.restrict_mode,
)
if not dest_obj:
# Some folders (e.g. Unsorted Videos) can't contain other folders
return None, None, None, None
else:
dest_dir = dest_obj.get_actual_dir(app_obj)
return parent_obj, parent_dir, dest_obj, dest_dir
def compile_mini_options_dict(options_manager_obj):
"""Called by downloads.VideoDownloader.confirm_new_video() and
.confirm_old_video().
Also called by downloads.StreamDownloader.do_download().
Compiles a dictionary containing a subset of download options from the
specified options.OptionsManager object, to be passed on to
mainapp.TartubeApp.announce_video_download().
Args:
options_manager_obj (options.OptionsManager): The options manager
for this download
"""
mini_options_dict = {
'keep_description': \
options_manager_obj.options_dict['keep_description'],
'keep_info': \
options_manager_obj.options_dict['keep_info'],
'keep_annotations': \
options_manager_obj.options_dict['keep_annotations'],
'keep_thumbnail': \
options_manager_obj.options_dict['keep_thumbnail'],
'move_description': \
options_manager_obj.options_dict['move_description'],
'move_info': \
options_manager_obj.options_dict['move_info'],
'move_annotations': \
options_manager_obj.options_dict['move_annotations'],
'move_thumbnail': \
options_manager_obj.options_dict['move_thumbnail'],
}
return mini_options_dict
def convert_bytes_to_string(num_bytes):
"""Can be called by anything.
Uses formats.FILESIZE_METRIC_DICT to convert an arbitrary integer, in
bytes, into a readable string like '27.5 MiB'.
Based on code from https://stackoverflow.com/questions/12523586/
python-format-size-application-converting-b-to-kb-mb-gb-tb
Args:
num_bytes (int): An integer, 0 or above
Return values:
A string formatted to 1dp
"""
# Don't want to return '0.0 B', this string looks a lot nicer
if num_bytes == 0:
return '0 KiB'
unit_step = 1024
unit_step_thresh = unit_step - 0.05
last_label = formats.FILESIZE_METRIC_LIST[-1]
for unit in formats.FILESIZE_METRIC_LIST:
if num_bytes < unit_step_thresh:
break
if unit != last_label:
num_bytes /= unit_step
return '{:.1f} {}'.format(num_bytes, unit)
def convert_enhanced_template_from_json(convert_type, enhanced_name, \
json_dict):
"""Can be called by anything.