forked from garybuhrmaster/tv_grab_zz_sdjson_sqlite
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtv_grab_az_sdjson_sqlite
executable file
·9893 lines (8645 loc) · 372 KB
/
tv_grab_az_sdjson_sqlite
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 -w
#
# tv_grab_az_sdjson_sqlite
#
# Copyright (c) 2016, 2017 Gary Buhrmaster <[email protected]>
#
# This code is distributed under the GNU General Public License v2 (GPLv2)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 2 as published by the Free Software Foundation.
#
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
#
# For extended help information run
# tv_grab_az_sdjson_sqlite --info
#
#
# NOTE - Automated XMLTV testing will report failure since Schedules Direct
# requires an account for downloading of data. The automated testing
# likely needs a way (a new capability?) that indicates that the grabber
# cannot be tested. In addition, for many real world lineups, we again
# fall into the different interpretations of the terms "station" and
# "channel". Unlike how XMLTV uses the term, we consider a "station"
# as a programming entity which has a schedule of programs. A "channel"
# is a technical means of delivering a particular "station". XMLTV
# uses channel when they mean station. For many lineups (for example,
# a cable/satellite provider, or OTA repeaters) the exact same "station"
# is on multiple "channels", which results in "duplicate" messages from
# the automated testing tool which presumes that the channels need not
# be duplicated. In an ideal world, that might be true, but as the
# channel (in XMLTV terms) is also overloaded with the display name
# which is used for automated discovery and updates in PVRs, we report
# each "channel" seperately, even when the "station" is the same.
#
#
# Version history:
#
# 2017/11/30 - 1.35 - Populate thetvdb episode-num.
# 2017/10/11 - 1.34 - download artwork.
# 2018/11/10 - 1.60 - include subscription info in additional paths
# 2018/11/03 - 1.59 - additional protection against bad data
# 2018/10/30 - 1.58 - initial protections against bad data
# 2018/09/15 - 1.57 - support lineup selection by transmitter
# 2018/09/15 - 1.56 - enhance obtainAvailble to use uri
# 2018/09/14 - 1.55 - support explicit lineup name for --manage-lineup add
# 2018/09/13 - 1.54 - revise previously-shown (new is new and no supplemental)
# 2018/09/05 - 1.53 - multi-lineup plumbing - configure
# 2018/09/05 - 1.52 - add initial Schedules Direct "IPTV" transport
# 2018/09/05 - 1.51 - multi-lineup plumbing - getLineup (v2)
# 2018/09/05 - 1.50 - provide proper bind data types
# 2018/09/04 - 1.49 - support short-name in getLineup for other types
# 2018/09/03 - 1.48 - use available channum
# 2018/09/02 - 1.47 - remove dead code
# 2018/09/02 - 1.46 - fix grammer
# 2018/08/30 - 1.45 - multi-lineup plumbing - mainline code
# 2018/08/30 - 1.44 - multi-lineup plumbing - getLineup
# 2018/08/30 - 1.43 - multi-lineup plumbing - SD_isLineupFetchRequired
# 2018/08/30 - 1.42 - multi-lineup plumbing - lineupValidate
# 2018/08/30 - 1.41 - multi-lineup plumbing - channelWriter
# 2018/08/29 - 1.40 - multi-lineup plumbing - SD_cleanLineups
# 2018/08/29 - 1.39 - multi-lineup plumbing - canonical lineup details
# 2018/08/25 - 1.38 - remove dead code
# 2018/08/25 - 1.37 - minor whitespace adjustments
# 2018/06/17 - 1.36 - handle deleted lineups not having description
# 2018/02/03 - 1.35 - remove lang from channel display-name
# 2018/02/03 - 1.34 - remove use warning nonfatal experimental in package
# 2017/07/21 - 1.33 - dtd compliance. Only actors can have roles
# 2017/06/19 - 1.32 - derive category from showtype
# 2017/04/20 - 1.31 - provide fixup support
# 2017/04/18 - 1.30 - fix typo (in version history)
# 2017/04/06 - 1.29 - add supplemental SHow data to EPisodes
# 2017/04/02 - 1.28 - misc. code cleanup
# 2017/03/26 - 1.27 - misc. code cleanup
# 2017/03/21 - 1.26 - fix sth typos
# 2017/03/21 - 1.25 - fix trailing whitespace
# 2016/09/10 - 1.24 - change (improve) cast mapping
# 2016/09/10 - 1.23 - remove use warning nonfatal experimental decl
# 2016/08/25 - 1.22 - no warning messages for malformed SD data if quiet
# 2016/08/25 - 1.21 - additional error checking of SD data
# 2016/08/24 - 1.20 - correct sql error reporting
# 2016/08/03 - 1.19 - reflect multinational capability (and fix docs)
# 2016/08/03 - 1.18 - rename grabber based on xmltv agreed convention
# 2016/07/30 - 1.17 - don't report radio stations as tvshow category
# 2016/07/30 - 1.16 - eliminate XML:Writer validation for performance
# 2016/07/17 - 1.15 - use Digest::SHA rather than Digest::SHA1
# 2016/06/07 - 1.14 - support multipart episodes
# 2016/06/07 - 1.13 - improved season/episode value checks
# 2016/05/28 - 1.12 - add support for episodeImage
# 2016/05/26 - 1.11 - use program duration as length
# 2016/05/26 - 1.10 - hack for tv_find_grabbers source parsing of desc
# 2016/05/25 - 1.9 - Support total seasons, and more robust validation
# 2016/05/24 - 1.8 - retry limit updates and get-lineup improvements
# 2016/05/21 - 1.7 - protect against bad json returned by server
# 2016/05/21 - 1.6 - correct (mis)use of global variable in package
# 2016/05/20 - 1.5 - minor output formatting improvements for xmltv_ns
# 2016/05/19 - 1.4 - correct totalEpisodes output
# 2016/05/19 - 1.3 - add support for totalEpisodes metadata
# 2016/04/28 - 1.2 - update version number in history and output
# 2016/04/23 - 1.1 - Minor update for improved(?) category ordering
# 2016/04/01 - 1.0 - First release
#
eval 'exec /usr/bin/perl -w -S $0 ${1+"$@"}' if 0; # not running under some shell
require 5.016;
use feature ':5.16';
use strict;
use warnings FATAL => 'all';
use warnings NONFATAL => qw(exec recursion internal malloc newline deprecated portable);
no warnings 'once';
use utf8;
STDERR->autoflush(1); # Autoflush STDERR
use XMLTV 0.005067;
use XMLTV::Options qw/ParseOptions/;
use XMLTV::Configure::Writer;
use XMLTV::Configure qw/LoadConfig SaveConfig/;
use XMLTV::Ask;
use XML::Writer;
use Encode qw/decode encode/;
use JSON;
use Digest::MD5 qw(md5_hex);
use Digest::SHA qw(sha1 sha1_hex sha1_base64);
use File::Basename;
use File::Which;
use File::HomeDir;
use File::Path qw(make_path);
use File::Spec::Functions qw(catdir tmpdir);
use DateTime;
use DateTime::TimeZone;
use DateTime::Format::ISO8601;
use DateTime::Format::SQLite;
use DateTime::Format::Strptime;
use HTML::Entities;
use POSIX qw(strftime);
use List::MoreUtils qw(natatime);
use List::Util qw/min max/;
use DBI;
use DBI qw(:sql_types);
use DBD::SQLite;
use Scalar::Util qw/looks_like_number/;
use Storable qw(dclone);
use Data::Dumper;
my $RFC2838_COMPLIANT = 1; # RFC2838 compliant station ids, which makes XMLTV
# validate even though the docs say "SHOULD" not "MUST"
# Has to be a "CVS" Id string for XMLTV::Options.
my $SCRIPT_VERSION = '$Id: tv_grab_az_sdjson_sqlite,v 1.57 3976d0 2019/06/22 01:19:00 gtb Exp ed $';
my $SCRIPT_URL = 'https://github.com/azlm8t/tv_grab_zz_sdjson_sqlite';
my $SCRIPT_NAME = basename("$0");
my $SCRIPT_NAME_DIR = dirname("$0");
my $SCRIPT_DB_VERSION = 4; # Used for script/db updates (see DB_open_global)
my $SD_DESC = 'Schedules Direct';
my $SD_SITEURL = 'https://www.schedulesdirect.org';
my $SD_COMMENT = 'Note: This data has been downloaded from Schedules Direct, ' .
'and use of the data is restricted by the subscriber agreement ' .
'to non-commercial use with open source projects. Refer to ' .
'the Schedules Direct subscriber agreement for more information';
my $SD_SCHEDULE_HASH_CHUNK = 250; # Request stations schedules hash in chunk sizes
my $SD_SCHEDULE_CHUNK = 1000; # Request stations schedules in chunk sizes
my $SD_PROGRAM_CHUNK = 4000; # Request program data in chunk sizes
my $SD_ARTWORK_CHUNK = 500; # Request artwork data in chunk sizes
my $JSON = JSON->new()->shrink(1)->utf8(1);
my $SD = SchedulesDirect->new();
my $DBH; # DataBase Handle
my $nowDateTime = DateTime->now( time_zone => 'UTC' );
my $nowDateTimeSQLite = DateTime::Format::SQLite->format_datetime($nowDateTime);
my $GRABBER_FIXUPS = {}; # Grabber fixups for broken applications
foreach my $fixup(split(':', $ENV{'TV_GRAB_TARGET_APPLICATION_FIXUPS'} || ''))
{
$GRABBER_FIXUPS->{$fixup} = undef;
}
my $quiet = 0;
my $debug = 0;
my $download = 1;
my $num_prog_from_cache = 0;
my $num_prog_details_not_from_cache = 0;
my $num_prog_details_total = 0;
my $len_prog_not_printed = 0;
my $num_imdb_lookups_other = 0;
my $num_imdb_lookups_movie = 0;
my $num_imdb_lookups_from_cache = 0;
my $num_imdb_lookups_movie_success = 0;
my $num_imdb_lookups_other_success = 0;
my $passwordHash;
my $opt;
my $conf;
my $param;
my %num_progs_per_channel; # Map channel id to number of programmes on that channel.
my %channel_names; # Map channel id to canonical name.
my %catmap_major = (
movie => "\N{CLAPPER BOARD}",
news => "\N{NEWSPAPER}",
radio => "\N{RADIO}",
series => "\N{TELEVISION}",
sports => "\N{SPORTS MEDAL}",
'sports non-event' => "\N{SPORTS MEDAL}",
);
my %catmap_minor = (
action => "\N{COLLISION SYMBOL}",
'adults only' => "\N{NO ONE UNDER EIGHTEEN SYMBOL}",
adventure => "\N{BOW AND ARROW}",
animals => "\N{PAW PRINTS}",
animated => "\N{PENCIL}",
art => "\N{ARTIST PALETTE}",
auction => "\N{MONEY WITH WINGS}",
'auto racing' => "\N{RACING CAR}",
auto => "\N{AUTOMOBILE}",
baseball => "\N{BASEBALL}",
basketball => "\N{BASKETBALL AND HOOP}",
#boxing => "\N{BOXING GLOVE}",
'bus./financial' => "\N{CHART WITH UPWARDS TREND}",
children => "\N{BABY}",
comedy => "\N{FACE WITH TEARS OF JOY}",
computers => "\N{PERSONAL COMPUTER}",
community => "\N{FAMILY}",
cooking => "\N{COOKING}",
'crime drama' => "\N{POLICE OFFICER}",
dance => "\N{DANCER}",
educational => "\N{GRADUATION CAP}",
fantasy => "\N{UNICORN FACE}",
fashion => "\N{HIGH-HEELED SHOE}",
'figure skating' => "\N{ICE SKATE}",
fishing => "\N{FISHING POLE AND FISH}",
football => "\N{AMERICAN FOOTBALL}", # American Football (not soccer)
'game show' => "\N{GAME DIE}",
#gymnastics => "\N{PERSON DOING CARTWHEEL}",
history => "\N{CASTLE}",
holiday => "\N{AIRPLANE}",
'home improvement' => "\N{CONSTRUCTION WORKER}",
horror => "\N{SKULL}",
horse => "\N{HORSE FACE}",
'house/garden' => "\N{HOUSE WITH GARDEN}",
interview => "\N{SPEAKING HEAD IN SILHOUETTE}",
law => "\N{POLICE OFFICER}",
#'martial arts' => "\N{MARTIAL ARTS UNIFORM}",
medical => "\N{AMBULANCE}",
military => "\N{MILITARY MEDAL}",
miniseries => "\N{LINK SYMBOL}",
#'mixed martial arts' => "\N{MARTIAL ARTS UNIFORM}",
motorcycle => "\N{RACING MOTORCYCLE}",
music => "\N{MUSICAL NOTE}",
musical => "\N{MUSICAL NOTE}",
mystery => "\N{LEFT-POINTING MAGNIFYING GLASS}",
nature => "\N{ELEPHANT}",
paranormal => "\N{GHOST}",
poker => "\N{BLACK SPADE SUIT}",
politics => "\N{BALLOT BOX WITH BALLOT}",
#'pro wrestling' => "\N{WRESTLERS}",
#reality => "\N{SELFIE}",
religious => "\N{PLACE OF WORSHIP}",
romance => "\N{BEATING HEART}",
'romantic comedy' => "\N{BEATING HEART}",
'science fiction' => "\N{EXTRATERRESTRIAL ALIEN}",
science => "\N{MICROSCOPE}",
#shopping => "\N{SHOPPING TROLLEY}",
sitcom=> "\N{GRINNING FACE}",
skiing => "\N{SKIER}",
soap => "\N{COUCH AND LAMP}",
soccer => "\N{SOCCER BALL}",
'sports talk' => "\N{SPEAKING HEAD IN SILHOUETTE}",
spy=> "\N{SLEUTH OR SPY}",
standup => "\N{MICROPHONE}",
swimming => "\N{SWIMMER}",
talk => "\N{SPEAKING HEAD IN SILHOUETTE}",
technology => "\N{PERSONAL COMPUTER}",
tennis => "\N{TENNIS RACQUET AND BALL}",
theater => "\N{PERFORMING ARTS}",
travel => "\N{AIRPLANE}",
war => "\N{MILITARY MEDAL}",
weather => "\N{SUN BEHIND CLOUD}",
weightlifting => "\N{WEIGHT LIFTER}",
western => "\N{CACTUS}",
);
( $opt, $conf ) = ParseOptions
(
{
grabber_name => "$SCRIPT_NAME",
capabilities => [qw/baseline manualconfig preferredmethod lineups apiconfig/],
stage_sub => \&configureGrabber,
listchannels_sub => \&listChannels,
list_lineups_sub => \&listLineups,
get_lineup_sub => \&getLineup,
load_old_config_sub => \&loadOldConfig,
preferredmethod => 'allatonce',
version => "$SCRIPT_VERSION",
description => 'Multinational (Schedules Direct JSON web services with SQLite DB and local segment caching)',
extra_options => [qw/manage-lineups
force-download
force-vacuum|vacuum-force
download-only
no-download
no-prune
no-channel-output
merge-split=n
artwork-max-width=n
channel-regex=s
channel-exclude-regex=s
channel-short-days=n
channel-short-days-exclude-regex=s
output-bad-channel-details=s
use-category-for-keyword!
update-category-with-grabber!
update-description-with-all!
update-description-with-credits!
update-description-with-categories!
update-description-with-year!
update-description-with-season-episode!
update-description-with-icons!
update-description-with-icons-basic!
update-description-with-icons-entity!
update-description-with-premiere!
update-description-with-live!
update-description-with-advisory!
update-description-with-artwork!
update-description-with-stars!
update-description-with-stars-color|update-description-with-stars-colour=s
update-description-with-rating!
update-description-with-title!
update-previously-shown-with-year!
use-imdb!
imdb-db-type=s
imdb-db=s
imdb-user=s
imdb-pass=s
imdb-dir=s
imdb-download=s
prefer-imdb-rating!
content-rating-order=s
passwordhash=s
cache-driver=s
cache-namespace-extra=s
cache-expiry=s
cache-ignore-unchanged-programmes!
cache-purge-expired!
cache-force-clear!
cache-root-dir=s
cache-compression-threshold=n
vacuum-frequency=n
benchmark/],
defaults => { days => 30 },
}
);
$debug = $opt->{'debug'};
$quiet = $opt->{'quiet'};
$passwordHash = $opt->{'passwordhash'};
my $channelRegex = $opt->{'channel-regex'};
my $channelExcludeRegex = $opt->{'channel-exclude-regex'};
$SD->Debug(1) if ($debug);
#
# Special case for managing lineups
#
# This should (possibly) be done at the Schedules Direct
# site itself (as it is done now), or a seperate program,
# but as of now, this is it.
#
if ($opt->{'manage-lineups'})
{
manageLineups();
exit(0);
}
#
# Verify we have what we need to proceed and
# perform a few checks for things we do not
# support
#
configValidate($conf, $opt);
my $use_benchmark = use_benchmark();
if ($opt->{'offset'} < 0)
{
# Note: While it is (in theory) possible to
# support an offset of -1, it requires a
# bit of hoop jumping to get that data from
# Schedules Direct, and it is not really
# considered to be worth it for the edge
# cases that might exist. The data may be
# in the database in some cases.
print (STDERR "Offset value may not be less than 0\n");
exit(1);
}
if ($opt->{'days'} < 0)
{
print (STDERR "Day value may not be less than 0\n");
exit(1);
}
if (!defined(eval {require JSON::XS}))
{
print (STDERR "WARNING: Perl module JSON::XS not installed. JSON encode/decode performance will be poor.\n") if (!$quiet);
}
$download = 0 if ($opt->{'no-download'});
#
# Various sql and statement handles for accessing our database
#
my $sql;
my $sql0;
my $sql1;
my $sql2;
my $sql3;
my $sql4;
my $sth;
my $sth0;
my $sth1;
my $sth2;
my $sth3;
my $sth4;
#
# Open database
#
print (STDERR "Opening the local database\n") if (!$quiet);
DB_open_global($conf->{'database'}->[0]);
my $imdb;
if (get_option("use-imdb")) {
my $dbtype = get_option('imdb-db-type') // "mysql";
my $db = get_option('imdb-db') // "imdb"; # Or use imdb@localhost, etc.
my $user = get_option('imdb-user') // "imdb";
my $pass = get_option('imdb-pass') // "imdb";
my $dbi = "DBI:$dbtype:$db";
$imdb = TVHIMDB->new(dbi => $dbi, user=>$user, pass=>$pass);
my $dir = get_option('imdb-dir') // "/var/db/mysql_secure";
my $dl = get_option("imdb-download");
$imdb->download($dir, $dl) if $dl;
$imdb->import($dir);
}
#
# Provide the ability to force a (mostly) complete download
# for all data by deleting most of the data in the database,
# making this (in effect) a "first download".
#
if ($opt->{'force-download'})
{
print (STDERR " clearing existing database to force full download\n") if (!$quiet);
DB_clean();
}
check_cache_clear();
#
# If we are not downloading data, we need to verify
# that the lineup is in the database now.
#
if (!$download)
{
lineupValidate($conf->{'lineup'});
goto skipDownload;
}
#
# Login and perform the usual checks
#
print (STDERR "Obtaining authentication token for Schedules Direct\n") if (!$quiet);
SD_login();
my $expiry = $SD->accountExpiry;
if (!defined($expiry))
{
print (STDERR "Unable to obtain the account expiration date: " . $SD->ErrorString . "\n");
exit(1);
}
# lastDateUpdated (from SD status) is across all lineups.
my $dataLastUpdated = $SD->obtainDataLastUpdated;
if (!defined($dataLastUpdated))
{
print (STDERR "Unable to obtain the Schedules Direct data last updated: " . $SD->ErrorString . "\n");
exit(1);
}
my $expiryDateTime = DateTime::Format::ISO8601->parse_datetime($expiry);
my $dataLastUpdatedDateTime = DateTime::Format::ISO8601->parse_datetime($dataLastUpdated);
print (STDERR " Schedules Direct account expires on " . $expiryDateTime . "\n") if (!$quiet);
print (STDERR " Schedules Direct data last updated on " . $dataLastUpdatedDateTime . "\n") if (!$quiet);
SD_cleanLineups();
#
# Start the download process
#
print (STDERR "Downloading data from Schedules Direct\n") if (!$quiet);
# We used to fetch unconditionally here, now it's done
# based on $download to be compatible with list-channels and
# list-lineups.
my $fetchLineupRequired = lineupFetchAndValidate($conf);
my $t_downloadstart = Benchmark->new if $use_benchmark;
# We do this sequentially for the moment since we are
# checking for lineups that are out of date or never
# downloaded and then figuring out schedule hashes.
for my $lineup (@{$conf->{lineup}}) {
print STDERR "Downloading data for $lineup\n" unless $quiet;
#
# We can skip downloading station schedules if our data is current
#
$sql = 'select 1 from lineups l1 where (l1.downloaded <= ? and l1.lineup in ( ' . join(', ', ('?') x scalar(@{$conf->{'lineup'}})) . ' )) union select 1 where not exists (select 1 from lineups l2 where l2.lineup in ( ' . join(', ', ('?') x scalar(@{$conf->{'lineup'}})) . ' ))';
$sth = $DBH->prepare_cached($sql);
if (!defined($sth))
{
print (STDERR "Unexpected error when preparing statement ($sql): " . $DBH->errstr . "\n");
exit(1);
}
$param = 1;
$sth->bind_param( $param, DateTime::Format::SQLite->format_datetime($dataLastUpdatedDateTime), SQL_DATETIME );
$param++;
for (my $i=0; $i < scalar(@{$conf->{'lineup'}}); $i++)
{
$sth->bind_param( $param, @{$conf->{'lineup'}}[$i], SQL_VARCHAR);
$param++;
}
for (my $i=0; $i < scalar(@{$conf->{'lineup'}}); $i++)
{
$sth->bind_param( $param, @{$conf->{'lineup'}}[$i], SQL_VARCHAR);
$param++;
}
$sth->execute();
if ($sth->err())
{
print (STDERR "Unexpected error when executing statement ($sql): " . $sth->errstr . "\n");
exit(1)
}
my $fetchStationSchedulesRequired = $sth->fetchrow_array() || 0;;
$sth->finish();
if ((!$fetchStationSchedulesRequired) && (!$fetchLineupRequired))
{
print (STDERR " not downloading station schedule hashes for $lineup (data current)\n") if (!$quiet);
}
else
{
#
# Obtain the current schedule hash values for our
# lineup stations and feed to our DB
#
# Note that there is no (substantial) advantage in
# requesting only the days we will be processing
# as tests have shown that Schedules Direct takes
# about the same time to return all vs just one,
# and it complicates matters to request ranges
# and deal with potential errors due to out of
# range issues.
#
$sql = 'select distinct stations.station from stations as stations where stations.station in (select distinct channels.station from channels as channels where channels.lineup in ( ' . join(', ', ('?') x scalar(@{$conf->{'lineup'}})) . ' ) and channels.selected = 1)';
$sth = $DBH->prepare_cached($sql);
if (!defined($sth))
{
print (STDERR "Unexpected error when preparing statement ($sql): " . $DBH->errstr . "\n");
exit(1);
}
$param = 1;
for (my $i=0; $i < scalar(@{$conf->{'lineup'}}); $i++)
{
$sth->bind_param( $param, @{$conf->{'lineup'}}[$i], SQL_VARCHAR);
$param++;
}
$sth->execute();
if ($sth->err())
{
print (STDERR "Unexpected error when executing statement ($sql): " . $sth->errstr . "\n");
exit(1)
}
$sth->bind_col( 1, undef, SQL_VARCHAR );
my $stationsSchedulesHashList = $sth->fetchall_arrayref([0]);
$sth->finish();
print (STDERR " downloading station schedule hashes for " . scalar(@{$stationsSchedulesHashList}) . " stations\n") if (!$quiet);
$sql = "replace into stations_schedules_hash (station, day, hash, details) values ( ?, ?, ?, ?)";
$sth = $DBH->prepare_cached($sql);
if (!defined($sth))
{
print (STDERR "Unexpected error when preparing statement ($sql): " . $DBH->errstr . "\n");
exit(1);
}
my $stationsSchedulesHashIter;
$stationsSchedulesHashIter = natatime $SD_SCHEDULE_HASH_CHUNK, @{$stationsSchedulesHashList};
while(my @chunk = $stationsSchedulesHashIter->())
{
print (STDERR " downloading schedule hashes for " . scalar(@chunk) . " stations in this chunk\n") if ((!$quiet) && ((scalar(@chunk) != scalar(@{$stationsSchedulesHashList}))));
my $stationsSchedulesHashRequest = [];
foreach (@chunk)
{
my $s = {};
$s->{'stationID'} = $_->[0];
push(@{$stationsSchedulesHashRequest}, $s);
}
my $r = $SD->obtainStationsSchedulesHash(@{$stationsSchedulesHashRequest});
if (!defined($r))
{
print (STDERR "Unexpected error when obtaining station schedules hashes: " . $SD->ErrorString() . "\n");
exit(1);
}
if (ref($r) ne 'HASH')
{
print (STDERR "Unexpected return data type " . ref($r) . " when obtaining station schedules hashes.\n");
exit(1);
}
foreach my $station(keys %{$r})
{
if (ref($r->{$station}) ne 'HASH')
{
# print (STDERR "Unexpected return data type " . ref($r->{$station}) . " for station $station while obtaining station schedules hashes\n");
next;
}
foreach my $day(keys %{$r->{$station}})
{
my $s = $r->{$station}->{$day};
# If we have an error code (non-zero) then ignore this hash.
# We get SD error 7030 when there are lineup issues.
next if $s->{code};
my $hash = $s->{'md5'} || '';
my $details = $JSON->utf8->encode($s);
$sth->bind_param( 1, $station, SQL_VARCHAR );
$sth->bind_param( 2, $day, SQL_DATE );
$sth->bind_param( 3, $hash, SQL_VARCHAR );
$sth->bind_param( 4, $details, SQL_VARCHAR );
$sth->execute();
if ($sth->err)
{
print (STDERR "Unexpected error when executing statement ($sql): " . $sth->errstr . "\n");
exit(1);
}
}
}
$DBH->commit();
}
#
# Indicate we have downloaded the data
#
$sql = 'update lineups set downloaded = ? where lineup in ( ' . join(', ', ('?') x scalar(@{$conf->{'lineup'}})) . ' )';
$sth = $DBH->prepare_cached($sql);
if (!defined($sth))
{
print (STDERR "Unexpected error when preparing statement ($sql): " . $DBH->errstr . "\n");
exit(1);
}
$param = 1;
$sth->bind_param( $param, $nowDateTimeSQLite, SQL_DATETIME );
$param++;
for (my $i=0; $i < scalar(@{$conf->{'lineup'}}); $i++)
{
$sth->bind_param( $param, @{$conf->{'lineup'}}[$i], SQL_VARCHAR);
$param++;
}
$sth->execute();
if ($sth->err())
{
print (STDERR "Unexpected error when executing statement ($sql): " . $sth->errstr . "\n");
exit(1)
}
$DBH->commit();
}
# We _should_ be able to end the "for each lineup" here
# and then do the remaining fetch across all lineups.
# But, for the moment, we'll do it all per-lineup
# since difference in performance should be negligible
# vs. risk of errors.
####} # for each lineup, download schedule hashes.
#
# Obtain the station schedules for days for which we do
# not have current information based on hash values and
# feed to our DB
#
for (my $retry = 0; $retry < 7; $retry++)
{
my $downloadQueued = 0;
my $startDateTime = DateTime->now(time_zone => 'UTC')->add(days => $opt->{'offset'});
my $endDateTime = DateTime->now(time_zone => 'UTC')->add(days => $opt->{'offset'})->add(days => $opt->{'days'});
#
# Note that we only update schedules (if needed) for days which will
# produce reports for. This may, in some cases, reduce the overheads
#
# Note also that it is important to check for the day to be >= today
# in order to skip retrieving schedules where the hash is obsolete.
# Since Schedules Direct does not update past station_schedules, but
# we keep them around for a bit, our past schedule hash can be invalid,
# but we do not want to force a request for such schedules, which would
# likely fail since Schedules Direct does not make available data
# which older than (about) 24 hours ago.
#
$sql = "select distinct stations_schedules_hash.station, stations_schedules_hash.day from stations_schedules_hash as stations_schedules_hash " .
" left outer join schedules_hash as schedules_hash on stations_schedules_hash.station = schedules_hash.station " .
" AND stations_schedules_hash.day = schedules_hash.day " .
" where (stations_schedules_hash.station in (select distinct channels.station " .
" from channels as channels where channels.lineup in ( " . join(', ', ('?') x scalar(@{$conf->{'lineup'}})) . " ) " .
" and channels.selected = 1)) " .
" AND (schedules_hash.station is NULL OR schedules_hash.hash != stations_schedules_hash.hash) " .
" AND stations_schedules_hash.day >= ? AND stations_schedules_hash.day < ? " .
" ORDER by stations_schedules_hash.station, stations_schedules_hash.day";
$sth = $DBH->prepare_cached($sql);
if (!defined($sth))
{
print (STDERR "Unexpected error when preparing statement ($sql): " . $DBH->errstr . "\n");
exit(1);
}
$param = 1;
for (my $i=0; $i < scalar(@{$conf->{'lineup'}}); $i++)
{
$sth->bind_param( $param, @{$conf->{'lineup'}}[$i], SQL_VARCHAR);
$param++;
}
$sth->bind_param( $param, DateTime::Format::SQLite->format_date($startDateTime), SQL_DATE );
$param++;
$sth->bind_param( $param, DateTime::Format::SQLite->format_date($endDateTime), SQL_DATE );
$param++;
$sth->execute();
if ($sth->err)
{
print (STDERR "Unexpected error when executing statement ($sql): " . $sth->errstr . "\n");
exit(1);
}
$sth->bind_col( 1, undef, SQL_VARCHAR );
$sth->bind_col( 2, undef, SQL_DATE );
my $stationsSchedulesList = $sth->fetchall_arrayref();
$sth->finish();
if (scalar(@{$stationsSchedulesList}) == 0)
{
if ($retry == 0)
{
print (STDERR " not downloading daily schedules (data current)\n") if (!$quiet);
}
last;
}
print (STDERR " downloading " . scalar(@{$stationsSchedulesList}) . " new, updated, or missing daily schedules" . (($retry == 0) ? "" : " (retry $retry)") . "\n") if (!$quiet);
sleep(min(30, (10 * $retry)));
$sql1 = "delete from schedules where station = ? and day = ?";
$sql2 = "replace into schedules (station, day, starttime, duration, program, program_hash, details) values (?, ?, ?, ?, ?, ?, ?)";
$sql3 = "replace into schedules_hash (station, day, hash) values (?, ?, ?)";
$sth1 = $DBH->prepare_cached($sql1);
if (!defined($sth1))
{
print (STDERR "Unexpected error when preparing statement ($sql1): " . $DBH->errstr . "\n");
exit(1);
}
$sth2 = $DBH->prepare_cached($sql2);
if (!defined($sth2))
{
print (STDERR "Unexpected error when preparing statement ($sql2): " . $DBH->errstr . "\n");
exit(1);
}
$sth3 = $DBH->prepare_cached($sql3);
if (!defined($sth3))
{
print (STDERR "Unexpected error when preparing statement ($sql3): " . $DBH->errstr . "\n");
exit(1);
}
$sql4 = "delete from stations where station = ?";
$sth4 = $DBH->prepare_cached($sql4);
if (!defined($sth4))
{
print (STDERR "Unexpected error when preparing statement ($sql4): " . $DBH->errstr . "\n");
exit(1);
}
my $schedulesIter;
$schedulesIter = natatime $SD_SCHEDULE_CHUNK, @{$stationsSchedulesList};
while(my @chunk = $schedulesIter->())
{
print (STDERR " downloading " . scalar(@chunk) . " new, updated, or missing daily schedules in this chunk\n") if ((!$quiet) && ((scalar(@chunk) != scalar(@{$stationsSchedulesList}))));
my $stationsSchedulesRequest = [];
foreach (@chunk)
{
my $s = {};
$s->{'stationID'} = $_->[0];
$s->{'date'} = [$_->[1]];
push (@{$stationsSchedulesRequest}, ($s));
}
my $r = $SD->obtainStationsSchedules(@{$stationsSchedulesRequest});
if (!defined($r))
{
# For some reason, sometimes Schedules Direct returns malformed response (I believe due to
# their optimization for the program array returns, which can result in partial data).
# We will force a retry under those conditions.
print (STDERR "Unexpected error when obtaining station schedules: " . $SD->ErrorString() . " (will retry)\n") if (!$quiet);
$downloadQueued = 1;
next;
}
if (ref($r) ne 'ARRAY')
{
# For some reason, sometimes Schedules Direct returns malformed response (I believe due to
# their optimization for the program array returns, which can result in partial data).
# We will force a retry under those conditions.
print (STDERR "Unexpected error when obtaining station schedules: " . $SD->ErrorString() . " (will retry)\n") if (!$quiet);
$downloadQueued = 1;
next;
}
my %errs;
foreach my $sched(@{$r})
{
my $hash;
my $dayDateTime;
my $sID = $sched->{'stationID'};
my $code = $sched->{'code'} || 0;
if ($code != 0)
{
++$errs{$code};
if ($code == 7100)
{
$downloadQueued = 1;
}
elsif ($code == 7030) {
# SCHEDULE_NOT_IN_LINEUP
#
# We should not normally get these, but we've
# had cases where SD says the station is in your
# configured lineup, then complains that station
# is not in your lineup. Deleting the station
# then causes the next lineup fetch to
# re-populate the station with the same details,
# so is probably pointless, but seems a good idea
# to delete stations we're told don't exist just
# in case.
my $stnid = $sched->{stationID};
if ($stnid) {
print STDERR "......Deleting station $stnid that is no longer in lineup $lineup (SD error 7030)\n" unless $quiet;
$sth4->execute($stnid);
if ($sth4->err) {
print (STDERR "Unexpected error when executing statement ($sql4): " . $sth4->errstr . "\n");
exit(1);
}
}
}
next;
}
my $meta = $sched->{'metadata'};
if (defined($meta))
{
$hash = $meta->{'md5'};
if (defined($meta->{'startDate'}))
{
$dayDateTime = DateTime::Format::ISO8601->parse_datetime($meta->{'startDate'});
}
}
my $programs = $sched->{'programs'};
if ((!defined($hash)) || (!defined($dayDateTime)) || (!defined($programs)))
{
next;
}
$sth1->bind_param( 1, $sID, SQL_VARCHAR );
$sth1->bind_param( 2, DateTime::Format::SQLite->format_date($dayDateTime), SQL_DATE );
$sth1->execute();
if ($sth1->err)
{
print (STDERR "Unexpected error when executing statement ($sql1): " . $sth1->errstr . "\n");
exit(1);
}
foreach my $program(@{$programs})
{
my $pID = $program->{'programID'};
my $airDateTime = $program->{'airDateTime'};
my $duration = $program->{'duration'};
my $phash = $program->{'md5'};
my $details = $JSON->utf8->encode($program);
if ((!defined($duration)) || (!defined($phash)) || (!defined($pID)) || (!defined($airDateTime)))
{
print (STDERR "Unexpected parsing error in program (data malformed) in schedule for $sID on " . $meta->{'startDate'} . ", skipping\n") if (!$quiet);
next;
}
my $starttime = DateTime::Format::ISO8601->parse_datetime($airDateTime);
$sth2->bind_param( 1, $sID, SQL_VARCHAR );
$sth2->bind_param( 2, DateTime::Format::SQLite->format_date($dayDateTime), SQL_DATE );
$sth2->bind_param( 3, DateTime::Format::SQLite->format_datetime($starttime), SQL_DATETIME );
$sth2->bind_param( 4, $duration, SQL_INTEGER );
$sth2->bind_param( 5, $pID, SQL_VARCHAR );
$sth2->bind_param( 6, $phash, SQL_VARCHAR );
$sth2->bind_param( 7, $details, SQL_VARCHAR );
$sth2->execute();
if ($sth2->err)
{
print (STDERR "Unexpected error when executing statement ($sql2): " . $sth2->errstr . "\n");
exit(1);
}
}
$sth3->bind_param( 1, $sID, SQL_VARCHAR );
$sth3->bind_param( 2, DateTime::Format::SQLite->format_date($dayDateTime), SQL_DATE );
$sth3->bind_param( 3, $hash, SQL_VARCHAR );
$sth3->execute();
if ($sth3->err)
{
print (STDERR "Unexpected error when executing statement ($sql3): " . $sth3->errstr . "\n");
exit(1);
}
}
# We had some SCHEDULE_NOT_IN_LINEUP errors (7030) that (from a user POV)
# are invisible and just cause repeated downloads, so ensure we log any errors.
if (!$quiet && scalar keys %errs) {
printf STDERR "...Received %d unique error codes from SD during this chunk\n", scalar keys %errs;
print STDERR "......SD Error Code: $_ Count: $errs{$_}\n" for sort keys %errs;
}
$DBH->commit();
}
# We are done unless one (or more) entities indicate that the server queued the request
last if (!$downloadQueued);
}
my %artworkProgram;
#
# Obtain the program information for programs for which
# we do not have current information based on hash values
# and feed to our DB
#
for (my $retry = 0; $retry < 7; $retry++)
{
my $downloadQueued = 0;
my $startDateTime = DateTime->now(time_zone => 'UTC')->add(days => $opt->{'offset'});
my $endDateTime = DateTime->now(time_zone => 'UTC')->add(days => $opt->{'offset'})->add(days => $opt->{'days'});
#
# Note that we only update programs (if needed) for days which will
# produce reports for. This may, in some cases, reduce the overheads
#
# Note also that it is important to check for the day to be >= today
# in order to skip retrieving programs where the program hash is
# obsolete. Since Schedules Direct does not update past schedules,
# but we keep then around for a bit, our past program hash can
# be invalid, but we do not want to request such programs (since