-
Notifications
You must be signed in to change notification settings - Fork 0
/
vod.py
1970 lines (1693 loc) · 88.1 KB
/
vod.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/python3
import sys
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
try:
TIMEZONE = ZoneInfo("America/Los_Angeles")
except ZoneInfoNotFoundError:
print("\nTimezone info not found. Please run `pip install tzdata` and try again.\n", file=sys.stderr)
sys.exit()
"""
Requires Python 3.9+ (imports zoneinfo). Place this file in your scripts folder.
* Windows users: You will need to run `pip install tzdata` one time to install timezone information.
This script is for criticalrole.miraheze.org when a new video posts to Critical Role's YouTube channel.
To test the script run:
>> python pwb.py vod -simulate -all -ep_id:3x25 -page:User:FCGBot/episode
Example command for cut and pasting in the values:
>> python pwb.py vod -all -ep:3x38 -page:"Campaign 3 Episode 38" -yt:U5mkmw46m4U -new_ep_name:"A Dark Balance" -runtime:4:20:43 -episode_summary:"Bells Hells return to safety..." -actors:"Marisha, Sam" -airdate:2022-10-20 -simulate
A number of maintenance activities can be performed together (-all) or independently:
-update_page Add runtime, thumbnail image & caption, episode summary, & VOD link to episode page
-move Move the episode page from a placeholder name to the name specified in the video
-ep_list Add entry to list of episodes page, as determined from Module:Ep/Decoder
-ep_array In Module:Ep/Array, make new episode title valid input & the display value
-yt_switcher Add the episode + YouTube ID to Module:Ep/YTURLSwitcher
-airdate_order Add the episode id & airdate to Module:AirdateOrder/Array
-transcript Create transcript pages for English and other translations (auto-skips TRANSCRIPT_EXCLUSIONS)
-no_translations Only create the transcript page for English (auto-skips TRANSCRIPT_EXCLUSIONS)
-transcript_list Add transcript page to list of transcripts (auto-skips TRANSCRIPT_EXCLUSIONS)
-ignore_break To manually override break checking for campaign episodes
-upload Upload and link to the episode thumbnail; ignored if already exists
-long_short Check whether the runtime for the episode is one of the longest or shortest
-redirects Make sure episode code redirect(s) exist and link to newest episode name
-navbox Make sure the episode code is in the navbox, as determined from Module:Ep/Decoder
-cite_cat Check if the article maintenance category has been created
-4SD For 4-Sided Dive only, add ep_id to the 3xNN episodes since the previous
-appendix For Midst only, interactively create [[Module:Midst appendices/Array]] entry
Local data can be downloaded from various modules:
-decoder For forcing a re-download of Module:Ep/Decoder. Does not occur with -all
-actor_data For forcing a re-download of Module:ActorData. Does not occur with -all
-download_data For forcing a re-download of all data listed above. Does not occur with -all
Use global -simulate option for test purposes. No changes to live wiki will be done.
For every potential change, you will be shown a diff of the edit and asked to accept or reject it.
No changes will be made automatically. Actions are skipped if change is not needed (e.g., an entry for
the episode already exists on the module page).
All other parameters are passed in the format -parameter:value. Use "quotes" around value if it has
spaces (e.g., -actors:"Marisha, Taliesin, Matt"). If a string includes a "!", it will only work if it is
enclosed in single quotes like '!'.
You will be prompted to enter a missing value if needed. No quotation marks needed in this case.
-ep: REQUIRED. The CxNN code of the episode with newly uploaded VOD (-ep_id also valid)
-page: REQUIRED. The page to be edited, usually current episode page
-yt: The 11-character unique identifier or full URL for the YouTube video (-yt_id also valid)
-airdate: YYYY-MM-DD of the date episode aired. Can be inferred from episode page if filled in.
-airtime: Time of day the episode aired. Optional, can be inferred from episode page if filled in.
-runtime: HH:MM:SS length of the episode video
-actors: L-R of actors in thumbnail. Separate with ','. First names ok (from ActorData list)
-episode_summary: The 1-2 line summary of the episode from the YouTube video.
-old_ep_name: If different from -page:, the current name of the episode (mostly for testing)
-new_ep_name: Where the episode will be moved to, if it has been renamed
-new_page_name: Only if page name differs from new_ep_name (usually 'A' vs 'A (episode)')
-image_name: The name of the thumbnail image file to upload. Automatic and shouldn't be needed.
-file_desc: To override the automatically generated description for an uploaded image
-caption: To override the automatically generated caption for an episode thumbnail
-summary: A pywikibot command that adds an edit summary message and shouldn't be needed.
-host: Actor who is the 4SD host or running one-shot (DM, GM also work here)
-game_system: For one-shots, game system if not Dungeons & Dragons
-airsub: For Midst, the earlier date the episode released to subscribers
-transcript_link: For Midst, the url of the transcript
-illustrator: For Midst, the illustrator of the thumbnail/icon art
-logline: For Midst, the episode quote for the quotebox
-icon_url: For Midst, the url of the .png episode icon
Other parameters (most of which are automatically calculated values but still can be passed in)
can be found in `update_options` for EpisodeBot (line 107).
Potential future features:
1) Make sure that the episode has been removed from upcoming events
2) Pull YouTube info automatically using the YouTube API
This script is a
:py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`. All settings can be
made either by giving option with the command line or with a settings file
which is scripts.ini by default.
"""
# Distributed under the terms of the MIT license.
import re
from copy import deepcopy
from datetime import datetime
import mwparserfromhell
import pywikibot
from pywikibot import pagegenerators
from pywikibot.bot import (
ExistingPageBot,
SingleSiteBot,
QuitKeyboardInterrupt,
)
from pywikibot.specialbots import UploadRobot
import requests
from cr_modules.cr import *
from cr_modules.ep import *
from cr_modules.transcript import YoutubeTranscript, DEFAULT_LANGUAGE
from dupes import DupeDetectionBot
MINISERIES = ['OS', 'E', 'CO', 'MW']
# for streamlining YouTube language codes
LANGUAGE_CONVERSIONS = {
'en-US': 'en',
'en-UK': 'en',
}
class EpisodeBot(
SingleSiteBot, # A bot only working on one site
ExistingPageBot, # CurrentPageBot which only treats existing pages
):
"""
:ivar summary_key: Edit summary message key. The message that should be
used is placed on /i18n subdirectory. The file containing these
messages should have the same name as the caller script (i.e. basic.py
in this case). Use summary_key to set a default edit summary message.
:type summary_key: str
"""
use_redirects = False # treats non-redirects only
update_options = {
'summary': 'Updating newly-released episode page (via pywikibot)',
'yt': None, # YT object
'runtime': None, # how long the episode goes for
'old_ep_name': None, # the old placeholder name of the episode
'new_ep_name': None, # the new official name of the episode
'new_page_name': None, # if different from episode title (usually 'A' vs 'A (episode)')
'ep': None, # Ep object
'image_name': None, # unless specified, builds automatically from Ep.image_filename
'actors': None, # Actors object. list of actors in thumbnail image (optional)
'host': None, # the host (4SD) or GM (one-shot, defaults to Matt)
'game_system': None, # rules for gameplay (one-shot, defaults to Dungeons & Dragons)
'airdate': None, # usually from episode page, used to update list of episodes
'airtime': None, # usually from episode page
'episode_summary': None, # taken from list of episodes to add to episode page
'summary_only': None, # for only adding episode_summary to episode page
'airdate_dict': None, # for using airdates to determine 4SD-C3 episodes
'array_dicts': None, # for converting episode codes into page names and episode titles
'all': None, # run: -update_page, -move, -upload, -ep_list, -yt_switcher, -ep_array, -transcript, -redirects, -navbox
'update_page': None, # update the contents of the episode page (may still need to access for info)
'move': None, # move page (only if new page name exists & is different from old one)
'upload': None, # upload the YouTube video thumbnail
'file_desc': None, # manually created thumbnail file description
'caption': None, # manually created infobox thumbnail caption
'long_short': None, # check whether runtime is one of longest or shortest
'ep_list': None, # add to/update list of episodes
'airdate_order': None, # add to/update the airdate order
'yt_switcher': None, # add to/update the yt url switcher
'ep_array': None, # add to/update the ep array
'transcript': None, # create episode transcript pages (auto-skips TRANSCRIPT_EXCLUSIONS)
'ignore_break': None, # Don't run BreakFinder when generating the transcript
'no_translations': None, # only create English transcript (auto-skips TRANSCRIPT_EXCLUSIONS)
'transcript_list': None, # add transcript page to list of transcripts (auto-skips TRANSCRIPT_EXCLUSIONS)
'TRANSCRIPT_EXCLUSIONS': None, # calculated from Decoder. CxNN prefixes with no transcripts
'ts': None, # YoutubeTranscript object
'redirects': None, # add/update redirects from ep_id to new_page_name
'navbox': None, # add ep_id to the appropriate navbox template
'cite_cat': None, # create article maintenance category for episode code
'4SD': None, # add 4SD param to 3xNN pages (4SD only)
'airsub': None, # date episode released to subscribers (Midst only)
'transcript_link': None, # external transcript link (Midst only)
'illustrator': None, # name of thumbnail illustrator (Midst only)
'logline': None, # add quotebox after infobox (Midst only)
'icon_url': None, # direct url to icon image (Midst only)
'appendix': None, # whether to prompt for appendix (Midst only)
}
@property
def display_ep(self):
display = f'"{self.opt.new_ep_name}" ({self.opt.ep.code})'
return display
def get_wikicode(self):
text = self.current_page.text
wikicode = mwparserfromhell.parse(text)
return wikicode
def get_infobox(self, wikicode=None):
if wikicode is None:
wikicode = self.get_wikicode()
return next(x for x in wikicode.filter_templates() if x.name.matches(INFOBOX_EPISODE))
def move_page(self) -> None:
move_summary = 'Moving page to new episode name (via pywikibot)'
# get the new target title
if not (self.opt.new_page_name or self.opt.new_ep_name):
target_title = pywikibot.input("Please enter the new name of the episode")
elif not self.opt.new_page_name:
target_title = self.opt.new_ep_name
else:
target_title = self.opt.new_page_name
# make sure doesn't conflict with existing page (handling redirects separately)
target_page = pywikibot.Page(self.site, target_title)
if target_page.exists() and not target_page.isRedirectPage():
add_end = pywikibot.input_yn(f"{self.opt.new_page_name} already exists. Add ' (episode)' to page name?")
if add_end:
self.opt.new_page_name = target_title + " (episode)"
else:
new_name = pywikibot.input(f"Please enter new page name for {target_title}")
self.opt.new_page_name = new_name
elif target_page.exists():
overwrite = pywikibot.input_yn(f"{self.opt.new_page_name} is a redirect. Overwrite?")
if overwrite:
new_name = pywikibot.input(f"Please enter new page name for {target_title}")
self.opt.new_page_name = new_name
else:
self.opt.new_page_name = self.opt.new_ep_name
move_it = pywikibot.input_yn(f"Move [[{self.current_page.title()}]] to [[{self.opt.new_page_name}]]?")
if move_it:
pywikibot.output(f"Moving page from [[{self.current_page.title()}]] to [[{self.opt.new_page_name}]]")
old_title = str(self.current_page.title())
self.current_page.move(self.opt.new_page_name,
reason=move_summary,
)
pywikibot.output('Page move complete.')
else:
pywikibot.output('Page move skipped.')
def update_summary(self, wikicode=None):
'''For adding the episode summary to the intro paragraph of the episode article.
It can be added after it is retrieved from an existing list of episodes entry parameter,
or it can be passed into the opening command (presumably, from YouTube description).
'''
if self.opt.summary_only:
self.current_page = pywikibot.Page(self.site, self.opt.new_page_name)
if wikicode is None:
wikicode = self.get_wikicode()
text = str(wikicode)
# if there's an episode summary not included in the text, create new article text
no_markup = ''.join([str(x) for x in wikicode.filter_text()])
if (self.opt.episode_summary and
self.opt.episode_summary not in no_markup):
old_intro = str(wikicode.get_sections(include_lead=True, flat=True)[0])
new_intro = old_intro.rstrip() + ' ' + self.opt.episode_summary + '\n\n'
new_text = str(wikicode).replace(old_intro, new_intro)
else:
new_text = text
# have editor decide whether to add on the summary or not
if new_text != text and self.opt.update_page:
pywikibot.showDiff(text, new_text)
do_it = pywikibot.input_yn('Continue with summary addition?')
if do_it:
wikicode = mwparserfromhell.parse(new_text)
if self.opt.summary_only:
self.put_current(new_text, summary=self.opt.summary)
else:
pass
return wikicode
def handle_infobox_image(self, infobox, param_name='image', image='thumbnail'):
# if image field is filled in with existing file, cancel thumbnail procedure
# otherwise, use image_name if entered
if image == 'thumbnail':
image_name = (self.opt.image_name
if self.opt.get('image_name')
else self.opt.ep.image_filename)
elif image == 'icon':
image_name = self.opt.ep.icon_filename
file = None
if infobox.has_param(param_name) and self.opt.upload:
image_value = (remove_comments(infobox[param_name].value)).strip()
if image_value and 'file' not in image_value.lower():
file_value = 'File:' + image_value
elif not image_value:
file_value = 'File:' + image_name
else:
file_value = image_value
file = pywikibot.Page(self.site, file_value)
if image_value and not image_name:
image_value = image_value.replace('File:', '')
self.opt.image_name = image_value
# if image already (or to be) uploaded but not in param, add to infobox
if not image_value:
infobox[param_name] = image_name
if self.opt.upload and image_value and image_value != image_name:
pywikibot.output(
f'Infobox image {image_value} does not match entered {image_name}. Please resolve and try again.')
sys.exit()
# don't offer to fill in field if upload not in procedure or file doesn't exist
if self.opt.image_name and not file:
file = pywikibot.Page(self.site, image_name)
if not self.opt.upload and (not file or not file.exists()):
pass
elif (image_name and
infobox.has_param('param_name') and
not does_value_exist(infobox, param_name)):
infobox[param_name] = ' ' + image_name.lstrip()
return infobox
def update_4SD_infobox(self, infobox):
params_to_update = {
'image1_tab': 'Main',
'image1': self.opt.ep.image_filename,
'image1_caption': f'{{{{art official caption|nointro=true|subject=Thumbnail|screenshot=1|source={self.opt.ep.wiki_nolink}}}}}',
'image2_tab': 'Game',
'image2': self.opt.ep.game_filename,
'image2_caption': 'Thumbnail for the C-block game portion, entitled More-Sided Dive.'
}
for param_name, default_value in params_to_update.items():
if not does_value_exist(infobox, param_name):
if not infobox.has_param(param_name):
infobox.add(param_name, default_value, before='epCode')
else:
infobox[param_name] = default_value
if infobox.has_param('image'):
infobox.remove('image')
if infobox.has_param('caption'):
infobox.remove('caption')
return infobox
def update_midst_infobox(self, infobox):
params_to_update = {
'image1_tab': 'Icon',
'image1': self.opt.ep.icon_filename,
'image1_caption': 'Icon by Third Person',
'image2_tab': 'Thumbnail',
'image2': self.opt.ep.image_filename,
'image2_caption': 'Thumbnail for the video version'
}
for param_name, default_value in params_to_update.items():
if not does_value_exist(infobox, param_name):
if not infobox.has_param(param_name):
infobox.add(param_name, default_value, before='epCode')
else:
infobox[param_name] = default_value
if infobox.has_param('image'):
infobox.remove('image')
if infobox.has_param('caption'):
infobox.remove('caption')
# subscriber airdate
if not does_value_exist(infobox, 'airsub'):
if self.opt.get('airsub'):
infobox['airsub'] = self.opt.airsub.date
else:
airsub_string = get_validated_input(arg='airsub', regex=DATE_REGEX)
airsub = Airdate(airsub_string)
self.opt.airsub = airsub
infobox['airsub'] = airsub.date
elif self.opt.airsub:
infobox_airsub = Airdate(infobox['airsub'].value.strip())
try:
assert self.opt.airsub.date == infobox_airsub.date
except AssertionError:
new_airsub_string = get_validated_input(arg='airsub', regex=DATE_REGEX, input_msg=f'Infobox airsub {infobox_airsub.date} does not match entered airsub {self.opt.airsub.date}. Enter airsub date (YYYY-MM-DD):')
new_airsub = Airdate(new_airsub_string)
infobox['airsub'] = new_airsub.date
else:
self.opt.airsub = Airdate(infobox['airsub'].value.strip())
try:
assert self.opt.airsub.date <= self.opt.airdate.date
except AssertionError:
print(f'\nAirdate for subscribers {self.opt.airsub.date} is after general airdate {self.opt.airdate.date}. Check dates and try again')
sys.exit()
return infobox
def treat_page(self) -> None:
"""Load the episode page, change the relevant fields, save it, move it."""
# TO DO: split up into multiple functions for each type of update
ep = self.opt.ep
if not self.opt.old_ep_name:
self.opt.old_ep_name = self.current_page.title()
old_ep_name = self.opt.old_ep_name
self.current_page = pywikibot.Page(self.site, old_ep_name)
wikicode = deepcopy(self.get_wikicode())
# prepend short description
# don't add if already exists
shortdesc = next((x for x in wikicode.filter_templates()
if x.name.matches("short description")),
'')
shortdesc_value = ''
if self.opt.update_page:
if (isinstance(shortdesc, mwparserfromhell.wikicode.Template) and
shortdesc[1].strip() != 'Campaign 3 Episode x'):
pywikibot.output("Short description already on episode page; creation skipped.")
elif ep.shortdesc_value:
# if one-shot in the episode title, no shortdesc is needed
if ep.prefix == 'OS' and any(
any(
target.lower() in value.lower()
for target in ['one-shot', 'one shot']
)
for value in [old_ep_name, self.opt.new_ep_name]
):
shortdesc_value = 'none'
else:
shortdesc_value = ep.shortdesc_value
pywikibot.output(f'\nSHORT DESCRIPTION: {shortdesc_value}')
answer = pywikibot.input("Hit enter to accept automatic short description or write your own:")
if answer:
shortdesc_value = answer
else:
pass
else:
write_shortdesc = pywikibot.input_yn("No short description auto-generated. Write one?")
if write_shortdesc:
shortdesc_value = pywikibot.input("Please write the short description (no template info)")
# handle infobox
infobox = self.get_infobox(wikicode=wikicode)
infobox['epCode'] = ep.code
if self.opt.runtime and not does_value_exist(infobox, param_name='runtime'):
# add all runtimes together
total_runtime = str(sum(self.opt.runtime, timedelta()))
if ep.prefix == '4SD' and len(self.opt.runtime) == 2:
# footnote explaining runtime addition for 4SD 2-parters
runtime_footnote = ''.join([
'''{{fn|This episode was uploaded in two parts. ''',
'''The first, which covered the question portions, was uploaded as 4-Sided Dive ''',
f'''and ran for {str(self.opt.runtime[0])}. ''',
'''The second, which covered the game portion, was uploaded as More-Sided Dive ''',
f'''and ran for {str(self.opt.runtime[1])}.}}}}'''
])
total_runtime += runtime_footnote
infobox['runtime'] = total_runtime
# prompt if infobox airdate conflicts w/user entry
if does_value_exist(infobox, 'airdate') and self.opt.airdate:
if Airdate(infobox['airdate'].value.strip()).date == self.opt.airdate.date:
pass
else:
airdate_1 = Airdate(infobox['airdate'].value.strip()).date
airdate_2 = self.opt.airdate.date
if len(airdate_1) and airdate_1 != airdate_2:
new_airdate_string = get_validated_input(arg='airdate', regex=DATE_REGEX, input_msg=f'Infobox airdate {airdate_1} does not match entered airdate {airdate_2}. Enter airdate (YYYY-MM-DD):')
new_airdate = Airdate(new_airdate_string)
self.opt.airdate.datetime = self.opt.airdate.datetime.replace(**{x: getattr(new_airdate.datetime, x) for x in ['day', 'month', 'year']})
infobox['airdate'] = new_airdate.date
else:
infobox['airdate'] = self.opt.airdate
# get the airdate & airtime from infobox so it can be used later
elif does_value_exist(infobox, 'airdate') and not self.opt.airdate:
self.opt.airdate = Airdate(infobox['airdate'].value.strip())
# add airdate to infobox if entered and not already there
elif self.opt.airdate and not does_value_exist(infobox, 'airdate'):
infobox['airdate'] = self.opt.airdate.date
# prompt for airdate if updating episode page, existing field is blank, and not already provided
elif (self.opt.update_page and
not infobox['airdate'].value.strip() and
infobox.has_param('airdate') and
not self.opt.airdate):
airdate_string = get_validated_input(arg='airdate', regex=DATE_REGEX)
self.opt.airdate = Airdate(airdate_string)
infobox['airdate'] = self.opt.airdate.date
else:
self.opt.airdate = ""
if infobox.has_param('airtime') and infobox['airdate'].value.strip() and not self.opt.airtime:
# add airtime to airdate object
self.opt.airtime = Airdate(infobox['airtime'].value.strip())
if self.opt.airtime:
self.opt.airdate = Airdate(datetime.combine(
self.opt.airdate.datetime.date(),
self.opt.airtime.datetime.timetz()))
else:
self.opt.airtime = ""
# Midst: add image fields, plus transcript link
if ep.prefix == 'Midst':
self.handle_infobox_image(infobox, param_name='image1', image='icon')
self.handle_infobox_image(infobox, param_name='image2', image='thumbnail')
self.update_midst_infobox(infobox)
if not does_value_exist(infobox, 'transcript'):
infobox['transcript'] = self.opt.transcript_link
if not does_value_exist(infobox, 'midst illustrator'):
infobox['midst illustrator'] = self.opt.illustrator
elif ep.prefix == '4SD' and len(self.opt.yt) == 2:
infobox = self.update_4SD_infobox(infobox)
else:
infobox = self.handle_infobox_image(infobox)
# only write caption if field not filled in or missing AND image field filled in
if ((not infobox.has_param('caption')
or not does_value_exist(infobox, param_name='caption'))
and does_value_exist(infobox, param_name='image')
and ep.prefix != 'Midst'):
if self.opt.get('caption'):
infobox['caption'] = self.opt['caption']
else:
infobox['caption'] = make_image_caption(actors=self.opt.actors, ep=ep)
# Add game system for one-shots
if (ep.prefix == 'OS' and not
(infobox.has_param('system') or remove_comments(infobox['system'].value)) and
self.opt.get('game_system', '').lower() != 'dungeons & dragons'):
infobox.add('system', self.opt['game_system'], after='runtime')
# add logline for Midst if not there yet
if ep.prefix == 'Midst' and self.opt.get('logline'):
logline = Logline(self.opt['logline'])
if self.opt['logline'] not in wikicode:
wikicode.insert_after(infobox, logline.line)
else:
pywikibot.output(f'Logline already present for {ep.code}; skipping')
if not any([x.name.matches(ep.campaign.navbox) for x in wikicode.filter_templates()]):
wikicode.append('\n' + f"{{{{{ep.campaign.navbox}}}}}")
if self.opt.episode_summary:
wikicode = self.update_summary(wikicode=wikicode)
if (shortdesc and shortdesc_value):
shortdesc.value = shortdesc_value.strip()
text = str(wikicode)
elif shortdesc_value:
shortdesc = f"{{{{short description|{shortdesc_value}}}}}"
text = '\n'.join([str(shortdesc), str(wikicode)])
else:
text = str(wikicode)
# Add {{TranscriptLink}} template to synopsis
link_template = next((x for x in wikicode.filter_templates() if x.name.matches('TranscriptLink')), None)
url = 'Transcript:' + self.opt.new_page_name
transcript_page = pywikibot.Page(self.site, url)
if (not link_template
and (self.opt.transcript or transcript_page.exists())
and self.opt['ep'].prefix not in self.opt.TRANSCRIPT_EXCLUSIONS
):
synopsis_heading = next((x for x in wikicode.filter_headings() if x.title.matches('Synopsis')), None)
if synopsis_heading:
text = text.replace(str(synopsis_heading), str(synopsis_heading) + '\n{{TranscriptLink}}')
assert 'TranscriptLink' in text
else:
pywikibot.output("No synopsis section found; link to transcript in article will not be added.")
if self.opt.update_page:
self.put_current(text, summary=self.opt.summary)
if (self.opt.move or self.opt.all) and self.opt.new_page_name != self.opt.old_ep_name:
self.move_page()
def verify_default_thumbnail_url(yt):
if type(yt) == str:
url = yt
elif type(yt) == YT:
url = yt.thumbnail_url
r = requests.get(url)
if r.ok:
return url
elif type(yt) == YT:
r2 = requests.get(yt.thumbnail_url_backup)
if r2.ok:
return yt.thumbnail_url_backup
return None
def select_thumbnail_url(yt):
'''Interactive way to select thumbnail url if default fails.'''
verified = verify_default_thumbnail_url(yt)
if verified == yt.thumbnail_url:
url = yt.thumbnail_url
elif verified == yt.thumbnail_url_backup:
pywikibot.output('Highest-res YouTube thumbnail was not found.\n')
choices = [('Use lower-res YouTube thumbnail', '1'), ('Use Twitter or other image url', '2')]
response = pywikibot.input_choice(
'What would you like to do?',
choices)
if response == '1':
url = yt.thumbnail_url_backup
else:
url = pywikibot.input('Enter the url for the high-quality episode thumbnail')
else:
url = ''
return url
class EpArrayBot(EpisodeBot):
'''Change the display value for ep_array and add page title as value.
If an entry for the episode does not already exist, it will create one after prev_ep_id.'''
def get_array_dicts(self):
if not self.opt.array_dicts:
self.opt.array_dicts = self.make_array_dicts()
return self.opt.array_dicts
def make_array_dicts(self):
self.current_page = pywikibot.Page(self.site, EP_ARRAY)
array_dicts = []
text = self.current_page.text
for x in re.finditer(ARRAY_ENTRY_REGEX, text):
y = x.groupdict()
if not y['pagename']:
y['pagename'] = ''
if y['altTitles']:
y['altTitles'] = re.findall(r'"(.*?)"', y['altTitles'])
else:
y['altTitles'] = []
array_dicts.append(y)
return array_dicts
def dict_to_entry(self, array_dict):
'''for turning one of these dicts into a string'''
entry = ''
for k, v in array_dict.items():
if not v:
continue
elif k == 'epcode':
entry += f' ["{v}"] = {{' + '\n'
elif isinstance(v, str):
entry += f' ["{k}"] = "{v}"' + ',\n'
elif isinstance(v, list):
list_string = ', '.join([f'"{x}"' for x in v])
entry += f' ["{k}"] = {{{list_string}}}' + ',\n'
else:
raise
entry += ' },\n'
return entry
def build_full_array_page(self, array_dicts):
array_string = 'return {\n'
for array_dict in array_dicts:
entry = self.dict_to_entry(array_dict)
array_string += entry
array_string += '}'
return array_string
def get_current_dict(self, array_dicts):
'''Get array dict for current episode'''
ep = self.opt.ep
current_entry = next((x for x in array_dicts if x['epcode'] ==
ep.code), '')
return current_entry
# replace self.opt.ep.get_prev_episode().code
def get_previous_dict(self, array_dicts):
prev_ep_code = self.opt.ep.get_prev_episode().code
prev_entry = next((x for x in array_dicts if x['epcode'] ==
prev_ep_code), '')
return prev_entry
def build_new_array_dict(self):
'''Creating values for the fields that would populate an episode entry.'''
ep = self.opt.ep
if ep.prefix == '4SD':
display_title = "''4-Sided Dive'': " + self.opt.new_ep_name
else:
display_title = self.opt.new_ep_name
if self.opt.old_ep_name not in [self.opt.new_ep_name, self.opt.new_page_name]:
ep_values = [self.opt.old_ep_name.lower()]
else:
ep_values = []
if self.opt.new_page_name != display_title:
pagename = self.opt.new_page_name
else:
pagename = ''
array_dict = {
'epcode': ep.code,
'title': display_title,
'pagename': pagename,
'altTitles': ep_values,
}
return array_dict
def update_new_dict(self, new_dict, current_dict):
'''Add the existing altTitles together, but assume new_dict is otherwise correct.'''
# Get the 'altTitles' lists from both dictionaries (default to empty lists if the key does not exist)
new_alt_titles = new_dict.get('altTitles', [])
current_alt_titles = current_dict.get('altTitles', [])
# Merge the altTitles lists and remove duplicates
new_dict['altTitles'] = list(dict.fromkeys(new_alt_titles + current_alt_titles))
return new_dict
def treat_page(self):
self.current_page = pywikibot.Page(self.site, EP_ARRAY)
text = self.current_page.text
ep = self.opt.ep
# Replace tabs with 4 spaces
text = text.replace('\t', ' ')
current_entry = next((x for x in re.split(r'\n\s+\},\n',
text) if re.search(fr'\["{ep.code}"\]', x)),
'')
if current_entry:
current_entry += '\n },\n'
array_dicts = self.get_array_dicts()
current_dict = self.get_current_dict(array_dicts=array_dicts)
else:
current_dict = {}
new_dict = self.build_new_array_dict()
new_dict = self.update_new_dict(new_dict, current_dict)
# Make sure that for relevant episode codes it is also the latest
latest = ep.campaign.latest
if latest and latest not in new_dict['altTitles']:
text = re.sub(fr'"{latest}"(, )?', '', text)
new_dict['altTitles'].append(latest)
new_entry = self.dict_to_entry(new_dict)
if current_entry:
text = text.replace(current_entry, new_entry)
else:
prev_entry = next((x for x in re.split(r'\n\s+\},\n',
text) if re.search(fr'\["{ep.get_previous_episode().code}"\]', x)),
'') + '\n },\n'
text = text.replace(prev_entry, '\n'.join([prev_entry, new_entry]))
self.put_current(text, summary=f"Updating {ep.code} entry (via pywikibot)")
class YTSwitcherBot(EpisodeBot):
'''Add yt_link as value by updating or creating entry'''
def treat_page(self):
self.current_page = pywikibot.Page(self.site, YT_SWITCHER)
text = self.current_page.text
ep = self.opt.ep
prev_ep = ep.get_previous_episode()
yt_url_list = [yt.url for yt in self.opt.yt]
# format yt_urls
if len(yt_url_list) == 1:
yt_urls = f'{{"{yt_url_list[0]}"}}'
elif ep.prefix == '4SD':
yt_urls = '\n'.join([
f'{{',
f' {{"{yt_url_list[0]}", "4-Sided Dive"}},',
f' {{"{yt_url_list[1]}", "More-Sided Dive"}},',
f' }}'])
else:
yt_urls = f'{{\n' + ',\n'.join([f' {{"{yt_url}"}}' for yt_url in yt_url_list]) + f'\n}}'
# Pattern to match ep code and its video array
pattern = fr'''\["{ep.code}"\]\s*=\s*(\{{.*?\}},|\{{(?:\s*\{{.*?\}},\s*)+}},)'''
# if it already exists as an entry, substitute in yt_link
if ep.code in text:
text = re.sub(pattern,
fr'''["{ep.code}"] = {yt_urls},''',
text,
flags=re.DOTALL)
# if previous episode is already there, append after it
elif prev_ep and re.search(fr'''\["{prev_ep.code}"\]\s*=\s*\{{.*?\}},''', text):
prev_entry = re.search(fr'''\["{prev_ep.code}"\]\s*=\s*\{{.*?\}},''', text).group()
new_entry = f''' ["{ep.code}"] = {yt_urls},'''
text = text.replace(prev_entry, '\n'.join([prev_entry, new_entry]))
# otherwise, append episode to the end of the list
else:
text = text.replace(
'["default"] = {""}',
f'["{ep.code}"] = {yt_urls},\n ["default"] = {{""}}'
)
self.put_current(text, summary=f"Adding youtube link for {ep.code} (via pywikibot)")
class EpListBot(EpisodeBot):
'''For updating a list of episodes with a brand-new entry or new values for the current episode.'''
def build_episode_entry_dict(self, num=None):
ep = self.opt.ep
'''Creating values for the fields that would populate an episode entry.'''
# default number in table is episode number; can be overwritten
if num is None:
num = str(ep.number)
if self.opt.host:
aux1 = self.opt.host.make_actor_list_string()
else:
aux1 = ''
if self.opt.ep.prefix == '4SD':
wiki_code = ep.wiki_noshow
transcript = ''
elif self.opt.ep.prefix == 'Midst':
wiki_code = ep.wiki_code
transcript = self.opt.transcript_link
aux1 = self.opt.illustrator
else:
wiki_code = ep.wiki_code
transcript = f'{{{{ep/Transcript|{ep.code}|style=unlinked}}}}'
if self.opt.ep.prefix == 'OS':
game_system = self.opt.game_system
else:
game_system = ''
entry_dict = {
'no': num,
'ep': wiki_code,
'airdate': self.opt.airdate.date,
'VOD': ep.wiki_vod,
'transcript': transcript,
'runtime': str(sum(self.opt.runtime, timedelta())),
'aux1': aux1,
'aux2': game_system,
'summary': self.opt.episode_summary,
}
return entry_dict
def build_episode_entry(self, num=None):
'''Create the string for a brand new episode entry.'''
entry_dict = self.build_episode_entry_dict(num=num)
ep_entry = "{{Episode table entry\n"
for k, v in entry_dict.items():
if v:
ep_entry += f'|{k} = {v}' + '\n'
ep_entry += '}}'
return ep_entry
def treat_page(self):
'''Also has the option of getting an existing episode summary from the page.'''
ep = self.opt.ep
prev_ep = ep.get_previous_episode()
list_page_name = ep.campaign.current_list
if not list_page_name:
list_page_name = pywikibot.input(f"Please enter name of list of episodes page for {ep.code}")
self.current_page = pywikibot.Page(self.site, list_page_name)
wikicode = deepcopy(self.get_wikicode())
text = str(wikicode)
# if previous episode isn't there, search episode num - 1 until find one (otherwise none)
while prev_ep and (prev_ep.code.lower() not in text.lower()):
prev_ep = prev_ep.get_previous_episode()
# find previous entry and use to calculate table number two ways
# try finding by episode code
previous_entry_wiki = next((x for x in wikicode.filter_templates()
if x.has_param('ep') and x.name.matches('Episode table entry') and
prev_ep and prev_ep.code in x['ep']), '')
#if that fails, try finding the last entry
if not previous_entry_wiki:
for template in reversed(wikicode.filter_templates()):
if template.name.matches('Episode table entry'):
previous_entry_wiki = template
break
num = int(str(previous_entry_wiki['no'].value)) + 1 if previous_entry_wiki else ep.number
# create new table entry from scratch if it doesn't exist yet, inserting after previous episode
if not any([ep.code in str(x) for x in wikicode.filter_templates()
if x.name.matches('ep')]):
ep_entry = self.build_episode_entry(num=num)
if previous_entry_wiki:
previous_entry = ''.join(['|' + str(x) for x in previous_entry_wiki.params]) + '}}'
if previous_entry in text:
text = text.replace(previous_entry, '\n'.join([previous_entry, ep_entry]))
else:
pywikibot.output(f"Episode table entry for {prev_ep.code} not formatted correctly; cannot insert {ep.code} entry")
elif '}}<section end="episodes" />' in text:
text = text.replace('}}<section end="episodes" />',
ep_entry + '\n}}<section end="episodes" />')
elif '<!-- Place new entries ABOVE this line -->' in text:
text = text.replace('<!-- Place new entries ABOVE this line -->',
ep_entry + '\n<!-- Place new entries ABOVE this line -->')
else:
pywikibot.output("No previous entry or end-of-section marker to append to")
# if the table entry exists, update any individual params to the new ones in ep_entry_dict
# do not overwrite 'no' parameter
else:
ep_entry_dict = self.build_episode_entry_dict(num=num)
existing_entry = next(x for x in wikicode.filter_templates()
if x.has_param('ep') and x.name.matches('Episode table entry') and ep.code in x['ep'])
for k, v in ep_entry_dict.items():
if (v and
not (existing_entry.has_param(k) and
existing_entry[k].value.strip() == v) and
k != 'no'):
if len(str(v).strip()):
existing_entry[k] = v
else:
existing_entry[k] = ' \n' # adding wiki standard whitespace padding
else:
pass # any values already in the table & not in the newly-created entry will be kept
# offer the episode summary if available and if episode page is to be updated
if not self.opt.episode_summary and self.opt.update_page and len(existing_entry['summary'].value.strip()):
eplist_summary = existing_entry['summary'].value.strip()
summ = pywikibot.input_yn(f'\n{eplist_summary}\nUse above existing episode list entry summary on episode page?')
if summ:
self.opt.episode_summary = eplist_summary
else:
pass
text = str(wikicode)
self.put_current(text, summary=f"Updating entry for {ep.code} (via pywikibot)")
class TranscriptBot(EpisodeBot):
'''For creating transcript pages by downloading and processing youtube captions.
Works for both English and all manually translated captions.'''
def build_transcripts(self, no_translations=None):
if no_translations is None:
no_translations = self.opt.no_translations
assert no_translations is not None
if self.opt.ignore_break:
ts = YoutubeTranscript(ep=self.opt.ep, yt=self.opt.yt[0],
actor_data=ACTOR_DATA, ignore_break=True)
else:
ts = YoutubeTranscript(ep=self.opt.ep, yt=self.opt.yt[0],
actor_data=ACTOR_DATA)
if no_translations:
ts.download_and_build_transcript()
else:
ts.download_all_language_transcripts()
return ts
def make_single_transcript_page(self, language=DEFAULT_LANGUAGE):
url = 'Transcript:' + self.opt.new_page_name
self.current_page = pywikibot.Page(self.site, url)
ts = self.build_transcripts(no_translations=True)
if self.current_page.exists() and self.current_page.text:
# if existing transcript page, replace transcript in transcript_dict
# all duplicate line detection and .json should still be the same
pywikibot.output(f'Transcript page already exists for {self.opt.new_page_name}; creation skipped')
ts.transcript_dict[language] = self.current_page.text
else:
transcript_text = ts.transcript_dict.get(language)
self.put_current(transcript_text,
summary=f"Creating {self.opt.ep.code} transcript (via pywikibot)")
self.opt.ts = ts
def make_all_transcript_pages(self):
ts = self.build_transcripts(no_translations=False)
for language, transcript in ts.transcript_dict.items():