forked from primaeval/plugin.video.iptv.recorder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
3496 lines (2743 loc) · 132 KB
/
main.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
# -*- coding: utf-8 -*-
from xbmcswift2 import Plugin, ListItem
from HTMLParser import HTMLParser
from collections import namedtuple
from datetime import datetime, timedelta, tzinfo
from language import get_string as _
from struct import *
import base64
import calendar
import chardet
import ctypes
import glob
import gzip
import StringIO
import json
import os, os.path
import platform
import random
import re
import requests
import shutil
import sqlite3
import stat
import subprocess
import sys
import threading
import time
import urllib
import uuid
import xbmc, xbmcaddon, xbmcvfs, xbmcgui, xbmcplugin
def addon_id():
return xbmcaddon.Addon().getAddonInfo('id')
def log(v):
xbmc.log(repr(v), xbmc.LOGERROR)
plugin = Plugin()
big_list_view = True
if plugin.get_setting("multiline") == "true":
CR = "[CR]"
else:
CR = ""
def get_icon_path(icon_name):
return "special://home/addons/%s/resources/img/%s.png" % (addon_id(), icon_name)
def remove_formatting(label):
label = re.sub(r"\[/?[BI]\]", '', label, flags=re.I)
label = re.sub(r"\[/?COLOR.*?\]", '', label, flags=re.I)
return label
def escape( str ):
str = str.replace("&", "&")
str = str.replace("<", "<")
str = str.replace(">", ">")
str = str.replace("\"", """)
return str
def unescape( str ):
str = str.replace("<", "<")
str = str.replace(">", ">")
str = str.replace(""", "\"")
str = str.replace("&", "&")
return str
def delete(path):
dirs, files = xbmcvfs.listdir(path)
for file in files:
xbmcvfs.delete(path+file)
for dir in dirs:
delete(path + dir + '/')
xbmcvfs.rmdir(path)
def rmdirs(path):
path = xbmc.translatePath(path)
dirs, files = xbmcvfs.listdir(path)
for dir in dirs:
rmdirs(os.path.join(path,dir))
xbmcvfs.rmdir(path)
def find(path):
path = xbmc.translatePath(path)
all_dirs = []
all_files = []
dirs, files = xbmcvfs.listdir(path)
for file in files:
file_path = os.path.join(path,file)
all_files.append(file_path)
for dir in dirs:
dir_path = os.path.join(path,dir)
all_dirs.append(dir_path)
new_dirs, new_files = find(os.path.join(path, dir))
for new_dir in new_dirs:
new_dir_path = os.path.join(path,dir,new_dir)
all_dirs.append(new_dir_path)
for new_file in new_files:
new_file = os.path.join(path,dir,new_file)
all_files.append(new_file)
return all_dirs, all_files
@plugin.route('/play_channel/<channelname>')
def play_channel(channelname):
channelname = channelname.decode("utf8")
#channelname = urllib.quote_plus(channelname.encode("utf8"))
conn = sqlite3.connect(xbmc.translatePath('%sxmltv.db' % plugin.addon.getAddonInfo('profile')))
c = conn.cursor()
channel = c.execute("SELECT * FROM streams WHERE name=?", (channelname, )).fetchone()
if not channel:
return
uid, name, tvg_name, tvg_id, tvg_logo, groups, url = channel
#plugin.set_resolved_url(url)
xbmc.Player().play(url)
@plugin.route('/play_channel_external/<channelname>')
def play_channel_external(channelname):
channelname = channelname.decode("utf8")
#channelname = urllib.quote_plus(channelname.encode("utf8"))
conn = sqlite3.connect(xbmc.translatePath('%sxmltv.db' % plugin.addon.getAddonInfo('profile')))
c = conn.cursor()
channel = c.execute("SELECT * FROM streams WHERE name=?", (channelname, )).fetchone()
if not channel:
return
uid, name, tvg_name, tvg_id, tvg_logo, groups, url = channel
if url:
cmd = [plugin.get_setting('external.player')]
args = plugin.get_setting('external.player.args')
if args:
cmd.append(args)
cmd.append(url)
#TODO shell?
subprocess.Popen(cmd,shell=windows())
@plugin.route('/play_external/<path>')
def play_external(path):
cmd = [plugin.get_setting('external.player')]
args = plugin.get_setting('external.player.args')
if args:
cmd.append(args)
cmd.append(xbmc.translatePath(path))
subprocess.Popen(cmd,shell=windows())
def xml2local(xml):
#TODO combine
return utc2local(xml2utc(xml))
def utc2local(utc):
timestamp = calendar.timegm(utc.timetuple())
local = datetime.fromtimestamp(timestamp)
return local.replace(microsecond=utc.microsecond)
def str2dt(string_date):
format ='%Y-%m-%d %H:%M:%S'
try:
res = datetime.strptime(string_date, format)
except TypeError:
res = datetime(*(time.strptime(string_date, format)[0:6]))
return utc2local(res)
def total_seconds(td):
return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
@plugin.route('/jobs')
def jobs():
conn = sqlite3.connect(xbmc.translatePath('%sxmltv.db' % plugin.addon.getAddonInfo('profile')), detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cursor = conn.cursor()
jobs = cursor.execute("SELECT * FROM jobs ORDER by channelname, start").fetchall()
items = []
now = datetime.now()
for uid, uuid, channelid, channelname, title, start, stop, type in jobs:
local_stop = utc2local(stop)
if local_stop < now:
continue
url = ""
channel = cursor.execute("SELECT * FROM streams WHERE tvg_id=?", (channelid, )).fetchone()
if channel:
uid, name, tvg_name, tvg_id, tvg_logo, groups, url = channel
echannelname=name.encode("utf8")
context_items = []
context_items.append((_("Delete Job"), 'XBMC.RunPlugin(%s)' % (plugin.url_for(delete_job, job=uuid))))
context_items.append((_("Delete All Jobs"), 'XBMC.RunPlugin(%s)' % (plugin.url_for(delete_all_jobs))))
if url:
context_items.append((_("Play Channel"), 'XBMC.RunPlugin(%s)' % (plugin.url_for(play_channel, channelname=echannelname))))
if plugin.get_setting('external.player'):
context_items.append((_("Play Channel External"), 'XBMC.RunPlugin(%s)' % (plugin.url_for(play_channel_external, channelname=echannelname))))
label = "%s [COLOR yellow]%s[/COLOR] %s[COLOR grey]%s - %s[/COLOR] %s" % (channelname, title, CR, utc2local(start), utc2local(stop), type)
items.append({
'label': label,
'path': plugin.url_for(delete_job, job=uuid),
'context_menu': context_items,
'thumbnail':get_icon_path('recordings'),
})
return items
@plugin.route('/rules')
def rules():
conn = sqlite3.connect(xbmc.translatePath('%sxmltv.db' % plugin.addon.getAddonInfo('profile')), detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cursor = conn.cursor()
rules = cursor.execute('SELECT uid, channelid, channelname, title, start AS "start [TIMESTAMP]", stop AS "stop [TIMESTAMP]", description, type, name FROM rules ORDER by channelname, title, start, stop').fetchall()
items = []
for uid, channelid, channelname, title, start, stop, description, type, rulename in rules:
url = ""
channel = cursor.execute("SELECT * FROM streams WHERE tvg_id=?", (channelid, )).fetchone()
if channel:
cuid, name, tvg_name, tvg_id, tvg_logo, groups, url = channel
echannelname=name.encode("utf8")
context_items = []
context_items.append((_("Delete Rule"), 'XBMC.RunPlugin(%s)' % (plugin.url_for(delete_rule, uid=uid))))
context_items.append((_("Delete All Rules"), 'XBMC.RunPlugin(%s)' % (plugin.url_for(delete_all_rules))))
if url:
context_items.append((_("Play Channel"), 'XBMC.RunPlugin(%s)' % (plugin.url_for(play_channel, channelname=echannelname))))
if plugin.get_setting('external.player'):
context_items.append((_("Play Channel External"), 'XBMC.RunPlugin(%s)' % (plugin.url_for(play_channel_external, channelname=echannelname))))
if type.startswith("WATCH"):
type = type.replace("WATCH ","")
type_label = "WATCH"
elif type.startswith("REMIND"):
type = type.replace("REMIND ","")
type_label = "REMIND"
else:
type_label = "RECORD"
label = "TODO"
if type == "ALWAYS":
label = "%s [COLOR yellow]%s[/COLOR] %s ALWAYS" % (channelname, title, type_label)
elif type == "DAILY":
label = "%s [COLOR yellow]%s[/COLOR] %s[COLOR grey]%s - %s[/COLOR] %s DAILY" % (channelname, title, CR, utc2local(start).time(), utc2local(stop).time(), type_label)
elif type == "WEEKLY":
label = "%s [COLOR yellow]%s[/COLOR] %s[COLOR grey]%s - %s[/COLOR] %s WEEKLY" % (channelname, title, CR, utc2local(start).time(), utc2local(stop).time(), type_label)
elif type == "SEARCH":
label = "%s [COLOR yellow]%s[/COLOR] %s SEARCH" % (channelname, title, type_label)
elif type == "PLOT":
label = "%s [COLOR yellow](%s)[/COLOR] %s PLOT" % (channelname, description, type_label)
if rulename:
label = "(%s) %s" % (rulename,label)
items.append({
'label': label,
'path': plugin.url_for(delete_rule, uid=uid),
'context_menu': context_items,
'thumbnail':get_icon_path('recordings'),
})
return items
@plugin.route('/delete_all_rules')
def delete_all_rules(ask=True):
if ask and not (xbmcgui.Dialog().yesno("IPTV Recorder", _("Delete All Rules?"))):
return
conn = sqlite3.connect(xbmc.translatePath('%sxmltv.db' % plugin.addon.getAddonInfo('profile')), detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cursor = conn.cursor()
conn.execute("DELETE FROM rules")
conn.commit()
conn.close()
refresh()
@plugin.route('/delete_rule/<uid>')
def delete_rule(uid, ask=True):
conn = sqlite3.connect(xbmc.translatePath('%sxmltv.db' % plugin.addon.getAddonInfo('profile')), detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cursor = conn.cursor()
if ask and not (xbmcgui.Dialog().yesno("IPTV Recorder", _("Cancel Record?"))):
return
conn.execute("DELETE FROM rules WHERE uid=?", (uid, ))
conn.commit()
conn.close()
refresh()
@plugin.route('/delete_all_jobs')
def delete_all_jobs(ask=True):
if ask and not (xbmcgui.Dialog().yesno("IPTV Recorder", _("Delete All Jobs?"))):
return
conn = sqlite3.connect(xbmc.translatePath('%sxmltv.db' % plugin.addon.getAddonInfo('profile')), detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cursor = conn.cursor()
conn.execute("DELETE FROM jobs")
conn.commit()
conn.close()
refresh()
@plugin.route('/delete_job/<job>')
def delete_job(job, kill=True, ask=True):
conn = sqlite3.connect(xbmc.translatePath('%sxmltv.db' % plugin.addon.getAddonInfo('profile')), detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cursor = conn.cursor()
job_details = cursor.execute("SELECT uuid FROM jobs WHERE uuid=?", (job, )).fetchone()
if not job_details:
return
if ask and not (xbmcgui.Dialog().yesno("IPTV Recorder", _("Cancel Record?"))):
return
if windows() and plugin.get_setting('task.scheduler') == 'true':
cmd = ["schtasks", "/delete", "/f", "/tn", job]
subprocess.Popen(cmd, shell=True)
else:
xbmc.executebuiltin('CancelAlarm(%s, True)' % job)
directory = "special://profile/addon_data/plugin.video.iptv.recorder/jobs/"
xbmcvfs.mkdirs(directory)
pyjob = directory + job + ".py"
pid = xbmcvfs.File(pyjob+'.pid').read()
xbmcvfs.delete(pyjob)
xbmcvfs.delete(pyjob+'.pid')
if pid and kill:
if windows():
subprocess.Popen(["taskkill", "/im", pid], shell=True)
else:
#TODO correct kill switch
subprocess.Popen(["kill", "-9", pid])
conn.execute("DELETE FROM jobs WHERE uuid=?", (job, ))
conn.commit()
conn.close()
refresh()
def windows():
if os.name == 'nt':
return True
else:
return False
def android_get_current_appid():
with open("/proc/%d/cmdline" % os.getpid()) as fp:
return fp.read().rstrip("\0")
@plugin.route('/delete_ffmpeg')
def delete_ffmpeg():
if xbmc.getCondVisibility('system.platform.android'):
ffmpeg_dst = '/data/data/%s/ffmpeg' % android_get_current_appid()
xbmcvfs.delete(ffmpeg_dst)
def ffmpeg_location():
ffmpeg_src = xbmc.translatePath(plugin.get_setting('ffmpeg'))
if xbmc.getCondVisibility('system.platform.android'):
ffmpeg_dst = '/data/data/%s/ffmpeg' % android_get_current_appid()
if (plugin.get_setting('ffmpeg') != plugin.get_setting('ffmpeg.last')) or (not xbmcvfs.exists(ffmpeg_dst) and ffmpeg_src != ffmpeg_dst):
xbmcvfs.copy(ffmpeg_src, ffmpeg_dst)
plugin.set_setting('ffmpeg.last',plugin.get_setting('ffmpeg'))
ffmpeg = ffmpeg_dst
else:
ffmpeg = ffmpeg_src
if ffmpeg:
try:
st = os.stat(ffmpeg)
if not (st.st_mode & stat.S_IXUSR):
try:
os.chmod(ffmpeg, st.st_mode | stat.S_IXUSR)
except:
pass
except:
pass
if xbmcvfs.exists(ffmpeg):
return ffmpeg
else:
xbmcgui.Dialog().notification("IPTV Recorder", _("ffmpeg exe not found!"))
@plugin.route('/record_once/<programmeid>/<channelid>/<channelname>')
def record_once(programmeid, channelid, channelname, do_refresh=True, watch=False, remind=False):
channelid = channelid.decode("utf8")
channelname = channelname.decode("utf8")
start = None
stop = None
threading.Thread(target=record_once_thread,args=[programmeid, do_refresh, watch, remind, channelid, channelname, start, stop, False, None]).start()
@plugin.route('/watch_once/<programmeid>/<channelid>/<channelname>')
def watch_once(programmeid, channelid, channelname, do_refresh=True, watch=True, remind=False):
channelid = channelid.decode("utf8")
channelname = channelname.decode("utf8")
start = None
stop = None
threading.Thread(target=record_once_thread,args=[programmeid, do_refresh, watch, remind, channelid, channelname, start, stop, False, None]).start()
@plugin.route('/remind_once/<programmeid>/<channelid>/<channelname>')
def remind_once(programmeid, channelid, channelname, do_refresh=True, watch=False, remind=True):
channelid = channelid.decode("utf8")
channelname = channelname.decode("utf8")
start = None
stop = None
threading.Thread(target=record_once_thread,args=[programmeid, do_refresh, watch, remind, channelid, channelname, start, stop, False, None]).start()
@plugin.route('/record_one_time/<channelname>')
def record_one_time( channelname):
#channelid = channelid.decode("utf8")
channelname = channelname.decode("utf8")
utcnow = datetime.utcnow()
ts = time.time()
utc_offset = total_seconds(datetime.fromtimestamp(ts) - datetime.utcfromtimestamp(ts))
date = xbmcgui.Dialog().input("Start Date",type=xbmcgui.INPUT_DATE)
if not date:
return
day, month, year = date.split('/')
start = xbmcgui.Dialog().input("Start Time",type=xbmcgui.INPUT_TIME)
if not start:
return
hms = start.split(':')
hour = hms[0]
min = hms[1]
start = utcnow.replace(day=int(day), month=int(month), year=int(year), hour=int(hour), minute=int(min), second=0, microsecond=0) - timedelta(seconds=utc_offset)
stop = xbmcgui.Dialog().input("Stop",type=xbmcgui.INPUT_TIME)
if not stop:
return
hms = stop.split(':')
hour = hms[0]
min = hms[1]
stop = utcnow.replace(day=int(day), month=int(month), year=int(year), hour=int(hour), minute=int(min), second=0, microsecond=0) - timedelta(seconds=utc_offset)
if stop < start:
stop = stop + timedelta(days=1)
name = xbmcgui.Dialog().input("Rule Name").decode("utf8")
do_refresh = False
watch = False
remind = False
channelid = None
threading.Thread(target=record_once_thread,args=[None, do_refresh, watch, remind, channelid, channelname, start, stop, False, name]).start()
@plugin.route('/record_and_play/<channelname>')
def record_and_play(channelname):
#channelid = channelid.decode("utf8")
channelname = channelname.decode("utf8")
utcnow = datetime.utcnow()
ts = time.time()
utc_offset = total_seconds(datetime.fromtimestamp(ts) - datetime.utcfromtimestamp(ts))
start = utcnow - timedelta(seconds=utc_offset)
hours = xbmcgui.Dialog().input("Hours",type=xbmcgui.INPUT_NUMERIC,defaultt="4")
#log(hours)
stop = utcnow - timedelta(seconds=utc_offset) + timedelta(hours=int(hours))
do_refresh = False
watch = False
remind = False
channelid = None
threading.Thread(target=record_once_thread,args=[None, do_refresh, watch, remind, channelid, channelname, start, stop, True, None]).start()
time.sleep(5)
return recordings()
@plugin.route('/record_once_time/<channelid>/<channelname>/<start>/<stop>')
def record_once_time(channelid, channelname, start, stop, do_refresh=True, watch=False, remind=True, title=None):
if channelid:
channelid = channelid.decode("utf8")
channelname = channelname.decode("utf8")
threading.Thread(target=record_once_thread,args=[None, do_refresh, watch, remind, channelid, channelname, start, stop, False, title]).start()
@plugin.route('/record_epg/<channelname>/<name>/<start>/<stop>')
def record_epg(channelname, name, start, stop):
channelname = channelname.decode("utf8")
name = name.decode("utf8")
start = get_utc_from_string(start.decode("utf8"))
stop = get_utc_from_string(stop.decode("utf8"))
log("Scheduling record for '{}: {} ({} to {})'".format(channelname, name, start, stop))
do_refresh = False
watch = False
remind = False
channelid = None
threading.Thread(target=record_once_thread,args=[None, do_refresh, watch, remind, channelid, channelname, start, stop, False, name]).start()
def get_utc_from_string(date_string):
utcnow = datetime.utcnow()
ts = time.time()
utc_offset = total_seconds(datetime.fromtimestamp(ts) - datetime.utcfromtimestamp(ts))
r = re.search(r'(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):\d{2}', date_string)
if r:
year, month, day, hour, minute = r.group(1), r.group(2), r.group(3), r.group(4), r.group(5)
return utcnow.replace(day=int(day), month=int(month), year=int(year), hour=int(hour), minute=int(minute),
second=0, microsecond=0) - timedelta(seconds=utc_offset)
def record_once_thread(programmeid, do_refresh=True, watch=False, remind=False, channelid=None, channelname=None, start=None,stop=None, play=False, title=None):
#TODO check for ffmpeg process already recording if job is re-added
#channelname = urllib.unquote_plus(channelname)
conn = sqlite3.connect(xbmc.translatePath('%sxmltv.db' % plugin.addon.getAddonInfo('profile')), detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cursor = conn.cursor()
if programmeid:
programme = cursor.execute('SELECT channelid, title, sub_title, start AS "start [TIMESTAMP]", stop AS "stop [TIMESTAMP]", date, description, episode, categories FROM programmes WHERE uid=? LIMIT 1', (programmeid, )).fetchone()
channelid, title, sub_title, start, stop, date, description, episode, categories = programme
nfo = {"programme":{"channelid":channelid, "title":title, "sub_title":sub_title, "start":datetime2timestamp(start), "stop":datetime2timestamp(stop), "date":date, "description":description, "episode":episode, "categories":categories}}
else:
#title = None
nfo = {}
#log((channelid,channelname))
if channelid:
channel = cursor.execute("SELECT * FROM streams WHERE tvg_id=? AND tvg_name=?", (channelid, channelname)).fetchone()
if not channel:
channel = cursor.execute("SELECT * FROM streams WHERE tvg_id=? AND name=?", (channelid, channelname)).fetchone()
else:
channel = cursor.execute("SELECT * FROM streams WHERE name=?", (channelname,)).fetchone()
if not channel:
channel = cursor.execute("SELECT * FROM streams WHERE tvg_name=?", (channelname,)).fetchone()
if not channel:
xbmc.log("No channel %s" % channelname, xbmc.LOGERROR)
return
uid, name, tvg_name, tvg_id, tvg_logo, groups, url = channel
thumbnail = tvg_logo
if not channelname:
channelname = name
nfo["channel"] = {"channelname":channelname, "thumbnail":thumbnail, "channelid":tvg_id}
#log(url)
if not url:
xbmc.log("No url for %s" % channelname, xbmc.LOGERROR)
return
url_headers = url.split('|', 1)
url = url_headers[0]
headers = {}
if len(url_headers) == 2:
sheaders = url_headers[1]
aheaders = sheaders.split('&')
if aheaders:
for h in aheaders:
k, v = h.split('=', 1)
headers[k] = urllib.unquote_plus(v)
local_starttime = utc2local(start)
local_endtime = utc2local(stop)
if programmeid:
ftitle = sane_name(title)
if sub_title:
fsub_title = sane_name(sub_title)
else:
ftitle = sane_name(title)
fchannelname = sane_name(channelname)
folder = ""
movie = False
series = False
if programmeid:
if episode:
if episode == "MOVIE":
movie = True
if date and len(date) == 4:
filename = "%s (%s)" % (ftitle, date)
folder = "%s (%s) - %s - %s" % (ftitle, date, fchannelname, local_starttime.strftime("%Y-%m-%d %H-%M"))
else:
folder = ftitle
filename = "%s - %s - %s" % (ftitle, fchannelname, local_starttime.strftime("%Y-%m-%d %H-%M"))
else:
series = True
folder = ftitle
filename = "%s %s - %s - %s" % (ftitle, episode, fchannelname, local_starttime.strftime("%Y-%m-%d %H-%M"))
else:
folder = ftitle
if sub_title:
filename = "%s %s - %s - %s" % (ftitle, fsub_title, fchannelname, local_starttime.strftime("%Y-%m-%d %H-%M"))
else:
filename = "%s - %s - %s" % (ftitle, fchannelname, local_starttime.strftime("%Y-%m-%d %H-%M"))
else:
folder = fchannelname
if ftitle:
filename = "%s - %s - %s" % (ftitle, fchannelname, local_starttime.strftime("%Y-%m-%d %H-%M"))
else:
filename = "%s - %s" % (fchannelname, local_starttime.strftime("%Y-%m-%d %H-%M"))
if watch:
type = "WATCH"
elif remind:
type = "REMIND"
else:
type = "RECORD"
job = cursor.execute("SELECT * FROM jobs WHERE channelid=? AND channelname=? AND start=? AND stop=? AND type=?", (channelid, channelname, start, stop, type)).fetchone()
if job:
return
before = int(plugin.get_setting('minutes.before') or "0")
after = int(plugin.get_setting('minutes.after') or "0")
local_starttime = local_starttime - timedelta(minutes=before)
local_endtime = local_endtime + timedelta(minutes=after)
now = datetime.now()
if (local_starttime < now) and (local_endtime > now):
local_starttime = now
immediate = True
else:
immediate = False
length = local_endtime - local_starttime
seconds = total_seconds(length)
kodi_recordings = xbmc.translatePath(plugin.get_setting('recordings'))
ffmpeg_recordings = plugin.get_setting('ffmpeg.recordings') or kodi_recordings
if series:
dir = os.path.join(kodi_recordings, "TV", folder)
ffmpeg_dir = os.path.join(ffmpeg_recordings, "TV", folder)
elif movie:
dir = os.path.join(kodi_recordings, "Movies", folder)
ffmpeg_dir = os.path.join(ffmpeg_recordings, "Movies", folder)
else:
dir = os.path.join(kodi_recordings, "Other", folder)
ffmpeg_dir = os.path.join(ffmpeg_recordings, "Other", folder)
xbmcvfs.mkdirs(dir)
path = os.path.join(dir, filename)
json_path = path + '.json'
path = path + '.' + plugin.get_setting("ffmpeg.ext")
ffmpeg = ffmpeg_location()
if not ffmpeg:
return
if plugin.get_setting('json',bool):
json_nfo = json.dumps(nfo)
f = xbmcvfs.File(json_path,'w')
f.write(json_nfo)
f.close()
cmd = [ffmpeg]
cmd.append("-i")
cmd.append(url)
for h in headers:
cmd.append("-headers")
cmd.append("%s:%s" % (h, headers[h]))
probe_cmd = cmd
ffmpeg_recording_path = os.path.join(ffmpeg_dir, filename + '.' + plugin.get_setting("ffmpeg.ext"))
cmd = probe_cmd + ["-y", "-t", str(seconds), "-fflags","+genpts","-vcodec","copy","-acodec","copy"]
ffmpeg_reconnect = plugin.get_setting('ffmpeg.reconnect',bool)
if ffmpeg_reconnect:
cmd = cmd + ["-reconnect_at_eof", "1", "-reconnect_streamed", "1", "-reconnect_delay_max", "300"]
ffmpeg_args = plugin.get_setting('ffmpeg.args')
if ffmpeg_args:
cmd = cmd + ffmpeg_args.split(' ')
if (plugin.get_setting('ffmpeg.pipe') == 'true') and not (windows() and (plugin.get_setting('task.scheduler') == 'true')):
cmd = cmd + ['-f', 'mpegts','-']
else:
cmd.append(ffmpeg_recording_path.encode('utf8'))
post_command = plugin.get_setting('post.command')
post_cmd = post_command.split(' ')
post_cmd = [s.replace("$p",ffmpeg_recording_path.encode('utf8')).replace("$d",ffmpeg_dir.encode('utf8')).replace("$f",filename.encode('utf8') + '.' + plugin.get_setting("ffmpeg.ext")) for s in post_cmd]
directory = "special://profile/addon_data/plugin.video.iptv.recorder/jobs/"
xbmcvfs.mkdirs(directory)
job = str(uuid.uuid1())
pyjob = directory + job + ".py"
f = xbmcvfs.File(pyjob, 'wb')
f.write("# -*- coding: utf-8 -*-\n")
f.write("import os, subprocess, time\n")
debug = plugin.get_setting('debug.ffmpeg') == 'true'
if watch == False and remind == False:
if not (windows() and (plugin.get_setting('task.scheduler') == 'true')):
f.write("import xbmc,xbmcvfs,xbmcgui\n")
notification = 'xbmcgui.Dialog().notification("Recording: %s", "%s", sound=%s)\n' % (channelname, title, plugin.get_setting('silent')=="false")
f.write(notification.encode("utf8"))
f.write("cmd = %s\n" % repr(cmd))
if url.startswith('plugin://'):
f.write("player = xbmc.Player()\n")
f.write("player.play('%s')\n" % url.encode("utf8"))
f.write("new_url = ''\n")
f.write("for _ in range(60):\n")
f.write(" time.sleep(1)\n")
f.write(" if player.isPlaying():\n")
f.write(" new_url = player.getPlayingFile()\n")
f.write(" break\n")
f.write("time.sleep(1)\n")
f.write("player.stop()\n")
f.write("time.sleep(1)\n")
f.write("if new_url:\n")
f.write(" cmd[2] = new_url\n")
else:
f.write("cmd = %s\n" % repr(cmd))
if debug:
f.write("stdout = open(r'%s','w+')\n" % xbmc.translatePath(pyjob+'.stdout.txt'))
f.write("stderr = open(r'%s','w+')\n" % xbmc.translatePath(pyjob+'.stderr.txt'))
f.write("p = subprocess.Popen(cmd, stdout=stdout, stderr=stderr, shell=%s)\n" % windows())
else:
if (plugin.get_setting('ffmpeg.pipe') == 'true') and not (windows() and (plugin.get_setting('task.scheduler') == 'true')):
f.write("p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=%s)\n" % windows())
else:
f.write("p = subprocess.Popen(cmd, shell=%s)\n" % windows())
f.write("f = open(r'%s', 'w+')\n" % xbmc.translatePath(pyjob+'.pid'))
f.write("f.write(repr(p.pid))\n")
f.write("f.close()\n")
if (plugin.get_setting('ffmpeg.pipe') == 'true') and not (windows() and (plugin.get_setting('task.scheduler') == 'true')):
f.write('video = xbmcvfs.File(r"%s","wb")\n' % path.encode('utf8'))
f.write('playing = False\n')
f.write("while True:\n")
f.write(" data = p.stdout.read(1000000)\n")
f.write(" if data:\n")
f.write(" video.write(data)\n")
f.write(" else:\n")
f.write(" break\n")
if play:
f.write(" if not playing:\n")
f.write(" xbmc.Player().play(r'%s')\n" % path.encode('utf8'))
f.write(" playing = True\n")
f.write("video.close()\n")
else:
f.write("p.wait()\n")
if debug:
f.write("stderr.close()\n")
f.write("stdout.close()\n")
if not (windows() and (plugin.get_setting('task.scheduler') == 'true')):
notification = 'xbmcgui.Dialog().notification("Recording finished: %s", "%s", sound=%s)\n' % (channelname, title, plugin.get_setting('silent')=="false")
f.write(notification.encode("utf8"))
if post_command:
f.write("post_cmd = %s\n" % repr(post_cmd))
f.write("p = subprocess.Popen(post_cmd, shell=%s)\n" % windows())
#TODO copy file somewhere else
elif remind == True:
cmd = 'xbmcgui.Dialog().notification("%s", "%s", sound=%s)\n' % (channelname, title, plugin.get_setting('silent')=="false")
f.write("import xbmc, xbmcgui\n")
f.write("%s\n" % cmd.encode("utf8"))
else:
if (plugin.get_setting('external.player.watch') == 'true') or (windows() and (plugin.get_setting('task.scheduler') == 'true')):
cmd = [plugin.get_setting('external.player'), plugin.get_setting('external.player.args'), url]
f.write("cmd = %s\n" % repr(cmd))
f.write("p = subprocess.Popen(cmd, shell=%s)\n" % windows())
else:
cmd = 'xbmc.Player().play("%s")\n' % url
f.write("import xbmc\n")
f.write("%s\n" % cmd.encode("utf8"))
f.close()
if windows() and (plugin.get_setting('task.scheduler') == 'true') and remind == False:
if immediate:
cmd = 'RunScript(%s)' % (pyjob)
xbmc.executebuiltin(cmd)
else:
st = "%02d:%02d" % (local_starttime.hour, local_starttime.minute)
sd = "%02d/%02d/%04d" % (local_starttime.day, local_starttime.month, local_starttime.year)
cmd = ["schtasks", "/create", "/f", "/tn", job, "/sc", "once", "/st", st, "/sd", sd, "/tr", "%s %s" % (xbmc.translatePath(plugin.get_setting('python')), xbmc.translatePath(pyjob))]
subprocess.Popen(cmd, shell=True)
else:
now = datetime.now()
diff = local_starttime - now
minutes = ((diff.days * 86400) + diff.seconds) / 60
#minutes = 1
if minutes < 1:
if local_endtime > now:
cmd = 'RunScript(%s)' % (pyjob)
xbmc.executebuiltin(cmd)
else:
xbmcvfs.delete(pyjob)
return
else:
cmd = 'AlarmClock(%s, RunScript(%s), %d, True)' % (job, pyjob, minutes)
xbmc.executebuiltin(cmd)
conn.execute("INSERT OR REPLACE INTO jobs(uuid, channelid, channelname, title, start, stop, type) VALUES(?, ?, ?, ?, ?, ?, ?)",
[job, channelid, channelname, title, start, stop, type])
conn.commit()
conn.close()
if do_refresh:
refresh()
@plugin.route('/convert/<path>')
def convert(path):
input = xbmcvfs.File(path,'rb')
output = xbmcvfs.File(path.replace('.ts','.mp4'),'wb')
error = open(xbmc.translatePath("special://profile/addon_data/plugin.video.iptv.recorder/errors.txt"),"w")
cmd = [ffmpeg_location(),"-fflags","+genpts","-y","-i","-","-vcodec","copy","-acodec","copy","-f", "mpegts", "-"]
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=error, shell=windows())
t = threading.Thread(target=read_thread,args=[p,output])
t.start()
while True:
data = input.read(100000)
log(("read",len(data)))
if not data:
break
p.stdin.write(data)
p.stdin.close()
error.close()
def read_thread(p,output):
while True:
data = p.stdout.read(100000)
if not len(data):
break
output.write(data)
output.close()
@plugin.route('/renew_jobs')
def renew_jobs():
#TODO check for ffmpeg process already recording if job is re-added
conn = sqlite3.connect(xbmc.translatePath('%sxmltv.db' % plugin.addon.getAddonInfo('profile')), detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cursor = conn.cursor()
try:
jobs = cursor.execute("SELECT * FROM jobs").fetchall()
except:
return
for uid, uuid, channelid, channelname, title, start, stop, type in jobs:
local_starttime = utc2local(start)
local_endtime = utc2local(stop)
before = int(plugin.get_setting('minutes.before') or "0")
after = int(plugin.get_setting('minutes.after') or "0")
local_starttime = local_starttime - timedelta(minutes=before)
local_endtime = local_endtime + timedelta(minutes=after)
now = datetime.now()
if local_endtime < now:
delete_job(uuid,ask=False)
continue
if (local_starttime < now) and (local_endtime > now):
local_starttime = now
immediate = True
else:
immediate = False
directory = "special://profile/addon_data/plugin.video.iptv.recorder/jobs/"
xbmcvfs.mkdirs(directory)
job = uuid
pyjob = directory + job + ".py"
#TODO reduce time of job if already started
if windows() and (plugin.get_setting('task.scheduler') == 'true'):
if immediate:
cmd = 'RunScript(%s)' % (pyjob)
xbmc.executebuiltin(cmd)
else:
pass
else:
now = datetime.now()
diff = local_starttime - now
minutes = ((diff.days * 86400) + diff.seconds) / 60
#minutes = 1
if minutes < 1:
if local_endtime > now:
cmd = 'RunScript(%s)' % (pyjob)
xbmc.executebuiltin(cmd)
else:
xbmcvfs.delete(pyjob)
else:
cmd = 'AlarmClock(%s, RunScript(%s), %d, True)' % (job, pyjob, minutes)
xbmc.executebuiltin(cmd)
conn.close()
def sane_name(name):
if not name:
return
if windows() or (plugin.get_setting('filename.urlencode') == 'true'):
name = urllib.quote(name.encode("utf8"))
name = name.replace("%20",' ')
name = name.replace('/',"%2F")
else:
quote = {'"': '%22', '|': '%7C', '*': '%2A', '/': '%2F', '<': '%3C', ':': '%3A', '\\': '%5C', '?': '%3F', '>': '%3E'}
for char in quote:
name = name.replace(char, quote[char])
return name
def refresh():
containerAddonName = xbmc.getInfoLabel('Container.PluginName')
AddonName = xbmcaddon.Addon().getAddonInfo('id')
if (containerAddonName == AddonName) and (plugin.get_setting('refresh') == 'true') :
xbmc.executebuiltin('Container.Refresh')
@plugin.route('/record_daily_time/<channelname>')
def record_daily_time(channelname):
#channelid = channelid.decode("utf8")
channelname = channelname.decode("utf8")
utcnow = datetime.utcnow()
ts = time.time()
utc_offset = total_seconds(datetime.fromtimestamp(ts) - datetime.utcfromtimestamp(ts))
start = xbmcgui.Dialog().input("Start Time",type=xbmcgui.INPUT_TIME)
hms = start.split(':')
hour = hms[0]
min = hms[1]
start = utcnow.replace(hour=int(hour),minute=int(min),second=0,microsecond=0) - timedelta(seconds=utc_offset)
stop = xbmcgui.Dialog().input("Stop",type=xbmcgui.INPUT_TIME)
hms = stop.split(':')
hour = hms[0]
min = hms[1]
stop = utcnow.replace(hour=int(hour),minute=int(min),second=0,microsecond=0) - timedelta(seconds=utc_offset)
if stop < start:
stop = stop + timedelta(days=1)
name = xbmcgui.Dialog().input("Rule Name").decode("utf8")
conn = sqlite3.connect(xbmc.translatePath('%sxmltv.db' % plugin.addon.getAddonInfo('profile')), detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)