This file is indexed.

/usr/bin/tv_grab_sd_json is in xmltv-util 0.5.69-1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
#!/usr/bin/perl -w

my $grabber_cvs_id = '$Id: tv_grab_sd_json,v 1.23 2017/01/22 20:38:18 rmeden Exp $';

=head1 NAME

tv_grab_sd_json - Grab TV listings from Schedules Direct SD-JSON service.

=head1 SYNOPSIS

tv_grab_sd_json --help

tv_grab_sd_json --info

tv_grab_sd_json --version

tv_grab_sd_json --capabilities

tv_grab_sd_json --description


tv_grab_sd_json [--config-file FILE]
                [--days N] [--offset N]
                [--output FILE] [--quiet] [--debug]

tv_grab_sd_json --configure [--config-file FILE]

=head1 DESCRIPTION

This is an XMLTV grabber for the Schedules Direct
(http://www.schedulesdirect.org) JSON API.

=head1 CONFIGURATION

Run tv_grab_sd_json with the --configure option to create a config file.

MythTV does not use the default XMLTV config file path. If using MythTV you
should also specify the config file such as:

    tv_grab_sd_json --configure --config-file ~/.mythtv/source_name.xmltv

Doing the XMLTV config from within the MythTV GUI seems very flaky so you
are probably better off configuring from the command line.

=head1 AUTHOR

Kevin Groeneveld (kgroeneveld at gmail dot com)

=cut

use strict;
use XMLTV;
use XMLTV::Options qw(ParseOptions);
use XMLTV::Configure::Writer;
use XMLTV::Ask;
use Cwd;
use Storable;
use LWP::UserAgent;
use JSON;
use Digest::SHA qw(sha1_hex);
use DateTime;
use Scalar::Util qw(looks_like_number);
use Try::Tiny;
use Data::Dumper;

my $grabber_name;
my $grabber_version;

if($grabber_cvs_id =~ m!\$Id: ([^,]+),v (\S+) ([0-9/: -]+) !) {
	$grabber_name = $1;
	$grabber_version = "$2 $3";
}
else {
	$grabber_name = 'tv_grab_sd_json';
    $grabber_version = '0.1';
}

# The XMLTV::Writer docs only indicate you need to set 'encoding'. However,
# this value does not get passed to the underlying XML::Writer object. Unless
# 'ENCODING' is also specified XML::Writer does not actually encode the data!
my %w_args = (
	'encoding' => 'utf-8',
	'ENCODING' => 'utf-8',
	'UNSAFE'   => 1,
);

my %tv_attributes = (
	'source-info-name'    => 'Schedules Direct',
	'source-info-url'     => 'http://www.schedulesdirect.org',
	'generator-info-name' => "$grabber_name $grabber_version",
);

my @channel_id_formats = (
	[ 'default', 'I%s.json.schedulesdirect.org', 'Default Format' ],
	[ 'zap2it',  'I%s.labs.zap2it.com',          'tv_grab_na_dd Format' ],
	[ 'mythtv',  '%s',                           'MythTV Internal DD Grabber Format' ],
);

my @previously_shown_formats = (
	[ 'date',     '%Y%m%d',          'Date Only' ],
	[ 'datetime', '%Y%m%d%H%M%S %z', 'Date And Time' ],
);

my $cache_schema = 1;

my $sd_json_baseurl = 'https://json.schedulesdirect.org';
my $sd_json_api = '/20141201/';
my $sd_json_token;
my $sd_json_status;
my $sd_json_request_max = 5000;

my $ua = LWP::UserAgent->new(agent => "$grabber_name $grabber_version");
$ua->default_header('accept-encoding' => scalar HTTP::Message::decodable());

my $debug;
my $quiet;

# In general we rely on ParseOptions to parse the command line options. However
# ParseOptions does not pass the options to stage_sub so we check for some
# options on our own.
for my $opt (@ARGV) {
	$debug = 1 if($opt =~ /--debug/i);
	$quiet = 1 if($opt =~ /--quiet/i);
}

$quiet = 0 if $debug;
$ua->show_progress(1) unless $quiet;

my ($opt, $conf) = ParseOptions({
	grabber_name => $grabber_name,
	version => $grabber_cvs_id,
	description => 'Schedules Direct JSON API',
	capabilities => [qw/baseline manualconfig preferredmethod/],
	stage_sub => \&config_stage,
	listchannels_sub => \&list_channels,
	preferredmethod => 'allatonce',
	defaults => { days => -1 },
});

print STDERR "**Warning** this grabber will be rename tv_grab_zz_sdjson in the next release. (switch now!)\n";

sub get_conf_format {
	my ($config, $options, $text) = @_;
	my $result;

	if($conf->{$config}->[0]) {
		for my $format (@{$options}) {
			if($format->[0] eq $conf->{$config}->[0]) {
				$result = $format->[1];
				last;
			}
		}
	}

	if(!$result) {
		print STDERR "Valid $text not specified in config, using default.\n" unless $quiet;
		$result = $options->[0]->[1];
	}

	return $result;
}

my $channel_id_format = get_conf_format('channel-id-format', \@channel_id_formats, 'channel ID format');
my $previously_shown_format = get_conf_format('previously-shown-format', \@previously_shown_formats, 'previously shown format');

# default days to largish value
if($opt->{'days'} < 0) {
	$opt->{'days'} = 100;
}

sub get_start_stop_time {
	# calculate start and stop time from offset and days options
	my $dt_start = DateTime->today(time_zone => 'local');
	$dt_start->add(days => $opt->{'offset'});
	my $dt_stop = $dt_start->clone();
	$dt_stop->add(days => $opt->{'days'});

	# source data has times in UTC
	$dt_start->set_time_zone('UTC');
	$dt_stop->set_time_zone('UTC');

	# convert DateTime to seconds from epoch which will allow for a LOT faster
	# comparisons than comparing DateTime objects
	return ($dt_start->epoch(), $dt_stop->epoch());
}
my ($time_start, $time_stop) = get_start_stop_time();

my $cache_file = $conf->{'cache'}->[0];

sub get_default_cache_file {
	my $winhome;
	if(defined $ENV{HOMEDRIVE} && defined $ENV{HOMEPATH}) {
		$winhome = $ENV{HOMEDRIVE} . $ENV{HOMEPATH};
	}
	my $home = $ENV{HOME} || $winhome || getcwd();

	return "$home/.xmltv/$grabber_name.cache";
}

# days to add to day of month to get days since Jan 1st
my @days_norm = ( -1, 30, 58, 89, 119, 150, 180, 211, 242, 272, 303, 333 );
my @days_leap = ( -1, 30, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 );

sub is_leap_year {
	return (!($_[0] % 4) && (($_[0] % 100) || !($_[0] % 400)));
}

sub parse_airtime {
	use integer;
	my ($year, $month, $day, $hour, $min, $sec) = ($_[0] =~ /(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+)Z/);

	# determine number of days since Jan 1st of requested year
	$month -= 1;
	$day += is_leap_year($year) ? $days_leap[$month] : $days_norm[$month];

	# add number of days (minus leap days) for years since 1970
	$day += ($year - 1970) * 365;

	# add leap days from previous years since year 0 (we already included leap
	# day for this year), subtract number of leap days between 0 and 1970 (477)
	$year -= 1;
	$day += $year / 4 - $year / 100 + $year / 400 - 477;

	return ($day * 86400 + $hour * 3600 + $min * 60 + $sec);
}

sub format_airtime {
	my ($sec, $min, $hour, $day, $month, $year) = gmtime($_[0]);
	return sprintf('%04d%02d%02d%02d%02d%02d +0000', $year + 1900, $month + 1, $day, $hour, $min, $sec);
}

my $dt_zone_local = DateTime::TimeZone->new(name => 'local');

# SD-JSON only specifies a date for originalAirDate. Older versions of
# mythtv need full date and time even though xmltv only requires date.
# We assume local time as mythtv expects and set the time to noon to
# minimize the chance of an error causing the day to be off by one.
sub parse_original_airdate {
	my ($year, $month, $day) = ($_[0] =~ /(\d+)-(\d+)-(\d+)/);
	local $Params::Validate::NO_VALIDATION = 1;
	return DateTime->new(
		year       => $year,
		month      => $month,
		day        => $day,
		hour       => 12,
		time_zone  => $dt_zone_local,
	);
}

sub retry {
	my ($action) = @_;
	my $retry = 3;
	my $result;

	for(;;) {
		try {
			$result = $action->();
		}
		catch {
			if(--$retry) {
				print STDERR $_, "Retry in 10 seconds...\n" unless $quiet;
				sleep 10;
			}
			else {
				die $_, "Retry count exceeded.";
			}
		};
		return $result if $result;
	}
}

sub sd_json_request {
	my ($method, $path, $content) = @_;

	my $url;
	if($path =~ /^\//) {
		$url = $sd_json_baseurl . $path;
	}
	else {
		$url = $sd_json_baseurl . $sd_json_api . $path;
	}

	my @params;
	push(@params, content_type => 'application/json');
	push(@params, token => $sd_json_token) unless $path eq 'token';
	push(@params, content => encode_json($content)) if defined $content;

	my $response = $ua->$method($url, @params);
	if($response->is_success()) {
		return decode_json($response->decoded_content());
	}
	else {
		my $msg = $response->decoded_content();

		if($response->header('content-type') =~ m{application/json}i) {
			my $error = decode_json($msg);

			# for lineups request don't consider 4102/NO_LINEUPS an error
			if($path eq 'lineups' && $error->{'code'} == 4102) {
				return undef;
			}

			$msg = "Server (ID=$error->{'serverID'} Time=$error->{'datetime'}) returned an error:\n"
				."$error->{'message'} ($error->{'code'}/$error->{'response'})";
		}

		print STDERR Dumper($response) if $debug;
		die $msg, "\n";
	}
}

sub sd_json_get_token {
	my ($username, $password) = @_;

	retry sub {
		my $response = sd_json_request('post', 'token', { username => $username, password => $password });
		if(ref $response ne 'HASH' || !exists $response->{'token'}) {
			die "Invalid token response.\n";
		}
		return $response->{'token'};
	};
}

sub sd_json_get_status {
	retry sub {
		my $status = sd_json_request('get', 'status');
		if(ref $status ne 'HASH' ||
			ref $status->{'systemStatus'} ne 'ARRAY' || ref $status->{'systemStatus'}->[0] ne 'HASH' ||
			ref $status->{'account'} ne 'HASH' ||
			ref $status->{'lineups'} ne 'ARRAY') {
			die "Invalid status response.\n"
		}
		return $status;
	}
}

sub sd_json_get_available {
	my ($type) = @_;
	my $result = sd_json_request('get', 'available');

	if($type) {
		for my $entry (@{$result}) {
			if($entry->{'type'} eq $type) {
				return $entry;
			}
		}
	}

	return $result;
}

sub sd_json_get_lineups {
	return sd_json_request('get', 'lineups');
}

sub sd_json_get_headends {
	my ($country, $postalcode) = @_;
	return sd_json_request('get', "headends?country=$country&postalcode=$postalcode");
}

sub sd_json_get_transmitters {
	my ($country) = @_;
	return sd_json_request('get', "transmitters/$country");
}

sub sd_json_add_lineup {
	my ($lineup) = @_;
	return sd_json_request('put', "lineups/$lineup");
}

sub sd_json_delete_lineup {
	my ($lineup) = @_;
	return sd_json_request('delete', "lineups/$lineup");
}

sub sd_json_get_lineup {
	my ($lineup) = @_;
	retry sub {
		my $lineup = sd_json_request('get', $lineup);
		if(ref $lineup ne 'HASH') {
			die "Invalid lineup response.\n"
		}
		return $lineup;
	}
}

sub sd_json_get_schedules_md5 {
	my ($channels) = @_;
	my @stations;
	for my $channel (@{$channels}) {
		push(@stations, { stationID => $channel });
	}
	return sd_json_request('post', 'schedules/md5', \@stations);
}

sub sd_json_get_schedules {
	my ($schedules) = @_;
	return sd_json_request('post', 'schedules', $schedules);
}

sub sd_json_get_programs {
	my ($programs) = @_;
	return sd_json_request('post', 'programs', $programs);
}

sub sd_json_init {
	my ($conf) = @_;

	if(!defined $sd_json_status) {
		$sd_json_token = sd_json_get_token($conf->{'username'}->[0], sha1_hex($conf->{'password'}->[0]));
		$sd_json_status = sd_json_get_status();

		my $status = $sd_json_status->{'systemStatus'}->[0]->{'status'};
		if($status !~ /online/i) {
			die "Schedules Direct system status: $status\n";
		}
	}
}

sub sd_json_get_image_url {
	my ($url) = @_;

	if($url =~ /^http/) {
		return $url;
	}
	else {
		return $sd_json_baseurl . $sd_json_api . 'image/' . $url;
	}
}

sub get_lineup_description {
	my ($lineup) = @_;

	my $location  = $lineup->{'location'}  // 'unknown';
	my $transport = $lineup->{'transport'} // 'unknown';
	my $name      = $lineup->{'name'}      // 'unknown';
	my $id        = $lineup->{'lineup'}    // 'unknown';

	if($lineup->{'isDeleted'}) {
		return "$id | $name";
	}
	elsif($transport eq 'QAM') {
		return "$id | $transport";
	}
	else {
		return "$id | $name | $location | $transport";
	}
}

my %transmitter_countries;

sub ask_search_by_transmitter {
	my ($country) = @_;

	if(!%transmitter_countries) {
		my $available = sd_json_get_available('DVB-T');
		for ($available->{'description'} =~ /[A-Z]{3}/g) {
			$transmitter_countries{$_} = undef;
		}
	}

	if(exists $transmitter_countries{$country}) {
		my @options;
		push(@options, 'transmitter');
		push(@options, 'postal' );

		if(ask_choice('Search by Transmitter or Postal Code:', $options[0], @options) eq $options[0]) {
			return 1;
		}
	}

	return 0;
}

sub config_stage {
	my ($stage, $conf) = @_;

	if($stage ne 'start' && $stage ne 'login') {
		sd_json_init($conf);
	}

	my $result;
	my $w = new XMLTV::Configure::Writer(OUTPUT => \$result, %w_args);
	$w->start(\%tv_attributes);

	if($stage eq 'start') {
		$w->write_string({
			id => 'cache',
			description => [ [ 'Cache file for lineups, schedules and programs.', 'en' ] ],
			title => [ [ 'Cache file', 'en' ] ],
			default => get_default_cache_file(),
		});

		$w->start_selectone({
			id => 'channel-id-format',
			description => [ [ 'If you are migrating from a different grabber selecting an alternate channel ID format can make the migration easier.', 'en' ] ],
			title => [ [ 'Select channel ID format', 'en' ] ],
		});
		for my $format (@channel_id_formats) {
			$w->write_option({
				value => $format->[0],
				text  => [ [ $format->[2].' (eg: '.sprintf($format->[1], 12345).')', 'en' ] ],
			});
		}
		$w->end_selectone();

		$w->start_selectone({
			id => 'previously-shown-format',
			description => [ [ 'As the JSON data only includes the previously shown date normally the XML output should only have the date. However some programs such as older versions of MythTV also need a time.', 'en' ] ],
			title => [ [ 'Select previously shown format', 'en' ] ],
		});
		for my $format (@previously_shown_formats) {
			$w->write_option({
				value => $format->[0],
				text  => [ [ $format->[2], 'en' ] ],
			});
		}
		$w->end_selectone();

		$w->end('login');
	}
	elsif($stage eq 'login') {
		$w->write_string({
			id => 'username',
			description => [ [ 'Schedules Direct username.', 'en' ] ],
			title => [ [ 'Username', 'en' ] ],
		});
		$w->write_secretstring({
			id => 'password',
			description => [ [ 'Schedules Direct password.', 'en' ] ],
			title => [ [ 'Password', 'en' ] ],
		});

		$w->end('account-lineups');
	}
	elsif($stage eq 'account-lineups') {
		# This stage doesn't work with configapi and I am not sure if there is
		# currently any good way to make it work...
		my $edit;
		do {
			my $max = $sd_json_status->{'account'}->{'maxLineups'};
			my $lineups = sd_json_get_lineups();
			$lineups = $lineups->{'lineups'};
			my $count = 0;

			say("This step configures the lineups enabled for your Schedules "
				."Direct account. It impacts all other configurations and "
				."programs using the JSON API with your account. A maximum of "
				."$max lineups can by added to your account. In a later step "
				."you will choose which lineups or channels to actually use "
				."for this configuration.\n"
				."Current lineups enabled for your Schedules Direct account:"
			);

			say('#. Lineup ID | Name | Location | Transport');
			for my $lineup (@{$lineups}) {
				$count++;
				my $desc = get_lineup_description($lineup);
				say("$count. $desc");
			}
			if(!$count) {
				say('(none)');
			}

			my @options;
			push(@options, 'continue') if $count;
			push(@options, 'add' ) if($count < $max);
			push(@options, 'delete') if $count;
			$edit = ask_choice('Edit account lineups:', $options[0], @options);

			try
			{
				if($edit eq 'add') {
					my $country = uc(ask('Lineup ID or Country (ISO-3166-1 alpha 3 such as USA or CAN):'));
					if(length($country) > 3) {
						sd_json_add_lineup("$country");
					}
					else {
						my $count = 0;
						my @lineups;

						if(ask_search_by_transmitter($country)) {
							my $transmitters = sd_json_get_transmitters($country);

							say('#. Lineup ID | Transmitter');
							for my $transmitter (sort(keys %{$transmitters})) {
								$count++;
								my $lineup = $transmitters->{$transmitter};
								push(@lineups, $lineup);
								say("$count. $lineup | $transmitter");
							}
						}
						else {
							my $postalcode = ask(($country eq 'USA') ? 'Zip Code:' : 'Postal Code:');
							my $headends = sd_json_get_headends($country, $postalcode);

							say('#. Lineup ID | Name | Location | Transport');
							for my $headend (@{$headends}) {
								for my $lineup (@{$headend->{'lineups'}}) {
									$count++;
									my $id = $lineup->{'lineup'};
									push(@lineups, $id);
									say("$count. $id | $lineup->{'name'} | $headend->{'location'} | $headend->{'transport'}");
								}
							}
						}

						my $add = ask_choice('Add lineup (0 = none):', 0, (0 .. $count));
						if($add) {
							sd_json_add_lineup($lineups[$add - 1]);
						}
					}
				}
				elsif($edit eq 'delete') {
					my $delete = ask_choice('Delete lineup (0 = none):', 0, (0 .. $count));
					if($delete) {
						sd_json_delete_lineup($lineups->[$delete - 1]->{'lineup'});
					}
				}
			}
			catch {
				say($_);
			};
		}
		while($edit ne 'continue');

		$w->end('select-mode');
	}
	elsif($stage eq 'select-mode') {
		$w->start_selectone({
			id => 'mode',
			description => [ [ 'Choose whether you want to include complete lineups or individual channels for this configuration.', 'en' ] ],
			title => [ [ 'Select mode', 'en' ] ],
		});
		$w->write_option({
			value => 'lineup',
			text  => [ [ 'lineups', 'en' ] ],
		});
		$w->write_option({
			value => 'channels',
			text  => [ [ 'channels', 'en' ] ],
		});
		$w->end_selectone();

		$w->end('select-lineups');
	}
	elsif($stage eq 'select-lineups') {
		my $lineups = sd_json_get_lineups();
		$lineups = $lineups->{'lineups'};

		my $desc;
		if($conf->{'mode'}->[0] eq 'lineup') {
			$desc = 'Choose lineups to use for this configuration.';
		}
		else {
			$desc = 'Choose lineups from which you want to select channels for this configuration.';
		}

		$w->start_selectmany({
			id => $conf->{'mode'}->[0],
			description => [ [ $desc, 'en' ] ],
			title => [ [ 'Select linups', 'en' ] ],
		});
		for my $lineup (@{$lineups}) {
			my $id = $lineup->{'lineup'};
			$w->write_option({
				value => $id,
				text  => [ [ $id, 'en' ] ],
			});
		}
		$w->end_selectmany();

		$w->end('select-channels');
	}
	else {
		die "Unknown stage $stage";
	}

	return $result;
}

my $cache;
my $cache_lineups;
my $cache_schedules;
my $cache_programs;
my %channel_index;
my %channel_map;

sub cache_load {
	sub get_hash {
		my $hash = $cache->{$_[0]};
		return (ref $hash eq 'HASH') ? $hash : {};
	}

	# make sure the cache file is readable and writable
	if(open(my $fh, '+>>', $cache_file)) {
		close($fh);
	}
	else {
		die "Cannot open $cache_file for read/write.\n";
	}

	# attempt to retreive cached data
	try {
		$cache = retrieve($cache_file);
		if(ref $cache ne 'HASH') {
			die "Invalid cache file.\n";
		}

		if($cache->{'schema'} == $cache_schema) {
			$cache_lineups = get_hash('lineups');
			$cache_schedules = get_hash('schedules');
			$cache_programs = get_hash('programs');
		}
		else {
			die "Ignoring cache file with old schema.\n";
		}
	}
	catch {
		print STDERR unless $quiet;
		$cache_lineups = {};
		$cache_schedules = {};
		$cache_programs = {};
	};

	$cache = { schema => $cache_schema, lineups => $cache_lineups, schedules => $cache_schedules, programs => $cache_programs };
}

sub cache_update_lineups {
	print STDERR "Updating lineups...\n" unless $quiet;

	my $now = DateTime->now()->epoch();
	my %lineups_enabled;
	my @lineups_update;

	# check for out of date lineups
	for my $lineup (@{$sd_json_status->{'lineups'}}) {
		if(ref $lineup ne 'HASH') {
			print STDERR "Invalid lineup in account status.\n" unless $quiet;
			next;
		}

		my $id = $lineup->{'lineup'};
		if(!$id || ref $id) {
			print STDERR "Invalid lineup in account status.\n" unless $quiet;
			next;
		}

		$lineups_enabled{$id} = 1;

		my $metadata = $cache_lineups->{$id}->{'metadata'};
		if(ref $metadata ne 'HASH') {
			print STDERR "lineup $id: new\n" if $debug;
			push(@lineups_update, $lineup);
		}
		elsif($metadata->{'modified'} ne $lineup->{'modified'}) {
			print STDERR "lineup $id: old\n" if $debug;
			push(@lineups_update, $lineup);
		}
		else {
			print STDERR "lineup $id: current\n" if $debug;
			$cache_lineups->{$id}->{'accessed'} = $now;
		}
	}

	# check that configured lineups are actually enabled for the account
	my $lineup_error;
	for my $lineup (@{$conf->{'lineup'}}, @{$conf->{'channels'}}) {
		if(!$lineups_enabled{$lineup}) {
			$lineup_error = 1;
			print STDERR "Lineup $lineup in the current configuration is not enabled on your account.\n";
		}
	}

	if($lineup_error) {
		die "Please reconfigure the grabber or your account settings.\n"
	}

	# update lineups
	for my $lineup (@lineups_update) {
		my $id = $lineup->{'lineup'};
		my $uri = $lineup->{'uri'};

		if(!$uri || ref $uri) {
			print STDERR "Invalid lineup URI in account status.\n" unless $quiet;
			next;
		}

		my $update = sd_json_get_lineup($uri);
		$cache_lineups->{$id} = $update;
		$cache_lineups->{$id}->{'accessed'} = $now;
	}
}

sub cache_update_schedules {
	my ($channels) = @_;

	print STDERR "Updating schedules...\n" unless $quiet;

	my $now = DateTime->now()->epoch();
	my $schedules_md5 = sd_json_get_schedules_md5($channels);
	my @channels_update;

	while(my ($channel, $schedule) = each %{$schedules_md5}) {
		if(ref $schedule ne 'HASH') {
			print STDERR "Invalid schedule for channel $channel\n" unless $quiet;
			next;
		}

		my @dates;
		while(my ($date, $latest) = each %{$schedule}) {
			my $metadata = $cache_schedules->{$channel}->{$date}->{'metadata'};
			if(!defined $metadata) {
				print STDERR "channel $channel $date: new\n" if $debug;
				push(@dates, $date);
			}
			elsif($metadata->{'md5'} ne $latest->{'md5'}) {
				print STDERR "channel $channel $date: old\n" if $debug;
				push(@dates, $date);
			}
			else {
				print STDERR "channel $channel $date: current\n" if $debug;
			}
		}
		if(@dates) {
			push(@channels_update, { stationID => $channel, date => \@dates });
		}
	}

	# update schedules
	while(my @block = splice(@channels_update, 0, $sd_json_request_max)) {
		my $schedules = sd_json_get_schedules(\@block);
		for my $schedule (@{$schedules}) {
			my $channel = $schedule->{'stationID'};
			my $date = $schedule->{'metadata'}->{'startDate'};
			$cache_schedules->{$channel}->{$date} = $schedule;
		}
	}

	print STDERR "Updating programs...\n" unless $quiet;

	my %programs_update_hash;

	# create list of programs to update
	for my $channel (@{$channels}) {
		for my $schedule (values %{$cache_schedules->{$channel}}) {
			for my $program (@{$schedule->{'programs'}}) {
				my $airtime = parse_airtime($program->{'airDateTime'});
				my $dur = int($program->{'duration'});

				if(($airtime + $dur) > $time_start && $airtime < $time_stop) {
					my $id = $program->{'programID'};
					my $cached = $cache_programs->{$id};

					if(!defined $cached) {
						print STDERR "program $id: new\n" if $debug;
						$programs_update_hash{$id} = 1;
					}
					elsif($cached->{'md5'} ne $program->{'md5'}) {
						print STDERR "program $id: old\n" if $debug;
						$programs_update_hash{$id} = 1;
					}
					else {
						print STDERR "program $id: current\n" if $debug;
						$cache_programs->{$id}->{'accessed'} = $now;
					}
				}
			}
		}
	}

	# update programs
	my @programs_update = keys %programs_update_hash;
	while(my @block = splice(@programs_update, 0, $sd_json_request_max)) {
		my $programs = sd_json_get_programs(\@block);

		for my $id (@block) {
			$cache_programs->{$id} = shift @{$programs};
			$cache_programs->{$id}->{'accessed'} = $now;
		}
	}
}

sub cache_drop_old {
	my $limit = DateTime->now()->subtract(days => 10)->epoch();

	print STDERR "Removing old cache entries...\n" unless $quiet;

	while(my ($key, $hash) = each %{$cache}) {
		if($key eq 'lineups' || $key eq 'programs') {
			# remove old lineups and programs
			while(my ($key, $value) = each %{$hash}) {
				if(ref $value ne 'HASH' || !exists $value->{'accessed'} || $value->{'accessed'} < $limit) {
					print STDERR "$key: drop\n" if $debug;
					delete $hash->{$key};
				}
			}
		}
		elsif($key eq 'schedules') {
			# remove old schedules
			my $today = DateTime->today()->strftime('%Y-%m-%d');
			while(my ($channel, $schedules) = each %{$hash}) {
				if(ref $schedules ne 'HASH') {
					print STDERR "$channel: drop\n" if $debug;
					delete $cache_schedules->{$channel};
					next;
				}

				while(my ($date, $schedule) = each %{$schedules}) {
					if($date lt $today) {
						print STDERR "$channel $date: drop\n" if $debug;
						delete $schedules->{$date};
					}
				}

				if(scalar keys %{$schedules} == 0) {
					print STDERR "$channel: drop\n" if $debug;
					delete $cache_schedules->{$channel};
				}
			}
		}
		elsif($key ne 'schema') {
			# remove unknown keys
			delete $cache->{$key};
		}
	}
}

sub cache_save {
	store($cache, $cache_file);
}

sub cache_index_channels {
	print STDERR "Indexing channels...\n" unless $quiet;

	# create index
	for my $id (@{$conf->{'lineup'}}, @{$conf->{'channels'}}) {
		my $lineup = $cache_lineups->{$id};
		if(ref $lineup ne 'HASH' || ref $lineup->{'stations'} ne 'ARRAY') {
			print STDERR "Invalid stations array for lineup $id\n" unless $quiet;
			next;
		}

		for my $channel (@{$lineup->{'stations'}}) {
			if(ref $channel ne 'HASH') {
				print STDERR "Invalid channel in lineup $id\n" unless $quiet;
				next;
			}
			$channel_index{$channel->{'stationID'}} = $channel;
		}

		my $qam = $lineup->{'qamMappings'};
		my $map;

		if($qam) {
			$map = $lineup->{'map'}->{$qam->[0]};
		}
		else {
			$map = $lineup->{'map'};
		}

		for my $channel (@{$map}) {
			$channel_map{$channel->{'stationID'}} = $channel;
		}
	}
}

sub get_channel_list {
	my ($conf) = @_;
	my %hash;

	if($conf->{'mode'}->[0] eq 'lineup') {
		for my $lineup (@{$conf->{'lineup'}}) {
			if(ref $cache_lineups->{$lineup}->{'stations'} ne 'ARRAY') {
				print STDERR "Invalid stations array for lineup $lineup\n" unless $quiet;
				next;
			}

			for my $channel (@{$cache_lineups->{$lineup}->{'stations'}}) {
				if(ref $channel ne 'HASH' || !$channel->{'stationID'}) {
					print STDERR "Invalid channel in lineup $lineup\n" unless $quiet;
					next;
				}
				$hash{$channel->{'stationID'}} = 1;
			}
		}
	}
	else {
		for my $channel (@{$conf->{'channel'}}) {
			if(exists $channel_index{$channel}) {
				$hash{$channel} = 1;
			}
			else {
				print STDERR "Channel ID $channel in the current configuration is not found in any enabled lineup.\n" unless $quiet;
			}
		}
	}

	my @list = sort(keys %hash);
	return \@list;
}

sub get_channel_number {
	my ($map) = @_;

	if($map->{'virtualChannel'}) {
		return $map->{'virtualChannel'};
	}
	elsif($map->{'atscMajor'}) {
		return "$map->{'atscMajor'}_$map->{'atscMinor'}";
	}
	elsif($map->{'channel'}) {
		return $map->{'channel'};
	}
	elsif($map->{'frequencyHz'}) {
		return $map->{'frequencyHz'};
	}

	return undef;
}

sub get_icon {
	my ($url, $width, $height) = @_;
	my %result;

	if($url) {
		$result{'src'} = sd_json_get_image_url($url);
		if($width && $height) {
			$result{'width'} = $width;
			$result{'height'} = $height;
		}

		return [ \%result ];
	}
	else {
		return undef;
	}
}

sub write_channel {
	my ($w, $channel, $map) = @_;

	my %ch;

	# mythtv seems to assume that the first three display-name elements are
	# name, callsign and channel number. We follow that scheme here.
	$ch{'id'} = sprintf($channel_id_format, $channel->{'stationID'});
	$ch{'display-name'} = [
		[ $channel->{'name'}       || 'unknown name'     ],
		[ $channel->{'callsign'}   || 'unknown callsign' ],
		[ get_channel_number($map) || 'unknown number'   ]
	];

	my $logo = $channel->{'logo'};
	my $icon = get_icon($logo->{'URL'}, $logo->{'width'}, $logo->{'height'});
	$ch{'icon'} = $icon if $icon;

	$w->write_channel(\%ch);
}

# this is used by the last stage of --configure
sub list_channels {
	my ($conf, $opt) = @_;

	# use raw channel id in configuration files
	$channel_id_format = '%s';

	my $result;
	my $w = new XMLTV::Writer(OUTPUT => \$result, %w_args);
	$w->start(\%tv_attributes);

	for my $id (@{$conf->{'channels'}}) {
		my $lineup = sd_json_get_lineup("lineups/$id");
		for my $channel (@{$lineup->{'stations'}}) {
			write_channel($w, $channel);
		}
	}

	$w->end();
	return $result;
}

sub get_program_title {
	my ($details) = @_;
	my $title = $details->{'titles'}->[0]->{'title120'};

	if($title) {
		return [ [ $title ] ];
	}
	else {
		return [ [ 'unknown' ] ];
	}
}

sub get_program_subtitle {
	my ($details) = @_;
	my $subtitle = $details->{'episodeTitle150'};

	if($subtitle) {
		return [ [ $subtitle ] ];
	}
	else {
		return undef;
	}
}

sub get_program_description {
	my ($details) = @_;
	my $descriptions = $details->{'descriptions'};

	if(exists $descriptions->{'description1000'}) {
		return [ [ $descriptions->{'description1000'}->[0]->{'description'} ] ];
	}
	elsif(exists $descriptions->{'description100'}) {
		return [ [ $descriptions->{'description100'}->[0]->{'description'} ] ];
	}
	else {
		return undef;
	}
}

sub get_program_credits {
	my ($details) = @_;
	my %credits;

	for my $credit (@{$details->{'cast'}}, @{$details->{'crew'}}) {
		my $role = $credit->{'role'};
		my $name = $credit->{'name'};
		my $key;

		if($role =~ /director/i) {
			$key = 'director';
		}
		elsif($role =~ /(actor|voice)/i) {
			$key = 'actor';
			if($credit->{'characterName'}) {
				$name = [ $name, $credit->{'characterName'} ];
			}
		}
		elsif($role =~ /writer/i) {
			$key = 'writer';
		}
		elsif($role =~ /producer/i) {
			$key = 'producer';
		}
		elsif($role =~ /(host|anchor)/i) {
			$key = 'presenter';
		}
		elsif($role =~ /(guest|contestant)/i) {
			$key = 'guest';
		}
		else {
#			print STDERR "$role\n";
		}

		if($key) {
			if(exists $credits{$key}) {
				push(@{$credits{$key}}, $name);
			}
			else {
				$credits{$key} = [ $name ];
			}
		}
	}

	if(scalar keys %credits) {
		return \%credits;
	}
	else {
		return undef;
	}
}

sub get_program_date {
	my ($details) = @_;

	my $year = $details->{'movie'}->{'year'};
	if($year) {
		return $year;
	}

	return undef;
}

sub get_program_category {
	my ($channel, $details) = @_;
	my %seen;
	my @result;

	sub add {
		my ($result, $category, $seen) = @_;
		if($category && !exists $seen->{$category}) {
			$seen->{$category} = 1;
			push(@{$result}, [ $category ]);
		}
	}

	for my $genre (@{$details->{'genres'}}) {
		add(\@result, $genre, \%seen);
	}
	add(\@result, $details->{'showType'}, \%seen);

	# mythtv specifically looks for movie|series|sports|tvshow
	my $entity_type = $details->{'entityType'};
	if($entity_type =~ /movie/i) {
		add(\@result, 'movie', \%seen);
	}
	elsif($entity_type =~ /episode/i) {
		add(\@result, 'series', \%seen);
	}
	elsif($entity_type =~ /sports/i) {
		add(\@result, 'sports', \%seen);
	}
	elsif($channel->{'isRadioStation'}) {
		add(\@result, 'radio', \%seen);
	}
	else {
		add(\@result, 'tvshow', \%seen);
	}

	if(scalar @result) {
		return \@result;
	}
	else {
		return undef;
	}
}

sub get_program_length {
	my ($details) = @_;
	my $duration = $details->{'duration'} || $details->{'movie'}->{'duration'};

	if($duration) {
		return $duration;
	}
	else {
		return undef;
	}
}

sub get_program_icon {
	my ($details) = @_;
	my $episode_image = $details->{'episodeImage'};
	return get_icon($episode_image->{'uri'}, $episode_image->{'width'}, $episode_image->{'height'});
}

sub get_program_url {
	my ($details) = @_;

	my $url = $details->{'officialURL'};
	if($url) {
		return [ $url ];
	}

	return undef;
}

sub _get_program_episode {
	my ($number, $total) = @_;
	my $result = '';

	if(looks_like_number($number) && int($number)) {
		$result = sprintf('%d', $number - 1);
		if(looks_like_number($total) && int($total)) {
			$result .= sprintf('/%d', $total);
		}
	}

	return $result;
}

sub get_program_episode {
	my ($program, $details) = @_;
	my $season = '';
	my $episode = '';
	my $part = '';
	my @result;

	my $metadata = $details->{'metadata'}->[0]->{'Gracenote'};
	if($metadata)
	{
		$season = _get_program_episode($metadata->{'season'}, $metadata->{'totalSeason'});
		$episode = _get_program_episode($metadata->{'episode'}, $metadata->{'totalEpisodes'});
	}

	my $multipart = $program->{'multipart'};
	if($multipart) {
		$part = _get_program_episode($multipart->{'partNumber'}, $multipart->{'totalParts'});
	}

	if(length($season) || length($episode) || length($part)) {
		push(@result, [ sprintf('%s.%s.%s', $season, $episode, $part), 'xmltv_ns' ]);
	}

	push(@result, [ $program->{'programID'}, 'dd_progid' ]);

	return \@result;
}

sub get_program_video {
	my ($program) = @_;
	my %video;

	for my $item (@{$program->{'videoProperties'}}) {
		if($item =~ /hdtv/i) {
			$video{'quality'} = 'HDTV';
		}
	}

	if(scalar keys %video) {
		return \%video;
	}
	else {
		return undef;
	}
}

sub get_program_audio {
	my ($program) = @_;
	my %audio;

	for my $item (@{$program->{'audioProperties'}}) {
		if($item =~ /mono/i) {
			$audio{'stereo'} = 'mono';
		}
		elsif($item =~ /stereo/i) {
			$audio{'stereo'} = 'stereo';
		}
		elsif($item =~ /DD/i) {
			$audio{'stereo'} = 'dolby digital';
		}
	}

	if(scalar keys %audio) {
		return \%audio;
	}

	return undef;
}

# The xmltv docs state this field is "When and where the programme was last shown".
# However mythtv expects the original air date to be in this field.
sub get_program_previously_shown {
	my ($details) = @_;
	my %previously_shown;

	my $date = $details->{'originalAirDate'};
	if($date) {
		my $dt = parse_original_airdate($date);
		$previously_shown{'start'} = $dt->strftime($previously_shown_format);
	}

	if(scalar keys %previously_shown) {
		return \%previously_shown;
	}

	return undef;
}

sub get_program_premiere {
	my ($program) = @_;
	my $premiere = $program->{'isPremiereOrFinale'};

	if(defined $premiere && $premiere =~ /premiere/i) {
		return [ $premiere ];
	}

	return undef;
}

sub get_program_new {
	my ($program) = @_;
	my $new = $program->{'new'};

	if(defined $new) {
		return 1;
	}

	return undef;
}

sub get_program_subtitles {
	my ($program) = @_;

	if(grep('^cc$', @{$program->{'audioProperties'}})) {
		return [ { 'type' => 'teletext' } ];
	}

	return undef;
}

sub get_program_rating {
	my ($program, $details) = @_;

	# first check 'contentRating' then 'ratings'
	my $ratings = $details->{'contentRating'};
	if(!defined $ratings || ref $ratings ne 'ARRAY') {
		$ratings = $program->{'ratings'};
		if(!defined $ratings || ref $ratings ne 'ARRAY') {
			return undef;
		}
	}

	my @result;
	for my $rating (@{$ratings}) {
		my $code = $rating->{'code'};
		my $body = $rating->{'body'};
		if($code) {
			push(@result, [ $code, $body ]);
		}
	}

	if(scalar @result) {
		return \@result;
	}

	return undef;
}

sub get_program_star_rating {
	my ($details) = @_;
	my $rating = $details->{'movie'}->{'qualityRating'}->[0];

	if($rating) {
		return [ [ "$rating->{'rating'}/$rating->{'maxRating'}", $rating->{'ratingsBody'} ] ];
	}
	else {
		return undef;
	}
}

sub write_programme {
	my ($w, $channel, $program, $details) = @_;

	my $airtime = parse_airtime($program->{'airDateTime'});
	my $dur = int($program->{'duration'});

	if(($airtime + $dur) > $time_start && $airtime < $time_stop) {
		my $start = format_airtime($airtime);
		my $stop = format_airtime($airtime + $dur);

		$w->write_programme({
			'channel'          => sprintf($channel_id_format, $channel->{'stationID'}),
			'start'            => $start,
			'stop'             => $stop,
			'title'            => get_program_title($details),
			'sub-title'        => get_program_subtitle($details),
			'desc'             => get_program_description($details),
			'credits'          => get_program_credits($details),
			'date'             => get_program_date($details),
			'category'         => get_program_category($channel, $details),
#			'keyword'          => undef,
#			'language'         => undef,
#			'orig-language'    => undef,
			'length'           => get_program_length($details),
			'icon'             => get_program_icon($details),
			'url'              => get_program_url($details),
#			'country'          => undef,
			'episode-num'      => get_program_episode($program, $details),
			'video'            => get_program_video($program),
			'audio'            => get_program_audio($program),
			'previously-shown' => get_program_previously_shown($details),
			'premiere'         => get_program_premiere($program),
#			'last-chance'      => undef,
			'new'              => get_program_new($program),
			'subtitles'        => get_program_subtitles($program),
			'rating'           => get_program_rating($program, $details),
			'star-rating'      => get_program_star_rating($details),
#			'review'           => undef,
		});
	}
}

sub grab_listings {
	my ($conf) = @_;
	my $channels;

	print STDERR "Initializing...\n" unless $quiet;
	cache_load();
	sd_json_init($conf);
	cache_update_lineups();
	cache_index_channels();
	$channels = get_channel_list($conf);

	if(!@{$channels}) {
		die "No lineups or channels configured.\n";
	}

	cache_update_schedules($channels);
	cache_drop_old();
	cache_save();

	print STDERR "Writing output...\n" unless $quiet;
	my $w = new XMLTV::Writer(%w_args);
	$w->start(\%tv_attributes);

	# write channels
	for my $channel (@{$channels}) {
		write_channel($w, $channel_index{$channel}, $channel_map{$channel});
	}

	# write programs
	for my $channel (@{$channels}) {
		my $schedules = $cache_schedules->{$channel};
		for my $day (sort(keys %{$schedules})) {
			for my $program (@{$schedules->{$day}->{'programs'}}) {
				write_programme($w, $channel_index{$channel}, $program, $cache_programs->{$program->{'programID'}});
			}
		}
	}

	$w->end();
	print STDERR "Done\n" unless $quiet;
}

grab_listings($conf);