Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- import xbmcplugin, xbmcaddon, xbmcgui, xbmc
- import requests, json, sys, re, os
- from urlparse import parse_qsl
- from urllib import urlencode
- _url = sys.argv[0]
- _handle = int(sys.argv[1])
- addon_id = 'plugin.video.OUTPUTADDONNAME'
- addon = xbmcaddon.Addon(id=addon_id)
- addonname = addon.getAddonInfo('name')
- path = 'special://home/addons/%s/' % addon_id
- icon = addon.getAddonInfo('icon')
- fanart = addon.getAddonInfo('fanart')
- dialog = xbmcgui.Dialog()
- ytplaylive = 'plugin://plugin.video.youtube/play/?channel_id={0}&live=1'
- ytplayvideo = 'plugin://plugin.video.youtube/play/?video_id={0}'
- ytplaylist = 'plugin://plugin.video.youtube/play/?playlist_id={0}&play=1&order={1}'
- BASE_URL = 'https://www.googleapis.com/youtube/v3'
- API_KEY = addon.getSetting('OUTPUTADDONNAME.api.key')
- CHANNEL_ID = addon.getSetting('OUTPUTADDONNAME.channel.key')
- MAX_RESULTS = 25
- SEARCH_QUERY = ''
- MENU_ITEMS = ['Playlists',
- 'MostRecentVideos',
- 'MostViewedVideos',
- 'PopularUploads',
- 'HighestRatedVideos',
- 'CompletedLiveStreams',
- 'ViewLiveStreams',
- 'PlayRandomVideo',
- 'PlayRandomContinuous',
- 'Search']
- """_____________________________________________________________
- Helper Functions
- These help to keep the addon organized and easy to implement
- _____________________________________________________________"""
- def get_url(**kwargs):
- try: kwargs = {k: unicode(v).encode('ascii', 'ignore') for k,v in kwargs.iteritems()}
- except: pass
- return '{0}?{1}'.format(_url, urlencode(kwargs))
- def addItem(text, url, isFolder, endDirectory=False, hasThumb=None, isPlayable=False, hasContext=False):
- list_item = xbmcgui.ListItem(label=text)
- if hasThumb is None:
- hasThumb = icon
- list_item.setArt({'thumb':hasThumb, 'fanart':fanart})
- if hasContext:
- params = dict(parse_qsl(url))
- playlistId = params.get('playlist')
- list_item.addContextMenuItems([(
- 'Shuffle & Play All',
- 'RunPlugin({0})'.format(ytplaylist.format(playlistId, 'shuffle'))
- )])
- if isPlayable:
- list_item.setProperty('IsPlayable','true')
- xbmcplugin.addDirectoryItem(_handle, url, list_item, isFolder)
- if endDirectory:
- xbmcplugin.addSortMethod(_handle, xbmcplugin.SORT_METHOD_NONE)
- xbmcplugin.endOfDirectory(_handle)
- def getEndpoint(channel, section, page=None, playlist=None, query=None):
- if section == 'Playlists':
- if playlist:
- url = '/'.join([BASE_URL, 'playlistItems?'])
- url += urlencode({'key':API_KEY,'maxResults':MAX_RESULTS,'channelId':channel,'playlistId':playlist,'part':'snippet,contentDetails'})
- else:
- url = '/'.join([BASE_URL, 'playlists?'])
- url += urlencode({'key':API_KEY,'maxResults':MAX_RESULTS,'channelId':channel,'part':'snippet,contentDetails'})
- elif section == 'MostRecentVideos':
- url = '/'.join([BASE_URL, 'search?'])
- url += urlencode({'key':API_KEY,'maxResults':MAX_RESULTS,'channelId':channel,'part':'snippet','type':'video','order':'date'})
- elif section == 'MostViewedVideos':
- url = '/'.join([BASE_URL, 'search?'])
- url += urlencode({'key':API_KEY,'maxResults':MAX_RESULTS,'channelId':channel,'part':'snippet','type':'video','order':'viewCount'})
- elif section == 'PopularUploads':
- url = '/'.join([BASE_URL, 'search?'])
- pId = 'PU{0}'.format(channel[2:])
- url += urlencode({'key':API_KEY,'maxResults':MAX_RESULTS,'channelId':channel,'playlistId':pId,'part':'snippet','type': 'video'})
- elif section.startswith('PlayRandom'):
- url = '/'.join([BASE_URL, 'playlistItems?'])
- pId = 'UU{0}'.format(channel[2:])
- url += urlencode({'key':API_KEY,'maxResults':MAX_RESULTS,'channelId':channel,'playlistId':pId,'part':'snippet,contentDetails','type': 'video'})
- elif section == 'HighestRatedVideos':
- url = '/'.join([BASE_URL, 'search?'])
- url += urlencode({'key':API_KEY,'maxResults':MAX_RESULTS,'channelId':channel,'part':'snippet','type':'video','order': 'rating'})
- elif section == 'CompletedLiveStreams':
- url = '/'.join([BASE_URL, 'search?'])
- url += urlencode({'key':API_KEY,'maxResults':MAX_RESULTS,'channelId':channel,'part':'snippet','type':'video','order':'date','eventType':'completed'})
- elif section == 'ViewLiveStream':
- url = '/'.join([BASE_URL, 'search?'])
- url += urlencode({'key':API_KEY,'maxResults':MAX_RESULTS,'channelId':channel,'part':'snippet','type':'video','eventType':'live'})
- elif section == 'Search':
- url = '/'.join([BASE_URL, 'search?'])
- url += urlencode({'key':API_KEY,'maxResults':MAX_RESULTS,'channelId':channel,'q':query,'part':'snippet','type':'video','order':'relevance'})
- if page:
- url += '&pageToken={0}'.format(page)
- return url
- def getImage(item):
- #Get the best quality available
- try: thumbnails = item['snippet']['thumbnails']
- except: return None
- try: return thumbnails['maxres']['url']
- except: pass
- try: return thumbnails['high']['url']
- except: pass
- try: return thumbnails['medium']['url']
- except: pass
- try: return thumbnails['standard']['url']
- except: pass
- try: return thumbnails['default']['url']
- except: return None
- """_____________________________________________________________
- End Helper Functions
- _____________________________________________________________"""
- def mainMenu():
- addItem('[COLOR red][B]___Welcome to %s___[/B][/COLOR]' % addonname, '', isFolder=False)
- for i, mItem in enumerate(MENU_ITEMS):
- url = get_url(section=mItem)
- itemText = re.sub(r"(\w)([A-Z])", r"\1 \2", mItem)
- if mItem.startswith('PlayRandom'):
- addItem(itemText, url, isFolder=False)
- else:
- addItem(itemText, url, isFolder=True)
- addItem('[COLOR red][B]___Welcome to %s___[/B][/COLOR]' % addonname, '', isFolder=False, endDirectory=True)
- def drawSection(section, page=None, playlist=None, query=None):
- if section == 'Search':
- query = dialog.input('[COLOR red][B]Enter Search Term[/B][/COLOR]')
- if len(query) == 0:
- quit()
- apiCall = getEndpoint(CHANNEL_ID, section, page, playlist, query)
- if section.startswith('PlayRandom'):
- randomize(section, apiCall)
- quit()
- apiResp = requests.get(apiCall).json()
- if len(apiResp['items']) > 0:
- for item in apiResp['items']:
- try:
- #Video from Search results
- url = ytplayvideo.format(item['id']['videoId'])
- context = False
- playable = True
- folder = False
- except:
- try:
- #Video from a Playlist
- url = ytplayvideo.format(item['contentDetails']['videoId'])
- context = False
- playable = True
- folder = False
- except:
- #List of Playlists
- url = get_url(section=section, playlist=item['id'])
- context = True
- playable = False
- folder = True
- image = getImage(item)
- addItem(item['snippet']['title'], url, isFolder=folder, hasThumb=image, isPlayable=playable, hasContext=context)
- if apiResp.get('nextPageToken') is not None:
- url = get_url(section=section, page=apiResp['nextPageToken'])
- addItem('[COLOR red][B]___Next Page___[/B][/COLOR]', url, isFolder=True, endDirectory=True)
- else:
- addItem('[COLOR red][B]___End of Directory___[/B][/COLOR]', '', isFolder=False, endDirectory=True)
- else:
- addItem('[COLOR red][B]___No Active Live Streams___[/B][/COLOR]', '', isFolder=False, endDirectory=True)
- def randomize(section, apiCall):
- if section.endswith('Video'):
- vids = []
- apiResp = requests.get(apiCall).json()
- for item in apiResp['items']:
- vid = ytplayvideo.format(item['contentDetails']['videoId'])
- vids.append(vid)
- while apiResp.get('nextPageToken') is not None:
- apiResp = requests.get(apiCall + '&pageToken=' + apiResp['nextPageToken']).json()
- for item in apiResp['items']:
- vid = ytplayvideo.format(item['contentDetails']['videoId'])
- vids.append(vid)
- choice = random.choice(vids)
- xbmc.executebuiltin('PlayMedia(%s)' % choice)
- elif section.endswith('Continuous'):
- playlistId = 'UU{0}'.format(CHANNEL_ID[2:])
- xbmc.executebuiltin("xbmc.playercontrol(RepeatAll)")
- xbmc.executebuiltin('RunPlugin(%s)' % ytplaylist.format(playlistId, 'shuffle'))
- def router(paramstring):
- params = dict(parse_qsl(sys.argv[2][1:]))
- if params:
- playlist = params.get('playlist')
- section = params.get('section')
- page = params.get('page')
- if playlist:
- drawSection(section, page, playlist)
- elif section:
- drawSection(section, page)
- else:
- raise ValueError('Invalid paramstring: {0}!'.format(paramstring))
- else:
- mainMenu()
- if __name__ == '__main__':
- router(sys.argv[2][1:])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement