def listSeries(self, items, addToFavorites=True): if not items: xbmcplugin.endOfDirectory(HANDLE, succeeded=False) if not addToFavorites: xbmcgui.Dialog().ok(ADDON.getAddonInfo('name'), ADDON.getLocalizedString(30013), ADDON.getLocalizedString(30018), ADDON.getLocalizedString(30019)) else: xbmcgui.Dialog().ok(ADDON.getAddonInfo('name'), ADDON.getLocalizedString(30013)) else: directoryItems = list() for item in items: menuItems = list(self.menuItems) if self.favorites.count(item['SeriesTitle']) > 0: runScript = "XBMC.RunPlugin(plugin://plugin.video.drnu/?delfavorite=%s)" % item['SeriesTitle'].replace('&', '%26').replace(',', '%2C') menuItems.append((ADDON.getLocalizedString(30201), runScript)) else: runScript = "XBMC.RunPlugin(plugin://plugin.video.drnu/?addfavorite=%s)" % item['SeriesTitle'].replace('&', '%26').replace(',', '%2C') menuItems.append((ADDON.getLocalizedString(30200), runScript)) iconImage = item['PrimaryImageUri'] # HACK: the servers behind /mu-online/api/1.2 is often returning Content-Type="text/xml" instead of "image/jpeg", this problem is not pressent for /mu/bar (the "Classic API") assert(self.api.API_URL.endswith("/mu-online/api/1.2")) iconImage = iconImage.replace("/mu-online/api/1.2/bar/","/mu/bar/") listItem = xbmcgui.ListItem(item['SeriesTitle'], iconImage=iconImage) listItem.setProperty('Fanart_Image', iconImage) listItem.addContextMenuItems(menuItems, False) url = PATH + '?listVideos=' + item['SeriesSlug'] directoryItems.append((url, listItem, True)) xbmcplugin.addDirectoryItems(HANDLE, directoryItems) xbmcplugin.endOfDirectory(HANDLE)
def __init__(self): self._parse_argv() self.tokens = {} sortLetterList = list() # 0 if false, 1 if true hasParentItem = xbmc.getCondVisibility('System.GetBool(filelists.showparentdiritems)') ignoreArticles = xbmc.getCondVisibility('System.GetBool(filelists.ignorethewhensorting)') wid = xbmcgui.getCurrentWindowId() currentWindow = xbmcgui.Window(wid) # get sort tokens from advancedsettings.xml f = xbmcvfs.File(xbmc.translatePath('special://userdata/advancedsettings.xml')) advancedsettings = f.read() f.close() if advancedsettings: root = ET.fromstring(advancedsettings) sorttokens = root.find('sorttokens') # user specified tokens, proceed to create dictionary if sorttokens is not None: self.tokens = { token.text.encode('utf-8') : u'' for token in sorttokens.findall('token') } if self.TYPE == "scroll": xbmcplugin.setResolvedUrl(handle=self.handle, succeeded=False, listitem=xbmcgui.ListItem()) containerId = self._get_view_mode() targetList = currentWindow.getControl(containerId) targetList.selectItem(int(self.pos)) currentWindow.setFocus(targetList) elif self.path: xbmcplugin.setContent(self.handle, 'files') self._parse_files(sortLetterList, hasParentItem, ignoreArticles) xbmcplugin.addDirectoryItems(self.handle, sortLetterList) xbmcplugin.endOfDirectory(handle=self.handle) return
def build_playlist(): play_list = parse_channels() # add list to Kodi xbmcplugin.addDirectoryItems(addon_handle, play_list, len(play_list)) # set the content of the directory xbmcplugin.setContent(addon_handle, 'songs') xbmcplugin.endOfDirectory(addon_handle)
def listEpisodes(self, items, addSortMethods=True): directoryItems = list() for item in items: if 'PrimaryAsset' not in item or 'Uri' not in item['PrimaryAsset'] or not item['PrimaryAsset']['Uri']: continue infoLabels = { 'title': item['Title'] } if 'Description' in item: infoLabels['plot'] = item['Description'] if 'PrimaryBroadcastStartTime' in item and item['PrimaryBroadcastStartTime'] is not None: broadcastTime = self.parseDate(item['PrimaryBroadcastStartTime']) if broadcastTime: infoLabels['date'] = broadcastTime.strftime('%d.%m.%Y') infoLabels['aired'] = broadcastTime.strftime('%Y-%m-%d') infoLabels['year'] = int(broadcastTime.strftime('%Y')) iconImage = item['PrimaryImageUri'] listItem = xbmcgui.ListItem(item['Title'], iconImage=iconImage) listItem.setInfo('video', infoLabels) listItem.setProperty('Fanart_Image', iconImage) url = PATH + '?playVideo=' + item['Slug'] listItem.setProperty('IsPlayable', 'true') listItem.addContextMenuItems(self.menuItems, False) directoryItems.append((url, listItem)) xbmcplugin.addDirectoryItems(HANDLE, directoryItems) if addSortMethods: xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_DATE) xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_TITLE) xbmcplugin.endOfDirectory(HANDLE)
def list_categories(): """ Create the list of categories in the Kodi interface. Returns: None """ categories = get_categories() listing = [] for category in categories: # Create a list item with a text label and a thumbnail image. list_item = xbmcgui.ListItem(label=FEEDS[category]['name'], thumbnailImage=FEEDS[category]['icon']) # set fanart my_addon = xbmcaddon.Addon('plugin.audio.dancarlin') #list_item.setProperty('fanart_image', my_addon.getAddonInfo('fanart')) list_item.setArt({'fanart': my_addon.getAddonInfo('fanart')}) # Set additional info for the list item. list_item.setInfo('video', {'title': category, 'genre': 'news'}) list_item.setInfo('audio', {'title': category, 'genre': 'news'}) # Create a URL for the plugin recursive callback. # e.g., plugin://plugin.audio.dancarlin/?action=listing&category=common_sense url = '{0}?action=listing&category={1}'.format(_url, category) # is_folder = True means that this item opens a sub-list of lower level items. is_folder = True # Add our item to the listing as a 3-element tuple. listing.append((url, list_item, is_folder)) # Add our listing to Kodi. xbmcplugin.addDirectoryItems(_handle, listing, len(listing)) # Add a sort method for the virtual folder items (alphabetically, ignore articles) xbmcplugin.addSortMethod(_handle, xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE) # Finish creating a virtual folder. xbmcplugin.endOfDirectory(_handle)
def getSources(fanart): ilist = [] url = 'https://public-api.viewster.com/genres' headers = defaultHeaders headers['Auth-token'] = cache.cacheFunction(getToken) html = getRequest(url, None, headers) cats = json.loads(html) for list in cats: name = list['Name'].decode(UTF8) url = str(list['Id']) img = 'http://divaag.vo.llnwd.net/o42/http_rtmpe/shared/Viewster_Artwork/internal_artwork/g%s_1280x720.jpg' % url mode = 'GC' u = '%s?url=%s&name=%s&mode=%s' % (sys.argv[0],qp(url), qp(name), mode) liz=xbmcgui.ListItem(name, '',None, img) liz.setProperty('fanart_image', addonfanart) ilist.append((u, liz, True)) searches = [("/search/Movies#%s",__language__(30001)),("/search/TvShow#%s",__language__(30002))] for url,name in searches: url = url % name lname = "[COLOR red]%s[/COLOR]" % name u = '%s?url=%s&name=%s&mode=DS' % (sys.argv[0],qp(url), qp(name)) liz=xbmcgui.ListItem(lname, '',icon, None) ilist.append((u, liz, True)) xbmcplugin.addDirectoryItems(int(sys.argv[1]), ilist, len(ilist)) if addon.getSetting('enable_views') == 'true': xbmc.executebuiltin("Container.SetViewMode(%s)" % addon.getSetting('default_view')) xbmcplugin.endOfDirectory(int(sys.argv[1]))
def getTabs(gturl, gtname): ilist = [] url = gturl.replace(' ','%20') html = getRequest(url) html = re.compile('<section class="category-content full">(.+?)</section', re.DOTALL).search(html).group(1) if '<li class="active">' in html: getShows(gturl, gtname) return cats = re.compile('<a href="(.+?)" aria-label="(.+?)".+?</a', re.DOTALL).findall(html) for url,name in cats: try: name = cleanname(name) plot = name mode = 'GL' catname = gtname if gtname != name: catname = catname+' - '+name u = '%s?url=%s&name=%s&mode=%s' % (sys.argv[0],qp(url), qp(catname), mode) liz=xbmcgui.ListItem(name, '','DefaultFolder.png', icon) liz.setInfo( 'Video', { "Title": name, "Plot": plot }) liz.setProperty('fanart_image', addonfanart) liz.setProperty('IsPlayable', 'true') ilist.append((u, liz, False)) except: pass xbmcplugin.addDirectoryItems(int(sys.argv[1]), ilist, len(ilist))
def list_programs(self, type): xbmcplugin.setContent(HANDLE, 'movies') programs = self.api.get_program_list(type) if not programs: self.display_error(30000) return items = [] for program in programs: fanart = '' if 'program_image' in program: fanart = program['program_image'] infoLabels = { 'title': program['name'], 'plot' : program['description'], 'genre' : program['category']['name'] } item = xbmcgui.ListItem(program['name'], iconImage=fanart) item.setProperty('Fanart_Image', fanart) item.setInfo('video', infoLabels) if type == 'all': url = self._build_url({'episodes_nid': program['nid'].encode('utf-8')}) item.setProperty('IsPlayable', 'false') items.append((url, item, True)) elif type == 'most_viewed' or type == 'live_shows': url = self._build_url({'play_video': program['id']}) item.setProperty('IsPlayable', 'true') items.append((url, item, False)) xbmcplugin.addDirectoryItems(HANDLE, items) xbmcplugin.endOfDirectory(HANDLE)
def LIST(self, url): if Debug: self.LOG('LIST()') json = simplejson.loads(urllib.urlopen(url).read()) for entry in json['videos']: id = entry['id'] title = entry['title'] description = entry['description'] _duration = entry['duration'] if _duration >= 3600 * 1000: duration = time.strftime('%H:%M:%S', time.gmtime(_duration / 1000)) else: duration = time.strftime('%M:%S', time.gmtime(_duration / 1000)) video = entry['cdn_asset_url'] channel = entry['channel_name'] thumbnail_version = entry['thumbnail_version'] thumbnail = 'http://img1.newslook.com/images/dyn/videos/%s/%s/pad/324/231/%s.jpg' % (id, thumbnail_version, id) listitem = xbmcgui.ListItem(title, iconImage='DefaultVideo.png', thumbnailImage=thumbnail) listitem.setProperty('IsPlayable', 'true') listitem.setProperty('mimetype', 'video/mp4') listitem.setInfo(type='video', infoLabels={'title' : title, 'plot' : description, 'duration': duration, }) xbmcplugin.addDirectoryItems(int(sys.argv[1]), [(video, listitem, False)]) # Content Type xbmcplugin.setContent(int(sys.argv[1]), 'movies') # Sort methods xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_NONE, label2Mask='%D') # End of directory... xbmcplugin.endOfDirectory(int(sys.argv[1]), True)
def listShows(self, channel): items = list() shows = self.api.get_shows(channel) if not shows: xbmcplugin.endOfDirectory(HANDLE, succeeded=False) self.displayError(ADDON.getLocalizedString(30205)) return for show in shows: fanart = show['image'] infoLabels = { 'title': show['title'] #'plot': show['description'] } item = xbmcgui.ListItem(show['title'], iconImage=fanart) item.setInfo('video', infoLabels) item.setProperty('Fanart_Image', fanart) url = self._build_url({'seasons_url': show['_links']['seasons']['href']}) items.append((url, item, True)) xbmcplugin.addDirectoryItems(HANDLE, items) xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_TITLE) xbmcplugin.endOfDirectory(HANDLE)
def list_episodes(self, episodes): if not episodes: self.display_error(30000) return items = [] for episode in episodes: fanart = episode['image'] info_labels = { 'title': episode['title'], 'plot' : episode['description'], 'aired' : episode['broadcast_date_time'], 'genre' : episode['program']['category']['name'] } item = xbmcgui.ListItem(episode['title'], iconImage=fanart) item.setInfo('video', info_labels) item.setProperty('Fanart_Image', fanart) url = self._build_url({'play_video': episode['id']}) item.setProperty('IsPlayable', 'true') items.append((url, item)) xbmcplugin.addDirectoryItems(HANDLE, items) xbmcplugin.endOfDirectory(HANDLE)
def showMainMenu(self): items = list() # A-Z Program Series item = xbmcgui.ListItem(ADDON.getLocalizedString(30000), iconImage=os.path.join(ADDON.getAddonInfo('path'), 'resources', 'icons', 'all.png')) item.setProperty('Fanart_Image', FANART_IMAGE) items.append((PATH + '?show=listAZ', item, True)) # Most viewed item = xbmcgui.ListItem(ADDON.getLocalizedString(30011), iconImage=os.path.join(ADDON.getAddonInfo('path'), 'resources', 'icons', 'eye.png')) item.setProperty('Fanart_Image', FANART_IMAGE) items.append((PATH + '?show=mostViewed', item, True)) # # Search videos item = xbmcgui.ListItem(ADDON.getLocalizedString(30003), iconImage=os.path.join(ADDON.getAddonInfo('path'), 'resources', 'icons', 'search.png')) item.setProperty('Fanart_Image', FANART_IMAGE) items.append((PATH + '?show=search', item, True)) # Recently watched Program Series item = xbmcgui.ListItem(ADDON.getLocalizedString(30007), iconImage=os.path.join(ADDON.getAddonInfo('path'), 'resources', 'icons', 'eye-star.png')) item.setProperty('Fanart_Image', FANART_IMAGE) items.append((PATH + '?show=recentlyWatched', item, True)) # Favorite Program Series item = xbmcgui.ListItem(ADDON.getLocalizedString(30008), iconImage=os.path.join(ADDON.getAddonInfo('path'), 'resources', 'icons', 'plusone.png')) item.setProperty('Fanart_Image', FANART_IMAGE) items.append((PATH + '?show=favorites', item, True)) xbmcplugin.addDirectoryItems(HANDLE, items) xbmcplugin.endOfDirectory(HANDLE)
def listVideos(tagId): listing = map(toListItem, loadVideoList(tagId)) xbmcplugin.addDirectoryItems(_HANDLE, listing, len(listing)) xbmcplugin.addSortMethod(_HANDLE, xbmcplugin.SORT_METHOD_DATEADDED) xbmcplugin.addSortMethod(_HANDLE, xbmcplugin.SORT_METHOD_LABEL) xbmcplugin.endOfDirectory(_HANDLE)
def getPBSKidsVids(kvurl, kvname): ilist = [] pg = getRequest(uqp(kvurl).replace(" ", "+").replace("&", "%26")) pg = pg.strip("()") a = json.loads(pg)["items"] for b in a: name = b["title"] plot = b["description"] img = b["images"]["kids-mezzannine-16x9"]["url"] try: captions = b["captions"]["srt"]["url"] except: captions = "" try: url = b["videos"]["flash"]["mp4-2500k"]["url"] except: try: url = b["videos"]["flash"]["mp4-1200k"]["url"] except: url = b["videos"]["flash"]["url"] mode = "PKP" u = "%s?url=%s&captions=%s&mode=%s" % (sys.argv[0], qp(url), qp(captions), mode) liz = xbmcgui.ListItem(name, plot, "DefaultFolder.png", img) liz.setInfo("Video", {"Title": name, "Studio": kvname, "Plot": plot}) liz.setProperty("IsPlayable", "true") ilist.append((u, liz, False)) xbmcplugin.addDirectoryItems(int(sys.argv[1]), ilist, len(ilist))
def listVideos(self, programCards): items = list() if 'Data' in programCards: programCards = programCards['Data'] for programCard in programCards: if 'ProgramCard' in programCard: programCard = programCard['ProgramCard'] if not 'PrimaryAssetUri' in programCard: continue infoLabels = self.createInfoLabels(programCard) imageAsset = self.api.getAsset('Image', programCard) if imageAsset: iconImage = imageAsset['Uri'] else: iconImage = '' item = xbmcgui.ListItem(infoLabels['title'], iconImage=iconImage) item.setInfo('video', infoLabels) item.setProperty('Fanart_Image', iconImage) url = PATH + '?videoasset=' + programCard['PrimaryAssetUri'] + '&urn=' + programCard['Urn'] item.setProperty('IsPlayable', 'true') items.append((url, item)) xbmcplugin.addDirectoryItems(HANDLE, items) xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_DATE) xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_TITLE) xbmcplugin.endOfDirectory(HANDLE)
def getFeatured(gzurl): setContent("episodes") ilist = [] pg = getRequest("http://video.pbs.org/programs/") a = re.compile('\("#programsCarousel"\)\.programCarousel\(.+?\:(.+?)\);', re.DOTALL).search(pg).group(1) a = '{"data":' + a b = json.loads(a) b = b["data"] a = re.compile('<ul id="carouselProgramList"(.+?)</ul>', re.DOTALL).search(pg).group(1) c = re.compile('<li.+?href="(.+?)".+?src="(.+?)".+?alt="(.+?)".+?</li>', re.DOTALL).findall(a) i = 0 for url, img, name in c: name = h.unescape(name).encode(UTF8) plot = b[i]["description"] plot = h.unescape(plot).encode(UTF8) fanart = b[i]["background"] if fanart == None: fanart = addonfanart i += 1 mode = "GV" u = "%s?url=%s&name=%s&mode=%s&imageicon=%s&fanart=%s&desc=%s" % ( sys.argv[0], qp(url), qp(name), mode, qp(img), qp(fanart), qp(plot), ) liz = xbmcgui.ListItem(name, "", None, img) liz.setInfo("Video", {"TVShowTitle": name, "Title": name, "Plot": plot, "Season": -1}) liz.setProperty("Fanart_Image", fanart) ilist.append((u, liz, True)) xbmcplugin.addDirectoryItems(int(sys.argv[1]), ilist, len(ilist)) endView("category_view")
def getAtoZ(gzurl): setContent("files") ilist = [] azheaders = defaultHeaders azheaders["X-Requested-With"] = "XMLHttpRequest" pg = getRequest("http://video.pbs.org/programs/list", None, azheaders) a = json.loads(pg) for y in gzurl: try: b = a[y] for x in b: fullname = h.unescape("%s [%s]" % (x["title"], x["video_count"])).encode(UTF8) name = h.unescape(x["title"]).encode(UTF8) plot = h.unescape(x["producer"]).encode(UTF8) url = ("program/%s" % (x["slug"])).encode(UTF8) mode = "GV" u = "%s?url=%s&name=%s&mode=%s" % (sys.argv[0], qp(url), qp(name), mode) liz = xbmcgui.ListItem(fullname, "", icon, None) # liz.setInfo( 'Video', { "Title": name, "Plot": plot }) liz.setProperty("Fanart_Image", addonfanart) ilist.append((u, liz, True)) except: pass xbmcplugin.addDirectoryItems(int(sys.argv[1]), ilist, len(ilist)) endView("default_view")
def ShowProviders(): listItems = [] contextMenuItems = [] contextMenuItems.append(('Clear HTTP Cache', "XBMC.RunPlugin(%s?clearcache=1)" % sys.argv[0] )) contextMenuItems.append(('Test Forwarded IP', "XBMC.RunPlugin(%s?testforwardedip=1)" % sys.argv[0] )) providers = providerfactory.getProviderList() for provider in providers: if not provider.ShowMe(): continue provider.SetResourceFolder(RESOURCE_PATH) providerId = provider.GetProviderId() providerName = provider.GetProviderName() log(u"Adding " + providerName + u" provider", xbmc.LOGDEBUG) newListItem = xbmcgui.ListItem( providerName ) url = baseURL + u'?provider=' + providerId log(u"url: " + url, xbmc.LOGDEBUG) thumbnailPath = provider.GetThumbnailPath(providerId) log(providerName + u" thumbnail: " + thumbnailPath, xbmc.LOGDEBUG) newListItem.setThumbnailImage(thumbnailPath) newListItem.addContextMenuItems( contextMenuItems ) listItems.append( (url,newListItem,True) ) xbmcplugin.addDirectoryItems( handle=pluginHandle, items=listItems ) xbmcplugin.endOfDirectory( handle=pluginHandle, succeeded=True )
def _create_actor_list(self, category, page): "Erzeuge die Darstellerliste." items = [] actors = Actors() for actor in actors.names_and_images(category, page): name, image = actor url = sys.argv[0] + "?" + urllib.urlencode({'actor' : name}) image = "%s/%s.jpg" % (Config.THUMBNAILS_URL, name) item = xbmcgui.ListItem(name, iconImage=image) item.addContextMenuItems( self._create_context_menu_add(name, url, image) ) items.append((url, item, True,)) url = sys.argv[0] + "?" + urllib.urlencode({ 'category' : category, 'page' : int(page) + 1 }) if not actors.reached_last_page(): items.append((url, xbmcgui.ListItem( self._addon.getLocalizedString(30160), iconImage='DefaultFolder.png') , True ) ) xbmcplugin.addDirectoryItems(self._plugin_id, items) xbmcplugin.endOfDirectory(self._plugin_id, cacheToDisc=True) xbmc.executebuiltin("Container.SetViewMode(500)")
def getSources(): ilist = [] url = 'http://www.hallmarkchanneleverywhere.com/Movies?NodeID=28' name = 'Movies' u = '%s?url=%s&name=%s&mode=%s' % (sys.argv[0],qp(url), qp(name), 'GM') liz=xbmcgui.ListItem(name, '',icon, None) liz.setProperty('fanart_image', addonfanart) ilist.append((u, liz, True)) html = getRequest('http://www.hallmarkchanneleverywhere.com/Series?NodeID=29') c = re.compile('<div class="imageviewitem">.+?src="(.+?)".+?class="commontitle" href="(.+?)">(.+?)<',re.DOTALL).findall(html) for img, url, name in c: img = HALLMARKBASE % img name = h.unescape(name.decode(UTF8)) url = HALLMARKBASE % url.replace('&','&') html = getRequest(url) plot = re.compile('<div id="imageDetail">.+?</div>(.+?)<', re.DOTALL).search(html).group(1) plot = h.unescape(plot.decode(UTF8)).strip() infoList ={} infoList['Title'] = name infoList['Plot'] = plot u = '%s?url=%s&name=%s&mode=GE' % (sys.argv[0], qp(url), qp(name)) liz=xbmcgui.ListItem(name, '',None, img) liz.setInfo( 'Video', infoList) liz.setProperty('fanart_image', addonfanart) ilist.append((u, liz, True)) xbmcplugin.addDirectoryItems(int(sys.argv[1]), ilist, len(ilist)) if addon.getSetting('enable_views') == 'true': xbmc.executebuiltin("Container.SetViewMode(%s)" % addon.getSetting('default_view')) xbmcplugin.endOfDirectory(int(sys.argv[1]))
def getGenre(url): ilist=[] url = uqp(url) (url, id) = url.split('#',1) html = getRequest('http://www.snagfilms.com%s' % url) html = re.compile('Snag.page.data = (.+?)];').search(html).group(1) html = html + ']' a = json.loads(html) for b in a[1:]: try: if b["id"] == id: c = b['data']['items'] for item in c: name = cleanname(item['title']).encode(UTF8) plot = cleanname(item['description']).encode(UTF8) u = "%s?url=%s&mode=GV" % (sys.argv[0], qp(item['id'])) img = item['images']['poster'] liz=xbmcgui.ListItem(name, '','DefaultFolder.png', img) liz.setInfo( 'Video', { "Title": name, "Plot": plot }) liz.setProperty('fanart_image', addonfanart) liz.setProperty('IsPlayable', 'true') liz.setProperty('mimetype', 'video/x-msvideo') ilist.append((u, liz, False)) except: pass xbmcplugin.addDirectoryItems(int(sys.argv[1]), ilist, len(ilist))
def _create_listing(self, context): """ Create a virtual folder listing @param context: context dictionary @type context: dict @return: """ self.log('Creating listing from {0}'.format(str(context)), xbmc.LOGDEBUG) if context.get('content'): xbmcplugin.setContent(self._handle, context['content']) # This must be at the beginning listing = [] for item in context['listing']: if item.get('list_item') is not None: list_item = item['list_item'] is_folder = item.get('is_folder', True) else: list_item = self.create_list_item(item) if item.get('is_playable'): list_item.setProperty('IsPlayable', 'true') is_folder = False else: is_folder = item.get('is_folder', True) listing.append((item['url'], list_item, is_folder)) xbmcplugin.addDirectoryItems(self._handle, listing, len(listing)) if context['sort_methods'] is not None: [xbmcplugin.addSortMethod(self._handle, method) for method in context['sort_methods']] xbmcplugin.endOfDirectory(self._handle, context['succeeded'], context['update_listing'], context['cache_to_disk']) if context['view_mode'] is not None: xbmc.executebuiltin('Container.SetViewMode({0})'.format(context['view_mode']))
def ListShows(self, html): self.log(u"", xbmc.LOGDEBUG) listItems = [] try: soup = BeautifulSoup(html, selfClosingTags=[u'img']) episodes = soup.findAll(u'a', u"thumbnail-programme-link") for episode in episodes: self.AddEpisodeToList(listItems, episode) xbmcplugin.addDirectoryItems( handle=self.pluginHandle, items=listItems ) xbmcplugin.endOfDirectory( handle=self.pluginHandle, succeeded=True ) return True except (Exception) as exception: if not isinstance(exception, LoggingException): exception = LoggingException.fromException(exception) if html is not None: msg = "html:\n\n%s\n\n" % html exception.addLogMessage(msg) # Error getting list of shows exception.addLogMessage(self.language(30049)) # Error getting list of shows exception.process(severity = self.logLevel(xbmc.LOGERROR)) return False
def GetMiroFeed(self, url): if Debug: self.LOG('GetMiroFeed()') feedHtml = fetcher.fetch(url, CACHE_TIME) encoding = feedHtml.split('encoding="')[1].split('"')[0] feedHtml = feedHtml.decode(encoding, 'ignore').encode('utf-8') feed = feedparser.parse(feedHtml) for item in feed['items']: infoLabels = {} if item.link.startswith('http://www.miroguide.com/feeds/'): id = item.link.replace('http://www.miroguide.com/feeds/', '') else: id = re.findall('/(.+?).jpeg', item.thumbnail)[0] title = infoLabels['title'] = item.title.replace(''', "'").replace('&', '&').replace('"', '"') if isinstance(title, str): # BAD: Not true for Unicode strings! try: title = infoLabels['title'] = title.encode('utf-8', 'replace') #.encode('utf-8') except: continue #skip this, it likely will bork # I put it here because above isinstance code not working well with some languages. title = infoLabels['title'] = title.encode('utf-8', 'replace') #.encode('utf-8') try: infoLabels['date'] = item.updated except: infoLabels['date'] = '' subtitle = infoLabels['date'] soup = self.StripTags(item.description)#, convertEntities=BSS.HTML_ENTITIES try: infoLabels['plot'] = soup.contents[0] except: infoLabels['plot'] = item.description.encode('utf-8', 'ignore') thumb = item.thumbnail if thumb == '': thumb = __icon__ feedUrl = item["summary_detail"]["value"].replace('amp;', '') feedUrl = feedUrl[feedUrl.find('url1=') + 5:] feedUrl = feedUrl[:feedUrl.find('&trackback1')].replace('%3A', ':') feddUrl = feedUrl.replace(' ', '%20') listitem = xbmcgui.ListItem(title, iconImage='DefaultVideo.png', thumbnailImage=thumb) if self._issubscripted(id): infoLabels['overlay'] = xbmcgui.ICON_OVERLAY_WATCHED contextmenu = [(__language__(30102), 'XBMC.RunPlugin(%s?action=unsubscribe&id=%s)' % \ (sys.argv[0], id))] else: infoLabels['overlay'] = xbmcgui.ICON_OVERLAY_NONE contextmenu = [(__language__(30101), 'XBMC.RunPlugin(%s?action=subscribe&id=%s&name=%s&feedurl=%s&thumbnail_url=%s&description=%s)' % \ (sys.argv[0], id, urllib.quote_plus(title), urllib.quote_plus(feedUrl), thumb, ''))] listitem.setInfo(type='video', infoLabels=infoLabels) listitem.addContextMenuItems(contextmenu, replaceItems=False) parameters = '%s?action=getfeed&url=%s' % (sys.argv[0], urllib.quote_plus(feedUrl)) xbmcplugin.addDirectoryItems(int(sys.argv[1]), [(parameters, listitem, True)]) # Sort methods and content type... xbmcplugin.setContent(int(sys.argv[1]), 'movie') xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_UNSORTED) xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_VIDEO_TITLE) if infoLabels['date']: xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_DATE) # End of directory... xbmcplugin.endOfDirectory(int(sys.argv[1]), True)
def START(self): if Debug: self.LOG('START()') category = [] # If keys exist in miro.db show My Subscription directory. if db.keys() != list(): if Debug: self.LOG('My Subscriptions directory activated.') category += [{'title':__language__(30201), 'url':'', 'action':'mysubscriptions'}, ] db.close() category += [{'title':__language__(30202), 'url':'https://www.miroguide.com/api/list_categories?datatype=json', 'action':'categories', 'filter':'category'}, {'title':__language__(30203), 'url':'https://www.miroguide.com/api/list_languages?datatype=json', 'action':'categories', 'filter':'language'}, {'title':__language__(30204), 'url':'http://feeds.feedburner.com/miroguide/new', 'action':'getmirofeed'}, {'title':__language__(30205), 'url':'http://feeds.feedburner.com/miroguide/featured', 'action':'getmirofeed'}, {'title':__language__(30206), 'url':'http://feeds.feedburner.com/miroguide/popular', 'action':'getmirofeed'}, {'title':__language__(30207), 'url':'http://feeds.feedburner.com/miroguide/toprated', 'action':'getmirofeed'}, {'title':__language__(30208), 'url':'https://www.miroguide.com/rss/tags/HD', 'action':'getmirofeed'}, #{'title':__language__(30209), 'url':'https://www.miroguide.com/rss/search/', 'action':'getmirofeed'}, ] for i in category: try: filter = i['filter'] except: filter = '' listitem = xbmcgui.ListItem(i['title'], iconImage='DefaultFolder.png', thumbnailImage=__icon__) parameters = '%s?action=%s&url=%s&filter=%s' % \ (sys.argv[0], i['action'], urllib.quote_plus(i['url']), filter) xbmcplugin.addDirectoryItems(int(sys.argv[1]), [(parameters, listitem, True)]) # Sort methods and content type... xbmcplugin.addSortMethod(handle=int(sys.argv[1]), sortMethod=xbmcplugin.SORT_METHOD_NONE) # End of directory... xbmcplugin.endOfDirectory(int(sys.argv[1]), True)
def list_categories(): f = urllib2.urlopen('http://api.m.panda.tv/ajax_get_all_subcate?__version=1.0.5.1098&__plat=iOS') obj = json.loads(f.read()) listing=[] list_item = xbmcgui.ListItem(label='全部直播') # list_item.setProperty('fanart_image', game['img']) url='{0}?action=all'.format(_url) listing.append((url, list_item, True)) for game in obj['data']: list_item = xbmcgui.ListItem(label=game['cname'], thumbnailImage=game['img']) list_item.setProperty('fanart_image', game['img']) url='{0}?action=room_list&game_id={1}'.format(_url, game['ename']) is_folder=True listing.append((url, list_item, is_folder)) xbmcplugin.addDirectoryItems(_handle,listing,len(listing)) #xbmcplugin.addSortMethod(_handle, xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE) # Finish creating a virtual folder. xbmcplugin.endOfDirectory(_handle)
def GetSubscriptions(self): if Debug: self.LOG('GetSubscriptions()') for k, v in db.iteritems(): id = k name = v['name'] feedUrl = v['url'] if not feedUrl: continue try: thumb = v['thumbnail_url'] except: pass summary = v['description'] listitem = xbmcgui.ListItem(name, iconImage='DefaultVideo.png', thumbnailImage=thumb) listitem.setInfo(type='video', infoLabels={'title' : name, 'plot' : summary, }) contextmenu = [(__language__(30102), 'XBMC.RunPlugin(%s?action=unsubscribe&id=%s)' % \ (sys.argv[0], id))] listitem.addContextMenuItems(contextmenu, replaceItems=False) parameters = '%s?action=getfeed&url=%s' % (sys.argv[0], urllib.quote_plus(feedUrl)) xbmcplugin.addDirectoryItems(int(sys.argv[1]), [(parameters, listitem, True)]) db.close() # Sort methods and content type... xbmcplugin.setContent(int(sys.argv[1]), 'movies') xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_UNSORTED) xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_VIDEO_TITLE) # End of directory... xbmcplugin.endOfDirectory(int(sys.argv[1]), True)
def ListAvailable(self, html): self.log(u"", xbmc.LOGDEBUG) listItems = [] try: soup = BeautifulSoup(html, selfClosingTags=[u'img']) count = int(soup.find(u'meta', { u'name' : u"episodes_available"} )[u'content']) availableEpisodes = soup.findAll(u'a', u"thumbnail-programme-link") for index in range ( 0, count ): self.AddEpisodeToList(listItems, availableEpisodes[index]) xbmcplugin.addDirectoryItems( handle=self.pluginHandle, items=listItems ) xbmcplugin.endOfDirectory( handle=self.pluginHandle, succeeded=True ) return True except (Exception) as exception: if not isinstance(exception, LoggingException): exception = LoggingException.fromException(exception) if html is not None: msg = "html:\n\n%s\n\n" % html exception.addLogMessage(msg) # Error getting count of available episodes exception.addLogMessage(self.language(30045)) exception.process(self.language(30046), self.language(30045), self.logLevel(xbmc.LOGERROR)) return False
def list_categories(offset): #f=urllib2.urlopen('http://www.douyutv.com/directory') #rr=BeautifulSoup(f.read()) rr=BeautifulSoup(requests.get('http://www.douyutv.com/directory',headers=headers).text) catel=rr.findAll('a',{'class':'thumb'},limit=offset+PAGE_LIMIT+1) rrr=[(x['href'], x.p.text,x.img['data-original']) for x in catel] offset=int(offset) if offset+PAGE_LIMIT<len(rrr): rrr=rrr[offset:offset+PAGE_LIMIT] nextpageflag=True else: rrr=rrr[offset:] nextpageflag=False listing=[] for classname,textinfo,img in rrr: list_item=xbmcgui.ListItem(label=textinfo,thumbnailImage=img) #list_item.setProperty('fanart_image',img) url=u'{0}?action=listing&category={1}&offset=0'.format(_url,classname) is_folder=True listing.append((url,list_item,is_folder)) if nextpageflag==True: list_item=xbmcgui.ListItem(label=NEXT_PAGE) url=u'{0}?offset={1}'.format(_url,str(offset+PAGE_LIMIT)) is_folder=True listing.append((url,list_item,is_folder)) xbmcplugin.addDirectoryItems(_handle,listing,len(listing)) #xbmcplugin.addSortMethod(_handle, xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE) # Finish creating a virtual folder. xbmcplugin.endOfDirectory(_handle)
def show_series_list(afv, rfv, tp, s): # global handle, plugin, root_url, lang # import xml.etree.cElementTree as cET if s is None: common.show_message(lang(30003), lang(30004)) return False xbmc.log("Start elementtree", 4) root = ET.fromstring(s) xbmc.log("end elementtree", 4) xbmc.log("Start elementtree", 4) xbmc.log("end elementtree", 4) sl = root.findall('fp/serieslist/item') channel_items = [] if sl: for serie_obj in sl: serie_channel = get_serial_channel(tp, serie_obj) url = sys.argv[0] + '?f=show_episodes&id=' + serie_channel['id'] + '&tp=' + tp item = get_list_item_for_serie_channel(serie_channel, tp, afv, rfv) channel_items.append((url, item, True,)) xbmcplugin.addDirectoryItems(handle, channel_items, len(channel_items)) xbmcplugin.addSortMethod(handle, xbmcplugin.SORT_METHOD_TITLE) xbmcplugin.endOfDirectory(handle) else: common.show_message(lang(30003), lang(30005)) xbmc.log("Prepare end", 4) return True
def run(url_suffix=""): socket.setdefaulttimeout(int(ADDON.getSetting("buffer_timeout"))) urllib2.install_opener(urllib2.build_opener(NoRedirectHandler())) # Pause currently playing Elementum file to avoid doubling requests if xbmc.Player().isPlaying() and ADDON_ID in xbmc.Player().getPlayingFile( ): xbmc.Player().pause() url = sys.argv[0].replace("plugin://%s" % ADDON_ID, ELEMENTUMD_HOST + url_suffix) + sys.argv[2] log.debug("Requesting %s from %s" % (url, repr(sys.argv))) try: data = _json(url) except urllib2.URLError as e: if 'Connection refused' in e.reason: notify(getLocalizedString(30116), time=7000) else: import traceback map(log.error, traceback.format_exc().split("\n")) notify(e.reason, time=7000) return except Exception as e: import traceback map(log.error, traceback.format_exc().split("\n")) try: msg = unicode(e) except: try: msg = str(e) except: msg = repr(e) notify(getLocalizedLabel(msg), time=7000) return if not data: return if data["content_type"]: content_type = data["content_type"] if data["content_type"].startswith("menus"): content_type = data["content_type"].split("_")[1] xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_UNSORTED) if content_type != "tvshows": xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE) xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_DATE) xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_GENRE) xbmcplugin.setContent(HANDLE, content_type) listitems = range(len(data["items"])) for i, item in enumerate(data["items"]): # Translate labels if item["label"][0:8] == "LOCALIZE": item["label"] = unicode(getLocalizedLabel(item["label"]), 'utf-8') if item["label2"][0:8] == "LOCALIZE": item["label2"] = getLocalizedLabel(item["label2"]) listItem = xbmcgui.ListItem(label=item["label"], label2=item["label2"], iconImage=item["icon"], thumbnailImage=item["thumbnail"]) if item.get("info"): listItem.setInfo("video", item["info"]) if item.get("stream_info"): for type_, values in item["stream_info"].items(): listItem.addStreamInfo(type_, values) if item.get("art"): listItem.setArt(item["art"]) elif ADDON.getSetting( 'default_fanart') == 'true' and item["label"] != unicode( getLocalizedString(30218), 'utf-8'): fanart = os.path.join(ADDON_PATH, "fanart.png") listItem.setArt({'fanart': fanart}) if item.get("context_menu"): # Translate context menus for m, menu in enumerate(item["context_menu"]): if menu[0][0:8] == "LOCALIZE": menu[0] = getLocalizedLabel(menu[0]) listItem.addContextMenuItems(item["context_menu"]) listItem.setProperty("isPlayable", item["is_playable"] and "true" or "false") if item.get("properties"): for k, v in item["properties"].items(): listItem.setProperty(k, v) listitems[i] = (item["path"], listItem, not item["is_playable"]) xbmcplugin.addDirectoryItems(HANDLE, listitems, totalItems=len(listitems)) # Set ViewMode if data["content_type"]: viewMode = ADDON.getSetting("viewmode_%s" % data["content_type"]) if viewMode: try: xbmc.executebuiltin('Container.SetViewMode(%s)' % viewMode) except Exception as e: log.warning("Unable to SetViewMode(%s): %s" % (viewMode, repr(e))) xbmcplugin.endOfDirectory(HANDLE, succeeded=True, updateListing=False, cacheToDisc=True)
def get_list(): xbmcplugin.setContent(plugin.handle, "episodes") show_id = plugin.args["show_id"][0] if "show_id" in plugin.args else "" page = int(plugin.args["page"][0] if "page" in plugin.args else 0) category = int(plugin.args["category"][0] if "category" in plugin.args else 0) porady_dict = json.loads(get_page(_apiurl + "shows")) data = json.loads( get_page(_apiurl + "loadmore?type=articles&ignore_ids=&page=" + str(page) + "&porad=" + show_id + "&_=" + str(int(time.time())))) count = 0 duration = 0 listing = [] for item in data["items"]: if item["host"] and item["premium"] == 0: desc = item["title"].strip() thumb = item["cover"] slug_url = item["slug"] slug_show = item["porad"] show_title = (list([ x for x in porady_dict if x["slug"] == slug_show ]))[0]["title"] title = item["perex"].strip() if item["perex"] else item["host"] title_label = title if category == 1: title_label = "[COLOR blue]{0}[/COLOR] · {1}".format( show_title, title) date = datetime.datetime( *(time.strptime(item["published_at"], "%Y-%m-%d %H:%M:%S")[:6] )).strftime("%Y-%m-%d") if 'duration' in item: l = item['duration'].strip().split(":") for pos, value in enumerate(l[::-1]): duration += int(value) * 60**pos list_item = xbmcgui.ListItem(title_label) list_item.setInfo( "video", { "mediatype": "episode", "tvshowtitle": show_title, "title": title, "plot": desc, "duration": duration, "premiered": date, }, ) list_item.setArt({"icon": thumb}) list_item.setProperty("IsPlayable", "true") listing.append(( plugin.url_for(get_video, slug_show=slug_show, slug_url=slug_url), list_item, False, )) count += 1 if int(data["is_more"]) > 0 and count > 0: list_item = xbmcgui.ListItem(label=_addon.getLocalizedString(30003)) list_item.setArt({"icon": "DefaultFolder.png"}) listing.append(( plugin.url_for(get_list, show_id=show_id, category=1, page=page + 1), list_item, True, )) xbmcplugin.addDirectoryItems(plugin.handle, listing, len(listing)) xbmcplugin.endOfDirectory(plugin.handle)
def get_next_episodes(item_id, limit): ''' Only for synced content. ''' with Database('emby') as embydb: db = emby_db.EmbyDatabase(embydb.cursor) library = db.get_view_name(item_id) if not library: return result = JSONRPC('VideoLibrary.GetTVShows').execute({ 'sort': {'order': "descending", 'method': "lastplayed"}, 'filter': { 'and': [ {'operator': "true", 'field': "inprogress", 'value': ""}, {'operator': "is", 'field': "tag", 'value': "%s" % library} ]}, 'properties': ['title', 'studio', 'mpaa', 'file', 'art'] }) try: items = result['result']['tvshows'] except (KeyError, TypeError): return list_li = [] for item in items: if settings('ignoreSpecialsNextEpisodes.bool'): params = { 'tvshowid': item['tvshowid'], 'sort': {'method': "episode"}, 'filter': { 'and': [ {'operator': "lessthan", 'field': "playcount", 'value': "1"}, {'operator': "greaterthan", 'field': "season", 'value': "0"} ]}, 'properties': [ "title", "playcount", "season", "episode", "showtitle", "plot", "file", "rating", "resume", "tvshowid", "art", "streamdetails", "firstaired", "runtime", "writer", "dateadded", "lastplayed" ], 'limits': {"end": 1} } else: params = { 'tvshowid': item['tvshowid'], 'sort': {'method': "episode"}, 'filter': {'operator': "lessthan", 'field': "playcount", 'value': "1"}, 'properties': [ "title", "playcount", "season", "episode", "showtitle", "plot", "file", "rating", "resume", "tvshowid", "art", "streamdetails", "firstaired", "runtime", "writer", "dateadded", "lastplayed" ], 'limits': {"end": 1} } result = JSONRPC('VideoLibrary.GetEpisodes').execute(params) try: episodes = result['result']['episodes'] except (KeyError, TypeError): pass else: for episode in episodes: li = create_listitem(episode) list_li.append((episode['file'], li)) if len(list_li) == limit: break xbmcplugin.addDirectoryItems(int(sys.argv[1]), list_li, len(list_li)) xbmcplugin.setContent(int(sys.argv[1]), 'episodes') xbmcplugin.endOfDirectory(int(sys.argv[1]))
def browse(media, view_id=None, folder=None, server_id=None): ''' Browse content dynamically. ''' LOG.info("--[ v:%s/%s ] %s", view_id, media, folder) if not window('emby_online.bool') and server_id is None: monitor = xbmc.Monitor() for i in range(300): if window('emby_online.bool'): break elif monitor.waitForAbort(0.1): return else: LOG.error("Default server is not online.") return folder = folder.lower() if folder else None if folder is None and media in ('homevideos', 'movies', 'books', 'audiobooks'): return browse_subfolders(media, view_id, server_id) if folder and folder == 'firstletter': return browse_letters(media, view_id, server_id) if view_id: view = TheVoid('GetItem', {'ServerId': server_id, 'Id': view_id}).get() xbmcplugin.setPluginCategory(int(sys.argv[1]), view['Name']) content_type = "files" if media in ('tvshows', 'seasons', 'episodes', 'movies', 'musicvideos', 'songs', 'albums'): content_type = media elif media in ('homevideos', 'photos'): content_type = "images" elif media in ('books', 'audiobooks'): content_type = "videos" elif media == 'music': content_type = "artists" if folder == 'recentlyadded': listing = TheVoid('RecentlyAdded', {'Id': view_id, 'ServerId': server_id}).get() elif folder == 'genres': listing = TheVoid('Genres', {'Id': view_id, 'ServerId': server_id}).get() elif media == 'livetv': listing = TheVoid('LiveTV', {'Id': view_id, 'ServerId': server_id}).get() elif folder == 'unwatched': listing = TheVoid('Browse', {'Id': view_id, 'ServerId': server_id, 'Filters': ['IsUnplayed']}).get() elif folder == 'favorite': listing = TheVoid('Browse', {'Id': view_id, 'ServerId': server_id, 'Filters': ['IsFavorite']}).get() elif folder == 'inprogress': listing = TheVoid('Browse', {'Id': view_id, 'ServerId': server_id, 'Filters': ['IsResumable']}).get() elif folder == 'boxsets': listing = TheVoid('Browse', {'Id': view_id, 'ServerId': server_id, 'Media': get_media_type('boxsets'), 'Recursive': True}).get() elif folder == 'random': listing = TheVoid('Browse', {'Id': view_id, 'ServerId': server_id, 'Media': get_media_type(content_type), 'Sort': "Random", 'Limit': 25, 'Recursive': True}).get() elif (folder or "").startswith('firstletter-'): listing = TheVoid('Browse', {'Id': view_id, 'ServerId': server_id, 'Media': get_media_type(content_type), 'Params': {'NameStartsWith': folder.split('-')[1]}}).get() elif (folder or "").startswith('genres-'): listing = TheVoid('Browse', {'Id': view_id, 'ServerId': server_id, 'Media': get_media_type(content_type), 'Params': {'GenreIds': folder.split('-')[1]}}).get() elif folder == 'favepisodes': listing = TheVoid('Browse', {'Media': get_media_type(content_type), 'ServerId': server_id, 'Limit': 25, 'Filters': ['IsFavorite']}).get() elif media == 'homevideos': listing = TheVoid('Browse', {'Id': folder or view_id, 'Media': get_media_type(content_type), 'ServerId': server_id, 'Recursive': False}).get() elif media == 'movies': listing = TheVoid('Browse', {'Id': folder or view_id, 'Media': get_media_type(content_type), 'ServerId': server_id, 'Recursive': True}).get() elif media in ('boxset', 'library'): listing = TheVoid('Browse', {'Id': folder or view_id, 'ServerId': server_id, 'Recursive': True}).get() elif media == 'episodes': listing = TheVoid('Browse', {'Id': folder or view_id, 'Media': get_media_type(content_type), 'ServerId': server_id, 'Recursive': True}).get() elif media == 'boxsets': listing = TheVoid('Browse', {'Id': folder or view_id, 'ServerId': server_id, 'Recursive': False, 'Filters': ["Boxsets"]}).get() elif media == 'tvshows': listing = TheVoid('Browse', {'Id': folder or view_id, 'ServerId': server_id, 'Recursive': True, 'Media': get_media_type(content_type)}).get() elif media == 'seasons': listing = TheVoid('BrowseSeason', {'Id': folder, 'ServerId': server_id}).get() elif media != 'files': listing = TheVoid('Browse', {'Id': folder or view_id, 'ServerId': server_id, 'Recursive': False, 'Media': get_media_type(content_type)}).get() else: listing = TheVoid('Browse', {'Id': folder or view_id, 'ServerId': server_id, 'Recursive': False}).get() if listing: actions = Actions(server_id) list_li = [] listing = listing if type(listing) == list else listing.get('Items', []) for item in listing: li = xbmcgui.ListItem() li.setProperty('embyid', item['Id']) li.setProperty('embyserver', server_id) actions.set_listitem(item, li) if item.get('IsFolder'): params = { 'id': view_id or item['Id'], 'mode': "browse", 'type': get_folder_type(item, media) or media, 'folder': item['Id'], 'server': server_id } path = "%s?%s" % ("plugin://plugin.video.emby/", urllib.urlencode(params)) context = [] if item['Type'] in ('Series', 'Season', 'Playlist'): context.append(("Play", "RunPlugin(plugin://plugin.video.emby/?mode=playlist&id=%s&server=%s)" % (item['Id'], server_id))) if item['UserData']['Played']: context.append((_(16104), "RunPlugin(plugin://plugin.video.emby/?mode=unwatched&id=%s&server=%s)" % (item['Id'], server_id))) else: context.append((_(16103), "RunPlugin(plugin://plugin.video.emby/?mode=watched&id=%s&server=%s)" % (item['Id'], server_id))) li.addContextMenuItems(context) list_li.append((path, li, True)) elif item['Type'] == 'Genre': params = { 'id': view_id or item['Id'], 'mode': "browse", 'type': get_folder_type(item, media) or media, 'folder': 'genres-%s' % item['Id'], 'server': server_id } path = "%s?%s" % ("plugin://plugin.video.emby/", urllib.urlencode(params)) list_li.append((path, li, True)) else: if item['Type'] not in ('Photo', 'PhotoAlbum'): params = { 'id': item['Id'], 'mode': "play", 'server': server_id } path = "%s?%s" % ("plugin://plugin.video.emby/", urllib.urlencode(params)) li.setProperty('path', path) context = [(_(13412), "RunPlugin(plugin://plugin.video.emby/?mode=playlist&id=%s&server=%s)" % (item['Id'], server_id))] if item['UserData']['Played']: context.append((_(16104), "RunPlugin(plugin://plugin.video.emby/?mode=unwatched&id=%s&server=%s)" % (item['Id'], server_id))) else: context.append((_(16103), "RunPlugin(plugin://plugin.video.emby/?mode=watched&id=%s&server=%s)" % (item['Id'], server_id))) li.addContextMenuItems(context) list_li.append((li.getProperty('path'), li, False)) xbmcplugin.addDirectoryItems(int(sys.argv[1]), list_li, len(list_li)) if content_type == 'images': xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_VIDEO_TITLE) xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_DATE) xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_VIDEO_RATING) xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_VIDEO_RUNTIME) xbmcplugin.setContent(int(sys.argv[1]), content_type) xbmcplugin.endOfDirectory(int(sys.argv[1]))
def getVideos(self): # # Init # current_page = 1 # title = "" thumbnail_url = "" list_item = '' is_folder = False # Create a list for our items. listing = [] # # Get HTML page # response = requests.get(self.video_list_page_url) html_source = response.text html_source = convertToUnicodeString(html_source) # log("html_source", html_source) # Parse response soup = getSoup(html_source) #<a href="https://www.uitzendinggemist.net/programmas/5339-1_April_Met_Jack_De_Aap.html" title="1 April Met Jack De Aap">1 April Met Jack De Aap</a> tv_shows = soup.findAll( 'a', attrs={ 'href': re.compile("^https://www.uitzendinggemist.net/programmas/") }) for tv_show in tv_shows: log("tv_show", tv_show) video_page_url = tv_show['href'] log("video_page_url", video_page_url) last_part_of_video_url = str(video_page_url).replace( "https://www.uitzendinggemist.net/programmas/", "") log("last_part_of_video_url", last_part_of_video_url) if last_part_of_video_url == "": log( "skipping video_page_url with empty last_part_of_video_url after https://www.uitzendinggemist.net/programmas/ in url", video_page_url) continue letter_or_number = last_part_of_video_url[0:1] slash_or_no_slash = last_part_of_video_url[1:2] if letter_or_number.isalpha(): log( "skipping video_page_url with letter after https://www.uitzendinggemist.net/programmas/ in url", video_page_url) continue if slash_or_no_slash == "/": log( "skipping video_page_url with slash after number after https://www.uitzendinggemist.net/programmas/ in url", video_page_url) continue title = tv_show["title"] if self.show_channel == "True": try: channel = tv_show.select('img')[1]["alt"] log("channel", channel) channel = str(channel).replace("Nederland", "NL ") title = channel + ": " + title except: pass log("title", title) context_menu_items = [] # Add refresh option to context menu context_menu_items.append((LANGUAGE(30667), 'Container.Refresh')) # Add to list... list_item = xbmcgui.ListItem(label=title, thumbnailImage=thumbnail_url) list_item.setArt({ 'thumb': thumbnail_url, 'icon': thumbnail_url, 'fanart': os.path.join(IMAGES_PATH, 'fanart-blur.jpg') }) list_item.setProperty('IsPlayable', 'false') # let's remove any non-ascii characters title = title.encode('ascii', 'ignore') parameters = { "action": "list-episodes", "plugin_category": title, "url": video_page_url, "next_page_possible": "False", "show_channel": "True", "title": title } url = self.plugin_url + '?' + urllib.parse.urlencode(parameters) is_folder = True # Adding context menu items to context menu list_item.addContextMenuItems(context_menu_items, replaceItems=False) # Add our item to the listing as a 3-element tuple. listing.append((url, list_item, is_folder)) # # Next page entry... # if self.next_page_possible == 'True': # next_page = current_page + 1 # list_item = xbmcgui.ListItem(LANGUAGE(30503), thumbnailImage=os.path.join(IMAGES_PATH, 'next-page.png')) # list_item.setArt({'fanart': os.path.join(IMAGES_PATH, 'fanart-blur.jpg')}) # list_item.setProperty('IsPlayable', 'false') # parameters = {"action": "list-specials", "plugin_category": self.plugin_category, # "url": str(self.base_url) + str(next_page) + '/', # "next_page_possible": self.next_page_possible} # url = self.plugin_url + '?' + urllib.parse.urlencode(parameters) # is_folder = True # # Add refresh option to context menu # list_item.addContextMenuItems([('Refresh', 'Container.Refresh')]) # # Add our item to the listing as a 3-element tuple. # listing.append((url, list_item, is_folder)) # # log("next url", url) # Add our listing to Kodi. # Large lists and/or slower systems benefit from adding all items at once via addDirectoryItems # instead of adding one by ove via addDirectoryItem. xbmcplugin.addDirectoryItems(self.plugin_handle, listing, len(listing)) # Disable sorting xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE) # Finish creating a virtual folder. xbmcplugin.endOfDirectory(self.plugin_handle)
def list_episodes_recent(id, urlname, page, category): xbmcplugin.setContent(plugin.handle, 'episodes') listing = [] client = GraphQLClient(_apiurl) if 'none' in (id, page) and category == 'episodes': query = '''query LoadTags($limit :Int,$episodesConnectionFirst :Int){tags(listing:homepage,limit:$limit){...TimelineBoxFragmentOnTag episodesConnection(first :$episodesConnectionFirst){...EpisodeCardsFragmentOnEpisodeItemConnection}}tagsCount(listing:homepage)}fragment TimelineBoxFragmentOnTag on Tag{id,dotId,name,urlName,category,originTag{...DefaultOriginTagFragmentOnTag}}fragment EpisodeCardsFragmentOnEpisodeItemConnection on EpisodeItemConnection{totalCount pageInfo{endCursor hasNextPage}edges{node{...EpisodeCardFragmentOnEpisode}}}fragment DefaultOriginTagFragmentOnTag on Tag{id,dotId,name,urlName,category,images{...DefaultFragmentOnImage}}fragment EpisodeCardFragmentOnEpisode on Episode{id dotId name perex duration images{...DefaultFragmentOnImage}urlName originTag{...DefaultOriginTagFragmentOnTag}publish views}fragment DefaultFragmentOnImage on Image{usage,url}''' params = { 'limit': 1, 'episodesConnectionFirst': _addon.getSetting('limit') } data = client.execute(query, params) items = data['data']['tags'][0]['episodesConnection']['edges'] pageinfo = data['data']['tags'][0]['episodesConnection']['pageInfo'] id = data['data']['tags'][0]['id'] if not 'none' in (page) and category == 'episodes': query = '''query LoadTag($id :ID,$episodesConnectionAfter :String,$episodesConnectionFirst :Int){tagData:tag(id:$id){episodesConnection(after:$episodesConnectionAfter,first :$episodesConnectionFirst){...SeasonEpisodeCardsFragmentOnEpisodeItemConnection}}}fragment SeasonEpisodeCardsFragmentOnEpisodeItemConnection on EpisodeItemConnection{totalCount pageInfo{endCursor hasNextPage}edges{node{...SeasonEpisodeCardFragmentOnEpisode}}}fragment SeasonEpisodeCardFragmentOnEpisode on Episode{id dotId name namePrefix perex duration images{...DefaultFragmentOnImage}urlName originTag{...DefaultOriginTagFragmentOnTag}publish views}fragment DefaultFragmentOnImage on Image{usage,url}fragment DefaultOriginTagFragmentOnTag on Tag{id,dotId,name,urlName,category,images{...DefaultFragmentOnImage}}''' params = { 'id': id, 'episodesConnectionAfter': page, 'episodesConnectionFirst': _addon.getSetting('limit') } data = client.execute(query, params) items = data['data']['tagData']['episodesConnection']['edges'] pageinfo = data['data']['tagData']['episodesConnection']['pageInfo'] if 'none' in (id, page) and category == 'channel_episodes': query = '''query LoadChildTags($urlName :String,$childTagsConnectionFirst :Int,$episodesConnectionFirst :Int){tag(urlName:$urlName,category:service){childTagsConnection(first :$childTagsConnectionFirst){...TimelineBoxFragmentOnTagConnection edges{node{episodesConnection(first :$episodesConnectionFirst){...EpisodeCardsFragmentOnEpisodeItemConnection}}}}}}fragment TimelineBoxFragmentOnTagConnection on TagConnection{totalCount pageInfo{endCursor hasNextPage}edges{node{...TimelineBoxFragmentOnTag}}}fragment EpisodeCardsFragmentOnEpisodeItemConnection on EpisodeItemConnection{totalCount pageInfo{endCursor hasNextPage}edges{node{...EpisodeCardFragmentOnEpisode}}}fragment TimelineBoxFragmentOnTag on Tag{id,dotId,name,urlName,category,originTag{...DefaultOriginTagFragmentOnTag}}fragment EpisodeCardFragmentOnEpisode on Episode{id dotId name perex duration images{...DefaultFragmentOnImage}urlName originTag{...DefaultOriginTagFragmentOnTag}publish views}fragment DefaultOriginTagFragmentOnTag on Tag{id,dotId,name,urlName,category,images{...DefaultFragmentOnImage}}fragment DefaultFragmentOnImage on Image{usage,url}''' params = { 'urlName': urlname, 'childTagsConnectionFirst': 1, 'episodesConnectionFirst': _addon.getSetting('limit') } data = client.execute(query, params) items = data['data']['tag']['childTagsConnection']['edges'][0]['node'][ 'episodesConnection']['edges'] pageinfo = data['data']['tag']['childTagsConnection']['edges'][0][ 'node']['episodesConnection']['pageInfo'] if not 'none' in (page) and category == 'channel_episodes': query = '''query LoadTag($id :ID,$episodesConnectionAfter :String,$episodesConnectionFirst :Int){tagData:tag(id:$id){episodesConnection(after:$episodesConnectionAfter,first :$episodesConnectionFirst){...SeasonEpisodeCardsFragmentOnEpisodeItemConnection}}}fragment SeasonEpisodeCardsFragmentOnEpisodeItemConnection on EpisodeItemConnection{totalCount pageInfo{endCursor hasNextPage}edges{node{...SeasonEpisodeCardFragmentOnEpisode}}}fragment SeasonEpisodeCardFragmentOnEpisode on Episode{id dotId name namePrefix perex duration images{...DefaultFragmentOnImage}urlName originTag{...DefaultOriginTagFragmentOnTag}publish views}fragment DefaultFragmentOnImage on Image{usage,url}fragment DefaultOriginTagFragmentOnTag on Tag{id,dotId,name,urlName,category,images{...DefaultFragmentOnImage}}''' params = { 'id': id, 'episodesConnectionAfter': page, 'episodesConnectionFirst': _addon.getSetting('limit') } data = client.execute(query, params) items = data['data']['tagData']['episodesConnection']['edges'] pageinfo = data['data']['tagData']['episodesConnection']['pageInfo'] for item in items: menuitems = [] item = item['node'] show_title = item['originTag']['name'] name = item['name'].strip() listitem = xbmcgui.ListItem(u'[COLOR blue]{0}[/COLOR] · {1}'.format( show_title, name)) listitem.setInfo( 'video', { 'mediatype': 'episode', 'tvshowtitle': show_title, 'title': name, 'plot': item['perex'], 'duration': item['duration'], 'premiered': datetime.utcfromtimestamp(item['publish']).strftime('%Y-%m-%d') }) listitem.setArt({'icon': _image(item['images'])}) listitem.setProperty('IsPlayable', 'true') menuitems.append( (_addon.getLocalizedString(30006), 'Container.Update(' + plugin.url_for(list_episodes, item['originTag']['id'], item['originTag']['urlName'], 'none', item['originTag']['category']) + ')')) menuitems.append( (_addon.getLocalizedString(30007), 'Container.Update(' + plugin.url_for(list_channels, item['originTag']['urlName'], 'related') + ')')) listitem.addContextMenuItems(menuitems) listing.append((plugin.url_for(get_video, item['urlName']), listitem, False)) if (pageinfo['hasNextPage'] == True): listitem = xbmcgui.ListItem(_addon.getLocalizedString(30001)) listing.append((plugin.url_for(list_episodes_recent, id, urlname, pageinfo['endCursor'], 'episodes'), listitem, True)) xbmcplugin.addDirectoryItems(plugin.handle, listing, len(listing)) xbmcplugin.endOfDirectory(plugin.handle)
def search_movie(item): title = item['title'] year = item['year'] filename = item['filename'] mansearchstr = item['mansearchstr'] hd['Cookie'] = 'LanguageFilter=13,45' if mansearchstr: title = re.sub('\(\w+?\)', '', urllib.unquote(mansearchstr)) mess('Manual search for string') else: title = re.sub('&#.* ', '', title.replace("&", "and")).strip() title = ' '.join(s for s in title.split()) subspage_url = find_movie(title, year) subtitles = [] subs = [] pattern = '<a href="(/subtitles/.+?)">\s+<span class=".+?">\s*(.+?)\s+</span>\s+<span>\s+(.+?)\s+</span>' if subspage_url: url = subscene + subspage_url subs = re.findall(pattern, xread(url, hd)) if re.search('[S|s]\d\d', item['filename']): newtitle = ' '.join(s for s in title.split() if not re.search('[S|s]\d\d', s)) newtitle = '%s %s Season' % (newtitle, seasons[re.search( '[S|s](\d\d)', item['filename']).group(1)]) subspage_url = find_movie(newtitle, year) if subspage_url: url = subscene + subspage_url subs += re.findall(pattern, xread(url, hd)) if mansearchstr: url = subscene + '/subtitles/release?q=' + urllib.quote_plus( title) + '&r=true' subs += re.findall(pattern, xread(url, hd)) if not subs and '-' in title: newtitle = ' '.join(s for s in re.sub('\(.+?\)', '', title.split('-')[1]).split()) subspage_url = find_movie(newtitle, year) if subspage_url: url = subscene + subspage_url subs += re.findall(pattern, xread(url, hd)) if not subs: newtitle = ' '.join(s for s in re.sub('\(.+?\)', '', title.split('-')[0]).split()) subspage_url = find_movie(newtitle, year) if subspage_url: url = subscene + subspage_url subs += re.findall(pattern, xread(url, hd)) phudeviet_url = find_phudeviet(title, year) if not phudeviet_url: phudeviet_url = google_find_phudeviet(title, year) if phudeviet_url: pattern_pdv = '<td class="td4".+"(.+png)">.+\s+<td class="td1".+href="(.+?)">(.+?)<.+td>' for lang, href, fn in re.findall(pattern_pdv, xread(phudeviet_url)): if 'Anh.png' in lang: lang = "English" else: lang = "Phudeviet" subs.append((href, lang, fn)) notification = '' if not subs: mess(u'Tìm gần đúng') url = 'http://subscene.com/subtitles/release?q=%s' % title.replace( ' ', '.') + '.' + year log(url) pattern = '<a href="(/subtitles/.+?)">\s+<span class=".+?">\s*(.+?)\s+</span>\s+<span>\s+(.+?)\s+</span>' subs = re.findall(pattern, xread(url, hd)) if subs: notification = u'tìm gần đúng!' if not subs: mess(u'Không tìm thấy phụ đề') fn = os.path.splitext(filename)[0].split('.x264')[0].replace( ' ', '.').replace('-', '.').replace('*', '.') ratlist = fn.split('.') for link, lang, name in subs: name = name.strip().replace(' ', '.') rat = 1 label = 'vie' if 'Vietnam' in lang: img = 'vi' url = subscene + link elif 'Phude' in lang: img = 'vi' url = link name = 'phudeviet.org ' + name else: img = 'en' url = subscene + link if addon.getSetting('trans_sub') == 'false': label = 'eng' for i in ratlist: try: if re.search(i, name): rat += 1 except: pass subtitles.append((name, url, label, img, str(rat))) items = list() for fn, link, label, img, rating in sorted( subtitles, cmp=lambda x, y: cmp(x[0], y[3]), reverse=True): item = xbmcgui.ListItem(label=label, label2=fn, iconImage=rating, thumbnailImage=img) url = "plugin://%s/?action=download&link=%s&filename=%s&img=%s" % ( service, link, fn, img) items.append((url, item, False)) if items: xbmcplugin.addDirectoryItems(int(sys.argv[1]), items) if not filename: filename = title mess(u'Movie: %s' % filename, 20000, 'Xshare %s: Movie year - %s ' % (notification, year))
def showMainMenu(self): items = list() # Live TV item = xbmcgui.ListItem(ADDON.getLocalizedString(30027), iconImage=os.path.join( ADDON.getAddonInfo('path'), 'resources', 'icons', 'livetv.png')) item.setProperty('Fanart_Image', FANART_IMAGE) item.addContextMenuItems(self.menuItems, False) items.append((PATH + '?show=liveTV', item, True)) # A-Z Program Series item = xbmcgui.ListItem(ADDON.getLocalizedString(30000), iconImage=os.path.join( ADDON.getAddonInfo('path'), 'resources', 'icons', 'all.png')) item.setProperty('Fanart_Image', FANART_IMAGE) item.addContextMenuItems(self.menuItems, False) items.append((PATH + '?show=listAZ', item, True)) # Latest item = xbmcgui.ListItem(ADDON.getLocalizedString(30001), iconImage=os.path.join( ADDON.getAddonInfo('path'), 'resources', 'icons', 'all.png')) item.setProperty('Fanart_Image', FANART_IMAGE) item.addContextMenuItems(self.menuItems, False) items.append((PATH + '?show=latest', item, True)) # Premiere item = xbmcgui.ListItem(ADDON.getLocalizedString(30025), iconImage=os.path.join( ADDON.getAddonInfo('path'), 'resources', 'icons', 'new.png')) item.setProperty('Fanart_Image', FANART_IMAGE) item.addContextMenuItems(self.menuItems, False) items.append( (PATH + '?listVideos=%s' % tvapi.SLUG_PREMIERES, item, True)) # Themes / Repremiere item = xbmcgui.ListItem(ADDON.getLocalizedString(30028), iconImage=os.path.join( ADDON.getAddonInfo('path'), 'resources', 'icons', 'all.png')) item.setProperty('Fanart_Image', FANART_IMAGE) item.addContextMenuItems(self.menuItems, False) items.append((PATH + '?show=themes', item, True)) # Most viewed item = xbmcgui.ListItem(ADDON.getLocalizedString(30011), iconImage=os.path.join( ADDON.getAddonInfo('path'), 'resources', 'icons', 'eye.png')) item.setProperty('Fanart_Image', FANART_IMAGE) item.addContextMenuItems(self.menuItems, False) items.append((PATH + '?show=mostViewed', item, True)) # Spotlight item = xbmcgui.ListItem(ADDON.getLocalizedString(30002), iconImage=os.path.join( ADDON.getAddonInfo('path'), 'resources', 'icons', 'star.png')) item.setProperty('Fanart_Image', FANART_IMAGE) item.addContextMenuItems(self.menuItems, False) items.append((PATH + '?show=highlights', item, True)) # Search videos item = xbmcgui.ListItem(ADDON.getLocalizedString(30003), iconImage=os.path.join( ADDON.getAddonInfo('path'), 'resources', 'icons', 'search.png')) item.setProperty('Fanart_Image', FANART_IMAGE) item.addContextMenuItems(self.menuItems, False) items.append((PATH + '?show=search', item, True)) # Recently watched Program Series item = xbmcgui.ListItem(ADDON.getLocalizedString(30007), iconImage=os.path.join( ADDON.getAddonInfo('path'), 'resources', 'icons', 'eye-star.png')) item.setProperty('Fanart_Image', FANART_IMAGE) item.addContextMenuItems(self.menuItems, False) items.append((PATH + '?show=recentlyWatched', item, True)) # Favorite Program Series item = xbmcgui.ListItem(ADDON.getLocalizedString(30008), iconImage=os.path.join( ADDON.getAddonInfo('path'), 'resources', 'icons', 'plusone.png')) item.setProperty('Fanart_Image', FANART_IMAGE) items.append((PATH + '?show=favorites', item, True)) item.addContextMenuItems(self.menuItems, False) xbmcplugin.addDirectoryItems(HANDLE, items) xbmcplugin.endOfDirectory(HANDLE)
def list_files(folder_id, id, server): username = addon.getSetting('username') password = addon.getSetting('password') api_url = 'https://tugaleak.com/kodi-api/api.php' data = {'command': folder_id, 'username': username, 'password': password, 'id': id, 'server': server} rslt = request(api_url, data) if rslt['statusCode'] != 200: return notify_api_error(rslt) if rslt['status'] == 'error': return notify_api_error(rslt) listing = [] if folder_id == 'categories': for category_data in rslt['data']: infoLabels = { 'title': category_data['vcat_title'] } li = xbmcgui.ListItem(label=category_data['vcat_title']) li.setInfo('video', infoLabels) li.setProperty('fanart_image', __fanart__) url = '{0}?action=list_files&folder_id=videos&id={1}'.format(__url__, category_data['vcat_id']) is_folder = True listing.append((url, li, is_folder)) elif folder_id == 'videos': for video_data in rslt['data']: infoLabels = { 'title': video_data['v_title'], 'genre': '12312312', 'mediatype': 'video' } thumbnail = 'https://tugaleak.com/uploads/{0}'.format(video_data['v_thumbnail_medium']) arts = {'thumb': thumbnail, 'icon': thumbnail, 'fanart': thumbnail} li = xbmcgui.ListItem(label=video_data['v_title'], iconImage=thumbnail, thumbnailImage=thumbnail) li.setArt(arts) li.setInfo(type='video', infoLabels=infoLabels) li.setProperty('fanart_image', thumbnail) url = '{0}?action=list_files&folder_id=servers&id={1}'.format(__url__, video_data['v_id']) is_folder = True listing.append((url, li, is_folder)) elif folder_id == 'servers': for server_data in rslt['data']: infoLabels = { 'title': server_data['vbs_name'] } li = xbmcgui.ListItem(label=server_data['vbs_name']) li.setInfo('video', infoLabels) li.setProperty('fanart_image', __fanart__) url = '{0}?action=list_files&folder_id=movies&id={1}&server={2}'.format(__url__, id, server_data['vbo_server']) is_folder = True listing.append((url, li, is_folder)) elif folder_id == 'movies': nCount = 1 for movie_data in rslt['data']: title = 'Episode {0} ({1})'.format(nCount, movie_data['vbo_url']) infoLabels = { 'title': title } li = xbmcgui.ListItem(label=title) li.setInfo('video', infoLabels) li.setProperty('fanart_image', __fanart__) # li.setProperty('IsPlayable', 'true') # is_folder = False is_folder = True # listing.append((movie_data['vbo_url'], li, is_folder)) url = '{0}?action=url_resolve&video_url={1}'.format(__url__, movie_data['vbo_url']) listing.append((url, li, is_folder)) nCount += 1 xbmcplugin.setContent(__handle__, 'movies') xbmcplugin.addDirectoryItems(__handle__, listing, len(listing)) xbmcplugin.addSortMethod(__handle__, xbmcplugin.SORT_METHOD_LABEL_IGNORE_FOLDERS) xbmcplugin.endOfDirectory(__handle__)
def _process_items(self, items, driveid): listing = [] for item in items: Logger.debug(item) item_id = item['id'] item_name = Utils.unicode(item['name']) item_name_extension = item['name_extension'] item_driveid = Utils.default( Utils.get_safe_value(item, 'drive_id'), driveid) list_item = xbmcgui.ListItem(item_name) url = None is_folder = 'folder' in item params = { 'content_type': self._content_type, 'item_driveid': item_driveid, 'item_id': item_id, 'driveid': driveid } if 'extra_params' in item: params.update(item['extra_params']) context_options = [] info = { 'size': item['size'], 'date': KodiUtils.to_kodi_item_date_str( KodiUtils.to_datetime( Utils.get_safe_value(item, 'last_modified_date'))) } if is_folder: params['action'] = '_list_folder' url = self._addon_url + '?' + urllib.urlencode(params) params['action'] = '_search' cmd = 'ActivateWindow(%d,%s?%s)' % (xbmcgui.getCurrentWindowId( ), self._addon_url, urllib.urlencode(params)) context_options.append( (self._common_addon.getLocalizedString(32039), cmd)) if self._content_type == 'audio' or self._content_type == 'video': params['action'] = '_open_export' params['name'] = urllib.quote(Utils.str(item_name)) context_options.append( (self._common_addon.getLocalizedString(32004), 'RunPlugin(' + self._addon_url + '?' + urllib.urlencode(params) + ')')) del params['name'] elif self._content_type == 'image' and self._auto_refreshed_slideshow_supported: params['action'] = '_slideshow' context_options.append( (self._common_addon.getLocalizedString(32032), 'RunPlugin(' + self._addon_url + '?' + urllib.urlencode(params) + ')')) elif (('video' in item or (item_name_extension and item_name_extension in self._video_file_extensions)) and self._content_type == 'video') or ( ('audio' in item or (item_name_extension and item_name_extension in self._audio_file_extensions)) and self._content_type == 'audio'): list_item.setProperty('IsPlayable', 'true') params['action'] = 'download' cmd = 'RunPlugin(' + self._addon_url + '?' + urllib.urlencode( params) + ')' context_options.append( (self._common_addon.getLocalizedString(32051), cmd)) params['action'] = 'play' url = self._addon_url + '?' + urllib.urlencode(params) info_type = self._content_type if 'audio' in item: info.update(item['audio']) info_type = 'music' elif 'video' in item: list_item.addStreamInfo('video', item['video']) list_item.setInfo(info_type, info) if 'thumbnail' in item: list_item.setArt({ 'icon': item['thumbnail'], 'thumb': item['thumbnail'] }) elif ('image' in item or (item_name_extension and item_name_extension in self._image_file_extensions) ) and self._content_type == 'image': Logger.debug( 'image in item: %s' % (Utils.str('image' in item)), ) Logger.debug( 'item_name_extension in self._image_file_extensions: %s' % (Utils.str( item_name_extension in self._image_file_extensions), )) params['action'] = 'download' cmd = 'RunPlugin(' + self._addon_url + '?' + urllib.urlencode( params) + ')' context_options.append( (self._common_addon.getLocalizedString(32051), cmd)) if 'url' in item: url = item['url'] else: url = self._get_item_play_url( urllib.quote(Utils.str(item_name)), driveid, item_driveid, item_id) if 'image' in item: info.update(item['image']) list_item.setInfo('pictures', info) if 'thumbnail' in item and item['thumbnail']: list_item.setArt({ 'icon': item['thumbnail'], 'thumb': item['thumbnail'] }) if url: context_options.extend( self.get_context_options(list_item, params, is_folder)) list_item.addContextMenuItems(context_options) mimetype = Utils.default( Utils.get_mimetype_by_extension(item_name_extension), Utils.get_safe_value(item, 'mimetype')) if mimetype: list_item.setProperty('mimetype', mimetype) listing.append((url, list_item, is_folder)) xbmcplugin.addDirectoryItems(self._addon_handle, listing, len(listing)) xbmcplugin.endOfDirectory(self._addon_handle, True)
def getContent(url, params): log.debug("== ENTER: getContent ==") media_type = params.get("media_type", None) if not media_type: xbmcgui.Dialog().ok(string_load(30135), string_load(30139)) log.debug("URL: {0}", url) log.debug("MediaType: {0}", media_type) pluginhandle = int(sys.argv[1]) settings = xbmcaddon.Addon() # determine view type, map it from media type to view type view_type = "" content_type = "" media_type = str(media_type).lower().strip() if media_type.startswith("movie"): view_type = "Movies" content_type = 'movies' elif media_type == "musicalbums": view_type = "Albums" content_type = 'albums' elif media_type == "musicartists": view_type = "Artists" content_type = 'artists' elif media_type == "musicartist": view_type = "Albums" content_type = 'albums' elif media_type == "music" or media_type == "audio" or media_type == "musicalbum": view_type = "Music" content_type = 'songs' elif media_type.startswith("boxsets"): view_type = "Movies" content_type = 'sets' elif media_type.startswith("boxset"): view_type = "BoxSets" content_type = 'movies' elif media_type == "tvshows": view_type = "Series" content_type = 'tvshows' elif media_type == "series": view_type = "Seasons" content_type = 'seasons' elif media_type == "season" or media_type == "episodes": view_type = "Episodes" content_type = 'episodes' log.debug("media_type:{0} content_type:{1} view_type:{2} ", media_type, content_type, view_type) # show a progress indicator if needed progress = None if (settings.getSetting('showLoadProgress') == "true"): progress = xbmcgui.DialogProgress() progress.create(string_load(30112)) progress.update(0, string_load(30113)) # update url for paging start_index = 0 page_limit = int(settings.getSetting('moviePageSize')) if page_limit > 0 and media_type.startswith("movie"): url_prev = None m = re.search('StartIndex=([0-9]{1,4})', url) if m and m.group(1): log.debug("UPDATING NEXT URL: {0}", url) start_index = int(m.group(1)) log.debug("current_start : {0}", start_index) if start_index > 0: prev_index = start_index - page_limit if prev_index < 0: prev_index = 0 url_prev = re.sub('StartIndex=([0-9]{1,4})', 'StartIndex=' + str(prev_index), url) url_next = re.sub('StartIndex=([0-9]{1,4})', 'StartIndex=' + str(start_index + page_limit), url) log.debug("UPDATING NEXT URL: {0}", url_next) else: log.debug("ADDING NEXT URL: {0}", url) url_next = url + "&StartIndex=" + str(start_index + page_limit) + "&Limit=" + str(page_limit) url = url + "&StartIndex=" + str(start_index) + "&Limit=" + str(page_limit) log.debug("ADDING NEXT URL: {0}", url_next) # use the data manager to get the data #result = dataManager.GetContent(url) #total_records = 0 #if result is not None and isinstance(result, dict): # total_records = result.get("TotalRecordCount", 0) use_cache = params.get("use_cache", "true") == "true" dir_items, detected_type, total_records = processDirectory(url, progress, params, use_cache) if dir_items is None: return log.debug("total_records: {0}", total_records) # add paging items if page_limit > 0 and media_type.startswith("movie"): if url_prev: list_item = xbmcgui.ListItem("Prev Page (" + str(start_index - page_limit + 1) + "-" + str(start_index) + " of " + str(total_records) + ")") u = sys.argv[0] + "?url=" + urllib.quote(url_prev) + "&mode=GET_CONTENT&media_type=movies" log.debug("ADDING PREV ListItem: {0} - {1}", u, list_item) dir_items.insert(0, (u, list_item, True)) if start_index + page_limit < total_records: upper_count = start_index + (page_limit * 2) if upper_count > total_records: upper_count = total_records list_item = xbmcgui.ListItem("Next Page (" + str(start_index + page_limit + 1) + "-" + str(upper_count) + " of " + str(total_records) + ")") u = sys.argv[0] + "?url=" + urllib.quote(url_next) + "&mode=GET_CONTENT&media_type=movies" log.debug("ADDING NEXT ListItem: {0} - {1}", u, list_item) dir_items.append((u, list_item, True)) # set the Kodi content type if content_type: xbmcplugin.setContent(pluginhandle, content_type) elif detected_type is not None: # if the media type is not set then try to use the detected type log.debug("Detected content type: {0}", detected_type) if detected_type == "Movie": view_type = "Movies" content_type = 'movies' if detected_type == "Episode": view_type = "Episodes" content_type = 'episodes' xbmcplugin.setContent(pluginhandle, content_type) # set the sort items if page_limit > 0 and media_type.startswith("movie"): xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_UNSORTED) else: setSort(pluginhandle, view_type) xbmcplugin.addDirectoryItems(pluginhandle, dir_items) xbmcplugin.endOfDirectory(pluginhandle, cacheToDisc=False) # send display items event display_items_notification = {"view_type": view_type} send_event_notification("display_items", display_items_notification) if (progress != None): progress.update(100, string_load(30125)) progress.close() return
def show_listing(title_items, category=None, sort=None, content=None, cache=True): """ Show a virtual directory in Kodi """ from resources.lib.addon import routing if content: # content is one of: files, songs, artists, albums, movies, tvshows, episodes, musicvideos, videos, images, games xbmcplugin.setContent(routing.handle, content=content) # Jump through hoops to get a stable breadcrumbs implementation category_label = '' if category: if not content: category_label = addon_name() + ' / ' if isinstance(category, int): category_label += localize(category) else: category_label += category elif not content: category_label = addon_name() xbmcplugin.setPluginCategory(handle=routing.handle, category=category_label) # Add all sort methods to GUI (start with preferred) if sort is None: sort = DEFAULT_SORT_METHODS elif not isinstance(sort, list): sort = [sort] + DEFAULT_SORT_METHODS for key in sort: xbmcplugin.addSortMethod(handle=routing.handle, sortMethod=SORT_METHODS[key]) # Add the listings listing = [] for title_item in title_items: # Three options: # - item is a virtual directory/folder (not playable, path) # - item is a playable file (playable, path) # - item is non-actionable item (not playable, no path) is_folder = bool(not title_item.is_playable and title_item.path) is_playable = bool(title_item.is_playable and title_item.path) list_item = xbmcgui.ListItem(label=title_item.title, path=title_item.path) if title_item.prop_dict: list_item.setProperties(title_item.prop_dict) list_item.setProperty(key='IsPlayable', value='true' if is_playable else 'false') list_item.setIsFolder(is_folder) if title_item.art_dict: list_item.setArt(title_item.art_dict) if title_item.info_dict: # type is one of: video, music, pictures, game list_item.setInfo(type='video', infoLabels=title_item.info_dict) if title_item.stream_dict: # type is one of: video, audio, subtitle list_item.addStreamInfo('video', title_item.stream_dict) if title_item.context_menu: list_item.addContextMenuItems(title_item.context_menu) is_folder = bool(not title_item.is_playable and title_item.path) url = title_item.path if title_item.path else None listing.append((url, list_item, is_folder)) succeeded = xbmcplugin.addDirectoryItems(routing.handle, listing, len(listing)) xbmcplugin.endOfDirectory(routing.handle, succeeded, cacheToDisc=cache)
def _list_models(self, category, tag, keyword, page): if category == "followed" and not self._has_auth(): return if not category: category = "featured" items = [] params = {} if not keyword: params['category'] = category params['action'] = 'new_search' url = '?'.join([self._url, urllib.urlencode(params)]) label = self._addon.getLocalizedString(30212) item = xbmcgui.ListItem(label) items.append((url, item, True)) if tag: cat = self._categories[category]['tag'] params['tag'] = tag else: categories = {} categories.update(self._categories) categories.update(self._categories_extra) cat = categories[category]['url'] if not keyword and category in self._categories: params['action'] = 'get_tags' params['page'] = 1 url = '?'.join([self._url, urllib.urlencode(params)]) item = xbmcgui.ListItem("#tags") items.append((url, item, True)) models = self._chaturbate.get_models(cat, tag, keyword, int(page)) last_page = (len(models) == 0) for model in models: name = model['name'] params['action'] = 'play' params['model'] = name if name: image = model['image'] info = model['info'] if model['follow']: label = name + " *" else: label = name url = '?'.join([self._url, urllib.urlencode(params)]) item = xbmcgui.ListItem(label) item.setArt({'icon': image, 'thumb': image, 'fanart': image}) item.setInfo('video', { 'title': name, 'mediatype': 'video', 'plot': info }) item.setCast([{"name": name}]) item.addContextMenuItems(self._create_model_context_menu(name)) items.append((url, item, False)) else: last_page = True if not last_page: params['action'] = 'get_models' params['page'] = int(page) + 1 url = '?'.join([self._url, urllib.urlencode(params)]) label = self._addon.getLocalizedString(30231) item = xbmcgui.ListItem("%s (%d)" % (label, int(page) + 1)) items.append((url, item, True)) xbmcplugin.addDirectoryItems(self._plugin_handle, items, len(items)) xbmcplugin.endOfDirectory(self._plugin_handle)
def getVideos(self): # # Init # # Create a list for our items. listing = [] # # Get HTML page # response = requests.get(self.video_list_page_url, headers=HEADERS) html_source = response.text html_source = convertToUnicodeString(html_source) # log("html_source", html_source) try: json_data = json.loads(html_source) # for item in json_data['data']: # log("attribute1", item['canonical_links']['self']) # log("attribute2", item['attributes']['title']) # exit(1) except (ValueError, KeyError, TypeError): xbmcgui.Dialog().ok(LANGUAGE(30000), LANGUAGE(30109)) exit(1) for item in json_data['data']: serie_title = item['attributes']['title'] serie_url_middle_part = item['canonical_links']['self'] # the serie url should something like this: # https://svod-be.roosterteeth.com/api/v1/shows/always-open/seasons serie_url = ROOSTERTEETH_SERIES_BASE_URL + serie_url_middle_part + '/seasons' # remove '/series/' from the url serie_url = serie_url.replace('/series/', '/') thumb = item['included']['images'][0]['attributes']['thumb'] title = serie_title log("title", title) url = serie_url log("url", url) thumbnail_url = thumb log("thumbnail_url", thumbnail_url) # Add to list... list_item = xbmcgui.ListItem(label=title, thumbnailImage=thumbnail_url) list_item.setArt({ 'thumb': thumbnail_url, 'icon': thumbnail_url, 'fanart': os.path.join(IMAGES_PATH, 'fanart-blur.jpg') }) list_item.setProperty('IsPlayable', 'false') # let's remove any non-ascii characters from the title, to prevent errors with urllib.parse.parse_qs # of the parameters title = title.encode('ascii', 'ignore') parameters = { "action": "list-serie-seasons", "url": url, "title": title, "thumbnail_url": thumbnail_url, "next_page_possible": "False" } plugin_url_with_parms = self.plugin_url + '?' + urllib.parse.urlencode( parameters) is_folder = True # Add refresh option to context menu list_item.addContextMenuItems([('Refresh', 'Container.Refresh')]) # Add our item to the listing as a 3-element tuple. listing.append((plugin_url_with_parms, list_item, is_folder)) # Add our listing to Kodi. # Large lists and/or slower systems benefit from adding all items at once via addDirectoryItems # instead of adding one by ove via addDirectoryItem. xbmcplugin.addDirectoryItems(self.plugin_handle, listing, len(listing)) # Disable sorting xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE) # Finish creating a virtual folder. xbmcplugin.endOfDirectory(self.plugin_handle)
def actionSearchMenu(params): def _modalKeyboard(heading): kb = xbmc.Keyboard('', heading) kb.doModal() return kb.getText() if kb.isConfirmed() else '' if 'searchType' in params: # Support for the 'actionShowInfo()' function reloading this route, sending it an already searched query. # This also supports external query calls, like from OpenMeta. if 'query' in params: query = params['query'] else: query = _modalKeyboard(params.get('searchTitle', 'Search')) if query: params['query'] = query params['section'] = 'ALL' actionCatalogSection( params ) # Send the search type and query for the catalog functions to use. return xbmcplugin.addDirectoryItems( PLUGIN_ID, ( ( buildURL({ 'action': 'actionSearchMenu', 'path': URL_PATHS[ 'search'], # A special, non-web path used by 'getCatalogProperty()'. 'searchType': 'series', 'searchTitle': 'Search Cartoon/Anime Name' }), xbmcgui.ListItem( '[COLOR lavender][B]Search Cartoon/Anime Name[/B][/COLOR]' ), True), (buildURL({ 'action': 'actionSearchMenu', 'path': URL_PATHS['search'], 'searchType': 'movies', 'searchTitle': 'Search Movie Name' }), xbmcgui.ListItem( '[COLOR lavender][B]Search Movie Name[/B][/COLOR]'), True), (buildURL({ 'action': 'actionSearchMenu', 'path': URL_PATHS['search'], 'searchType': 'episodes', 'searchTitle': 'Search Episode Name' }), xbmcgui.ListItem( '[COLOR lavender][B]Search Episode Name[/B][/COLOR]'), True), (buildURL({ 'action': 'actionGenresMenu', 'path': URL_PATHS['genre'] }), xbmcgui.ListItem( '[COLOR lavender][B]Search by Genre[/B][/COLOR]'), True), (buildURL({ 'action': 'actionTraktMenu', 'path': 'trakt' }), xbmcgui.ListItem( '[COLOR lavender][B]Search by Trakt List[/B][/COLOR]'), True))) xbmcplugin.endOfDirectory(PLUGIN_ID)
def getVideos(self): # # Init # shownsfw = (SETTINGS.getSetting('nsfw') == 'true') listing = [] # # Get data # # Set cookies for cookie-firewall and nsfw-switch if SETTINGS.getSetting('nsfw') == 'true': cookies = {"Cookie": "cpc=10", "nsfw": "1"} else: cookies = {"Cookie": "cpc=10"} # Determine if cloudflare protection is active or not html_source = requests.get(self.video_list_page_url, cookies=cookies).text if str(html_source).find("cloudflare") >= 0: cloudflare_active = True else: cloudflare_active = False # Make a session sess = requests.session() # Get the page if cloudflare_active == True: try: import cfscrape except: xbmcgui.Dialog().ok(LANGUAGE(30000), LANGUAGE(30513)) sys.exit(1) try: # returns a CloudflareScraper instance scraper = cfscrape.create_scraper(sess) except: xbmcgui.Dialog().ok(LANGUAGE(30000), LANGUAGE(30514)) sys.exit(1) try: html_source = scraper.get(self.video_list_page_url).content except: xbmcgui.Dialog().ok(LANGUAGE(30000), LANGUAGE(30515)) sys.exit(1) else: html_source = sess.get(self.video_list_page_url, cookies=cookies).text json_source = html_source data = json.loads(json_source) if not data['success']: xbmcplugin.endOfDirectory(self.plugin_handle) return for item in data['items']: title = item['title'] description = item['description'] thumbnail_url = item['thumbnail'] nsfw = item['nsfw'] if not nsfw or shownsfw: # {"id":"6737324_36df9881","title":"Hardcore brei-oma","thumbnail":"http:\/\/media.dumpert.nl\/sq_thumbs\/6737324_36df9881.jpg", # "still":"http:\/\/media.dumpert.nl\/stills\/6737324_36df9881.jpg","description":"Heeft vroeger wat uitgevroten... WTF?","date":"2016-03-18T19:35:56+01:00", # "tags":"dwdd oma wtf breien oud","nsfw":false,"nopreroll":false,"stats":{"views_total":466917,"views_today":32706,"kudos_total":4916,"kudos_today":343}, # "stills":{"thumb":"http:\/\/media.dumpert.nl\/sq_thumbs\/6737324_36df9881.jpg","thumb-medium":"http:\/\/media.dumpert.nl\/sq_thumbs\/medium\/6737324_36df9881.jpg", # "still":"http:\/\/media.dumpert.nl\/stills\/6737324_36df9881.jpg","still-medium":"http:\/\/media.dumpert.nl\/stills\/medium\/6737324_36df9881.jpg", # "still-large":"http:\/\/media.dumpert.nl\/stills\/large\/6737324_36df9881.jpg"},"media":[{"description":"","mediatype":"VIDEO","duration":55, # "variants":[{"version":"tablet","uri":"http:\/\/media.dumpert.nl\/tablet\/36df9881_VID_20160318_WA0000.mp4.mp4.mp4"},{"version":"mobile", # "uri":"http:\/\/media.dumpert.nl\/mobile\/36df9881_VID_20160318_WA0000.mp4.mp4.mp4"}]}]} # # grab first item (tablet) # skip embedded (youtube links) for now {"version":"embed","uri":"youtube:wOeZB7bnoxw"} if item['media'][0]['mediatype'] == 'VIDEO' and item['media'][ 0]['variants'][0]['version'] != 'embed': url = item['media'][0]['variants'][0]['uri'] list_item = xbmcgui.ListItem(label=title, thumbnailImage=thumbnail_url) list_item.setInfo("video", { "title": title, "studio": ADDON, "plot": description }) list_item.setArt({ 'thumb': thumbnail_url, 'icon': thumbnail_url, 'fanart': os.path.join(IMAGES_PATH, 'fanart-blur.jpg') }) list_item.setProperty('IsPlayable', 'true') is_folder = False # Add refresh option to context menu list_item.addContextMenuItems([('Refresh', 'Container.Refresh')]) # Add our item to the listing as a 3-element tuple. listing.append((url, list_item, is_folder)) # Next page entry if self.next_page_possible == 'True': next_page = self.current_page + 1 list_item = xbmcgui.ListItem(LANGUAGE(30503), thumbnailImage=os.path.join( IMAGES_PATH, 'next-page.png')) list_item.setArt( {'fanart': os.path.join(IMAGES_PATH, 'fanart-blur.jpg')}) list_item.setProperty('IsPlayable', 'false') parameters = { "action": "json", "plugin_category": self.plugin_category, "url": str(self.base_url) + str(next_page) + '/', "next_page_possible": self.next_page_possible } url = self.plugin_url + '?' + urllib.urlencode(parameters) is_folder = True # Add refresh option to context menu list_item.addContextMenuItems([('Refresh', 'Container.Refresh')]) # Add our item to the listing as a 3-element tuple. listing.append((url, list_item, is_folder)) # Add our listing to Kodi. # Large lists and/or slower systems benefit from adding all items at once via addDirectoryItems # instead of adding one by ove via addDirectoryItem. xbmcplugin.addDirectoryItems(self.plugin_handle, listing, len(listing)) # Disable sorting xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE) # Finish creating a virtual folder. xbmcplugin.endOfDirectory(self.plugin_handle)
def actionEpisodesMenu(params): xbmcplugin.setContent(PLUGIN_ID, 'episodes') # Memory-cache the last episode list, to help when the user goes back and forth while watching # multiple episodes of the same show. This way only one web request is needed. lastListURL = getRawWindowProperty(PROPERTY_EPISODE_LIST_URL) if lastListURL and lastListURL == params['url']: listData = getWindowProperty(PROPERTY_EPISODE_LIST_DATA) else: url = params['url'] # Always get episodes from the mobile version of the show page. r = requestHelper( url.replace('/www.', '/m.', 1) if url. startswith('http') else BASEURL_MOBILE + url) html = r.text # Try to scrape thumb and plot metadata from the show page. dataStartIndex = html.find('category_description') if dataStartIndex == -1: raise Exception('Episode description scrape fail: ' + url) else: htmlSlice = html[dataStartIndex:html.find('/p>', dataStartIndex)] thumb = re.search('''<img.*?src.*?"(.*?)"''', htmlSlice) thumb = thumb.group(1) if thumb else '' plot = re.search('''<p>(.*?)<''', htmlSlice, re.DOTALL) plot = plot.group(1) if plot else '' dataStartIndex = html.find('ui-listview-z', dataStartIndex) if dataStartIndex == -1: raise Exception('Episode list scrape fail: ' + url) # Episode list data: a tuple with the thumb, plot and an inner tuple of per-episode data. listData = (thumb, plot, tuple(match.groups() for match in re.finditer( '''<a.*?"(.*?)".*?>(.*?)</''', html[dataStartIndex:html.rfind('button')]))) setRawWindowProperty(PROPERTY_EPISODE_LIST_URL, params['url']) setWindowProperty(PROPERTY_EPISODE_LIST_DATA, listData) def _episodeItemsGen(): playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) playlist.clear() showURL = params['url'] thumb = listData[0] artDict = { 'icon': thumb, 'thumb': thumb, 'poster': thumb } if thumb else None plot = listData[1] listItemFunc = makeListItemClean if ADDON.getSetting( 'cleanupEpisodes') == 'true' else makeListItem itemParams = {'action': 'actionResolve', 'url': None} listIter = iter(listData[2]) if ADDON.getSetting( 'reverseEpisodes') == 'true' else reversed(listData[2]) for URL, title in listIter: item = listItemFunc(title, showURL, artDict, plot, isFolder=False, isSpecial=False, oldParams=None) itemParams['url'] = URL itemURL = buildURL(itemParams) playlist.add(itemURL, item) yield (itemURL, item, False) xbmcplugin.addDirectoryItems(PLUGIN_ID, tuple(_episodeItemsGen())) xbmcplugin.endOfDirectory(PLUGIN_ID)
def getVideos(self): # # Init # shownsfw = (SETTINGS.getSetting('nsfw') == 'true') listing = [] # # Get HTML page # response = requests.get(self.video_list_page_url) # response.status json_source = response.text json_source = convertToUnicodeString(json_source) data = json.loads(json_source) if not data['success']: xbmcplugin.endOfDirectory(self.plugin_handle) return for item in data['items']: title = item['title'] description = item['description'] thumbnail_url = item['stills']['still-large'] for i in item['media']: duration = i.get('duration', False) nsfw = item['nsfw'] if not nsfw or shownsfw: # {"id":"6737324_36df9881","title":"Hardcore brei-oma","thumbnail":"http:\/\/media.dumpert.nl\/sq_thumbs\/6737324_36df9881.jpg", # "still":"http:\/\/media.dumpert.nl\/stills\/6737324_36df9881.jpg","description":"Heeft vroeger wat uitgevroten... WTF?","date":"2016-03-18T19:35:56+01:00", # "tags":"dwdd oma wtf breien oud","nsfw":false,"nopreroll":false,"stats":{"views_total":466917,"views_today":32706,"kudos_total":4916,"kudos_today":343}, # "stills":{"thumb":"http:\/\/media.dumpert.nl\/sq_thumbs\/6737324_36df9881.jpg","thumb-medium":"http:\/\/media.dumpert.nl\/sq_thumbs\/medium\/6737324_36df9881.jpg", # "still":"http:\/\/media.dumpert.nl\/stills\/6737324_36df9881.jpg","still-medium":"http:\/\/media.dumpert.nl\/stills\/medium\/6737324_36df9881.jpg", # "still-large":"http:\/\/media.dumpert.nl\/stills\/large\/6737324_36df9881.jpg"},"media":[{"description":"","mediatype":"VIDEO","duration":55, # "variants":[{"version":"tablet","uri":"http:\/\/media.dumpert.nl\/tablet\/36df9881_VID_20160318_WA0000.mp4.mp4.mp4"},{"version":"mobile", # "uri":"http:\/\/media.dumpert.nl\/mobile\/36df9881_VID_20160318_WA0000.mp4.mp4.mp4"}]}]} # # grab first item (tablet) # skip embedded (youtube links) for now {"version":"embed","uri":"youtube:wOeZB7bnoxw"} if item['media'][0]['mediatype'] == 'VIDEO' and item['media'][ 0]['variants'][0]['version'] != 'embed': file = item['media'][0]['variants'][0]['uri'] log("json file", file) list_item = xbmcgui.ListItem(label=title, thumbnailImage=thumbnail_url) list_item.setInfo( "video", { "title": title, "studio": "Dumpert", "mediatype": "video", "plot": description }) list_item.setArt({ 'thumb': thumbnail_url, 'icon': thumbnail_url, 'fanart': os.path.join(IMAGES_PATH, 'fanart-blur.jpg') }) list_item.setProperty('IsPlayable', 'true') parameters = {"action": "play-file", "file": file} url = self.plugin_url + '?' + urllib.parse.urlencode( parameters) is_folder = False # Add refresh option to context menu list_item.addContextMenuItems([('Refresh', 'Container.Refresh')]) # Add our item to the listing as a 3-element tuple. listing.append((url, list_item, is_folder)) # Next page entry if self.next_page_possible == 'True': next_page = self.current_page + 1 list_item = xbmcgui.ListItem(LANGUAGE(30503), thumbnailImage=os.path.join( IMAGES_PATH, 'next-page.png')) list_item.setArt( {'fanart': os.path.join(IMAGES_PATH, 'fanart-blur.jpg')}) list_item.setProperty('IsPlayable', 'false') parameters = { "action": "json", "plugin_category": self.plugin_category, "url": str(self.base_url) + str(next_page) + '/', "next_page_possible": self.next_page_possible } url = self.plugin_url + '?' + urllib.parse.urlencode(parameters) is_folder = True # Add refresh option to context menu list_item.addContextMenuItems([('Refresh', 'Container.Refresh')]) # Add our item to the listing as a 3-element tuple. listing.append((url, list_item, is_folder)) # Add our listing to Kodi. # Large lists and/or slower systems benefit from adding all items at once via addDirectoryItems # instead of adding one by one via addDirectoryItem. xbmcplugin.addDirectoryItems(self.plugin_handle, listing, len(listing)) # Disable sorting xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE) # Finish creating a virtual folder. xbmcplugin.endOfDirectory(self.plugin_handle)
def run(): url = urllib.parse.urlparse(sys.argv[0]) path = url.path handle = int(sys.argv[1]) args = urllib.parse.parse_qs(sys.argv[2][1:]) xbmcplugin.setContent(handle, "songs") if path == PATH_ROOT: action = args.get("action", None) if action is None: items = listItems.root() xbmcplugin.addDirectoryItems(handle, items, len(items)) xbmcplugin.endOfDirectory(handle) elif "call" in action: collection = listItems.from_collection( api.call(args.get("call")[0])) xbmcplugin.addDirectoryItems(handle, collection, len(collection)) xbmcplugin.endOfDirectory(handle) elif "settings" in action: addon.openSettings() else: xbmc.log("Invalid root action", xbmc.LOGERROR) elif path == PATH_CHARTS: action = args.get("action", [None])[0] genre = args.get("genre", ["soundcloud:genres:all-music"])[0] if action is None: items = listItems.charts() xbmcplugin.addDirectoryItems(handle, items, len(items)) xbmcplugin.endOfDirectory(handle) else: api_result = api.charts({ "kind": action, "genre": genre, "limit": 50 }) collection = listItems.from_collection(api_result) xbmcplugin.addDirectoryItems(handle, collection, len(collection)) xbmcplugin.endOfDirectory(handle) elif path == PATH_DISCOVER: selection = args.get("selection", [None])[0] collection = listItems.from_collection(api.discover(selection)) xbmcplugin.addDirectoryItems(handle, collection, len(collection)) xbmcplugin.endOfDirectory(handle) elif path == PATH_PLAY: # Public params track_id = args.get("track_id", [None])[0] playlist_id = args.get("playlist_id", [None])[0] url = args.get("url", [None])[0] # Public legacy params (@deprecated) audio_id_legacy = args.get("audio_id", [None])[0] track_id = audio_id_legacy if audio_id_legacy else track_id # Private params media_url = args.get("media_url", [None])[0] if media_url: resolved_url = api.resolve_media_url(media_url) item = xbmcgui.ListItem(path=resolved_url) xbmcplugin.setResolvedUrl(handle, succeeded=True, listitem=item) elif track_id: collection = listItems.from_collection(api.resolve_id(track_id)) playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC) resolve_list_item(handle, collection[0][1]) playlist.add(url=collection[0][0], listitem=collection[0][1]) elif playlist_id: call = "/playlists/{id}".format(id=playlist_id) collection = listItems.from_collection(api.call(call)) playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC) for item in collection: resolve_list_item(handle, item[1]) playlist.add(url=item[0], listitem=item[1]) elif url: collection = listItems.from_collection(api.resolve_url(url)) playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC) for item in collection: resolve_list_item(handle, item[1]) playlist.add(url=item[0], listitem=item[1]) else: xbmc.log("Invalid play param", xbmc.LOGERROR) elif path == PATH_SEARCH: action = args.get("action", None) query = args.get("query", [""])[0] if query: if action is None: search(handle, query) elif "people" in action: xbmcplugin.setContent(handle, "artists") collection = listItems.from_collection( api.search(query, "users")) xbmcplugin.addDirectoryItems(handle, collection, len(collection)) xbmcplugin.endOfDirectory(handle) elif "albums" in action: xbmcplugin.setContent(handle, "albums") collection = listItems.from_collection( api.search(query, "albums")) xbmcplugin.addDirectoryItems(handle, collection, len(collection)) xbmcplugin.endOfDirectory(handle) elif "playlists" in action: xbmcplugin.setContent(handle, "albums") collection = listItems.from_collection( api.search(query, "playlists_without_albums")) xbmcplugin.addDirectoryItems(handle, collection, len(collection)) xbmcplugin.endOfDirectory(handle) else: xbmc.log("Invalid search action", xbmc.LOGERROR) else: if action is None: items = listItems.search() xbmcplugin.addDirectoryItems(handle, items, len(items)) xbmcplugin.endOfDirectory(handle) elif "new" in action: query = xbmcgui.Dialog().input(addon.getLocalizedString(30101)) search_history.add(query) search(handle, query) else: xbmc.log("Invalid search action", xbmc.LOGERROR) # Legacy search query used by Chorus2 (@deprecated) elif path == PATH_SEARCH_LEGACY: query = args.get("q", [""])[0] collection = listItems.from_collection(api.search(query)) xbmcplugin.addDirectoryItems(handle, collection, len(collection)) xbmcplugin.endOfDirectory(handle) elif path == PATH_USER: user_id = args.get("id")[0] default_action = args.get("call")[0] if user_id: items = listItems.user(user_id) collection = listItems.from_collection(api.call(default_action)) xbmcplugin.addDirectoryItems(handle, items, len(items)) xbmcplugin.addDirectoryItems(handle, collection, len(collection)) xbmcplugin.endOfDirectory(handle) else: xbmc.log("Invalid user action", xbmc.LOGERROR) elif path == PATH_SETTINGS_CACHE_CLEAR: vfs_cache.destroy() dialog = xbmcgui.Dialog() dialog.ok("SoundCloud", addon.getLocalizedString(30501)) else: xbmc.log("Path not found", xbmc.LOGERROR)
def actionLatestMoviesMenu(params): # Returns a list of links from a hidden "/anime/movies" area. # Since this page is very large (130 KB), we memory cache it after it's been requested. html = getRawWindowProperty(PROPERTY_LATEST_MOVIES) if not html: r = requestHelper( BASEURL + params['path']) # Path unused, data is already on the homepage. html = r.text setRawWindowProperty(PROPERTY_LATEST_MOVIES, html) dataStartIndex = html.find('catlist-listview') if dataStartIndex == -1: raise Exception('Latest movies scrape fail') # Persistent property with item metadata. infoItems = getWindowProperty(PROPERTY_INFO_ITEMS) or {} def _movieItemsGen(): artDict = { 'icon': ADDON_ICON, 'thumb': ADDON_ICON, 'poster': ADDON_ICON } reIter = re.finditer('''<a.*?href="(.*?)".*?>(.*?)</''', html[dataStartIndex:html.find('CAT List FINISH')], re.DOTALL) # The page has like 6000 items going back to 2010, so we limit to only the latest 200. for x in range(200): entryURL, entryTitle = next(reIter).groups() if entryURL in infoItems: entryPlot, entryThumb = infoItems[entryURL] yield (buildURL({ 'action': 'actionResolve', 'url': entryURL }), makeListItem(entryTitle, entryURL, { 'icon': ADDON_ICON, 'thumb': entryThumb, 'poster': entryThumb }, entryPlot, isFolder=False, isSpecial=True, oldParams=None), False) else: yield (buildURL({ 'action': 'actionResolve', 'url': entryURL }), makeListItem(entryTitle, entryURL, artDict, '', isFolder=False, isSpecial=True, oldParams=params), False) xbmcplugin.addDirectoryItems(PLUGIN_ID, tuple(_movieItemsGen())) xbmcplugin.endOfDirectory(PLUGIN_ID)
listing = [] for item in d['entries']: title = item['title'] url = item.enclosures[0].href #Beschreibung der Folge auslesen, für Audio nicht notwendig, aber für Audio praktisch summary = item['description'] #Einige Folgen haben kein Thumbnailbild, die bekommen ein Standard-Bild verpasst try: thumb = item['image'].href except: thumb = "https://heise.cloudimg.io/bound/480x270/q75.png-lossy-75.webp-lossy-75.foil1/_www-heise-de_/ct/imgs/04/1/4/2/6/3/2/5/9cc02d4fe2a3a731.jpeg" #Baue fürs GUI ein Listenelement list_item = xbmcgui.ListItem(label=title, thumbnailImage=thumb) #Fanart des Plug-ins als Hintergrundbild nutzen ctuplink_plugin = xbmcaddon.Addon('plugin.video.ctuplinkrss') list_item.setArt({'fanart': ctuplink_plugin.getAddonInfo('fanart')}) list_item.setProperty('IsPlayable', 'true') listing.append((url, list_item, False)) #In diesem Beispiel fügen wir alle Items in einem der Liste hinzu xbmcplugin.addDirectoryItems(addon_handle, listing, len(listing)) #Schließe die Liste ab xbmcplugin.endOfDirectory(addon_handle, succeeded=True)
def actionCatalogSection(params): catalog = getCatalogProperty(params) path = params['path'] isSpecial = path in { URL_PATHS['ova'], URL_PATHS['movies'], URL_PATHS['latest'] } and path != URL_PATHS['popular'] searchType = params.get('searchType', None) if searchType == 'series' or not isSpecial: action = 'actionEpisodesMenu' isFolder = True else: # Special case for the OVA, movie and episode-search catalogs, they link to the video player pages already. action = 'actionResolve' isFolder = False thumb = params.get('thumb', ADDON_ICON) artDict = { 'icon': thumb, 'thumb': thumb, 'poster': thumb } if thumb else None # Persistent property with item metadata. infoItems = getWindowProperty(PROPERTY_INFO_ITEMS) or {} if ADDON.getSetting( 'cleanupEpisodes') == 'true' and searchType != 'episodes': listItemFunc = makeListItemClean else: listItemFunc = makeListItem if params['section'] == 'ALL': sectionItems = chain.from_iterable(catalog[sectionName] for sectionName in sorted(catalog)) else: sectionItems = catalog[params['section']] def _sectionItemsGen(): for entry in sectionItems: entryURL = entry[0] # Decorate the items that the user requested info on. if entryURL in infoItems: itemPlot, itemThumb = infoItems[entryURL] yield (buildURL({ 'action': action, 'url': entryURL }), listItemFunc( entry[1], entryURL, { 'icon': ADDON_ICON, 'thumb': itemThumb, 'poster': itemThumb }, itemPlot, isFolder, isSpecial, None), isFolder) else: yield (buildURL({ 'action': action, 'url': entryURL }), listItemFunc(entry[1], entryURL, artDict, '', isFolder, isSpecial, params), isFolder) xbmcplugin.addDirectoryItems(PLUGIN_ID, tuple(_sectionItemsGen())) xbmcplugin.endOfDirectory(PLUGIN_ID) #, updateListing=updateListing)
def return_youtubevideos(name, url, token, page): items_per_page = int(selfAddon.getSetting('items_per_page')) list_of_tupple_items = [] if page != 1: url_api = 'https://www.googleapis.com/youtube/v3/playlistItems?part=id,snippet,contentDetails&maxResults=' + str( items_per_page ) + '&playlistId=' + url + '&key=' + youtube_api_key + '&pageToken=' + token else: url_api = 'https://www.googleapis.com/youtube/v3/playlistItems?part=id,snippet,contentDetails&maxResults=' + str( items_per_page) + '&playlistId=' + url + '&key=' + youtube_api_key raw = urllib.urlopen(url_api) resp = json.load(raw) raw.close() try: nextpagetoken = resp["nextPageToken"] except: nextpagetoken = '' try: availablevideos = resp["pageInfo"]["totalResults"] except: availablevideos = 1 returnedVideos = resp["items"] totalvideos = len(returnedVideos) totalpages = int(math.ceil((float(availablevideos) / items_per_page))) video_ids = [] if returnedVideos: for video in returnedVideos: videoid = video["contentDetails"]["videoId"] video_ids.append(videoid) video_ids = ','.join(video_ids) url_api = 'https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id=' + video_ids + '&key=' + youtube_api_key raw = urllib.urlopen(url_api) resp = json.load(raw) raw.close() returnedVideos = resp["items"] for video in returnedVideos: title = video["snippet"]["title"] plot = video["snippet"]["description"] aired = video["snippet"]["publishedAt"] thumb = video["snippet"]["thumbnails"]["high"]["url"] videoid = video["id"] #process duration duration_string = video["contentDetails"]["duration"] try: duration = return_duration_as_seconds(duration_string) except: duration = '0' try: aired = re.compile('(.+?)-(.+?)-(.+?)T').findall(aired)[0] date = aired[2] + '.' + aired[1] + '.' + aired[0] aired = aired[0] + '-' + aired[1] + '-' + aired[2] except: aired = '' date = '' try: if episode_playlists: if url in episode_playlists: episode = re.compile('(\d+)').findall(title)[0] else: episode = '' else: episode = '' except: episode = '' #playcount if os.path.exists( os.path.join(watchedfolder, str(videoid) + '.txt')): playcount = 1 else: playcount = 0 infolabels = { 'plot': plot.encode('utf-8'), 'aired': aired, 'date': date, 'tvshowtitle': tvshowtitle, 'title': title.encode('utf-8'), 'originaltitle': title.encode('utf-8'), 'status': status, 'cast': cast, 'duration': duration, 'episode': episode, 'playcount': playcount } #Video and audio info video_info = {'codec': 'avc1', 'aspect': 1.78} audio_info = {'codec': 'aac', 'language': 'en'} try: if video["contentDetails"]["definition"].lower() == 'hd': video_info['width'] = 1280 video_info['height'] = 720 audio_info['channels'] = 2 else: video_info['width'] = 854 video_info['height'] = 480 audio_info['channels'] = 1 try: if xbmcaddon.Addon(id='plugin.video.youtube').getSetting( 'kodion.video.quality.ask' ) == 'false' and xbmcaddon.Addon( id='plugin.video.youtube').getSetting( 'kodion.video.quality' ) != '3' and xbmcaddon.Addon( id='plugin.video.youtube').getSetting( 'kodion.video.quality') != '4': video_info['width'] = 854 video_info['height'] = 480 audio_info['channels'] = 1 except: pass except: video_info['width'] = 854 video_info['height'] = 480 audio_info['channels'] = 1 #build and append item tupple = build_episode_item(title.encode('utf-8'), videoid, 5, thumb, page, infolabels, video_info, audio_info) list_of_tupple_items.append(tupple) if list_of_tupple_items: number_of_items = len(list_of_tupple_items) xbmcplugin.addDirectoryItems(int(sys.argv[1]), list_of_tupple_items, totalItems=number_of_items) add_sort_methods() if totalpages > 1 and (page + 1) <= totalpages: addDir('[B]' + translate(30010) + '[/B] ' + str(page) + '/' + str(totalpages), url, 1, os.path.join(artfolder, 'next.png'), page + 1, 1, token=nextpagetoken) xbmcplugin.setContent(int(sys.argv[1]), 'episodes') return
def search(handle, query): search_options = listItems.search_sub(query) collection = listItems.from_collection(api.search(query)) xbmcplugin.addDirectoryItems(handle, search_options, len(collection)) xbmcplugin.addDirectoryItems(handle, collection, len(collection)) xbmcplugin.endOfDirectory(handle)
def route(params): if params: if params['action'] == 'alpha': create_alpha_listing(params) if params['action'] == 'mixtapes': create_mixtape_listings(params) if params['action'] == 'tracks': create_track_listings(params) if params['action'] == 'search': search(params) if params['action'] == 'play': play_track(params) else: listings = [] home = [{ 'title': _language(30001), 'url': build_url({ 'action': 'alpha', 'type': 'artist', 'category': _language(30001) }) }, { 'title': _language(30002), 'url': build_url({ 'action': 'alpha', 'type': 'title', 'category': _language(30002) }) }, { 'title': _language(30003), 'url': build_url({ 'action': 'mixtapes', 'url': _most_listens_url, 'category': _language(30003) }) }, { 'title': _language(30004), 'url': build_url({ 'action': 'mixtapes', 'url': _most_downloads_url, 'category': _language(30004) }) }, { 'title': _language(30005), 'url': build_url({ 'action': 'mixtapes', 'url': _most_favorited_url, 'category': _language(30005) }) }, { 'title': _language(30006), 'url': build_url({ 'action': 'mixtapes', 'url': _highest_rating_url, 'category': _language(30006) }) }, { 'title': _language(30007), 'url': build_url({ 'action': 'mixtapes', 'url': _hot_this_week_url, 'category': _language(30007) }) }, { 'title': _language(30008), 'url': build_url({ 'action': 'mixtapes', 'url': _newest_url, 'category': _language(30008) }) }, { 'title': _language(30009), 'url': build_url({ 'action': 'mixtapes', 'url': '{0}2xplatinum/'.format(_celebrated_url), 'category': _language(30009) }) }, { 'title': _language(30010), 'url': build_url({ 'action': 'mixtapes', 'url': '{0}platinum/'.format(_celebrated_url), 'category': _language(30010) }) }, { 'title': _language(30011), 'url': build_url({ 'action': 'mixtapes', 'url': '{0}gold/'.format(_celebrated_url), 'category': _language(30011) }) }, { 'title': _language(30012), 'url': build_url({ 'action': 'mixtapes', 'url': '{0}sliver/'.format(_celebrated_url), 'category': _language(30012) }) }, { 'title': _language(30013), 'url': build_url({ 'action': 'mixtapes', 'url': '{0}bronze/'.format(_celebrated_url), 'category': _language(30013) }) }, { 'title': _language(30014), 'url': build_url({'action': 'search'}) }] for item in home: li = xbmcgui.ListItem(label=item['title']) li.setArt({ 'thumb': _default_icon, 'icon': _default_icon, 'fanart': _default_fanart }) li.setInfo('music', {'title': item['title']}) listings.append((item['url'], li, True)) xbmcplugin.addDirectoryItems(_handle, listings, len(listings)) xbmcplugin.endOfDirectory(_handle)
def addEntries(l): lists = [] doneList = [] for d in l: if str(d) in doneList: #primitive methode to filter duplicated entries continue doneList.append(str(d)) if '_overridepath' in d: u = d['_overridepath'] else: u = _buildUri(d) newd = {} for key in d: if key.startswith('_'): if isinstance(d[key], unicode): d[key] = d[key].encode('utf-8', 'ignore') newd[key[1:]] = d[key] elif isinstance(d[key], unicode): newd[key] = d[key].encode('utf-8', 'ignore') else: newd[key] = d[key] d = newd if 'type' in d and d['type'] == 'nextPage': d['name'] = translation(31040) if not 'mode' in d: d['mode'] = get_params()['mode'] if isinstance(d["name"], unicode): d["name"] = d["name"].encode('utf-8') d["name"] = clearString(d["name"]) if 'airedISO8601' in d or 'airedISO8601A' in d: d['aired'], d['airedtime'] = _airedISO8601(d) if 'type' in d and d['type'] == 'date' and 'airedtime' in d: d["name"] = '(' + str(d["airedtime"]) + ') ' + d["name"] elif 'type' in d and d['type'] == 'date' and 'time' in d: d["name"] = '(' + str(d["date"]) + ') ' + d["name"] ilabels = { "Title": clearString(d.get('name', '')), "Plot": clearString(d.get('plot', '')), "Plotoutline": clearString(d.get('plot', '')), "Duration": d.get('duration', ''), "Mpaa": d.get('mpaa', ''), "Aired": d.get('aired', ''), "Studio": d.get('channel', ''), } if 'epoch' in d: ilabels['aired'] = time.strftime("%Y-%m-%d", time.gmtime(float(d['epoch']))) if 'episode' in d: ilabels['Episode'] = d['episode'] if 'Season' in d: ilabels['Season'] = d['season'] if 'tvshowtitle' in d: ilabels['tvshowtitle'] = d['tvshowtitle'] ilabels['tagline'] = d['tvshowtitle'] ilabels['album'] = d['tvshowtitle'] if 'rating' in d: ilabels['rating'] = d['rating'] if 'type' in d and d['type'] != 'nextPage': if d['type'] == 'video' or d['type'] == 'live' or d[ 'type'] == 'date' or d['type'] == 'clip': ilabels['mediatype'] = 'video' elif d['type'] == 'shows' or d['type'] == 'season': ilabels['mediatype'] = 'season' elif d['type'] == 'episode': ilabels['mediatype'] = 'episode' else: ilabels['mediatype'] = 'video' ok = True liz = xbmcgui.ListItem(clearString(d.get('name', ''))) if d['type'] == 'audio': liz.setInfo(type="music", infoLabels=ilabels) else: liz.setInfo(type="Video", infoLabels=ilabels) liz.addStreamInfo('subtitle', {'language': 'deu'}) art = {} art['thumb'] = d.get('thumb') art['landscape'] = d.get('thumb') art['poster'] = d.get('thumb') art['fanart'] = d.get('fanart', d.get('thumb', fanart)) art['icon'] = d.get('channelLogo', '') liz.setArt(art) if 'customprops' in d: for prop in d['customprops']: liz.setProperty(prop, d['customprops'][prop]) if d.get('type', None) == 'video' or d.get('type', None) == 'live' or d.get( 'type', None) == 'date' or d.get('type', None) == 'clip' or d.get( 'type', None) == 'episode' or d.get('type', None) == 'audio': #xbmcplugin.setContent( handle=int( sys.argv[ 1 ] ), content="episodes" ) liz.setProperty('IsPlayable', 'true') lists.append([u, liz, False]) else: lists.append([u, liz, True]) if len(l) > 0: type = l[0]['_type'] if type == 'video' or type == 'live' or type == 'date' or type == 'clip' or type == 'episode': xbmcplugin.setContent(handle=int(sys.argv[1]), content="episodes") elif type == 'shows' or type == 'season': xbmcplugin.setContent(handle=int(sys.argv[1]), content="tvshows") else: xbmcplugin.setContent(handle=int(sys.argv[1]), content="files") xbmcplugin.addDirectoryItems(int(sys.argv[1]), lists)
def execute(self): if self.category: Logger.info("Plugin::show_channel_list for %s", self.category) else: Logger.info("Plugin::show_channel_list") try: # only display channels channel_register = ChannelIndex.get_register() channels = channel_register.get_channels() xbmc_items = [] # Should we show the "All Favourites"? if AddonSettings.show_show_favourites_in_channel_list(): icon = Config.icon fanart = Config.fanart name = LanguageHelper.get_localized_string(LanguageHelper.AllFavouritesId) description = LanguageHelper.get_localized_string(LanguageHelper.AllFavouritesDescriptionId) kodi_item = xbmcgui.ListItem(name, name) kodi_item.setInfo("video", {"Plot": description}) # set art try: kodi_item.setIconImage(icon) except: # it was deprecated pass kodi_item.setArt({'thumb': icon, 'icon': icon}) kodi_item.setProperty(self._propertyRetrospect, "true") kodi_item.setProperty(self._propertyRetrospectCategory, "true") if not AddonSettings.hide_fanart(): kodi_item.setArt({'fanart': fanart}) url = self.parameter_parser.create_action_url( None, action=action.ALL_FAVOURITES) xbmc_items.append((url, kodi_item, True)) for channel in channels: if self.category and channel.category != self.category: Logger.debug("Skipping %s (%s) due to category filter", channel.channelName, channel.category) continue # Get the Kodi item item = channel.get_kodi_item() item.setProperty(self._propertyRetrospect, "true") item.setProperty(self._propertyRetrospectChannel, "true") if channel.settings: item.setProperty(self._propertyRetrospectChannelSetting, "true") if channel.adaptiveAddonSelectable: item.setProperty(self._propertyRetrospectAdaptive, "true") # Get the context menu items context_menu_items = self._get_context_menu_items(channel) item.addContextMenuItems(context_menu_items) # Get the URL for the item url = self.parameter_parser.create_action_url( channel, action=action.LIST_FOLDER) # Append to the list of Kodi Items xbmc_items.append((url, item, True)) # Add the items ok = xbmcplugin.addDirectoryItems(self.handle, xbmc_items, len(xbmc_items)) # Just let Kodi display the order we give. xbmcplugin.addSortMethod(handle=self.handle, sortMethod=xbmcplugin.SORT_METHOD_UNSORTED) xbmcplugin.addSortMethod(handle=self.handle, sortMethod=xbmcplugin.SORT_METHOD_TITLE) xbmcplugin.addSortMethod(handle=self.handle, sortMethod=xbmcplugin.SORT_METHOD_GENRE) xbmcplugin.setContent(handle=self.handle, content="tvshows") xbmcplugin.endOfDirectory(self.handle, ok) except: xbmcplugin.endOfDirectory(self.handle, False) Logger.critical("Error fetching channels for plugin", exc_info=True)
def render(self, list_items): # as_type=None causes all items to show their icons with DirectoryRenderer.start_directory(self.handle, as_type=self.get_collection()): xbmcplugin.addDirectoryItems(self.handle, list_items)
def getVideos(self): # # Init # current_page = 1 # Create a list for our items. listing = [] # # Get HTML page # response = requests.get(self.video_list_page_url) html_source = response.text html_source = convertToUnicodeString(html_source) # log("html_source", html_source) # Parse response soup = getSoup(html_source) #<div class="col-xs-6 col-sm-4 col-md-3 col-lg-5ths"><div class="kr_blok_main" style="height: 320px;"><h3 class="kr_blok_title"><a class="iframe2_Removethis" href="https://www.uitzendinggemist.net/aflevering/500774/The_Voice_Of_Holland.html" title="Afl. 9">Afl. 9</a></h3><div class="kr_blok_thumb"><a class="iframe_Removethis" href="https://www.uitzendinggemist.net/aflevering/500774/The_Voice_Of_Holland.html" title="The Voice Of Holland - Afl. 9"><img src="https://screenshots.rtl.nl/system/thumb/sz=355x200/uuid=0bf9b7ee-8cd7-3a2a-ad2f-dd1b5ed079bb" alt="The Voice Of Holland - Afl. 9" width="180" height="102"></a></div><p class="kr_blok_desc">Spectaculaire muzikale zoektocht van coaches Ali B, Waylon, Anouk en Lil Kleine naar de beste nieuwe zangstem van Nederland. Presentatie: Martijn Krabbé en Chantal Janzen. </p><p class="kr_blok_date">03-01-2020</p><p class="kr_blok_host">RTL4</p><p class="kr_blok_more"><a href="https://www.uitzendinggemist.net/programmas/3902-The_Voice_Of_Holland.html" title="The Voice Of Holland Gemist">Alle afleveringen bekijken</a></p><p class="icon"><a href="https://www.uitzendinggemist.net/zenders/RTL-4.html" title="RTL 4"><img src="https://www.uitzendinggemist.net/images/rtl-4-xs.png" alt="RTL 4" width="20" height="18" border="0"></a></p></div></div> tv_shows = soup.findAll( 'div', attrs={'class': re.compile("^" + "kr_blok_main")}) log("len(tv_shows)", len(tv_shows)) for tv_show in tv_shows: tv_show = convertToUnicodeString(tv_show) log("tv_show", tv_show) video_page_url = tv_show.a['href'] log("video_page_url", video_page_url) #<div class="kr_blok_main" style="height: 320px;"><h3 class="kr_blok_title"><a href="https://www.uitzendinggemist.net/aflevering/500734/Ik_Vertrek.html" title="Ik Vertrek">Ik Vertrek</a></h3><div class="kr_blok_thumb"><a href="https://www.uitzendinggemist.net/aflevering/500734/Ik_Vertrek.html" title="Ik Vertrek - Milko En Mario In Portugal"><img src="https://images.poms.omroep.nl/image/s320/c320x180/1316596.jpg" alt="Ik Vertrek - Milko En Mario In Portugal" width="180" height="102"></a></div><p class="kr_blok_subtitle">Milko En Mario In Portugal</p><p class="kr_blok_desc">Mario (47) en Milko (54) wonen in een prachtig appartement in Amsterdam Oud-Zuid. De supermarkt is om de hoek, musea zijn op loopafstand en er is altijd leven op straat. Het ste ... </p><p class="kr_blok_date">03-01-2020</p><p class="kr_blok_host">TROS</p><p class="kr_blok_more"><a href="https://www.uitzendinggemist.net/programmas/328-Ik_Vertrek.html" title="Ik Vertrek Gemist">Alle afleveringen bekijken</a></p><p class="icon"><a href="https://www.uitzendinggemist.net/zenders/Nederland-2.html" title="Nederland 2"><img src="https://www.uitzendinggemist.net/images/nederland-2-xs.png" alt="Nederland 2" width="20" height="18" border="0"></a></p></div> #<div class="kr_blok_main" style="height: 270px;"><h3 class="kr_blok_title">Chateau Meiland </h3><div class="kr_blok_thumb"><a href="https://www.uitzendinggemist.net/programmas/59250-Chateau_Meiland.html"><img alt="Chateau Meiland " height="102" src="https://img.kijk.nl/media/cache/computer_retina_series_program_header/imgsrc06/images/redactioneel/1085720-LS---20190520112813--0e03ad5aaa47df615ea8e4d6f1204dbd.jpg" width="180"/></a></div><div class="kr_blok_desc">Martien en Erica gaan opnieuw het huwelijksbootje in</div><p class="icon"><a href="https://www.uitzendinggemist.net/zenders/SBS-6.html" title="SBS 6"><img alt="SBS 6" border="0" height="18" src="https://www.uitzendinggemist.net/images/sbs-6-xs.png" width="20"/></a></p></div> try: title_part1 = tv_show.a['title'] log("tp1", title_part1) title_part2 = tv_show.img['alt'] log("tp2", title_part2) title_part2 = convertToUnicodeString(title_part2) title_part2 = title_part2.replace(title_part1, '', 1) title_part2 = title_part2.replace(" -", "") title = title_part1 + ": " + title_part2 except: try: title = tv_show.select('h3')[0].get_text(strip=True) except: title = "" if self.show_channel == "True": channel = tv_show.select('img')[1]["alt"] log("channel", channel) channel = str(channel).replace("Nederland", "NL ") title = channel + ": " + title log("title", title) try: # Get the text of the second p-tag plot = tv_show.select('p')[1].get_text(strip=True) except: try: plot = tv_show.select('div')[1].get_text(strip=True) except: plot = "" log("plot", plot) thumbnail_url = tv_show.img['src'] log("thumbnail_url", thumbnail_url) log("title", title) context_menu_items = [] # Add refresh option to context menu context_menu_items.append((LANGUAGE(30667), 'Container.Refresh')) # Add to list list_item = xbmcgui.ListItem(label=title) list_item.setInfo("video", {"title": title, "studio": ADDON}) list_item.setArt({ 'thumb': thumbnail_url, 'icon': thumbnail_url, 'fanart': os.path.join(IMAGES_PATH, 'fanart-blur.jpg') }) list_item.setProperty('IsPlayable', 'true') # let's remove any non-ascii characters title = title.encode('ascii', 'ignore') parameters = { "action": "list-episodes", "plugin_category": title, "url": video_page_url, "next_page_possible": "False", "show_channel": self.show_channel, "title": title } url = self.plugin_url + '?' + urllib.parse.urlencode(parameters) is_folder = True # Add refresh option to context menu list_item.addContextMenuItems([('Refresh', 'Container.Refresh')]) # Add our item to the listing as a 3-element tuple. listing.append((url, list_item, is_folder)) # # Next page entry # if self.next_page_possible == 'True': # next_page = self.current_page + 1 # thumbnail_url = os.path.join(IMAGES_PATH, 'next-page.png') # list_item = xbmcgui.ListItem(LANGUAGE(30503)) # list_item.setArt({'thumb': thumbnail_url, 'icon': thumbnail_url, # 'fanart': os.path.join(IMAGES_PATH, 'fanart-blur.jpg')}) # list_item.setProperty('IsPlayable', 'false') # parameters = {"action": "list", "plugin_category": self.plugin_category, "url": str(self.next_url), # "next_page_possible": self.next_page_possible} # url = self.plugin_url + '?' + urllib.parse.urlencode(parameters) # is_folder = True # # Add refresh option to context menu # list_item.addContextMenuItems([('Refresh', 'Container.Refresh')]) # # Add our item to the listing as a 3-element tuple. # listing.append((url, list_item, is_folder)) # Add our listing to Kodi # Large lists and/or slower systems benefit from adding all items at once via addDirectoryItems # instead of adding one by ove via addDirectoryItem. xbmcplugin.addDirectoryItems(self.plugin_handle, listing, len(listing)) # Disable sorting xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE) # Finish creating a virtual folder. xbmcplugin.endOfDirectory(self.plugin_handle)
def addEntries(self, d): lists = [] #print(json.dumps(d)) for item in d['items']: u = self._buildUri(item['params']) #print('Pluginpath') #print(self._buildUri(item['params'])) #print('Item') #print(json.dumps(item, indent=4, sort_keys=True)) """if 'type' in items anitems d['type'] == 'date' and 'airedtime' in items: items["name"] = '(' + str(items["airedtime"]) + ') ' + items["name"] elif 'type' in items and items['type'] == 'date' and 'time' in items: items["name"] = '(' + str(items["date"]) + ') ' + items["name"] """ metadata = item['metadata'] liz = xbmcgui.ListItem(metadata.get('name', '')) ilabels = { "Title": metadata.get('name', ''), "Plot": metadata.get('plot', metadata.get('plotoutline', '')), "Plotoutline": metadata.get('plotoutline', ''), "Duration": str(metadata.get('duration', '')), "Mpaa": metadata.get('mpaa', ''), "Aired": metadata.get('aired', ''), "Studio": metadata.get('channel', ''), #"episode": metadata.get('episode',None), #"season": metadata.get('season',''), "tvshowtitle": metadata.get('tvshowtitle', ''), "rating": metadata.get('rating', ''), "director": metadata.get('directors', ''), "artist": metadata.get('artists', []), "writer": metadata.get('writers', ''), "credits": metadata.get('credits', ''), "genre": metadata.get('genres', ''), "year": metadata.get('year', ''), "premiered": metadata.get('premiered', ''), "premiered": metadata.get('originaltitle', ''), } if 'art' in metadata: liz.setArt(metadata['art']) if 'episode' in metadata: liz.setArt(metadata['episode']) if 'season' in metadata: liz.setArt(metadata['season']) if 'subtitles' in metadata: #TODO liz.addStreamInfo('subtitle', {'language': 'deu'}) if 'actors' in metadata: liz.setCast(metadata['actors']) if 'type' in item: if item['type'] in ['video', 'live', 'date', 'clip']: ilabels['mediatype'] = 'video' elif item['type'] in ['tvshow']: ilabels['mediatype'] = 'tvshow' elif item['type'] in ['shows', 'season']: ilabels['mediatype'] = 'season' elif item['type'] in ['episode']: ilabels['mediatype'] = 'episode' elif item['type'] in ['movie']: ilabels['mediatype'] = 'movie' elif item['type'] in ['sport']: ilabels['mediatype'] = 'sport' else: ilabels['mediatype'] = 'video' ok = True if item['type'] in ['audio', 'songs']: liz.setInfo(type="music", infoLabels=ilabels) else: liz.setInfo(type="Video", infoLabels=ilabels) """ art = {} art['thumb'] = d.get('thumb') art['landscape'] = d.get('thumb') art['poster'] = d.get('thumb') art['fanart'] = d.get('fanart',d.get('thumb',fanart)) art['icon'] = d.get('channelLogo','') liz.setArt(art)""" """ if 'customprops' in d: for prop in d['customprops']: liz.setProperty(prop, d['customprops'][prop]) """ if item.get('type', None) in [ 'video', 'live', 'date', 'clip', 'episode', 'audio', 'sport', 'sports', 'movie', 'song' ]: liz.setProperty('IsPlayable', 'true') lists.append([u, liz, False]) else: lists.append([u, liz, True]) if 'content' in d: xbmcplugin.setContent(handle=int(sys.argv[1]), content=d['content']) else: xbmcplugin.setContent(handle=int(sys.argv[1]), content="files") """ if d['type'] in ['video', 'live', 'date', 'clip', 'episode']: xbmcplugin.setContent(handle=int(sys.argv[1]), content="episodes" ) elif d['type'] in ['shows', 'season']: xbmcplugin.setContent(handle=int(sys.argv[1]), content="tvshows" ) elif d['type'] in ['sport']: xbmcplugin.setContent(handle=int(sys.argv[1]), content="sport" ) elif d['type'] in ['movie']: xbmcplugin.setContent(handle=int(sys.argv[1]), content="movies" ) elif d['type'] in ['songs']: xbmcplugin.setContent(handle=int(sys.argv[1]), content="songs" ) else: xbmcplugin.setContent(handle=int(sys.argv[1]), content="files" ) """ xbmcplugin.addDirectoryItems(int(sys.argv[1]), lists)