forked from damienlangg/SimpleMovieCatalog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmoviecat.pl
executable file
·2528 lines (2229 loc) · 73.1 KB
/
moviecat.pl
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/perl
=copyright
Simple Movie Catalog 2.6.0
Copyright (C) 2008-2016 damien.langg@gmail.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
=cut
use strict;
my $progver = "2.6.0";
my $author = 'damien.langg@gmail.com';
my $copyright = "Copyright 2008-2016, $author";
my $progbin = "moviecat.pl";
my $progname = "Simple Movie Catalog";
my $progurl = "http://smoviecat.sf.net/";
use Cwd;
use FindBin;
use File::Find;
use File::Path;
use File::Basename;
use File::Copy;
use File::stat qw(); # no-override
use LWP::Simple;
use IO::Handle;
use Data::Dumper;
require LWP::Protocol::https;
#use Term::ReadKey qw(GetTerminalSize);
my $have_term = eval 'use Term::ReadKey; 1';
#use Time::HiRes qw(time);
my $hires_time = sub { time(); };
if (eval 'use Time::HiRes; 1') {
$hires_time = \&Time::HiRes::time;
}
my $g_stime = $hires_time->();
# System install mode: if enabled, cache and log are placed inside the
# report directory instead of program dir, because the user will not have
# permission to write to it. And program dir is absolute instead of deduced
# from binary pathname
my $system_install = 0;
my $prog_dir;
if ($system_install) {
$prog_dir = "/usr/share/smoviecat";
} else {
$prog_dir = $FindBin::Bin;
}
push @INC, "$prog_dir/lib";
require "IMDB_Movie.pm";
my $enable_interactive = 0;
### Globals
# cache and log are placed in proper directories in init()
my $imdb_cache_base = "imdb_cache";
my $imdb_cache = $imdb_cache_base;
my $scan_log = "scan.log";
my $image_dir = "images";
my $image_cache;
my $max_cache_days = 90; # keep cache for up to 3 months
my $base_path = "report/movies";
my $base_name;
my $base_dir;
my $jsname = "moviecat.js";
my @parse_ext = qw( nfo txt url desktop );
my @video_ext = qw( mpg mpeg mpe mp4 avi mov qt wmv mkv iso bin cue ratdvd tivo ts divx );
my @media_ext = (@video_ext, qw( vob nfo rar srt sub ));
my @hidef = qw( hidef hd hdtv hddvdrip hddvd bluray bd5 bd9
720 720p 720i 1080 1080p 1080i );
my @tags_3d = qw(3D HSBS Half-SBS H-SBS Half.Over.Under Half-OU Half.OU);
my @codec = (@hidef, @tags_3d, qw(
cam ts r5 dvdscr dvdrip dvd dvd9 cd1 cd2
vcd xvid divx x264 matroska wmv
dts dolby ac3 vorbis mp3 sub
));
# series: s01e02 / season 1 / episode 2 / 1x2
my @series_tag = ( 's\d{1,2}e\d{1,2}', 'season\W+\d+', 'episode\W+\d+', '\d+x\d+' );
my @subsearch = (
"http://opensubtitles.org/en/search2/sublanguageid-eng/moviename-%TITLE%",
"https://subscene.com/subtitles/title?q=%TITLE%",
"https://www.podnapisi.net/subtitles/search/?keywords=%TITLE%",
);
my @opt_links = (
"Trailers=http://www.imdb.com/title/tt%ID%/trailers",
"http://www.youtube.com/results?search_query=%TITLE%",
"http://www.rottentomatoes.com/search/?search=%TITLE%",
"movies.io=http://movies.io/m/search?utf8=%E2%9C%93&q=%TITLE%",
"http://www.flixster.com/search/?search=%TITLE%",
"http://letterboxd.com/search/%TITLE%",
# "http://www.google.com/search?q=%TITLE%",
# "http://en.wikipedia.org/wiki/Special:Search?search=%TITLE%",
);
my @opt_user; # list of users vote history urls
my @user_vote;
my $opt_i = 0; # interactive
my $opt_auto = 1; # Auto guess and report exact matches
my $opt_miss = 1; # Report folders with missing info
my $opt_miss_match = 0; # Report guessed exact matches as missing
my $opt_match_first = 0;# Match first if multiple matches exists
my $opt_match_year = 0; # Match also folders with missing year
my $opt_match_fname = 1;# Match file names
my $opt_auto_save = 0; # Save auto guessed exact matches
my $opt_group_table = 1;# use table for groups
my $opt_xml = 0; # xml export
my $opt_aka = 0; # search AKA titles
my $opt_theme = 'white'; # default theme
my $opt_otitle = 0; # original title
my $verbose = 1;
my $columns = 80;
my %movie; # movie{id}
my @group; # group list - array of ptr to mlist
my $ngroup;
my $pgroup; # ptr to current group
my $pmlist; # current group movie list - ptr to hash
my %all_dirs; # visited dirs
my $ndirs;
# global skip: sample subs subtitles
my @skiplist = qw( sample subs subtitles cover covers );
my @rxskiplist = qw( /subs-.*/ /\W*sample\W*/ );
my @ignorelist; # ignore dir with missing info, not recursive
my %gbl_tags;
# @{$gbl_tags{"TAG"}{pattern}}
# ${$gbl_tags{"TAG"}{order}} : sorted<0, user>0, 3d=90, hidef=91, imdb=100, guess=110
@{$gbl_tags{"3D"}{pattern}} = @tags_3d;
$gbl_tags{"3D"}{order} = 90;
@{$gbl_tags{"HiDef"}{pattern}} = @hidef;
$gbl_tags{"HiDef"}{order} = 91;
my $F_HTML;
my $F_LOG;
my $last_cache_valid;
### Setup
$| = 1; # autoflush stdout
# override download function
$IMDB::Movie::download_func = \&cache_imdb_id;
### Utility Funcs
sub print_html {
print $F_HTML @_, "\n";
}
sub print_html_n {
print $F_HTML @_;
}
sub print_level {
return if (shift > $verbose);
print @_;
}
my $defer_log;
sub print_log {
my $line = join '', @_;
chomp $line;
# print_level 2, $line, "\n";
my $stamp = sprintf "[ %.6f ] ", ($hires_time->() - $g_stime);
my $msg = $stamp . $line . "\n";
if (not $F_LOG) {
$defer_log .= $msg;
} else {
print $F_LOG $msg;
}
}
sub print_error {
print_log "ERROR: ", @_;
print "ERROR: ", @_, "\n";
}
sub print_info {
print_log "INFO: ", @_;
print @_;
}
sub print_note {
print_log "NOTE: ", @_;
print_level 1, @_;
}
sub print_detail {
print_log "DETAIL: ", @_;
print_level 2, @_;
}
sub print_debug {
print_log "DEBUG: ", @_;
my $msg = "@_";
chomp $msg;
print_level 3, "$msg\n";
}
sub _print_debug {
print @_, "\n";
}
sub abort {
print_error @_;
die;
}
sub unique {
my %seen;
grep(!$seen{$_}++, @_);
}
sub unique_icase {
my %seen;
grep(!$seen{lc($_)}++, @_);
}
sub match_ext
{
my ($name, @ext) = @_;
grep { $name =~ /\.$_$/i } @ext;
}
sub match_ext_list
{
my @match;
for my $name (@_) {
if (match_ext($name, @media_ext)) {
push @match, $name;
}
}
return @match;
}
sub cut_ext {
my $f = shift;
$f =~ s/\.\w+$//;
return $f;
}
sub cut_ext_l {
my @l;
for my $f (@_) { push @l, cut_ext($f); }
return @l;
}
# normalize path
# internal path representation uses /
sub normal_path {
my $path = shift;
$path =~ tr[\\][/];
return $path;
}
# expand ~ and ${VAR}
sub expand_path {
my $path = shift;
$path =~ s/^~\//$ENV{HOME}\//;
while ($path =~ s/\$\{([a-zA-Z_]+)\}/$ENV{$1}/) {};
return $path;
}
# sort by alphanum, ignore case
sub by_alpha {
lc($a) cmp lc($b);
}
# config error
sub exit_cfg {
exit 10;
}
###############################
### Scan
sub getfile {
my $filename = shift;
my $F;
open $F, "<:utf8", $filename or return undef;
my $contents;
{
local $/ = undef; # Read entire file at once
$contents = <$F>; # Return file as one single `line'
} # $/ regains its old value
close $F;
return \$contents; # return reference
}
sub valid_cache
{
my $fname = shift;
$last_cache_valid = 0;
return 0 unless -e $fname;
my $age = -M _; # age in days
my $valid = $age <= $max_cache_days;
print_debug "Cache age: ",
sprintf("%.0f ", $age), #sprintf("%.1f ", $age),
($valid?"(ok)":"(too old)"), " '$fname'";
$last_cache_valid = $valid;
return $valid;
}
sub cache_imdb_id
{
my $id = shift;
my $html_file = $imdb_cache . "/imdb-$id.html";
my $html;
if (valid_cache($html_file) and $html = getfile($html_file)) {
print_debug "Using Cached: $html_file\n";
print_note " ";
} else {
print_debug "Connecting to IMDB... ($id)\n";
print_note ".";
unlink $html_file if -e $html_file;
$html = IMDB::Movie::download_page_id($id);
if (!$html) {
print_debug "Error getting page: $id\n";
return undef;
}
my $F_CACHE;
if (open $F_CACHE, ">:utf8", $html_file) {
print_debug "Write Cache: $html_file\n";
print $F_CACHE $$html;
close $F_CACHE;
} else {
print_log "Error Writing Cache: $html_file: $!\n";
}
}
return $html;
}
sub cache_imdb_find
{
my ($title, $year) = @_;
my $fname = lc("$title ($year)");
$fname =~ tr[:/\\][-];
my $html_file = $imdb_cache . "/imdb_find".($opt_aka?"_aka":"")."-$fname.html";
my $html;
if (valid_cache($html_file) and $html = getfile($html_file)) {
print_debug "Using Cached: $html_file\n";
print_note " ";
} else {
print_debug "Connecting to IMDB...\n";
print_note ".";
unlink $html_file if -e $html_file;
$html = IMDB::Movie::get_page_find($title, $year);
if (!$html) {
print_debug "Error getting page: $title ($year)\n";
return undef;
}
my $F_CACHE;
if (open $F_CACHE, ">:utf8", $html_file) {
print_debug "Write Cache: $html_file\n";
print $F_CACHE $$html;
close $F_CACHE;
} else {
print_log "Error Writing Cache: $html_file: $!\n";
}
}
return $html;
}
sub img_name
{
my $id = shift;
return "imdb-" . $id . ".jpg";
}
sub cache_image
{
my $m = shift;
if (!$m or !$m->id or (!$m->img and (!$m->photos or !$m->photos->[0]))) {
print_note "-";
return 1;
}
if (!$m->img and $m->photos and $m->photos->[0]) {
# use first gallery photo if no poster
print_debug "No poster found - using first photo '", $m->photos->[0], "'";
$m->{img} = $m->photos->[0];
}
my $img_file = $image_cache . "/" . img_name($m->id);
# only refresh image cache if html cache changed
if ($last_cache_valid and -e $img_file) {
print_note " ";
return 1;
}
print_note ".";
print_debug "Getting image: ", $m->img, "";
my $image = get($m->img);
if (!$image) {
print_error "Getting image: ", $m->img, "";
return 0;
}
my $F_IMG;
if (open $F_IMG, ">:raw", $img_file) {
print_debug "Write Image Cache: $img_file\n";
print $F_IMG $image;
close $F_IMG;
} else {
print_error "Saving image: ", $img_file, "$!";
return 0;
}
return 1;
}
sub cache_movie
{
my $m = shift;
if ($opt_otitle == 1) {
if ($m->{otitle} and !defined($m->{rtitle})) {
$m->{rtitle} = $m->{title}; # save regional title
$m->{title} = $m->{otitle}; # use original title
}
} elsif ($opt_otitle == 2) {
if ($m->{og_title} and !defined($m->{rtitle})) {
$m->{rtitle} = $m->{title}; # save regional title
$m->{title} = $m->{og_title}; # use opengraph title
}
}
$movie{$m->id} = $m;
cache_image($m);
}
sub getmovie
{
my $id = shift;
my $m = $movie{$id};
if ($m) { return $m;}
my $html = cache_imdb_id($id);
if (!$html) {
print_log "*** Error: get imdb $id\n";
print_note " FAIL1";
return undef;
}
$m = IMDB::Movie->new_html($id, $html);
print_debug("MOVIE: ", Dumper($m));
if (!$m) {
print_log "*** Error: parse imdb $id\n";
print_note " FAIL2";
return undef;
}
cache_movie($m);
return $m;
}
sub match_title
{
my ($t1, $t2) = @_;
# print_debug "\nT1: $t1 T2: $t2\n";
$t1 = lc($t1);
# remove non-alphanums/keep space
# $t1 =~ s/[^\w ]//g;
# remove non-alphanums
$t1 =~ s/\W//g;
$t2 = lc($t2);
$t2 =~ s/\W//g;
#print_debug "\nT1: $t1 T2: $t2\n";
return $t1 eq $t2;
}
sub match_m_title
{
my ($title, $m) = @_;
if ($m->{otitle} and match_title($title, $m->{otitle})) { return 1; }
if ($m->{rtitle} and match_title($title, $m->{rtitle})) { return 1; }
return match_title($title, $m->{title});
}
sub findmovie
{
my ($title, $year, $type) = @_;
my $html = cache_imdb_find($title, $year);
if (!$html) {
print_log "*** Error: find imdb '$title' ($year)\n";
print_note " FAIL\n";
return undef;
}
my @matches = IMDB::Movie::get_matches($html);
my $m;
if (@matches) {
# if type specified, find first matching type
if ($type) {
my $i;
for $i (0 .. $#matches) {
print_log "match[$i] = ", $matches[$i]->{id},
" ", $matches[$i]->{title},
" (", $matches[$i]->{year},
") [", $matches[$i]->{type}, "]\n";
# if year known it has to match too
if ($year and ($year != $matches[$i]->{year})) { next; }
if ($matches[$i]->{type} =~ /$type/) {
print_log "match type: $title ($year) [$type]\n";
# move $i to first place
@matches = ($matches[$i], splice(@matches, $i, 1));
last;
}
}
}
# search result - cache first hit
if ($matches[0]->{id}) {
$m = getmovie($matches[0]->{id});
if ($m) {
# add match list
$m->{matches} = \@matches;
# not a direct hit! unless title matches (almost) exactly
if (match_m_title($title, $m)) {
print_debug("Search '$title' ($year) Exact Match: ".$m->id." ".$m->title);
$m->{direct_hit} = 1;
} else {
# if type matches then accept
if ($type and $m->type =~ /$type/i) {
$m->{direct_hit} = 1;
} else {
$m->{direct_hit} = 0;
}
}
return $m;
} else {
print_log "ERR: ", $matches[0]->{id}, "\n";
}
}
}
# direct hit or no match
$m = IMDB::Movie->new_html(0, $html);
print_debug("MOVIE: ", Dumper($m));
if (!$m) {
print_log "*** Error: parse imdb '$title' ($year)\n";
return undef;
}
print_debug("Search '$title' ($year) Direct Hit: "
.$m->{direct_hit}." id:".$m->id." t:".$m->title);
cache_movie($m);
return $m;
}
sub save_movie
{
my ($dir, $movie) = @_;
my $fname;
my $F_INFO;
$fname = $movie->{title}." (".$movie->year.")";
$fname =~ s/[\/\\:]/-/g;
$fname =~ tr/<>/()/;
$fname = "$dir/$fname - imdb.nfo";
print_info "Saving: $fname\n";
if (!open $F_INFO, ">", $fname) {
print_error "Opening '$fname' $!";
return;
}
print $F_INFO "# Generated by $progname $progver #\n\n";
print $F_INFO $movie->title, " (", $movie->year, ") ", $movie->type, "\n";
print $F_INFO IMDB::Movie::get_url_id($movie->id), "\n\n";
close $F_INFO;
}
sub shorten
{
my $name = shift;
my $max = $columns - 20; #60;
my $sep = "~~";
if (length($name) > $max) {
my ($l1, $l2, $l3);
$l2 = length($sep);
$l1 = int (($max - $l2) / 2);
$l3 = $max - $l1 - $l2;
$name = substr($name, 0, $l1) . $sep . substr($name, -$l3, $l3);
} else {
$name = sprintf("%-".$max."s", $name);
}
return "$name ";
}
sub open_bom
{
my $fname = shift;
my ($bom, $FH);
open $FH, "<", $fname;
read $FH, $bom, 2;
if ($bom eq "\x{fe}\x{ff}" or $bom eq "\x{ff}\x{fe}") {
# print_debug "UNICODE UTF-16: $fname\n";
seek $FH, 0, 'SEEK_SET';
binmode $FH, "encoding(UTF-16)";
}
return $FH;
}
sub get_dirent
{
my ($dir, $fname) = @_;
my $dirent = $fname ? \%{$all_dirs{$dir}->{file}{$fname}} : \%{$all_dirs{$dir}};
return $dirent;
}
sub split_location
{
my $path = shift;
if ($path =~ /[\/\\]$/) {
chop $path;
return ($path);
}
if (exists $all_dirs{$path}) {
return ($path);
}
my $dir = dirname($path);
my $fname = basename($path);
return ($dir, $fname);
}
sub get_dirent_location
{
my $path = shift;
my ($dir, $fname) = split_location($path);
return get_dirent($dir, $fname);
}
sub dir_assign_movie
{
my ($dir, $movie, $fname) = @_;
my $id = $movie->id;
my $dirent = get_dirent($dir, $fname);
$dirent->{info} = 1;
$dirent->{id}{$id} = 1; # $movie
if ($dirent->{mtime}) {
print_debug "Existing mtime: $dir/$fname, ", $dirent->{mtime};
} else {
my $path = $fname ? "$dir/$fname" : $dir;
$dirent->{mtime} = File::stat::stat($path)->mtime;
print_debug "mtime: $dir/$fname, ", $dirent->{mtime};
}
}
sub group_assign_tag
{
my ($id, $tag, $ord) = @_;
if (!$pmlist->{$id}->{tag}{$tag}) {
$pmlist->{$id}->{tag}{$tag} = 1;
$pgroup->{tag}{$tag}++;
}
if (!$gbl_tags{$tag}{order}) {
$gbl_tags{$tag}{order} = $ord;
}
}
sub group_assign_movie
{
my ($path, $movie) = @_;
my $id = $movie->id;
#print_debug "group_assign_movie $path : $id";
$pmlist->{$id}->{movie} = $movie;
$pmlist->{$id}->{location}{$path}++;
# match path tags
my $lcpath = lc(normal_path($path));
for my $tag (keys %gbl_tags) {
for my $pat (@{$gbl_tags{$tag}{pattern}}) {
$pat = lc(normal_path($pat));
if (index($lcpath, $pat) >= 0) {
group_assign_tag($id, "$tag");
last;
}
}
}
# imdb movie type to tag
if ($movie->type =~ /series/i) {
group_assign_tag($id, "Series", 100);
} elsif ($movie->type =~ /vg/i) {
group_assign_tag($id, "VideoGame", 100);
} elsif ($movie->type =~ /video/i) {
group_assign_tag($id, "Video", 100);
} elsif ($movie->type =~ /tv/i) {
group_assign_tag($id, "TV", 100);
} elsif ($movie->type =~ /\bv\b/i) { # \b = word boundary
group_assign_tag($id, "Video", 100);
} elsif ($movie->type) {
group_assign_tag($id, $movie->type, 100);
}
}
sub count_loc
{
my $id = shift;
my $num_loc = 0;
return unless $pmlist->{$id};
for my $nl (values %{$pmlist->{$id}->{location}}) { $num_loc += $nl; }
return $num_loc;
}
sub parse_nfo
{
my ($fdir, $fname) = @_;
print_debug "PARSE: $fname\n";
my $shortname = shorten($fname);
my $found = 0;
my $F_NFO = open_bom $fname;
while (<$F_NFO>) {
if (/imdb\.com\/title\/tt(\d+)/i) {
my $id = $1;
$found++;
if ($found>1) {
$shortname = shorten(" +++ ($found) " . $fname . "");
}
print_detail "$fname: $id\n";
print_note "$shortname: $id";
my $m;
if ($pmlist->{$id}) {
$m = $pmlist->{$id}->{movie};
} else {
$m = getmovie($id);
}
if (!$m) {
# print failure?
print_note "\n";
next;
}
dir_assign_movie($fdir, $m);
group_assign_movie($fdir."/", $m);
my $num_loc = count_loc($id);
if ( $num_loc > 1 ) { print_note "*$num_loc"; }
print_note " OK\n";
}
}
close $F_NFO;
if (!$found) {
print_detail "$fname: IMDB NOT FOUND\n";
print_note "$shortname: IMDB NOT FOUND\n";
}
}
my $END_DIR_MARK = "...END...";
# find process (wanted)
sub process_file
{
my $fname = $File::Find::name;
print_debug "PROCESS: '$fname'\n";
if (substr($fname, -1-length($END_DIR_MARK)) eq "/$END_DIR_MARK") {
# filter will append this as the last entry in dir.
# this is better done here than in post-process,
check_dir_info($File::Find::dir);
return;
}
if (match_ext($fname, @parse_ext) and -f $fname) {
parse_nfo($File::Find::dir, $fname);
}
}
sub match_path
{
my ($dir, $name, $match) = @_;
my $cmpname;
# equalize slashes
$match = normal_path($match);
if ($match =~ m{/}) {
# slash in match name, use last part of full path name
my $path = "$dir/$name";
$cmpname = substr($path, -length($match));
#print_debug "Skip-search path: $match in: $cmpname\n";
} else {
$cmpname = $name;
}
# ignore case
return (lc($cmpname) eq lc($match));
}
# find preprocess
sub filter_dir
{
my @list;
my $visited = $all_dirs{$File::Find::dir}->{visited};
# if already visited in previous group, just copy info.
if ($visited) {
print_debug "RE-VISITED: $File::Find::dir\n";
for my $id (keys %{$all_dirs{$File::Find::dir}->{id}}) {
group_assign_movie($File::Find::dir."/", $movie{$id});
print_debug "RE-VISITED: $File::Find::dir : $id\n";
print_note shorten("$File::Find::dir/"), ": $id (re)\n";
}
} else {
print_debug "VISITED: $File::Find::dir\n";
$all_dirs{$File::Find::dir}->{visited} = 1;
}
print_debug "FILTER: @_\n";
for my $name (@_) {
next if ($name eq "." or $name eq "..");
my $skip = 0;
#my $fname = normal_path($File::Find::dir . "/" . $name);
my $fname = "$File::Find::dir/$name";
# only stat file once
my $f_is_dir = -d $fname;
my $f_is_file = -f _; # _ is previous stat
# if already visited, pass through only directories,
# no need to process files again.
next if ($visited and ! $f_is_dir);
# print_debug "filter check: $name\n";
for my $s (@{$pgroup->{skiplist}}, @skiplist) {
if (match_path($File::Find::dir, $name, $s)) {
$skip = 1;
last;
}
}
# append "/" to dirs
my $fnamex = $fname;
if ( $f_is_dir ) { $fnamex .= "/"; }
for my $re (@{$pgroup->{rxskiplist}}, @rxskiplist) {
# ignore case
# use (?-i) in regex to force case sensitive
if ($fnamex =~ /$re/i) {
#print_debug "SKIP RegEx: $re path: $fname\n";
$skip = 1;
last;
}
}
if ($skip) {
print_note shorten(" --- " . $fname), ": SKIP\n";
} else {
# is file?
if ($f_is_file) {
# is relevant media file?
if (match_ext($name, @media_ext)) {
$all_dirs{$File::Find::dir}->{relevant}->{$name} = 1;
}
# has to be parsed?
if (match_ext($name, @parse_ext)) {
push @list, $name;
}
}
# directory
elsif ($f_is_dir) {
push @list, $name;
}
}
}
# append a special marker to end of list, so that process_files
# will try to autoguess if no info is found.
push @list, $END_DIR_MARK;
return @list;
}
# check if info can be inherited from parent
# Cases:
# dir/name.rar dir/name/file.avi
# dir/cd[12]/file.avi
# note: find() processes files in a dir first, then follows subdirs,
# so it's safe to assume the subdir has had all files processed already.
sub inherit
{
my ($dir, $parent) = @_;
return 0 unless ($all_dirs{$parent}->{info});
print_note shorten("$dir/"), ": Inherit\n";
$all_dirs{$dir}->{info} = $all_dirs{$parent}->{info};
$all_dirs{$dir}->{id} = $all_dirs{$parent}->{id};
$all_dirs{$dir}->{mtime} = $all_dirs{$parent}->{mtime};
for my $id (keys %{$all_dirs{$parent}->{id}}) {
if ($pmlist->{$id}) {
# inherit only if present in current group
$pmlist->{$id}->{location}{$dir}++;
}
}
return 1;
}
sub automatch1
{
my ($dir, $fname) = @_;
my $path = "$dir/$fname";
my ($title, $year, $type, $ccount) = path_to_guess($fname ? cut_ext($fname) : $dir);
return 0 if (!$title);
return 0 if (!$opt_match_year and !$year and !$type and ($ccount < 2));
my $dirent = get_dirent($dir, $fname);
print_note shorten($path), ": GUESS\n";
print_note shorten(" ??? Guess: '".$title."' (".$year.")".($type?" [$type]":"")), ": ";
my $msearch = findmovie($title, $year, $type);
if (!$msearch && $year) {
# no match found, retry without year
$msearch = findmovie($title, 0, $type);
}
if ($msearch and $msearch->id and
($msearch->direct_hit or $opt_match_first))
{
print_note $msearch->id, " MATCH\n";
dir_assign_movie($dir, $msearch, $fname);
if (!$opt_miss_match) {
group_assign_movie($path, $msearch);
}
if ($opt_auto_save) {
save_movie($dir, $msearch);
} else {
$dirent->{guess} = 1;
group_assign_tag($msearch->id, "Guess", 110);
}
return 1 if ($msearch->direct_hit);
# return 1 if direct hit
} elsif ($msearch) {
my $nmatch = scalar @{$msearch->matches};
print_note "Matches: $nmatch\n";
$dirent->{matches} = $nmatch;
$dirent->{matchlist} = $msearch->matches;
} else {
$dirent->{matches} = 0;
print_note "No Match\n";
}
return 0;
}
sub automatch
{
my $dir = shift;
print_debug "AUTOMATCH: $dir";
return if (automatch1($dir));
return unless ($opt_match_fname);
# not direct hit and match_fname enabled:
# search through relevant files
return unless ($all_dirs{$dir}->{relevant});
my $fn;
for $fn (keys %{$all_dirs{$dir}->{relevant}}) {
if (match_ext($fn, @video_ext)) {
print_debug("filename guess: $dir/$fn");
automatch1($dir, $fn);
}
}
}
# find postprocess
sub check_dir_info
{
my $path = shift;
# my ($dir, $parent) = fileparse($path);
my $parent = dirname($path);
my $dir = basename($path);
print_debug "CHECK DIR: '$parent' '$dir' $path\n";
return if (!$parent or $dir eq ".");
# if already visited, no need to guess again
return if ($all_dirs{$path}->{info});
return if (!$all_dirs{$path}->{relevant});
# check for rar, nfo, cd1/cd2, VIDEO_TS
my $rar = "$parent/$dir.rar";
my $nfo = "$parent/$dir.nfo";
if ( -e $rar or -e $nfo
or $dir =~ /^cd\d$/i
or uc($dir) eq "VIDEO_TS" )
{
if (inherit($path, $parent)) { return; }
}
# automatch
if ($opt_auto) {
automatch($path);
}
}