-
Notifications
You must be signed in to change notification settings - Fork 5
/
amc.groovy
executable file
·1205 lines (1014 loc) · 42.1 KB
/
amc.groovy
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
// filebot -script "fn:amc" --output "X:/media" --action copy --conflict override --def subtitles=en music=y artwork=y "ut_dir=%D" "ut_file=%F" "ut_kind=%K" "ut_title=%N" "ut_label=%L" "ut_state=%S"
// log input parameters
_def.each{ n, v -> log.finer('Parameter: ' + [n, n =~ /pushover|pushbullet|mail|myepisodes|sonarr|potato|plex|langdetect/ ? '*****' : v].join(' = ')) }
args.each{ log.finer("Argument: $it") }
def output = __args[__args.findIndexOf{ it == "--output"} + 1]
// initialize variables
def input = []
def failOnError = (_args.conflict == 'fail')
// enable/disable features as specified via --def parameters
def unsorted = tryQuietly{ unsorted.toBoolean() }
def music = tryQuietly{ music.toBoolean() }
def subtitles = tryQuietly{ subtitles.split(/\W+/) as List }
def artwork = tryQuietly{ artwork.toBoolean() && !'TEST'.equalsIgnoreCase(_args.action) }
def extras = tryQuietly{ extras.toBoolean() }
def clean = tryQuietly{ clean.toBoolean() }
def exec = tryQuietly{ exec.toString() }
def apiInfo = { url ->
def match = ( url =~ /^(http[s]?\:\/\/)?([\w\.]+)?[\:]?([\d]{1,5})?([\/\w\d]+)?[\|]?([\w\d]+)?$/ )
if (match.matches()) {
match = match[0]
try {
def result = [type:match[1], host:match[2], port:match[3], path:match[4], token:match[5]]
return result
} catch (e) {}
}
return null
}
// array of xbmc/plex hosts
def xbmc = tryQuietly{ xbmc.split(/[ ,|]+/) }
def plex = tryQuietly{ !'TEST'.equalsIgnoreCase(_args.action) ? apiInfo(plex.toString()) : null }
def sonarr = tryQuietly{ !'TEST'.equalsIgnoreCase(_args.action) ? apiInfo(sonarr.toString()) : null }
def potato = tryQuietly{ !'TEST'.equalsIgnoreCase(_args.action) ? apiInfo(potato.toString()) : null }
// extra options, myepisodes updates and email notifications
def storeReport = tryQuietly{ storeReport.toBoolean() }
def skipExtract = tryQuietly{ skipExtract.toBoolean() }
def deleteAfterExtract = tryQuietly{ deleteAfterExtract.toBoolean() }
def excludeList = tryQuietly{ (excludeList as File).isAbsolute() ? (excludeList as File) : new File(_args.output ?: '.', excludeList).getCanonicalFile() }
def myepisodes = tryQuietly{ myepisodes.split(':', 2) }
def gmail = tryQuietly{ gmail.split(':', 2) }
def mail = tryQuietly{ mail.split(':', 3) }
def pushover = tryQuietly{ pushover.toString() }
def pushbullet = tryQuietly{ !'TEST'.equalsIgnoreCase(_args.action) ? pushbullet.toString() : null }
def reportError = tryQuietly{ reportError.toBoolean() }
def subLangFilter = tryQuietly{ subLangFilter.split(",") }
def langdetect = tryQuietly{ langdetect.toString() }
def scratchCleanup = []
// user-defined filters
def label = tryQuietly{ ut_label } ?: null
def ignore = tryQuietly{ ignore } ?: null
def minFileSize = tryQuietly{ minFileSize.toLong() }; if (minFileSize == null) { minFileSize = 50 * 1000L * 1000L }
def minLengthMS = tryQuietly{ minLengthMS.toLong() }; if (minLengthMS == null) { minLengthMS = 10 * 60 * 1000L }
def format = [
tvs: tryQuietly{ seriesFormat } ?: '''TV Shows/{n}/{episode.special ? 'Special' : 'Season '+s.pad(2)}/{n} - {episode.special ? 'S00E'+special.pad(2) : s00e00} - {t.replaceAll(/[`´‘’ʻ]/, /'/).replaceAll(/[!?.]+$/).replacePart(', Part $1')}{'.'+lang}''',
anime: tryQuietly{ animeFormat } ?: '''Anime/{n}/{episode.special ? 'Special' : 'Season '+s.pad(2)}/{primaryTitle} - {sxe} - {t.replaceAll(/[!?.]+$/).replaceAll(/[`´‘’ʻ]/, /'/).replacePart(', Part $1')}''',
mov: tryQuietly{ movieFormat } ?: '''Movies/{n} ({y})/{n} ({y}){' CD'+pi}{'.'+lang}''',
music: tryQuietly{ musicFormat } ?: '''Music/{n}/{album+'/'}{pi.pad(2)+'. '}{artist} - {t}'''
]
/*'*/
// force movie/series/anime logic
def forceMovie = { f ->
label =~ /^(?i:Movie|Couch.Potato)/ ||
(f.name =~ /(?i:Movie)/ && parseEpisodeNumber(f.name, false) == null) ||
f.dir.listPath().any{ it.name ==~ /(?i:Movies)/ } ||
f.path =~ /(?<=tt)\\d{7}/
}
def forceSeries = { f ->
label =~ /^(?i:TV|Kids.Shows)/ ||
f.dir.listPath().any{ it.name ==~ /(?i:TV.Shows)/ } ||
parseEpisodeNumber(f.path) ||
parseDate(f.path) ||
f.path =~ /(?i:tvs-|tvp-|EP[0-9]{2,3}|Season\D?[0-9]{1,2}\D|(19|20)\d{2}.S\d{2})/
}
def forceAnime = { f ->
label =~ /^(?i:Anime)/ ||
f.dir.listPath().any{ it.name ==~ /(?i:Anime)/ } ||
(
f.isVideo() &&
(
f.name =~ /(?i:HorribleSubs)/ ||
f.name =~ "[\\(\\[]\\p{XDigit}{8}[\\]\\)]" ||
getMediaInfo(f, '{media.AudioLanguageList} {media.TextCodecList}').tokenize().containsAll(['Japanese', 'ASS'])
)
)
}
def forceAnimeMovie = { f ->
(
//parseEpisodeNumber(f.name, false) == null &&
//(
f.name =~ /(?i:Movie)/ ||
getMediaInfo(f, '{minutes}').toInteger() > 70
//)
)
}
/*def forceAnimeSeries = { f ->
(
parseEpisodeNumber(f.name, false) != null ||
getMediaInfo(file:f, format:'{minutes}').toInteger() < 60
)
}*/
def forceAudio = { f ->
label =~ /^(?i:audio|music|music.video)/ ||
(
f.isAudio() &&
!f.isVideo()
)
}
def forceIgnore = { f ->
label =~ /^(?i:games|ebook|other|ignore|seeding)/ ||
f.path.findMatch(ignore) != null
}
def forceDVDOrder = { f ->
f.dir.listPath().any{ it.name =~ /(?i:bd|dvd|bluray|bdrip|dvdrip|blu-ray)/ } || f.name =~ /(?i:bd|dvd|bluray|bdrip|dvdrip|blu-ray)/
}
def forceAbsoluteOrder = { f ->
f.dir.listPath().any{ it.name =~ /(?<!\])(?!\[)\d{3}/ }
}
// include artwork/nfo, pushover/pushbullet and ant utilities as required
if (artwork || xbmc || plex || sonarr || potato) { include('lib/htpc') }
if (pushover || pushbullet ) { include('lib/web') }
if (gmail || mail) { include('lib/ant') }
if (music) {
CustomAcoustID = (new GroovyClassLoader()).parseClass(new File("/home/filebot/lib/acoustid.groovy")).newInstance()
def loader = Thread.currentThread().getContextClassLoader()
loader.addURL(new URL("file:///home/filebot/lib/jaudiotagger-2.2.2.jar"))
AudioFileIO = Class.forName( 'org.jaudiotagger.audio.AudioFileIO', true, loader )
FieldKey = Class.forName( 'org.jaudiotagger.tag.FieldKey', true, loader )
ImageIO = Class.forName( 'javax.imageio.ImageIO', true, loader )
}
// error reporting functions
def sendEmailReport = { title, message, messagetype ->
if (gmail) {
sendGmail(
subject: title,
message: message,
messagemimetype: messagetype,
to: any{ mailto } { gmail[0] + '@gmail.com' }, // mail to self by default
user: gmail[0],
password: gmail[1]
)
}
if (mail) {
sendmail(
mailhost: mail[0],
mailport: mail[1],
from: mail[2],
to: mailto,
subject: title,
message: message,
messagemimetype: messagetype
)
}
}
def fail = { message ->
if (reportError) {
sendEmailReport('[FileBot] Failure', message, 'text/plain')
}
die(message)
}
// sanity checks
args.findAll{ !it.exists() }.each{ fail("File not found: $it") }
// check user-defined pre-condition
if (tryQuietly{ !(ut_state ==~ ut_state_allow) }) {
fail("Invalid state: ut_state = $ut_state (expected $ut_state_allow)")
}
// check ut mode vs standalone mode
if ((tryQuietly{ ut_dir } == '/') || (args.size() > 0 && (tryQuietly{ ut_dir }?.size() > 0 || tryQuietly{ ut_file }?.size() > 0)) || (args.size() == 0 && (tryQuietly{ ut_dir } == null && tryQuietly{ ut_file } == null))) {
fail("Invalid arguments: pass in either file arguments or ut_dir/ut_file parameters but not both")
}
// define and load exclude list (e.g. to make sure files are only processed once)
def excludePathSet = [] as HashSet
if (excludeList?.exists()) {
excludeList.eachLine('UTF-8'){ excludePathSet += it }
log.finest "Using excludes: ${excludeList} (${excludePathSet.size()})"
}
// specify how to resolve input folders, e.g. grab files from all folders except disk folders and already processed folders (i.e. folders with movie/tvshow nfo files)
def resolveInput(f) {
// ignore system and hidden folders
//if (f.isHidden()) {
// log.finest "Ignore hidden: $f"
// return []
//}
// ignore already processed folders
if (f.isDirectory() && f.listFiles().toList().any{ it.name ==~ /movie.nfo|tvshow.nfo/ }) {
log.finest "Ignore processed folder: $f"
return []
}
// resolve recursively
if (f.isDirectory() && !f.isDisk())
return f.listFiles().toList().findResults{ resolveInput(it) }
else
return f
}
// collect input fileset as specified by the given --def parameters
def roots = []
if (args.empty) {
// assume we're called with utorrent parameters (account for older and newer versions of uTorrents)
if (ut_kind == 'single' || (ut_kind != 'multi' && ut_dir && ut_file)) {
roots += new File(ut_dir, ut_file) // single-file torrent
} else {
roots += new File(ut_dir)
/*def dir = new File(ut_dir)
if (!dir.isDirectory()){
def filename = ut_dir.replaceFirst(~/\.[^\.]+$/, '')
log.fine "Input file is singe file, search for companion files in the same parent directory"
new File(dir.parent).eachFile(groovy.io.FileType.FILES) {
if (it.canonicalFile.toString().contains(filename)) {
log.fine "Search: $it => add"
roots += it
return
}
log.fine "Search: $it => skip"
}
} else {
roots += dir // multi-file torrent
}*/
}
} else {
// assume we're called normally with arguments
roots += args
}
log.fine "Roots: $roots"
// sanitize input
roots = roots.findAll{ it?.exists() }.collect{ it.canonicalFile }.unique() // roots could be folders as well as files
// flatten nested file structure
input = roots.flatten{ f -> resolveInput(f) }
// ignore archives that are on the exclude path list
input = input.findAll{ f -> !excludePathSet.contains(f.path) }
// extract archives (zip, rar, etc) that contain at least one video file
def extractedArchives = []
def tempFiles = []
input = input.flatten{ f ->
if (!skipExtract && (f.isArchive() || f.hasExtension('001'))) {
def extractDir = new File(f.dir, '/.scratch/' + f.nameWithoutExtension)
extractDir.mkdirs()
def extractFiles = extract(file: f, output: extractDir, conflict: 'auto', filter: { it.isArchive() || it.isVideo() || it.isSubtitle() || (music && it.isAudio()) }, forceExtractAll: true) ?: []
if (extractFiles.size() > 0) {
extractedArchives += f
tempFiles += extractDir
tempFiles += extractFiles
}
scratchCleanup.push(extractDir.parentFile);
return extractFiles
}
return f
}
// ignore files that are on the exclude path list
input = input.findAll{ f -> !excludePathSet.contains(f.path) }
// update exclude list with all input that will be processed during this run
if (excludeList) {
excludeList.withWriterAppend('UTF-8') { out ->
extractedArchives.path.each{ out.println(it) }
input.path.each{ out.println(it) }
}
}
// helper function to work with the structure relative path rather than the whole absolute path
def relativeInputPath = { f ->
def r = roots.find{ r -> f.path.startsWith(r.path) && r.isDirectory() && f.isFile() }
if (r != null) {
return f.path.substring(r.path.length() + 1)
}
return f.name
}
def detectLanguage = { file ->
def text = ""
BufferedReader r = new BufferedReader(new FileReader(file));
String line;
for ( int ln = 0; (line = r.readLine()) != null && ln <= 25; ln++ ) {
text += " " + line.replaceAll(/<[^>]+>/, '').replaceAll(/[^\p{L}\s]/, '').trim()
}
r.close();
text = text.replaceAll(/\s{2,}/, ' ').trim();
log.info("Found subtitle text: " + text)
if (text && langdetect) {
def url = 'http://ws.detectlanguage.com/0.2/detect?q=' + java.net.URLEncoder.encode(text) + '&key=' + langdetect
def request = WebRequest.fetch(new URL(url))
def json = (new groovy.json.JsonSlurper()).parseText(java.nio.charset.Charset.forName("UTF-8").decode(request).toString());
def lang = tryQuietly { json.data.detections[0].language }
def isReliable = tryQuietly { json.data.detections[0].isReliable }
if (lang && isReliable) {
log.info("Language detected: [$lang]")
return lang
} else {
log.info("Language detection failed.")
}
} else {
log.info("Unable to read text in subtitle file.")
}
return null;
}
// keep original input around so we can print excluded files later
def originalInputSet = input as LinkedHashSet
// process only media files
input = input.findAll{ f -> (f.isVideo() && !tryQuietly{ f.hasExtension('iso') && !f.isDisk() }) || f.isSubtitle() || (f.isDirectory() && f.isDisk()) || (music && f.isAudio()) }
// ignore clutter files
input = input.findAll{ f -> !(relativeInputPath(f) =~ /(?<=\b|_)(?i:sample|trailer|extras|music.video|scrapbook|behind.the.scenes|extended.scenes|deleted.scenes|mini.series|s\d{2}c\d{2}|S\d+EXTRA|\d+xEXTRA|NCED|NCOP|(OP|ED)\p{Digit}\p{Alpha}|Formula.1.\d{4})(?=\b|_)/) }
// ignore video files that don't conform with the file-size and video-length limits
input = input.findAll{ f -> !(f.isVideo() && ((minFileSize > 0 && f.length() < minFileSize) || (minLengthMS > 0 && tryQuietly{ getMediaInfo(f, '{duration}').toLong() < minLengthMS }))) }
// ignore subtitles files that are not stored in the same folder as the movie
input = input.collectNested{ f ->
if (f.isSubtitle()) {
if (f.parentFile.listFiles{ it.isVideo() }.any{ f.isDerived(it) } || f.parentFile.name.toLowerCase().contains('sub')) {
if (f.getExtension() == 'idx' || f.getExtension() == 'sub'){
return f;
}
def file = f
def lang = tryQuietly{ new net.filebot.format.MediaBindingBean(null, f, null).detectSubtitleLanguage() }
log.fine("[$f.name] => [$lang]");
if (!lang) {
lang = detectLanguage(f);
if (lang) {
def move = new File (f.parentFile.toString() + "/.scratch/" + f.getNameWithoutExtension() + '.' + lang + '.' + f.getExtension())
move.mkdirs()
Files.copy(f.toPath(), move.toPath(), StandardCopyOption.REPLACE_EXISTING)
scratchCleanup.push(move.parentFile);
file = move;
}
}
if (!subLangFilter || lang in subLangFilter) {
return file;
} else {
return null;
}
} else {
return null;
}
}
return f;
}.grep{ return it }
// print exclude and input sets for logging
input.each{ f -> log.finer("Input: $f") }
(originalInputSet - input).each{ f -> log.finest("Exclude: $f") }
// early abort if there is nothing to do
if (input.size() == 0) die("No files selected for processing")
// group episodes/movies and rename according to XBMC standards
def groups = input.groupBy{ f ->
// skip auto-detection if possible
if (forceIgnore(f))
return []
if (music && forceAudio(f)) // process audio only if music mode is enabled
return [music: f.dir.name]
if (forceAnime(f)){
def anime = (detectAnimeName(f) ?: detectAnimeName(input.findAll{ s -> f.dir == s.dir && s.isVideo() })) ?: f.name.replaceFirst(/\.[^.]+$/, '').replaceFirst(/-(?![^\(\[]*[\)\]]).+$/, '').findAll(/[a-zA-Z0-9]+(?![^\(\[]*[\)\]])/)
if (forceAnimeMovie(f)) {
return [anime: anime, mov: detectMovie(f, false)]
} else { //if (forceAnimeSeries(f)) {
def order = "airdate"
if (forceAbsoluteOrder(f)){
order = "absolute";
} else if (forceDVDOrder(f)){
order = "dvd"
}
return [order: order, anime: anime]
}
}
if (forceMovie(f)){
/*if (forceAnimeMovie(f)){
def mov = detectMovie(f, false)
return [mov: detectMovie(f, false)]
}*/
return [mov: detectMovie(f, false)]
}
if (forceSeries(f)){
def order = "airdate"
if (forceDVDOrder(f)){
order = "dvd"
}
return [order: order, tvs: detectSeriesName(f) ?: detectSeriesName(input.findAll{ s -> f.dir == s.dir && s.isVideo() })]
}
def tvs = detectSeriesName(f)
def mov = detectMovie(f, false)
log.fine("$f.name [series: $tvs, movie: $mov]")
// DECIDE EPISODE VS MOVIE (IF NOT CLEAR)
if (tvs && mov) {
def norm = { s -> s.ascii().normalizePunctuation().lower().space(' ') }
def dn = norm(guessMovieFolder(f)?.name ?: '')
def fn = norm(f.nameWithoutExtension)
def sn = norm(tvs)
def mn = norm(mov.name)
def my = mov.year as String
/*
println '--- EPISODE FILTER (POS) ---'
println parseEpisodeNumber(fn, true) || parseDate(fn)
println ([dn, fn].find{ it =~ sn && matchMovie(it) == null } && (parseEpisodeNumber(stripReleaseInfo(fn.after(sn), false), false) || stripReleaseInfo(fn.after(sn), false) =~ /\D\d{1,2}\D{1,3}\d{1,2}\D/) && matchMovie(fn) == null)
println (fn.after(sn) ==~ /.{0,3} - .+/ && matchMovie(fn) == null)
println f.dir.listFiles{ it.isVideo() && (dn =~ sn || norm(it.name) =~ sn) && it.name =~ /\d{1,3}/}.findResults{ it.name.matchAll(/\d{1,3}/) as Set }.unique().size() >= 10
println '--- EPISODE FILTER (NEG) ---'
println (mn == fn)
println (mov.year >= 1950 && f.listPath().reverse().take(3).find{ it.name.contains(my) && parseEpisodeNumber(it.name.after(my), false) == null })
println (mn =~ sn && [dn, fn].find{ it =~ /\b(19|20)\d{2}\b/ && parseEpisodeNumber(it.after(/\b(19|20)\d{2}\b/), false) == null })
println '--- MOVIE FILTER (POS) ---'
println (fn.contains(mn) && parseEpisodeNumber(fn.after(mn), false) == null)
println (mn.getSimilarity(fn) >= 0.8 || [dn, fn].find{ it.findAll( ~/\d{4}/ ).findAll{ y -> [mov.year-1, mov.year, mov.year+1].contains(y.toInteger()) }.size() > 0 } != null)
println ([dn, fn].find{ it =~ mn && !(it.after(mn) =~ /\b\d{1,3}\b/) && (it.getSimilarity(mn) > 0.2 + it.getSimilarity(sn)) } != null)
println (detectMovie(f, true) && [dn, fn].find{ it =~ /(19|20)\d{2}/ } != null)
*/
// S00E00 | 2012.07.21 | One Piece 217 | Firefly - Serenity | [Taken 1, Taken 2, Taken 3, Taken 4, ..., Taken 10]
if ((parseEpisodeNumber(fn, true) || parseDate(fn) || ([dn, fn].find{ it =~ sn && matchMovie(it) == null } && (parseEpisodeNumber(stripReleaseInfo(fn.after(sn), false), false) || stripReleaseInfo(fn.after(sn), false) =~ /\D\d{1,2}\D{1,3}\d{1,2}\D/) && matchMovie(fn) == null) || (fn.after(sn) ==~ /.{0,3} - .+/ && matchMovie(fn) == null) || f.dir.listFiles{ it.isVideo() && (dn =~ sn || norm(it.name) =~ sn) && it.name =~ /\d{1,3}/}.findResults{ it.name.matchAll(/\d{1,3}/) as Set }.unique().size() >= 10 || mov.year < 1900) && !( (mn == fn) || (mov.year >= 1950 && f.listPath().reverse().take(3).find{ it.name.contains(my) && parseEpisodeNumber(it.name.after(my), false) == null }) || (mn =~ sn && [dn, fn].find{ it =~ /\b(19|20)\d{2}\b/ && parseEpisodeNumber(it.after(/\b(19|20)\d{2}\b/), false) == null }) ) ) {
log.fine("Exclude Movie: $mov")
mov = null
} else if ((fn.contains(mn) && parseEpisodeNumber(fn.after(mn), false) == null) || (mn.getSimilarity(fn) >= 0.8 || [dn, fn].find{ it.findAll( ~/\d{4}/ ).findAll{ y -> [mov.year-1, mov.year, mov.year+1].contains(y.toInteger()) }.size() > 0 } != null) || ([dn, fn].find{ it =~ mn && !(it.after(mn) =~ /\b\d{1,3}\b/) && (it.getSimilarity(mn) > 0.2 + it.getSimilarity(sn)) } != null) || (detectMovie(f, false) && [dn, fn].find{ it =~ /(19|20)\d{2}|(?i:CD)[1-9]/ } != null)) {
log.fine("Exclude Series: $tvs")
tvs = null
}
}
// CHECK CONFLICT
if (((mov && tvs) || (!mov && !tvs))) {
if (failOnError) {
fail("Media detection failed")
} else {
log.fine("Unable to differentiate: [$f.name] => [$tvs] VS [$mov]")
return [tvs: null, mov: null, anime: null]
}
}
return [tvs: tvs, mov: mov, anime: null]
}
def postProcess = { files ->
if (output){
files.each{ file ->
if (file.isVideo()) {
def prefix = file.name.indexOf('[')
if (prefix > -1) {
prefix = file.name.substring(0,prefix)
} else {
prefix = ""
}
//log.info("Prefix: " + prefix)
def list = []
if (!file.parentFile.exists()) {
return;
}
file.parentFile.eachFile(FileType.FILES) { f ->
log.info(f.name)
if (f.name.startsWith(prefix) && f.isVideo())
list << f
}
if (list.size() > 1){
log.info("Found duplicates: " + list)
list = list.collect{ f ->
def media = new net.filebot.format.MediaBindingBean(null, f)
def vf = media.getVideoFormat().replaceAll("[\\D]", "").toInteger()
def af = media.getAudioChannels().split().collect{ it.replaceAll("[\\D]", "").toInteger() }.sort().last()
def sort = "$vf.$af".toDouble()
log.info("Sort duplicates by quality: [$f.name] => [$sort]")
return [file:f, sort:sort]
}.sort{ it.sort }
def best = list.pop()
log.info("Best quality: " + best)
if (best.sort == list.last().sort){
if (pushbullet) {
list.push(best)
PushBullet(pushbullet).sendNote('Filebot requests fixing duplicates manually', "[$file.name] => ${list*.file}", tryQuietly{ mailto })
}
} else {
list.each {
def name = it.file.getNameWithoutExtension();
it.file.parentFile.eachFile(FileType.FILES) { f ->
if (f.canonicalFile.toString().contains(output) && f.canonicalFile.toString().contains(name)){
log.info("Remove worse quality: " + f)
def fs = new File(f.canonicalFile.toString().replace(output, output + '/.recycle'))
log.info(f.canonicalFile.toString() + ", writable: " + f.canWrite())
fs.parentFile.mkdirs()
log.info(fs.canonicalFile.toString() + ", writable: " + fs.parentFile.canWrite())
f.renameTo(fs)
}
}
}
}
}
}
}
}
}
// group entries by unique tvs/mov descriptor
groups = groups.groupBy{ group, files -> group.collectEntries{ type, query -> [type, query ? query.toString().ascii().normalizePunctuation().lower() : null] } }.collectEntries{ group, maps -> [group, maps.values().flatten()] }
// log movie/series/anime detection results
groups.each{ group, files -> log.finest("Group: $group => ${files*.name}") }
// process each batch
groups.each{ group, files ->
// fetch subtitles (but not for anime)
if (group.anime == null && subtitles != null) {
files.each{ file ->
if (file.isVideo() && file.size() > 0){
subtitles.each{ languageCode ->
def langName = net.filebot.Language.getLanguage(languageCode).getName()
def subs = getMediaInfo(file, '{media.Text_Language_List}')
log.fine("Lookup: Checking for [$langName] embedded sub in [$file.name] => [$subs]")
if (!subs.tokenize().contains(langName)) {
log.fine("Lookup: No embedded sub found, searching for subtitles.")
def subtitleFiles = getMissingSubtitles(file:file, lang:languageCode, strict:true, output:'srt', encoding:'UTF-8', db: 'OpenSubtitles', format:'MATCH_VIDEO_ADD_LANGUAGE_TAG') ?: []
files += subtitleFiles
input += subtitleFiles // make sure subtitles are added to the exclude list and other post processing operations
tempFiles += subtitleFiles // if downloaded for temporarily extraced files delete later
} else {
log.fine("Ignore: Embedded sub found, cancel subtitle search.")
}
}
}
}
}
// EPISODE MODE
if ((group.tvs || group.anime) && !group.mov) {
// choose series / anime config
def config
def dest
log.info "Using TV Order: " + group.order
if (group.tvs){
config = [name:group.tvs, format:format.tvs, db:'TheTVDB']
dest = rename(file: files, format: config.format, db: config.db, order: group.order)
} else {
//files.mapByFolder().each{ dir, fs ->
def season = ''
def tvdbname = ''
def animeTitle = ''
def aformat = format.anime
def seriesName = group.anime//detectAnimeName(files)
def options = AniDB.search(seriesName, _args.locale)
def date = new net.filebot.web.SimpleDate(files.get(0).lastModified());
log.info "Using Series Name: ${seriesName}"
log.info "First File Date: ${date}"
if (!options.isEmpty()) {
log.info "Found Anime Series in AniDb => ${options*.name}"
//log.info "Properties Returned => [${anime.properties}]"
options.each{ series ->
series.metaClass.score = new Double(0);
series.effectiveNames.each{ name ->
series.score = series.score + name.getSimilarity(seriesName);
}
}
def sorted = options.sort{ -it.score }
//log.info "Animes Sorted by Similarity: ${sorted*.primaryTitle}"
// filter by date
def anime = sorted.find{ AniDB.getSeriesData(it, net.filebot.web.SortOrder.forName(group.order), _args.locale).seriesInfo.startDate < date }
def animeid = anime.getId()
animeTitle = anime.getName()
log.info "Using Anime Series in AniDb: [$animeid] => [$animeTitle]"
def dom
def search
def tvdbid
try {
dom = Cache.getCache('anime_xml_store', CacheType.Persistent).xml('anime-list.xml') {
new URL('https://raw.githubusercontent.com/ScudLee/anime-lists/master/'+it)
}.expire(Cache.ONE_WEEK).get()
search = net.filebot.util.XPathUtilities.selectNode("anime-list/anime[@anidbid='$animeid']", dom)
tvdbid = net.filebot.util.XPathUtilities.selectString("@tvdbid", search).toInteger()
season = net.filebot.util.XPathUtilities.selectString("@defaulttvdbseason", search)
if (!season.isNumber()){
season = ''
}
} catch(e) {
log.warning "Failed: Mapping AniDb to TVDB Name & Season: [$animeid] => [?]"
}
if (tvdbid){
tvdbname = TheTVDB.lookupByID(tvdbid, _args.locale).getName()
if (!animeTitle.isEmpty()){
aformat = aformat.replaceAll(/(\{[^\}]*)(primaryTitle)([^\}]*\})/, "\$1'$animeTitle'\$3")
}
log.info "Succes: Mapping AniDb to TVDB: [$animeTitle] => [$tvdbname, Season: $season]"
} else {
log.warning "Failed: Mapping AniDb to TVDB Name & Season: [$animeid] => [$tvdbid, Season: $season] => [?]"
}
} else {
log.warning "Failed: Anime Series not found in AniDb: [$seriesName]"
}
config = [name:group.anime, format:aformat, db:'TheTVDB']
// fix absolute
if (group.order == "absolute") {
def pattern = Pattern.compile("(?<!\\])(?!\\[)(\\d{3})", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE)
def renamed = []
files.each{ f ->
def file = f.parent + '/.scratch/' + pattern.matcher(f.nameWithoutExtension).replaceAll("E\$1") + '.' + f.extension as File
file.getParentFile().mkdirs()
Files.createLink(Paths.get(file.path), Paths.get(f.path))
renamed.push(file)
}
files = renamed
//files = rename(file:files.sort(), action:'hardlink', format:files.get(0).parent + '/.scratch/{fn.replaceAll(/(?<!\\])(?!\\[)(\\d{3})/, "E\\$1")}', query:animeTitle, db:'AniDB', order:'absolute')
if (files != null && !files.empty) {
scratchCleanup.addAll(files);
}
group.order = "airdate"
}
if (tvdbname.isEmpty()) {
dest = rename(file: files, format: config.format, db: config.db, order: group.order)
} else if (season.isEmpty()){
dest = rename(file: files, format: config.format, db: config.db, query: tvdbname, order: group.order)
} else {
dest = rename(file: files, format: config.format, db: config.db, query: tvdbname, filter:"s == $season", order: group.order)
}
//}
//[name:group.anime, format:format.anime, db:'AniDB']
}
/*def config = group.tvs ? [name:group.tvs, format:format.tvs, db:'TheTVDB']
: [name:group.anime, format:format.anime, db:'AniDB']
def dest = rename(file: files, format: config.format, db: config.db)*/
if (dest && artwork) {
dest.mapByFolder().each{ dir, fs ->
def hasSeasonFolder = (config.format =~ /(?i)Season/)
def sxe = fs.findResult{ eps -> parseEpisodeNumber(eps) }
def seriesName = detectSeriesName(fs)
def options = TheTVDB.search(seriesName, _args.locale)
if (options.isEmpty()) {
log.warning "TV Series not found: $config.name"
return
}
def series = options.sortBySimilarity(seriesName, { s -> s.name }).get(0)
log.fine "Fetching series artwork for [$series] to [$dir]"
fetchSeriesArtworkAndNfo(hasSeasonFolder ? dir.dir : dir, dir, series, sxe && sxe.season > 0 ? sxe.season : 1)
}
}
if (dest) postProcess(dest)
if (dest == null && failOnError) {
fail("Failed to rename series: $config.name")
}
}
// MOVIE MODE
else if (group.mov && !group.tvs) {
def dest
if (group.anime){
def tmdbname = ''
def aformat = format.mov
def movieName = group.anime//detectMovie(files, false)
def options = AniDB.search(movieName, _args.locale)
if (!options.isEmpty()) {
def anime = options.sortBySimilarity(movieName, { s -> s.name }).get(0)
def animeid = anime.getId()
def animeTitle = anime.getName()
log.info "Found: Anime in AniDb: [$animeid] => [$animeTitle]"
def dom
def search
def tmdbid
def imdbid
try {
dom = Cache.getCache('anime_xml_store', CacheType.Persistent).xml('anime-list.xml') {
new URL('https://raw.githubusercontent.com/ScudLee/anime-lists/master/'+it)
}.expire(Cache.ONE_WEEK).get()
search = net.filebot.util.XPathUtilities.selectNode("anime-list/anime[@anidbid='$animeid']", dom)
imdbid = tryQuietly { net.filebot.util.XPathUtilities.selectString("@imdbid", search).replaceFirst('tt', '').toInteger() }
tmdbid = tryQuietly { net.filebot.util.XPathUtilities.selectString("@tmdbid", search).toInteger() }
} catch(e) {
log.warning "Failed: Mapping AniDb to IMDB"
}
if (imdbid || tmdbid){
if (!animeTitle.isEmpty()){
aformat = aformat.replaceAll(/(\{[^\}]*)(primaryTitle)([^\}]*\})/, "\$1'$animeTitle'\$3")
}
def movie
if (tmdbid){
movie = new net.filebot.web.Movie(null, 0, -1, tmdbid)
} else {
movie = new net.filebot.web.Movie(null, 0, imdbid, -1)
}
movie = TheMovieDB.getMovieDescriptor(movie, _args.locale)
tmdbname = movie.getName() + ' ' + movie.getYear()
log.info "Succes: Mapping AniDb to TMDb: [$animeTitle] => ["+ (tmdbid ? "TMDB: $tmdbid" : "IMDB: $imdbid") + "] => [$tmdbname]"
} else {
log.warning "Failed: Mapping AniDb to TMDb: [$animeid] => [?]"
}
}
if (tmdbname.isEmpty()) {
dest = rename(file: files, format: aformat, db: 'TheMovieDB')
} else {
dest = rename(file: files, format: aformat, db: 'TheMovieDB', query: tmdbname)
}
} else {
dest = rename(file:files, format:format.mov, db:'TheMovieDB')
}
if (dest && artwork) {
dest.mapByFolder().each{ dir, fs ->
def movieFile = fs.findAll{ it.isVideo() || it.isDisk() }.sort{ it.length() }.reverse().findResult{ it }
if (movieFile != null) {
def movie = detectMovie(movieFile, false)
log.fine "Fetching movie artwork for [$movie] to [$dir]"
fetchMovieArtworkAndNfo(dir, movie, movieFile, extras)
}
}
}
if (dest) postProcess(dest)
if (dest == null && failOnError) {
fail("Failed to rename movie: $group.mov")
}
}
// MUSIC MODE
else if (group.music) {
def filesCopy = files.collect{ file ->
def path = Paths.get(file.parent + '/.scratch/' + file.name)
scratchCleanup.push(path.toFile().parentFile)
path.toFile().getParentFile().mkdirs()
if (Files.exists(path.toFile().getParentFile().toPath())){
Files.copy(file.toPath(), path, StandardCopyOption.REPLACE_EXISTING)
return path.toFile()
}
}
def folder
def lookup = CustomAcoustID.lookup(filesCopy, [tracks: filesCopy.size(), group: group.music])
def mimeToExt = { mime ->
return mime.replaceFirst('image/', '').replaceFirst('jpeg', 'jpg')
}
def setID3 = { file, track ->
//log.info ('Custom: Album Artist: ' + track.getAlbumArtist() + ', Album: ' + track.getAlbum() + ", CD: " + track.getMedium() + "/" + track.getMediumCount() + ", Tracks: " + track.getTrack().toString().pad(2) + "/" + track.getTrackCount().toString().pad(2) + ', Artist: ' + track.getArtist() + ", Title: " + track.getTitle())
def f = AudioFileIO.read(file);
if (!folder || folder.type != 3){
def art = f.getTag()
if (art){
art = art.getFirstArtwork()
if (art){
folder = [image: art.getImage(), ext: mimeToExt(art.getMimeType()), type:0 ]
f.getTag().getArtworkList().each{
if (it.getPictureType() == 3)
folder = [image: it.getImage(), ext: mimeToExt(it.getMimeType()), type:3 ]
}
}
}
}
AudioFileIO.delete(f)
def tag = f.createDefaultTag();
if (track.getArtist()){
tag.setField(FieldKey.ARTIST, track.getArtist());
if (track.getAlbumArtist()) {
tag.setField(FieldKey.ALBUM_ARTIST, track.getAlbumArtist());
} else {
tag.setField(FieldKey.ALBUM_ARTIST, track.getArtist());
}
} else if (track.getAlbumArtist()) {
tag.setField(FieldKey.ARTIST, track.getAlbumArtist());
tag.setField(FieldKey.ALBUM_ARTIST, track.getAlbumArtist());
}
if (track.getTitle()){
tag.setField(FieldKey.TITLE, track.getTitle());
} else if (track.getTrackTitle()) {
tag.setField(FieldKey.TITLE, track.getTrackTitle());
}
if (track.getAlbum())
tag.setField(FieldKey.ALBUM, track.getAlbum());
if (track.getAlbumReleaseDate()){
tag.setField(FieldKey.YEAR, track.getAlbumReleaseDate().toString());
}
if (track.getMedium())
tag.setField(FieldKey.DISC_NO, track.getMedium().toString());
if (track.getMediumCount())
tag.setField(FieldKey.DISC_TOTAL, track.getMediumCount().toString());
if (track.getTrack())
tag.setField(FieldKey.TRACK, track.getTrack().toString());
if (track.getTrackCount())
tag.setField(FieldKey.TRACK_TOTAL, track.getTrackCount().toString());
//if (track.getMBID())
// tag.setField(FieldKey.MUSICBRAINZ_TRACK_ID, track.getMBID());
f.setTag(tag)
f.commit();
}
def process = []
lookup.each{ file, track ->
log.info ("[$file]")
if (track){
setID3(file, track)
process.add(file)
}
}
def dest = rename(action: ('TEST'.equalsIgnoreCase(_args.action) ? 'test' : 'move'), file:process, format:format.music, db:'ID3 Tags')
files.mapByFolder().each{ dir, fs ->
def detectType = { file ->
def count = 0
if ( file.name.toLowerCase().contains('cover') ){
count++
}
if ( file.name.toLowerCase().contains('front' )){
count++
}
if ( file.parent.toLowerCase().replaceAll(/\W/, '').contains(dir.name.toLowerCase().replaceAll(/\W/, '')) ){
count++
}
return count
}
def list = [dir]
if (dir.toString().toLowerCase().contains('cd')){
list.add(dir.getParentFile())
}
log.info("Search Paths: " + list.toString())
list.each{
it.eachFileMatch(FileType.FILES, ~/.*\.jpg|png|jpeg$/) { file ->
log.info('Found image in folder path: ' + file.getName())
def type = detectType(file)
if (!folder || folder.type < type){
folder = [image: ImageIO.read(file), ext: file.getExtension(), type:type ]
}
}
}
}
if (dest && folder) {
def imagesAreEqual = {image1, image2 ->
if (image1.width != image2.width || image1.height != image2.height) {
return false
}
for (int x = 1; x < image2.width; x++) {
for (int y = 1; y < image2.height; y++) {
if (image1.getRGB(x, y) != image2.getRGB(x, y)) {
return false
}
}
}
return true
}
dest.mapByFolder().each{ dir, fs ->
def artFile
def count = 0
while (true) {
artFile = new File(dir.toString() + '/folder' + (count < 1 ? '' : count.toString()) + '.' + folder.ext)
if (artFile.exists()) {
log.info('Art File: Found existing ' + artFile.toString())
if (imagesAreEqual(ImageIO.read(artFile),folder.image)){
log.info('Skipping Art File: Already exists')
return;
}
count++
} else {
break;
}
}
log.info('Art File: ' + artFile.toString() + ", Type: $folder.type")
if (!'TEST'.equalsIgnoreCase(_args.action) && artFile){
ImageIO.write(folder.image, folder.ext, artFile);
}
}
} else if (dest == null && failOnError) {
fail("Failed to rename music: $group.music")
}
}
}
// ---------- POST PROCESSING ---------- //
// deal with remaining files that cannot be sorted automatically
if (unsorted) {
def unsortedFiles = (input - getRenameLog().keySet())
if (unsortedFiles.size() > 0) {
log.info "Processing ${unsortedFiles.size()} unsorted files"