summaryrefslogtreecommitdiff
path: root/lib/gcstar/GCImport/GCImportFolder.pm
blob: 10d9fd195c9502158f632f87540d29ae3979cf2d (plain)
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
package GCImport::GCImportFolder;

###################################################
#
#  Copyright 2005-2010 Christian Jodar
#
#  This file is part of GCstar.
#
#  GCstar 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 2 of the License, or
#  (at your option) any later version.
#
#  GCstar 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 GCstar; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
#
###################################################

use strict;

use GCImport::GCImportBase;

{
    package GCImport::GCImporterFolder;

    use File::Find;
    use File::Basename;
    use base qw(GCImport::GCImportBaseClass);

    use GCPlugins;

    sub new
    {
        my $proto = shift;
        my $class = ref($proto) || $proto;
        my $self  = $class->SUPER::new();
        
        bless ($self, $class);
        return $self;
    }

    sub wantsFieldsSelection
    {
        return 0;
    }

    sub wantsFileSelection
    {
        return 1;
    }
    
    sub wantsDirectorySelection
    {
        return 1;
    }
    
    sub shouldBeHidden
    {
        return 1;
    }

    sub getFilePatterns
    {
       return ();
    }
    
    #Return supported models name
    sub getModels
    {
        return ['GCfilms', 'GCMusics'];
    }

    sub getOptions
    {
        my $self = shift;
        
        my $pluginsList;
        foreach (@{$self->{model}->getPluginsNames})
        {
            my $plugin = $GCPlugins::pluginsMap{$self->{model}->getName}->{$_};
            push @$pluginsList,$plugin->getName;
        }
        
        
        return [
            {
                name => 'plugin',
                type => 'options',
                label => 'Plugin',
                valuesList => $pluginsList
            },
            {
                name => 'multipleResult',
                type => 'options',
                label => 'MultipleResult',
                tooltip => 'MultipleResultTooltip',
                valuesList => 'Ask,AskEnd,AddWithoutInfo,DontAdd,TakeFirst',
                default => 'Ask',
            },
            {
                name => 'noResult',
                type => 'options',
                label => 'NoResult',
                tooltip => 'NoResultTooltip',
                valuesList => 'AddWithoutInfo,DontAdd', # TODO AskNewName AskNewPlugin at End
                default => 'AddEmpty',
            },
            {
                name => 'recursive',
                type => 'yesno',
                label => 'Recursive',
                default => '1'
            },

            {
                name => 'suffixes',
                type => 'short text',
                label => 'Suffixes',
                tooltip => 'SuffixesTooltip',
                default => '',
            },

            {
                name => 'remove',
                type => 'short text',
                label => 'Remove',
                tooltip => 'RemoveTooltip',
                default => '',
            },
            {
                name => 'removeWholeWord',
                type => 'yesno',
                label => 'RemoveWholeWord',
                tooltip => 'RemoveTooltipWholeWord',
                default => '1',
            },
            {
                name => 'removeRegularExpr',
                type => 'yesno',
                label => 'RemoveRegularExpr',
                tooltip => 'RemoveTooltipRegularExpr',
                changedCallback => sub { 
                        my ($self,$widget) =@_;
                            $widget->[0]->{options}->{removeWholeWord}->lock($self->getValue);
                        },
                default => '0',
            },
            {
                name => 'skipFileAlreadyInCollection',
                type => 'options',
                label => 'SkipFileAlreadyInCollection',
                tooltip => 'SkipFileAlreadyInCollectionTooltip',
                valuesList => 'SkipFileNo,SkipFileFullPath,SkipFileFileName,SkipFileFileNameAndUpdate',
                default => 'SkipFileNo',
            },
            {
                name => 'infoFromFileNameRegExp',
                type => 'history text',
                label => 'InfoFromFileNameRegExp',
                tooltip => 'InfoFromFileNameRegExpTooltip',
                initValues => ['',
                                '^$A\s*([[\(]part $x( of $y)?[)\]])?\s*([[\(]$Y[)\]])?\s*$',
                                '^$N\s+[^\w ]\s+S$SE$E\s+[^\w ]\s+$T\s+([[(]part $x( of $y)?[)\]])?\s*$',
                                ],
                default => '',
             },
        ];
        
        
    }
      
    sub getModelName
    {
        my $self = shift;
        return $self->{model}->getName;
    }

    # Required by extracter to make this class acts as a panel
    sub AUTOLOAD
    {
        return [];
    }

    sub getItemsArray
    {
        my ($self, $directory) = @_;
        my @result;
        my @filesList;

        #First we try to get the correct plugin
        my $plugin = $GCPlugins::pluginsMap{$self->{model}->getName}->{$self->{options}->{plugin}};
        $plugin->{bigPics} = $self->{options}->{parent}->{options}->bigPics;
        my $titleField = $self->{model}->{commonFields}->{title};
        my $fileField = $self->{model}->{commonFields}->{play};

        # Required by extracter
        $self->{lang} = $self->{options}->{lang};

        (my $suffixes = $self->{options}->{suffixes}) =~ s/[,; ]/\|/g;
        $suffixes =~ s/\*\.//g;
        # Create list of files
        if ($self->{options}->{recursive})
        {
            find(sub {
                return if -d $File::Find::name;
                return if ! /$suffixes$/;
                my $name=Encode::decode_utf8($File::Find::name);
                push @filesList, $name;
            }, $directory);
        }
        else
        {
            foreach (glob "$directory/*")
            {
                next if -d $_;
                next if ! /$suffixes$/;
                push @filesList, $_;
            }
        }
        my $resultsDialog;
        # initialize choose good result dialog if needed
        if (($self->{options}->{multipleResult} ne 'Ask') || ($self->{options}->{multipleResult} ne 'AskEnd'))
        {
            $resultsDialog = $self->{options}->{parent}->getDialog('Results');
            $resultsDialog->setModel($self->{model}, $self->{model}->{fieldsInfo});
            $resultsDialog->setMultipleSelection(0);
        }
        #Initialize stuff to retrieve info from name with regexp
        my $infoFromName;
        if ($self->{options}->{infoFromFileNameRegExp} ne '')
        {
            my %knownParam=($titleField=>'T',alphabTitle=>'A',year=>'Y',season=>'S',episode=>'E',alphabSeries=>'N',number=>'x',totNumber=>'y');
            my $orderStr= $self->{options}->{infoFromFileNameRegExp};
            $orderStr=~ s/(?<!\$).//g;
            # Search the order of $A $T ... in the user regexp
            my %places;
            foreach my $key (keys %knownParam) {
                my $i=1+index $orderStr,$knownParam{$key};
                $places{$i} = $key;
            }
            my $myRegExp=$self->{options}->{infoFromFileNameRegExp};
            # avoid capturing something else than $T,$A ... make already present () not capturing
            $myRegExp =~ s/(?<!\\)\(/(?:/g;
            my $articles='(?:'.join('|',@{$self->{model}->{parent}->{articles}}).')\'?\b';
            our $myRegExpArt=qr/^(.*?)(?:, ?($articles))?$/i;
            
            $myRegExp =~ s/\$A/(.*?(?:, ?$articles)?)/g;
            $myRegExp =~ s/\$N/(.*?(?:, ?$articles)?)/g;
            $myRegExp =~ s/\$T/(.*?)/;
            $myRegExp =~ s/\$Y/(\\d{2}|\\d{4}?)/;
            $myRegExp =~ s/\$x/(\\d{1,2})/;
            $myRegExp =~ s/\$y/(\\d{1,2})/;
            $myRegExp =~ s/\$E/(\\d{1,4}?)/;
            $myRegExp =~ s/\$S/(\\d{1,2}?)/;
            sub deAlpha{
                my $s;
                $_[0] =~ $myRegExpArt;
                $s=$1;
                my $a=$2.' ' if $2 && (substr($2,-1) ne '\'');
                $s=$a.$s if $a;
                return $s;
            }
            # Check if regexp is good
            my $pattern = shift;
            my $test = eval { $myRegExp=qr/$myRegExp/i };
            #print $myRegExp;
            #
            if ($@)
            {
                $myRegExp= qr/./ ;print $@;
            }
            my $i=2;
            $infoFromName=sub {
                my $n=$_[0] ;
                $n=~ $myRegExp;
                my %info; # TODO Can be more readable in Perl 5.10 by using named capturing
                $info{$places{1}}=$1 if $1;$info{$places{2}}=$2 if $2;$info{$places{3}}=$3 if $3;$info{$places{4}}=$4 if $4;$info{$places{5}}=$5 if $5;
                $info{$places{6}}=$6 if $6;$info{$places{7}}=$7 if $7;$info{$places{8}}=$8 if $8;$info{$places{9}}=$9 if $9;$info{$places{10}}=$10 if $10;
                $info{$places{11}}=$11 if $11;$info{$places{12}}=$12 if $12;$info{$places{13}}=$13 if $13;$info{$places{14}}=$14 if $14;$info{$places{15}}=$15 if $15;
                $info{$places{16}}=$16 if $16;$info{$places{17}}=$17 if $17;$info{$places{18}}=$18 if $18;$info{$places{19}}=$19 if $19;$info{$places{20}}=$20 if $20;

                $info{$titleField}=deAlpha($info{alphabTitle}) if($info{alphabTitle});
                $info{series}=deAlpha($info{alphabSeries}) if($info{alphabSeries});
                return \%info;
            }
        }
        # initialize regexp word to remove
        my $removed =$self->{options}->{remove};
        if(!$self->{options}->{removeRegularExpr})
        {
            $removed =~ s/[,; ]/\|/g;
            if($self->{options}->{removeWholeWord})
            {
                $removed=~s/\|/\\b\|\\b/g ;
                $removed='\b'.$removed.'\b';
            }
        }
        # if we want to ignore files already in the list
        # we initialize a hash with filenames to be fast !
        my %fileNameKnown;
        if($self->{options}->{skipFileAlreadyInCollection} ne 'SkipFileNo')
        {
            if($self->{options}->{skipFileAlreadyInCollection} eq 'SkipFileFullPath')
            {
                foreach my $originalFilm(@{$self->{options}->{originalList}->{itemArray}})
                {
                    $fileNameKnown{$originalFilm->{$fileField}}=$originalFilm;
                }
            }
            else
            {
                foreach my $originalFilm(@{$self->{options}->{originalList}->{itemArray}})
                {
                    $fileNameKnown{basename($originalFilm->{$fileField})}=$originalFilm;
                }
            }
        }
        my $hasFileWaiting=0;my $inWaitingQueue=0;
        # Main loop on files entries
        file: foreach my $file(@filesList)
        {
            if($file eq 'WaitingList')
            {
                $inWaitingQueue=1;
                next file;
            }
            # Skip file already in the collection
                next file if(($self->{options}->{skipFileAlreadyInCollection} eq 'SkipFileFullPath') && (exists $fileNameKnown{$file}));
                next file if(($self->{options}->{skipFileAlreadyInCollection} eq 'SkipFileFileName') && (exists $fileNameKnown{basename($file)}));
                if(($self->{options}->{skipFileAlreadyInCollection} eq 'SkipFileFileNameAndUpdate') && (exists $fileNameKnown{basename($file)}))
                {
                    # if filename already in collection, and collection full path invalid : correct it
                    if (!(-e $fileNameKnown{basename($file)}->{$fileField}))
                    {
                        print "Path updated : ",$fileNameKnown{basename($file)}->{$fileField},"\n";
                        print "           --> ",$file,"\n";
                        $fileNameKnown{basename($file)}->{$fileField}=$file;
                    }
                    next file;
                }
            
            # Get info from the file (avi, mp3, ...)
            my $extracter = $self->{model}->getExtracter($self, $file, $self, $self->{model});
            my $extracted = $extracter->getInfo;
             # Add info from file
            my $infoFromFile={$fileField => $file};
            foreach my $field(keys %$extracted)
            {
                $infoFromFile->{$field} = $extracted->{$field}->{value};
            }
            
            # Test if subtitle is present
            if ($self->{model}->getName eq 'GCfilms')
            {
                my @subtitlesExt=qw(sub srt);
                my @subtitlesFiles;
                my $startFileName=$file;
                $startFileName=~s/\.[^.]*$//;
                for my $ext(@subtitlesExt)
                {
                    my $fileSubsName=$startFileName.'.'.$ext;
                    if(-e $fileSubsName)
                    {
                        #TODO Try to guess the language see cpan 
                        my $lang=["Yes"];
                        push @subtitlesFiles,$lang;
                    }
                }
                $infoFromFile->{subt}=\@subtitlesFiles if (@subtitlesFiles);
            }
            my $infoFromFileName;
            my $name = basename($file);
            # Filter the name
            # Remove suffix
            $name =~ s/\.[^.]*$//;
            # Try to apply regexp on filename
            if ($self->{options}->{infoFromFileNameRegExp} ne '')
            {
                $infoFromFileName=&$infoFromName($name);
                $name = $infoFromFileName->{$titleField} if ($infoFromFileName->{$titleField} ne '');
                #TODO: Use this known info to search with plugin
            }
            # Remove everything between () {} []
            $name =~ s/[\(\[\{].*?[\)\]\}]/ /g;
            # Remove special characters
            $name =~ s/[-\._,#@"']/ /g;
            #'"
            # Remove info from extracter for movies
            if ($self->{model}->getName eq 'GCfilms')
            {
                my $info = $extracted->{video}->{value}.'|'.$extracted->{audio}->{value}->[0]->[1];
                $info =~ s/ (.*?)//g;
                $name =~ s/$info//g;
            }
            $name =~ s/$removed//gi;

            # $name contains the title to search
            $plugin->{title} = $name;
            $plugin->{type} = 'load';
            $plugin->{urlField} = $self->{model}->{commonFields}->{url};
            $plugin->{searchField} = $titleField;

            #Initialize what will be pushed in the array
            my $infoPlugin = {$titleField => $name};
        
            $self->{options}->{parent}->setWaitCursor($self->{options}->{lang}->{StatusSearch}.' ('.$name.')');
            $plugin->load;

            my $itemNumber = $plugin->getItemsNumber;

            if ($itemNumber == 0)
            {
                goto endPluginGetItemInfo if (($self->{options}->{noResult} eq 'AddEmpty'));
                next file if (($self->{options}->{noResult} eq 'DontAdd'));
            }
            else
            {
                $plugin->{type} = 'info';
                if (($itemNumber == 1) || ($self->{options}->{multipleResult} eq 'TakeFirst'))
                {
                    $plugin->{wantedIdx} = 0;
                }
                elsif($self->{options}->{multipleResult} eq 'AddWithoutInfo' )
                {
                    goto endPluginGetItemInfo;
                }
                elsif($self->{options}->{multipleResult} eq 'DontAdd' )
                {
                    next file;
                }
                elsif($self->{options}->{multipleResult} eq 'AskEnd' && !$inWaitingQueue)
                {
                    # re push the filename at the end of the list, to be proceded
                    push @filesList,'WaitingList' if !$hasFileWaiting;
                    push @filesList,$file;
                    $hasFileWaiting=1;
                    next file;
                }
                else
                {
                    # Ask the user to choose
                    my $withNext = 0;
                    my @items = $plugin->getItems;
                    $resultsDialog->setWithNext(0);
                    $resultsDialog->setSearchPlugin($plugin);
                    $resultsDialog->setList($name, @items);
                    $resultsDialog->show;
                    if ($resultsDialog->{validated})
                    {
                        $plugin->{wantedIdx} = $resultsDialog->getItemsIndexes->[0];
                    }
                }
                $infoPlugin = $plugin->getItemInfo;
                my $title = $infoPlugin->{$titleField};
                $self->{options}->{parent}->{defaultPictureSuffix} = $plugin->getDefaultPictureSuffix;
                foreach my $field(@{$self->{model}->{managedImages}})
                {
                    $infoPlugin->{$field} = '' if $infoPlugin->{$field} eq 'empty';
                    next if !$infoPlugin->{$field};
                    ($infoPlugin->{$field}) = $self->{options}->{parent}->downloadPicture($infoPlugin->{$field}, $title);
                }
                $infoPlugin->{plugin} =$plugin->getName();
                $infoPlugin->{comment} = $self->getLang->{CommentAuto}
                                 . "\n"
                                 . $self->getLang->{CommentSite}
                                 . $plugin->getName()
                                 . "\n"
                                 . $self->getLang->{CommentTitle}
                                 . $name
                                 . "\n"
                                 . $extracted->{comment}->{displayed};
           }
            endPluginGetItemInfo:
           
            # Add the default value
            my $defaultInfo = $self->{model}->getDefaultValues;
            
            my $info;
            # TODO : ask the user for order, or even for order on each fields
            my @order=($defaultInfo,$infoFromFile,$infoFromFileName,$infoPlugin);
            for my $infoSource(@order)
            {
                foreach my $field(keys %$infoSource)
                {
                    $info->{$field} =$infoSource->{$field} if $infoSource->{$field};
                }
            }
            push @result, $info;
            $self->{options}->{parent}->restoreCursor;            
        }
        return \@result;
    }
    
    
    sub getEndInfo
    {
        my $self = shift;
        my $message;
                
        return $message;
    }
}

1;