def play_video(path):
"""
Play a video by the provided path.
:param path: str
"""
# if the previous two if statements dont hit then the path is a
# video path so modify the string and play it with the youtube plugin
###############
# the path to let videos be played by the youtube plugin
youtubePath='plugin://plugin.video.youtube/?action=play_video&videoid='
# remove the full webaddress to make youtube plugin work correctly
path=path.replace('https://youtube.com/watch?v=','')
# also check for partial webaddresses we only need the video id
path=path.replace('watch?v=','')
# add youtube path to path to make videos play with the kodi youtube plugin
path=youtubePath+path
# Create a playable item with a path to play.
play_item = xbmcgui.ListItem(path=path)
# Pass the item to the Kodi player.
xbmcplugin.setResolvedUrl(_handle, True, listitem=play_item)
python类ListItem()的实例源码
def play_all(arrayOfObjects):
# create the playlist
playlist= xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
index=1
# for each item in the playlist
for item in arrayOfObjects:
path=item['video']
# the path to let videos be played by the youtube plugin
youtubePath='plugin://plugin.video.youtube/?action=play_video&videoid='
# remove the full webaddress to make youtube plugin work correctly
path=path.replace('https://youtube.com/watch?v=','')
# also check for partial webaddresses we only need the video id
path=path.replace('watch?v=','')
# add youtube path to path to make videos play with the kodi youtube plugin
path=youtubePath+path
# create listitem to insert in the playlist
list_item = xbmcgui.ListItem(label=item['name'])
#list_item.setInfo('video', {'title':title , 'genre':'menu' })
list_item.setInfo('video', item)
list_item.setArt(item)
list_item.setProperty('IsPlayable', 'true')
# add item to the playlist
playlist.add(path,list_item,index)
# increment the playlist index
index+=1
def get_user_colorthemes(self):
'''get all user stored color themes as listitems'''
listitems = []
for file in xbmcvfs.listdir(self.userthemes_path)[1]:
if file.endswith(".theme"):
file = file.decode("utf-8")
themefile = self.userthemes_path + file
label = file.replace(".theme", "")
icon = themefile.replace(".theme", ".jpg")
if not xbmcvfs.exists(icon):
icon = ""
desc = "user defined theme"
if label == self.get_activetheme():
desc = xbmc.getLocalizedString(461)
listitem = xbmcgui.ListItem(label, iconImage=icon)
listitem.setLabel2(desc)
listitem.setPath(themefile)
listitems.append(listitem)
return listitems
def list_streams(streams):
stream_list = []
# iterate over the contents of the dictionary songs to build the list
for stream in streams:
# create a list item using the stream's name for the label
li = xbmcgui.ListItem(label=stream['name'])
# set the thumbnail image
li.setArt({'thumb': stream['logo']})
# set the list item to playable
li.setProperty('IsPlayable', 'true')
# build the plugin url for Kodi
url = build_url({'mode': 'stream', 'url': stream['url'], 'title': stream['name']})
# add the current list item to a list
stream_list.append((url, li, False))
# add list to Kodi per Martijn
# http://forum.kodi.tv/showthread.php?tid=209948&pid=2094170#pid2094170
xbmcplugin.addDirectoryItems(addon_handle, stream_list, len(stream_list))
# set the content of the directory
xbmcplugin.setContent(addon_handle, 'songs')
xbmcplugin.endOfDirectory(addon_handle)
def list_podcast_radios(radios):
radio_list = []
# iterate over the contents of the list of radios
for radio in sorted(radios, key=operator.itemgetter('name')):
url = build_url({'mode': 'podcasts-radio', 'foldername': radio['name'], 'url': radio['url'], 'name': radio['name']})
li = xbmcgui.ListItem(radio['name'], iconImage='DefaultFolder.png')
radio_list.append((url, li, True))
# add list to Kodi per Martijn
# http://forum.kodi.tv/showthread.php?tid=209948&pid=2094170#pid2094170
xbmcplugin.addDirectoryItems(addon_handle, radio_list, len(radio_list))
# set the content of the directory
xbmcplugin.setContent(addon_handle, 'songs')
xbmcplugin.endOfDirectory(addon_handle)
def list_podcast_programs(programs):
program_list = []
# iterate over the contents of the list of programs
for program in programs:
url = build_url({'mode': 'podcasts-radio-program', 'foldername': urllib.quote(program['name'].encode('utf8')), 'url': program['url'], 'name': urllib.quote(program['name'].encode('utf8')), 'radio': program['radio']})
li = xbmcgui.ListItem(program['name'], iconImage='DefaultFolder.png')
program_list.append((url, li, True))
# add list to Kodi per Martijn
# http://forum.kodi.tv/showthread.php?tid=209948&pid=2094170#pid2094170
xbmcplugin.addDirectoryItems(addon_handle, program_list, len(program_list))
# set the content of the directory
xbmcplugin.setContent(addon_handle, 'songs')
xbmcplugin.endOfDirectory(addon_handle)
def add_artist_listitems(self, artists):
for item in artists:
if KODI_VERSION > 17:
li = xbmcgui.ListItem(item["name"], path=item['url'], offscreen=True)
else:
li = xbmcgui.ListItem(item["name"], path=item['url'])
infolabels = {
"title": item["name"],
"genre": item["genre"],
"artist": item["name"],
"rating": item["rating"]
}
li.setInfo(type="Music", infoLabels=infolabels)
li.setArt({"thumb": item['thumb']})
li.setProperty('do_not_analyze', 'true')
li.setProperty('IsPlayable', 'false')
li.setLabel2(item["followerslabel"])
li.addContextMenuItems(item["contextitems"], True)
xbmcplugin.addDirectoryItem(
handle=self.addon_handle,
url=item["url"],
listitem=li,
isFolder=True,
totalItems=len(artists))
def add_next_button(self, listtotal):
# adds a next button if needed
params = self.params
if listtotal > self.offset + self.limit:
params["offset"] = self.offset + self.limit
url = "plugin://plugin.audio.spotify/"
for key, value in params.iteritems():
if key == "action":
url += "?%s=%s" % (key, value[0])
elif key == "offset":
url += "&%s=%s" % (key, value)
else:
url += "&%s=%s" % (key, value[0])
li = xbmcgui.ListItem(
xbmc.getLocalizedString(33078),
path=url,
iconImage="DefaultMusicAlbums.png"
)
li.setProperty('do_not_analyze', 'true')
li.setProperty('IsPlayable', 'false')
xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=True)
def addOfflineMediaFile(self,offlinefile):
listitem = xbmcgui.ListItem(offlinefile.title, iconImage=offlinefile.thumbnail,
thumbnailImage=offlinefile.thumbnail)
if offlinefile.resolution == 'original':
infolabels = decode_dict({ 'title' : offlinefile.title})
else:
infolabels = decode_dict({ 'title' : offlinefile.title + ' - ' + offlinefile.resolution })
listitem.setInfo('Video', infolabels)
listitem.setProperty('IsPlayable', 'true')
xbmcplugin.addDirectoryItem(self.plugin_handle, offlinefile.playbackpath, listitem,
isFolder=False, totalItems=0)
return offlinefile.playbackpath
##
# Calculate the number of accounts defined in settings
# parameters: the account type (usually plugin name)
##
def program_to_kodi_item(node):
"""
Convert a show API object to a kodi list item
"""
id = int(node.get('id',0))
li = {
'label': node.get('name',''),
'url': common.plugin.get_url(action='list_medias',filter_medias='program_medias_recent',program_id=id),
#'thumb': image, # Item thumbnail
#'fanart': image,
'info': {
'video': { ##http://romanvm.github.io/Kodistubs/_autosummary/xbmcgui.html#xbmcgui.ListItem.setInfo
#'plot': node.get('description',''),#Long Description
#'plotoutline': node.get('description',''),#Short Description
}
}
}
return li
def getTweets(self):
self.getControl(32500).setLabel("#"+self.hash)
self.getControl(32503).setImage(os.path.join(addon_path,"resources","img","twitter_sm.png"))
tweetitems = []
tweets = tweet.get_hashtag_tweets(self.hash)
if tweets:
for _tweet in tweets:
td = ssutils.get_timedelta_string(datetime.datetime.utcnow() - _tweet["date"])
item = xbmcgui.ListItem(_tweet["text"].replace("\n",""))
item.setProperty("profilepic",_tweet["profilepic"])
item.setProperty("author","[B]" +"@" + _tweet["author"] + "[/B]")
item.setProperty("timedelta", td)
tweetitems.append(item)
self.getControl(32501).reset()
self.getControl(32501).addItems(tweetitems)
if tweetitems:
self.setFocusId(32501)
return
def onInit(self):
self.getControl(32540).setImage(os.path.join(addon_path,"resources","img","goal.png"))
xbmc.executebuiltin("SetProperty(loading-script-matchcenter-leagueselection,1,home)")
leagues = api.Search().Leagues(sport="Soccer")
leagues_to_be_shown = ssutils.get_league_tables_ids()
items = []
if leagues:
for league in leagues:
if str(league.idLeague) in str(leagues_to_be_shown):
item = xbmcgui.ListItem(league.strLeague)
item.setProperty("thumb",str(league.strBadge))
item.setProperty("identifier",str(league.idLeague))
items.append(item)
xbmc.executebuiltin("ClearProperty(loading-script-matchcenter-leagueselection,Home)")
self.getControl(32500).addItems(items)
if len(items) <= 9:
self.getControl(32541).setWidth(962)
self.getControl(32542).setWidth(962)
def show_sport_selection(self):
"""Creates the KODI list items for the static sport selection"""
self.utils.log('Sport selection')
sports = self.constants.get_sports_list()
for sport in sports:
url = self.utils.build_url({'for': sport})
list_item = xbmcgui.ListItem(label=sports.get(sport).get('name'))
list_item = self.item_helper.set_art(
list_item=list_item,
sport=sport)
xbmcplugin.addDirectoryItem(
handle=self.plugin_handle,
url=url,
listitem=list_item,
isFolder=True)
xbmcplugin.addSortMethod(
handle=self.plugin_handle,
sortMethod=xbmcplugin.SORT_METHOD_DATE)
xbmcplugin.endOfDirectory(self.plugin_handle)
def __add_static_folders(self, statics, sport):
"""
Adds static folder items to Kodi (if available)
:param statics: All static entries
:type statics: dict
:param sport: Chosen sport
:type sport: string
"""
if statics.get(sport):
static_lanes = statics.get(sport)
if static_lanes.get('categories'):
lanes = static_lanes.get('categories')
for lane in lanes:
url = self.utils.build_url({
'for': sport,
'static': True,
'lane': lane.get('id')})
list_item = xbmcgui.ListItem(label=lane.get('name'))
xbmcplugin.addDirectoryItem(
handle=self.plugin_handle,
url=url,
listitem=list_item,
isFolder=True)
def __add_video_item(self, video, list_item, url):
"""
Adds a playable video item to Kodi
:param video: Video details
:type video: dict
:param list_item: Kodi list item
:type list_item: xbmcgui.ListItem
:param url: Video url
:type url: string
"""
if video.get('islivestream', True) is True:
xbmcplugin.addDirectoryItem(
handle=self.plugin_handle,
url=url,
listitem=list_item,
isFolder=False)
def direct_play(url):
_log("direct_play ["+url+"]")
title = ""
try:
xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", path=url)
except:
xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", )
xlistitem.setInfo( "video", { "Title": title } )
playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
playlist.clear()
playlist.add( url, xlistitem )
player_type = xbmc.PLAYER_CORE_AUTO
xbmcPlayer = xbmc.Player( player_type )
xbmcPlayer.play(playlist)
def direct_play(url):
_log("direct_play ["+url+"]")
title = ""
try:
xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", path=url)
except:
xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", )
xlistitem.setInfo( "video", { "Title": title } )
playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
playlist.clear()
playlist.add( url, xlistitem )
player_type = xbmc.PLAYER_CORE_AUTO
xbmcPlayer = xbmc.Player( player_type )
xbmcPlayer.play(playlist)
def onInit( self ):
plugintools.log("ChannelWindow.onInit")
if self.first_time == True:
return
self.first_time = True
self.control_list = self.getControl(100)
for item in self.itemlist:
list_item = xbmcgui.ListItem( item.title , iconImage=item.thumbnail, thumbnailImage=item.thumbnail)
info_labels = { "Title" : item.title, "FileName" : item.title, "Plot" : item.plot }
list_item.setInfo( "video", info_labels )
if item.fanart!="":
list_item.setProperty('fanart_image',item.fanart)
self.control_list.addItem(list_item)
self.setFocusId(100)
def addMenuItem(caption, link, icon=None, thumbnail=None, folder=False):
"""
Add a menu item to the xbmc GUI
Parameters:
caption: the caption for the menu item
icon: the icon for the menu item, displayed if the thumbnail is not accessible
thumbail: the thumbnail for the menu item
link: the link for the menu item
folder: True if the menu item is a folder, false if it is a terminal menu item
Returns True if the item is successfully added, False otherwise
"""
listItem = xbmcgui.ListItem(unicode(caption), iconImage=icon, thumbnailImage=thumbnail)
listItem.setInfo(type="Video", infoLabels={ "Title": caption })
return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=link, listitem=listItem, isFolder=folder)
def addMenuItem(caption, link, icon=None, thumbnail=None, folder=False):
"""
Add a menu item to the xbmc GUI
Parameters:
caption: the caption for the menu item
icon: the icon for the menu item, displayed if the thumbnail is not accessible
thumbail: the thumbnail for the menu item
link: the link for the menu item
folder: True if the menu item is a folder, false if it is a terminal menu item
Returns True if the item is successfully added, False otherwise
"""
listItem = xbmcgui.ListItem(unicode(caption), iconImage=icon, thumbnailImage=thumbnail)
listItem.setInfo(type="Video", infoLabels={ "Title": caption })
return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=link, listitem=listItem, isFolder=folder)
def addMenuItem(caption, link, icon=None, thumbnail=None, folder=False):
"""
Add a menu item to the xbmc GUI
Parameters:
caption: the caption for the menu item
icon: the icon for the menu item, displayed if the thumbnail is not accessible
thumbail: the thumbnail for the menu item
link: the link for the menu item
folder: True if the menu item is a folder, false if it is a terminal menu item
Returns True if the item is successfully added, False otherwise
"""
listItem = xbmcgui.ListItem(unicode(caption), iconImage=icon, thumbnailImage=thumbnail)
listItem.setInfo(type="Video", infoLabels={ "Title": caption })
return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=str(link), listitem=listItem, isFolder=folder)
def play_video(path):
"""
Play a video by the provided path.
:param path: str
"""
# Create a playable item with a path to play.
play_item = xbmcgui.ListItem(path=path)
vid_url = play_item.getfilename()
stream_url = resolve_url(vid_url)
if stream_url:
play_item.setPath(stream_url)
# Pass the item to the Kodi player.
print "in play video"
print play_item
xbmcplugin.setResolvedUrl(addon_handle, True, listitem=play_item)
# addon kicks in
def play_video(path):
"""
Play a video by the provided path.
:param path: str
"""
# Create a playable item with a path to play.
play_item = xbmcgui.ListItem(path=path)
vid_url = play_item.getfilename()
stream_url = resolve_url(vid_url)
if stream_url:
play_item.setPath(stream_url)
# Pass the item to the Kodi player.
print "in play video"
print play_item
xbmcplugin.setResolvedUrl(addon_handle, True, listitem=play_item)
# 002 start
#link = "http://www.vidsplay.com/wp-content/uploads/2017/04/alligator.mp4"
def addDir(name,url,mode,iconimage,plot='',isFolder=True):
try:
PID = iconimage.split('productionId=')[1]
except:pass
u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)
ok=True
liz=xbmcgui.ListItem(name,iconImage="DefaultVideo.png", thumbnailImage=iconimage)
liz.setInfo( type="Video", infoLabels={ "Title": name, "Plot": plot,'Premiered' : '2012-01-01','Episode' : '7-1' } )
menu=[]
if mode == 2:
menu.append(('[COLOR yellow]Add To Favourites[/COLOR]','XBMC.RunPlugin(%s?mode=13&url=%s&name=%s&iconimage=%s)'% (sys.argv[0],url,name,PID)))
if mode == 204:
menu.append(('[COLOR yellow]Remove Favourite[/COLOR]','XBMC.RunPlugin(%s?mode=14&url=%s&name=%s&iconimage=%s)'% (sys.argv[0],url,name,iconimage)))
liz.addContextMenuItems(items=menu, replaceItems=False)
if mode==3:
xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_DATE)
if isFolder==False:
liz.setProperty("IsPlayable","true")
ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=isFolder)
return ok
def addDir(name,url,mode,iconimage,description):
u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)+"&description="+urllib.quote_plus(description)
ok=True
name=replaceHTMLCodes(name)
name=name.strip()
liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
liz.setInfo( type="Video", infoLabels={ "Title": name, "Plot": description} )
menu = []
if mode ==200 or mode ==201 or mode ==202 or mode ==203:
if not 'feeds' in url:
if not 'f4m' in url:
if 'm3u8' in url:
liz.setProperty('mimetype', 'application/x-mpegURL')
liz.setProperty('mimetype', 'video/MP2T')
liz.setProperty("IsPlayable","true")
ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
else:
menu.append(('Play All Videos','XBMC.RunPlugin(%s?name=%s&mode=2001&iconimage=None&url=%s)'% (sys.argv[0],name,url)))
liz.addContextMenuItems(items=menu, replaceItems=False)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
return ok
def show_listing(self, list_items, sort=None):
listing = []
for title_item in list_items:
list_item = xbmcgui.ListItem(label=title_item.title)
url = self._url + '?' + urlencode(title_item.url_dictionary)
list_item.setProperty('IsPlayable', str(title_item.is_playable))
if title_item.thumbnail is not None:
list_item.setArt({'thumb': title_item.thumbnail})
list_item.setInfo('video', title_item.video_dictionary)
listing.append((url, list_item, not title_item.is_playable))
xbmcplugin.addDirectoryItems(self._handle, listing, len(listing))
if sort is not None:
kodi_sorts = {sortmethod.ALPHABET: xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE}
kodi_sortmethod = kodi_sorts.get(sort)
xbmcplugin.addSortMethod(self._handle, kodi_sortmethod)
xbmcplugin.endOfDirectory(self._handle)
def _users(self):
page = int(self.root.params['page'])
users = media_entries('fave.getUsers', self.root.conn, _NO_OWNER, page = page)
if page < users['pages']:
params = {'do': _DO_FAVE_USERS, 'page': page + 1}
self.root.add_folder(self.root.gui._string(400602), params)
for u in users['items']:
list_item = xbmcgui.ListItem(u'%s %s' % (u.info['last_name'], u.info['first_name']))
#p_key = 'photo_%d' % (max(map(lambda x: int(x.split('_')[1]), filter(lambda x: x.startswith('photo_'), m.info.keys()))),)
#list_item.setArt({'thumb': m.info[p_key], 'icon': m.info[p_key]})
params = {'do': _DO_HOME, 'oid': u.id}
url = self.root.url(**params)
xbmcplugin.addDirectoryItem(_addon_id, url, list_item, isFolder = True)
if page < users['pages']:
params = {'do': _DO_FAVE_USERS, 'page': page + 1}
self.root.add_folder(self.root.gui._string(400602), params)
xbmcplugin.endOfDirectory(_addon_id)
def _groups(self):
page = int(self.root.params['page'])
links = media_entries('fave.getLinks', self.root.conn, _NO_OWNER, page = page)
if page < links['pages']:
params = {'do': _DO_FAVE_GROUPS, 'page': page + 1}
self.root.add_folder(self.root.gui._string(400602), params)
for l in links['items']:
l_id = l.info['id'].split('_')
if l_id[0] == '2':
list_item = xbmcgui.ListItem(l.info['title'])
p_key = 'photo_%d' % (max(map(lambda x: int(x.split('_')[1]), filter(lambda x: x.startswith('photo_'), l.info.keys()))),)
list_item.setArt({'thumb': l.info[p_key], 'icon': l.info[p_key]})
params = {'do': _DO_HOME, 'oid': -int(l_id[-1])}
url = self.root.url(**params)
xbmcplugin.addDirectoryItem(_addon_id, url, list_item, isFolder = True)
if page < links['pages']:
params = {'do': _DO_FAVE_GROUPS, 'page': page + 1}
self.root.add_folder(self.root.gui._string(400602), params)
xbmcplugin.endOfDirectory(_addon_id)
def _photo_albums(self):
page = int(self.root.params['page'])
oid = self.root.params['oid']
kwargs = {'page': page, 'need_covers': 1, 'need_system': 1}
albums = media_entries('photos.getAlbums', self.root.conn, oid, **kwargs)
if page < albums['pages']:
params = {'do': _DO_PHOTO_ALBUMS,'oid': oid,'page': page + 1}
self.root.add_folder(self.root.gui._string(400602), params)
for a in albums['items']:
list_item = xbmcgui.ListItem(a.info['title'])
list_item.setInfo('pictures', {'title': a.info['title']})
list_item.setArt({'thumb': a.info['thumb_src'], 'icon': a.info['thumb_src']})
params = {'do': _DO_PHOTO, 'oid': oid, 'album': a.id, 'page': 1}
url = self.root.url(**params)
xbmcplugin.addDirectoryItem(_addon_id, url, list_item, isFolder = True)
if page < albums['pages']:
params = {'do': _DO_PHOTO_ALBUMS,'oid': oid,'page': page + 1}
self.root.add_folder(self.root.gui._string(400602), params)
xbmcplugin.endOfDirectory(_addon_id)
switch_view()
def _main_video_search(self):
page = int(self.root.params['page'])
self.root.add_folder(self.root.gui._string(400516), {'do': _DO_VIDEO_SEARCH, 'q':'none', 'page': 1})
history = get_search_history(_FILE_VIDEO_SEARCH_HISTORY)
count = len(history)
pages = int(ceil(count / float(_SETTINGS_PAGE_ITEMS)))
if page < pages:
params = {'do': _DO_MAIN_VIDEO_SEARCH, 'page': page + 1}
self.root.add_folder(self.root.gui._string(400602), params)
h_start = _SETTINGS_PAGE_ITEMS * (page -1)
h_end = h_start + _SETTINGS_PAGE_ITEMS
history = history[h_start:h_end]
for h in history:
query_hex = binascii.hexlify(pickle.dumps(h, -1))
list_item = xbmcgui.ListItem(h)
params = {'do': _DO_VIDEO_SEARCH, 'q': query_hex, 'page': 1}
url = self.root.url(**params)
xbmcplugin.addDirectoryItem(_addon_id, url, list_item, isFolder = True)
if page < pages:
params = {'do': _DO_MAIN_VIDEO_SEARCH, 'page': page + 1}
self.root.add_folder(self.root.gui._string(400602), params)
xbmcplugin.endOfDirectory(_addon_id)