-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpervert.pl
365 lines (309 loc) · 10.6 KB
/
pervert.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
use strict;
use warnings;
use utf8;
use open qw/:std :utf8/;
use 5.020;
use FindBin qw/$Bin/;
use lib "$Bin/lib/";
use JSON;
use Getopt::Long;
use DBI;
use DBD::SQLite;
use Thescene::Parser qw/parse_string/;
use LWP::UserAgent;
use XML::LibXML;
use Data::Dumper;
sub main{
my $configFile;
GetOptions("config=s"=>\$configFile);
if (!defined $configFile || !-e $configFile) {
say "Please define a valid configuration file";
exit 0;
}
open my $configFH, '<', $configFile;
my $configs;
{
local $/;
$configs = decode_json( <$configFH> );
}
close $configFH;
my $dbh = _load_db($configs->{historyDatabase});
say "Starting at ".localtime;
_start_processing($configs, $dbh);
}
sub _start_processing{
my ($configs, $dbh) = @_;
my $browser = LWP::UserAgent->new(agent => "PerVeRt App/1.0",
ssl_opts => { verify_hostname => 0 },
timeout => 10);
my @wishes = @{_load_wishes($configs)};
my @candidates = ();
for (@{$configs->{feeds}}){
my $name = $_->{name};
print "Connecting to $name ";
my $response = $browser->get($_->{url});
if($response->is_error){
say "[Unable to connect: ",$response->code."]";
next;
}
print "\n";
eval{
my $content = $response->content;
$content =~ s/•//gi;
my $dom = XML::LibXML->load_xml(string => $content);
for my $item ($dom->findnodes('//channel/item')) {
my $title = $item->findvalue('title');
$title =~ s/\s+\-\s+$name$//;
if ($title =~ /\s/){
my @words = split(/\s+/, $title);
$title = join('.',@words[0..$#words-1]).'-'.$words[-1];
}
my $data = parse_string($title);
# say $title;
# say Dumper($data);
next if !$data->{source} || !$data->{resolution} || !$data->{source} || !$data->{group} || !$data->{title};
$data->{title}=join(".",map{ucfirst $_; } split(/\./, lc($data->{title})));
for my $wish (@wishes){
my $approved=1;
for my $k (keys %$wish){
# next if !exists $data->{$k};
#All the parameters in the wish must be present
if (!exists $data->{$k}){
$approved = 0;
last;
}
my $regexp = qr/$wish->{$k}/i;
if($data->{$k} !~ /$regexp/){
$approved=0;
last;
}
}
if($approved){
$data->{url}=$item->findvalue('link');
my $searchTerms = join(' ', map{$_.':'.$wish->{$_}} keys %$wish);
$data->{search}=$searchTerms;
push @candidates, $data;
}
}
}
};
if ($@) {
warn $@;
}
}
say "Number of candidates found: ".@candidates;
print_candidate($_) for (@candidates);
@candidates = @{_filter_and_remove_duplicates($configs, $dbh, \@candidates)};
say "Number of candidates approved: ".@candidates;
for my $data (@candidates){
print 'Downloading: '.$data->{title};
print " ".$data->{episode} if exists $data->{episode};
print " ".$data->{date} if exists $data->{date};
print " ".$data->{resolution} if exists $data->{resolution};
my $isDownloaded = _download($configs, $browser, $data);
_store_data_to_db($dbh, $data) if $isDownloaded;
}
}
sub print_candidate {
my ($candidate) = @_;
print "[$candidate->{title}] ";
print "[$candidate->{episode}] " if(exists $candidate->{episode});
print "[$candidate->{date}] " if(exists $candidate->{date});
print "[$candidate->{source}] " if(exists $candidate->{source});
print "[$candidate->{group}] " if(exists $candidate->{group});
print "[$candidate->{audio}] " if(exists $candidate->{audio});
print "[$candidate->{fix}] " if(exists $candidate->{fix});
print "[$candidate->{codec}] " if(exists $candidate->{fix});
print "[$candidate->{language}] " if(exists $candidate->{language});
print "[$candidate->{resolution}] " if(exists $candidate->{resolution});
print "[$candidate->{subtitles}] " if(exists $candidate->{subtitles});
print "[$candidate->{type}] " if(exists $candidate->{type});
print "[$candidate->{desc}] " if(exists $candidate->{desc} && $candidate->{desc} ne '');
print "[$2] " if ($candidate->{url} =~ /http(s)?:\/\/(.*?)\//);
print "\n";
}
sub _filter_and_remove_duplicates{
my ($configs, $dbh, $downloadList) = @_;
my @finalDownloadList=();
my @candidates=();
my @finalList = ();
# We need this to make sure that the proper realeases have priority
my @downloadList = sort {
if(exists $a->{type} && $a->{type} =~ /proper/i){
return -1;
}elsif(exists $b->{type} && $b->{type} =~ /proper/i){
return 1;
}else{
# We prefer the ones with more parameters set. However if they have the same number of parameters set
# we prefer the ones with higher resolution.
if (keys %$a == keys %$b) {
if(exists $a->{resolution} && exists $b->{resolution}) {
return _convert_resolution_to_int($a->{resolution}) <=> _convert_resolution_to_int($b->{resolution});
} else {
return 0;
}
}
return keys %$a cmp keys %$b;
} } @$downloadList;
for my $candidate (@downloadList){
print "Checking ";
print_candidate($candidate);
if(!_exists_in_history($dbh, $candidate) && !_is_filtered($configs->{filters}, $candidate)){
my $ignore = 0;
say "\tDoesn't exist in history and is not filtered - Checking previous candidates";
for my $position (0..$#finalList){
my $finalCandidate = $finalList[$position];
if (lc($finalCandidate->{title}) eq lc($candidate->{title})){
if($finalCandidate->{episode} eq $candidate->{episode}) {
say "Found already processed candidate for the same media. Discarding this one";
$ignore = 1;
last;
}
}
}
push @finalList, $candidate if !$ignore;
}
}
say "Candidates approved: ";
print "\t" && print_candidate $_ for(@finalList);
return \@finalList;
}
sub _convert_resolution_to_int{
my ($resolution) = @_;
return 0 if !$resolution;
$resolution =~ /(\d+).+/;
return int($1);
}
sub _load_wishes{
my ($configs) = @_;
my @wishList = ();
open my $ifh,'<', $configs->{requests} or die "Unable to open file $configs->{requests}: $!";
while (<$ifh>) {
chomp;
next if $_ eq '';
my %data = (title =>'');
my @args=split(' ', $_);
for my $arg (@args){
if($arg=~ /(.*?):(.*)/){
$data{$1}=$2;
}else{
$data{title}.=$arg;
}
}
push @wishList, \%data;
}
close $ifh;
return \@wishList;
}
sub _download{
my ($configs, $browser, $data) = @_;
my $outputFile = $data->{title};
$outputFile .= '.'.$data->{episode} if exists $data->{episode};
$outputFile .= '.'.$data->{date} if exists $data->{date};
$outputFile .= '.nzb';
my $response = $browser->get($data->{url}, ':content_file'=>$configs->{downloadFolder}."/$outputFile");
if($response->is_error){
say "[Unable to connect: ",$response->code."]";
return 0;
}
print "\n";
return 1;
}
sub _is_filtered{
my ($filters, $data) = @_;
my $filterName;
my $accept_download=0;
for my $k (keys %$data){
next if !exists $data->{$k};
$filterName='accept'.ucfirst $k;
if(exists $filters->{$filterName}){
for my $filter (@{$filters->{$filterName}}){
my $regexp = qr/$filter/i;
if ($data->{$k} !~ $regexp){
$accept_download += 1;
}
}
# Didn't match any of the accepted filter
if ($accept_download == @{$filters->{$filterName}} && @{$filters->{$filterName}} != 0) {
say "\tIgnored because of accepted filter @{$filters->{$filterName}}";
return 1;
}
$accept_download=0;
}
$filterName='ignore'.ucfirst $k;
if(exists $filters->{$filterName}){
for my $filter (@{$filters->{$filterName}}){
my $regexp = qr/$filter/i;
if ($data->{$k} =~ $regexp){
say "\tIgnored because of $filter [$data->{$k} vs $regexp]";
return 1;
}
}
}
}
return 0;
}
sub _load_db{
my ($dbFile) = @_;
if (!-e $dbFile) {
say "Please define a correct history database in the configuration file";
exit 0;
}
my $dbh = DBI->connect("dbi:SQLite:dbname=$dbFile",'','', {RaiseError=>1, AutoCommit=>1});
my $verified = 0;
for my $table ($dbh->tables('','main','%','TABLE')){
$verified++ if ('history' eq lc((split(/"/, $table))[3]));
}
if (!$verified) {
say "Please define a correct sqlite table.";
exit 0;
}
return $dbh;
}
sub _exists_in_history{
my ($dbh, $data) = @_;
my $query = 'select * from history where valid=1 and title like ?';
my @parameters = $data->{title};
if(exists $data->{episode}){
$query.=' and episode like ?';
push @parameters, $data->{episode};
}elsif(exists $data->{date}){
$query.=' and date like ?';
push @parameters, $data->{date};
}
my $stmt = $dbh->prepare($query);
$stmt->execute(@parameters);
my ($tuples, $rows) = $dbh->selectall_arrayref($stmt);
# We don't want to download the same invalid url
# At this moment it can exist as invalid, so we need to check if it already exists as an invalid
if (scalar @$tuples == 0){
$query = 'select * from history where valid= 0 and url=?';
$stmt = $dbh->prepare($query);
$stmt->execute($data->{url});
($tuples, $rows) = $dbh->selectall_arrayref($stmt);
return 1 if scalar(@$tuples)>0; # Same URL
# It can be the same episode but from a different indexer. So we need to check if all the params are different
# except the url and the valid parameter.
@parameters = grep {$_ ne 'url' && $_ ne 'valid'} keys %$data;
$query = 'select * from history where '.join(' and ', map{ "'$_' like ?";} @parameters );
$stmt = $dbh->prepare($query);
$stmt->execute(map{$data->{$_}} @parameters);
($tuples, $rows) = $dbh->selectall_arrayref($stmt);
return scalar(@$tuples)>0;
}
return 1;
}
sub _store_data_to_db{
my ($dbh, $data) = @_;
return 0 if !defined $data->{search} || !defined $data->{url};
my @parameters = qw/language title subtitles resolution codec audio group episode source date fix type search url/;
my $query = 'insert into history('.join(',',map{"'$_'"} @parameters).') values('.join(',', map{'?'} @parameters).')';
my $stmt = $dbh->prepare($query);
my $rv = $stmt->execute(map{$data->{$_}}@parameters) or die 'Error while storing data: '.$stmt->errstr;
return 1;
}
main;
# parse_name('Deadwood.S03E08.SPANiSH.HDTV.X264-LPH');
# parse_name('HandsOnHardcore.16.11.30.Lexi.Dona.XXX.1080p.MP4-KTR');
# parse_name('Judge.Judy.S18E45.720p.HDTV.x264-WaLMaRT');
# parse_name('La.Que.Se.Avecina.S09E17.SPANiSH.720p.HDTV.x264-BFN');