Advertisement
caffeinatedmike

addon.py sample

Jul 27th, 2018
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.33 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. import xbmcplugin, xbmcaddon, xbmcgui, xbmc
  3. import requests, json, sys, re, os
  4. from urlparse import parse_qsl
  5. from urllib import urlencode
  6.  
  7. _url = sys.argv[0]
  8. _handle = int(sys.argv[1])
  9. addon_id = 'plugin.video.OUTPUTADDONNAME'
  10. addon = xbmcaddon.Addon(id=addon_id)
  11. addonname = addon.getAddonInfo('name')
  12. path = 'special://home/addons/%s/' % addon_id
  13. icon = addon.getAddonInfo('icon')
  14. fanart = addon.getAddonInfo('fanart')
  15. dialog = xbmcgui.Dialog()
  16.  
  17. ytplaylive = 'plugin://plugin.video.youtube/play/?channel_id={0}&live=1'
  18. ytplayvideo = 'plugin://plugin.video.youtube/play/?video_id={0}'
  19. ytplaylist = 'plugin://plugin.video.youtube/play/?playlist_id={0}&play=1&order={1}'
  20. BASE_URL = 'https://www.googleapis.com/youtube/v3'
  21. API_KEY = addon.getSetting('OUTPUTADDONNAME.api.key')
  22. CHANNEL_ID = addon.getSetting('OUTPUTADDONNAME.channel.key')
  23. MAX_RESULTS = 25
  24. SEARCH_QUERY = ''
  25.  
  26. MENU_ITEMS = ['Playlists',
  27.               'MostRecentVideos',
  28.               'MostViewedVideos',
  29.               'PopularUploads',
  30.               'HighestRatedVideos',
  31.               'CompletedLiveStreams',
  32.               'ViewLiveStreams',
  33.               'PlayRandomVideo',
  34.               'PlayRandomContinuous',
  35.               'Search']
  36.  
  37. """_____________________________________________________________
  38. Helper Functions
  39. These help to keep the addon organized and easy to implement
  40. _____________________________________________________________"""
  41. def get_url(**kwargs):
  42.     try: kwargs = {k: unicode(v).encode('ascii', 'ignore') for k,v in kwargs.iteritems()}
  43.     except: pass
  44.     return '{0}?{1}'.format(_url, urlencode(kwargs))
  45.  
  46. def addItem(text, url, isFolder, endDirectory=False, hasThumb=None, isPlayable=False, hasContext=False):
  47.     list_item = xbmcgui.ListItem(label=text)
  48.     if hasThumb is None:
  49.         hasThumb = icon
  50.     list_item.setArt({'thumb':hasThumb, 'fanart':fanart})
  51.     if hasContext:
  52.         params = dict(parse_qsl(url))
  53.         playlistId = params.get('playlist')
  54.         list_item.addContextMenuItems([(
  55.                 'Shuffle & Play All',
  56.                 'RunPlugin({0})'.format(ytplaylist.format(playlistId, 'shuffle'))
  57.         )])
  58.     if isPlayable:
  59.         list_item.setProperty('IsPlayable','true')
  60.     xbmcplugin.addDirectoryItem(_handle, url, list_item, isFolder)
  61.     if endDirectory:
  62.         xbmcplugin.addSortMethod(_handle, xbmcplugin.SORT_METHOD_NONE)
  63.         xbmcplugin.endOfDirectory(_handle)
  64.  
  65. def getEndpoint(channel, section, page=None, playlist=None, query=None):
  66.     if section == 'Playlists':
  67.         if playlist:
  68.             url = '/'.join([BASE_URL, 'playlistItems?'])
  69.             url += urlencode({'key':API_KEY,'maxResults':MAX_RESULTS,'channelId':channel,'playlistId':playlist,'part':'snippet,contentDetails'})
  70.         else:
  71.             url = '/'.join([BASE_URL, 'playlists?'])
  72.             url += urlencode({'key':API_KEY,'maxResults':MAX_RESULTS,'channelId':channel,'part':'snippet,contentDetails'})
  73.     elif section == 'MostRecentVideos':
  74.         url = '/'.join([BASE_URL, 'search?'])
  75.         url += urlencode({'key':API_KEY,'maxResults':MAX_RESULTS,'channelId':channel,'part':'snippet','type':'video','order':'date'})
  76.     elif section == 'MostViewedVideos':
  77.         url = '/'.join([BASE_URL, 'search?'])
  78.         url += urlencode({'key':API_KEY,'maxResults':MAX_RESULTS,'channelId':channel,'part':'snippet','type':'video','order':'viewCount'})
  79.     elif section == 'PopularUploads':
  80.         url = '/'.join([BASE_URL, 'search?'])
  81.         pId = 'PU{0}'.format(channel[2:])
  82.         url += urlencode({'key':API_KEY,'maxResults':MAX_RESULTS,'channelId':channel,'playlistId':pId,'part':'snippet','type': 'video'})
  83.     elif section.startswith('PlayRandom'):
  84.         url = '/'.join([BASE_URL, 'playlistItems?'])
  85.         pId = 'UU{0}'.format(channel[2:])
  86.         url += urlencode({'key':API_KEY,'maxResults':MAX_RESULTS,'channelId':channel,'playlistId':pId,'part':'snippet,contentDetails','type': 'video'})
  87.     elif section == 'HighestRatedVideos':
  88.         url = '/'.join([BASE_URL, 'search?'])
  89.         url += urlencode({'key':API_KEY,'maxResults':MAX_RESULTS,'channelId':channel,'part':'snippet','type':'video','order': 'rating'})
  90.     elif section == 'CompletedLiveStreams':
  91.         url = '/'.join([BASE_URL, 'search?'])
  92.         url += urlencode({'key':API_KEY,'maxResults':MAX_RESULTS,'channelId':channel,'part':'snippet','type':'video','order':'date','eventType':'completed'})
  93.     elif section == 'ViewLiveStream':
  94.         url = '/'.join([BASE_URL, 'search?'])
  95.         url += urlencode({'key':API_KEY,'maxResults':MAX_RESULTS,'channelId':channel,'part':'snippet','type':'video','eventType':'live'})
  96.     elif section == 'Search':
  97.         url = '/'.join([BASE_URL, 'search?'])
  98.         url += urlencode({'key':API_KEY,'maxResults':MAX_RESULTS,'channelId':channel,'q':query,'part':'snippet','type':'video','order':'relevance'})
  99.     if page:
  100.         url += '&pageToken={0}'.format(page)
  101.     return url
  102.  
  103. def getImage(item):
  104.     #Get the best quality available
  105.     try: thumbnails = item['snippet']['thumbnails']
  106.     except: return None
  107.     try: return thumbnails['maxres']['url']
  108.     except: pass
  109.     try: return thumbnails['high']['url']
  110.     except: pass
  111.     try: return thumbnails['medium']['url']
  112.     except: pass
  113.     try: return thumbnails['standard']['url']
  114.     except: pass
  115.     try: return thumbnails['default']['url']
  116.     except: return None
  117.  
  118. """_____________________________________________________________
  119. End Helper Functions
  120. _____________________________________________________________"""
  121.  
  122. def mainMenu():
  123.     addItem('[COLOR red][B]___Welcome to %s___[/B][/COLOR]' % addonname, '', isFolder=False)
  124.     for i, mItem in enumerate(MENU_ITEMS):
  125.         url = get_url(section=mItem)
  126.         itemText = re.sub(r"(\w)([A-Z])", r"\1 \2", mItem)
  127.         if mItem.startswith('PlayRandom'):
  128.             addItem(itemText, url, isFolder=False)
  129.         else:
  130.             addItem(itemText, url, isFolder=True)
  131.     addItem('[COLOR red][B]___Welcome to %s___[/B][/COLOR]' % addonname, '', isFolder=False, endDirectory=True)
  132.  
  133. def drawSection(section, page=None, playlist=None, query=None):
  134.     if section == 'Search':
  135.         query = dialog.input('[COLOR red][B]Enter Search Term[/B][/COLOR]')
  136.         if len(query) == 0:
  137.             quit()
  138.     apiCall = getEndpoint(CHANNEL_ID, section, page, playlist, query)
  139.     if section.startswith('PlayRandom'):
  140.         randomize(section, apiCall)
  141.         quit()
  142.     apiResp = requests.get(apiCall).json()
  143.     if len(apiResp['items']) > 0:
  144.         for item in apiResp['items']:
  145.             try:
  146.                 #Video from Search results
  147.                 url = ytplayvideo.format(item['id']['videoId'])
  148.                 context = False
  149.                 playable = True
  150.                 folder = False
  151.             except:
  152.                 try:
  153.                     #Video from a Playlist
  154.                     url = ytplayvideo.format(item['contentDetails']['videoId'])
  155.                     context = False
  156.                     playable = True
  157.                     folder = False
  158.                 except:
  159.                     #List of Playlists
  160.                     url = get_url(section=section, playlist=item['id'])
  161.                     context = True
  162.                     playable = False
  163.                     folder = True
  164.             image = getImage(item)
  165.             addItem(item['snippet']['title'], url, isFolder=folder, hasThumb=image, isPlayable=playable, hasContext=context)
  166.         if apiResp.get('nextPageToken') is not None:
  167.             url = get_url(section=section, page=apiResp['nextPageToken'])
  168.             addItem('[COLOR red][B]___Next Page___[/B][/COLOR]', url, isFolder=True, endDirectory=True)
  169.         else:
  170.             addItem('[COLOR red][B]___End of Directory___[/B][/COLOR]', '', isFolder=False, endDirectory=True)
  171.     else:
  172.         addItem('[COLOR red][B]___No Active Live Streams___[/B][/COLOR]', '', isFolder=False, endDirectory=True)
  173.  
  174. def randomize(section, apiCall):
  175.     if section.endswith('Video'):
  176.         vids = []
  177.         apiResp = requests.get(apiCall).json()
  178.         for item in apiResp['items']:
  179.             vid = ytplayvideo.format(item['contentDetails']['videoId'])
  180.             vids.append(vid)
  181.         while apiResp.get('nextPageToken') is not None:
  182.             apiResp = requests.get(apiCall + '&pageToken=' + apiResp['nextPageToken']).json()
  183.             for item in apiResp['items']:
  184.                 vid = ytplayvideo.format(item['contentDetails']['videoId'])
  185.                 vids.append(vid)
  186.         choice = random.choice(vids)
  187.         xbmc.executebuiltin('PlayMedia(%s)' % choice)
  188.     elif section.endswith('Continuous'):
  189.         playlistId = 'UU{0}'.format(CHANNEL_ID[2:])
  190.         xbmc.executebuiltin("xbmc.playercontrol(RepeatAll)")
  191.         xbmc.executebuiltin('RunPlugin(%s)' % ytplaylist.format(playlistId, 'shuffle'))
  192.  
  193. def router(paramstring):
  194.     params = dict(parse_qsl(sys.argv[2][1:]))
  195.     if params:
  196.         playlist = params.get('playlist')
  197.         section = params.get('section')
  198.         page = params.get('page')
  199.        
  200.         if playlist:
  201.             drawSection(section, page, playlist)
  202.         elif section:
  203.             drawSection(section, page)
  204.         else:
  205.             raise ValueError('Invalid paramstring: {0}!'.format(paramstring))
  206.     else:
  207.         mainMenu()
  208.        
  209. if __name__ == '__main__':
  210.     router(sys.argv[2][1:])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement