-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
recordService.py
2385 lines (1916 loc) · 105 KB
/
recordService.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/env python
# -*- coding: utf-8 -*-
# GNU General Public License
# m-TVGuide KODI Addon
# Copyright (C) 2020 Mariusz89B
# Copyright (C) 2016 Andrzej Mleczko
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see https://www.gnu.org/licenses.
# MIT License
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import sys
if sys.version_info[0] > 2:
PY3 = True
else:
PY3 = False
if PY3:
import configparser
else:
import ConfigParser
import os, threading, datetime, subprocess, unicodedata, time, re, copy
import xbmc, xbmcgui, xbmcvfs
from strings import *
import strings as strings2
from playService import BasePlayService
import serviceLib
from skins import Skin
from source import Program, Channel
if PY3:
import urllib.request, urllib.parse, urllib.error
import urllib.request as Request
from urllib.parse import quote
from urllib.error import HTTPError, URLError
else:
import urllib
import urllib2 as Request
from urllib2 import HTTPError, URLError
from urllib2 import quote
import requests
if xbmc.getCondVisibility('system.platform.android'):
SHELL = True
else:
SHELL = False
recordIcon = 'recordIcon.png'
downloadIcon = 'downloadIcon.png'
downloadNotificationName = strings(59985)
finishedDownloadNotificationName = strings(59986)
recordNotificationName = strings(69004)
finishedRecordNotificationName = strings(69005)
nonExistingRecordDirName = strings(69006)
nonExistingDownloadDirName = strings(69061)
failedRecordDialogName = strings(69007)
failedDownloadDialogName = strings(69059)
missingRecordBinaryString = strings(69008)
missingDownloadBinaryString = strings(69060)
maxNrOfReattempts = int(ADDON.getSetting('max_reattempts'))
minRecordedFileSize = 4097152 #Less then 4MB, remove downloaded data
ACTION_PARENT_DIR = 9
ACTION_PREVIOUS_MENU = 10
KEY_NAV_BACK = 92
sess = requests.Session()
UA = xbmc.getUserAgent()
try:
if PY3:
config = configparser.RawConfigParser()
else:
config = ConfigParser.RawConfigParser()
config.read(os.path.join(Skin.getSkinPath(), 'settings.ini'))
skin_resolution = config.getboolean("Skin", "resolution")
except:
skin_resolution = '720p'
def decodeBackslashPath(s):
if sys.version_info[0] < 3:
s = s.replace('\\', '/').decode('utf-8').encode('utf-8')
else:
s = s
return s
def decodePath(s):
if sys.version_info[0] < 3:
s = s.decode('utf-8')
else:
s = s
return s
def encodePath(s):
if sys.version_info[0] < 3:
s = s.encode('utf-8')
else:
s = s
return s
def asciiPath(s):
if sys.version_info[0] < 3:
s = s.decode('utf-8').encode('latin-1')
else:
s = s
return s
class proxydt(datetime.datetime):
@staticmethod
def strptime(date_string, format):
import time
return datetime.datetime(*(time.strptime(date_string, format)[0:6]))
datetime.proxydt = proxydt
class RecordTimer:
def __init__(self, startDate, startOffset, timer, programList):
self.startDate = startDate
self.startOffset = startOffset
self.timer = timer
self.programList = programList
class DownloadTimer:
def __init__(self, startDate, startOffset, timer, programList):
self.startDate = startDate
self.startOffset = startOffset
self.timer = timer
self.programList = programList
class RecordService(BasePlayService):
def __init__(self, epg):
BasePlayService.__init__(self)
if PY3:
self.rtmpdumpExe = xbmcvfs.translatePath(ADDON.getSetting('rtmpdumpExe'))
self.ffmpegdumpExe = xbmcvfs.translatePath(ADDON.getSetting('ffmpegExe'))
self.icon = os.path.join(xbmcvfs.translatePath(ADDON.getAddonInfo('path')), recordIcon)
self.dwicon = os.path.join(xbmcvfs.translatePath(ADDON.getAddonInfo('path')), downloadIcon)
self.recordDestinationPath = xbmcvfs.translatePath(ADDON.getSetting('record_folder'))
else:
self.rtmpdumpExe = xbmc.translatePath(ADDON.getSetting('rtmpdumpExe'))
self.ffmpegdumpExe = xbmc.translatePath(ADDON.getSetting('ffmpegExe'))
self.icon = os.path.join(xbmc.translatePath(ADDON.getAddonInfo('path')), recordIcon)
self.dwicon = os.path.join(xbmc.translatePath(ADDON.getAddonInfo('path')), downloadIcon)
self.recordDestinationPath = xbmc.translatePath(ADDON.getSetting('record_folder'))
self.rtmpdumpAvailable = os.path.isfile(self.rtmpdumpExe)
self.ffmpegdumpAvailable = os.path.isfile(self.ffmpegdumpExe)
self.useOnlyFFmpeg = ADDON.getSetting('use_only_ffmpeg')
self.epg = epg
self.threadList = list()
self.threadDownloadList = list()
self.timers = list()
self.timersdw = list()
self.cleanupTimer = None
self.cleanupDownloadTimer = None
self.ffmpegFormat = 'mpegts'
self.isDownload = False
self.program = None
self.processIsCanceled = False
self.strmUrl = None
self.archiveString = None
self.downloadDuration = 0
self.progress = None
self.downloadSize = 0
self.elapsedTime = 0
self.durationTime = 0
self.startOffsetDownload = 0
self.endOffsetDownload = 0
self.downloading = False
self.showDialogOk = False
if ADDON.getSetting('ffmpeg_dis_cop_un') == 'true':
self.ffmpegDisableCopyUnknown = True
else:
self.ffmpegDisableCopyUnknown = False
if 'avconv' in self.ffmpegdumpExe:
self.force_h264_mp4toannexb = True
else:
self.force_h264_mp4toannexb = False
if ADDON.getSetting('record_stop_playback') == 'true':
self.recordingStopsPlayback = True
else:
self.recordingStopsPlayback = False
if PY3:
try:
self.profilePath = xbmcvfs.translatePath(ADDON.getAddonInfo('profile'))
except:
self.profilePath = xbmcvfs.translatePath(ADDON.getAddonInfo('profile')).decode('utf-8')
else:
try:
self.profilePath = xbmc.translatePath(ADDON.getAddonInfo('profile'))
except:
self.profilePath = xbmc.translatePath(ADDON.getAddonInfo('profile')).decode('utf-8')
def getDistro(self):
if xbmc.getCondVisibility('System.HasAddon(service.coreelec.settings)'):
return "CoreElec"
elif xbmc.getCondVisibility('System.HasAddon(service.libreelec.settings)'):
return "LibreElec"
elif xbmc.getCondVisibility('System.HasAddon(service.osmc.settings)'):
return "OSMC"
else:
return "Kodi"
def convertTimedelta(self, duration):
days, seconds = duration.days, duration.seconds
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = (seconds % 60)
return minutes
def formatFileSize(self, num):
step_unit = 1000.0
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if num < step_unit:
return "%3.1f %s" % (num, x)
num /= step_unit
def calcFileSize(self, duration, bitrate, depth):
result = bitrate / depth * duration * 1000
return result
def createProgressDialog(self):
self.progress = xbmcgui.DialogProgressBG()
self.progress.create(strings(69056))
#xbmc.sleep(1000)
return self.progress
def downloadMenuCoreELEC(self, program):
self.dwnl = False
self.chkdate = True
self.program.startDate = self.startInputDialog(program.startDate)
if self.program.startDate is None:
return
self.program.endDate = self.endInputDialog(program.endDate)
if self.program.endDate is None:
return
self.calculatedStartDate = self.program.startDate
self.calculatedEndDate = self.program.endDate
self.dwnl = True
self.chkdate = True
if self.calculatedStartDate > self.calculatedEndDate:
self.dwnl = False
elif self.calculatedEndDate > datetime.datetime.now():
self.dwnl = False
self.chkdate = False
return [self.dwnl, self.chkdate, 0, 0]
def startInputDialog(self, startDate):
input_date = xbmcgui.Dialog().input(strings(70024), defaultt=str(startDate) , type=xbmcgui.INPUT_ALPHANUM)
if input_date:
try:
start = proxydt.strptime(str(input_date), '%Y-%m-%d %H:%M:%S')
return start
except:
xbmcgui.Dialog().notification(strings(57051), strings(60015), xbmcgui.NOTIFICATION_WARNING, sound=True)
self.startInputDialog(startDate)
def endInputDialog(self, endDate):
input_date = xbmcgui.Dialog().input(strings(70025), defaultt=str(endDate), type=xbmcgui.INPUT_ALPHANUM)
if input_date:
try:
end = proxydt.strptime(str(input_date), '%Y-%m-%d %H:%M:%S')
return end
except:
xbmcgui.Dialog().notification(strings(57051), strings(60015), xbmcgui.NOTIFICATION_WARNING, sound=True)
self.endInputDialog(endDate)
def renameFile(self, program):
filename = None
kb = xbmc.Keyboard(self.normalizeString(program.title) + '_' + str(program.startDate.strftime('%Y-%m-%d_%H-%M')) + '.mpeg','')
kb.setHeading(strings(60016))
kb.setHiddenInput(False)
kb.doModal()
c = kb.getText() if kb.isConfirmed() else None
if c == '': c = None
if c:
filename = c
if '.mpeg' not in filename:
xbmcgui.Dialog().notification(strings(30353), strings(60017))
return self.renameFile(program)
if filename:
filename = filename.replace('.mpeg', '')
program = Program(channel=Channel(id=program.channel.id, title=program.channel.title, logo=program.channel.logo, titles=program.channel.titles, streamUrl=program.channel.streamUrl), title=program.title, startDate=program.startDate, endDate=program.endDate, description=program.description, productionDate=program.productionDate, director=program.director, actor=program.actor, imageLarge=program.imageLarge, imageSmall=program.imageSmall, categoryA=program.categoryA, categoryB=program.categoryB, fileName=filename)
return program
def recordProgramGui(self, program, catchupList, watch=False, length=0):
self.program = program
self.showDialogOk = True
_program = None
self.isDownload = False
updateDB = False
try:
if not watch:
if self.calculateTimeDifference(program.endDate) <= 0:
if program.channel.title.upper() in [x.split('=')[0] for x in catchupList] and ADDON.getSetting('archive_support') == 'true' and program.startDate < datetime.datetime.now():
self.isDownload = True
if self.isProgramDownloadScheduled(program):
ret = xbmcgui.Dialog().yesno(strings(69064), strings(69063))
if ret:
self.epg.database.removeRecording(program)
self.cancelProgramDownload(program)
updateDB = True
elif program.recordingScheduled != 1:
if PY3:
res = xbmcgui.Dialog().yesno(strings(70006) + ' - ' + strings(57051), strings(31000).format(program.title) )
else:
res = xbmcgui.Dialog().yesno(strings(70006) + ' - ' + strings(57051), strings(31000).format(program.title.encode('utf-8').decode('utf-8')) )
if res:
if self.getDistro() != 'Kodi':
try:
saveRecording, chkdate, self.startOffsetDownload, self.endOffsetDownload = self.downloadMenuCoreELEC(program)
except:
return
else:
downloadMenu = DownloadMenu(program)
downloadMenu.doModal()
saveRecording, chkdate, self.startOffsetDownload, self.endOffsetDownload = downloadMenu.getOffsets()
if saveRecording:
program = self.renameFile(program)
if not program.fileName:
return
self.startOffsetDownload *= 60
self.endOffsetDownload *= 60
_program = self.epg.database.getPrograms(program.channel, program, self.program.startDate, self.program.endDate)
if _program is None:
_program = program
if self.scheduleDownload(_program, _program.startDate, _program.endDate):
self.epg.database.addRecording(_program, _program.startDate, _program.endDate)
updateDB = True
elif not chkdate:
xbmcgui.Dialog().ok(failedDownloadDialogName, strings(59998))
else:
self.epg.database.removeRecording(program)
self.abortProgramDownload(program)
updateDB = True
else:
xbmcgui.Dialog().ok(strings(70006) + ' - ' + strings(57051), strings(59987) )
return
if program.endDate > datetime.datetime.now() and self.isProgramRecordScheduled(program):
ret = xbmcgui.Dialog().yesno(strings(69000), strings(69009))
if ret:
self.epg.database.removeRecording(program)
self.cancelProgramRecord(program)
updateDB = True
elif program.recordingScheduled != 1:
if not self.isDownload:
recordMenu = RecordMenu(program)
recordMenu.doModal()
saveRecording, startOffset, endOffset = recordMenu.getOffsets()
if saveRecording:
program = self.renameFile(program)
if not program.fileName:
return
startOffset *= 60
endOffset *= 60
if self.scheduleRecording(program, startOffset, endOffset):
self.epg.database.addRecording(program, startOffset, endOffset)
updateDB = True
else:
self.epg.database.removeRecording(program)
self.abortProgramRecord(program)
updateDB = True
else:
startOffset = 0
endOffset = int(length) * 60
if self.scheduleRecording(program, startOffset, endOffset):
self.epg.database.addRecording(program, startOffset, endOffset)
updateDB = True
except:
deb('recordProgramGui exception: %s' % getExceptionString())
return updateDB
def scheduleDownload(self, program, startOffset, endOffset, delayRecording = 0):
program = copy.deepcopy(program)
if PY3:
deb('DownloadService scheduling download for program {}, starting at {}, start offset {}'.format(program.title, program.startDate, startOffset))
else:
deb('DownloadService scheduling download for program {}, starting at {}, start offset {}'.format(program.title.encode('utf-8'), program.startDate, startOffset))
if self.rtmpdumpAvailable == False and self.ffmpegdumpAvailable == False:
deb('DownloadService - no record application installed!')
self.showThreadedDialog(failedDownloadDialogName, "\n" + missingDownloadBinaryString + ' RTMPDUMP & FFMPEG.')
return False
if not self.checkIfDownloadDirExist():
return False
for element in self.getScheduledDownloadingsForThisTime(program.startDate):
if element.startOffset == startOffset:
programList = element.programList #Fetch already scheduled list of programs
for prog in programList:
if program.channel == prog.channel and program.startDate == prog.startDate:
return False #already on list
programList.append(program) #add one more
return True
programList = list()
programList.append(program)
timer = threading.Timer(0, self.downloadChannel, [program.startDate, startOffset])
self.timersdw.append(DownloadTimer(program.startDate, startOffset, timer, programList))
timer.start()
return True
def downloadChannel(self, startTime, startOffset):
deb('DownloadService downloadChannel startTime {}, startOffset {}'.format(startTime, startOffset))
try:
for element in self.getScheduledDownloadingsForThisTime(startTime):
if element.startOffset == startOffset:
programList = element.programList
self.timersdw.remove(element)
for program in programList:
urlList = self.epg.database.getStreamUrlList(program.channel)
try:
urlList = sorted(urlList, key=lambda x: x[1], reverse=True)
except:
pass
threadData = {'urlDownloadList' : urlList, 'program' : program, 'downloadHandle' : None, 'stopDownloadTimer' : None, 'terminateDownloadThread' : False}
thread = threading.Thread(name='downloadLoop', target = self.downloadLoop, args=[threadData])
self.threadDownloadList.append([thread, threadData])
for thread, threadData in self.threadDownloadList:
try:
thread.start()
except:
thread.join()
thread.start()
if not self.downloading:
self.processIsCanceled = False
self.startDownload(threadData)
except Exception as ex:
deb('downloadChannel Exception: {}'.format(ex))
def startDownload(self, threadData):
deb('startDownload')
diag = self.createProgressDialog()
durationTime = (self.program.endDate - self.program.startDate).total_seconds()
iDownsize = 0
while not (self.processIsCanceled or diag.isFinished()):
try:
program = self.getOutputFilename(threadData['program'], threadData['partNumber'])
dest = os.path.join(decodePath(self.recordDestinationPath), self.getOutputFilename(threadData['program'], threadData['partNumber']))
if xbmcvfs.exists(dest):
stat = os.stat(dest)
iDownsize = stat.st_size
except:
program = ''
iDownsize = 1000
if float(self.downloadSize) > 1:
iTotalSize = float(self.downloadSize)
else:
iTotalSize = 1000
self.stateCallBackFunction(program, iDownsize, iTotalSize, durationTime)
self.processIsCanceled = True
self.downloading = False
self.progress.close()
def stateCallBackFunction(self, program, iDownsize, iTotalSize, durationTime):
if self.progress.isFinished():
self.createProgressDialog()
if self.elapsedTime != 0:
elapsedTime = datetime.proxydt.strptime(str(self.elapsedTime), '%H:%M:%S.%f')
else:
elapsedTime = datetime.proxydt.strptime(str('00:00:00.01'), '%H:%M:%S.%f')
elapsedTime = (elapsedTime - datetime.datetime(1900, 1, 1, 0, 0)).total_seconds() + 5
iPercent = int(float(elapsedTime * 100) / durationTime)
if iTotalSize <= 1000:
TotalSize = '-'
elif iTotalSize < 5000000:
TotalSize = '0 MB'
else:
TotalSize = self.formatFileSize(iTotalSize)
if iDownsize < 5000000:
Downsize = '0 MB'
else:
Downsize = self.formatFileSize(int(iDownsize))
downloadSpeed = round(int(iDownsize) * 0.000008 / int(elapsedTime), 1)
self.progress.update(iPercent, str(program), str(Downsize) + ' / ' + str(TotalSize) + ', ' + str(downloadSpeed) + ' mbit/s')
if (self.progress.isFinished()) and not (self.processIsCanceled):
self.processIsCanceled = True
self.progress.close()
def StopAll(self):
self.processIsCanceled = True
self.downloading = False
try:
self.progress.close()
except:
pass
return
def downloadLoop(self, threadData):
threadData['success'] = False
threadData['notificationDisplayed'] = False
threadData['destinationFile'] = os.path.join(decodeBackslashPath(self.recordDestinationPath), encodePath(self.getOutputFilename(threadData['program'])))
threadData['partNumber'] = 1
threadData['nrOfReattempts'] = 0
threadData['downloadOptions'] = { 'forceRTMPDump' : False, 'settingsChanged' : False, 'force_h264_mp4toannexb' : self.force_h264_mp4toannexb }
threadData['downloadDuration'] = self.calculateDownloadTimeDifference(threadData['program'].startDate, threadData['program'].endDate, timeOffset = -5 )
while self.checkIfDownloadShouldContinue(threadData):
for url in threadData['urlDownloadList']:
try:
strmUrl = url[0]
except:
pass
if not self.checkIfDownloadShouldContinue(threadData):
break
threadData['downloadOptions']['forceRTMPDump'] = False
self.downloadUrl(strmUrl, threadData)
if threadData['downloadOptions']['settingsChanged'] == True and self.checkIfDownloadShouldContinue(threadData):
deb('DownloadService - detected settings change for downloaded stream - retrying download')
self.downloadUrl(strmUrl, threadData)
#Go to sleep, maybe after that any service will be free to use
for sleepTime in range(5):
if not self.checkIfDownloadShouldContinue(threadData):
break
time.sleep(1)
if PY3:
deb('DownloadService - end of download program: {}'.format(threadData['program'].title))
else:
deb('DownloadService - end of download program: {}'.format(threadData['program'].title.encode('utf-8')))
self.epg.database.removeRecording(threadData['program'])
threadData['notificationDisplayed'] = True
self.showEndDownloadNotification(threadData)
try:
self.progress.close()
except:
pass
if self.cleanupDownloadTimer is not None:
self.cleanupDownloadTimer.cancel()
self.cleanupDownloadTimer = threading.Timer(0.2, self.cleanupFinishedDownloadThreads)
self.cleanupDownloadTimer.start()
def downloadProgram(self, startDate, endDate):
startDate += datetime.timedelta(seconds=self.startOffsetDownload)
endDate += datetime.timedelta(seconds=self.endOffsetDownload)
try:
ProgramEndDate = datetime.proxydt.strptime(str(endDate), '%Y-%m-%d %H:%M:%S')
ProgramStartDate = datetime.proxydt.strptime(str(startDate), '%Y-%m-%d %H:%M:%S')
except:
ProgramEndDate = datetime.proxydt.strptime(str(datetime.datetime.now()), '%Y-%m-%d %H:%M:%S.%f')
ProgramStartDate = datetime.proxydt.strptime(str(datetime.datetime.now()), '%Y-%m-%d %H:%M:%S.%f')
try:
ProgramNowDate = datetime.proxydt.strptime(str(datetime.datetime.now()), '%Y-%m-%d %H:%M:%S.%f')
except:
ProgramNowDate = datetime.proxydt.strptime(str(datetime.datetime.now()), '%Y-%m-%d %H:%M:%S')
downloadProgram = ''
from time import mktime
n = datetime.datetime.now()
t = ProgramStartDate
e = ProgramEndDate
# Duration
durationCalc = int(((ProgramEndDate - ProgramStartDate).total_seconds() / 60.0))
duration = str(durationCalc)
# Offset
offsetCalc = int(((datetime.datetime.now() - ProgramStartDate).total_seconds() / 60.0))
offset = str(offsetCalc)
# UTC/LUTC
if PY3:
utc = str(int(datetime.datetime.timestamp(t)))
lutc = str(int(datetime.datetime.timestamp(e)))
else:
utc = str(int(time.mktime(t.timetuple())))
lutc = str(int(time.mktime(e.timetuple())))
# Datestring
year = t.strftime("%Y")
month = t.strftime("%m")
day = t.strftime("%d")
hour = t.strftime("%H")
minute = t.strftime("%M")
second = t.strftime("%S")
archivePlaylist = '{duration}, {offset}, {utc}, {lutc}, {y}, {m}, {d}, {h}, {min}, {s}'.format(
duration=duration, offset=offset, utc=utc, lutc=lutc, y=year, m=month, d=day, h=hour, min=minute, s=second)
if PY3:
mktime_duration = int(datetime.datetime.timestamp(e) - datetime.datetime.timestamp(t))
else:
mktime_duration = int(time.mktime(e.timetuple())) - int(time.mktime(t.timetuple()))
#mktime_duration = str(mktime_duration)
return archivePlaylist, mktime_duration
def downloadUrl(self, url, threadData):
self.archiveString, self.downloadDuration = self.downloadProgram(self.program.startDate, self.program.endDate)
threadData['downloadOptions']['settingsChanged'] = False
threadData['downloadDuration'] = self.downloadDuration
if threadData['downloadDuration'] <= 0:
deb('DownloadService - downloadUrl duration is 0, aborting download')
return
if self.recordingStopsPlayback and (xbmc.Player().isPlaying() or self.epg.playService.isWorking()):
deb('DownloadService - stopping ongoing playback')
self.epg.playService.stopPlayback()
xbmc.sleep(500)
drmList = ['C More', 'Polsat GO', 'Polsat GO Box', 'Ipla', 'nc+ GO', 'PlayerPL', 'Telia Play', 'TVP GO']
try:
p = re.compile('service=(.+?)&cid=.*')
service = p.findall(url)[0]
except:
threadData['nrOfReattempts'] += 1
return #go to next stream - this one seems to be locked
if service in drmList:
if self.showDialogOk:
xbmcgui.Dialog().ok('Digital rights management (DRM)', 'The selected stream from {url} is protected by Digital rights management (DRM) system, the digital content is restricted and cannot be recorded. m-TVGuide will continue on to try and record next available stream.'.format(url=service))
self.showDialogOk = False
threadData['nrOfReattempts'] += 1
return #go to next stream - this one seems to be locked
cid, service = self.parseUrl(url)
channelInfo = self.getChannelDownload(cid, service)
strmUrl_catchup = ''
strmUrl = ''
if channelInfo is not None:
if channelInfo.catchup:
strmUrl_catchup = channelInfo.catchup
else:
strmUrl = channelInfo.strm
# Catchup format string
if ADDON.getSetting('archive_support') == 'true':
if str(self.archiveString) != '':
archivePlaylist = str(self.archiveString)
catchupList = archivePlaylist.split(', ')
p = re.compile('service=playlist_\d&cid=\d+_AR.*')
if not p.match(url):
return False
# Catchup strings
duration = catchupList[0]
offset = catchupList[1]
utc = catchupList[2]
lutc = catchupList[3]
year = catchupList[4]
month = catchupList[5]
day = catchupList[6]
hour = catchupList[7]
minute = catchupList[8]
second = catchupList[9]
if strmUrl_catchup or ADDON.getSetting('archive_type') == '4':
if strmUrl_catchup:
try:
strmUrl = strmUrl_catchup.format(start=utc, timestamp=lutc)
except:
strmUrl = strmUrl_catchup.format(utc=utc, lutc=lutc)
if 'mono' in strmUrl:
strmUrl = re.sub('\$', '', str(strmUrl))
strmUrl = re.sub('mono', 'video', str(strmUrl))
else:
deb('archive_type(4) wrong type')
self.epg.database.removeRecording(self.program)
self.cancelProgramDownload(self.program)
updateDB = True
xbmcgui.Dialog().ok(strings(30998), strings(59979))
self.processIsCanceled = True
return False
else:
# Default
if ADDON.getSetting('archive_type') == '0':
matches = re.compile('^(http[s]?://[^/]+)/([^/]+)/([^/]*)(mpegts|\\.m3u8)(\\?.+=.+)?$')
catchupList = ['hls-custom', 'mono']
if matches.match(strmUrl):
r = matches.search(strmUrl)
fsHost = r.group(1) if r else ''
r = matches.search(strmUrl)
fsChannelId = r.group(2) if r else ''
r = matches.search(strmUrl)
fsListType = r.group(3) if r else ''
r = matches.search(strmUrl)
fsStreamType = r.group(4) if r else ''
r = matches.search(strmUrl)
fsUrlAppend = r.group(5) if r else ''
if fsStreamType == 'mpegts':
m_catchupSource = str(fsHost) + "/" + str(fsChannelId) + '/timeshift_abs-$' + str(utc) + '.ts' + str(fsUrlAppend)
else:
offset = str(int(offset) * 60)
if fsListType == 'index':
m_catchupSource = str(fsHost) + '/' + str(fsChannelId) + '/timeshift_rel-' + str(offset) + '.m3u8' + str(fsUrlAppend)
elif fsListType == 'video':
m_catchupSource = str(fsHost) + '/' + str(fsChannelId) + '/video-' + str(utc) + '-' + str(lutc) + '.m3u8' + str(fsUrlAppend)
elif any(x in fsListType for x in catchupList):
# Temporary fix for PlusX service
#day = datetime.datetime.now() - datetime.timedelta(days=1)
#if PY3:
#timestamp = int(datetime.datetime.timestamp(day))
#else:
#timestamp = int(time.mktime(day.timetuple()))
#if int(utc) > timestamp:
new_url = strmUrl + '?utc={utc}&lutc={lutc}'.format(utc=utc, lutc=lutc)
response = requests.get(new_url, allow_redirects=False, verify=False, timeout=5)
strmUrlNew = response.headers.get('Location', None) if 'Location' in response.headers else strmUrl
if strmUrlNew:
strmUrlNew
else:
strmUrlNew = strmUrl
r = matches.search(strmUrlNew)
fsHost = r.group(1) if r else ''
r = matches.search(strmUrlNew)
fsChannelId = r.group(2) if r else ''
r = matches.search(strmUrlNew)
fsListType = r.group(3) if r else ''
r = matches.search(strmUrlNew)
fsStreamType = r.group(4) if r else ''
r = matches.search(strmUrlNew)
fsUrlAppend = r.group(5) if r else ''
fsUrlAppend = re.sub('&.*$', '', str(fsUrlAppend))
fsListType = 'video'
m_catchupSource = str(fsHost) + '/' + str(fsChannelId) + '/' + str(fsListType) + '-' + str(utc) + '-' + str(offset) + str(fsStreamType) + str(fsUrlAppend)
else:
m_catchupSource = str(fsHost) + '/' + str(fsChannelId) + '/' + 'timeshift_rel-' + str(offset) + '.m3u8' + str(fsUrlAppend)
#m_catchupSource = str(fsHost) + '/' + str(fsChannelId) + '/' + str(fsListType.replace('mono', 'video')) + '-timeshift_rel-' + str(offset) + '.m3u8' + str(fsUrlAppend)
#m_catchupSource = str(fsHost) + '/' + str(fsChannelId) + '/' + 'mono-timeshift_rel-' + str(offset) + '.m3u8' + str(fsUrlAppend)
strmUrl = m_catchupSource
else:
deb('archive_type(0) wrong type')
self.epg.database.removeRecording(self.program)
self.cancelProgramDownload(self.program)
updateDB = True
xbmcgui.Dialog().ok(strings(30998), strings(59979))
self.processIsCanceled = True
return False
# Append
if ADDON.getSetting('archive_type') == '1':
setting = ADDON.getSetting('archive_string')
putc = re.compile('(^\?utc=|^\&utc=)')
mutc = putc.match(setting)
putv = re.compile('(^.*)(\{Y\}.\{m\}.\{d\}.*\{H\}.\{M\}.\{S\})(?=.*|$)')
mutv = putv.match(setting)
if mutc:
catchup = ADDON.getSetting('archive_string').format(utc=utc, lutc=lutc)
elif mutv:
catchup = ADDON.getSetting('archive_string').format(Y=year, m=month, d=day, H=hour, M=minute, S=second)
putc = re.compile('(^\?utc=|^\&utc=)')
mutc = putc.match(catchup)
putv = re.compile('(^.*)(\d{4}.\d{2}.\d{2}.*\d{2}.\d{2}.\d{2})(?=.*|$)')
mutv = putv.match(catchup)
m_catchupSource = strmUrl + catchup
if mutc:
strmUrl = m_catchupSource + '-' + str(int(duration)*60)
elif mutv:
strmUrl = m_catchupSource + '?duration={duration}'.format(duration=str(int(duration)*60))
else:
deb('archive_type(1) wrong type')
self.epg.database.removeRecording(self.program)
self.cancelProgramDownload(self.program)
updateDB = True
xbmcgui.Dialog().ok(strings(30998), strings(59979))
self.processIsCanceled = True
return False
# Xtream Codes
if ADDON.getSetting('archive_type') == '2':
matches = re.compile('^(http[s]?://[^/]+)/(?:live/)?([^/]+)/([^/]+)/([^/\\.]+)(\\.m3u[8]?|\\.ts)?$')
if matches.match(strmUrl):
xcHost = matches.search(strmUrl).group(1)
xcUsername = matches.search(strmUrl).group(2)
xcPassword = matches.search(strmUrl).group(3)
xcChannelId = matches.search(strmUrl).group(4)
xcExtension = matches.search(strmUrl).group(5)
if xcExtension is None:
m_isCatchupTSStream = True
xcExtension = ".ts"
start = '{y}-{m}-{d}:{h}-{min}'.format(y=year, m=month, d=day, h=hour, min=minute)
timeshift = duration + '/' + start
try:
m_catchupSource = xcHost + "/timeshift/" + xcUsername + "/" + xcPassword + "/"+timeshift+"/" + xcChannelId + xcExtension
except:
m_catchupSource = xcHost + "/timeshift/" + xcUsername + "/" + xcPassword + "/"+timeshift+"/" + xcChannelId + '.m3u8'
strmUrl = m_catchupSource
else:
deb('archive_type(2) wrong type')
self.epg.database.removeRecording(self.program)
self.cancelProgramDownload(self.program)
updateDB = True
xbmcgui.Dialog().ok(strings(30998), strings(59979))
self.processIsCanceled = True
return False
# Shift
if ADDON.getSetting('archive_type') == '3':
if '?' in strmUrl:
m_catchupSource = strmUrl + '&utc={utc}&lutc={lutc}-{duration}'.format(utc=utc, lutc=lutc, duration=duration)
strmUrl = m_catchupSource
else:
m_catchupSource = strmUrl + '?utc={utc}&lutc={lutc}-{duration}'.format(utc=utc, lutc=lutc, duration=duration)
strmUrl = m_catchupSource
self.checkConnection(strmUrl)
try:
channelInfo.strm = strmUrl
except:
channelInfo.strm
if channelInfo is None:
threadData['nrOfReattempts'] += 1
deb('DownloadService downloadUrl - locked service {} - trying next, nrOfReattempts: {}, max: {}'.format(service, threadData['nrOfReattempts'], maxNrOfReattempts))
return #go to next stream - this one seems to be locked
self.findNextUnusedOutputFilename(threadData)
if not self.downloading:
recordCommand = self.generateFFMPEGDownloadCommand(channelInfo, threadData['downloadDuration'], threadData['destinationFile'], threadData['downloadOptions'])
if recordCommand:
self.showStartDownloadNotification(threadData)
output = self.download(recordCommand, threadData)
self.postDownloadActions(output, threadData)
else:
threadData['nrOfReattempts'] += 1
def download(self, recordCommand, threadData):
deb('DownloadService download command: {}'.format(str(recordCommand)))
avgList = list()
threadData['downloadStartTime'] = datetime.datetime.now()
output = ''
si = None
if os.name == 'nt':
si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
recordEnviron = os.environ.copy()
oldLdPath = recordEnviron.get("LD_LIBRARY_PATH", '')
recordEnviron["LD_LIBRARY_PATH"] = os.path.join(os.path.dirname(recordCommand[0]), 'lib') + ':/lib:/usr/lib:/usr/local/lib'
if oldLdPath != '':
recordEnviron["LD_LIBRARY_PATH"] = recordEnviron["LD_LIBRARY_PATH"] + ":" + oldLdPath
try:
threadData['stopDownloadTimer'] = threading.Timer(threadData['downloadDuration'], self.stopDownload, [threadData])
threadData['stopDownloadTimer'].start()
threadData['downloadHandle'] = subprocess.Popen(recordCommand, shell=SHELL, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, startupinfo=si, env=recordEnviron)
duration = threadData['downloadDuration']
self.downloading = True
for line in threadData['downloadHandle'].stdout:
p = re.compile('.*time=(.*?)\s')
i = 1