1414# along with this program. If not, see <http://www.gnu.org/licenses/>.
1515################################################################################
1616
17- import urllib2
17+ try :
18+ # Python 3
19+ from urllib .request import urlopen , Request
20+ from urllib .error import HTTPError , URLError
21+ except ImportError :
22+ # Python 2
23+ from urllib2 import urlopen , Request , HTTPError , URLError
24+
1825import base64
1926import codecs
2027import time
@@ -93,7 +100,7 @@ def mainRun(userdata):
93100 country = 'USA'
94101 else :
95102 country = 'CAN'
96- logging .info ('Running zap2epg-0.7 .4 for zipcode: %s and lineup: %s' , zipcode , lineup )
103+ logging .info ('Running zap2epg-1.3 .4 for zipcode: %s and lineup: %s' , zipcode , lineup )
97104 pythonStartTime = time .time ()
98105 cacheDir = os .path .join (userdata , 'cache' )
99106 dayHours = int (days ) * 8 # set back to 8 when done testing
@@ -104,23 +111,24 @@ def mainRun(userdata):
104111 def tvhMatchGet ():
105112 tvhUrlBase = 'http://' + tvhurl + ":" + tvhport
106113 channels_url = tvhUrlBase + '/api/channel/grid?all=1&limit=999999999&sort=name&filter=[{"type":"boolean","value":true,"field":"enabled"}]'
107- if usern is not None and passw is not None :
108- logging .info ('Adding Tvheadend username and password to request url...' )
109- request = urllib2 .Request (channels_url )
110- request .add_header ('Authorization' , b'Basic ' + base64 .b64encode (usern + b':' + passw ))
111- response = urllib2 .urlopen (request )
112- else :
113- response = urllib2 .urlopen (channels_url )
114114 try :
115+ if usern is not None and passw is not None :
116+ logging .info ('Adding Tvheadend username and password to request url...' )
117+ request = Request (channels_url )
118+ request .add_header ('Authorization' , b'Basic ' + base64 .b64encode (usern + b':' + passw ))
119+ response = urlopen (request )
120+ else :
121+ response = urlopen (channels_url )
122+
115123 logging .info ('Accessing Tvheadend channel list from: %s' , tvhUrlBase )
116124 channels = json .load (response )
117125 for ch in channels ['entries' ]:
118126 channelName = ch ['name' ]
119127 channelNum = ch ['number' ]
120128 tvhMatchDict [channelNum ] = channelName
121129 logging .info ('%s Tvheadend channels found...' , str (len (tvhMatchDict )))
122- except urllib2 . HTTPError as e :
123- logging .exception ('Exception: tvhMatch - %s' , e . strerror )
130+ except ( HTTPError , URLError ) as e :
131+ logging .exception ('Exception: tvhMatch - %s' , str ( e ) )
124132 pass
125133
126134 def deleteOldCache (gridtimeStart ):
@@ -136,8 +144,8 @@ def deleteOldCache(gridtimeStart):
136144 fn = os .path .join (cacheDir , entry )
137145 os .remove (fn )
138146 logging .info ('Deleting old cache: %s' , entry )
139- except OSError , e :
140- logging .warn ('Error Deleting: %s - %s.' % (e .filename , e . strerror ))
147+ except OSError as e :
148+ logging .warn ('Error Deleting: %s - %s.' % (e .filename , str ( e ) ))
141149 except Exception as e :
142150 logging .exception ('Exception: deleteOldCache - %s' , repr (e ))
143151
@@ -154,8 +162,8 @@ def deleteOldShowCache(showList):
154162 try :
155163 os .remove (fn )
156164 logging .info ('Deleting old show cache: %s' , entry )
157- except OSError , e :
158- logging .warn ('Error Deleting: %s - %s.' % (e .filename , e . strerror ))
165+ except OSError as e :
166+ logging .warn ('Error Deleting: %s - %s.' % (e .filename , str ( e ) ))
159167 except Exception as e :
160168 logging .exception ('Exception: deleteOldshowCache - %s' , repr (e ))
161169
@@ -211,7 +219,7 @@ def printHeader(fh, enc):
211219 fh .write ("<?xml version=\" 1.0\" encoding=\" " + enc + "\" ?>\n " )
212220 fh .write ("<?xml-stylesheet href=\" xmltv.xsl\" type=\" text/xsl\" ?>\n " )
213221 fh .write ("<!DOCTYPE tv SYSTEM \" xmltv.dtd\" >\n \n " )
214- fh .write ("<tv source-info-url=\" http://tvschedule.zap2it .com/\" source-info-name=\" zap2it .com\" >\n " )
222+ fh .write ("<tv source-info-url=\" http://tvschedule.gracenote .com/\" source-info-name=\" gracenote .com\" >\n " )
215223
216224 def printFooter (fh ):
217225 fh .write ("</tv>\n " )
@@ -222,9 +230,16 @@ def printStations(fh):
222230 try :
223231 logging .info ('Writing Stations to xmltv.xml file...' )
224232 try :
225- scheduleSort = OrderedDict (sorted (schedule .iteritems (), key = lambda x : float (x [1 ]['chnum' ])))
233+ # Python 3
234+ iter_method = schedule .items
235+ except AttributeError :
236+ # Python 2
237+ iter_method = schedule .iteritems
238+
239+ try :
240+ scheduleSort = OrderedDict (sorted (iter_method (), key = lambda x : float (x [1 ]['chnum' ])))
226241 except :
227- scheduleSort = OrderedDict (sorted (schedule . iteritems (), key = lambda x : x [1 ]['chfcc' ]))
242+ scheduleSort = OrderedDict (sorted (iter_method (), key = lambda x : x [1 ]['chfcc' ]))
228243 for station in scheduleSort :
229244 fh .write ('\t <channel id=\" ' + station + '.zap2epg\" >\n ' )
230245 if 'chtvh' in scheduleSort [station ] and scheduleSort [station ]['chtvh' ] is not None :
@@ -256,15 +271,26 @@ def printEpisodes(fh):
256271 logging .info ('Writing Episodes to xmltv.xml file...' )
257272 if xdesc is True :
258273 logging .info ('Appending Xdetails to description for xmltv.xml file...' )
259-
260274 try :
261- scheduleSort = OrderedDict (sorted (schedule .iteritems (), key = lambda x : float (x [1 ]['chnum' ])))
275+ # Python 3
276+ iter_method = schedule .items
277+ except AttributeError :
278+ # Python 2
279+ iter_method = schedule .iteritems
280+ try :
281+ scheduleSort = OrderedDict (sorted (iter_method (), key = lambda x : float (x [1 ]['chnum' ])))
262282 except :
263- scheduleSort = OrderedDict (sorted (schedule . iteritems (), key = lambda x : x [1 ]['chfcc' ]))
283+ scheduleSort = OrderedDict (sorted (iter_method (), key = lambda x : x [1 ]['chfcc' ]))
264284
265285 for station in scheduleSort :
266286 lang = 'en'
267- sdict = OrderedDict (sorted (schedule [station ].iteritems ()))
287+ try :
288+ # Python 3
289+ iter_method = schedule [station ].items
290+ except AttributeError :
291+ # Python 2
292+ iter_method = schedule [station ].iteritems
293+ sdict = OrderedDict (sorted (iter_method ()))
268294 for episode in sdict :
269295 if not episode .startswith ("ch" ):
270296 try :
@@ -335,7 +361,7 @@ def printEpisodes(fh):
335361 #os.remove(fn)
336362 #logging.info('Deleting episode %s:', episode)
337363 except Exception as e :
338- logging .exception ('Exception: printEpisodes' )
364+ logging .exception ('Exception: printEpisodes: %s' , str ( e ) )
339365
340366 def xmltv ():
341367 try :
@@ -463,11 +489,11 @@ def parseXdetails():
463489 retry = 3
464490 while retry > 0 :
465491 logging .info ('Downloading details data for: %s' , EPseries )
466- url = 'https://tvlistings.zap2it .com/api/program/overviewDetails'
492+ url = 'https://tvlistings.gracenote .com/api/program/overviewDetails'
467493 data = 'programSeriesID=' + EPseries
468494 try :
469- URLcontent = urllib2 . Request (url , data = data )
470- JSONcontent = urllib2 . urlopen (URLcontent ).read ()
495+ URLcontent = Request (url , data = data )
496+ JSONcontent = urlopen (URLcontent ).read ()
471497 if JSONcontent :
472498 with open (fileDir , "wb+" ) as f :
473499 f .write (JSONcontent )
@@ -477,7 +503,7 @@ def parseXdetails():
477503 time .sleep (1 )
478504 retry -= 1
479505 logging .warn ('Retry downloading missing details data for: %s' , EPseries )
480- except urllib2 . URLError , e :
506+ except URLError as e :
481507 time .sleep (1 )
482508 retry -= 1
483509 logging .warn ('Retry downloading details data for: %s - %s' , EPseries , e )
@@ -516,8 +542,8 @@ def parseXdetails():
516542 os .remove (fileDir )
517543 logging .info ('Deleting %s due to TBA listings' , filename )
518544 showList .remove (edict ['epseries' ])
519- except OSError , e :
520- logging .warn ('Error Deleting: %s - %s.' % (e .filename , e . strerror ))
545+ except OSError as e :
546+ logging .warn ('Error Deleting: %s - %s.' % (e .filename , str ( e ) ))
521547 except Exception as e :
522548 logging .exception ('Could not parse TBAcheck for: %s - %s' , episode , e )
523549 else :
@@ -690,12 +716,13 @@ def makeDescsortList(optList):
690716 if not os .path .exists (fileDir ):
691717 try :
692718 logging .info ('Downloading guide data for: %s' , str (gridtime ))
693- url = 'http ://tvlistings.zap2it .com/api/grid?lineupId=×pan=3&headendId=' + lineupcode + '&country=' + country + '&device=' + device + '&postalCode=' + zipcode + '&time=' + str (gridtime ) + '&pref=-&userId=-'
694- saveContent = urllib2 . urlopen (url ).read ()
719+ url = 'https ://tvlistings.gracenote .com/api/grid?lineupId=×pan=3&headendId=' + lineupcode + '&country=' + country + '&device=' + device + '&postalCode=' + zipcode + '&time=' + str (gridtime ) + '&pref=-&userId=-'
720+ saveContent = urlopen (url ).read ()
695721 savepage (fileDir , saveContent )
696- except :
722+ except Exception as e :
697723 logging .warn ('Could not download guide data for: %s' , str (gridtime ))
698724 logging .warn ('URL: %s' , url )
725+ logging .warn ('Exception: %s' , str (e ))
699726 if os .path .exists (fileDir ):
700727 try :
701728 with gzip .open (fileDir , 'rb' ) as f :
@@ -709,10 +736,11 @@ def makeDescsortList(optList):
709736 try :
710737 os .remove (fileDir )
711738 logging .info ('Deleting %s due to TBA listings' , filename )
712- except OSError , e :
713- logging .warn ('Error Deleting: %s - %s.' % (e .filename , e . strerror ))
714- except :
739+ except OSError as e :
740+ logging .warn ('Error Deleting: %s - %s.' % (e .filename , str ( e ) ))
741+ except Exception as e :
715742 logging .warn ('JSON file error for: %s - deleting file' , filename )
743+ logging .warn ('Exception: %s' , str (e ))
716744 os .remove (fileDir )
717745 count += 1
718746 gridtime = gridtime + 10800
@@ -727,7 +755,7 @@ def makeDescsortList(optList):
727755 logging .info ('%s Stations and %s Episodes written to xmltv.xml file.' , str (stationCount ), str (episodeCount ))
728756 return timeRun , stationCount , episodeCount
729757 except Exception as e :
730- logging .exception ('Exception: main' )
758+ logging .exception ('Exception: main ' + str ( e ) )
731759
732760
733761if __name__ == '__main__' :
0 commit comments