-
Notifications
You must be signed in to change notification settings - Fork 3
/
MythUtil-Channel-XMLTV-getLineup
executable file
·580 lines (544 loc) · 29.1 KB
/
MythUtil-Channel-XMLTV-getLineup
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
#!/usr/bin/python3
import argparse
import sys
import time
import json
import re
import xml.etree.ElementTree
import os
import socket
import tempfile
import errno
import hashlib
import urllib.parse
import natsort
import requests
import requests.auth
class MythTVServices():
def __init__(self, host=None, port=None, username=None, password=None):
if host is None:
host = 'localhost'
self.host = host
if port is None:
port = 6544
self.port = port
self.session = requests.Session()
if username and password:
self.session.auth = requests.auth.HTTPDigestAuth(username, password)
self.request(service='Myth', api='version')
def request(self, service=None, api=None, data={}, method=None, stream=False):
version = '0.28'
headers = {'User-Agent':'{} Python Services API Client'.format(version),
'Accept':'application/json',
'Accept-Encoding':'gzip,deflate'}
if api is None:
raise ValueError('api must be specified')
url = 'http://{}:{}/{}/{}'.format(self.host, self.port, service, api)
if method is None:
if bool(data):
method = 'post'
else:
method = 'get'
if method == 'get':
response = self.session.get(url, headers=headers, params=data, stream=stream)
elif method == 'post':
response = self.session.post(url, headers=headers, data=data, stream=stream)
else:
raise ValueError('method is not post or get: {}'.format(method))
response.raise_for_status()
if stream:
response.raw.decode_content = True
return response.raw
else:
return response.json()
def Capture(self, api=None, data={}, method=None, stream=False):
return self.request(service='Capture', api=api, data=data, method=method, stream=stream)
def Channel(self, api=None, data={}, method=None, stream=False):
return self.request(service='Channel', api=api, data=data, method=method, stream=stream)
def Content(self, api=None, data={}, method=None, stream=False):
return self.request(service='Content', api=api, data=data, method=method, stream=stream)
def Dvr(self, api=None, data={}, method=None, stream=False):
return self.request(service='Dvr', api=api, data=data, method=method, stream=stream)
def Frontend(self, api=None, data={}, method=None, stream=False):
return self.request(service='Frontend', api=api, data=data, method=method, stream=stream)
def Guide(self, api=None, data={}, method=None, stream=False):
return self.request(service='Guide', api=api, data=data, method=method, stream=stream)
def Myth(self, api=None, data={}, method=None, stream=False):
return self.request(service='Myth', api=api, data=data, method=method, stream=stream)
def Video(self, api=None, data={}, method=None, stream=False):
return self.request(service='Video', api=api, data=data, method=method, stream=stream)
def channelNormalize(channel):
m0 = re.match(r'^(\d+)$', channel)
m1 = re.match(r'^(\d+)\.(\d+)$', channel)
m2 = re.match(r'^(\d+)_(\d+)$', channel)
m3 = re.match(r'^(\d+)-(\d+)$', channel)
if m0:
return '{}'.format(int(m0.group(1)))
elif m1:
return '{}.{}'.format(int(m1.group(1)), int(m1.group(2)))
elif m2:
return '{}.{}'.format(int(m2.group(1)), int(m2.group(2)))
elif m3:
return '{}.{}'.format(int(m3.group(1)), int(m3.group(2)))
raise TypeError('Invalid channel: {}'.format(channel))
def channelCheck(channel):
try:
return channelNormalize(channel)
except Exception:
raise argparse.ArgumentTypeError('{} is not a valid channel'.format(channel))
def channelOffset(channel, offset):
if ((offset is None) or (offset == 0)):
return channel
m0 = re.match(r'^(\d+)$', channel)
m1 = re.match(r'^(\d+)\.(\d+)$', channel)
if m0:
return '{}'.format((offset + int(m0.group(1))))
elif m1:
return '{}.{}'.format((offset + int(m1.group(1))), int(m1.group(2)))
raise TypeError('Invalid channel: {}'.format(channel))
def unsignedInt(v):
try:
v = int(v)
except ValueError:
raise argparse.ArgumentTypeError("{} is not a valid positive integer".format(v))
if v < 0:
raise argparse.ArgumentTypeError("{} is not a valid positive integer".format(v))
return v
def versionTuple(v):
return tuple(map(int, (v.split("."))))
def transformAPIElementNames(APIname, existingDict):
transforms = \
{
'VideoSource':
{
'Id': 'SourceId',
},
'Channel':
{
'SourceId': 'SourceID',
'MplexId': 'MplexID',
'ChanId': 'ChannelID',
'ChanNum': 'ChannelNumber',
'ServiceId': 'ServiceID',
'ATSCMajorChan': 'ATSCMajorChannel',
'ATSCMinorChan': 'ATSCMinorChannel',
'Visible': 'visible',
'FrequencyId': 'FrequencyID',
'DefaultAuth': 'DefaultAuthority'
}
}
transform = transforms.get(APIname, {})
newDict = {}
for key, value in existingDict.items():
newKey = transform.get(key, key)
if newKey is not None:
newDict[newKey] = value
return newDict
def extendedVisibility(arg):
ua = str(arg).lower()
if ua in ['true'[:len(ua)], 'yes'[:len(ua)], '1', 'visible'[:len(ua)]]:
return 'Visible'
elif ua in ['false'[:len(ua)], 'no'[:len(ua)], '0', 'invisible'[:len(ua)], 'notvisible'[:len(ua)], 'not visible'[:len(ua)]]:
return 'Not Visible'
elif ua in ['always'[:len(ua)], '2', 'always visible'[:len(ua)]]:
return 'Always Visible'
elif ua in ['never'[:len(ua)], '-1', 'never visible'[:len(ua)]]:
return 'Never Visible'
raise argparse.ArgumentTypeError('{} is not a valid visible/true, not visible/false, always visible, never visible value'.format(arg))
def reportCheck(report):
reportType = str(report).lower()
if reportType == 'new'[:len(reportType)]:
return 'new'
if reportType == 'missing'[:len(reportType)]:
return 'missing'
if reportType == 'changed'[:len(reportType)]:
return 'changed'
raise argparse.ArgumentTypeError('{} is not a valid type to ignore'.format(report))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--backend', '--host', action='store', type=str, default='localhost',
help='the host (backend) to access. The default is localhost.')
parser.add_argument('--port', action='store', type=int, default=6544,
help='the port to connect to on on the host. The default is 6544')
parser.add_argument('--username', action='store', type=str, default=None,
help='the username to use for host authentication')
parser.add_argument('--password', action='store', type=str, default=None,
help='the password to use for host authentication')
sourcegroup = parser.add_mutually_exclusive_group(required=True)
sourcegroup.add_argument('--videosource-name', action='store', type=str, dest='sourceName',
help='the video source name')
sourcegroup.add_argument('--videosource-id', action='store', type=unsignedInt, dest='sourceId',
help='the video source id')
parser.add_argument('--channel', '--channels', '--include-channel', '--include-channels',
nargs='+', type=channelCheck, dest='channelInclude',
help='list of channels to consider. The default is all')
parser.add_argument('--exclude-channel', '--exclude-channels', '--no-channel', '--no-channels',
nargs='+', type=channelCheck, dest='channelExclude',
help='list of channels to exclude. The default is none')
parser.add_argument('--add', action='store_true', default=False,
help='add any channels in xmltv lineup')
parser.add_argument('--delete', action='store_true', default=False,
help='delete any channels not in xmltv lineup')
parser.add_argument('--update', action='store_true', default=False,
help='update the channels to match xmltv lineup')
parser.add_argument('--no-update-name', action='store_true', default=False, dest='noUpdateName',
help='do not update the channel name')
parser.add_argument('--no-update-callsign', action='store_true', default=False, dest='noUpdateCallsign',
help='do not update the callsign')
parser.add_argument('--no-update-icons', action='store_true', default=False, dest='noUpdateIcons',
help='do not update the icon')
parser.add_argument('--no-update-xmltvid', action='store_true', default=False, dest='noUpdateXMLTVID',
help='do not update the xmltvid')
parser.add_argument('--no-update-freqid', action='store_true', default=False, dest='noUpdateFreqID',
help='do not update the frequency id')
parser.add_argument('--no-strict-icon-check', action='store_true', default=False, dest='noStrictIcon',
help='do not check remote icon against local (bypass a slow/expensive check)')
parser.add_argument('--refresh-icons', action='store_true', default=False, dest='refreshIcons',
help='refresh all eligible icons')
parser.add_argument('--include-extra-icons', action='store_true', default=False, dest='extraIcons',
help='include extra available icons when downloading')
parser.add_argument('--visibility', action='store', type=extendedVisibility, dest='extendedvisible',
default='Visible', help='specify the new channel(s) visibility')
parser.add_argument('--lcnoffset', action='store', type=unsignedInt, dest='lcnoffset',
help='lcnoffset override')
parser.add_argument('--no-lcnoffset', action='store_true', default=False, dest='noOffset',
help='do not apply videosource lcnoffset to either channel or freqid numbers')
parser.add_argument('--no-lcnoffset-channel-number', action='store_true', default=False, dest='noOffsetChannum',
help='do not apply videosource lcnoffset to channel number')
parser.add_argument('--no-lcnoffset-freqid', action='store_true', default=False, dest='noOffsetFreqID',
help='do not apply videosource lcnoffset to freqid number')
parser.add_argument('--no-report', nargs='+', type=reportCheck, dest='noReport',
help='do not report (or act) on specified types ("new", "missing", "changed")')
parser.add_argument('file', nargs='?', type=argparse.FileType('rb'), default=sys.stdin)
args = parser.parse_args()
s = MythTVServices(args.backend, args.port, args.username, args.password)
try:
hostname = s.Myth('GetHostName')['String']
except Exception:
print('Unable to obtain hostname from host {}:{}'.format(args.backend, args.port))
sys.exit(1)
ChannelServiceVersion = versionTuple(s.Channel('version')['String'])
if (ChannelServiceVersion < versionTuple("1.9")) and (args.extendedvisible in ['Never Visible', 'Always Visible']):
print('Warning: backend does not supported extended visibility settings')
# Validate sourceid/name
mythsl = s.Channel('GetVideoSourceList')['VideoSourceList']['VideoSources']
sourceId = None
sourceName = None
sourceOffset = 0
for source in mythsl:
if int(source['Id']) == args.sourceId or source['SourceName'] == args.sourceName:
sourceId = int(source['Id'])
sourceName = source['SourceName']
if ChannelServiceVersion >= versionTuple('1.10'):
sourceOffset = int(source['LCNOffset'])
if args.lcnoffset is not None:
sourceOffset = args.lcnoffset
break
if sourceId is None:
print('Video source not found')
sys.exit(1)
# Get channel list for source
mythChannelInfo = s.Channel('GetChannelInfoList', {'SourceID': sourceId, 'Details': True})['ChannelInfoList']['ChannelInfos']
mythChannelList = []
for mythChannel in mythChannelInfo:
if 'ChanNum' not in mythChannel:
continue
c = channelNormalize(mythChannel['ChanNum'])
if args.channelInclude is not None:
if c not in args.channelInclude:
continue
if args.channelExclude is not None:
if c in args.channelExclude:
continue
mythChannelList.append(mythChannel)
mythChannelList = natsort.natsorted(mythChannelList, key=lambda c: c['ChanNum'])
# Get channel list from get-lineup XML
xmlLineup = []
try:
tree = xml.etree.ElementTree.parse(args.file)
except xml.etree.ElementTree.ParseError:
print("Unable to parse input file")
sys.exit(1)
root = tree.getroot()
# Some file validation
if root.tag != 'xmltv-lineups':
print('The XMLTV get-linup file does not appear to be valid (root element is not xmltv-lineups)')
sys.exit(1)
for lineup in root.iter('xmltv-lineup'):
lineupName = lineup.get('id')
lineupType = None
if lineup.find('type') is not None:
lineupType = lineup.find('type').text
if lineupType not in ['STB', 'DTV']:
print('The XMLTV get-lineup file does not specify a supported type ({}) for lineup {}'.format(lineupType, lineupName))
sys.exit(1)
if lineupType in ['DTV']: # Future support for DVB/ATSC?
print('The XMLTV get-lineup type ({}) for lineup {} has limited support'.format(lineupType, lineupName))
for lineup in root.iter('xmltv-lineup'):
for lineupEntry in lineup.iter('lineup-entry'):
channum = None
xmltvid = None
callsign = None
name = None
icon = list()
freqid = None
if lineupEntry.find('preset') is not None:
channum = lineupEntry.find('preset').text
lineupStation = lineupEntry.find('station')
if lineupStation is not None:
xmltvid = lineupStation.get('rfc2838', default=None)
if lineupStation.find('name') is not None:
name = lineupStation.find('name').text
if lineupStation.find('short-name') is not None:
callsign = lineupStation.find('short-name').text
if lineupStation.find('logo') is not None:
for logo in lineupStation.findall('logo'):
if logo.get('url') is not None:
icon.append(logo.get('url'))
freqid = channum
if lineupEntry.find('stb-channel/stb-preset') is not None:
freqid = lineupEntry.find('stb-channel/stb-preset').text
if lineupEntry.find('atsc-channel/number') is not None:
freqid = lineupEntry.find('atsc-channel/number').text
# preset is not required, so use the stb-preset
if (channum is None) and (freqid is not None):
channum = freqid
# reject malformed lineup entries
try:
channum = channelNormalize(channum)
freqid = channelNormalize(freqid)
except TypeError:
continue
# adjust channum and freqid if lcnoffset
if ((not args.noOffset) and (not args.noOffsetChannum)):
channum = channelOffset(channum, sourceOffset)
if ((not args.noOffset) and (not args.noOffsetFreqID)):
freqid = channelOffset(freqid, sourceOffset)
if args.channelInclude is not None:
if channum not in args.channelInclude:
continue
if args.channelExclude is not None:
if channum in args.channelExclude:
continue
c = {}
c['channum'] = channum
c['xmltvid'] = xmltvid
c['freqid'] = freqid
c['name'] = name
c['callsign'] = callsign
c['icon'] = icon
# Don't add duplicates (more common when mixing OTA DX'ers lineups?)
for xmlChannel in xmlLineup:
if (xmlChannel['channum'] == channum) and (xmlChannel['xmltvid'] == xmltvid) and \
(xmlChannel['freqid'] == freqid) and (xmlChannel['name'] == name) and \
(xmlChannel['callsign'] == callsign):
continue
xmlLineup.append(c)
xmlLineup = natsort.natsorted(xmlLineup, key=lambda c: c['freqid'])
# Check for MythTV channels that do not exist in get-lineup XMLTV channels
for mythChannel in mythChannelList:
found = False
for xmlChannel in xmlLineup:
if mythChannel['ChanNum'] == xmlChannel['channum']:
found = True
break
if (not found) and ((args.noReport is None) or ('missing' not in args.noReport)):
print('Channel {}, callsign: "{}", name: "{}" is not in the XMLTV channel list'.format(mythChannel['ChanNum'], mythChannel['CallSign'], mythChannel['ChannelName']))
if args.delete:
data = {}
data['ChanId'] = mythChannel['ChanId']
if bool(s.Channel('RemoveDBChannel', transformAPIElementNames('Channel', data))['bool']):
print(' Channel deleted')
else:
print(' Channel deletion failed')
# Check XMLTV channels against MythTV channels
for xmlChannel in xmlLineup:
found = False
for mythChannel in mythChannelList:
if mythChannel['ChanNum'] == xmlChannel['channum']:
found = True
break
if found and ((args.noReport is None) or ('changed' not in args.noReport)):
update = False
if ChannelServiceVersion >= versionTuple("1.9"):
data = {}
data['ChanId'] = mythChannel['ChanId']
else:
# Copy existing values
data = mythChannel.copy()
if (len(xmlChannel['icon']) == 0) and (mythChannel['IconURL'] == ''):
pass # Nothing to see here
elif (len(xmlChannel['icon']) > 0) and (mythChannel['IconURL'] == ''):
print('Channel {} has a new icon'.format(mythChannel['ChanNum']))
if ((not args.noUpdateIcons) and (args.update)):
iconFilename = urllib.parse.urlparse(xmlChannel['icon'][0])[2].rpartition('/')[2]
downloadFileData = {}
downloadFileData['StorageGroup'] = 'ChannelIcons'
downloadFileData['URL'] = xmlChannel['icon'][0]
if bool(s.Content('DownloadFile', downloadFileData)['bool']):
data['Icon'] = iconFilename
update = True
else:
print(' Channel {} icon download failed'.format(mythChannel['ChanNum']))
if (args.extraIcons):
for icon in xmlChannel['icon'][1:]:
downloadFileData = {}
downloadFileData['StorageGroup'] = 'ChannelIcons'
downloadFileData['URL'] = icon
if bool(s.Content('DownloadFile', downloadFileData)['bool']):
pass
else:
print(' Channel {} extra icon download failed'.format(mythChannel['ChanNum']))
elif (len(xmlChannel['icon']) == 0) and (mythChannel['IconURL'] != ''):
print('Channel {} icon is no longer valid'.format(mythChannel['ChanNum']))
if not args.noUpdateIcons:
data['Icon'] = ''
update = True
else:
# xmlChannel and mythChannel both have icons.
if not args.noStrictIcon:
# comparing is expensive, so allow one to accept that icons are icons
mythChannelIcon = None
for attempt in range(2):
try:
mythChannelIcon = s.Guide('GetChannelIcon', {'ChanID': mythChannel['ChanId']}, stream=True).read()
except requests.exceptions.RequestException:
mythChannelIcon = None
time.sleep(0.1)
else:
break
if mythChannelIcon is None:
print('Channel {} icon cannot be retrieved from the backend'.format(mythChannel['ChanNum']))
mythChannelIcon = b''
mythChannelIconHash = hashlib.sha256(mythChannelIcon).hexdigest()
try:
xmlIcon = requests.get(xmlChannel['icon'][0]).content
except requests.exceptions.RequestException:
print('Channel {} icon cannot be retrieved from source'.format(xmlChannel['channum']))
xmlIcon = b''
xmlIconHash = hashlib.sha256(xmlIcon).hexdigest()
if (xmlIconHash != mythChannelIconHash) or args.refreshIcons:
if xmlIconHash != mythChannelIconHash:
print('Channel {} icon differs from source'.format(mythChannel['ChanNum']))
elif ((not args.noUpdateIcons) and (args.update)):
print('Channel {} icon refresh forced'.format(mythChannel['ChanNum']))
if ((not args.noUpdateIcons) and (args.update)):
iconFilename = urllib.parse.urlparse(xmlChannel['icon'][0])[2].rpartition('/')[2]
downloadFileData = {}
downloadFileData['StorageGroup'] = 'ChannelIcons'
downloadFileData['URL'] = xmlChannel['icon'][0]
if bool(s.Content('DownloadFile', downloadFileData)['bool']):
data['Icon'] = iconFilename
update = True
else:
print(' Channel {} icon download failed'.format(mythChannel['ChanNum']))
if (args.extraIcons):
for icon in xmlChannel['icon'][1:]:
downloadFileData = {}
downloadFileData['StorageGroup'] = 'ChannelIcons'
downloadFileData['URL'] = icon
if bool(s.Content('DownloadFile', downloadFileData)['bool']):
pass
else:
print(' Channel {} extra icon download failed'.format(mythChannel['ChanNum']))
if xmlChannel['freqid'] != mythChannel['FrequencyId']:
print('Channel {} with existing frequency id: "{}" has a revised frequency id: {}'.format(mythChannel['ChanNum'], mythChannel['FrequencyId'], xmlChannel['freqid']))
if not args.noUpdateFreqID:
data['FrequencyId'] = xmlChannel['freqid']
update = True
if xmlChannel['xmltvid'] != mythChannel['XMLTVID']:
print('Channel {} with existing XMLTVID: "{}" has a revised XMLTVID: "{}"'.format(mythChannel['ChanNum'], mythChannel['XMLTVID'], xmlChannel['xmltvid']))
if not args.noUpdateXMLTVID:
data['XMLTVID'] = xmlChannel['xmltvid']
update = True
if xmlChannel['callsign'] != mythChannel['CallSign']:
print('Channel {} with existing callsign: "{}" has a revised callsign: "{}"'.format(mythChannel['ChanNum'], mythChannel['CallSign'], xmlChannel['callsign']))
if not args.noUpdateCallsign:
data['CallSign'] = xmlChannel['callsign']
update = True
if xmlChannel['name'] != mythChannel['ChannelName']:
print('Channel {} with existing name: "{}" has a new name: "{}"'.format(mythChannel['ChanNum'], mythChannel['ChannelName'], xmlChannel['name']))
if not args.noUpdateName:
data['ChannelName'] = xmlChannel['name']
update = True
if update and args.update:
if bool(s.Channel('UpdateDBChannel', transformAPIElementNames('Channel', data))['bool']):
print(' Channel {} updated'.format(mythChannel['ChanNum']))
else:
print(' Channel {} update failed'.format(mythChannel['ChanNum']))
if (not found) and ((args.noReport is None) or ('new' not in args.noReport)):
print('Channel {}, callsign: "{}", name: "{}" is new'.format(xmlChannel['channum'], xmlChannel['callsign'], xmlChannel['name']))
if args.add:
# Attempt to download icon (if not excluded)
iconFilename = ''
if not args.noUpdateIcons:
if (len(xmlChannel['icon']) > 0):
downloadFileData = {}
downloadFileData['StorageGroup'] = 'ChannelIcons'
downloadFileData['URL'] = xmlChannel['icon'][0]
if bool(s.Content('DownloadFile', downloadFileData)['bool']):
iconFilename = urllib.parse.urlparse(xmlChannel['icon'][0])[2].rpartition('/')[2]
else:
print(' Channel {} icon download failed'.format(xmlChannel['channum']))
if (args.extraIcons):
for icon in xmlChannel['icon'][1:]:
downloadFileData = {}
downloadFileData['StorageGroup'] = 'ChannelIcons'
downloadFileData['URL'] = icon
if bool(s.Content('DownloadFile', downloadFileData)['bool']):
pass
else:
print(' Channel {} extra icon download failed'.format(xmlChannel['channum']))
# We need to create a valid ChannelID:
try:
chanId = sourceId * 10000 + int(xmlChannel['channum'])
except Exception:
chanId = sourceId * 10000
while True:
try:
data = {}
data['ChanID'] = chanId
if int(s.Channel('GetChannelInfo', data)['ChannelInfo']['ChanId']) == 0:
break
except Exception:
break
chanId += 1
data = {}
data['ChanId'] = chanId
data['SourceId'] = sourceId
data['ChanNum'] = xmlChannel['channum']
data['FrequencyId'] = xmlChannel['freqid']
data['XMLTVID'] = xmlChannel['xmltvid']
data['CallSign'] = xmlChannel['callsign']
data['ChannelName'] = xmlChannel['name']
data['Icon'] = iconFilename
data['ATSCMajorChan'] = 0
data['ATSCMinorChan'] = 0
data['DefaultAuth'] = ''
data['Format'] = 'Default'
if ChannelServiceVersion >= versionTuple("1.9"):
data['ExtendedVisible'] = args.extendedvisible
else:
data['Visible'] = bool(args.extendedvisible in ['Visible', 'Always Visible'])
data['UseEIT'] = 0
data['MplexId'] = 0
data['ServiceId'] = 0
if bool(s.Channel('AddDBChannel', transformAPIElementNames('Channel', data))['bool']):
print(' Channel {} added'.format(xmlChannel['channum']))
mythChannel = data.copy()
mythChannel['IconURL'] = data['Icon']
mythChannel['FineTune'] = 0
mythChannel['ChanFilters'] = ''
mythChannel['InputId'] = 0
mythChannel['CommFree'] = False
mythChannel['DefaultAuth'] = ''
mythChannel['Programs'] = []
mythChannelList.append(mythChannel)
else:
print(' Channel {} addition failed'.format(xmlChannel['channum']))
if args.add or args.delete or args.update:
try:
s.Dvr('RescheduleRecordings')
except Exception:
pass
sys.exit(0)