-
Notifications
You must be signed in to change notification settings - Fork 1
/
web_get_iplayer.py
executable file
·2708 lines (2179 loc) · 115 KB
/
web_get_iplayer.py
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/python3 -u
"""
For full details, see the README.md in
https://github.com/speculatrix/web_get_iplayer
This script operates in two modes:
1/ a web interface to find programs using the same APIs
that the android apps use to find TV and Radio programs,
and then queue them for downloading
2/ a cron job to process the queues and call get_iplayer to
download the programs
3/ an RSS feed generator - coming soon!
(c) 2015,2016,2017 & 2018 by Paul Mansfield
Released under GPLv3 or later by the author
Get the JW player from here:
https://ssl.p.jwpcdn.com/player/download/jwplayer-7.12.8.zip
Unpack that so that the content appear as a directory called jwplayer-7.12.8
under your htdocs directory; then in settings ensure Flv7Uri has the correct URI
Please forgive the hacky nature of the code, this was my first python
program of any size
Variables starting p_ are parameters provided directly by the user
of the web UI and therefore must be considered dangerous
"""
# pylint:disable=bad-whitespace
# pylint:disable=too-many-arguments
# pylint:disable=too-many-branches
# pylint:disable=too-many-lines
# pylint:disable=too-many-locals
# pylint:disable=too-many-statements
# pylint:disable=line-too-long
import base64
import cgi
import cgitb
import codecs
import configparser
from collections import OrderedDict
#import datetime
import hashlib
import json
import os
from os.path import expanduser
import psutil
import pwd
import re # now have two problems
import shutil
import signal
import stat
import sys
import time
import urllib3
#####################################################################################################################
# Globals
# use ConfigParse to manage the settings
my_settings = configparser.ConfigParser()
PATH_OF_SCRIPT = os.path.dirname(os.path.realpath(__file__))
CGI_PARAMS = cgi.FieldStorage()
#####################################################################################################################
# constants
dbg_level = 0 # default value no debug
# the HTML document root (please make a subdirectory called python_errors off webroot which is writable by web daemon)
# this is hopefully the only thing you ever need to change
#DOCROOT_DEFAULT = '/var/www/html'
DOCROOT_DEFAULT = '/home/iplayer'
# state files, queues, logs and so on are stored in this directory
CONTROL_DIR = '/var/lib/web_get_iplayer'
# the settings file is stored in the control directory
SETTINGS_FILE = 'web_get_iplayer.settings'
SETTINGS_SECTION = 'user'
# default values of the settings when being created
SETTINGS_DEFAULTS = { 'base_url' : '/iplayer' , # relative URL direct to the iplayer files
'directory' : '1' , # automatically store downloads in sub-directory
'download_args' : '--nocopyright --raw --thumb --thumbsize 192',
'flash_height' : '720' , # standard flashhd BBC video rez
'flash_width' : '1280' , # ...
'get_iplayer' : PATH_OF_SCRIPT + '/get_iplayer' , # full get_iplayer path
'http_proxy' : '' , # http proxy, blank if not set
'iplayer_directory' : '/home/iplayer' , # file system location of downloaded files
'max_download_par' : '1' , # maximum download processes in parallel
'max_recent_items' : '5' , # maximum recent items
'max_trnscd_par' : '1' , # maximum transcoding processes in parallel
'quality_audio' : 'best,hlsaachigh,hlsaacstd' , # flashaachigh, flashaacstd etc
'quality_video' : 'best,hlshd,hlsvhigh,hlsstd' , # decreasing priority
'trnscd_cmd_audio' : '/usr/local/bin/m4a-to-mp3.sh' , # this command is passed two args input & output
'trnscd_cmd_video' : '/usr/local/bin/ts-to-mp4.sh' , # this command is passed two args input & output
'Flv5Enable' : '0' , # whether to show the JWplayer 7 column
'Flv5Uri' : '/jwmediaplayer-5.8' , # URI where the JW "longtail" JW5 player was unpacked
'Flv5UriSWF' : '/player.swf' , # the swf of the JW5 player
'Flv5UriJS' : '/swfobject.js' , # the jscript of the JW5 player
'Flv6Enable' : '0' , # whether to show the JWplayer 7 column
'Flv5Key' : '' , # JW Player 5 Key, leave blank if you don't have one
'Flv6Uri' : '/jwplayer-6-11' , # URI where the JW "longtail" JW6 player was unpacked
'Flv6UriJS' : '/jwplayer.js' , # the jscript of the JW6 player
'Flv6Key' : '' , # JW Player 6 Key, leave blank if you don't have one
'Flv7Enable' : '1' , # whether to show the JWplayer 7 column
'Flv7Uri' : '/jwplayer-7.12.8' , # URI where the JW "longtail" JW7 player was unpacked
'Flv7UriJS' : '/jwplayer.js' , # the jscript of the JW6 player
'Flv7Key' : '' , # JW Player 7 Key, leave blank if you don't have one
}
TRANSCODE_COMMANDS = { 'M4A_MP3':
{ 'name' : 'M4A to MP3',
'mediatype' : 'audio',
'command' : '/usr/local/bin/m4a-to-mp3.sh',
'inext' : 'm4a',
'outext' : 'mp3',
},
'TS_MP4':
{ 'name' : 'TS to MP4',
'mediatype' : 'video',
'command' : '/usr/local/bin/ts-to-mp4.sh',
'inext' : 'ts',
'outext' : 'mp4',
},
'FLV_MP4' :
{ 'name' : 'FLV to MP4',
'mediatype' : 'video',
'command' : '/usr/local/bin/flv-to-mp4.sh',
'inext' : 'flv',
'outext' : 'mp4',
},
}
TRANSCODE_RESOLUTIONS = OrderedDict( [ ('original' , 'original resolution'),
('1920x1080' , '1920x1080 1080p' ),
('1280x720' , '1280x720 720p' ),
('1024x600' , '1024x600 WVGA' ),
('720x576' , '720x576 PAL' ),
('720x416' , '720x416 NTSC' ),
('360x288' , '360x288 qPAL' ),
('720x208' , '360x208 qNTSC' ),
] )
# file types which are images
IMAGE_FILE_SUFFIXES = [ '.jpg',
'.png',
]
# which video files to show from the download folder
MEDIA_FILE_SUFFIXES = [ '.avi',
'.flv',
'.m4a',
'.m4v',
'.mov',
'.mp3',
'.mp4',
'.ts',
]
# files of this type can be played with JW Player
JWPLAYABLE_SUFFIXES = [ '.flv',
'.m4a',
'.m4v',
'.mp4',
'.mp3',
]
# it seems everybody has the same API key, so we'll use a very common USer AGent string to not draw attention to ourselves
USAG = 'BBCiPlayer/4.4.0.235 (Nexus5; Android 4.4.4)'
# API_KEY from http://polling.bbc.co.uk/appconfig/iplayerradio/android/2.9.0/config.json
API_KEY = 'bLBgJDghrAMaZA1eSFB8TbqOTraEJbUa' # iplayer radio key
#API_KEY = 'q5wcnsqvnacnhjap7gzts9y6' # stopped working sometime about August 2018
# these URLs have been discovered using tcpdump whilst watching the android iplayer app
URL_LIST = {
'config' : 'http://ibl.api.bbci.co.uk/appconfig/iplayer/android/4.4.0/config.json',
'highlights' : 'http://ibl.api.bbci.co.uk/ibl/v1/home/highlights?lang=en&rights=mobile&availability=available&api_key=',
'popular' : 'http://ibl.api.bbci.co.uk/ibl/v1/groups/popular/episodes?rights=mobile&page=2&per_page=20&availability=available&api_key=',
'search_video' : 'http://search-suggest.api.bbci.co.uk/search-suggest/suggest?q={0}&scope=iplayer&format=bigscreen-2&mediatype=video&mediaset=android-phone-rtmp-high&apikey=' + API_KEY,
#'search_video_by_brand' : 'http://ibl.api.bbci.co.uk/ibl/v1/programmes/{0}?rights=mobile&availability=available&initial_child_count=1&api_key=' + API_KEY,
'search_episodes_video' : 'http://ibl.api.bbci.co.uk/ibl/v1/programmes/{0}/episodes?rights=mobile&availability=available&page=1&per_page=200&api_key=' + API_KEY,
'search_video_recomm' : 'http://ibl.api.bbci.co.uk/ibl/v1/episodes/{0}/recommendations?rights=mobile&availability=available&page=1&per_page=200&api_key=' + API_KEY,
'search_audio' : 'http://search-suggest.api.bbci.co.uk/search-suggest/suggest?q={0}&format=suggest&category_site=programmes&category_media_type=audio&apikey=' + API_KEY,
#'search_audio' : 'http://data.bbc.co.uk/search-suggest/suggest?q={0}&scope=iplayer&format=bigscreen-2&mediatype=audio&mediaset=android-phone-rtmp-high&apikey=' + API_KEY,
#'search_audio_by_brand' : 'http://ibl.api.bbci.co.uk/ibl/v1/programmes/{0}?rights=mobile&availability=available&mediatype=audio&initial_child_count=1&api_key=' + API_KEY,
#'search_episodes_audio' : 'http://ibl.api.bbci.co.uk/ibl/v1/episodes/{0}?rights=mobile&availability=available&mediatype=audio&api_key=' + API_KEY, #FIXME
'search_episodes_audio' : 'http://ibl.api.bbci.co.uk/ibl/v1/programmes/{0}/episodes?rights=mobile&availability=available&mediatype=audio&page=1&per_page=200&api_key=' + API_KEY,
'search_audio_recomm' : 'http://ibl.api.bbci.co.uk/ibl/v1/episodes/{0}/recommendations?rights=mobile&availability=available&page=1&per_page=200&api_key=' + API_KEY, #FIXME
'development' : 'http://ibl.api.bbci.co.uk/ibl/v1/programmes/{0}/episodes?rights=mobile&availability=available&page=1&per_page=200&api_key=' + API_KEY,
}
MEDIATYPES = { 'video', 'audio', }
HTML_ESCAPE_TABLE = {
'"': """ ,
"'": "'" ,
" ": "+" ,
}
HTML_UNESCAPE_TABLE = {
'"': '"' ,
"'": "'" ,
"+": " " ,
}
INPUT_FORM_ESCAPE_TABLE = {
'"': """ ,
"'": "'" ,
}
QUEUE_FIELDS = [ 'inode', 'pid', 'title', 'subtitle',
'mediatype', 'quality', 'force',
'trnscd_cmd_method', 'trnscd_rez',
'TT_submitted', 'TT_started', 'TT_finished',
'status', 'unix_pid',
]
SUBMIT_QUEUE = 'submit.txt' # where the web page submits/enqueues
PENDING_QUEUE = 'pending.txt' # cron job takes submit and appends to pending
ACTIVE_QUEUE = 'active.txt' # the currently running download
RECENT_ITEMS = 'recent.txt' # recently downloaded
TRNSCD_QUE_FIELDS = [ 'inode', 'pid', 'title', 'subtitle', 'mediatype',
'trnscd_cmd_method', 'trnscd_rez',
'TT_submitted', 'TT_started', 'TT_finished',
'status',
]
TRNSCDE_SUB_QUEUE = 'transcode_submit.txt' # submit queue for transcoding
TRNSCDE_ACT_QUEUE = 'transcode_active.txt' # active transcoding
TRNSCDE_REC_QUEUE = 'transcode_recent.txt' # recent transcoding
FAVOURITES_FIELDS = [ 'pid', 'pid_type', 'autodownload', 'mediatype', 'TT_added', 'title', 'subtitle', ]
FAVOURITES_FILE = 'favourites.txt' # saved brands, series, searches
URL_GITHUB_HASH_SELF = 'https://api.github.com/repos/speculatrix/web_get_iplayer/contents/web_get_iplayer.py'
URL_GITHUB_HASH_GETIPLAYER = 'https://api.github.com/repos/get-iplayer/get_iplayer/contents/get_iplayer'
# whitespace was used a lot above to make more readable, but it upsets pylint
# Xpylint:enable=bad-whitespace
#####################################################################################################################
def get_github_hash_self():
"""calculates the git hash of the version of this script in github"""
githubhash = 'UNKNOWN'
try:
opener = urllib2.build_opener()
json_data = json.load(opener.open(URL_GITHUB_HASH_SELF))
githubhash = json_data['sha']
except urllib2.HTTPError:
print('get_github_hash_self: Exception urllib2.HTTPError')
githubhash = 'urllib2.HTTPError:'
return githubhash
#####################################################################################################################
def get_github_hash_get_iplayer():
"""calculates the git hash of the version of the get_iplayer script in github"""
githubhash = 'UNKNOWN'
try:
opener = urllib2.build_opener()
json_data = json.load(opener.open(URL_GITHUB_HASH_GETIPLAYER))
githubhash = json_data['sha']
except urllib2.HTTPError:
print('get_github_hash_self: Exception urllib2.HTTPError')
githubhash = 'urllib2.HTTPError:'
return githubhash
#####################################################################################################################
def get_githash_self():
"""calculates the git hash of the running script"""
# stat this file
fullfile_name = __file__
fullfile_stat = os.stat(fullfile_name)
# read this entire file into memory
fullfile_content = ''
with open(fullfile_name, 'r') as fullfile_fh:
fullfile_content = fullfile_fh.read()
# do what "git hash-object" does
sha_obj = hashlib.sha1()
sha_obj.update('blob %d\0' % fullfile_stat.st_size)
sha_obj.update(fullfile_content)
return sha_obj.hexdigest()
#####################################################################################################################
def get_githash_get_iplayer():
"""calculates the git hash of the local copy of the get_iplayer script"""
# stat the get_iplayer file
fullfile_name = my_settings.get(SETTINGS_SECTION, 'get_iplayer')
fullfile_stat = os.stat(fullfile_name)
# read the entire get_iplayer file into memory
fullfile_content = ''
with open(fullfile_name, 'r') as fullfile_fh:
fullfile_content = fullfile_fh.read()
# do what "git hash-object" does
sha_obj = hashlib.sha1()
sha_obj.update('blob %d\0' % fullfile_stat.st_size)
sha_obj.update(fullfile_content)
return sha_obj.hexdigest()
#####################################################################################################################
def check_load_config_file():
"""check there's a config file which is writable;
returns 0 if OK, -1 if the rest of the page should be aborted,
> 0 to trigger rendering of the settings page"""
# who am i?
my_euser_id = os.geteuid()
my_egroup_id = os.getegid()
config_bad = 1
config_file_name = os.path.join(CONTROL_DIR, SETTINGS_FILE)
################################################
# verify that CONTROL_DIR exists and is writable
try:
qdir_stat = os.stat(CONTROL_DIR)
except OSError:
print('''Error, directory "%s" doesn\'t appear to exist.
Please do the following - needs root:
\tsudo mkdir "%s" && sudo chgrp %s "%s" && sudo chmod g+ws "%s"''' % (CONTROL_DIR, CONTROL_DIR, str(my_egroup_id), CONTROL_DIR, CONTROL_DIR) )
config_bad = -1
return config_bad # error so severe, no point in continuing
# owned by me and writable by me, or same group as me and writable through that group?
if ( (qdir_stat.st_uid == my_euser_id and (qdir_stat.st_mode & stat.S_IWUSR) != 0)
or (qdir_stat.st_gid == my_egroup_id and (qdir_stat.st_mode & stat.S_IWGRP) != 0) ):
#print('OK, %s exists and is writable' % CONTROL_DIR)
config_bad = 0
else:
print('''Error, won\'t be able to write to directory "%s".
Please do the following:
\tsudo chgrp %s "%s" && sudo chmod g+ws "%s"''' % (CONTROL_DIR, str(my_egroup_id), CONTROL_DIR, CONTROL_DIR, ) )
config_bad = -1
return config_bad # error so severe, no point in continuing
########
# verify the settings file exists and is writable
if not os.path.isfile(config_file_name):
print('''Error, can\'t open "%s" for reading.
Please do the following - needs root:
\tsudo touch "%s" && sudo chgrp %s "%s" && sudo chmod g+w "%s"''' % (config_file_name, config_file_name, str(my_egroup_id), config_file_name, config_file_name) )
config_bad = -1
return config_bad
# file is zero bytes?
config_stat = os.stat(config_file_name)
if config_stat.st_size == 0:
print('Config file is empty, please go to settings and submit to save\n')
config_bad = 1
return config_bad
# owned by me and writable by me, or same group as me and writable through that group?
if ( ( config_stat.st_uid == my_euser_id and (config_stat.st_mode & stat.S_IWUSR) != 0)
or ( config_stat.st_gid == my_egroup_id and (config_stat.st_mode & stat.S_IWGRP) != 0) ):
config_bad = 0
else:
print('''Error, won\'t be able to write to file "%s"
Please do the following - needs root:
\tsudo chgrp %s "%s" && sudo chmod g+w %s''' % (config_file_name, config_file_name, my_egroup_id, config_file_name, ) )
config_bad = 1
return config_bad
########
# verify can open the config file, by reading the contents
try:
my_settings.read(config_file_name)
#print('Debug, successfully opened %s' % (config_file_name, ) )
config_bad = 0
except NameError:
print('Fatal Error, failed loading config %s\n' % config_file_name)
config_bad = 1
return config_bad
except AttributeError:
config_bad = 1
print('Fatal Error, config %s missing item\n' % config_file_name)
return config_bad
# check that all the settings we know about were actually created
# in the my_settings hash
for setting in SETTINGS_DEFAULTS:
try:
my_settings.get(SETTINGS_SECTION, setting)
except configparser.NoOptionError:
print('Warning, there is no settings value for "%s", please go to settings, check values and save<br />' % (setting, ))
########
# verify can write in the directory where files are downloaded
iplayer_directory = ''
try:
iplayer_directory = my_settings.get(SETTINGS_SECTION, 'iplayer_directory')
except configparser.NoOptionError:
print('Config appears incomplete, please go to settings and submit to save')
config_bad = 1
return config_bad
except configparser.NoSectionError:
print('Config appears incomplete, please go to settings and submit to save')
config_bad = 1
return config_bad
try:
idir_stat = os.stat(iplayer_directory)
except OSError:
print('''Error, directory %s doesn\'t appear to exist.
Please execute the following - needs root:
# sudo mkdir %s && sudo chgrp %d %s && sudo chmod g+ws %s''' % (iplayer_directory, iplayer_directory, my_egroup_id, iplayer_directory, iplayer_directory, ) )
config_bad = 1
return config_bad
# owned by me and writable by me, or same group as me and writable through that group?
if ( ( idir_stat.st_uid == my_euser_id and (idir_stat.st_mode & stat.S_IWUSR) != 0)
or ( idir_stat.st_gid == my_egroup_id and (idir_stat.st_mode & stat.S_IWGRP) != 0) ):
config_bad = 0
#print('Debug, directory "%s" exists and is writable' % (iplayer_directory, ))
else:
print('''Error, won\'t be able to write to %s
Please do the following - needs root:
# sudo chgrp %d %s && sudo chmod g+ws %s''' % (iplayer_directory, my_egroup_id, iplayer_directory, iplayer_directory, ))
config_bad = 1
return config_bad
# verify that the queue submission file is writable IF it exists
s_q_f_name = os.path.join(CONTROL_DIR, SUBMIT_QUEUE)
try:
qfile_stat = os.stat(s_q_f_name)
# owned by me and writable by me, or same group as me and writable through that group?
if ( ( qfile_stat.st_uid == my_euser_id and (qfile_stat.st_mode & stat.S_IWUSR) != 0)
or ( qfile_stat.st_gid == my_egroup_id and (qfile_stat.st_mode & stat.S_IWGRP) != 0) ):
#print('OK, %s exists and is writable' % (s_q_f_name, ))
config_bad = 0
else:
print('''Error, won\'t be able to write to %s
Please do the following - needs root:
# sudo chgrp %d %s && sudo chmod g+w %s''' % (s_q_f_name, my_egroup_id, CONTROL_DIR, s_q_f_name, ) )
config_bad = 1
return config_bad
except OSError: # it's fine for file to not exist
#print('OK, %s doesn\'t exist' % (s_q_f_name, ))
config_bad = 0
#print('Debug, dropped through to end of check_load_config_file')
# verify that get_iplayer has a directory to write to
get_iplayer_dir = os.path.join(expanduser("~"), '.get_iplayer', )
if not os.path.isdir(get_iplayer_dir):
print('''Error, directory %s doesn\'t appear to exist.
Please do the following - needs root:
# sudo mkdir %s && sudo chown %d:%d %s && sudo chmod g+ws %s''' % (get_iplayer_dir, get_iplayer_dir, my_euser_id, my_egroup_id, get_iplayer_dir, get_iplayer_dir, ) )
config_bad = 1
# check that the get_iplayer program exists
get_iplayer_binary = my_settings.get(SETTINGS_SECTION, 'get_iplayer')
if not os.path.isfile(get_iplayer_binary):
print('''Error, get_iplayer program not found.
Please fix the configuration for get_iplayer below, or download the program and make it executable with the following commands.
# sudo wget -O %s https://raw.githubusercontent.com/get-iplayer/get_iplayer/master/get_iplayer
# sudo chmod ugo+x %s''' % (get_iplayer_binary, get_iplayer_binary, ) )
config_bad = 1
# check that the get_iplayer program is executable
if os.path.isfile(get_iplayer_binary) and not os.access(get_iplayer_binary, os.X_OK):
print('''Error, get_iplayer program is not executable.
Make it executable with the following command:
# sudo chmod ugo+x %s''' % (get_iplayer_binary, ))
config_bad = 1
# need swffile for the rtmpdump program to work
swffile = expanduser("~") + '/' + '.swfinfo'
if os.path.isfile(get_iplayer_binary) and not os.path.isfile(swffile):
print('''Error, file %s doesn\'t appear to exist.
Please do the following - needs root:
# sudo touch %s && sudo chgrp %d %s && sudo chmod g+w %s''' % (swffile, swffile, my_egroup_id, swffile, swffile, ))
config_bad = 1
return config_bad
#####################################################################################################################
def page_kill(p_unix_pid):
"""sends a kill to the process ID.. very dangerous!!"""
if p_unix_pid != '':
try:
unix_pid = int(p_unix_pid)
if p_unix_pid > 0:
os.kill(unix_pid, signal.SIGQUIT)
# FIXME! this should really check the process to verify that it's the get_iplayer task!
print('<p><b>Killed</b>, unix pid %d was sent a CTRL-C</p>' % (unix_pid, ))
except ValueError:
print('<p><b>Error</b>, unix pid %s supplied was invalid</p>' % (p_unix_pid, ))
else:
print('<p><b>Error</b>, no unix pid supplied</p>')
#####################################################################################################################
def cron_run_download():
""" this is the function called when in cron mode to process download queue"""
global dbg_level
# get active queue, if it's not empty, then exit as only one download may be active
# FIXME! allow multiple active downloads
active_queue = []
aqi = 0 # count pending queue entries, -1 if queue couldn't be read
a_q_f_name = os.path.join(CONTROL_DIR, ACTIVE_QUEUE)
if os.path.isfile(a_q_f_name):
aqi = read_queue(active_queue, a_q_f_name)
if aqi > 0:
print('Info, active queue is not empty, so cron downloads terminating')
return 0
# get pending queue
pend_queue = []
pqi = 0 # count pending queue entries, -1 if queue couldn't be read
p_q_f_name = os.path.join(CONTROL_DIR, PENDING_QUEUE)
if os.path.isfile(p_q_f_name):
pqi = read_queue(pend_queue, p_q_f_name)
if pqi == -1:
print('Error, aborting cron job, couldn\'t read pending queue file')
exit(1)
else:
print('Info, pending queue file didn\'t exist, it will be created')
# rename the submission queue file to a temporary name, then sleep.
# this is to mitigate the race condition of the web interface
# writing an entry just at that moment.
sub_queue = []
sqi = 0 # count submission queue entries, -1 if queue couldn't be read
s_q_f_name = os.path.join(CONTROL_DIR, SUBMIT_QUEUE)
s_q_f_tmp_name = s_q_f_name + '.tmp'
if os.path.isfile(s_q_f_name):
os.rename(s_q_f_name, s_q_f_tmp_name)
time.sleep(2)
sqi = read_queue(sub_queue, s_q_f_tmp_name)
os.remove(s_q_f_tmp_name)
if sqi == -1:
print('Warn, couldn\'t read submission queue file')
elif sqi > 0:
print('Info, sub_queue is now %s' % (str(sub_queue), ))
pend_queue.extend(sub_queue)
if write_queue(pend_queue, p_q_f_name) == -1:
print('Error, failed writing pending queue item to file %s' % (p_q_f_name, ))
else: # sqi == 0
print('Info, submission queue file is empty')
# recently completed
recent_queue = []
rci = 0 # count recent entries, -1 if queue couldn't be read
r_c_f_name = os.path.join(CONTROL_DIR, RECENT_ITEMS)
if os.path.isfile(r_c_f_name):
rci = read_queue(recent_queue, r_c_f_name)
if rci == -1:
print('Error, aborting cron job, couldn\'t read recent items file')
exit(1)
else:
print('Info, recent items list hasn\'t been created')
# transcode submissions
trnscd_sub_queue = []
tsi = 0 # count transcode submissions, -1 if queue couldn't be read
t_s_f_name = os.path.join(CONTROL_DIR, TRNSCDE_SUB_QUEUE)
if os.path.isfile(t_s_f_name):
tsi = read_queue(trnscd_sub_queue, t_s_f_name)
if tsi == -1:
print('Info, cron job, couldn\'t read trancode submission file')
else:
print('Info, transcode submission queue hasn\'t been created')
## now start processing the queues ##
first_item = []
if len(pend_queue) > 0:
#if pend_queue:
# pop the first item off the pending queue, and rewrite it
first_item = pend_queue.pop(0)
if write_queue(pend_queue, p_q_f_name) == -1:
print('Error, failed writing pending queue item to file %s' % (p_q_f_name, ))
first_item['TT_started'] = time.time()
first_item['status'] = 'now active'
print('pending queue now %s' % str(pend_queue))
active_queue.append(first_item)
print('active queue now %s' % str(active_queue))
if write_queue(pend_queue, p_q_f_name) == -1:
print('Error, failed writing submission queue item to %s' % (p_q_f_name, ))
# update active queue
if write_queue(active_queue, a_q_f_name) != -1:
print('Success, written active item %s to %s' % (str(active_queue), a_q_f_name, ))
#else:
#print('Pending queue is empty')
print('first item on queue %s' % str(first_item))
if len(first_item) > 0:
#if first_item:
print('Info, will start downloading %s' % (str(first_item), ))
first_item['status'] = 'attempting download'
log_dir = os.path.join(CONTROL_DIR, 'logs')
if not os.path.isdir(log_dir):
print('Info, CONTROL_DIR %s, need to make directory %s' % (CONTROL_DIR, log_dir, ))
os.mkdir(log_dir)
#os.lchmod(log_dir, 0775)
log_file = os.path.join(log_dir, first_item['pid'],)
# assemble the command to call get_iplayer
cmd = my_settings.get(SETTINGS_SECTION, 'get_iplayer') + ' ' + my_settings.get(SETTINGS_SECTION, 'download_args')
if first_item['force'] == 'y':
cmd = cmd + ' --force'
# set type - the BBC api uses video/audio, but get_iplayer uses tv/radio
if first_item['mediatype'] == 'video':
cmd = cmd + ' --type ' + 'tv'
else:
cmd = cmd + ' --type ' + 'radio'
# set quality mode
cmd = cmd + ' --quality ' + first_item['quality']
# set the pid
cmd = cmd + ' --pid ' + first_item['pid']
# redirect output
cmd = cmd + ' >> ' + log_file + ' 2>&1'
if dbg_level > 0:
print('calling shell to do %s' % (cmd, ))
os.chdir(my_settings.get(SETTINGS_SECTION, 'iplayer_directory'))
# FIXME! set the directory to a subdirectory matching
# FIXME! the first letter of the program.
get_iplayer_pid = os.fork()
if get_iplayer_pid:
first_item['unix_pid'] = get_iplayer_pid
# update active queue
if write_queue(active_queue, a_q_f_name) != -1:
print('Success, written active item %s to %s' % (str(active_queue), a_q_f_name, ))
os.wait()
else: # the sub process runs get_iplayer
# let the parent rewrite the active queue with our pid, this is
# a bodge but hopefully we won't encounter a race condition
time.sleep(1)
sys_error = os.system(cmd)
#subprocess.check_call(cmd, stdout=log_file, stderror=log_file)
if sys_error != 0:
print('Error, get_iplayer returned error code %d' % (sys_error, ))
first_item['status'] = 'execution of get_iplayer failed with error %d' % (sys_error, )
else:
first_item['status'] = 'download probably successful'
# record when the download completed
first_item['TT_finished'] = time.time()
# set active queue empty now the system() call finished
# FIXME! remove an individual item to allow for parallelism
active_queue = []
active_file = os.path.join(CONTROL_DIR, ACTIVE_QUEUE)
if write_queue(active_queue, active_file) == -1:
print('Error, failed to write empty active file')
else:
print('Success, written empty active file')
# attempt to get node number of the downloaded file
# as this makes it much easier to track if we end up
# with multiple items having transcoded it
first_item['inode'] = find_media_file_inode_by_pid(first_item['pid'])
first_item['img_inode'] = find_image_file_inode_by_pid(first_item['pid'])
first_item['unix_pid'] = ''
# append the most recent download to recent
recent_queue.append(first_item)
# shorten recent queue to max allowed in settings
while len(recent_queue) >= int(my_settings.get(SETTINGS_SECTION, 'max_recent_items')):
print('removing oldest item from recent items queue')
recent_queue.pop(0)
if write_queue(recent_queue, r_c_f_name) == -1:
print('Error, failed to write recent items file')
else:
print('Success, written recent items file')
# if transcode was requested, append to queue
if 'trnscd_cmd_method' in first_item and first_item['trnscd_cmd_method'] != '':
print('Info, trnscd_cmd_method was set, adding item to transcode queue')
# FIXME! check that the queue doesn't already contain an identical task
trnscd_item = { 'inode' : first_item['inode'],
'img_inode' : first_item['img_inode'],
'pid' : first_item['pid'],
'title' : first_item['title'],
'subtitle' : first_item['subtitle'],
'mediatype' : first_item['mediatype'],
'trnscd_cmd_method' : first_item['trnscd_cmd_method'],
'trnscd_rez' : first_item['trnscd_rez'],
'TT_submitted' : time.time(),
'TT_started' : '',
'TT_finished' : '',
'status' : 'queued',
}
trnscd_sub_queue.append(trnscd_item)
if write_queue(trnscd_sub_queue, t_s_f_name) == -1:
print('Error, failed to write transcode submission queue')
else:
print('Success, written transcode submission queue')
return 0
#####################################################################################################################
def cron_run_transcode():
""" this is the function called when in cron mode to process transcode queue"""
global dbg_level
######################### grab all the queues
# transcode active
trnscd_act_queue = []
tsi = 0 # count transcode submissions, -1 if queue couldn't be read
t_a_f_name = os.path.join(CONTROL_DIR, TRNSCDE_ACT_QUEUE)
if os.path.isfile(t_a_f_name):
tai = read_queue(trnscd_act_queue, t_a_f_name)
if tai == -1:
print('Info, cron job, couldn\'t read trancode active file')
else:
print('Info, transcode active queue hasn\'t been created')
# FIXME! allow parallel transcodes
if len(trnscd_act_queue) > 0:
print('Info, a transcode is already active')
return 0
# transcode submissions
trnscd_sub_queue = []
tsi = 0 # count transcode submissions, -1 if queue couldn't be read
t_s_f_name = os.path.join(CONTROL_DIR, TRNSCDE_SUB_QUEUE)
if os.path.isfile(t_s_f_name):
tsi = read_queue(trnscd_sub_queue, t_s_f_name)
if tsi == -1:
print('Info, cron job, couldn\'t read trancode submission file')
else:
print('Info, transcode submission queue hasn\'t been created')
# transcode recent
trnscd_rec_queue = []
tri = 0 # count recent submissions, -1 if queue couldn't be read
t_r_f_name = os.path.join(CONTROL_DIR, TRNSCDE_REC_QUEUE)
if os.path.isfile(t_s_f_name):
tri = read_queue(trnscd_rec_queue, t_r_f_name)
if tri == -1:
print('Info, cron job, couldn\'t read trancode recents file')
else:
print('Info, transcode submission recents hasn\'t been created')
######################### see if anything needs transcoding
if len(trnscd_sub_queue):
print('Info, transcode submission queue wasn\'t empty')
first_item = trnscd_sub_queue.pop(0)
if write_queue(trnscd_sub_queue, t_s_f_name) == -1:
print('Error, failed writing transcode submission queue to file %s' % (t_s_f_name, ))
trnscd_act_queue.append(first_item)
first_item['TT_started'] = time.time()
if write_queue(trnscd_act_queue, t_a_f_name) == -1:
print('Error, failed writing transcode active queue to file %s' % (t_a_f_name, ))
# break the file name up into parts, create a new file name according
# to how we transcode it, and generate a command to transcode
orig_file = find_file_name_by_inode(int(first_item['inode']))
if orig_file == "":
print('Error, failed to find file whose inode is %s' % (first_item['inode'], ))
first_item['status'] = 'failed to find file'
else:
first_item['status'] = 'attempting transcode'
file_prefix, _file_ext = os.path.splitext(orig_file)
trnscd_prefix = file_prefix.replace('original', 'transcoded')
trnscd_prefix = trnscd_prefix.replace('default', 'transcoded')
trnscd_prefix = trnscd_prefix.replace('editorial', 'transcoded')
rezopts = ''
fnameadd = ''
if 'trnscd_rez' in first_item and first_item['trnscd_rez'] != '':
if first_item['trnscd_rez'] == '' or first_item['trnscd_rez'] != 'original':
rezopts = ' -s %s' % (first_item['trnscd_rez'], )
fnameadd = '-%s' % (first_item['trnscd_rez'], )
cmd = '%s %s %s %s%s.%s' % (TRANSCODE_COMMANDS[first_item['trnscd_cmd_method']]['command'],
rezopts,
orig_file,
trnscd_prefix,
fnameadd,
TRANSCODE_COMMANDS[first_item['trnscd_cmd_method']]['outext'],
)
log_dir = os.path.join(CONTROL_DIR, 'logs')
if not os.path.isdir(log_dir):
print('Info, CONTROL_DIR %s, need to make directory %s' % (CONTROL_DIR, log_dir, ))
os.mkdir(log_dir)
#os.lchmod(log_dir, 0775)
log_file = os.path.join(log_dir, first_item['pid'],)
# redirect output
cmd = cmd + ' >> ' + log_file + ' 2>&1'
#if dbg_level > 0:
print('calling shell to do %s' % (cmd, ))
os.chdir(my_settings.get(SETTINGS_SECTION, 'iplayer_directory'))
# FIXME! set the directory to a subdirectory matching...
# FIXME! the first letter of the program.
#subprocess.check_call(cmd, stdout=log_file, stderror=log_file)
sys_error = os.system(cmd)
if sys_error != 0:
print('Error, transcode returned error code %d' % (sys_error, ))
first_item['status'] = 'execution of transcode script failed with error %d' % (sys_error, )
else:
first_item['status'] = 'transcode probably successful'
# copy the image if possible
if first_item['img_inode'] != '':
old_image = find_file_name_by_inode(int(first_item['img_inode']))
new_image = '%s%s.jpg' % (trnscd_prefix, fnameadd, )
print('Debug, trnscd_prefix %s, fnameadd %s, copyfile "%s" "%s"' % (trnscd_prefix, fnameadd, old_image, new_image, ))
if os.path.isfile(new_image):
print('Error, new_image "%s" file exists' % (new_image, ))
new_image = ''
if old_image != '' and new_image != '':
try:
shutil.copyfile(old_image, new_image)
except IOError: # need to prevent copyfile from crashing the script
print('Error, shutil_copyfile failed with exception')
trnscd_act_queue = []
if write_queue(trnscd_act_queue, t_a_f_name) == -1:
print('Error, failed writing transcode active queue to file %s' % (t_a_f_name, ))
first_item['TT_finished'] = time.time()
trnscd_rec_queue.append(first_item)
# shorten recent queue to max allowed in settings
while len(trnscd_rec_queue) >= int(my_settings.get(SETTINGS_SECTION, 'max_recent_items')):
print('removing oldest item from transcode recent items queue')
trnscd_rec_queue.pop(0)
if write_queue(trnscd_rec_queue, t_r_f_name) == -1:
print('Error, failed writing transcode recents list to file %s' % (t_r_f_name, ))
return 0
#####################################################################################################################
def delete_files_by_inode(p_dir, inode_list, del_img_flag):
"""scan the downloaded list of files and delete any whose inode matches
one in the list"""
sub_dir = os.path.join(my_settings.get(SETTINGS_SECTION, 'iplayer_directory'), p_dir)
#file_scsan = os.scandir(sub_dir) # sadly not in std python2.7
file_list = os.listdir(sub_dir)
for file_name in sorted(file_list):
full_file_path = os.path.join(sub_dir, file_name)
if os.path.isfile(full_file_path): # prevent statting a file as may be a jpg we just deleted
file_stat = os.stat(full_file_path)
#print('considering file %s which has inode %d\n<br >' % (full_file_path, file_stat[stat.ST_INO], ))
if str(file_stat[stat.ST_INO]) in inode_list:
print('file %s is being deleted \n<br >' % (full_file_path, ))
try:
os.remove(full_file_path)
except OSError as err: # for some reason the above works but throws exception
print('error deleting %s code %s\n<br />' % (full_file_path, err, ))
if del_img_flag:
file_prefix, _ignore = os.path.splitext(full_file_path)
image_file_name = file_prefix + '.jpg'
if os.path.isfile(image_file_name):
print('image %s is being deleted \n<br >' % (image_file_name, ))
try:
os.remove(image_file_name)
except OSError: # for some reason the above works but throws exception
print('error deleting %s\n<br />' % (image_file_name, ))
else:
print('there was no image file %s to be deleted\n<br >' % (image_file_name, ))
#####################################################################################################################
def find_media_file_inode_by_pid(p_pid):
"""this is used to find the inode of a file to uniquely identify it when freshly downloaded,
it only checks for files with a media file type, so ignores jpegs for example.
returns zero if a file wasn't found.
FIXME! doesn't look in subdirectories.
"""
file_inode = 0
print('Debug, find_media_file_inode_by_pid pid "%s"' % (p_pid, ))
file_list = os.listdir(my_settings.get(SETTINGS_SECTION, 'iplayer_directory'))
for file_name in file_list:
file_prefix, file_ext = os.path.splitext(file_name)
#print('Debug, find_media_file_inode_by_pid file_prefix "%s" has ext "%s"' % (file_prefix, file_ext, ))
if p_pid in file_prefix and file_ext in MEDIA_FILE_SUFFIXES:
file_inode = os.stat(file_name).st_ino
print('Debug, found inode %d for pid %s' % (file_inode, p_pid))
return file_inode
#####################################################################################################################
def find_image_file_inode_by_pid(p_pid):
"""this is used to find the image file name matching a program pid.
Note: When downloading radio programs, the image file name doesn't
exactly match the media file.
returns blank if a file wasn't found.
FIXME! doesn't look in subdirectories.
"""
file_inode = 0
print('Debug, find_image_file_inode_by_pid pid "%s"' % (p_pid, ))
file_list = os.listdir(my_settings.get(SETTINGS_SECTION, 'iplayer_directory'))
for file_name in file_list:
file_prefix, file_ext = os.path.splitext(file_name)
#print('Debug, find_image_file_inode_by_pid file_prefix "%s" has ext "%s"' % (file_prefix, file_ext, ))
if p_pid in file_prefix and file_ext in IMAGE_FILE_SUFFIXES:
file_inode = os.stat(file_name).st_ino
print('Debug, found inode %d for pid %s' % (file_inode, p_pid))
return file_inode
#####################################################################################################################
def find_file_name_by_inode(inode):
"""given an inode, finds the file name relative to the iplayer_directory
returns blank if a file wasn't found.