-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathbb.py
More file actions
1453 lines (1215 loc) · 49.2 KB
/
bb.py
File metadata and controls
1453 lines (1215 loc) · 49.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
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
# -*- coding: utf-8 -*-
import os
import sys
import shutil
import re
import subprocess
from textwrap import dedent
from collections import namedtuple, abc
from concurrent.futures.thread import ThreadPoolExecutor
from datetime import timedelta
from mimetypes import guess_type
import pymediainfo
import mutagen
import guessit
from unidecode import unidecode
from requests.exceptions import HTTPError
from .config import config
from .logging import log
from .torrent import make_torrent
from . import tvdb
from . import imdb
from . import musicbrainz as mb
from . import imagehosting
from . import goodreads
from .googlebooks import find_cover, find_categories
from .ffmpeg import FFMpeg
from . import templating as bb
from .submission import (Submission, form_field, finalize, cat_map,
SubmissionAttributeError, rlinput)
from .tracker import Tracker
from .scene import is_scene_crc, query_scene_fname
def format_tag(tag):
tag = unidecode(tag)
if '/' in tag:
# Multiple actors can be listed as a single actor like this:
# "Thierry Kazazian / Max Mittleman"
# (e.g. for "Miraculous: Tales of Ladybug & Cat Noir")
tag = tag[:tag.index('/')].strip()
return tag.replace(' ', '.').replace('-', '.').replace('\'', '.').lower()
def format_choices(choices):
return ", ".join([
str(num) + ": " + value
for num, value in enumerate(choices)
])
def uniq(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
class BbSubmission(Submission):
default_fields = ("form_title", "tags", "cover")
def show_fields(self, fields):
return super(BbSubmission, self).show_fields(
fields or self.default_fields)
def confirm_finalization(self, fields):
return super(BbSubmission, self).confirm_finalization(
fields or self.default_fields)
def subcategory(self):
path = self['path']
if os.path.isfile(path):
files = [(os.path.getsize(path), path)]
else:
files = []
for root, _, fs in os.walk(path):
for f in fs:
fpath = os.path.join(root, f)
files.append((os.path.getsize(fpath), fpath))
for _, path in sorted(files, reverse=True):
mime_guess, _ = guess_type(path)
if mime_guess:
mime_guess = mime_guess.split('/')
if mime_guess[0] == 'video':
return VideoSubmission
elif mime_guess[0] == 'audio':
return AudioSubmission
log.info("Unable to guess submission category using known mimetypes")
while True:
cat = input("Please manually specify category. "
"\nOptions: {}"
"\nCategory: ".format(", ".join(cat_map.keys())))
try:
return cat_map[cat]
except KeyError:
print('Invalid category.')
def subcategorise(self):
log.debug('Attempting to narrow category')
SubCategory = self.subcategory()
if type(self) == SubCategory:
return self
log.info("Narrowing category from {} to {}",
type(self).__name__, SubCategory.__name__)
sub = SubCategory(**self.fields)
sub.depends_on = self.depends_on
return sub
@staticmethod
def submit(payload):
t = Tracker()
return t.upload(**payload)
@form_field('scene', 'checkbox')
def _render_scene(self):
# todo: if path is directory, choose file for crc
path = os.path.normpath(self['path']) # removes trailing slash
try:
try:
if os.path.exists(path) and not os.path.isdir(path):
return is_scene_crc(path)
except KeyboardInterrupt:
sys.stdout.write('...skipped\n')
query_scene_fname(path)
except HTTPError as e:
log.notice(e)
while True:
choice = input('Is this a scene release? [y/N] ')
if not choice or choice.lower() == 'n':
return False
elif choice.lower() == 'y':
return True
def data_method(self, source, target):
def copy(source, target):
if os.path.isfile(source):
return shutil.copy(source, target)
if os.path.isdir(source):
return shutil.copytree(source, target)
raise Exception('Source {} is neither '
'file nor directory'.format(source))
cat_methods_map = {
'movie': ['hard', 'sym', 'copy', 'move'],
'tv': ['hard', 'sym', 'copy', 'move'],
'music': ['copy', 'move'],
'book': ['copy', 'move'],
}
method_map = {'hard': os.link,
'sym': os.symlink,
'copy': copy,
'move': shutil.move}
# use cmd line option if specified
option_method = self['options'].get('data_method', 'auto')
if option_method != 'auto':
method = option_method
else:
pref_method = config.get('Torrent', 'data_method')
if pref_method not in method_map:
log.warning(
'Preferred method {} not valid. '
'Choices are {}'.format(pref_method,
list(method_map.keys())))
try:
# todo fix this, proper category mapping,
# e.g. 'music' <-> bb.MusicSubmission
category = ('music' if isinstance(self, AudioSubmission)
else 'movie')
except AttributeError:
log.warning("{} does not have a category attribute",
type(self).__name__)
category = 'movie' # use movie data methods
cat_methods = cat_methods_map[category]
if pref_method in cat_methods:
# use user preferred method if in category method list
method = pref_method
else:
# otherwise use first category method
method = cat_methods[0]
log.notice('Copying data using \'{}\' method', method)
return method_map[method](source, target)
@finalize
@form_field('file_input', 'file')
def _render_torrentfile(self):
return make_torrent(self['path'])
def _finalize_torrentfile(self):
# move data to upload directory
up_dir = config.get('Torrent', 'upload_dir')
path_dir, path_base = os.path.split(self['path'])
if up_dir and not os.path.samefile(up_dir, path_dir):
target = os.path.join(up_dir, path_base)
if not os.path.exists(target):
self.data_method(self['path'], target)
else:
log.notice('Data method target already exists, skipping...')
# black hole
bh_dir = config.get('Torrent', 'black_hole')
if bh_dir:
fname = os.path.basename(self['torrentfile'])
dest = os.path.join(bh_dir, fname)
try:
assert os.path.exists(bh_dir)
assert not os.path.isfile(dest)
except AssertionError as e:
log.error(e)
else:
shutil.copy(self['torrentfile'], dest)
log.notice("Torrent file copied to {}", dest)
return self['torrentfile']
@form_field('type')
def _render_form_type(self):
try:
return self._form_type
except AttributeError:
raise SubmissionAttributeError(type(self).__name__ +
' has no _form_type attribute')
@form_field('submit')
def _render_form_submit(self):
return 'true'
title_tv_re = (
r"^(?P<title>.+)(?<!season) "
r"(?P<season_marker>(s|season |))"
r"(?P<season>((?<= s)[0-9]{2,})|(?<= )[0-9]+(?=x)|(?<=season )[0-9]+(?=$))"
r"((?P<episode_marker>[ex])(?P<episode>[0-9]+))?$")
TvSpecifier = namedtuple('TvSpecifier', ['title', 'season', 'episode'])
class VideoSubmission(BbSubmission):
default_fields = BbSubmission.default_fields
def _render_guess(self):
return dict(guessit.guessit(self['path']))
def subcategory(self):
if type(self) == VideoSubmission:
if self['tv_specifier']:
return TvSubmission
else:
return MovieSubmission
return type(self)
def _render_title(self):
# Use format "<original title> AKA <english title>" where applicable
title_original = self['summary']['title']
title_english = self['summary']['titles'].get('XWW', None)
if title_english is not None and title_original != title_english:
return '{} AKA {}'.format(title_original, title_english)
else:
return title_original
def _render_tv_specifier(self):
# if title is specified, look if season/episode are set
if self['title_arg']:
match = re.match(title_tv_re, self['title_arg'],
re.IGNORECASE)
if match:
episode = match.group('episode')
return TvSpecifier(
match.group('title'), int(match.group('season')),
episode and int(episode)) # if episode is None
# todo: test tv show name from title_arg, but episode from filename
guess = self['guess']
if guess['type'] == 'episode':
if self['title_arg']:
title = self['title_arg']
else:
title = guess['title']
try:
season = guess['season']
except KeyError:
raise Exception('Could not find a season in the path name. '
'Try specifying it in the TITLE argument, '
'e.g. "Some TV Show S02" for a season 2 pack')
return TvSpecifier(title, season, guess.get('episode'))
@form_field('tags')
def _render_tags(self):
# todo: get episode-specific actors (from imdb?)
n = self['options']['num_cast']
d = self['options']['num_directors']
tags = list(self['summary']['genres'])
if 'directors' in self['summary']:
tags += [a['name']
for a in self['summary']['directors'][:d]
if a['name']]
if 'cast' in self['summary']:
tags += [a['name']
for a in self['summary']['cast'][:n]
if a['name']]
tags = uniq(tags)
# Maximum tags length is 200 characters
def tags_string(tags):
return ",".join(format_tag(tag) for tag in tags)
while len(tags_string(tags)) > 200:
del tags[-1]
return tags_string(tags)
def _render_mediainfo_path(self):
assert os.path.exists(self['path'])
if os.path.isfile(self['path']):
return self['path']
contained_files = []
for dp, dns, fns in os.walk(self['path']):
contained_files += [os.path.join(dp, fn) for fn in fns
if (os.path.getsize(os.path.join(dp, fn))
> 10 * 2**20)]
if len(contained_files) == 1:
return contained_files[0]
print("\nWhich file would you like to run mediainfo on? Choices are")
contained_files.sort()
for k, v in enumerate(contained_files):
print("{}: {}".format(k, os.path.relpath(v, self['path'])))
while True:
try:
choice = input(
"Enter [0-{}]: ".format(len(contained_files) - 1))
return contained_files[int(choice)]
except (ValueError, IndexError):
pass
@finalize
def _render_screenshots(self):
ns = self['options']['num_screenshots']
ffmpeg = FFMpeg(self['mediainfo_path'])
return ffmpeg.take_screenshots(ns)
def _finalize_screenshots(self):
return imagehosting.upload(*self['screenshots'])
def _render_mediainfo(self):
try:
path = self['mediainfo_path']
if os.name == "nt":
mi = subprocess.Popen([r"mediainfo", path], shell=True,
stdout=subprocess.PIPE
).communicate()[0].decode('utf8')
else:
mi = subprocess.Popen([r"mediainfo", path],
stdout=subprocess.PIPE
).communicate()[0].decode('utf8')
except OSError:
sys.stderr.write(
"Error: Media Info not installed, refer to "
"http://mediainfo.sourceforge.net/en for installation")
exit(1)
else:
# Replace absolute path with file name
mi_dir = os.path.dirname(self['mediainfo_path']) + '/'
mi = mi.replace(mi_dir, '')
# bB's mediainfo parser expects "Xbps" instead of "Xb/s"
mi = mi.replace('Kb/s', 'Kbps') \
.replace('kb/s', 'Kbps') \
.replace('Mb/s', 'Mbps')
return mi
def _render_tracks(self):
video_tracks = []
audio_tracks = []
text_tracks = []
general = None
mi = pymediainfo.MediaInfo.parse(self['mediainfo_path'])
for track in mi.tracks:
if track.track_type == 'General':
general = track.to_data()
elif track.track_type == 'Video':
video_tracks.append(track.to_data())
elif track.track_type == 'Audio':
audio_tracks.append(track.to_data())
elif track.track_type == 'Text':
text_tracks.append(track.to_data())
else:
log.debug("Unknown track {}", track)
assert general is not None
assert len(video_tracks) == 1
video_track = video_tracks[0]
assert len(audio_tracks) >= 1
return {'general': general,
'video': video_track,
'audio': audio_tracks,
'text': text_tracks}
def _render_source(self):
sources = ('BluRay', 'BluRay 3D', 'WEB-DL',
'WebRip', 'HDTV', 'DVDRip', 'DVDSCR', 'CAM')
# ignored: R5, TeleSync, PDTV, SDTV, BluRay RC, HDRip, VODRip,
# TC, SDTV, DVD5, DVD9, HD-DVD
# todo: replace with guess from self['guess']
regpath = self['path'].lower().replace('-', '')
if 'bluray' in regpath:
return 'BluRay' # todo: 3d
elif 'webdl' in regpath:
return 'WEB-DL'
elif 'webrip' in regpath:
return 'WebRip'
elif 'hdtv' in regpath:
return 'HDTV'
# elif 'dvdscr' in self['path'].lower():
# markers['source'] = 'DVDSCR'
else:
print("File:", self['path'])
print("Choices:", format_choices(sources))
while True:
choice = input("Please specify a source by number: ")
try:
return sources[int(choice)]
except (ValueError, IndexError):
print("Please enter a valid choice")
def _render_container(self):
general = self['tracks']['general']
if general['format'] == 'Matroska':
return 'MKV'
elif general['format'] == 'AVI':
return 'AVI'
elif general['format'] == 'MPEG-4':
return 'MP4'
elif general['format'] == 'BDAV':
return 'm2ts'
else:
raise RuntimeError("Unknown or unsupported container '{}'".format(
general.format))
def _render_video_codec(self):
video_track = self['tracks']['video']
codec_id = video_track['codec_id']
match_list = [('(V_MPEG4/ISO/)?AVC1?', 'H.264'),
('(V_MPEGH/ISO/)?HEVC', 'H.265'),
('(V_MS/VFW/FOURCC / )?WVC1', 'VC-1'),
('VP9', 'VP9'),
('XVID', 'XVid'),
('(MP42|DX[45]0)', 'DivX'),
('(V_)?MPEG2', 'MPEG-2')
]
norm_codec_id = None
for rx, rv in match_list:
rx = re.compile(rx, flags=re.IGNORECASE)
if rx.match(codec_id):
norm_codec_id = rv
break
else:
if video_track['format'] == 'MPEG Video':
if video_track['format_version'] == 'Version 1':
norm_codec_id = 'MPEG-1'
elif video_track['format_version'] == 'Version 2':
norm_codec_id = 'MPEG-2'
elif video_track['format'] == 'AVC':
norm_codec_id = 'H.264'
# x264/5 is not a codec, but the rules is the rules
if (norm_codec_id == 'H.264' and
'x264' in video_track.get('writing_library', '')):
return 'x264'
elif (norm_codec_id == 'H.265' and
'x265' in video_track.get('writing_library', '')):
return 'x265'
elif norm_codec_id:
return norm_codec_id
msg = "Unknown or unsupported video codec '{}' ({}, {})".format(
video_track.get('codec_id'),
video_track.get('format'),
video_track.get('writing_library'))
raise RuntimeError(msg)
def _render_audio_codec(self):
audio_track = self['tracks']['audio'][0] # main audio track
if audio_track.get('codec_id_hint') == 'MP3':
return 'MP3'
elif 'Dolby Atmos' in audio_track['commercial_name']:
return 'Dolby Atmos'
elif 'DTS-HD' in audio_track['commercial_name']:
if audio_track.get('other_format', '') == 'DTS XLL X':
return 'DTS:X'
return 'DTS-HD'
codec_id = audio_track['codec_id']
if codec_id.startswith('A_'):
codec_id = codec_id[2:]
match_list = [('(E?AC-?3|2000)', 'AC-3'),
('DTS', 'DTS'),
('FLAC', 'FLAC'),
('(AAC|MP4A)', 'AAC'),
('(MP3|MPA1L3|55)', 'MP3'),
('TRUEHD', 'True-HD'),
('PCM', 'PCM'),
]
for rx, rv in match_list:
rx = re.compile(rx, flags=re.IGNORECASE)
if rx.match(codec_id):
return rv
raise ValueError("Unknown or unsupported audio codec '{}'".format(
audio_track['codec_id']))
def _render_resolution(self):
resolutions = ('2160p', '1080p', '720p', '1080i', '720i',
'480p', '480i', 'SD')
# todo: replace with regex?
# todo: compare result with mediainfo
for res in resolutions:
if res.lower() in self['path'].lower():
# warning: 'sd' might match any ol' title, but it's last anyway
return res
else:
print("File:", self['path'])
print("Choices:", format_choices(resolutions))
while True:
choice = input("Please specify a resolution by number: ")
try:
return resolutions[int(choice)]
except (ValueError, IndexError):
print("Please enter a valid choice")
# from mediainfo and filename
def _render_additional(self):
additional = []
video_track = self['tracks']['video']
audio_tracks = self['tracks']['audio']
text_tracks = self['tracks']['text']
# print [(track.title, track.language) for track in text_tracks]
# todo: rule checking, e.g.
# main_audio = audio_tracks[0]
# if (main_audio.language and main_audio.language != 'en' and
# not self['tracks']['text']):
# raise BrokenRule("Missing subtitles")
if 'remux' in os.path.basename(self['path']).lower():
additional.append('REMUX')
if self['guess'].get('proper_count') and self['scene']:
additional.append('PROPER')
edition = self['guess'].get('edition')
if isinstance(edition, str):
additional.append(edition)
elif isinstance(edition, abc.Sequence):
additional.extend(edition)
if 'BT.2020' in video_track.get('color_primaries', ''):
additional.append('HDR10')
for track in audio_tracks[1:]:
if 'title' in track and 'commentary' in track['title'].lower():
additional.append('w. Commentary')
break
if text_tracks:
additional.append('w. Subtitles')
return additional
def _render_form_release_info(self):
return " / ".join(self['additional'])
@finalize
@form_field('image')
def _render_cover(self):
return self['summary']['cover']
def _finalize_cover(self):
return imagehosting.upload(self['cover'])
class TvSubmission(VideoSubmission):
default_fields = VideoSubmission.default_fields + ('form_description',)
_cat_id = 'tv'
_form_type = 'TV'
__form_fields__ = {
'form_title': ('title', 'text'),
'form_description': ('desc', 'text'),
}
@property
def season(self):
return self['tv_specifier'].season
def _render_guess(self):
return dict(guessit.guessit(self['path'],
options=('--type', 'episode')))
def _render_search_title(self):
return self['tv_specifier'].title
def subcategory(self):
if type(self) == TvSubmission:
if self['tv_specifier'].episode is None:
return SeasonSubmission
else:
return EpisodeSubmission
return type(self)
@staticmethod
def tvdb_title_i18n(result):
try:
tvdb_sum = result.summary()
imdb_id = tvdb_sum['show_imdb_id']
i = imdb.IMDB()
imdb_info = i.get_info(imdb_id)
except Exception as e:
log.error(e)
return {'titles': {}}
imdb_sum = imdb_info.summary()
tvdb_title = tvdb_sum['title']
titles_d = {}
# Original title
titles_d['title'] = imdb_sum['title']
# dict of international titles
titles_d['titles'] = imdb_sum['titles']
# "XWW" is IMDb's international title, but unlike TVDB, it doesn't
# include the year if there are multiple shows with the same name.
if 'XWW' in titles_d['titles']:
titles_d['titles']['XWW'] = tvdb_title
return titles_d
def _render_markers(self):
return [self['source'], self['video_codec'],
self['audio_codec'], self['container'],
self['resolution']] + self['additional']
def _render_description(self):
sections = [("Description", self['section_description']),
("Information", self['section_information'])]
description = "\n".join(bb.section(*s) for s in sections)
description += bb.release
return description
@form_field('desc')
def _render_form_description(self):
ss = "".join(map(bb.img, self['screenshots']))
return (self['description'] + "\n" +
bb.section("Screenshots", bb.center(ss)) +
bb.mi(self['mediainfo']))
class EpisodeSubmission(TvSubmission):
@property
def episodes(self):
episodes = self['tv_specifier'].episode
if isinstance(episodes, abc.Sequence):
return episodes
return [episodes]
@form_field('title')
def _render_form_title(self):
return "{t} S{s:02d}{es} [{m}]".format(
t=self['title'], s=self.season,
es="".join("E{:02d}".format(e)
for e in self.episodes),
m=" / ".join(self['markers']))
def _render_summary(self):
t = tvdb.TVDB()
results = t.search(self['tv_specifier'])
title_i18n = self.tvdb_title_i18n(results[0])
summaries = []
show_summary = results[0].show_summary()
for result in results:
summary = result.summary()
summaries.append(summary)
ks = summaries[0].keys()
assert all(s.keys() == ks for s in summaries)
summary = {k: [s[k] for s in summaries] for k in ks}
summary.update(**show_summary)
summary.update(**title_i18n)
summary['cover'] = summary['cover'][0]
directors = uniq([n for names in summary['directors'] for n in names])
summary['directors'] = [{'name': name} for name in directors]
writers = uniq([n for names in summary['writers'] for n in names])
summary['writers'] = [{'name': name} for name in writers]
return summary
def _render_section_description(self):
summary = self['summary']
return (summary['seriessummary'] +
"".join(bb.spoiler(es, "Episode description")
for es in summary['episodesummary']))
def _render_section_information(self):
s = self['summary']
links = [[('TVDB', u)] for u in s['url']]
rating_bb = []
for i, imdb_id in enumerate(s['imdb_id']):
if imdb_id:
links[i].append(
('IMDb', "https://www.imdb.com/title/" + imdb_id))
i = imdb.IMDB()
rating, votes = i.get_rating(imdb_id)
rating_bb.append(
(bb.format_rating(rating[0], max=rating[1]) + " " +
bb.s1("({votes} votes)".format(votes=votes))))
else:
rating_bb.append("")
description = dedent("""\
[b]Episode titles[/b]: {title}
[b]Aired[/b]: {air_date} on {network}
[b]IMDb Rating[/b]: {rating}
[b]Directors[/b]: {directors}
[b]Writer(s)[/b]: {writers}
[b]Content rating[/b]: {contentrating}""").format(
title=' | '.join(
"{} ({})".format(
t, ", ".join(bb.link(*l) for l in ls)) # noqa: E741
for t, ls in zip(s['episode_title'], links)),
air_date=' | '.join(s['air_date']),
network=s['network'],
rating=' | '.join(rating_bb),
directors=' | '.join(d['name'] for d in s['directors']),
writers=' | '.join(w['name'] for w in s['writers']),
contentrating=s['contentrating']
)
return description
class SeasonSubmission(TvSubmission):
@form_field('title')
def _render_form_title(self):
return "{t} - Season {s} [{m}]".format(
t=self['title'],
s=self['tv_specifier'].season,
m=" / ".join(self['markers']))
def _render_summary(self):
t = tvdb.TVDB()
result = t.search(self['tv_specifier'])
summary = result.summary()
summary.update(self.tvdb_title_i18n(result))
return summary
def _render_section_description(self):
summary = self['summary']
return summary['seriessummary']
def _render_section_information(self):
s = self['summary']
links = [('TVDB', s['url'])]
imdb_id = s.get('show_imdb_id')
if imdb_id:
links.append(('IMDb',
"https://www.imdb.com/title/" + imdb_id))
description = dedent("""\
[b]Network[/b]: {network}
[b]Content rating[/b]: {contentrating}\n""").format(
contentrating=s['contentrating'],
network=s['network'],
)
i = imdb.IMDB()
# todo unify rating_bb and episode_fmt
def episode_fmt(e):
if not e['imdb_id']:
return bb.link(e['title'], e['url']) + "\n"
try:
rating, votes = i.get_rating(e['imdb_id'])
except ValueError:
return ''
else:
return (bb.link(e['title'], e['url']) + "\n" +
bb.s1(bb.format_rating(*rating)))
with ThreadPoolExecutor() as executor:
episodes = executor.map(episode_fmt, s['episodes'])
description += "[b]Episodes[/b]:\n" + bb.list(episodes, style=1)
return description
class MovieSubmission(VideoSubmission):
default_fields = (VideoSubmission.default_fields +
("description", "mediainfo", "screenshots"))
_cat_id = 'movie'
_form_type = 'Movies'
__form_fields__ = {
# field -> form field, type
'source': ('source', 'text'),
'video_codec': ('videoformat', 'text'),
'audio_codec': ('audioformat', 'text'),
'container': ('container', 'text'),
'resolution': ('resolution', 'text'),
'form_release_info': ('remaster_title', 'text'),
'mediainfo': ('release_desc', 'text'),
'screenshots': (lambda i, v: 'screenshot' + str(i + 1), 'text'),
}
def _render_guess(self):
return dict(guessit.guessit(self['path'],
options=('--type', 'movie')))
def _render_search_title(self):
if self['title_arg']:
return self['title_arg']
return self['guess']['title']
@form_field('title')
def _render_form_title(self):
return self['title']
@form_field('year')
def _render_year(self):
if 'summary' in self.fields:
return self['summary']['year']
elif 'year' in self['guess']:
return self['guess']['year']
else:
while True:
year = input('Please enter year: ')
try:
year = int(year)
except ValueError:
pass
else:
return year
def _render_summary(self):
i = imdb.IMDB()
movie = i.search(self['search_title'])
return movie.summary()
def _render_section_information(self):
def imdb_link(r):
return bb.link(r['name'], "https://www.imdb.com"+r['id'])
# todo: synopsis/longer description
n = self['options']['num_cast']
summary = self['summary']
metacritic = summary['metacritic']
links = [("IMDb", summary['url'])]
try:
links.append(("Metacritic", metacritic['metacriticUrl']))
except (TypeError, KeyError):
pass
return dedent("""\
[b]Title[/b]: {name} ({links})
[b]MPAA[/b]: {mpaa}
[b]IMDb rating[/b]: {rating} [size=1]({votes} votes)[/size]
[b]Metacritic[/b]: {metascore} [size=1]({metacount} reviews)[/size] | \
{metauser} [size=1]({metavotes} votes)[/size]
[b]Runtime[/b]: {runtime}
[b]Director(s)[/b]: {directors}
[b]Writer(s)[/b]: {writers}
[b]Cast[/b]: {cast}""").format(
links=", ".join(bb.link(*l) for l in links), # noqa: E741
name=summary['name'],
mpaa=summary['mpaa'],
rating=bb.format_rating(summary['rating'][0],
max=summary['rating'][1]),
metascore=str(metacritic.get('metaScore')),
metacount=str(metacritic.get('reviewCount', 0)),
metauser=str(metacritic.get('userScore')),
metavotes=str(metacritic.get('userRatingCount', 0)),
votes=summary['votes'],
runtime=summary['runtime'],
directors=" | ".join(imdb_link(d) for d in summary['directors']),
writers=" | ".join(imdb_link(w) for w in summary['writers']),
cast=" | ".join(imdb_link(a) for a in summary['cast'][:n])
)
def _render_section_description(self):
s = self['summary']
return s['description']
def _render_description(self):
# todo: templating, rottentomatoes, ...
sections = [("Description", self['section_description']),
("Information", self['section_information'])]
description = "\n".join(bb.section(*s) for s in sections)
description += bb.release
return description
@form_field('desc')
def _render_form_description(self):
return self['description']
class BookSubmission(BbSubmission):
_cat_id = 'book'
_form_type = 'E-Books'
def _desc(self):
s = self['summary']
return re.sub('<[^<]+?>', '', s['description'])
def _render_scene(self):
return False
@form_field('book_retail', 'checkbox')
def _render_retail(self):
return bool(
input('Is this a retail release? [y/N] ').lower()
== 'y')
@form_field('book_language')
def _render_language(self):
return self['summary']['language']
@form_field('book_publisher')
def _render_publisher(self):
return self['summary']['publisher']
@form_field('book_author')
def _render_author(self):
return self['summary']['authors'][0]['name']
@form_field('book_format')
def _render_format(self):
book_format = {
'EPUB': 'EPUB',
'MOBI': 'MOBI',
'PDF': 'PDF',
'HTML': 'HTML',
'TXT': 'TXT',
'DJVU': 'DJVU',
'CHM': 'CHM',
'CBR': 'CBR',
'CBZ': 'CBZ',
'CB7': 'CB7',
'TXT': 'TXT',
'AZW3': 'AZW3',
}
_, ext = os.path.splitext(self['path'])
return book_format[ext.replace('.', '').upper()]
def _render_summary(self):
gr = goodreads.Goodreads()
return gr.search(self['path'])
@form_field('book_year')
def _render_year(self):
if 'summary' in self.fields:
return self['summary']['publication_year']
else:
while True:
year = input('Please enter year: ')
try:
year = int(year)
except ValueError:
pass