Skip to content

Commit d6263c7

Browse files
authored
Merge pull request #4 from mathieugouin/fix-download-2
Fix download not working anymore
2 parents d252952 + c5ef0e8 commit d6263c7

File tree

1 file changed

+49
-14
lines changed

1 file changed

+49
-14
lines changed

zap2epg.py

Lines changed: 49 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,48 @@
3636
from collections import OrderedDict
3737

3838

39+
def fetch_url(string, options):
40+
url = 'https://tvlistings.gracenote.com'
41+
data = None #initialize variable
42+
if string == 'postal': #default.py line 201
43+
substring = "/gapzap_webapi/api/Providers/getPostalCodeProviders/{}/{}/gapzap/en".format(
44+
options['country'], options['zipcodeNew']
45+
)
46+
elif string == 'lineup': #default.py line 113, zap2epg.py line 768
47+
substring = ("/api/grid?aid=orbebb&TMSID=&AffiliateID=lat&FromPage=TV%20Grid&lineupId=&timespan=3"
48+
"&headendId={}&country={}&device={}&postalCode={}&time={}&isOverride=true&pref=-&userId=-").format(
49+
options['lineupcode'], options['country'], options['device'], options['zipcode'], options['gridtime']
50+
)
51+
elif string == 'programDetails': #zap2epg line 566
52+
substring = '/api/program/overviewDetails'
53+
data = options['data_encode']
54+
55+
try:
56+
combinedURL = url + substring
57+
58+
if isinstance(data, str):
59+
data = data.encode('utf-8') # encode string to bytes
60+
61+
headers = [
62+
("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:115.0) Gecko/20100101 Firefox/115.0"),
63+
("Accept", "application/json"),
64+
("Accept-Language", "en-US,en;q=0.9"),
65+
]
66+
req = Request(combinedURL, data=data, headers=dict(headers))
67+
resp = urlopen(req)
68+
return resp.read()
69+
except HTTPError as e:
70+
logging.warning("HTTP Error: {} - {}".format(e.code, e.reason))
71+
if e.code == 429: #Too Many Requests
72+
time.sleep(2)
73+
except URLError as e:
74+
logging.warning("URL Error: {}".format(e.reason))
75+
except Exception as e:
76+
logging.warning("Error Type: {}: {}".format(type(e).__name__, e))
77+
finally:
78+
resp.close()
79+
80+
3981
def mainRun(userdata):
4082
settingsFile = os.path.join(userdata, 'settings.xml')
4183
settings = ET.parse(settingsFile)
@@ -53,7 +95,6 @@ def mainRun(userdata):
5395
settingStr = None
5496
settingID = setting.get('id')
5597
settingsDict[settingID] = settingStr
56-
useragent = "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0"
5798
for setting in settingsDict:
5899
if setting == 'slist':
59100
stationList = settingsDict[setting]
@@ -101,7 +142,7 @@ def mainRun(userdata):
101142
country = 'USA'
102143
else:
103144
country = 'CAN'
104-
logging.info('Running zap2epg-1.3.5 for zipcode: %s and lineup: %s', zipcode, lineup)
145+
logging.info('Running zap2epg-1.3.6 for zipcode: %s and lineup: %s', zipcode, lineup)
105146
pythonStartTime = time.time()
106147
cacheDir = os.path.join(userdata, 'cache')
107148
dayHours = int(days) * 8 # set back to 8 when done testing
@@ -174,7 +215,6 @@ def convTime(t):
174215
def savepage(fileDir, data):
175216
with gzip.open(fileDir, "wb+") as f:
176217
f.write(data)
177-
f.close()
178218

179219
def genreSort(EPfilter, EPgenre):
180220
genreList = []
@@ -490,22 +530,20 @@ def parseXdetails():
490530
retry = 3
491531
while retry > 0:
492532
logging.info('Downloading details data for: %s', EPseries)
493-
url = 'https://tvlistings.gracenote.com/api/program/overviewDetails'
494533
data = 'programSeriesID=' + EPseries
495534
data_encode = data.encode('utf-8')
496535
try:
497-
URLcontent = Request(url, data=data_encode, headers={'User-Agent': useragent})
498-
JSONcontent = urlopen(URLcontent).read()
536+
URLcontent = fetch_url('programDetails', {'data_encode': data_encode})
537+
JSONcontent = json.dumps(json.loads(URLcontent)).encode('utf-8')
499538
if JSONcontent:
500539
with open(fileDir, "wb+") as f:
501540
f.write(JSONcontent)
502-
f.close()
503541
retry = 0
504542
else:
505543
time.sleep(1)
506544
retry -= 1
507545
logging.warn('Retry downloading missing details data for: %s', EPseries)
508-
except URLError as e:
546+
except Exception as e:
509547
time.sleep(1)
510548
retry -= 1
511549
logging.warn('Retry downloading details data for: %s - %s', EPseries, e)
@@ -514,7 +552,6 @@ def parseXdetails():
514552
if fileSize > 0:
515553
with open(fileDir, 'rb') as f:
516554
EPdetails = json.loads(f.read())
517-
f.close()
518555
logging.info('Parsing %s', filename)
519556
edict['epimage'] = EPdetails.get('seriesImage')
520557
edict['epfan'] = EPdetails.get('backgroundImage')
@@ -702,6 +739,7 @@ def makeDescsortList(optList):
702739
except Exception as e:
703740
logging.exception('Exception: addXdetails to description')
704741

742+
# mainRun code:
705743
try:
706744
if not os.path.exists(cacheDir):
707745
os.mkdir(cacheDir)
@@ -718,19 +756,16 @@ def makeDescsortList(optList):
718756
if not os.path.exists(fileDir):
719757
try:
720758
logging.info('Downloading guide data for: %s', str(gridtime))
721-
url = 'https://tvlistings.gracenote.com/api/grid?lineupId=&timespan=3&headendId=' + lineupcode + '&country=' + country + '&device=' + device + '&postalCode=' + zipcode + '&time=' + str(gridtime) + '&pref=-&userId=-'
722-
req = Request(url, data=None, headers={'User-Agent': useragent})
723-
saveContent = urlopen(req).read()
759+
options = {'lineupcode': lineupcode, 'country': country, 'device': device, 'zipcode': zipcode, 'gridtime': str(gridtime)}
760+
saveContent = fetch_url('lineup', options)
724761
savepage(fileDir, saveContent)
725762
except Exception as e:
726763
logging.warn('Could not download guide data for: %s', str(gridtime))
727-
logging.warn('URL: %s', url)
728764
logging.warn('Exception: %s', str(e))
729765
if os.path.exists(fileDir):
730766
try:
731767
with gzip.open(fileDir, 'rb') as f:
732768
content = f.read()
733-
f.close()
734769
logging.info('Parsing %s', filename)
735770
if count == 0:
736771
parseStations(content)

0 commit comments

Comments
 (0)