forked from edit4ever/script.module.zap2xml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zap2xml.py
2056 lines (1813 loc) · 75.2 KB
/
zap2xml.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
# zap2xml - zap2it tvschedule scraper -
import time
from HTMLParser import HTMLParser
from htmlentitydefs import name2codepoint
import codecs
import platform
import sys
import os
import shutil
import logging
import traceback
import getopt
import calendar
import re
import gzip
import json
import cookielib
import urllib
import inspect
import urllib2
import datetime
import ast
"""
import requests
from requests.auth import HTTPBasicAuth
from BeautifulSoup import BeautifulSoup
import html2text
import Cookie
import zlib
import binascii
import urlparse
LWP::UserAgent #www.mechanize
XML::LibXML
libxml2
lxml
"""
class Zap2xmllog():
debug = False
quiet = False
def __init__(self):
logfile = os.path.join(os.path.dirname(os.path.realpath(__file__)),'zap2xml.log')
if os.path.exists(logfile):
os.unlink(logfile)
logging.basicConfig(filename=logfile,level=logging.DEBUG,format='%(asctime)s %(message)s')
def setDebug(self,x=True):
self.debug = x
def setQuiet(self,x=False):
self.quiet = x
def pout (self, pstr, log_type='none',printOut = True, func = False):
if func:
pstr += ':Function: ' + inspect.stack()[1][3] + ' :Line: ' + str(inspect.stack()[1][2])
if printOut and not self.quiet:
if log_type == 'debug':
if self.debug:
print pstr
else:
print pstr
if log_type == 'info':
logging.info(pstr)
if log_type == 'warn':
logging.warning(pstr)
if log_type == 'error':
logging.error(pstr)
if log_type == 'critical':
logging.critical(pstr)
if log_type == 'debug'and self.debug:
logging.debug(pstr)
if log_type == 'error' or log_type == 'critical':
print log_type + repr(sys.exc_info()[0])
logging.error(traceback.format_exc())
log = Zap2xmllog()
log.setDebug()
operSys = platform.uname()[0]
log.pout(repr(platform.uname()),'info',printOut = False)
kodiPath = '/storage/.kodi/addons/'
mechLib = 'script.module.mechanize/lib'
if re.search('openelec', platform.uname()[1], re.IGNORECASE) or os.path.exists(kodiPath):
log.pout("Found openelec node name or " + kodiPath,'info',printOut = False)
if os.path.exists(kodiPath + mechLib):
sys.path.append(kodiPath + mechLib)
else: log.pout("Mechanize addon not installed error",'error')
import mechanize
confFile = os.path.join(os.path.dirname(os.path.realpath(__file__)), ".zap2xmlrc")
# Defaults
start = 0
days = 7
ncdays = 0
ncsdays = 0
retries = 3
outFile = 'xmltv.xml'
cacheDir = 'cache'
lang = u'en'
userEmail = None
password = None
proxy = None
postalcode = None
lineupId = None
sleeptime = 0
shiftMinutes = 0
outputXTVD = None
includeXMLTV = None
lineuptype = None
lineupname = None
lineuplocation = None
sTBA = "\\bTBA\\b|To Be Announced"
urlRoot = 'http://tvschedule.zap2it.com/tvlistings/'
tvgurlRoot = 'http://mobilelistings.tvguide.com/'
tvgMapiRoot = 'http://mapi.tvguide.com/'
tvgurl = 'http://www.tvguide.com/'
br = None #browser global
gridHours = 0
loggedinMatchZ = 0
loggedinStr = '.*Logout of your Screener account.*'
programs = {}
cp = None
stations = {}
cs = None
rcs = None
schedule = {}
sch = None
gridtimes = 0
mismatch = 0
coNum = 0
tb = 0
treq = 0
expired = 0
inStationTd = 0
inIcons = 0
inStationLogo = 0
iconDir = None
ua = None
tba = 0
exp = 0
count = None
zlineupId = None
zipcode = None
XTVD_startTime = None
XTVD_endTime = None
last_reSearchObj = None
tvgfavs = {}
# my favorite
def nop():
return
def reSearch(regexp,string, flags):
global last_reSearchObj
last_reSearchObj = re.search(regexp,string,flags)
return last_reSearchObj
# for image logo files
def getURLfile(url, fn):
global retries, sleeptime
rc = 0
while rc < retries:
log.pout("Getting: " + url,'info')
try:
mechanize.urlretrieve(url, fn)
return
except mechanize.HTTPError as e:
log.pout(e.message,'error',func=True)
time.sleep(sleeptime + 1)
rc += 1
log.pout('Failed to download within %d%s' % (retries, ' retries.\n'),'error', func=True)
def getURL(url):
global br, tb, treq, retries, sleeptime
if br is None:
login()
rc = 0
while rc < retries:
log.pout("Getting: " + url,'info')
try:
data = br.open(url).get_data()
# data = br.open(url).read()
data = unicode(data, 'utf-8')
tb += len(data)
treq += 1
return data
except mechanize.HTTPError as e: # todo handle urlError
log.pout(e.message,'error',func=True)
time.sleep(sleeptime + 1)
rc += 1
log.pout('Failed to download within %d%s' % (retries, ' retries.\n'),'error', func=True)
def wbf(fn, data):
with gzip.open(fn,"wb+") as f:
d = data.encode('utf-8') # turn into bytes/string so f.write doesn't try to make it ascii'
f.write(d)
f.close()
def copyLogo(key): # todo use os.join for this
global iconDir,stations
if iconDir is not None and "logo" in stations[key]:
num = stations[key]["number"]
src = iconDir + "/" + stations[key]["logo"] + stations[key]["logoExt"]
dest1 = iconDir + "/" + num + stations[key]["logoExt"]
dest2 = iconDir+ "/" + num + stations[key]["name"] + stations[key]["logoExt"]
#todo see if shutil is in openelec
shutil.copy(src, dest1)
shutil.copy(src, dest2)
def handleLogo(url):
global stations, cs
global iconDir
try:
os.stat(iconDir)
except Exception as e:
os.mkdir(iconDir)
(dirName, fileName) = os.path.split(url)
(fileBaseName, fileExtension)=os.path.splitext(fileName)
stations[cs]["logo"] = fileBaseName
stations[cs]["logoExt"] = fileExtension
stations[cs]["logoURL"] = url
f = iconDir + "/" + fileBaseName + fileExtension
if not os.path.exists(f):
getURLfile(url,f)
#wbf(f, getURL(url))
def setOriginalAirDate():
global cp,cs,sch
if cp[10:13] != '0000':
if "originalAirDate" not in programs[cp] or \
int(schedule[cs][sch]["time"]) < int(programs[cp]["originalAirDate"]):
programs[cp]["originalAirDate"] = schedule[cs][sch]["time"]
def on_th (self, tag, attrs):
global inStationTd
my_dict = {}
cls = 'class'
for attr in attrs:
my_dict[attr[0]] = attr[1]
if cls in my_dict:
if re.search('zc-st',my_dict[cls]):
inStationTd = 1
def on_td (self, tag, attrs):
global cs,rcs,sch,expired,exp,cp,inStationTd,schedule,programs,urlRoot
my_dict = {}
cls = 'class'
onclk = 'onclick'
for attr in attrs:
my_dict[attr[0]] = attr[1]
if cls in my_dict:
if re.search('zc-pg',my_dict[cls]):
if onclk in my_dict:
cs = rcs #set in on_a
oc = my_dict[onclk]
tmp = re.search(".*\((.*)\).*",oc)
oc = tmp.group(1)
a = re.split(",",oc)
cp = a[1]
cp = re.sub("'",'',cp)
sch = a[2]
if len(cp) == 0 :
cp = cs = sch = -1
expired += 1
exp = 1
if cs not in schedule:
schedule[cs] = {}
if sch not in schedule[cs]:
schedule[cs][sch] = {}
if cp not in programs:
programs[cp]= {}
if "genres" not in programs[cp]:
programs[cp]["genres"] = {}
schedule[cs][sch]["time"] = sch
schedule[cs][sch]["program"] = cp
schedule[cs][sch]["station"] = cs
if re.search('zc-g-C',my_dict[cls]):
programs[cp]["genres"]["children"] = 1
elif re.search('zc-g-N',my_dict[cls]):
programs[cp]["genres"]["news"] = 1
elif re.search('zc-g-M',my_dict[cls]):
programs[cp]["genres"]["movie"] = 1
elif re.search('zc-g-S',my_dict[cls]):
programs[cp]["genres"]["sports"] = 1
# if re.search('^MV',cp):
# programs[cp]["genres"]["movie"] = 1
# elif re.search('^SP',cp):
# programs[cp]["genres"]["sports"] = 1
# elif re.search('^EP',cp):
# programs[cp]["genres"]["series"] = 9
# elif re.search('^SH',cp) and "-j" in options:
# programs[cp]["genres"]["series"] = 9
if cp != -1 and "-D" in options:
fn = os.path.join(cacheDir,cp + ".js.gz")
if not os.path.isfile(fn):
data = getURL(urlRoot + "gridDetailService?pgmId=" + cp)
wbf(fn, data)
log.pout("[D] Parsing: " + cp,'info')
parseJSOND(fn)
if "-I" in options:
fn = os.path.join(cacheDir,"I" + cp + ".js.gz")
if not os.path.isfile(fn):
data = getURL(urlRoot + "gridDetailService?rtype=pgmimg&pgmId=" + cp)
if data: #sometimes we fail to get the url try to keep going
wbf(fn, data)
log.pout("[I] Parsing: " + cp,'info')
parseJSONI(fn)
elif re.search('zc-st',my_dict[cls]):
inStationTd = 1
def handleTags(text):
global schedule,cs,sch
if "rating" not in programs[cp]:
if re.search("TV-Y",text):
programs[cp]["rating"] = 'TV-Y'
elif re.search("TV-Y7",text):
programs[cp]["rating"] = 'TV-Y7'
elif re.search("TV-G",text):
programs[cp]["rating"] = 'TV-G'
elif re.search("TV-PG",text):
programs[cp]["rating"] = 'TV-PG'
elif re.search("TV-14",text):
programs[cp]["rating"] = 'TV-14'
elif re.search("TV-MA",text):
programs[cp]["rating"] = 'TV-MA'
if re.search("LIVE",text):
if "live" not in schedule[cs][sch]:
schedule[cs][sch]["live"] = {}
schedule[cs][sch]["live"] = 'Live'
setOriginalAirDate()
elif re.search("HD",text):
if "quality" not in schedule[cs][sch]:
schedule[cs][sch]["quality"] = {}
schedule[cs][sch]["quality"] = 'HD'
elif re.search("NEW",text):
if "new" not in schedule[cs][sch]:
schedule[cs][sch]["new"] = {}
schedule[cs][sch]["new"] = 'New'
setOriginalAirDate()
on_li_zc_ic = None
def on_li(self, tag, attrs):
global schedule,cs,sch,on_li_zc_ic
my_dict = {}
cls = 'class'
for attr in attrs:
my_dict[attr[0]] = attr[1]
if cls in my_dict: #else nada
if re.search('zc-ic-ne',my_dict[cls]):
schedule[cs][sch]["new"] = 'New'
setOriginalAirDate()
elif re.search('zc-ic-cc',my_dict[cls]):
schedule[cs][sch]["cc"] = 'CC'
elif re.search('zc-ic',my_dict[cls]):
on_li_zc_ic = True
elif re.search('zc-ic-live',my_dict[cls]):
schedule[cs][sch]["live"] = 'Live'
setOriginalAirDate()
elif re.search('zc-icons-hd',my_dict[cls]):
schedule[cs][sch]["quality"] = 'HD'
def on_img(self, tag, attrs):
global inIcons,schedule,cs,sch,inStationTd
my_dict = {}
for attr in attrs:
my_dict[attr[0]] = attr[1]
if inIcons:
if re.search("Live",my_dict["alt"]):
schedule[cs][sch]["live"] = "Live"
setOriginalAirDate()
elif re.search("New",my_dict["alt"]):
schedule[cs][sch]["new"] = "New"
setOriginalAirDate()
elif re.search("HD",my_dict["alt"]) or re.search("High Definition",my_dict["alt"])\
or re.search("video-hd",my_dict["src"]) or re.search("video-ahd",my_dict["src"]):
schedule[cs][sch]["quality"] = "HD"
elif inStationTd and re.search("Logo",my_dict["alt"]):
if iconDir is not None:
handleLogo(my_dict["src"])
def on_a(self, tag, attrs):
global cbdata, inStationTd,cs,rcs,stations,coNum,postalcode,lineupId, count
my_dict = {}
cls = 'class'
for attr in attrs:
my_dict[attr[0]] = attr[1]
if cls in my_dict: #else nada
if re.search('zc-pg-t',my_dict[cls]):
#set global for text/data handling
cbdata = 'title'
elif inStationTd :
tcs = my_dict['href']
tmp = re.search(".*stnNum=(\w+).*",tcs)
tcs = tmp.group(1)
if not re.search("stnNum",tcs):
cs = rcs = tcs
if cs not in stations:
stations[cs] = {}
if "stnNum" not in stations[cs]:
stations[cs]["stnNum"] = cs
if "number" not in stations[cs]:
tnum = urllib.unquote(my_dict["href"])
tnum = re.sub("\s","",tnum)
# match '.' or alphanumeric one or more time followed by anything
tmp = re.search(".*channel=([.\w]+).*",tnum)
if tmp:
tnum = tmp.group(1)
else: tnum = "0"
if not re.search("channel=",tnum):
stations[cs]["number"] = tnum
if "order" not in stations[cs]:
if "-b" in options:
stations[cs]["order"] = coNum + 1
else:
stations[cs]["order"] = stations[cs]["number"]
if postalcode is None and re.search("zipcode",my_dict["href"] ):
postalcode = my_dict["href"]
tmp = re.search(".*zipcode=(\w+).*",postalcode)
postalcode = tmp.group(1)
if lineupId is None and re.search("lineupId",my_dict["href"] ):
lineupId = my_dict["href"]
tmp = re.search(".*lineupId=(.*?)&.*",lineupId)
lineupId = urllib.unquote(tmp.group(1))
if count == 0 and inStationLogo and iconDir:
fn = os.path.join(cacheDir,"STNNUM" + cs + ".html.gz")
if not os.path.isfile(fn):
data = getURL(my_dict["href"])
#data = unicode(data,'utf8')
#data = data.encode('utf8')
wbf(fn,data)
log.pout("[STNNUM] Parsing: " + cs,'info')
parseSTNNUM(fn)
on_p_zc_pg_d = None
def on_p(self, tag, attrs):
global on_p_zc_pg_d
my_dict = {}
for attr in attrs:
my_dict[attr[0]] = attr[1]
if "class" in my_dict and re.search("zc-pg-d", my_dict["class"]):
on_p_zc_pg_d = True
return 0
on_div_zc_tn_c = None
on_div_zc_tn_t = None
def on_div(self, tag, attrs):
global inIcons,inStationLogo,on_div_zc_tn_c, on_div_zc_tn_t
my_dict = {}
for attr in attrs:
my_dict[attr[0]] = attr[1]
if "class" in my_dict and re.search("zc-icons", my_dict["class"]):
inIcons= 1
if "class" in my_dict and re.search("zc-tn-c", my_dict["class"]):
on_div_zc_tn_c = True
if "class" in my_dict and re.search("zc-tn-t", my_dict["class"]):
on_div_zc_tn_t = True
if "class" in my_dict and re.search("stationLogo", my_dict["class"]):
inStationLogo = 1
on_span_zc_pg_y = None
on_span_zc_pg_e = None
on_span_zc_st_c = None
on_span_zc_ic_s = None
on_span_zc_pg_t = None
def on_span(self, tag, attrs):
global on_span_zc_pg_y, on_span_zc_pg_e, on_span_zc_st_c, on_span_zc_ic_s, on_span_zc_pg_t
my_dict = {}
for attr in attrs:
my_dict[attr[0]] = attr[1]
if "class" in my_dict:
if re.search("zc-pg-y", my_dict["class"]):
on_span_zc_pg_y = True
elif re.search("zc-pg-e", my_dict["class"]):
on_span_zc_pg_e = True
elif re.search("zc-st-c", my_dict["class"]):
on_span_zc_st_c = True
elif re.search("zc-ic-s", my_dict["class"]):
on_span_zc_ic_s = True
elif re.search("zc-pg-t", my_dict["class"]):
on_span_zc_pg_t = True
def loginZAP(br):
global loggedinMatchZ, retries, sleeptime
rc = 0
while rc < retries :
# The site we will navigate into, handling it's session
log.pout( urlRoot + 'ZCLogin.do?method=getStandAlonePage&aid=tvschedule' + "\n",'info')
br.open(urlRoot + 'ZCLogin.do?method=getStandAlonePage&aid=tvschedule')
# View available forms
for f in br.forms():
log.pout("Form:\n" + str(f),'debug',printOut=False,func=True)
# Select the second (index one) form (the first form is a search query box)
br.select_form(name="zcLoginForm")
br.form.find_control('username').readonly = False
br.form.find_control('password').readonly = False
# User credentials
br.form['username'] = userEmail
br.form['password'] = password
# Login
response = br.submit()
# tmp1 = response.geturl()
# tmp2 = response.info()
# Invalid e-mail address/password. Please log in again.
# look for Logout
# todo find response success like perl script rather than search whole page
matchString = response.read()
m = loggedinMatchZ.search(matchString)
if m:
log.pout("Matched " + loggedinStr,'debug',func=True)
return
else:
log.pout("Didn't Match %s %s %d %s" % (loggedinStr, 'Sleep ', sleeptime+1, "sec."),'debug',func=True)
time.sleep(sleeptime + 1)
rc += 1
log.pout(("%s,%d,%s" % ("Failed to login within ", retries, " retries.\n")),'error',func=True)
sys.exit(-1)
def login():
global br, cj, proxy, options
if userEmail is None or userEmail == '' or password is None or password == '':
if zlineupId is None:
log.pout("Unable to login: Unspecified username or password.\n",'error',func=True)
exit(-1)
# Browser
br = mechanize.Browser()
# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
# Browser options
if '-P' in options: # todo longer time out for proxies?
br.set_proxies({'http':proxy})
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
br.addheaders = [('User-agent', 'Mozilla/4.0')]
if userEmail != '' and password != '':
log.pout("Logging in as " + userEmail + "\n","info")
if '-z' in options:
loginTVG()
else:
loginZAP(br)
else:
log.pout("Connecting with lineupId \"" + zlineupId + "\" (" + str(time.localtime(time.time())) + ")\n",'info')
# s/\s+$// match white space at end of line one or more times and replace with nothing
# shift function args
def rtrim (shift):
s = shift
#s =~ s/\s+$//
return re.sub("\s+$","",s)
def trim (shift):
s = shift
#$s =~ s/^\s+//
#$s =~ s/\s+$//
s = re.sub("^\s+","",s)
s = re.sub("\s+$","",s)
return s
# way to divide a string by 1000
def _rtrim3 (shift):
s = shift
return s[:-3] #substr(s, 0, len(s)-3)
def convTime(t):
global shiftMinutes
t = int(t) + (shiftMinutes * 60 * 1000)
return time.strftime("%Y%m%d%H%M%S",time.localtime(t/1000))
def convTimeXTVD(t):
global shiftMinutes
t = int(t) + (shiftMinutes * 60 * 1000)
return time.strftime("%Y-%m-%dT%H:%M:%SZ",time.gmtime(t/1000))
def stationToChannel(s):
if "-z" in options:
return "I%s.%s.tvguide.com" % (stations[s]["number"], stations[s]["stnNum"])
elif "-O" in options:
return "C%s%s.zap2it.com" % (stations[s]["number"],stations[s]["name"].lower())
return "I%s.labs.zap2it.com" % (stations[s]["stnNum"])
def convDateLocal(t):
if int(t) < 0:
tmp = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=(int(t)/1000))
return tmp.strftime("%Y%m%d")
return time.strftime("%Y%m%d", time.localtime((int(t)/1000)))
def convDateLocalXTVD(t):
if int(t) < 0:
tmp = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=(int(t)/1000))
return tmp.strftime("%Y%m%d")
return time.strftime("%Y-%m-%d", time.localtime((int(t)/1000)))
def convDurationXTVD(duration):
dur = int(duration)
hour = dur / 3600000
minutes = (dur - (hour * 3600000)) / 60000
return "PT%02dH%02dM" %(hour, minutes)
def appendAsterisk(title, station, s):
if "-A" in options:
if re.search("new",options["-A"]) and "new" in schedule[station][s]\
or re.search("live",options["-A"]) and "live" in schedule[station][s]:
title += " *"
return title
cbdata = None
class MyHTMLParser(HTMLParser):
entityref = None
charref = None
data_break = False
handling_data = False
def handle_starttag(self, tag, attrs):
# print "Start tag:", tag
# for attr in attrs:
# print " attr:", attr
if tag == 'td' or tag == 'a' or tag == 'th'\
or tag == 'p' or tag == 'div'or tag == 'span'\
or tag == 'li' or tag == 'img':
globals()['on_%s' % tag](self, tag, attrs)
def handle_endtag(self, tag):
global inStationTd,inIcons, inStationLogo
global cbdata,on_div_zc_tn_c,on_div_zc_tn_t
global on_span_zc_pg_y, on_span_zc_pg_e, on_span_zc_st_c, on_span_zc_ic_s
global on_span_zc_pg_t
global on_p_zc_pg_d, on_li_zc_ic
# print "End tag :", tag
if tag == 'td' or tag == 'th':
inStationTd = 0
if tag == 'a':
cbdata = None
self.handling_data = False
self.data_break = False
if tag == 'div':
inIcons = 0
inStationLogo = 0
on_div_zc_tn_c = on_div_zc_tn_t = False
if tag == 'span':
on_span_zc_pg_y = on_span_zc_pg_e = on_span_zc_st_c = on_span_zc_ic_s = \
on_span_zc_pg_t = self.handling_data = self.data_break = False
if tag == 'p':
on_p_zc_pg_d = False
if tag == 'li':
on_li_zc_ic = False
if tag == 'head':
head_found = False
def handle_data(self, data):
global programs,cbdata,cp,on_div_zc_tn_c,gridtimes,on_div_zc_tn_t
global on_span_zc_pg_y, on_span_zc_pg_e, on_span_zc_st_c, on_span_zc_ic_s
global on_span_zc_pg_t
global tba, sTBA, stations, cs
global on_p_zc_pg_d,on_li_zc_ic
# print "Data :", data
if cbdata == 'title': #set in on_a assume not special chars for now
self.handling_data = True
if cp not in programs: #if so do tis like data and reset cbdata on 'a' end tag
programs[cp] = {}
if 'title' in programs[cp] and self.data_break:
if self.entityref:
programs[cp]['title'] += self.entityref
self.entityref = None
if self.charref:
programs[cp]["title"] += self.charref
self.charref = None
programs[cp]['title'] += data
self.data_break = False
else:
programs[cp]['title'] = data #find same program in mult files overwrite
if on_div_zc_tn_c is True:
gridtimes = 0
on_div_zc_tn_c = False
if on_div_zc_tn_t is True:
gridtimes += 1
on_div_zc_tn_t = False
if on_span_zc_pg_y:
data = re.sub("[^\d]","",data)
programs[cp]["movie_year"] = data
on_span_zc_pg_y = False
if on_span_zc_pg_e:
self.handling_data = True
if "episode" in programs[cp] and self.data_break: #entityref or charref event add and clr ref
if self.entityref:
programs[cp]["episode"] += self.entityref
self.entityref = None
if self.charref:
programs[cp]["episode"] += self.charref
self.charref = None
programs[cp]["episode"] += data
self.data_break = False
else:
programs[cp]["episode"] = data
if re.search("$" + sTBA, data, re.IGNORECASE):
tba = 1
# on_span_zc_pg_e = False
if on_span_zc_st_c:
stations[cs]["name"] = trim(data)
on_span_zc_st_c = False
if on_span_zc_ic_s:
handleTags(data)
on_span_zc_ic_s = False
if on_span_zc_pg_t:
programs[cp]["title"] = data
if re.search("$" + sTBA,data, re.IGNORECASE):
tba = 1
on_span_zc_pg_t = False
if on_p_zc_pg_d:
if 'description' not in programs[cp]: # needed to not overwrite -D option
d = trim(data)
if len(d):
programs[cp]["description"] = d
on_p_zc_pg_d = False
if on_li_zc_ic:
handleTags(data)
on_li_zc_ic = False
# def handle_comment(self, data):
# print "Comment :", data
def handle_entityref(self, name): # &name like amp or apos
if name in name2codepoint: #getting KeyError: 'B'
# self.entityref = unichr(name2codepoint[name])
tmp = name2codepoint[name]
if tmp < 0x20 or tmp > 0x7f: #not sure I need this, had encode error before codec.open encoding setting
self.entityref = u"&#%d;" % tmp
else:
self.entityref = chr(tmp)
if self.handling_data:
self.data_break = True
def handle_charref(self, name): # &# or &#x number
if name.startswith('x'):
#self.charref = chr(int(name[1:], 16))
self.charref = unichr(int(name[1:], 16))
else:
#self.charref = chr(int(name))
self.charref = unichr(int(name))
if self.handling_data:
self.data_break = True
# print "Num ent :", c
# def handle_decl(self, data):
# print "Decl :", data
def parseJSONI(fn):
global programs, cp
with gzip.open(fn,"rb") as f:
b = f.read()
f.close()
b = re.sub("'","\"",b)
t = json.loads(b)
if "imageUrl" in t and re.search("^http",t["imageUrl"],re.IGNORECASE):
programs[cp]["imageUrl"] = t["imageUrl"]
def parseJSOND(fn):
global programs, cp
with gzip.open(fn,"rb") as f:
b = f.read()
f.close()
# todo figure out this re
b = re.sub("^.+?\=","",b,re.IGNORECASE|re.MULTILINE)
t = json.loads(b)
p=t["program"]
#todo remove xtra var like sn
if "seasonNumber" in p:
sn = p["seasonNumber"]
sn = re.sub("S","",sn,re.IGNORECASE)
if sn != '':
programs[cp]["seasonNum"] = sn
if "episodeNumber" in p:
en = p["episodeNumber"]
en = re.sub("E","",en,re.IGNORECASE)
if en != '':
programs[cp]["episodeNum"] = en
if "originalAirDate" in p:
oad = p["originalAirDate"]
if oad != '':
programs[cp]["originalAirDate"] = oad
if "description" in p:
desc = p["description"]
if desc != '':
programs[cp]["description"] = desc
if "genres" in p:
genres = p["genres"]
i = 1
for g in genres:
programs[cp]["genres"][g.lower()] = i
i += 1
if "seriesId" in p:
seriesId = p["seriesId"]
if seriesId != '':
programs[cp]["genres"]["series"] = 9
if "credits" in p:
credits = p["credits"]
i = 1
if"credits" not in programs[cp]:
programs[cp]["credits"] = {}
for g in credits:
programs[cp]["credits"][g] = i
i += 1
if "starRating" in p:
sr = p["starRating"]
tsr = len(sr)
if re.search("\+$",sr):
tsr -= 1
tsr += 0.5
programs[cp]["starRating"] = str(tsr)
def parseTVGFavs(data):
global tvgfavs, zlineupId
t = json.loads(data)
if 'message' in t:
m = t['message']
for f in m:
source = f['source']
channel = f['channel']
tvgfavs[channel] = source
log.pout("Lineup " + zlineupId + " favorites: " + str(tvgfavs.keys()),'info')
return
def sortPhash(a,b): # todo make ints and subtract?
global sortThing1, sortThing2
if b < a:
return -1
if b == a:
return 0
if b > a:
return 1
def parseTVGD(fn):
global programs, cp
with gzip.open(fn,"rb") as f:
b = f.read()
f.close()
t = json.loads(b)
if 'program' in t:
prog = t['program']
if 'release_year' in prog:
programs[cp]['movie_year'] = prog['release_year']
if 'tvobject' in t:
tvo = t['tvobject']
if 'photos' in tvo:
photos = tvo['photos']
phash = {}
for ph in photos:
w = int(ph['width']) * int(ph['height'])
u = ph['url']
phash[w] = u
big = sorted(phash.keys(),cmp=sortPhash)[0]
programs[cp]['imageUrl'] = phash[big]
return
def parseTVGGrid(fn):
global programs, cp, cs, stations, coNum, tba, sTBA
with gzip.open(fn,"rb") as f:
b = f.read()
f.close()
t = json.loads(b)
for e in t:
cjs = e['Channel']
cs = cjs['SourceId']
if len(tvgfavs)> 0:
if 'Number' in cjs and cjs['Number'] != '':
n = cjs['Number']
if n not in tvgfavs or cs != tvgfavs[n]:
continue
if cs not in stations:
stations[cs] = {}
if 'stnNum' not in stations[cs]:
stations[cs]['stnNum'] = cs
if 'Number' in cjs and cjs['Number'] != '':
stations[cs]['number'] = cjs['Number']
stations[cs]['name'] = cjs['Name']
if 'FullName' in cjs and cjs['FullName'] != cjs['Name']:
stations[cs]['fullname'] = cjs['FullName']
if 'order' not in stations[cs]:
if '-b' in options:
stations[cs]['order'] = coNum
coNum += 1
else:
stations[cs]['order'] = stations[cs]['number']
cps = e['ProgramSchedules']
for pe in cps:
cp = pe['ProgramId']
catid = pe['CatId']
if cp not in programs:
programs[cp] = {}
if 'genres' not in programs[cp]:
programs[cp]['genres'] = {}
if catid == 1:
programs[cp]['genres']['movie'] = 1
elif catid == 2:
programs[cp]['genres']['sports'] = 1
elif catid == 3:
programs[cp]['genres']['family'] = 1
elif catid == 4:
programs[cp]['genres']['news'] = 1
ppid = None
if 'ParentProgramId' in pe:
ppid = pe['ParentProgramId']
if ppid and int(ppid) != 0:
programs[cp]['genres']['series'] = 9
programs[cp]['title'] = pe['Title']
if re.search(sTBA, programs[cp]['title']):
tba = 1
if 'EpisodeTitle' in pe and pe['EpisodeTitle'] != '':
programs[cp]['episode'] = pe['EpisodeTitle']
if re.search(sTBA, programs[cp]['episode']):
tba = 1
if 'CopyText' in pe and pe['CopyText'] != '':
programs[cp]['description'] = pe['CopyText']
if 'Rating' in pe and pe['Rating'] != '':
programs[cp]['rating'] = pe['Rating']
sch = str(int(pe['StartTime']) *1000)
if cs not in schedule: