alexdunlop81

abc merged nossl

Jul 21st, 2013
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 16.28 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*
  3. import xbmcplugin
  4. import xbmc
  5. import xbmcgui
  6. import simplejson
  7. import os
  8. import urllib
  9. import urllib2
  10. import re
  11. import subprocess
  12. import sys
  13. import time
  14. from BeautifulSoup import BeautifulStoneSoup
  15. #from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
  16. #from SocketServer import ThreadingMixIn
  17. import resources.lib._common as common
  18. import resources.lib._connection as connection
  19. #from threading import Thread
  20. import _addoncompat
  21. import m3u8
  22. pluginHandle = int(sys.argv[1])
  23.  
  24. BRANDID = '001'
  25. SITE = 'abc'
  26. PARTNERID = '585231'
  27. SHOWLIST = 'http://api.watchabc.go.com/vp2/ws/s/contents/2015/shows/jsonp/' + BRANDID + '/001/-1'
  28. VIDEOLIST = 'http://api.watchabc.go.com/vp2/ws/s/contents/2015/videos/jsonp/' + BRANDID + '/001/'
  29. LIVETV = 'http://api.watchabc.go.com/vp2/ws/s/contents/2015/channels/jsonp/' + BRANDID + '/001/'
  30. VIDEOURL = 'http://api.watchabc.go.com/vp2/ws/s/contents/2015/videos/jsonp/' + BRANDID + '/001/'
  31. CLOSEDCAPTIONHOST = 'http://cdn.video.abc.com'
  32. GETAUTHORIZATION = 'http://api.watchdisneychannel.go.com/vp2/ws-secure/entitlement/2015/authorize/json'
  33. PLAYLISTULNK = 'http://www.kaltura.com/p/' + PARTNERID + '/sp/' + PARTNERID + '00/playManifest/format/http/entryId/'
  34.  
  35.  
  36. def masterlist():
  37.     master_db = []
  38.     master_data = connection.getURL(SHOWLIST)
  39.     master_menu = simplejson.loads(root_data)['shows']['show']
  40.     for master_item in master_menu:
  41.         master_name = master_item['title']
  42.         season_id = master_item['@id']
  43.         master_db.append((master_name, SITE,'seasons',season_id))
  44.     return master_db
  45.  
  46. def rootlist():
  47.     root_data = connection.getURL(LIVETV)
  48.     if int(simplejson.loads(root_data)['channels']['@count']) > 0:
  49.         common.add_directory('--- Feeds ---', SITE,'feed', LIVETV)
  50.     root_data2 = connection.getURL(SHOWLIST)
  51.     root_menu2 = simplejson.loads(root_data2)['shows']['show']
  52.     for root_item in root_menu2:
  53.         if (int(root_item['clips']['count']['@total']) + int(root_item['fullepisodes']['count']['@total'])) > 0:
  54.             root_name = root_item['title']
  55.             season_id = root_item['@id']
  56.             common.add_show(root_name, SITE,'seasons',season_id)
  57.     common.set_view('tvshows')
  58.  
  59. def seasons(show_id = common.args.url):
  60.     xbmcplugin.addSortMethod(pluginHandle, xbmcplugin.SORT_METHOD_LABEL)
  61.     show_menu = []
  62.     show_numbers = []
  63.     clip_numbers = []
  64.     show_url = VIDEOLIST + '-1/' + show_id + '/-1/-1/-1/-1'
  65.     show_data = connection.getURL(show_url)
  66.     show_data2 = simplejson.loads(show_data)['videos']
  67.     show_count = int(show_data2['@count'])
  68.     if show_count > 1:
  69.         show_menu = show_data2['video']
  70.     elif show_count == 1:
  71.         show_menu.append(dict(show_data2['video']))
  72.     for show_item in show_menu:
  73.         if show_item['@type'] == 'lf':
  74.             if show_item['season']['@id'] not in show_numbers:
  75.                 show_numbers.append(show_item['season']['@id'])
  76.                 show_name = 'Season ' + show_item['season']['@id']
  77.                 show_url = VIDEOLIST + show_item['@type'] + '/' + show_id + '/' + show_item['season']['@id'] + '/-1/-1/-1'
  78.                 common.add_directory(show_name, SITE, 'episodes', show_url)
  79.         elif show_item['@type'] == 'sf':
  80.             if show_item['season']['@id'] not in clip_numbers:
  81.                 clip_numbers.append(show_item['season']['@id'])
  82.                 show_name = 'Season Clips ' + show_item['season']['@id']
  83.                 show_url = VIDEOLIST + show_item['@type'] + '/' + show_id + '/' + show_item['season']['@id'] + '/-1/-1/-1'
  84.                 common.add_directory(show_name, SITE, 'episodes', show_url)
  85.     common.set_view('seasons')
  86.  
  87. def episodes(episode_url=common.args.url):
  88.     episode_menu = []
  89.     episode_data = connection.getURL(episode_url)
  90.     episode_data2 = simplejson.loads(episode_data)['videos']
  91.     episode_count = int(episode_data2['@count'])
  92.     if episode_count > 1:
  93.         episode_menu = episode_data2['video']
  94.     elif episode_count == 1:
  95.         episode_menu.append(dict(episode_data2['video']))
  96.     for episode_item in episode_menu:
  97.         highest_height = -1
  98.         episode_name = episode_item['title']
  99.         episode_duration = int(episode_item['duration']['$'])/60000
  100.         episode_number = episode_item['number']
  101.         season_number = episode_item['season']['@id']
  102.         episode_id = episode_item['@id']
  103.         episode_type = episode_item['@type']
  104.         try:
  105.             episode_description = episode_item['longdescription']
  106.         except:
  107.             episode_description = episode_item['description']
  108.         try:
  109.             episode_airDate = episode_item['airdates']['airdate'].rsplit(' ',1)[0]
  110.         except:
  111.             episode_airDate = episode_item['airdates']['airdate'][0].rsplit(' ',1)[0]
  112.         try:
  113.             for episode_picture in episode_item['thumbnails']['thumbnail']:
  114.                 try:
  115.                     picture_height = int(episode_picture['@width'])
  116.                 except:
  117.                     if episode_picture['@type'] == 'source-16x9':
  118.                         picture_height = 720
  119.                     else:
  120.                         picture_height = 0
  121.                 if picture_height > highest_height:
  122.                     highest_height = picture_height
  123.                     episode_thumb = episode_picture['$']
  124.         except:
  125.             episode_thumb = episode_item['thumbnails']['thumbnail']['$']
  126.         u = sys.argv[0]
  127.         u += '?url="' + urllib.quote_plus(episode_id) + '#' + urllib.quote_plus(episode_type) + '"'
  128.         u += '&mode="' + SITE + '"'
  129.         u += '&sitemode="playVideo"'
  130.         infoLabels={'title' : episode_name,
  131.                     'plot' : episode_description,
  132.                     'premiered' : common.format_date(episode_airDate,'%a, %d %b %Y %H:%M:%S','%d.%m.%Y'),
  133.                     'duration' : episode_duration,
  134.                     'episode' : episode_number,
  135.                     'season' : season_number }
  136.         common.add_video(u,episode_name,episode_thumb,infoLabels=infoLabels)
  137.     common.set_view('episodes')
  138.  
  139. def feed(channel_url = common.args.url):
  140.     channel_menu = []
  141.     channel_data = connection.getURL(channel_url)
  142.     channel_data2 = simplejson.loads(channel_data)['channels']
  143.     channel_count = int(channel_data2['@count'])
  144.     if channel_count > 1:
  145.         channel_menu = channel_data2['channel']
  146.     elif channel_count == 1:
  147.         channel_menu.append(dict(channel_data2['channel']))
  148.     for channel_item in channel_menu:
  149.         channel_name = channel_item['title']
  150.         channel_id = channel_item['@id']
  151.         channel_thumb = channel_item['thumbnails']['thumbnail']['$']
  152.         channel_description = channel_item['longdescription']
  153.         channel_airDate = channel_item['availdate'].rsplit(' ',1)[0]
  154.         u = sys.argv[0]
  155.         u += '?url="' + urllib.quote_plus(channel_id) + '#live"'
  156.         u += '&mode="' + SITE + '"'
  157.         u += '&sitemode="playVideo"'
  158.         infoLabels={'title' : channel_name,
  159.                     'plot' : channel_description,
  160.                     }
  161.         common.add_video(u,channel_name,channel_thumb,infoLabels=infoLabels)
  162.     common.set_view('episodes')        
  163.        
  164. def playVideo(url=common.args.url):
  165.     video_id = url.split('#')[0]
  166.     video_type = url.split('#')[1]
  167.     video_url = VIDEOURL + '-1/-1/-1/' + video_id + '/-1/-1'
  168.     video_data = connection.getURL(video_url)
  169.     video_data2 = simplejson.loads(video_data)['videos']['video']
  170.     print video_data2
  171.     if (video_data2['closedcaption']['@enabled'] == 'true') and (_addoncompat.get_setting('enablesubtitles') == 'true'):
  172.         closedcaption = CLOSEDCAPTIONHOST + video_data2['closedcaption']['src']['$'].split('.com')[1]
  173.         convert_subtitles(closedcaption)
  174.     print video_data2['assets']
  175.     print video_data2['assets']['asset']
  176.     try:
  177.         for video_item in video_data2['assets']['asset']:
  178.             if video_item['@format'] == 'ULNK':
  179.                 video_url2 = video_item['$']#.replace('http','https')
  180.     except:
  181.         video_url2 = video_data2['assets']['asset']['$']#.replace('http','https')
  182.     video_id=video_id.replace('VDKA','')
  183.     video_auth = '?' + get_authorization(video_id, video_type)
  184.     print video_auth
  185.     hbitrate = -1
  186.     sbitrate = int(_addoncompat.get_setting('quality'))
  187.    
  188.     print "vi",video_id
  189.     #video_auth = '?' + get_authorization(video_id, 'live','c')
  190.     #print video_auth
  191.     #video_url = VIDEOURL + '-1/-1/-1/' + video_id + '/-1/-1'
  192.     video_url = PLAYLISTULNK + video_id + '/a.f4m?playbackContext=brand%3D' + BRANDID + '%26device%3D001'
  193.     video_data = connection.getURL(video_url)
  194.     #video_data2 = simplejson.loads(video_data)['videos']['video']
  195.     video_tree = BeautifulStoneSoup(video_data, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
  196.     #print video_data2
  197.     video_url2 = video_tree.find('media')['url']
  198.     #print "vt",video_tree.prettify()
  199.     useProxy = False   
  200.     print "V2",video_url2
  201.     if 'mp4' in video_url2:
  202.         finalurl=video_url2
  203.     else:
  204.         useProxy=True
  205.         #video_url2=video_url2+video_auth
  206.         #use json?
  207.         #video_url2=video_url2.replace('m3u8','json')
  208.     #   video_auth = '?' + get_authorization(video_id, video_type)
  209.         video_data2 = connection.getURL(video_url2)
  210.         #print "V2",video_data2
  211.         #json_data=simplejson.loads(video_data2)
  212.         #print json_data
  213.         video_url3 = m3u8.parse(video_data2)
  214.         playlists=video_url3.get('playlists')
  215.         #print "P",playlists
  216.         for video_index in playlists:
  217.             bitrate = int(video_index.get('stream_info')['bandwidth'])
  218.             if bitrate > hbitrate and bitrate <= (sbitrate * 1000):
  219.                 hbitrate = bitrate
  220.                 video_url4 = video_index.get('uri')
  221.         video_data3 = re.sub(r"\#EXT-X-DISCONTINUITY\n","",connection.getURL(video_url4))
  222.         keyurl=re.compile('URI="(.*?)"').findall(video_data3)[0]
  223.         key_data = connection.getURL(keyurl)
  224.        
  225.         #try:
  226.         port=8080
  227.         #start_server(port,key_data)
  228.         #key_data="Test"
  229.     #   server=thread.start_new_thread( start_server, (port, key_data, ) )
  230.     #   MyHandler._key=key_data
  231.     #   server = ThreadedHTTPServer(('',port), MyHandler)
  232.         #server.serve_forever()
  233.     #   print "still unning"
  234.     #   th=threading.Thread(target=server.serve_forever)
  235.     #   th.daemon = True
  236.     #   th.start()
  237.     #thread.start_new_thread( print_time, ("Thread-2", 4, ) )
  238.         #except:
  239.         #   print "Error: unable to start thread"
  240.         keypath=os.path.join(common.PLUGINPATH,'resources','cache','play.key')
  241.         #keypath=os.path.join('U:\\','play.key')
  242.         keyfile = open(keypath, 'w')
  243.         keyfile.write(key_data)
  244.         keyfile.close()
  245.         filestring="XBMC.RunScript("+os.path.join(common.PLUGINPATH,'resources','lib','proxy.py')+","+keypath+","+str(port)+")"
  246.         print "EXE",str(filestring)
  247.         xbmc.executebuiltin(filestring)
  248.         time.sleep(2)
  249.         #print "kd",key_data
  250.         host="http://127.0.0.1"
  251.         #if port !=80:
  252.         #newkeyurl="http://elf"
  253.         host=host+":"+str(port)
  254.         newkeyurl=host
  255.         #/play.key"
  256.         video_data3 = video_data3.replace(keyurl,newkeyurl)#re.sub(rkeyurl,"http://abc.key",video_data3)
  257.         file = open(os.path.join(common.PLUGINPATH,'resources','cache','play.m3u8'), 'w')
  258.         file.write(video_data3)
  259.         file.close()
  260.         finalurl=os.path.join(common.PLUGINPATH,'resources','cache','play.m3u8')
  261.     print "Before******************************"
  262.     xbmcplugin.setResolvedUrl(pluginHandle, True, xbmcgui.ListItem(path = finalurl))
  263.     print "After,**************"
  264.     #global done
  265.     #done=True
  266.     if useProxy:
  267.         print "Stopping Server",host+'/stop'
  268.         connection.getURL('http://localhost:8080/stop')
  269.     if (_addoncompat.get_setting('enablesubtitles') == 'true') and (closedcaption != 'false'):
  270.         while not xbmc.Player().isPlaying():
  271.             xbmc.sleep(100)
  272.         subtitles = os.path.join(common.PLUGINPATH,'resources','cache','subtitle.srt')
  273.         xbmc.Player().setSubtitles(subtitles)
  274.    
  275.    
  276. # def playVideo(video_id_type = common.args.url):
  277.     # video_id, video_type = video_id_type.split('#')
  278.     # hbitrate = -1
  279.     # sbitrate = int(_addoncompat.get_setting('quality'))
  280.     # if video_type != 'live':
  281.         # video_auth = '?' + get_authorization(video_id, video_type)
  282.     # else:
  283.         # video_auth = '?' + get_authorization(video_id, video_type,'c')
  284.     # video_url = VIDEOURL + '-1/-1/-1/' + video_id + '/-1/-1'
  285.     # video_data = connection.getURL(video_url)
  286.     # video_data2 = simplejson.loads(video_data)['videos']['video']
  287.     # try:
  288.         # for video_item in video_data2['assets']['asset']:
  289.             # if video_item['@format'] == 'ULNK':
  290.                 # video_url2 = video_item['$'].replace('http','https')
  291.     # except:
  292.         # video_url2 = video_data2['assets']['asset']['$'].replace('http','https')
  293.     # print "vu2",video_url2
  294.     # video_data3 = connection.getURL(video_url2.replace('.m3u8','.json') + video_auth)
  295.     # video_url3 = simplejson.loads(video_data3)
  296.     # video_data4 = connection.getURL(video_url3['url'])
  297.    # bitrates = {    'a' : 57834,
  298.                    # 'b' : 107369,
  299.                    # 'c' : 189486,
  300.                    # 'd' : 351671,
  301.                    # 'e' : 584917,
  302.                    # 'f' : 1005810,
  303.                    # 'g' : 2080699,129
  304.                    # 'h' : 5014560 }
  305.    # for video_keys in video_data4['rays']:
  306.        # bitrate = int(video_index['bps'])
  307.        # if bitrate > hbitrate and bitrate <= (sbitrate * 1000):
  308.            # hbitrate = bitrate
  309.            # video_url3 = video_data4['url'].replace('__ray__',video_index['ray'])
  310.     # if video_type != 'live':
  311.         # video_data5 = simplejson.loads(video_data4)
  312.         # print video_data5
  313.         # no keys in json
  314.         # # m3u8data=video_data5['m3u8']
  315.         # getchild = video_data5['keys'].iterkeys().next()
  316.         # keytoreplace = '__key_' + getchild + '__'
  317.         # newkey = video_data5['keys'][getchild]['h']#.rstrip('\r\n')
  318.         # keyurl=re.compile('URI="(.*?)"').findall(m3u8data)[0]
  319.         # print "KEY",keyurl
  320.         # key_data = connection.getURL(keyurl+video_auth)
  321.         # keyfile = os.path.join(common.PLUGINPATH,'resources','cache','play.key')
  322.         # file = open(keyfile, 'w')
  323.         # file.write(key_data)
  324.         # file.close()
  325.         # video_data6 = video_data5['m3u8'].replace('#EXT-X-DISCONTINUITY\n','').replace('__RAY__','H').replace(keyurl,'http://127.0.0.1:8080')
  326.         #video_data6 = video_data5['m3u8'].replace('#EXT-X-DISCONTINUITY\n','')
  327.         # file = open(os.path.join(common.PLUGINPATH,'resources','cache','play.m3u8'), 'w')
  328.         # file.write(video_data6)
  329.         # file.close()
  330.         # finalurl = os.path.join(common.PLUGINPATH,'resources','cache','play.m3u8')
  331.     # else:
  332.         # finalurl = video_url3.replace('json','m3u8')
  333.     # filestring="XBMC.RunScript("+os.path.join(common.PLUGINPATH,'resources','lib','proxy.py')+","+keyfile+","+str(8080)+")"
  334.     # print "EXE",str(filestring)
  335.     # xbmc.executebuiltin(filestring)
  336.     # time.sleep(2)
  337.  
  338.     # if (video_data2['closedcaption']['@enabled'] == 'true') and (_addoncompat.get_setting('enablesubtitles') == 'true'):
  339.         # closedcaption = CLOSEDCAPTIONHOST + video_data2['closedcaption']['src']['$'].split('.com')[1]
  340.         # convert_subtitles(closedcaption)
  341.     # xbmcplugin.setResolvedUrl(pluginHandle, True, xbmcgui.ListItem(path=finalurl))
  342.     # if (_addoncompat.get_setting('enablesubtitles') == 'true') and (closedcaption != 'false'):
  343.         # while not xbmc.Player().isPlaying():
  344.             # xbmc.sleep(100)
  345.         # subtitles = os.path.join(common.pluginpath,'resources','cache','subtitle.srt')
  346.         # xbmc.Player().setSubtitles(subtitles)
  347.        
  348.     # print "Stopping Server",host+'/stop'
  349.     # connection.getURL('http://localhost:8080/stop')
  350.        
  351. def clean_subs(data):
  352.     br = re.compile(r'<br.*?>')
  353.     br_2 = re.compile(r'\n')
  354.     tag = re.compile(r'<.*?>')
  355.     space = re.compile(r'\s\s\s+')
  356.     sub = br.sub('\n', str(data))
  357.     sub = tag.sub(' ', sub)
  358.     sub = br_2.sub('<br/>', sub)
  359.     sub = space.sub(' ', sub)
  360.     return sub
  361.  
  362. def convert_subtitles(xml_closedcaption):
  363.     subtitle_array = []
  364.     str_output = ''
  365.     subtitle_data = connection.getURL(xml_closedcaption)
  366.     subtitle_data = BeautifulStoneSoup(subtitle_data, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
  367.     lines = subtitle_data.findAll('p')
  368.     for i, line in enumerate(lines):
  369.         if line is not None:
  370.             sub = clean_subs(line).decode('utf-8').encode('utf-8', 'ignore')
  371.             try:
  372.                 newsub = sub
  373.                 sub = BeautifulStoneSoup(sub, convertEntities=BeautifulStoneSoup.ALL_ENTITIES)
  374.             except:
  375.                 sub = newsub
  376.             start_time_hours, start_time_rest = line['begin'].split(':',1)
  377.             start_time_hours = '%02d' % (int(start_time_hours) - 1)
  378.             start_time = start_time_hours + ':' + start_time_rest.replace('.',',')
  379.             end_time_hours, end_time_rest = line['end'].split(':',1)
  380.             end_time_hours = '%02d' % (int(end_time_hours) - 1)
  381.             end_time = end_time_hours + ':' + end_time_rest.replace('.',',')
  382.             str_output += str(i+1) + '\n' + str(start_time) + ' --> ' + str(end_time) + '\n' + str(sub) + '\n\n'
  383.     file = open(os.path.join(common.PLUGINPATH,'resources','cache','subtitle.srt'), 'w')
  384.     file.write(str_output)
  385.     file.close()
  386.     return True
  387.  
  388. def get_authorization(video_id, video_type, uplynk_ct = False):
  389.     auth_time =  time.time()
  390.     parameters = {    'video_id' : video_id,
  391.                     '__rnd' : auth_time,
  392.                     'affiliate' : 'KABC',
  393.                     'city' : 'los angeles',
  394.                     'device' : '001',
  395.                     'brand' : BRANDID,
  396.                     'latitude' : 0,
  397.                     'longitude' : 0,
  398.                     'video_type' : video_type,
  399.                     'zipcode' : '90011' }
  400.     if uplynk_ct:
  401.         parameters['uplynk_ct'] = uplynk_ct,
  402.     auth_data = connection.getURL(GETAUTHORIZATION, parameters)
  403.     try:
  404.         auth_sig = simplejson.loads(auth_data)['entitlement']['uplynk']['sessionKey']
  405.     except:
  406.         auth_sig = ''
  407.     return auth_sig
Advertisement
Add Comment
Please, Sign In to add comment