forked from markcs/xml_tv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyourtv.pl
executable file
·1600 lines (1508 loc) · 58 KB
/
yourtv.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
use strict;
use warnings;
my %thr = ();
my $threading_ok = eval 'use threads; 1';
if ($threading_ok)
{
use threads;
use threads::shared;
}
my $MAX_THREADS = 7;
use IO::Socket::SSL;
my $FURL_OK = eval 'use Furl; 1';
if (!$FURL_OK)
{
warn("Furl not found, falling back to LWP for fetching URLs (this will be slow)...\n");
use LWP::UserAgent;
}
use JSON;
use JSON::Parse 'valid_json';
use XML::Simple;
use DateTime;
use Getopt::Long;
use XML::Writer;
use URI;
use URI::Escape;
use Thread::Queue;
use Fcntl qw(:DEFAULT :flock);
use File::Copy;
use Clone qw( clone );
use Cwd qw( getcwd );
use HTML::TableExtract;
use DB_File;
use Config::Tiny;
my %map = (
'&' => 'and',
);
my $chars = join '', keys %map;
my %DUPLICATE_CHANNELS = ();
my @DUPLICATED_CHANNELS = ();
my @dupes;
my @mapyourtvlcn;
my $YOURTVTOLCN;
my @CHANNELDATA;
my @DUPECHANDATA;
my @DUPEGUIDEDATA;
my $FVICONS;
my $DVBTRIPLET;
my @GUIDEDATA;
my $FVCACHEFILE = "fv.db";
my $FVTMPCACHEFILE = ".$$.freeview-tmp-cache.db";
my $CACHEFILE = "yourtv.db";
my $CACHETIME = 86400; # 1 day - don't change this unless you know what you are doing.
my $TMPCACHEFILE = ".$$.yourtv-tmp-cache.db";
my $MANUALICONS;
my $ua;
my $Config;
my $DUPES_COUNT = 0;
my $STDOLD;
my (%dbm_hash, %thrdret);
my (%fvdbm_hash, %fvthrdret);
local (*DBMRO, *DBMRW);
my ($configfile, $DEBUG, $VERBOSE, $log, $pretty, $USEFREEVIEWICONS, $NUMDAYS, $ignorechannels, $includechannels, $extrachannels, $paytv, $hdtvchannels, $REGION, $outputfile, $message, $help) = (undef, 0, 0, undef, 0, 0, 7, undef, undef, undef, undef, 0, undef ,undef, undef, undef);
GetOptions
(
'config=s' => \$configfile,
'debug' => \$DEBUG,
'verbose' => \$VERBOSE,
'log=s' => \$log,
'pretty' => \$pretty,
'days=i' => \$NUMDAYS,
'region=s' => \$REGION,
'output=s' => \$outputfile,
'ignore=s' => \$ignorechannels,
'include=s' => \$includechannels,
'fvicons' => \$USEFREEVIEWICONS,
'cachefile=s' => \$CACHEFILE,
'fvcachefile=s' => \$FVCACHEFILE,
'cachetime=i' => \$CACHETIME,
'extrachannels=s' => \$extrachannels,
'paytv=s' => \$paytv,
'hdtv=s' => \$hdtvchannels,
'message=s' => \$message,
'duplicates=s' => \@dupes,
'changeyourtvlcn=s' => \@mapyourtvlcn,
'help|?' => \$help,
) or die ("Syntax Error! Try $0 --help");
my %ABCRADIO;
$ABCRADIO{"200"}{name} = "Double J";
$ABCRADIO{"200"}{iconurl} = "https://www.abc.net.au/cm/lb/8811932/thumbnail/station-logo-thumbnail.jpg";
$ABCRADIO{"200"}{servicename} = "doublej";
$ABCRADIO{"201"}{name} = "ABC Jazz";
$ABCRADIO{"201"}{iconurl} = "https://www.abc.net.au/cm/lb/8785730/thumbnail/station-logo-thumbnail.png";
$ABCRADIO{"201"}{servicename} = "jazz";
$ABCRADIO{"202"}{name} = "ABC Kids Listen";
$ABCRADIO{"202"}{iconurl} = "https://d24j9r7lck9cin.cloudfront.net/l/o/7/7118.1519190192.png";
$ABCRADIO{"202"}{servicename} = "kidslisten";
$ABCRADIO{"203"}{name} = "ABC Country";
$ABCRADIO{"203"}{iconurl} = "https://www.abc.net.au/radio/images/service/2018/country_480.png";
$ABCRADIO{"203"}{servicename} = "";
$ABCRADIO{"204"}{name} = "ABC News Radio";
$ABCRADIO{"204"}{iconurl} = "https://upload.wikimedia.org/wikipedia/commons/e/ee/ABC_News_Radio_2014.png";
$ABCRADIO{"204"}{servicename} = "";
$ABCRADIO{"26"}{name} = "ABC Radio National";
$ABCRADIO{"26"}{iconurl} = "https://www.abc.net.au/news/image/8054480-3x2-940x627.jpg";
$ABCRADIO{"26"}{servicename} = "RN";
$ABCRADIO{"27"}{name} = "ABC Classic";
$ABCRADIO{"27"}{iconurl} = "https://www.abc.net.au/cm/lb/9104270/thumbnail/station-logo-thumbnail.png";
$ABCRADIO{"27"}{servicename} = "classic";
$ABCRADIO{"28"}{name} = "Triple J";
$ABCRADIO{"28"}{iconurl} = "https://www.abc.net.au/cm/lb/8541768/thumbnail/station-logo-thumbnail.png";
$ABCRADIO{"28"}{servicename} = "triplej";
$ABCRADIO{"29"}{name} = "Triple J Unearthed";
$ABCRADIO{"29"}{iconurl} = "https://www.abc.net.au/cm/rimage/8869368-16x9-large.jpg?v=2";
$ABCRADIO{"29"}{servicename} = "";
my %SBSRADIO;
$SBSRADIO{"36"}{name} = "SBS Arabic24";
$SBSRADIO{"36"}{iconurl} = "http://d6ksarnvtkr11.cloudfront.net/resources/sbs/radio/images/headerlogo_sbsarabic24_300_colour.png";
$SBSRADIO{"36"}{servicename} = "poparaby";
$SBSRADIO{"37"}{name} = "SBS Radio 1";
$SBSRADIO{"37"}{iconurl} = "http://d6ksarnvtkr11.cloudfront.net/resources/sbs/radio/images/headerlogo_sbs1_300_colour.png";
$SBSRADIO{"37"}{servicename} = "sbs1";
$SBSRADIO{"38"}{name} = "SBS Radio 2";
$SBSRADIO{"38"}{iconurl} = "http://d6ksarnvtkr11.cloudfront.net/resources/sbs/radio/images/headerlogo_sbs2_300_colour.png";
$SBSRADIO{"38"}{servicename} = "sbs2";
$SBSRADIO{"39"}{name} = "SBS Chill";
$SBSRADIO{"39"}{iconurl} = "http://d6ksarnvtkr11.cloudfront.net/resources/sbs/radio/images/header_chill_300_colour.png";
$SBSRADIO{"39"}{servicename} = "chill";
$SBSRADIO{"301"}{name} = "SBS Radio 1";
$SBSRADIO{"301"}{iconurl} = "http://d6ksarnvtkr11.cloudfront.net/resources/sbs/radio/images/headerlogo_sbs1_300_colour.png";
$SBSRADIO{"301"}{servicename} = "sbs1";
$SBSRADIO{"302"}{name} = "SBS Radio 2";
$SBSRADIO{"302"}{iconurl} = "http://d6ksarnvtkr11.cloudfront.net/resources/sbs/radio/images/headerlogo_sbs2_300_colour.png";
$SBSRADIO{"302"}{servicename} = "sbs2";
$SBSRADIO{"303"}{name} = "SBS Radio 3";
$SBSRADIO{"303"}{iconurl} = "http://d6ksarnvtkr11.cloudfront.net/resources/sbs/radio/images/headerlogo_sbs3_300_colour.png";
$SBSRADIO{"303"}{servicename} = "sbs3";
$SBSRADIO{"304"}{name} = "SBS Arabic24";
$SBSRADIO{"304"}{iconurl} = "http://d6ksarnvtkr11.cloudfront.net/resources/sbs/radio/images/headerlogo_sbsarabic24_300_colour.png";
$SBSRADIO{"304"}{servicename} = "poparaby";
$SBSRADIO{"305"}{name} = "SBS PopDesi";
$SBSRADIO{"305"}{iconurl} = "http://d6ksarnvtkr11.cloudfront.net/resources/sbs/radio/images/header_popdesi_300_colour.png";
$SBSRADIO{"305"}{servicename} = "popdesi";
$SBSRADIO{"306"}{name} = "SBS Chill";
$SBSRADIO{"306"}{iconurl} = "http://d6ksarnvtkr11.cloudfront.net/resources/sbs/radio/images/header_chill_300_colour.png";
$SBSRADIO{"306"}{servicename} = "chill";
$SBSRADIO{"307"}{name} = "SBS PopAsia";
$SBSRADIO{"307"}{iconurl} = "http://d6ksarnvtkr11.cloudfront.net/resources/sbs/radio/images/header_popasia_300_colour.png";
$SBSRADIO{"307"}{servicename} = "popasia";
get_duplicate_channels(@dupes) if (@dupes and scalar @dupes);
get_fixYourTVLCNMapping(@mapyourtvlcn);
if (defined($configfile)) {
$Config = Config::Tiny->read( $configfile );
$log = $Config->{main}->{log} if (defined($Config->{main}->{log}));
$DEBUG = ToBoolean($Config->{main}->{debug}) if (defined($Config->{main}->{debug}));
$VERBOSE = ToBoolean($Config->{main}->{verbose}) if (defined($Config->{main}->{verbose}));
$pretty = ToBoolean($Config->{main}->{pretty}) if (defined($Config->{main}->{pretty}));
$NUMDAYS = $Config->{main}->{days} if (defined($Config->{main}->{days}));
$REGION = $Config->{main}->{region} if (defined($Config->{main}->{region}));
$outputfile = $Config->{main}->{output} if (defined($Config->{main}->{output}));
$ignorechannels = $Config->{main}->{ignore} if (defined($Config->{main}->{ignore}));
$includechannels = $Config->{main}->{include} if (defined($Config->{main}->{include}));
$USEFREEVIEWICONS = ToBoolean($Config->{main}->{fvicons}) if (defined($Config->{main}->{fvicons}));
$CACHEFILE = $Config->{main}->{cachefile} if (defined($Config->{main}->{cachefile}));
$FVCACHEFILE = $Config->{main}->{fvcachefile} if (defined($Config->{main}->{fvcachefile}));
$CACHETIME = $Config->{main}->{cachetime} if (defined($Config->{main}->{cachetime}));
$extrachannels = $Config->{main}->{extrachannels} if (defined($Config->{main}->{extrachannels}));
$paytv = $Config->{main}->{paytv} if (defined($Config->{main}->{paytv}));
$hdtvchannels = $Config->{main}->{hdtv} if (defined($Config->{main}->{hdtv}));
$message = $Config->{main}->{message} if (defined($Config->{main}->{message}));
$MANUALICONS = $Config->{icons} if (defined($Config->{icons}));
if ((defined($Config->{mappingYourTVtoLCN})) and ((keys %{$Config->{mappingYourTVtoLCN}}) > 0))
{
$YOURTVTOLCN = $Config->{mappingYourTVtoLCN};
}
if ((defined($Config->{duplicate})) and ((keys %{$Config->{duplicate}}) > 0))
{
@DUPLICATED_CHANNELS = ();
%DUPLICATE_CHANNELS = %{$Config->{duplicate}};
while (my ($key, $value) = each %DUPLICATE_CHANNELS)
{
push(@DUPLICATED_CHANNELS,$value);
}
}
}
if (defined($log))
{
my $logfile;
$log =~ s/\/$//;
if (-d $log)
{
$logfile = $log.'/'.$REGION.".log";
}
else
{
$logfile = $log;
}
open (my $LOG, '>', $logfile) || die "can't open $logfile. Does $logfile exist?";
open (STDERR, ">>&=", $LOG) || die "can't redirect STDERR";
select $LOG;
}
if ($FURL_OK)
{
warn("Using Furl for fetching http:// and https:// requests.\n") if ($VERBOSE);
$ua = Furl->new(
agent => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0',
timeout => 30,
headers => [ 'Accept-Encoding' => 'application/json' ],
ssl_opts => {SSL_verify_mode => 0}
);
} else {
warn("Using LWP::UserAgent for fetching http:// and https:// requests.\n") if ($VERBOSE);
$ua = LWP::UserAgent->new;
$ua->agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0");
$ua->default_header( 'Accept-Encoding' => 'application/json');
$ua->default_header( 'Accept-Charset' => 'utf-8');
}
die usage() if ($help || !defined($REGION));
$CACHEFILE = "yourtv-region_$REGION.db" if ($CACHEFILE eq "yourtv.db");
my $validregion = 0;
my @REGIONS = buildregions();
for my $tmpregion ( @REGIONS )
{
if (($tmpregion->{id} eq $REGION) and ($tmpregion->{type} ne "FTA"))
{
die("\n"
. "--region option should be an FTA region\n"
. "For PayTV, please use both --region option and --paytv option\n"
. "\n\n");
}
}
for my $tmpregion ( @REGIONS )
{
if ($tmpregion->{id} eq $REGION)
{
$validregion = 1;
define_ABC_local_radio($tmpregion->{state});
}
}
die( "\n"
. "Invalid region specified. Please use one of the following:\n\t\t"
. join("\n\t\t", (map { "$_->{id}\t=\t$_->{name}" } @REGIONS) )
. "\n\n"
) if (!$validregion); # (!defined($REGIONS->{$REGION}));
warn("\nOptions...\nregion=$REGION, output=$outputfile, days = $NUMDAYS, fvicons = $USEFREEVIEWICONS, Verbose = $VERBOSE, pretty = $pretty, \n") if ($VERBOSE);
warn("extrachannels=$extrachannels, ") if ($VERBOSE and defined($extrachannels)) ;
warn("paytv-region=$paytv,\n") if ($VERBOSE and defined($paytv));
warn("message=$message,\n") if (defined($message) and ($VERBOSE));
warn("cachefile=$CACHEFILE\n") if (defined($CACHEFILE) and ($VERBOSE));
warn("fvcachefile=$FVCACHEFILE\n") if (defined($FVCACHEFILE) and ($VERBOSE));
warn("log=$log\n") if (defined($log) and ($VERBOSE));
# Initialise here (connections to the same server will be cached)
my @IGNORECHANNELS;
@IGNORECHANNELS = split(/,/,$ignorechannels) if (defined($ignorechannels));
my @INCLUDECHANNELS;
@INCLUDECHANNELS = split(/,/,$includechannels) if (defined($includechannels));
warn("Duplicate channels: @dupes \n") if ($VERBOSE);
warn("Ignored channels: @IGNORECHANNELS \n") if ($VERBOSE);
warn("Included channels: @IGNORECHANNELS \n") if ($VERBOSE);
getFVInfo($ua);
warn("\nInitializing queues...\n") if ($VERBOSE);
my $INQ = Thread::Queue->new();
my $OUTQ = Thread::Queue->new();
warn("Initializing $MAX_THREADS worker threads...\n") if ($VERBOSE);
for (1 .. $MAX_THREADS)
{
threads->create( \&url_fetch_thread )->detach();
warn("Started thread $_...\n") if ($DEBUG);
}
warn("My current directory for cachefiles is: " . getcwd . "\n") if ($VERBOSE);
if (! -e $FVCACHEFILE)
{
warn("Freeview cache file not present/readable, this run will be slower than normal...\n");
# Create a new and empty file so this doesn't fail
tie %fvdbm_hash, "DB_File", $FVCACHEFILE, O_CREAT | O_RDWR, 0644 or
die("Cannot write to $FVCACHEFILE");
untie %fvdbm_hash;
}
warn("Opening Freeview cache files...\n") if ($VERBOSE);
my $fvdbro = tie %fvdbm_hash, "DB_File", $FVCACHEFILE, O_RDONLY, 0644 or
die("Cannot open $FVCACHEFILE");
my $fvfdro = $fvdbro->fd; # get file desc
open FVDBMRO, "+<&=$fvfdro" or die "Could not dup DBMRO for lock: $!"; # Get dup filehandle
flock FVDBMRO, LOCK_EX; # Lock it exclusively
undef $fvdbro;
my $fvdbrw = tie %fvthrdret, "DB_File", $FVTMPCACHEFILE, O_CREAT | O_RDWR, 0644 or
die("Cannot write to $FVTMPCACHEFILE");
my $fvfdrw = $fvdbrw->fd; # get file desc
open FVDBMRW, "+<&=$fvfdrw" or die "Could not dup DBMRW for lock: $!"; # Get dup filehandle
flock FVDBMRW, LOCK_EX; # Lock it exclusively
undef $fvdbrw;
if (! -e $CACHEFILE)
{
warn("Cache file not present/readable, this run will be slower than normal...\n");
# Create a new and empty file so this doesn't fail
tie %dbm_hash, "DB_File", $CACHEFILE, O_CREAT | O_RDWR, 0644 or
die("Cannot write to $CACHEFILE");
untie %dbm_hash;
}
# catch die handler
$SIG{__DIE__} = \&close_cache_and_die;
# WARNING: This has to be done *AFTER* opening threads or thread closure
# segfault the interpreter because of double free()s
warn("Opening Cache files...\n") if ($VERBOSE);
my $dbro = tie %dbm_hash, "DB_File", $CACHEFILE, O_RDONLY, 0644 or
die("Cannot open $CACHEFILE");
my $fdro = $dbro->fd; # get file desc
open DBMRO, "+<&=$fdro" or die "Could not dup DBMRO for lock: $!"; # Get dup filehandle
flock DBMRO, LOCK_EX; # Lock it exclusively
undef $dbro;
my $dbrw = tie %thrdret, "DB_File", $TMPCACHEFILE, O_CREAT | O_RDWR, 0644 or
die("Cannot write to $TMPCACHEFILE");
my $fdrw = $dbrw->fd; # get file desc
open DBMRW, "+<&=$fdrw" or die "Could not dup DBMRW for lock: $!"; # Get dup filehandle
flock DBMRW, LOCK_EX; # Lock it exclusively
undef $dbrw;
warn("Getting Channel list...\n") if ($VERBOSE);
push(@CHANNELDATA,getchannels($ua, $REGION));
push(@CHANNELDATA,SBSgetchannels());
push(@CHANNELDATA,ABCgetchannels());
warn("Getting EPG data...\n") if ($VERBOSE);
push(@GUIDEDATA,getepg($ua, $REGION, $hdtvchannels));
push(@GUIDEDATA,ABCgetepg($ua));
push(@GUIDEDATA,SBSgetepg($ua));
warn("Getting extra channel and EPG data...\n\n") if ($VERBOSE);
if (defined ($extrachannels))
{
die("--extrachannel option in wrong format. It should be <other region>-<channel number>,<channel number>,etc") if ($extrachannels !~ /(\d+)-.*/);
my ($extraregion, $extrachannel) = $extrachannels =~ /(\d+)-(.*)/;
my @channel_array = split(/,/,$extrachannel);
push(@CHANNELDATA,getchannels($ua, $extraregion, @channel_array));
push(@GUIDEDATA,getepg($ua, $extraregion, $hdtvchannels, @channel_array));
}
if (defined ($paytv))
{
my $count = 0;
my $region_timezone;
my $region_state;
my $region_name;
for my $tmpregion ( @REGIONS )
{
if ($tmpregion->{id} eq $REGION) {
$region_timezone = $tmpregion->{timezone};
$region_name = $tmpregion->{name};
$region_state = $tmpregion->{state};
}
}
for my $tmpregion ( @REGIONS )
{
if ($tmpregion->{id} eq $paytv)
{
$REGIONS[$count]->{state} = $region_state;
$REGIONS[$count]->{name} = $region_name;
$REGIONS[$count]->{timezone} = $region_timezone;
}
$count++;
}
push(@CHANNELDATA,getchannels($ua, $paytv));
push(@GUIDEDATA,getepg($ua, $paytv, $hdtvchannels));
}
warn("Closing Queues...\n") if ($VERBOSE);
# this will close the queues
$INQ->end();
$OUTQ->end();
# joining all threads
warn("Shutting down all threads...\n") if ($VERBOSE);
warn("Closing Cache files.\n") if ($VERBOSE);
# close out both DBs and write the new temp one over the saved one
&close_cache();
# reset die handler
$SIG{__DIE__} = \&CORE::die;
warn("Replacing old Cache file with the new one...\n") if ($VERBOSE);
move($TMPCACHEFILE, $CACHEFILE);
move($FVTMPCACHEFILE, $FVCACHEFILE);
warn("Starting to build the XML...\n") if ($VERBOSE);
if (defined($message))
{
$message = "http://xmltv.net - ".$message;
}
else {
$message = "http://xmltv.net";
}
my $XML = XML::Writer->new( OUTPUT => 'self', DATA_MODE => ($pretty ? 1 : 0), DATA_INDENT => ($pretty ? 8 : 0) );
$XML->xmlDecl("UTF-8");
$XML->doctype("tv", undef, "xmltv.dtd");
$XML->startTag('tv', 'source-info-name' => $message, 'generator-info-url' => "http://www.xmltv.org/");
warn("Building the channel list...\n") if ($VERBOSE);
printchannels(\$XML);
warn("Building the EPG list...\n") if ($VERBOSE);
printepg(\$XML);
warn("Finishing the XML...\n") if ($VERBOSE);
$XML->endTag('tv');
if (!defined $outputfile)
{
warn("Finished! xmltv guide follows...\n\n") if ($VERBOSE);
print $XML;
print "\n" if ($pretty); # XML won't add a trailing newline
} else {
warn("Writing xmltv guide to $outputfile...\n") if ($VERBOSE);
open FILE, ">$outputfile" or die("Unable to open $outputfile file for writing: $!\n");
print FILE $XML;
close FILE;
warn("Done!\n") if ($VERBOSE);
}
exit(0);
sub close_cache_and_die
{
warn("Error. Script died\n");
warn($_[0]);
&close_cache;
unlink $TMPCACHEFILE;
unlink $FVTMPCACHEFILE;
exit(1);
}
sub close_cache
{
untie(%dbm_hash);
untie(%thrdret);
untie(%fvdbm_hash);
untie(%fvthrdret);
close DBMRW;
close DBMRO;
close FVDBMRW;
close FVDBMRO;
}
sub url_fetch_thread
{
local $| = 1;
my $tua;
if ($FURL_OK)
{
$tua = Furl->new(
agent => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0',
timeout => 30,
headers => [ 'Accept-Encoding' => 'application/json' ],
ssl_opts => {SSL_verify_mode => 0}
);
} else {
$tua = LWP::UserAgent->new;
$tua->agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0");
$tua->default_header('Accept-Encoding' => 'application/json');
$tua->default_header('Accept-Charset' => 'utf-8');
}
while (defined( my $airingid = $INQ->dequeue()))
{
my $url = "https://www.yourtv.com.au/api/airings/" . $airingid;
warn("Using $tua to fetch $url\n") if ($DEBUG);
print "." if ($VERBOSE);
my $res = $tua->get($url);
if (!$res->is_success)
{
warn("\n".threads->self()->tid(). ": Thread Fetch FAILED for: $url (" . $res->code . ")\n") if ($VERBOSE);
if ($res->code > 399 and $res->code < 500)
{
$OUTQ->enqueue("$airingid|FAILED");
} elsif ($res->code > 499) {
$OUTQ->enqueue("$airingid|ERROR");
} else {
# shouldn't be reached
$OUTQ->enqueue("$airingid|UNKNOWN")
}
} else {
$OUTQ->enqueue($airingid . "|" . $res->content);
warn(threads->self()->tid(). ": Thread Fetch SUCCESS for: $url\n") if ($DEBUG);
}
}
}
sub getchannels
{
#my $ua = shift;
my ($ua, $region, @extrachannels) = @_;
my @channeldata;
my $url = "https://www.yourtv.com.au/api/regions/" . $region . "/channels";
my $tmpchanneldata;
my $res = geturl($ua,$url);
if (!$res->is_success)
{
die("(getchannels) Unable to connect to YourTV. (".$res->{code}.")\n");
}
$tmpchanneldata = JSON->new->relaxed(1)->allow_nonref(1)->decode($res->content);
my $dupe_count = 0;
my $channelcount = 0;
for (my $count = 0; $count < @$tmpchanneldata; $count++)
{
next if ( ( grep( /^$tmpchanneldata->[$count]->{number}$/, @IGNORECHANNELS ) ) );
next if ( ( !( grep( /^$tmpchanneldata->[$count]->{number}$/, @INCLUDECHANNELS ) ) ) and ((@INCLUDECHANNELS > 0)));
next if ( ( !( grep( /^$tmpchanneldata->[$count]->{number}$/, @extrachannels ) ) ) and ((@extrachannels > 0)));
$channeldata[$channelcount]->{name} = $tmpchanneldata->[$count]->{description};
if (defined($YOURTVTOLCN->{$tmpchanneldata->[$count]->{number}}))
{
$channeldata[$channelcount]->{id} = $YOURTVTOLCN->{$tmpchanneldata->[$count]->{number}}.".yourtv.com.au";
$channeldata[$channelcount]->{lcn} = $YOURTVTOLCN->{$tmpchanneldata->[$count]->{number}};
warn("Changed YourTV channel $tmpchanneldata->[$count]->{number} to $YOURTVTOLCN->{$tmpchanneldata->[$count]->{number}} ...\n") if ($VERBOSE);
}
else
{
$channeldata[$channelcount]->{id} = $tmpchanneldata->[$count]->{number}.".yourtv.com.au";
$channeldata[$channelcount]->{lcn} = $tmpchanneldata->[$count]->{number};
}
my $channelIsDuped = 0;
++$channelIsDuped if ( ( grep( /$channeldata[$channelcount]->{lcn}$/, @DUPLICATED_CHANNELS ) ) );
if (defined($MANUALICONS->{$channeldata[$channelcount]->{lcn}}))
{
$channeldata[$channelcount]->{icon} = $MANUALICONS->{$channeldata[$channelcount]->{lcn}};
}
elsif (defined($tmpchanneldata->[$count]->{logo}->{url}))
{
$channeldata[$channelcount]->{icon} = $tmpchanneldata->[$count]->{logo}->{url};
$channeldata[$channelcount]->{icon} =~ s/.*(https.*?amazon.*)/$1/;
$channeldata[$channelcount]->{icon} = uri_unescape($channeldata[$channelcount]->{icon});
}
$channeldata[$channelcount]->{icon} = $FVICONS->{$channeldata[$channelcount]->{lcn}} if ((defined($FVICONS->{$channeldata[$channelcount]->{lcn}})) and ($USEFREEVIEWICONS));
warn("Got channel $channeldata[$channelcount]->{id} - $channeldata[$channelcount]->{name} ...\n") if ($VERBOSE);
if ($channelIsDuped)
{
foreach my $dchan (sort keys %DUPLICATE_CHANNELS)
{
next if ($DUPLICATE_CHANNELS{$dchan} ne $tmpchanneldata->[$count]->{number});
$DUPECHANDATA[$dupe_count]->{tv_id} = $channeldata[$count]->{tv_id};
$DUPECHANDATA[$dupe_count]->{name} = $channeldata[$count]->{name};
$DUPECHANDATA[$dupe_count]->{id} = $dchan . ".yourtv.com.au";
$DUPECHANDATA[$dupe_count]->{lcn} = $dchan;
$DUPECHANDATA[$dupe_count]->{icon} = $channeldata[$count]->{icon};
warn("Duplicated channel $channeldata[$count]->{name} -> $DUPECHANDATA[$dupe_count]->{id} ...\n") if ($VERBOSE);
++$dupe_count;
}
}
$channelcount++;
}
return @channeldata;
}
sub getepg
{
#my $ua = shift;
my ($ua, $region, $hdtv, @extrachannels) = @_;
my $showcount = 0;
my $dupe_scount = 0;
my $url;
my @guidedata;
my $region_timezone;
my $region_name;
my @hdtvchannels = split(/,/,$hdtv) if (defined($hdtv));
for my $tmpregion ( @REGIONS )
{
if ($tmpregion->{id} eq $region) {
$region_timezone = $tmpregion->{timezone};
$region_name = $tmpregion->{name};
}
}
warn(" \n") if ($VERBOSE);
my $nl = 0;
for(my $day = 0; $day < $NUMDAYS; $day++)
{
my $day = nextday($day);
my $id;
my $url = URI->new( 'https://www.yourtv.com.au/api/guide/' );
$url->query_form(day => $day, timezone => $region_timezone, format => 'json', region => $region);
warn(($nl ? "\n" : "" ) . "Getting channel program listing for $region_name ($region) for $day ...\n") if ($VERBOSE);
$nl = 0;
my $res = geturl($ua,$url);
if (!$res->is_success)
{
die("\n(getepg) FATAL: Unable to connect to YourTV for $url (".$res->{code}.")\n");
}
my $tmpdata;
eval
{
$tmpdata = JSON->new->relaxed(1)->allow_nonref(1)->decode($res->content);
1;
};
for (my $channelblocks = 0; $channelblocks < @$tmpdata; $channelblocks++)
{
my $chandata = $tmpdata->[$channelblocks]->{channels};
if (defined($chandata))
{
for (my $channelcount = 0; $channelcount < @$chandata; $channelcount++)
{
next if (!defined($chandata->[$channelcount]->{number}));
next if ( ( grep( /^$chandata->[$channelcount]->{number}$/, @IGNORECHANNELS ) ) );
next if ( ( !( grep( /^$chandata->[$channelcount]->{number}$/, @INCLUDECHANNELS ) ) ) and ((@INCLUDECHANNELS > 0)));
next if ( ( !( grep( /^$chandata->[$channelcount]->{number}$/, @extrachannels ) ) ) and ((@extrachannels > 0)));
my $enqueued = 0;
if (defined($YOURTVTOLCN->{$chandata->[$channelcount]->{number}}))
{
$id = $YOURTVTOLCN->{$chandata->[$channelcount]->{number}};
}
else
{
$id = $chandata->[$channelcount]->{number};
}
my $channelIsDuped = 0;
$channelIsDuped = $id if ( ( grep( /^$id$/, @DUPLICATED_CHANNELS ) ) );
my $blocks = $chandata->[$channelcount]->{blocks};
$id = $id.".yourtv.com.au";
for (my $blockcount = 0; $blockcount < @$blocks; $blockcount++)
{
my $subblocks = $blocks->[$blockcount]->{shows};
for (my $airingcount = 0; $airingcount < @$subblocks; $airingcount++)
{
warn("Starting... ($blockcount < " . scalar @$blocks . "| $airingcount < " . scalar @$subblocks . ")\n") if ($DEBUG);
my $airing = $subblocks->[$airingcount]->{id};
warn("Starting $airing...\n") if ($DEBUG);
# We don't use the cache for 'today' incase of any last minute programming changes
#
# but if cachetime is set, work out if we use the cache or not. (Advanced users only)
if (!exists $dbm_hash{$airing} || $dbm_hash{$airing} eq "$airing|undef")
{
warn("No cache data for $airing, requesting...\n") if ($DEBUG);
$INQ->enqueue($airing);
++$enqueued; # Keep track of how many fetches we do
}
else
{
my $usecache = 1; # default is to use the cache
$usecache = 0 if ($CACHETIME eq 86400 && ($day eq "today" || $day eq "tomorrow")); # anything today is not cached if default cachetime
if ($usecache && $CACHETIME ne 86400)
{
if ($day eq "today" || $day eq "tomorrow")
{
# CACHETIME is non default so more complicated
# so we just need to know if the airing is within our cachetime
# however at this level the aring has just things like "5:30 AM" or "6:00 PM"
# so we need to do some conversions
my $offset = getTimeOffset($region_timezone, $subblocks->[$airingcount]->{date}, $day);
warn("Checking $offset against $CACHETIME\n") if ($DEBUG);
$usecache = 0 if (abs($offset) eq $offset && $CACHETIME > $offset);
}
}
if (!$usecache)
{
warn("Cache Data is within the last $CACHETIME seconds, ignoring cache data for $airing, requesting...[" . $subblocks->[$airingcount]->{date} . "]\n") if ($DEBUG);
$INQ->enqueue($airing);
++$enqueued; # Keep track of how many fetches we do
}
else
{
# we can use the cache...
warn("Using cache for $airing.\n") if ($DEBUG && $day eq "today");
my $data = $dbm_hash{$airing};
warn("Got cache data for $airing.\n") if ($DEBUG);
$thrdret{$airing} = $data;
warn("Wrote cache data for $airing.\n") if ($DEBUG);
}
}
warn("Done $airing...\n") if ($DEBUG);
}
}
for (my $l = 0;$l < $enqueued; ++$l)
{
# At this point all the threads should have all the URLs in the queue and
# will resolve them independently - this means they will not necessarily
# be in the right order when we get them back. That said, because we will
# reuse these threads and queues on each loop we wait here to get back
# all the results before we continue.
my ($airing, $result) = split(/\|/, $OUTQ->dequeue(), 2);
warn("$airing = $result\n") if ($DEBUG);
$thrdret{$airing} = $result;
}
if ($VERBOSE && $enqueued)
{
local $| = 1;
print " ";
$nl++;
}
for (my $blockcount = 0; $blockcount < @$blocks; $blockcount++)
{
my $subblocks = $blocks->[$blockcount]->{shows};
#for (my $airingcount = 0; $airingcount < @$subblocks; $airingcount++)
#{
# my ($airing, $result) = split(/\|/, $OUTQ->dequeue(), 2);
# warn("$airing = $result\n") if ($DEBUG);
# $thrdret{$airing} = $result;
#}
# Here we will have all the returned data in the hash %thrdret with the
# url as the key.
for (my $airingcount = 0; $airingcount < @$subblocks; $airingcount++)
{
my $showdata;
my $airing = $subblocks->[$airingcount]->{id};
if ($thrdret{$airing} eq "FAILED")
{
warn("\nUnable to connect to YourTV for https://www.yourtv.com.au/api/airings/$airing ... skipping (".$res->{code}.")\n");
next;
}
elsif ($thrdret{$airing} eq "ERROR")
{
my $url = "https://www.yourtv.com.au/api/airings/".$airing;
$res = geturl($ua,$url);
if (!$res->is_success)
{
die("(getchannels) Unable to connect to YourTV. (".$res->{code}.")\n");
}
else
{
$thrdret{$airing} = $res->content;
}
}
elsif ($thrdret{$airing} eq "UNKNOWN")
{
die("FATAL: Unable to connect to YourTV for https://www.yourtv.com.au/api/airings/$airing ... (Unknown Error!)\n");
}
eval
{
$showdata = JSON->new->relaxed(1)->allow_nonref(1)->decode($thrdret{$airing});
1;
};
if (defined($showdata))
{
$guidedata[$showcount]->{id} = $id;
$guidedata[$showcount]->{airing_tmp} = $airing;
$guidedata[$showcount]->{desc} = $showdata->{synopsis};
$guidedata[$showcount]->{subtitle} = $showdata->{episodeTitle};
$guidedata[$showcount]->{start} = toLocalTimeString($showdata->{date},$region_timezone);
$guidedata[$showcount]->{stop} = addTime($showdata->{duration},$guidedata[$showcount]->{start});
$guidedata[$showcount]->{start} =~ s/[-T:]//g;
$guidedata[$showcount]->{start} =~ s/\+/ \+/g;
$guidedata[$showcount]->{stop} =~ s/[-T:]//g;
$guidedata[$showcount]->{stop} =~ s/\+/ \+/g;
$guidedata[$showcount]->{channel} = $showdata->{service}->{description};
$guidedata[$showcount]->{title} = $showdata->{title};
$guidedata[$showcount]->{rating} = $showdata->{classification};
if ($showdata->{highDefinition})
{
$guidedata[$showcount]->{quality} = "HDTV";
}
else
{
$guidedata[$showcount]->{quality} = "SDTV";
}
foreach my $hdtvc (@hdtvchannels)
{
if ($guidedata[$showcount]->{id} =~ /$hdtvc\./)
{
$guidedata[$showcount]->{quality} = "HDTV";
}
}
if (defined($showdata->{program}->{image}))
{
$guidedata[$showcount]->{url} = $showdata->{program}->{image};
}
else
{
$guidedata[$showcount]->{url} = getFVShowIcon($chandata->[$channelcount]->{number},$guidedata[$showcount]->{title},$guidedata[$showcount]->{start},$guidedata[$showcount]->{stop});
}
push(@{$guidedata[$showcount]->{category}}, $showdata->{genre}->{name});
push(@{$guidedata[$showcount]->{category}}, $showdata->{subGenre}->{name}) if (defined($showdata->{subGenre}->{name}));
# program types as defined by yourtv $showdata->{programType}->{id}
# 1 Television movie
# 2 Cinema movie
# 3 Mini series
# 4 Series no episodes
# 5 Series with episodes
# 6 Serial
# 8 Limited series
# 9 Special
my $tmpseries = toLocalTimeString($showdata->{date},$region_timezone);
my ($episodeYear, $episodeMonth, $episodeDay, $episodeHour, $episodeMinute) = $tmpseries =~ /(\d+)-(\d+)-(\d+)T(\d+):(\d+).*/;#S$1E$2$3$4$5/;
if (defined($showdata->{programType}->{id}))
{
my $programtype = $showdata->{programType}->{id};
if ($programtype eq "1")
{
push(@{$guidedata[$showcount]->{category}}, $showdata->{programType}->{name});
}
elsif ($programtype eq "2")
{
push(@{$guidedata[$showcount]->{category}}, $showdata->{programType}->{name});
}
elsif ($programtype eq "3")
{
push(@{$guidedata[$showcount]->{category}}, $showdata->{programType}->{name});
$guidedata[$showcount]->{episode} = $showdata->{episodeNumber} if (defined($showdata->{episodeNumber}));
$guidedata[$showcount]->{season} = "1";
}
elsif ($programtype eq "4")
{
$guidedata[$showcount]->{premiere} = "1";
$guidedata[$showcount]->{originalairdate} = $episodeYear."-".$episodeMonth."-".$episodeDay." ".$episodeHour.":".$episodeMinute.":00";#"$1-$2-$3 $4:$5:00";
if (defined($showdata->{episodeNumber}))
{
$guidedata[$showcount]->{episode} = $showdata->{episodeNumber};
}
else
{
$guidedata[$showcount]->{episode} = sprintf("%0.2d%0.2d",$episodeMonth,$episodeDay);
}
if (defined($showdata->{seriesNumber}))
{
$guidedata[$showcount]->{season} = $showdata->{seriesNumber};
}
else
{
$guidedata[$showcount]->{season} = $episodeYear;
}
}
elsif ($programtype eq "5")
{
if (defined($showdata->{seriesNumber}))
{
$guidedata[$showcount]->{season} = $showdata->{seriesNumber};
}
else
{
$guidedata[$showcount]->{season} = $episodeYear;
}
if (defined($showdata->{episodeNumber}))
{
$guidedata[$showcount]->{episode} = $showdata->{episodeNumber};
}
else
{
$guidedata[$showcount]->{episode} = sprintf("%0.2d%0.2d",$episodeMonth,$episodeDay);
}
}
elsif ($programtype eq "6")
{
if (defined($showdata->{seriesNumber}))
{
$guidedata[$showcount]->{season} = $showdata->{seriesNumber};
}
else
{
$guidedata[$showcount]->{season} = $episodeYear;
}
if (defined($showdata->{episodeNumber}))
{
$guidedata[$showcount]->{episode} = $showdata->{episodeNumber};
}
else
{
$guidedata[$showcount]->{episode} = sprintf("%0.2d%0.2d",$episodeMonth,$episodeDay);
}
}
elsif ($programtype eq "8")
{
if (defined($showdata->{seriesNumber}))
{
$guidedata[$showcount]->{season} = $showdata->{seriesNumber};
}
else
{
$guidedata[$showcount]->{season} = $episodeYear;
}
if (defined($showdata->{episodeNumber}))
{
$guidedata[$showcount]->{episode} = $showdata->{episodeNumber};
}
else
{
$guidedata[$showcount]->{episode} = sprintf("%0.2d%0.2d",$episodeMonth,$episodeDay);
}
}
elsif ($programtype eq "9")
{
$guidedata[$showcount]->{season} = $episodeYear;
$guidedata[$showcount]->{episode} = sprintf("%0.2d%0.2d",$episodeMonth,$episodeDay);
}
}
if (defined($showdata->{repeat} ) )
{
$guidedata[$showcount]->{previouslyshown} = 1; #"$episodeYear-$episodeMonth-$episodeDay";#"$1-$2-$3";
}
if (defined($showdata->{program}->{imdbId} ) )
{
$guidedata[$showcount]->{imdb} = $showdata->{program}->{imdbId};
}
if ($channelIsDuped)
{
foreach my $dchan (sort keys %DUPLICATE_CHANNELS)
{
next if ($DUPLICATE_CHANNELS{$dchan} ne $channelIsDuped);
my $did = $dchan . ".yourtv.com.au";
$DUPEGUIDEDATA[$DUPES_COUNT] = clone($guidedata[$showcount]);
$DUPEGUIDEDATA[$DUPES_COUNT]->{id} = $did;
$DUPEGUIDEDATA[$DUPES_COUNT]->{channel} = $did;
$DUPEGUIDEDATA[$DUPES_COUNT]->{quality} = "SDTV";
foreach my $hdtvc (@hdtvchannels)
{
if ($DUPEGUIDEDATA[$DUPES_COUNT]->{id} =~ /$hdtvc\./)
{
$DUPEGUIDEDATA[$DUPES_COUNT]->{quality} = "HDTV";
}
}
warn("Duplicated guide data for show entry $showcount -> $did $DUPES_COUNT ($guidedata[$showcount] -> $DUPEGUIDEDATA[$DUPES_COUNT]) ...\n") if ($DEBUG);
++$DUPES_COUNT;
}
}
$showcount++;
}
}
}
}
}
}
}
warn("\nProcessed a total of $showcount shows ...\n") if ($VERBOSE);
return @guidedata;
}
sub printchannels
{
my ($XMLRef) = @_;
foreach my $channel (@CHANNELDATA, @DUPECHANDATA)
{
$XML->startTag('channel', 'id' => $channel->{id});
$XML->dataElement('display-name', $channel->{name});
$XML->dataElement('lcn', $channel->{lcn});
$XML->emptyTag('icon', 'src' => $channel->{icon}) if (defined($channel->{icon}));
$XML->endTag('channel');
}
return;
}
sub printepg
{
my ($XMLRef) = @_;
foreach my $items (@GUIDEDATA, @DUPEGUIDEDATA)
{
my $movie = 0;
my $originalairdate = "";
${$XMLRef}->startTag('programme', 'start' => "$items->{start}", 'stop' => "$items->{stop}", 'channel' => "$items->{id}");
${$XMLRef}->dataElement('title', sanitizeText($items->{title}));
${$XMLRef}->dataElement('sub-title', sanitizeText($items->{subtitle})) if (defined($items->{subtitle}));
${$XMLRef}->dataElement('desc', sanitizeText($items->{desc})) if (defined($items->{desc}));
foreach my $category (@{$items->{category}}) {
${$XMLRef}->dataElement('category', sanitizeText($category));
}
my $uri = $items->{url};
if (defined $uri)
{
$uri =~ s/\s/\%20/g;
${$XMLRef}->emptyTag('icon', 'src' => $uri);
}
if (defined($items->{season}) && defined($items->{episode}))
{
my $episodeseries = sprintf("S%0.2dE%0.2d",$items->{season}, $items->{episode});
${$XMLRef}->dataElement('episode-num', $episodeseries, 'system' => 'SxxExx');
my $series = $items->{season} - 1;
my $episode = $items->{episode} - 1;
$series = 0 if ($series < 0);