-
Notifications
You must be signed in to change notification settings - Fork 3
/
xmltv-proc-nz
executable file
·761 lines (691 loc) · 28.4 KB
/
xmltv-proc-nz
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
#!/usr/bin/python
"""
xmltv-proc-nz by Hadley Rich <[email protected]>
Licensed under the BSD License.
Processes an XMLTV file in various ways. To use pipe an XML file like so;
cat freeview.xml | xmltv-proc-nz > better-file.xml
or;
xmltv-proc-nz freeview.xml > better-file.xml
"""
#TODO: Find repeats
#TODO: Regex replacements for categories
import csv
import logging
import time
import re
import sys
import urllib
import json
from xml.etree import cElementTree as ElementTree
from datetime import datetime, timedelta, tzinfo
from optparse import OptionParser
try:
import tmdb
except ImportError:
tmdb = False
try:
import tvdb_api
except ImportError:
tvdb = False
else:
tvdb = tvdb_api.Tvdb(language='en')
NAME = 'xmltv-proc-nz'
URL = 'http://nice.net.nz/xmltv-proc-nz'
VERSION = '0.5.9'
BASE_URL = 'http://nzepg.org'
TIME_FORMAT = '%Y%m%d%H%M%S'
log = logging.getLogger(NAME)
logging.basicConfig(level=logging.WARNING, format='%(message)s')
class UTC(tzinfo):
"""
Represents the UTC timezone
"""
def utcoffset(self, dt):
return timedelta(0)
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return timedelta(0)
class LocalTimezone(tzinfo):
"""
Represents the computers local timezone
"""
def __init__(self):
self.STDOFFSET = timedelta(seconds = -time.timezone)
if time.daylight:
self.DSTOFFSET = timedelta(seconds = -time.altzone)
else:
self.DSTOFFSET = self.STDOFFSET
self.DSTDIFF = self.DSTOFFSET - self.STDOFFSET
tzinfo.__init__(self)
def utcoffset(self, dt):
if self._isdst(dt):
return self.DSTOFFSET
else:
return self.STDOFFSET
def dst(self, dt):
if self._isdst(dt):
return self.DSTDIFF
else:
return timedelta(0)
def tzname(self, dt):
return time.tzname[self._isdst(dt)]
def _isdst(self, dt):
tt = (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1)
stamp = time.mktime(tt)
tt = time.localtime(stamp)
return tt.tm_isdst > 0
localtz = LocalTimezone()
utc = UTC()
class Opener(urllib.FancyURLopener):
version = '%s/%s' % (NAME, VERSION)
urllib._urlopener = Opener()
class BaseProcessor(object):
valid = True
def __call__(self, programme):
raise NotImplementedError
def post_process(self, programmes):
raise NotImplementedError
class Overrides(BaseProcessor):
"""
Use a web service to override shows in specific timeslots.
"""
def __init__(self):
if not tvdb:
log.warning('Overrides: tvdb_api module not found.')
try:
data = urllib.urlopen('%s/overrides/+json' % BASE_URL).read()
except IOError:
self.valid = False
log.warning('Overrides: Fetching data failed.')
else:
try:
self.overrides = json.loads(data)
except ValueError:
self.valid = False
log.warning('Overrides: JSON parse failed.')
else:
for o in self.overrides:
o['start'] = datetime.strptime(o['start'], '%Y-%m-%d %H:%M:%S')
o['start'] = o['start'].replace(tzinfo=utc)
o['start'] = o['start'].astimezone(localtz)
o['start'] = o['start'].replace(tzinfo=None)
def __call__(self, programme):
if not self.valid:
return
try:
start = programme.get('start')
stop = programme.get('stop')
if ' ' in start:
start, offset = start.split(' ')
if ' ' in stop:
stop = stop.split(' ')[0]
start = datetime.strptime(start, TIME_FORMAT)
stop = datetime.strptime(stop, TIME_FORMAT)
channel = programme.get('channel')
except:
log.debug('Overrides: Ignoring invalid programme')
return
for o in self.overrides:
if start == o['start'] and channel == o['xmltvid']:
log.info('Overrides: Found program on %s at %s', channel, start)
if programme.find('previously-shown') is not None:
programme.remove(programme.find('previously-shown'))
if 'previously_shown' in o and o['previously_shown']:
previously_shown = ElementTree.SubElement(programme, 'previously-shown')
if 'season' in o and o['season'] and 'episode' in o and o['episode']:
if programme.find('episode-num') is not None:
programme.remove(programme.find('episode-num'))
episode_num = ElementTree.SubElement(programme, 'episode-num')
episode_num.set('system', 'xmltv_ns')
episode_num.text = '%s.%s.0' % (o['season'] - 1, o['episode'] - 1)
if tvdb and 'tvdb_id' in o and o['tvdb_id']:
show = tvdb[o['tvdb_id']]
try:
episode = show[o['season']][o['episode']]
except:
log.error('Error getting episode %02dx%02d of %s', o['season'], o['episode'], o['tvdb_id'])
continue
log.info(
'Overrides: Using %s - %02dx%02d - %s',
show['seriesname'],
int(episode['seasonnumber']),
int(episode['episodenumber']),
episode['episodename']
)
if 'firstaired' in episode and episode['firstaired']:
if programme.find('date') is not None:
programme.remove(programme.find('date'))
date = ElementTree.SubElement(programme, 'date')
date.text = episode['firstaired'].replace('-', '')
if programme.find('sub-title') is not None:
programme.remove(programme.find('sub-title'))
sub_title = ElementTree.SubElement(programme, 'sub-title')
sub_title.text = episode['episodename']
if programme.find('desc') is not None:
if episode['overview']:
programme.find('desc').text = episode['overview']
else:
desc = ElementTree.SubElement(programme, 'desc')
desc.text = episode['overview']
if 'rating' in episode and episode['rating']:
if programme.find('star-rating') is not None:
programme.remove(programme.find('star-rating'))
rating = ElementTree.SubElement(programme, 'star-rating')
value = ElementTree.SubElement(rating, 'value')
value.text = '%s/10' % episode['rating']
class PlusOnes(BaseProcessor):
def __init__(self, *xmltvids):
self.xmltvids = xmltvids
def __call__(self, programme):
if programme.get('channel') in self.xmltvids:
previously_shown = ElementTree.SubElement(programme, 'previously-shown')
class BBCWorldOnTV1(BaseProcessor):
programmes_to_delete = []
programmes_to_insert = []
bbc_programmes = []
url = 'http://www.bbcworldnews.com' + \
'/Pages/SchedulesByFormats.aspx?TimeZone=348' + \
'&StartDate=%s&EndDate=%s&Format=CSV'
def __init__(self, *xmltvids):
self.xmltvids = xmltvids
today = datetime.now().strftime('%d/%m/%Y')
week_away = (datetime.now() + timedelta(days=7)).strftime('%d/%m/%Y')
try:
log.debug('BBCWorldOnTV1: Downloading data')
data = urllib.urlopen(self.url % (today, week_away)).read()
data = data.replace('\r', '')
except IOError:
self.valid = False
log.warning('BBCWorldOnTV1: Fetching listings failed.')
else:
reader = csv.reader(data.split(',\n'))
header = reader.next()
try:
for line in reader:
programme = {
'title': unicode(line[2], 'utf-8').encode('ascii', 'replace'),
'start': datetime.strptime('%s %s' % (line[0], line[1]), '%d/%m/%Y %H:%M'),
'stop': None,
'sub-title': unicode(line[3], 'utf-8').encode('ascii', 'replace'),
'desc': unicode(line[4], 'utf-8').encode('ascii', 'replace'),
'repeat': False,
}
if ' (r)' in programme['title']:
programme['repeat'] = True
programme['title'] = programme['title'].replace(' (r)', '')
self.bbc_programmes.append(programme)
except IndexError:
pass
stop = None
self.bbc_programmes.reverse()
for programme in self.bbc_programmes:
if stop:
programme['stop'] = stop
stop = programme['start']
self.bbc_programmes.reverse()
def __call__(self, programme):
if not self.valid:
return
try:
start = programme.get('start')
stop = programme.get('stop')
if ' ' in start:
start, offset = start.split(' ')
if ' ' in stop:
stop = stop.split(' ')[0]
start = datetime.strptime(start, TIME_FORMAT)
stop = datetime.strptime(stop, TIME_FORMAT)
title = programme.find('title').text
channel = programme.get('channel')
except:
log.debug('BBCWorldOnTV1: Ignoring invalid programme')
return
if channel in self.xmltvids and re.match(r'^BBC World( \d{4})?$', title):
for op in self.bbc_programmes:
if (op['stop'] and op['stop'] > start and op['start'] < stop) or op['start'] > start and op['start'] < stop:
np = ElementTree.Element('programme')
if op['start'] < start:
np.set('start', start.strftime("%Y%m%d%H%M%S %z") + offset)
else:
np.set('start', op['start'].strftime("%Y%m%d%H%M%S %z") + offset)
if op['stop']:
if op['stop'] > stop:
np.set('stop', stop.strftime("%Y%m%d%H%M%S %z") + offset)
else:
np.set('stop', op['stop'].strftime("%Y%m%d%H%M%S %z") + offset)
np.set('channel', channel)
np_title = ElementTree.SubElement(np, 'title')
np_title.text = op['title']
if op['sub-title']:
np_subtitle = ElementTree.SubElement(np, 'sub-title')
np_subtitle.text = op['sub-title']
if op['desc']:
np_desc = ElementTree.SubElement(np, 'desc')
np_desc.text = op['desc']
if op['repeat']:
np_repeat = ElementTree.SubElement(np, 'previously-shown')
self.programmes_to_insert.append(np)
self.programmes_to_delete.append(programme)
def post_process(self, tree):
for programme in self.programmes_to_delete:
log.debug('BBCWorldOnTV1: Removing program %s', programme.find('title').text)
tree.remove(programme)
for programme in self.programmes_to_insert:
log.debug('BBCWorldOnTV1: Inserting program %s', programme.find('title').text)
tree.append(programme)
class Movies(BaseProcessor):
"""
Augment movies with data from themoviedb.com
"""
def __init__(self):
self.cache = {}
if not tmdb:
self.valid = False
log.warning('Movies: TMDB module not found.')
try:
data = urllib.urlopen('%s/movie-channels/+json' % BASE_URL).read()
except IOError:
self.valid = False
log.warning('Movies: Fetching channel data failed.')
else:
try:
self.channels = json.loads(data)
except ValueError:
self.valid = False
log.warning('Movies: Parsing channel data failed.')
try:
data = urllib.urlopen('%s/movie-excludes/+json' % BASE_URL).read()
except IOError:
self.valid = False
log.warning('Movies: Fetching exclude data failed.')
else:
try:
self.exclude_strings = json.loads(data)
self.excludes = []
for e in self.exclude_strings:
self.excludes.append(re.compile(e))
except ValueError:
self.valid = False
log.warning('Movies: Parsing exclude data failed.')
def __call__(self, programme):
if not self.valid:
return
try:
start = programme.get('start')
stop = programme.get('stop')
title = programme.find('title').text
channel = programme.get('channel')
except:
log.debug('Movies: Ignoring invalid programme')
return
if stop is None:
return
# Unfortunately strptime can't handle numeric timezones so we strip it.
# It's only for getting possible movies so won't matter too much.
if ' ' in start:
start = start.split(' ')[0]
if ' ' in stop:
stop = stop.split(' ')[0]
start_time = time.mktime(time.strptime(start, TIME_FORMAT))
stop_time = time.mktime(time.strptime(stop, TIME_FORMAT))
duration = stop_time - start_time
if duration <= 5400 or duration > 14400: # Between 90 mins and 4 hours
return
if channel not in self.channels:
return
for regex in self.excludes:
if regex.match(title):
return
log.debug('Movies: Possible movie "%s" (duration %dm)', title, duration/60)
movie = None
if title in self.cache:
if self.cache[title] is None:
log.debug('Movies: Cached ignore for "%s"', title)
return
else:
movie = self.cache[title]
log.debug('Movies: Cache hit for "%s"', title)
else:
try:
results = tmdb.search(title.replace('?', ''))
except:
log.exception('Movies: TMDB problem searching')
return
matches = []
for result in results:
if normalise_movie_title(title) == normalise_movie_title(result['name']) and result['language'] == 'en':
matches.append(result)
log.debug('Movies: Exact title matches: %d', len(matches))
for movie in matches:
log.debug('Movies: Found match "%s" (%s)', movie['name'], movie['released'])
if len(matches) == 1:
try:
log.debug('Movies: Cache miss for "%s"', title)
movie = tmdb.getMovieInfo(matches[0]['id'])
except:
log.exception('Movies: TMDB problem fetching info')
return
self.cache[title] = movie
else:
self.cache[title] = None
return
log.info('Movies: Adding info from TMDB for %s', title)
show_type = ElementTree.SubElement(programme, 'category')
show_type.text = 'movie'
if 'categories' in movie and 'genre' in movie['categories']:
for c in movie['categories']['genre']:
exists = False
for old_cat in programme.findall('category'):
if old_cat.text == c:
exists = True
if not exists:
category = ElementTree.SubElement(programme, 'category')
category.text = c
if 'overview' in movie and movie['overview']:
if programme.find('desc') is not None:
programme.find('desc').text = movie['overview']
else:
desc = ElementTree.SubElement(programme, 'desc')
desc.text = movie['overview']
if 'url' in movie and movie['url']:
if programme.find('url') is not None:
programme.find('url').text = movie['url']
else:
url = ElementTree.SubElement(programme, 'url')
url.text = movie['url']
if 'runtime' in movie and movie['runtime']:
if programme.find('length') is not None:
programme.remove(programme.find('length'))
length = ElementTree.SubElement(programme, 'length')
length.set('units', 'minutes')
length.text = movie['runtime']
if 'released' in movie and movie['released']:
if programme.find('date') is not None:
programme.find('date').text = movie['released'].replace('-', '')
else:
date = ElementTree.SubElement(programme, 'date')
date.text = movie['released'].replace('-', '')
if 'rating' in movie and movie['rating']:
if programme.find('star-rating') is not None:
programme.remove(programme.find('star-rating'))
rating = ElementTree.SubElement(programme, 'star-rating')
value = ElementTree.SubElement(rating, 'value')
value.text = '%s/10' % movie['rating']
if 'cast' in movie:
if programme.find('credits') is not None:
programme.remove(programme.find('credits'))
credits = ElementTree.SubElement(programme, 'credits')
directors = []
actors = []
if 'director' in movie['cast']:
for d in movie['cast']['director']:
director = ElementTree.SubElement(credits, 'director')
director.text = d['name']
if 'actor' in movie['cast']:
for a in movie['cast']['actor']:
actor = ElementTree.SubElement(credits, 'actor')
actor.text = a['name']
actor.set('role', a['character'])
class HD(BaseProcessor):
"""
Look for a HD note in a description.
"""
regexes = (
re.compile(r'HD\.?$'),
re.compile(r'\(HD\)$'),
)
def __call__(self, programme):
desc = programme.find('desc')
if desc is not None and desc.text:
for regex in self.regexes:
matched = regex.search(desc.text)
if matched:
log.debug('HD: Found "%s"', programme.find('title').text)
if programme.find('video') is not None:
if programme.find('quality') is None:
quality = ElementTree.SubElement(programme.find('video'), 'quality')
quality.text = 'HDTV'
elif programme.find('quality').text != 'HDTV':
programme.find('quality').text = 'HDTV'
else:
video = ElementTree.SubElement(programme, 'video')
present = ElementTree.SubElement(video, 'present')
present.text = 'yes'
aspect = ElementTree.SubElement(video, 'aspect')
aspect.text = '16:9'
quality = ElementTree.SubElement(video, 'quality')
quality.text = 'HDTV'
desc.text = regex.sub('', desc.text)
class Subtitle(BaseProcessor):
"""
Look for a subtitle in a description.
"""
regexes = (
re.compile(r"(Today|Tonight)?:? ?'(?P<subtitle>.*?)'\.\s?"),
re.compile(r"'(?P<subtitle>.{2,60}?)\.'\s"),
re.compile(r"(?P<subtitle>.{2,60}?):\s"),
)
def __call__(self, programme):
desc = programme.find('desc')
if desc is not None and desc.text:
for regex in self.regexes:
matched = regex.match(desc.text)
if matched and 'subtitle' not in programme:
subtitle = ElementTree.SubElement(programme, 'sub-title')
subtitle.text = matched.group('subtitle')
log.debug('Subtitle: "%s" for "%s"', subtitle.text, programme.find('title').text)
desc.text = regex.sub('', desc.text)
class EpDesc(BaseProcessor):
"""
Look for a Season/Episode info in a description.
"""
regexes = (
re.compile(r' S\s?(\d+) Ep\s?(\d+)'),
)
def __call__(self, programme):
desc = programme.find('desc')
if desc is not None and desc.text:
for regex in self.regexes:
matched = regex.search(desc.text)
if matched:
season, episode = [int(x) for x in matched.groups()]
log.debug('EpDesc: Found season %s episode %s for "%s"', (season, episode, programme.find('title').text))
episode_num = ElementTree.SubElement(programme, 'episode-num')
episode_num.set('system', 'xmltv_ns')
episode_num.text = '%s.%s.0' % (season - 1, episode - 1)
class SearchReplaceTitle(BaseProcessor):
"""
Use a web service to normalise titles.
"""
def __init__(self):
try:
data = urllib.urlopen('%s/title-replacements/+json' % BASE_URL).read()
except IOError:
self.valid = False
log.warning('SearchReplaceTitle: Fetching replacements failed.')
else:
try:
self.replacements = json.loads(data)
except ValueError:
self.valid = False
log.warning('SearchReplaceTitle: JSON parse failed.')
def __call__(self, programme):
if not self.valid:
return
for r in self.replacements:
old_title = programme.find('title').text
if re.match(r['search'], old_title):
if r['description_match']:
# If there's a description_match then make sure the programme
# has a desc and it matches
desc = programme.find('desc')
if desc is None:
continue
if not re.match(r['description_match'], desc.text):
continue
desc.text = re.sub(r['description_match'], '', desc.text)
programme.find('title').text = re.sub(r['search'], r['replace'], programme.find('title').text)
if old_title != programme.find('title').text:
log.info(
'SearchReplaceTitle: Changed from "%s" to "%s"',
old_title,
programme.find('title').text
)
class Categories(BaseProcessor):
"""
Use a web service to add categories by title.
"""
def __init__(self):
try:
data = urllib.urlopen('%s/categories/+json' % BASE_URL).read()
except IOError:
self.valid = False
log.warning('Categories: Fetching data failed.')
else:
try:
self.categories = json.loads(data)
except ValueError:
self.valid = False
log.warning('Categories: JSON parse failed.')
def __call__(self, programme):
if self.valid:
for c in self.categories:
if 'category' not in c:
continue
if programme.find('title').text == c['title']:
# Remove existing categories
for category in programme.findall('category'):
programme.remove(category)
show_type = ElementTree.SubElement(programme, 'category')
show_type.text = c['show_type']
if 'categories' in c:
for newcat in c['categories']:
category = ElementTree.SubElement(programme, 'category')
category.text = newcat
log.info(
'Categories: Added categories for "%s"',
programme.find('title').text
)
def compare_programme(x, y):
"""
Comparison helper to sort the children elements of an
XMLTV programme tag.
"""
programme_order = (
'title', 'sub-title', 'desc', 'credits', 'date',
'category', 'language', 'orig-language', 'length',
'icon', 'url', 'country', 'episode-num', 'video', 'audio',
'previously-shown', 'premiere', 'last-chance', 'new',
'subtitles', 'rating', 'star-rating',
)
if programme_order.index(x.tag) < programme_order.index(y.tag):
return -1
elif programme_order.index(x.tag) > programme_order.index(y.tag):
return 1
else:
return 0
def normalise_movie_title(title):
"""
Normalise titles to help comparisons.
"""
normalised = title.lower()
if normalised.startswith('the '):
normalised = normalised[4:]
normalised = re.sub('[^a-z ]', '', normalised)
normalised = re.sub(' +', ' ', normalised)
normalised = normalised.replace(' the ', ' ')
return normalised
def indent(elem, level=0):
"""
Make ElementTree output pretty.
"""
i = "\n" + level * "\t"
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + "\t"
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
def check_for_updates():
"""
Check for script updates.
"""
try:
data = urllib.urlopen('%s/xmltv-proc-nz/+json' % BASE_URL).read()
except IOError:
log.critical('Cannot access Internet')
sys.exit(3)
else:
try:
stats = json.loads(data)
except ValueError, e:
print e
log.critical('Version check failed')
sys.exit(4)
if stats['version'] > VERSION:
log.warning(
'A new version (%s) is available at %s (current version %s)',
stats['version'],
URL,
VERSION
)
if stats['critical']:
log.critical('Version update is critical, exiting')
sys.exit(5)
if __name__ == '__main__':
parser = OptionParser(version='%prog ' + str(VERSION))
parser.set_defaults(debug=False)
parser.add_option('--debug', action='store_true',
help='output debugging information.')
parser.add_option('--verbose', action='store_true',
help='output verbose information.')
(options, args) = parser.parse_args()
if options.verbose:
log.setLevel(logging.INFO)
if options.debug:
log.setLevel(logging.DEBUG)
check_for_updates()
if sys.stdin.isatty():
if len(args) == 0:
log.critical('No input file')
sys.exit(2)
data = open(args[0]).read()
else:
data = sys.stdin.read()
processors = [
BBCWorldOnTV1('tv1.freeviewnz.tv'),
PlusOnes('tv3-plus1.freeviewnz.tv'),
SearchReplaceTitle(),
Subtitle(),
Categories(),
Movies(),
HD(),
EpDesc(),
Overrides(),
]
tree = ElementTree.XML(data)
for processor in processors:
for programme in tree.findall('.//programme'):
try:
processor(programme)
except:
log.exception("Failed processing with processor: %s", processor)
try:
processor.post_process(tree)
except NotImplementedError:
pass
except:
log.exception("Failed post processing with processor: %s", processor)
for programme in tree.findall('.//programme'):
programme[:] = sorted(programme, compare_programme)
indent(tree)
print '<?xml version="1.0" encoding="utf-8"?>'
print '<!DOCTYPE tv SYSTEM "xmltv.dtd">'
print ElementTree.tostring(tree, encoding='utf-8')