-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathWTV-MetaRenamer.ps1
2842 lines (2532 loc) · 116 KB
/
WTV-MetaRenamer.ps1
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
# WTV-MetaRenamer.ps1
#
# Script to scan a folder of WTV files, retrieve the metadata from each file
# and then look on TVDB (and local caches of said data) for matches of
# series name, season number and episode number against that metadata.
#
# If a match is made, the file is renamed and details kept in the undo PS1 file for easy reversal.
#
# Version history:
# 0.00 Initial version
# 0.01 Changed name of config XML file and tweaked text output.
# 0.02 Fixed issue #284 - BestMatchEpisode will pick empty episode names
# Fixed issue #282 - Proposed improvement to series name matching
# Fixed issue #285 - Add option to pick single matches
# Fixed issue #283 - Add interactive mode
# Fixed issue #337 - BME doesn't work if no valid episode name text can be found
# 0.03 Improved handling if series/episode information isn't cached AND cannot be retrieved from thetvdb
# Tidied up handling of getting settings from the config file
# Implemented new functionality to optionally MOVE programmes instead of just renaming them
# Move can either be to a single directory or to a series/season structure
# Implemented new functionality to perform character remapping
# 0.04 Fixed bug in handling of $move_to; added tests for whether or not it is an array (#479)
# 0.05 Added new functionality:
# flag to control whether or not the series folder is created if missing
# flag & code to control if the recording is deleted if the destination file already exists
# flag & code to control operating on a recording if it is older than the minimum age (#465)
# flag & code to control ignoring certain series (#416)
# 0.06 Fixed bug in test to check for colon in description. Now looks for colon and a space so that "4:50 From Paddington"
# doesn't get mis-parsed. Similar change made for ". "
# Fixed bug in loading of booleans from XML config file
# Fixed bug in handling of min_age functionality
# 0.07 Fixed bug introduced in the previous change of handling of regex usage.
# Added a check in RemapFilename to make sure we've actually got some char mappings.
# Fixed bug in FetchSeriesID so that broadcaster's programme name is saved, not TvDB's.
# 0.08 New functionality to support selecting ONLY specific series (to counter-point ignoring certain series).
# New functionality to control the output of logging; can now log processing info to a file.
# New functionality to move unmatched series and episodes to different folders for later examination.
# New functionality to move duplicates to a different folder for storage in case of errors either in the script
# or in previous recordings of the same episode.
# Tweak BME processing so that if the number of changes required is > 50% the length of the string, it is ignored.
# 0.09 Added support for non-English languages.
# Added configuration item to support different formats of renaming.
# Added configuration item to move ignored programmes to a folder.
# 0.10 Changed calls to GetDetailsOf to use a function instead so that the textual name of the attribute can be used
# instead of a fixed index number. Win7 SP1 changed the index numbers!
# Strange workaround required in GetSeriesID where we now seem to have to force a ToString conversion on a value
# that is already a string!
# 0.11 Added extra calls to ToString in GetSeriesID (overlooked in v0.10).
# 0.12 Added attributes to config file so that file attribute names can be changed from English easily if required.
# Now look up attribute indexes once when script runs instead of calling the function introduced in 0.10.
# Now remap the series name when using it for folder names
# Added functionality to optionally convert to DVR-MS as part of the renaming process
# 0.13 Added airdate to output of episode titles if not possible to match (Work item 1169)
# Added commandline support for -whatif and -verbose
# Added new parameters to config file to specify names of attributes for Recording time and Broadcast date
# Added capability, on a per series basis, to use the broadcast date or recording date as a match
# 0.14 Fixed bug that meant the check for recording date was only used if checking for broadcast date
# 0.15 Added debugging to the episode fetcher to try to troubleshoot a problem
# 0.16 Improvement to episode name matching (work item 570)
# Move and rename commercial skip metadata with wtv file (work item 1120)
# Specify location of undo and processing logs (work item 1344)
# Accept a single file to process (work item 1345)
# Season 0 needs to map to Specials (work item 1399)
# Move files to a series folder even if no match in TVDB (work item 1584)
# Fixed bug in extraction of episode info (work item 1725)
# Support for two episodes packaged within a single recording (work item 1582)
# 0.17 Bug fix: typo (work item 1732)
# Feature: rename if destination file exists (work item 1733)
# 0.18 Bug fix: date matching (work items 2034 & 1781)
# Bug fix: execution path improvement (work item 2032)
# Feature: extension of moving metadata (work item 1120)
# 0.19 Bug fix: changed API key for TheTVDB (work item 2439)
# Feature: flexible naming for multi-episodes (work item 2220)
# 0.20 Made mirror allocation more robust
# 0.21 Bug fix: work item 2447 (bug in MoveFile)
# Bug fix: work item 2446 (bug in GetMultiEpisodeFormat)
# 0.22 Improvement to make it easier to use WTV-MetaRenamer with a drag & drop batch file
# 0.23 Bug fix: extensions for metadata files weren't being handled properly
#
# Original author: Philip Colmer
param([string]$configurationfile, [string]$singlefile, [switch]$interactive, [switch]$whatif, [switch]$verbose)
if ($verbose.IsPresent)
{ $VerbosePreference = "Continue" }
else
{ $VerbosePreference = "SilentlyContinue" }
if ($whatif.IsPresent)
{ $WhatIfPreference = $true }
else
{ $WhatIfPreference = $false }
Set-StrictMode –version Latest
$version = "0.23"
$i_am_here = Split-Path -parent $MyInvocation.MyCommand.Definition
function get-ld
{
# get-ld.ps1 (Levenshtein Distance)
# Levenshtein Distance is the # of edits it takes to get from 1 string to another
# This is one way of measuring the "similarity" of 2 strings
# Many useful purposes that can help in determining if 2 strings are similar possibly
# with different punctuation or misspellings/typos.
#
# From https://www.codeproject.com/Tips/102192/Levenshtein-Distance-in-Windows-PowerShell.aspx
#
########################################################
# Putting this as first non comment or empty line declares the parameters
# the script accepts
###########
param([string] $first, [string] $second, [switch] $ignoreCase)
# No NULL check needed, why is that?
# PowerShell parameter handling converts Nulls into empty strings
# so we will never get a NULL string but we may get empty strings(length = 0)
#########################
$len1 = $first.length
$len2 = $second.length
# If either string has length of zero, the # of edits/distance between them
# is simply the length of the other string
#######################################
if($len1 -eq 0)
{ return $len2 }
if($len2 -eq 0)
{ return $len1 }
# make everything lowercase if ignoreCase flag is set
if($ignoreCase -eq $true)
{
$first = $first.tolowerinvariant()
$second = $second.tolowerinvariant()
}
# create 2d Array to store the "distances"
$dist = new-object -type 'int[,]' -arg ($len1+1),($len2+1)
# initialize the first row and first column which represent the 2
# strings we're comparing
for($i = 0; $i -le $len1; $i++)
{ $dist[$i,0] = $i }
for($j = 0; $j -le $len2; $j++)
{ $dist[0,$j] = $j }
$cost = 0
for($i = 1; $i -le $len1;$i++)
{
for($j = 1; $j -le $len2;$j++)
{
if($second[$j-1] -ceq $first[$i-1])
{
$cost = 0
}
else
{
$cost = 1
}
# The value going into the cell is the min of 3 possibilities:
# 1. The cell immediately above plus 1
# 2. The cell immediately to the left plus 1
# 3. The cell diagonally above and to the left plus the 'cost'
##############
# I had to add lots of parentheses to "help" the Powershell parser
# And I separated out the tempmin variable for readability
$tempmin = [System.Math]::Min(([int]$dist[($i-1),$j]+1) , ([int]$dist[$i,($j-1)]+1))
$dist[$i,$j] = [System.Math]::Min($tempmin, ([int]$dist[($i-1),($j-1)] + $cost))
}
}
# the actual distance is stored in the bottom right cell
return $dist[$len1, $len2];
}
function Write-VerboseAndLog($str)
{
Write-Verbose $str
if ($create_processing_logs)
{ $str >> $processing_log }
}
function Write-HostAndLog($str)
{
# Only output to host if running in interactive mode OR
# we aren't outputting to the log file
if ($interactive -eq $true -or $create_processing_logs -eq $false)
{ Write-Host $str}
if ($create_processing_logs)
{ $str >> $processing_log }
}
function FetchXml($url)
{
$result = New-Object XML
try
{
# $result = [xml](New-Object System.Net.WebClient).DownloadString($url)
$result.Load($url)
}
catch
{
Write-HostAndLog "... Error! Failed to retrieve $url"
$result = $null
}
Write-Output $result
}
function NodeExists($xmlnode, $to_match)
{
$this_node = $xmlnode.FirstChild
do
{
if ($this_node.name -eq $to_match)
{
return $true
}
$this_node = $this_node.NextSibling
} while ($this_node -ne $null)
# Failed to match the node name we are looking for
Write-Output $false
}
function AllocateDBMirror
{
try
{
$mirrors = FetchXML "http://www.thetvdb.com/api/$apikey/mirrors.xml"
}
catch
{
$mirrors = null
}
if ($mirrors -ne $null)
{
# Find the mirrors that host XML (bit mask 1)
$xml_mirrors = $mirrors.Mirrors.Mirror | Where-Object { $_.typemask -band 1 }
# Count them so that we can then pick one at random
$count = 0
foreach ($mirror in $xml_mirrors) { $count++ }
if ($count -eq 1)
{
Write-Output $xml_mirrors.mirrorpath
}
else
{
$rand = New-Object System.Random
$this_one = $rand.Next(1,$count+1)
foreach ($mirror in $xml_mirrors)
{
if ($count -eq $this_one) { Write-Output $mirror.mirrorpath; return }
$count--
}
}
}
else
{
# default to a sensible value
Write-Output "http://thetvdb.com"
}
}
function BestMatchEpisode($text)
{
# This function is called when we have a string to try to match against the episode
# names but the string isn't matching 100% accurately. For each episode, we calculate
# the edit distance and use that as an "accuracy" score. After we've performed all
# of the tests, we'll check the overall accuracy scores to see if there is one we are
# happy with.
#
# Note that if $interactive is true, we output $text to Host rather than Verbose so that if we don't get a match,
# the user has some context to help them pick matches against
if ($interactive)
{
Write-Host "... BestMatchEpisode called for '$text'"
}
else
{
Write-VerboseAndLog "... BestMatchEpisode called for '$text'"
}
# If the text we are being asked to test against is more than twice the length of
# the longest episode name we have, this probably isn't valid text. For example, it
# could be the episode synopsis.
#
# Retrieve the previously calculated longest episode name - it is stored
# in the SERIES ID attribute, not the Episode ID (which is used for the scoring)
$longest_episode_name = $episodes.Data.Series.GetAttribute("ID")
if ($text.Length -gt (2 * $longest_episode_name))
{ Write-VerboseAndLog "... BestMatchEpisode: ignoring very long text to test against"; return }
# We also won't bother if we haven't been passed anything!
if ($text.Length -eq 0)
{ Write-VerboseAndLog "... BestMatchEpisode: ignoring empty text to test against"; return }
foreach ($episode in $episodes.Data.Episode)
{
# Calculate how many characters would need to be changed in order to match the episode name
$score = Get-Ld $($episode.EpisodeName) $text -i
# 0.08: if the score is greater than 50% of the length of $text, we are going to ignore it
if ($score -gt ($text.Length / 2))
{
Write-VerboseAndLog "... '$($episode.EpisodeName)': ignoring score of $score as it exceeds the 50% threshold"
$score = -1
}
elseif (($score -lt $episode.GetAttribute("ID")) -or (-1 -eq $episode.GetAttribute("ID")))
{
Write-VerboseAndLog "... '$($episode.EpisodeName)': replacing previous score of $($episode.GetAttribute("ID")) with $score"
$episode.SetAttribute("ID", $score)
}
else
{
Write-VerboseAndLog "... '$($episode.EpisodeName)': ignoring score of $score as this is larger than previous score of $($episode.GetAttribute("ID"))"
}
}
}
function GetInputFromUser($upper)
{
# Get input from the user and validate it as either an empty string
# or a number in the range 1 to $upper.
# If an empty string, return -1.
$answer = 0
do
{
$val = Read-Host
if ($val -ne "")
{
$intval = 0
if ([int]::TryParse($val, [ref]$intval))
{
if ($intval -ge 1 -and $intval -le $upper)
{ $answer = $intval }
}
}
else
{ $answer = -1 }
} while ( $answer -eq 0 )
return $answer
}
function MatchEpisodeByDate($date)
{
# Looks through the XML data that has been preloaded into $episodes
# to see if there is an episode that has a matching date
# Either returns the season and episode numbers if a match found, or -1 if more
# than one match found, or 0 if no match found.
# The XML has the dates in the format yyyy-mm-dd so let's build a string to search for
$m = $([int]$date.month).ToString("0#")
$d = $([int]$date.day).ToString("0#")
$search = "$($date.year)-$m-$d"
Write-VerboseAndLog "... MatchEpisodeByDate: trying to find an episode with a date of '$search'"
$match = $episodes.Data.Episode | Where-Object { $_.FirstAired -eq $search }
if ($match -ne $null)
{
# Matched - but how many times?
$count = 0
foreach ($ep in $match) { $count++ }
if ($count -eq 1)
{
if ($match.EpisodeNumber -ne 0)
{
Write-Output ([int]$match.SeasonNumber)
Write-Output ([int]$match.EpisodeNumber)
}
else
{
# An episode number of 0 isn't valid
Write-VerboseAndLog "... matched but invalid episode number"
Write-Output ([int]0)
Write-Output ([int]0)
}
}
else
{
Write-VerboseAndLog "... more than 1 match"
Write-Output ([int]-1)
Write-Output ([int]-1)
}
}
else
{
# Not matched - return zeroes
Write-VerboseAndLog "... didn't match date"
Write-Output ([int]0)
Write-Output ([int]0)
}
}
function MatchEpisodePrecisely($text)
{
# Looks through the XML data that has been preloaded into $episodes
# to see if there is an episode that has an episode name matching the passed text
# Either returns the season and episode numbers if a match found, or -1 if more
# than one match found, or 0 if no match found.
Write-VerboseAndLog "... MatchEpisodePrecisely: trying to find an episode that matches '$text'"
$match = $episodes.Data.Episode | Where-Object { $_.EpisodeName -eq $text }
if ($match -ne $null)
{
# Matched - but how many times?
$count = 0
foreach ($ep in $match) { $count++ }
if ($count -eq 1)
{
if ($match.EpisodeNumber -ne 0)
{
Write-VerboseAndLog "... matched once; returning season and episode number"
Write-Output ([int]$match.SeasonNumber)
Write-Output ([int]$match.EpisodeNumber)
}
else
{
# An episode number of 0 isn't valid
Write-VerboseAndLog "... matched but invalid episode number"
Write-Output ([int]0)
Write-Output ([int]0)
}
}
else
{
# This bit of code is used if the function has managed to precisely match
# the episode name, but has done so more than once. Rare, but it happens.
Write-HostAndLog "... matched $count times - unable to safely rename"
$index = 1
foreach ($ep in $match)
{
$s = $([int]$ep.SeasonNumber).ToString("0#")
$e = $([int]$ep.EpisodeNumber).ToString("0#")
$a = $ep.FirstAired
if ($a -ne $null)
{ $a = "[Original airdate: $a]" }
if ($interactive)
{
Write-Host "... [$index] S$($s)E$($e) - $($ep.EpisodeName) $a"
}
else
{
Write-HostAndLog "... S$($s)E$($e) - $($ep.EpisodeName) $a"
}
$index++
}
# We end up with index being one too high ...
$index--
if ($interactive)
{
Write-Host "... Enter a number from 1 to $index or RETURN to skip"
$answer = GetInputFromUser $index
if ($answer -ne -1)
{
# User provided an answer in the correct range so find it and return
# that to the function caller
$index = 1
foreach ($ep in $match)
{
if ($index -eq $answer)
{
Write-Output ([int]$ep.SeasonNumber)
Write-Output ([int]$ep.EpisodeNumber)
return
}
$index++
}
}
}
Write-Output ([int]-1)
Write-Output ([int]-1)
}
}
else
{
# Not matched - return zeroes
Write-VerboseAndLog "... didn't match text"
Write-Output ([int]0)
Write-Output ([int]0)
}
}
function MatchEpisodeImprecisely($text)
{
# Looks through the XML data that has been preloaded into $episodes
# to see if there is an episode that has an episode name matching the passed text
# Either returns the season and episode numbers if a match found, or -1 if more
# than one match found, or 0 if no match found.
Write-VerboseAndLog "... MatchEpisodeImprecisely: trying to find an episode that matches '$text'"
# V0.16: Match test changed to include a comparison with all special characters stripped out
$match = $episodes.Data.Episode | Where-Object {(($text -replace "\'|\,|\!|\?|\-|\.| ","") -match ($_.EpisodeName -replace "\'|\,|\!|\?|\-|\.| ","") -and $_.EpisodeName -ne "")}
if ($match -ne $null)
{
# Matched - but how many times?
$count = 0
foreach ($ep in $match) { $count++ }
if ($count -eq 1)
{
if ($match.EpisodeNumber -ne 0)
{
Write-Output ([int]$match.SeasonNumber)
Write-Output ([int]$match.EpisodeNumber)
}
else
{
# An episode number of 0 isn't valid
Write-VerboseAndLog "... matched but invalid episode number"
Write-Output ([int]0)
Write-Output ([int]0)
}
}
else
{
# This bit of code is used if the function has managed to precisely match
# the episode name, but has done so more than once. Rare, but it happens.
Write-HostAndLog "... matched $count times - unable to safely rename"
$index = 1
foreach ($ep in $match)
{
$s = $([int]$ep.SeasonNumber).ToString("0#")
$e = $([int]$ep.EpisodeNumber).ToString("0#")
$a = $ep.FirstAired
if ($a -ne $null)
{ $a = "[Original airdate: $a]" }
if ($interactive)
{
Write-Host "... [$index] S$($s)E$($e) - $($ep.EpisodeName) $a"
}
else
{
Write-HostAndLog "... S$($s)E$($e) - $($ep.EpisodeName) $a"
}
$index++
}
# We end up with index being one too high ...
$index--
if ($interactive)
{
Write-Host "... Enter a number from 1 to $index or RETURN to skip"
$answer = GetInputFromUser $index
if ($answer -ne -1)
{
# User provided an answer in the correct range so find it and return
# that to the function caller
$index = 1
foreach ($ep in $match)
{
if ($index -eq $answer)
{
Write-Output ([int]$ep.SeasonNumber)
Write-Output ([int]$ep.EpisodeNumber)
return
}
$index++
}
}
}
Write-Output ([int]-1)
Write-Output ([int]-1)
}
}
else
{
# Not matched - return zeroes
Write-VerboseAndLog "... didn't match text"
Write-Output ([int]0)
Write-Output ([int]0)
}
}
function FetchEpisodeInfo($series_info)
{
$this_series_id = [int]$series_info[0]
$this_series_lang = $series_info[1]
# V0.16: Don't try to fetch episode information if the ID is negative
if ($this_series_id -lt 0)
{
Write-VerboseAndLog "... negative series number => returning no episode info"
return $null
}
# Have we already got the episode information for this series? If we
# have, load it and return.
$episode_info = New-Object XML
try
{
$episode_info.Load("$data_loc\EpInfo\$this_series_id.xml")
Write-VerboseAndLog "... retrieved episode information from cache"
}
catch
{
# Write-VerboseAndLog "... got error $Error[0] while trying to retrieve ep info from cache"
# We got an error, so let's request the base information, extract
# the en.xml file and save it as the info for this series.
# But let's also cope with the possibility that we can't retrieve the XML data from the server either!
trap {
Write-HostAndLog "... got error while trying to retrieve episode information from server"
Write-HostAndLog "... $($_.Exception.Message)"
return $null
}
$url = "$tvdb_mirror/api/$apikey/series/$this_series_id/all/$this_series_lang.zip"
Write-VerboseAndLog "... about to fetch '$url'"
$req = [System.Net.HttpWebRequest]::Create($url)
$res = $req.GetResponse()
if ($res.StatusCode -eq 200)
{
Write-VerboseAndLog "... got OK status code back"
$reader = $res.GetResponseStream()
# V0.16: Make sure the temporary zip file doesn't exist
if (Test-Path "$data_loc\EpInfo\Tmp.zip")
{ Remove-Item "$data_loc\EpInfo\Tmp.zip" }
$writer = New-Object System.IO.FileStream "$data_loc\EpInfo\Tmp.zip", "Create"
[byte[]]$buffer = New-Object byte[] 4096
Write-VerboseAndLog "... about to chunk the data"
do
{
$count = $reader.Read($buffer, 0, $buffer.Length)
Write-VerboseAndLog "... block read"
$writer.Write($buffer, 0, $count)
Write-VerboseAndLog "... and written"
} while ($count -gt 0)
Write-VerboseAndLog "... transfer done"
$reader.Close()
$writer.Flush()
$writer.Close()
$res.Close()
# Now extract "<language>.xml" from the Zip file
Write-VerboseAndLog "... opening Zip file"
$zip = New-Object Ionic.Zip.ZipFile("$data_loc\EpInfo\Tmp.zip")
$zip_item = $zip["$this_series_lang.xml"]
Write-VerboseAndLog "... extracting $this_series_lang.xml"
# V0.16: ensure we don't have a file there already as the Zip library won't overwrite it
if (Test-Path "$data_loc\EpInfo\$this_series_lang.xml")
{ Remove-Item "$data_loc\EpInfo\$this_series_lang.xml" }
$zip_item.Extract("$data_loc\EpInfo")
Write-VerboseAndLog "... extracted to EpInfo"
$zip.Dispose()
# Delete the zip file and rename the XML file
Remove-Item "$data_loc\EpInfo\Tmp.zip"
Rename-Item "$data_loc\EpInfo\$this_series_lang.xml" "$this_series_id.xml"
Write-VerboseAndLog "... loading '$data_loc\EpInfo\$this_series_id.xml'"
$episode_info.Load("$data_loc\EpInfo\$this_series_id.xml")
Write-VerboseAndLog "... downloaded episode information from server"
}
else
{
Write-VerboseAndLog "... failed to retrieve episode information from server"
return $null
}
}
# Pre-set the edit distance scores to be -1.
# The value is stored as an attribute of the ID node as an easy way to stash it.
# Also track the length of the longest episode name so that we can try to be
# smarter about when we use best match calculations if the test text is way too long.
$longest_episode_name = 0
foreach ($episode in $episode_info.Data.Episode)
{
$this_ep_length = $($episode.EpisodeName).Length
$episode.SetAttribute("ID", -1)
if ($this_ep_length -gt $longest_episode_name)
{ $longest_episode_name = $this_ep_length }
}
# Store the longest length in the *SERIES* ID attribute
$episode_info.Data.Series.SetAttribute("ID", $longest_episode_name)
# Return the XML data
Write-Output $episode_info
}
function FetchSeriesID($series_name)
{
# Make sure we have been given a series name!
if ($series_name -eq "")
{
Write-HostAndLog "... no series name provided"
return $null
}
# Check to see if the series name has been entered into the cached series database
$series_list = New-Object XML
$series_list.Load("$data_loc\SeriesList.xml")
$this_series = $series_list.Data.Series | Where-Object { $_.SeriesName -eq $series_name }
if ($this_series -ne $null)
{
# Got a match - return the series ID
Write-VerboseAndLog "... FetchSeriesID returning $($this_series.seriesid) from cache"
Write-Output $this_series.seriesid
# If this entry in the cache specifies a language code, return that, otherwise
# return the default language code.
if (NodeExists $this_series "language")
{
Write-VerboseAndLog "... returning language code $($this_series.language)"
Write-Output $this_series.language
}
else
{
Write-VerboseAndLog "... returning default language code $default_language"
Write-Output $default_language
}
# If this entry in the cache specifies that we can use the broadcast date or the
# date of recording, return that otherwise return false.
if (NodeExists $this_series "MatchBroadcastDate")
{
Write-VerboseAndLog "... returning MatchBroadcastDate as $($this_series.MatchBroadcastDate)"
Write-Output $this_series.MatchBroadcastDate
}
else
{
Write-VerboseAndLog "... returning MatchBroadcastDate as $false"
Write-Output $false
}
if (NodeExists $this_series "MatchRecordingDate")
{
Write-VerboseAndLog "... returning MatchRecordingDate as $($this_series.MatchRecordingDate)"
Write-Output $this_series.MatchRecordingDate
}
else
{
Write-VerboseAndLog "... returning MatchBroadcastDate as $false"
Write-Output $false
}
# Return the matching series name as well as this is needed by v0.16 when no episode data exists
Write-Output $series_name
return
}
# If it hasn't, try to retrieve the series ID from TvDB. If only one series is returned
# we'll go with that. If more than one, list them out for the user to manually update
# the file and then bork.
$series_info = FetchXML "$tvdb_mirror/api/GetSeries.php?seriesname='$series_name'"
if (($series_info -ne $null) -and ($series_info.data -ne ""))
{
$count = 0
foreach ($this_series in $series_info.Data.Series) { $count++ }
if ($count -gt 1)
{
# More than one match returned from TvDB - but does one of them match completely?
Write-VerboseAndLog "... TvDB has returned multiple matches"
foreach ($this_series in $series_info.Data.Series)
{
if ($this_series.SeriesName -eq $series_name)
{
Write-VerboseAndLog "... got precise match"
# Add the series information automatically to the list file
$series_xml = @($series_list.Data.Series)[0]
$new_series_xml = $series_xml.Clone()
$new_series_xml.seriesid = $this_series.seriesid
# Changed to save *broadcaster's* series name, not TvDB's
$new_series_xml.SeriesName = $series_name.ToString() # $this_series.SeriesName
$rubbish_output = $series_list.Data.AppendChild($new_series_xml)
$series_list.Save("$data_loc\SeriesList.xml")
Write-VerboseAndLog "... returning $($this_series.seriesid), language $default_language, MatchBroadcastDate = false and MatchRecordingDate = false"
Write-Output $this_series.seriesid
Write-Output $default_language
Write-Output $false
Write-Output $false
# Return the matching series name as well as this is needed by v0.16 when no episode data exists
Write-Output $series_name
return
}
}
}
if ($count -eq 1)
{
Write-VerboseAndLog "... FetchSeriesID has retrieved one match from TvDB"
Write-VerboseAndLog "... cloning XML entry for '$series_name'"
# Add the series information automatically to the list file
$series_xml = @($series_list.Data.Series)[0]
$new_series_xml = $series_xml.Clone()
$new_series_xml.seriesid = $series_info.Data.Series.seriesid
# Changed to save *broadcaster's* series name, not TvDB's
# Not sure what has broken PowerShell here but we seem to have to force a conversion
# of a string to a string!
$new_series_xml.SeriesName = $series_name.ToString() # $series_info.Data.Series.SeriesName
$rubbish_output = $series_list.Data.AppendChild($new_series_xml)
$series_list.Save("$data_loc\SeriesList.xml")
Write-VerboseAndLog "... returning $($series_info.Data.Series.seriesid), language $default_language, MatchBroadcastDate = false and MatchRecordingDate = false"
Write-Output $series_info.Data.Series.seriesid
Write-Output $default_language
Write-Output $false
Write-Output $false
# Return the matching series name as well as this is needed by v0.16 when no episode data exists
Write-Output $series_name
}
else
{
if ($interactive)
{
Write-Host "More than one series matches series name '$series_name':"
}
else
{
Write-HostAndLog "More than one series matches series name '$series_name':"
}
$index = 1
foreach ($this_series in $series_info.Data.Series)
{
if ($interactive)
{
Write-Host "... [$index] $($this_series.SeriesName)"
}
else
{
Write-HostAndLog "ID: $($this_series.seriesid); Name: $($this_series.SeriesName)"
}
$index++
}
# We end up with index being one too high ...
$index--
if ($interactive)
{
Write-Host "... Enter a number from 1 to $index or RETURN to skip"
$answer = GetInputFromUser $index
if ($answer -ne -1)
{
# User provided an answer in the correct range so find it and return
# that to the function caller
$index = 1
foreach ($this_series in $series_info.Data.Series)
{
if ($index -eq $answer)
{
# Add the series information automatically to the list file
# N.B. Because there were multiple matches for the series name
# provided, and the user has made their choice, we are going to
# record the pairing of the series name PROVIDED and the matching
# series ID. We DON'T record the *actual* series name otherwise
# it won't match next time either!
Write-VerboseAndLog "... series ID selected as $($this_series.seriesid)"
$series_xml = @($series_list.Data.Series)[0]
$new_series_xml = $series_xml.Clone()
$new_series_xml.seriesid = $this_series.seriesid
$new_series_xml.SeriesName = $series_name.ToString()
$rubbish_output = $series_list.Data.AppendChild($new_series_xml)
$series_list.Save("$data_loc\SeriesList.xml")
Write-Output $this_series.seriesid
Write-Output $default_language
Write-Output $false
Write-Output $false
# Return the matching series name as well as this is needed by v0.16 when no episode data exists
Write-Output $series_name
return
}
$index++
}
}
}
return $null
}
}
else
{
Write-VerboseAndLog "... failed to retrieve series information from TvDB"
return $null
}
}
function SafeBooleanConvert([string]$value)
{
if (($value -eq '$true') -or ($value -eq "true") -or ($value -eq "1") -or ($value -eq "yes") -or ($value -eq "y"))
{ return $true }
if (($value -eq '$false') -or ($value -eq "false") -or ($value -eq "0") -or ($value -eq "no") -or ($value -eq "n") -or ($value -eq ""))
{ return $false }
throw "Cannot convert '$value' to boolean"
return $null
}
function CheckForUpdatesSinceLastRun()
{
# See if we've been run before (i.e. we preserved the TvDB server time)
try
{
$previous_time = New-Object XML
$previous_time.Load("$data_loc\updates.xml")
}
catch
{
$previous_time = $null
}
# Get the current server time and save it away. We do this before anything
# else as we always want to do this, even if this is the first run.
$server_time = FetchXml "http://www.thetvdb.com/api/Updates.php?type=none"
if ($server_time -ne $null)
{ $server_time.Save("$data_loc\updates.xml") }
# If we have a previous time, see which series have been updated since
# last time. For any series that we have been caching, delete the episode
# cache. This will cause the script to re-download the episode list if
# we need to.
if ($previous_time -ne $null)
{
$time = $previous_time.items.time
$changes = FetchXML "http://www.thetvdb.com/api/Updates.php?type=all&time=$time"
if ($changes -ne $null)
{
if (NodeExists $changes.items "series")
{
foreach ($s in $changes.items.series)
{
if (Test-Path "$data_loc\EpInfo\$s.xml")
{
Write-VerboseAndLog "... series $s has been changed"
# Force -whatif to be false because WhatIfPreference (set at the
# top of the script) would otherwise potentially stop this file
# deletion from happening!
Remove-Item "$data_loc\EpInfo\$s.xml" -whatif:$false
}
}
}
else
{
Write-Host "No series updates"
}
}
}
}
function RemapFilename($name)
{
$new_name = $name
if ($char_map -ne $null)
{
foreach ($cm in $char_map)
{
# convert the "from" string to an array so that we can check for one char at a time
$cma = $($cm.from).ToCharArray()
# then step through each character, trying to replace any occurences with the "to" string
foreach ($c in $cma)
{
$new_name = $new_name.Replace([string]$c, $cm.to)
}
}
}
Write-Output $new_name
}
function SeriesIsInIgnoreList($series_ID)
{
Write-VerboseAndLog "... SeriesIsInIgnoreList"
$result = $false
if ($ignore_series -eq $null)
{
Write-VerboseAndLog "...... ignore list is empty"
}
else
{
foreach ($s in $ignore_series)
{
if ($s -eq $series_ID)
{
Write-HostAndLog "... recording is from a series on the ignore list; skipping"
$result = $true
}
}
}
Write-VerboseAndLog "...... returning $result"
return $result
}
function SeriesIsNotInOnlyList($series_ID)