Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # -*- coding: utf-8 -*
- import xbmcplugin
- import xbmc
- import xbmcgui
- import simplejson
- import os
- import urllib
- import urllib2
- import re
- import subprocess
- import sys
- import time
- from BeautifulSoup import BeautifulStoneSoup
- #from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
- #from SocketServer import ThreadingMixIn
- import resources.lib._common as common
- import resources.lib._connection as connection
- #from threading import Thread
- import _addoncompat
- import m3u8
- pluginHandle = int(sys.argv[1])
- BRANDID = '001'
- SITE = 'abc'
- PARTNERID = '585231'
- SHOWLIST = 'http://api.watchabc.go.com/vp2/ws/s/contents/2015/shows/jsonp/' + BRANDID + '/001/-1'
- VIDEOLIST = 'http://api.watchabc.go.com/vp2/ws/s/contents/2015/videos/jsonp/' + BRANDID + '/001/'
- LIVETV = 'http://api.watchabc.go.com/vp2/ws/s/contents/2015/channels/jsonp/' + BRANDID + '/001/'
- VIDEOURL = 'http://api.watchabc.go.com/vp2/ws/s/contents/2015/videos/jsonp/' + BRANDID + '/001/'
- CLOSEDCAPTIONHOST = 'http://cdn.video.abc.com'
- GETAUTHORIZATION = 'http://api.watchdisneychannel.go.com/vp2/ws-secure/entitlement/2015/authorize/json'
- PLAYLISTULNK = 'http://www.kaltura.com/p/' + PARTNERID + '/sp/' + PARTNERID + '00/playManifest/format/http/entryId/'
- def masterlist():
- master_db = []
- master_data = connection.getURL(SHOWLIST)
- master_menu = simplejson.loads(root_data)['shows']['show']
- for master_item in master_menu:
- master_name = master_item['title']
- season_id = master_item['@id']
- master_db.append((master_name, SITE,'seasons',season_id))
- return master_db
- def rootlist():
- root_data = connection.getURL(LIVETV)
- if int(simplejson.loads(root_data)['channels']['@count']) > 0:
- common.add_directory('--- Feeds ---', SITE,'feed', LIVETV)
- root_data2 = connection.getURL(SHOWLIST)
- root_menu2 = simplejson.loads(root_data2)['shows']['show']
- for root_item in root_menu2:
- if (int(root_item['clips']['count']['@total']) + int(root_item['fullepisodes']['count']['@total'])) > 0:
- root_name = root_item['title']
- season_id = root_item['@id']
- common.add_show(root_name, SITE,'seasons',season_id)
- common.set_view('tvshows')
- def seasons(show_id = common.args.url):
- xbmcplugin.addSortMethod(pluginHandle, xbmcplugin.SORT_METHOD_LABEL)
- show_menu = []
- show_numbers = []
- clip_numbers = []
- show_url = VIDEOLIST + '-1/' + show_id + '/-1/-1/-1/-1'
- show_data = connection.getURL(show_url)
- show_data2 = simplejson.loads(show_data)['videos']
- show_count = int(show_data2['@count'])
- if show_count > 1:
- show_menu = show_data2['video']
- elif show_count == 1:
- show_menu.append(dict(show_data2['video']))
- for show_item in show_menu:
- if show_item['@type'] == 'lf':
- if show_item['season']['@id'] not in show_numbers:
- show_numbers.append(show_item['season']['@id'])
- show_name = 'Season ' + show_item['season']['@id']
- show_url = VIDEOLIST + show_item['@type'] + '/' + show_id + '/' + show_item['season']['@id'] + '/-1/-1/-1'
- common.add_directory(show_name, SITE, 'episodes', show_url)
- elif show_item['@type'] == 'sf':
- if show_item['season']['@id'] not in clip_numbers:
- clip_numbers.append(show_item['season']['@id'])
- show_name = 'Season Clips ' + show_item['season']['@id']
- show_url = VIDEOLIST + show_item['@type'] + '/' + show_id + '/' + show_item['season']['@id'] + '/-1/-1/-1'
- common.add_directory(show_name, SITE, 'episodes', show_url)
- common.set_view('seasons')
- def episodes(episode_url=common.args.url):
- episode_menu = []
- episode_data = connection.getURL(episode_url)
- episode_data2 = simplejson.loads(episode_data)['videos']
- episode_count = int(episode_data2['@count'])
- if episode_count > 1:
- episode_menu = episode_data2['video']
- elif episode_count == 1:
- episode_menu.append(dict(episode_data2['video']))
- for episode_item in episode_menu:
- highest_height = -1
- episode_name = episode_item['title']
- episode_duration = int(episode_item['duration']['$'])/60000
- episode_number = episode_item['number']
- season_number = episode_item['season']['@id']
- episode_id = episode_item['@id']
- episode_type = episode_item['@type']
- try:
- episode_description = episode_item['longdescription']
- except:
- episode_description = episode_item['description']
- try:
- episode_airDate = episode_item['airdates']['airdate'].rsplit(' ',1)[0]
- except:
- episode_airDate = episode_item['airdates']['airdate'][0].rsplit(' ',1)[0]
- try:
- for episode_picture in episode_item['thumbnails']['thumbnail']:
- try:
- picture_height = int(episode_picture['@width'])
- except:
- if episode_picture['@type'] == 'source-16x9':
- picture_height = 720
- else:
- picture_height = 0
- if picture_height > highest_height:
- highest_height = picture_height
- episode_thumb = episode_picture['$']
- except:
- episode_thumb = episode_item['thumbnails']['thumbnail']['$']
- u = sys.argv[0]
- u += '?url="' + urllib.quote_plus(episode_id) + '#' + urllib.quote_plus(episode_type) + '"'
- u += '&mode="' + SITE + '"'
- u += '&sitemode="playVideo"'
- infoLabels={'title' : episode_name,
- 'plot' : episode_description,
- 'premiered' : common.format_date(episode_airDate,'%a, %d %b %Y %H:%M:%S','%d.%m.%Y'),
- 'duration' : episode_duration,
- 'episode' : episode_number,
- 'season' : season_number }
- common.add_video(u,episode_name,episode_thumb,infoLabels=infoLabels)
- common.set_view('episodes')
- def feed(channel_url = common.args.url):
- channel_menu = []
- channel_data = connection.getURL(channel_url)
- channel_data2 = simplejson.loads(channel_data)['channels']
- channel_count = int(channel_data2['@count'])
- if channel_count > 1:
- channel_menu = channel_data2['channel']
- elif channel_count == 1:
- channel_menu.append(dict(channel_data2['channel']))
- for channel_item in channel_menu:
- channel_name = channel_item['title']
- channel_id = channel_item['@id']
- channel_thumb = channel_item['thumbnails']['thumbnail']['$']
- channel_description = channel_item['longdescription']
- channel_airDate = channel_item['availdate'].rsplit(' ',1)[0]
- u = sys.argv[0]
- u += '?url="' + urllib.quote_plus(channel_id) + '#live"'
- u += '&mode="' + SITE + '"'
- u += '&sitemode="playVideo"'
- infoLabels={'title' : channel_name,
- 'plot' : channel_description,
- }
- common.add_video(u,channel_name,channel_thumb,infoLabels=infoLabels)
- common.set_view('episodes')
- def playVideo(url=common.args.url):
- video_id = url.split('#')[0]
- video_type = url.split('#')[1]
- video_url = VIDEOURL + '-1/-1/-1/' + video_id + '/-1/-1'
- video_data = connection.getURL(video_url)
- video_data2 = simplejson.loads(video_data)['videos']['video']
- print video_data2
- if (video_data2['closedcaption']['@enabled'] == 'true') and (_addoncompat.get_setting('enablesubtitles') == 'true'):
- closedcaption = CLOSEDCAPTIONHOST + video_data2['closedcaption']['src']['$'].split('.com')[1]
- convert_subtitles(closedcaption)
- print video_data2['assets']
- print video_data2['assets']['asset']
- try:
- for video_item in video_data2['assets']['asset']:
- if video_item['@format'] == 'ULNK':
- video_url2 = video_item['$']#.replace('http','https')
- except:
- video_url2 = video_data2['assets']['asset']['$']#.replace('http','https')
- video_id=video_id.replace('VDKA','')
- video_auth = '?' + get_authorization(video_id, video_type)
- print video_auth
- hbitrate = -1
- sbitrate = int(_addoncompat.get_setting('quality'))
- print "vi",video_id
- #video_auth = '?' + get_authorization(video_id, 'live','c')
- #print video_auth
- #video_url = VIDEOURL + '-1/-1/-1/' + video_id + '/-1/-1'
- video_url = PLAYLISTULNK + video_id + '/a.f4m?playbackContext=brand%3D' + BRANDID + '%26device%3D001'
- video_data = connection.getURL(video_url)
- #video_data2 = simplejson.loads(video_data)['videos']['video']
- video_tree = BeautifulStoneSoup(video_data, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
- #print video_data2
- video_url2 = video_tree.find('media')['url']
- #print "vt",video_tree.prettify()
- useProxy = False
- print "V2",video_url2
- if 'mp4' in video_url2:
- finalurl=video_url2
- else:
- useProxy=True
- #video_url2=video_url2+video_auth
- #use json?
- #video_url2=video_url2.replace('m3u8','json')
- # video_auth = '?' + get_authorization(video_id, video_type)
- video_data2 = connection.getURL(video_url2)
- #print "V2",video_data2
- #json_data=simplejson.loads(video_data2)
- #print json_data
- video_url3 = m3u8.parse(video_data2)
- playlists=video_url3.get('playlists')
- #print "P",playlists
- for video_index in playlists:
- bitrate = int(video_index.get('stream_info')['bandwidth'])
- if bitrate > hbitrate and bitrate <= (sbitrate * 1000):
- hbitrate = bitrate
- video_url4 = video_index.get('uri')
- video_data3 = re.sub(r"\#EXT-X-DISCONTINUITY\n","",connection.getURL(video_url4))
- keyurl=re.compile('URI="(.*?)"').findall(video_data3)[0]
- key_data = connection.getURL(keyurl)
- #try:
- port=8080
- #start_server(port,key_data)
- #key_data="Test"
- # server=thread.start_new_thread( start_server, (port, key_data, ) )
- # MyHandler._key=key_data
- # server = ThreadedHTTPServer(('',port), MyHandler)
- #server.serve_forever()
- # print "still unning"
- # th=threading.Thread(target=server.serve_forever)
- # th.daemon = True
- # th.start()
- #thread.start_new_thread( print_time, ("Thread-2", 4, ) )
- #except:
- # print "Error: unable to start thread"
- keypath=os.path.join(common.PLUGINPATH,'resources','cache','play.key')
- #keypath=os.path.join('U:\\','play.key')
- keyfile = open(keypath, 'w')
- keyfile.write(key_data)
- keyfile.close()
- filestring="XBMC.RunScript("+os.path.join(common.PLUGINPATH,'resources','lib','proxy.py')+","+keypath+","+str(port)+")"
- print "EXE",str(filestring)
- xbmc.executebuiltin(filestring)
- time.sleep(2)
- #print "kd",key_data
- host="http://127.0.0.1"
- #if port !=80:
- #newkeyurl="http://elf"
- host=host+":"+str(port)
- newkeyurl=host
- #/play.key"
- video_data3 = video_data3.replace(keyurl,newkeyurl)#re.sub(rkeyurl,"http://abc.key",video_data3)
- file = open(os.path.join(common.PLUGINPATH,'resources','cache','play.m3u8'), 'w')
- file.write(video_data3)
- file.close()
- finalurl=os.path.join(common.PLUGINPATH,'resources','cache','play.m3u8')
- print "Before******************************"
- xbmcplugin.setResolvedUrl(pluginHandle, True, xbmcgui.ListItem(path = finalurl))
- print "After,**************"
- #global done
- #done=True
- if useProxy:
- print "Stopping Server",host+'/stop'
- connection.getURL('http://localhost:8080/stop')
- if (_addoncompat.get_setting('enablesubtitles') == 'true') and (closedcaption != 'false'):
- while not xbmc.Player().isPlaying():
- xbmc.sleep(100)
- subtitles = os.path.join(common.PLUGINPATH,'resources','cache','subtitle.srt')
- xbmc.Player().setSubtitles(subtitles)
- # def playVideo(video_id_type = common.args.url):
- # video_id, video_type = video_id_type.split('#')
- # hbitrate = -1
- # sbitrate = int(_addoncompat.get_setting('quality'))
- # if video_type != 'live':
- # video_auth = '?' + get_authorization(video_id, video_type)
- # else:
- # video_auth = '?' + get_authorization(video_id, video_type,'c')
- # video_url = VIDEOURL + '-1/-1/-1/' + video_id + '/-1/-1'
- # video_data = connection.getURL(video_url)
- # video_data2 = simplejson.loads(video_data)['videos']['video']
- # try:
- # for video_item in video_data2['assets']['asset']:
- # if video_item['@format'] == 'ULNK':
- # video_url2 = video_item['$'].replace('http','https')
- # except:
- # video_url2 = video_data2['assets']['asset']['$'].replace('http','https')
- # print "vu2",video_url2
- # video_data3 = connection.getURL(video_url2.replace('.m3u8','.json') + video_auth)
- # video_url3 = simplejson.loads(video_data3)
- # video_data4 = connection.getURL(video_url3['url'])
- # bitrates = { 'a' : 57834,
- # 'b' : 107369,
- # 'c' : 189486,
- # 'd' : 351671,
- # 'e' : 584917,
- # 'f' : 1005810,
- # 'g' : 2080699,129
- # 'h' : 5014560 }
- # for video_keys in video_data4['rays']:
- # bitrate = int(video_index['bps'])
- # if bitrate > hbitrate and bitrate <= (sbitrate * 1000):
- # hbitrate = bitrate
- # video_url3 = video_data4['url'].replace('__ray__',video_index['ray'])
- # if video_type != 'live':
- # video_data5 = simplejson.loads(video_data4)
- # print video_data5
- # no keys in json
- # # m3u8data=video_data5['m3u8']
- # getchild = video_data5['keys'].iterkeys().next()
- # keytoreplace = '__key_' + getchild + '__'
- # newkey = video_data5['keys'][getchild]['h']#.rstrip('\r\n')
- # keyurl=re.compile('URI="(.*?)"').findall(m3u8data)[0]
- # print "KEY",keyurl
- # key_data = connection.getURL(keyurl+video_auth)
- # keyfile = os.path.join(common.PLUGINPATH,'resources','cache','play.key')
- # file = open(keyfile, 'w')
- # file.write(key_data)
- # file.close()
- # video_data6 = video_data5['m3u8'].replace('#EXT-X-DISCONTINUITY\n','').replace('__RAY__','H').replace(keyurl,'http://127.0.0.1:8080')
- #video_data6 = video_data5['m3u8'].replace('#EXT-X-DISCONTINUITY\n','')
- # file = open(os.path.join(common.PLUGINPATH,'resources','cache','play.m3u8'), 'w')
- # file.write(video_data6)
- # file.close()
- # finalurl = os.path.join(common.PLUGINPATH,'resources','cache','play.m3u8')
- # else:
- # finalurl = video_url3.replace('json','m3u8')
- # filestring="XBMC.RunScript("+os.path.join(common.PLUGINPATH,'resources','lib','proxy.py')+","+keyfile+","+str(8080)+")"
- # print "EXE",str(filestring)
- # xbmc.executebuiltin(filestring)
- # time.sleep(2)
- # if (video_data2['closedcaption']['@enabled'] == 'true') and (_addoncompat.get_setting('enablesubtitles') == 'true'):
- # closedcaption = CLOSEDCAPTIONHOST + video_data2['closedcaption']['src']['$'].split('.com')[1]
- # convert_subtitles(closedcaption)
- # xbmcplugin.setResolvedUrl(pluginHandle, True, xbmcgui.ListItem(path=finalurl))
- # if (_addoncompat.get_setting('enablesubtitles') == 'true') and (closedcaption != 'false'):
- # while not xbmc.Player().isPlaying():
- # xbmc.sleep(100)
- # subtitles = os.path.join(common.pluginpath,'resources','cache','subtitle.srt')
- # xbmc.Player().setSubtitles(subtitles)
- # print "Stopping Server",host+'/stop'
- # connection.getURL('http://localhost:8080/stop')
- def clean_subs(data):
- br = re.compile(r'<br.*?>')
- br_2 = re.compile(r'\n')
- tag = re.compile(r'<.*?>')
- space = re.compile(r'\s\s\s+')
- sub = br.sub('\n', str(data))
- sub = tag.sub(' ', sub)
- sub = br_2.sub('<br/>', sub)
- sub = space.sub(' ', sub)
- return sub
- def convert_subtitles(xml_closedcaption):
- subtitle_array = []
- str_output = ''
- subtitle_data = connection.getURL(xml_closedcaption)
- subtitle_data = BeautifulStoneSoup(subtitle_data, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
- lines = subtitle_data.findAll('p')
- for i, line in enumerate(lines):
- if line is not None:
- sub = clean_subs(line).decode('utf-8').encode('utf-8', 'ignore')
- try:
- newsub = sub
- sub = BeautifulStoneSoup(sub, convertEntities=BeautifulStoneSoup.ALL_ENTITIES)
- except:
- sub = newsub
- start_time_hours, start_time_rest = line['begin'].split(':',1)
- start_time_hours = '%02d' % (int(start_time_hours) - 1)
- start_time = start_time_hours + ':' + start_time_rest.replace('.',',')
- end_time_hours, end_time_rest = line['end'].split(':',1)
- end_time_hours = '%02d' % (int(end_time_hours) - 1)
- end_time = end_time_hours + ':' + end_time_rest.replace('.',',')
- str_output += str(i+1) + '\n' + str(start_time) + ' --> ' + str(end_time) + '\n' + str(sub) + '\n\n'
- file = open(os.path.join(common.PLUGINPATH,'resources','cache','subtitle.srt'), 'w')
- file.write(str_output)
- file.close()
- return True
- def get_authorization(video_id, video_type, uplynk_ct = False):
- auth_time = time.time()
- parameters = { 'video_id' : video_id,
- '__rnd' : auth_time,
- 'affiliate' : 'KABC',
- 'city' : 'los angeles',
- 'device' : '001',
- 'brand' : BRANDID,
- 'latitude' : 0,
- 'longitude' : 0,
- 'video_type' : video_type,
- 'zipcode' : '90011' }
- if uplynk_ct:
- parameters['uplynk_ct'] = uplynk_ct,
- auth_data = connection.getURL(GETAUTHORIZATION, parameters)
- try:
- auth_sig = simplejson.loads(auth_data)['entitlement']['uplynk']['sessionKey']
- except:
- auth_sig = ''
- return auth_sig
Advertisement
Add Comment
Please, Sign In to add comment