def showList(url,name): newShow(url) url=url+'/episodes' req = urllib2.Request(url) req.add_header('User-Agent', HEADER) f=urllib2.urlopen(req) a=f.read() f.close() p=re.compile('<!-- <span class="label">Page: </span> -->(.+?)<!-- <span class="label">Page: </span> -->', re.DOTALL) match=p.findall(a) o=re.compile('<a class="thumbnail" href="(.+?)"><img class="thumbnail" src="(.+?)"') data=o.findall(match[0]) q=re.compile('Episode (.+?)<br /> (.+?)</a></p>') data2=q.findall(match[0]) x=1 y=0 for url, thumb in data: url='http://revision3.com'+url print url name = 'Episode ' + data2[y][0] + ': ' + data2[y][1] name = str(int(x))+'. '+name li=xbmcgui.ListItem(name, iconImage=thumb, thumbnailImage=thumb) li.setInfo( type="Video", infoLabels={ "Title": name } ) u=sys.argv[0]+"?mode=2&name="+urllib.quote_plus(name)+"&url="+urllib.quote_plus(url) xbmcplugin.addDirectoryItem(int(sys.argv[1]),u,li) #uncomment below to limit the amount of eps per show to 25 # if (x == 24): # break x=x+1 y=y+1
def l111111l_SBK_(name,url,mode,iconimage,season): u=sys.argv[0]+l1l111_SBK_ (u"ࠤࡂࡹࡷࡲ࠽ࠣ৽")+urllib.quote_plus(url)+l1l111_SBK_ (u"ࠥࠪࡲࡵࡤࡦࠥ৾")+str(mode)+l1l111_SBK_ (u"ࠦࠫࡴࡡࡧࡀࠦ")+urllib.quote_plus(name)+l1l111_SBK_ (u"ࠧࠬࡳࡦࡣࡶࡳࡳࡃࠢ")+str(season) xbmcplugin.setContent(int(sys.argv[1]), l1l111_SBK_ (u"࠭ࡍࡰࡸࡩࡸ࠭ਁ")) l11lll1l1_SBK_=xbmcgui.ListItem(name, iconImage=l1l111_SBK_ (u"ࠢࡧࡣࡱࡥࡷࡺࡲࡪࠦਂ"), thumbnailImage=iconimage) l11lll1l1_SBK_.setProperty(l1l111_SBK_ (u"ࠨࡨࡤࡲࡦࡸࡴࡠࡰࡥࠧਃ"), __FANART__) xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=l11lll1l1_SBK_,isFolder=True) return True
def getCategoryItems(self, url, page): print "*** Get category items %s" % url page_url = "%s/page/%s/" % (url, str(int(page))) response = common.fetchPage({"link": page_url}) items = 0 if response["status"] == 200: content = common.parseDOM(response["content"], "div", attrs={"id": "page_content"}) movie = common.parseDOM(content, "div", attrs={"class": "movie_teaser clearfix"}) header = common.parseDOM(movie, "h2") links = common.parseDOM(header, "a", ret="href") titles = common.parseDOM(header, "a") poster = common.parseDOM(movie, "li", attrs={"class": "movie_teaser_poster"}) images = common.parseDOM(poster, "img", ret="src") teaser = common.parseDOM(movie, "div", attrs={"class": "teaser_info"}) descs = common.parseDOM(teaser, "div", attrs={"class": "teaser_desc"}) infos = common.parseDOM(teaser, "ul", attrs={"class": "teaser_ads"}) ratings = common.parseDOM(movie, "li", attrs={"class": "current-rating"}) pagenav = common.parseDOM(response["content"], "div", attrs={"id": "pagenav"}) for i, title in enumerate(titles): items += 1 info = common.parseDOM(infos[i], "li") image = images[i] genre = self.encode(', '.join(common.parseDOM(info[2], "a"))) year = info[1].split('</span>')[-1] desc = common.stripTags(self.encode(descs[i])) rating = int(ratings[i])/10 if ratings[i] > 0 else None try: tmp = year.split(' ') year = tmp[0] season = tmp[1]+tmp[2] title = "%s %s %s" % (self.encode(title), self.encode(season), year) except IndexError: title = "%s (%s)" % (self.encode(title), year) uri = sys.argv[0] + '?mode=show&url=%s' % (links[i]) item = xbmcgui.ListItem(title, iconImage=self.icon, thumbnailImage=self.url+image) item.setInfo(type='Video', infoLabels={'title': title, 'genre': genre, 'plot': desc, 'rating': rating}) xbmcplugin.addDirectoryItem(self.handle, uri, item, True) else: self.showErrorMessage("getCategoryItems(): Bad response status%s" % response["status"]) if pagenav and not items < 10: uri = sys.argv[0] + '?mode=%s&url=%s&page=%s' % ("category", url, str(int(page) + 1)) item = xbmcgui.ListItem("Next page >>", thumbnailImage=self.inext) xbmcplugin.addDirectoryItem(self.handle, uri, item, True) xbmc.executebuiltin('Container.SetViewMode(52)') xbmcplugin.endOfDirectory(self.handle, True)
def showListA(url,name): cat=name print url req = urllib2.Request(url) req.add_header('User-Agent', HEADER) f=urllib2.urlopen(req) a=f.read() f.close() p=re.compile('<item>(.+?)<title>(.+?) - ', re.DOTALL) o=re.compile('<enclosure url="(.+?)"') q=re.compile('</media:description>\n (<media:thumbnail url="(.+?)" width="100" height="100" />\n )?<media:player url', re.DOTALL) r=re.compile('<guid isPermaLink="false">(.+?)</guid>') info=re.compile('<content:encoded>\n(.+?)\n </content:encoded>', re.DOTALL).findall(a) print info time=r.findall(a) match=p.findall(a) URLS=o.findall(a) thumbs=q.findall(a) x=0 for title in match: thumb=thumbs[x][1] name = clean(match[x][1]) date=time[x] date=date.rsplit('/', 2) date=date[1] date=date.lstrip('0') title='Episode '+date+' - '+name name = str(int(x+1))+'. '+title url=URLS[x] #thumb=thumbs[x] li=xbmcgui.ListItem(clean(name), iconImage=thumb, thumbnailImage=thumb) li.setInfo( type="Video", infoLabels={ "Title": clean(name), "Director": 'Revision3', "Studio": 'Revision3', "Genre": cat, "Plot": clean(info[x]) } ) u=sys.argv[0]+"?mode=2&name="+urllib.quote_plus(title)+"&url="+urllib.quote_plus(url)+"&plot="+urllib.quote_plus(clean(info[x]))+"&cat="+urllib.quote_plus(cat) xbmcplugin.addDirectoryItem(int(sys.argv[1]),u,li) x=x+1
def addDir(name,url,mode,iconimage,itemcount,isFolder=False): try: if not 'COLOR' in name: splitName=name.partition('(') simplename="" simpleyear="" if len(splitName)>0: simplename=splitName[0] simpleyear=splitName[2].partition(')') if len(simpleyear)>0: simpleyear=simpleyear[0] mg = metahandlers.MetaData() meta = mg.get_meta('movie', name=simplename ,year=simpleyear) u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage) ok=True liz=xbmcgui.ListItem(name, iconImage=meta['cover_url'], thumbnailImage=meta['cover_url']) liz.setInfo( type="Video", infoLabels= meta ) liz.setProperty("IsPlayable","true") contextMenuItems = [] contextMenuItems.append(('Movie Information', 'XBMC.Action(Info)')) liz.addContextMenuItems(contextMenuItems, replaceItems=False) if not meta['backdrop_url'] == '': liz.setProperty('fanart_image', meta['backdrop_url']) else: liz.setProperty('fanart_image', fanart) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=isFolder,totalItems=itemcount) return ok except: u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage) ok=True liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage) liz.setInfo( type="Video", infoLabels={ "Title": name } ) liz.setProperty('fanart_image', fanart) liz.setProperty("IsPlayable","true") ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=isFolder) return ok
def addMenu(url,title): listitem = xbmcgui.ListItem(decode(title), iconImage='', thumbnailImage='') fanart = addon.getAddonInfo('path') + '/fanart.jpg' listitem.setProperty('fanart_image', fanart) xbmcplugin.addDirectoryItem(plugin_handle, url, listitem, isFolder=True, totalItems=0)
def list_episodes(self, movie_id): xbmcplugin.setContent(int(sys.argv[1]), 'episodes') query_params = {'movieid': movie_id} m = self.__request__('movie', query_params)['r'] _id = m['MovieID'] name = m['MovieName'] aka = m['KnownAs'] trailer = m['Trailer'] poster = m['Poster'] if 'Poster214x321' in m: poster = m['Poster214x321'] runtime = m['Runtime'] plot = m['PlotVI'] rating = m['ImdbRating'] country = m['Country'] release_date = m['ReleaseDate'] backdrop = m['Backdrop'] banner = m['Banner'] num_episodes = m['Episode'] thumbs = sorted(m['Thumbs'].keys(), key=lambda x: int(x)) for thumb in thumbs: t = unicode.join(u'',[u'Tập', ' ', thumb]) item = xbmcgui.ListItem(t) item.setInfo(type="Video", infoLabels={"Label": name, "Title": t, "Plot": plot, 'Year': release_date}) epThumb = m['Thumbs'][thumb] item.setArt({'poster': epThumb, 'thumb': epThumb}) item.setProperty("Fanart_Image", backdrop) u = self.__build_url__({'action': 'play_movie', 'movie_id': _id, 'episode': thumb}) xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=item,isFolder=False) xbmcplugin.endOfDirectory(int(sys.argv[1]), cacheToDisc=True)
def view(items, update_listing=False, urls=None): if urls is None: urls = [plugin.url_for_path(item.url) for item in items] total = len(items) for item, url in zip(items, urls): if not getattr(item, 'available', True): continue title = item.title if getattr(item, 'episode', None): title += " " + item.episode li = ListItem(title, thumbnailImage=getattr(item, 'thumb', '')) playable = plugin.route_for(url) == play li.setProperty('isplayable', str(playable)) if hasattr(item, 'fanart'): li.setProperty('fanart_image', item.fanart) if playable: info = { 'title': title, 'plot': item.description, 'mpaa': item.legal_age, } if item.category: info['genre'] = item.category.title if item.aired: info['aired'] = item.aired.strftime('%Y-%m-%d') li.setInfo('video', info) li.addStreamInfo('video', {'codec': 'h264', 'width': 1280, 'height': 720, 'duration': item.duration}) li.addStreamInfo('audio', {'codec': 'aac', 'channels': 2}) addDirectoryItem(plugin.handle, url, li, not playable, total) endOfDirectory(plugin.handle, updateListing=update_listing)
def Get_Header(par, count): if par.search == "": info = "Сериалов: " + "[COLOR FF00FF00]" + str(count) + "[/COLOR] | " info += "Жанр: " + "[COLOR FFFF00FF]" + par.genre_name + "[/COLOR] | " info += "Страна: " + "[COLOR FFFFF000]" + par.country_name + "[/COLOR]" else: info = "Поиск: " + "[COLOR FF00FFF0]" + par.search + "[/COLOR]" if info <> "": # -- info line name = info i = xbmcgui.ListItem(name, iconImage=icon, thumbnailImage=icon) u = sys.argv[0] + "?mode=EMPTY" # -- filter parameters u += "&genre=%s" % urllib.quote_plus(par.genre) u += "&genre_name=%s" % urllib.quote_plus(par.genre_name) u += "&country=%s" % urllib.quote_plus(par.country) u += "&country_name=%s" % urllib.quote_plus(par.country_name) xbmcplugin.addDirectoryItem(h, u, i, True) # -- genre if par.genre == "0" and par.search == "" and par.history == "": name = "[COLOR FFFF00FF]" + "[ЖАНР]" + "[/COLOR]" i = xbmcgui.ListItem(name, iconImage=icon, thumbnailImage=icon) u = sys.argv[0] + "?mode=GENRE" # -- filter parameters u += "&genre=%s" % urllib.quote_plus(par.genre) u += "&genre_name=%s" % urllib.quote_plus(par.genre_name) u += "&country=%s" % urllib.quote_plus(par.country) u += "&country_name=%s" % urllib.quote_plus(par.country_name) xbmcplugin.addDirectoryItem(h, u, i, True) # -- genre if par.country == "0" and par.search == "" and par.history == "": name = "[COLOR FFFFF000]" + "[СТРАНА]" + "[/COLOR]" i = xbmcgui.ListItem(name, iconImage=icon, thumbnailImage=icon) u = sys.argv[0] + "?mode=COUNTRY" # -- filter parameters u += "&genre=%s" % urllib.quote_plus(par.genre) u += "&genre_name=%s" % urllib.quote_plus(par.genre_name) u += "&country=%s" % urllib.quote_plus(par.country) u += "&country_name=%s" % urllib.quote_plus(par.country_name) xbmcplugin.addDirectoryItem(h, u, i, True) # -- search & history if par.country == "0" and par.genre == "0" and par.search == "" and par.history == "": name = "[COLOR FF00FFF0]" + "[ПОИСК]" + "[/COLOR]" i = xbmcgui.ListItem(name, iconImage=icon, thumbnailImage=icon) u = sys.argv[0] + "?mode=MOVIE" # -- filter parameters u += "&search=%s" % urllib.quote_plus("Y") xbmcplugin.addDirectoryItem(h, u, i, True) name = "[COLOR FF00FF00]" + "[ИСТОРИЯ]" + "[/COLOR]" i = xbmcgui.ListItem(name, iconImage=icon, thumbnailImage=icon) u = sys.argv[0] + "?mode=MOVIE" # -- filter parameters u += "&history=%s" % urllib.quote_plus("Y") xbmcplugin.addDirectoryItem(h, u, i, True)
def panDir(): while not panAuth(): if xbmcgui.Dialog().yesno(_name, ' Login Failed', 'Bad User / Pass / Proxy', ' Check Settings?'): _settings.openSettings() else: exit() sort = _settings.getSetting('sort') stations = _pandora.stations quickmix = stations.pop(0) # Quickmix if sort == '0': stations = stations # Normal elif sort == '2': stations = stations[::-1] # Reverse else: stations = sorted(stations, key=lambda s: s.name) # A-Z stations.insert(0, quickmix) # Quickmix back on top for station in stations: li = xbmcgui.ListItem(station.name, station.id) li.setProperty('IsPlayable', 'true') img = _settings.getSetting("img-%s" % station.id) li.setIconImage(img) li.setThumbnailImage(img) li.addContextMenuItems([('Select Thumb', "RunPlugin(plugin://%s/?thumb=%s)" % (_plugin, station.id))]) xbmcplugin.addDirectoryItem(_handle, "%s?station=%s" % (_base, station.id), li) xbmcplugin.endOfDirectory(_handle, cacheToDisc = False) xbmc.log("%s.Dir OK" % _plugin, xbmc.LOGDEBUG)
def addDir(title, url, mode, page=0, searchValue=''): sys_url = sys.argv[0] + '?title=' + urllib.quote_plus(title) + '&url=' + urllib.quote_plus(url) + \ '&mode=' + urllib.quote_plus(str(mode)) + '&page=' + urllib.quote_plus(str(page))+'&search'+\ urllib.quote_plus(str(searchValue)) item = xbmcgui.ListItem(title, iconImage='DefaultFolder.png', thumbnailImage='') xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=sys_url, listitem=item, isFolder=True)
def schedule247(): import datetime import time i = datetime.datetime.now() day,month,year=i.day, i.month, i.year s="%s/%s/%s"%(day,month,year) time=time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple()) time=str(time).replace('.0','')+'000' url='https://tockify.com/api/readEventView?calname=pilkalive&max=30&start-inclusive=true&startms='+time txt=json.loads(read_url(url)) events=txt['events'] for i in range (len(events)): time=events[i]['when']['start']['millis'] time=str(time)[:-3] event=events[i]['content']['summary']['text'] link=events[i]['content']['description']['text'] ts = datetime.datetime.fromtimestamp(float(time)) year,month,day,hour,minute=ts.strftime('%Y'),ts.strftime('%m'),ts.strftime('%d'),ts.strftime('%H'),ts.strftime('%M') from utils import pytzimp d = pytzimp.timezone(str(pytzimp.timezone('Europe/Madrid'))).localize(datetime.datetime(2000 + int(year), int(month), int(day), hour=int(hour), minute=int(minute))) timezona= addon.get_setting('timezone_new') my_location=pytzimp.timezone(pytzimp.all_timezones[int(timezona)]) convertido=d.astimezone(my_location) fmt = "%d-%m-%y [COLOR green]%H:%M[/COLOR]" time=convertido.strftime(fmt) event=event[5:] title='([COLOR blue][B]%s[/B][/COLOR]) [B][COLOR orange]%s[/COLOR][/B]'%(time,event) url = build_url({'mode': 'open_247_event','url':link}) li = xbmcgui.ListItem(title,iconImage='') xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True) xbmcplugin.endOfDirectory(addon_handle)
def ttv_sport(): base_url = 'http://super-pomoyka.us.to/trash/ttv-list/ttv.m3u' source = read_url(base_url) if source: match= re.compile("#EXTINF:-1,Sky Sports News \(.+?\)\n(.*)").findall(source) if match: name='Sky Sports News' ace=match[0] url='plugin://program.plexus/?mode=1&url=%s&name=%s'%(ace,name.replace(' ','+')) li = xbmcgui.ListItem('%s'%name, iconImage='http://addons.tvaddons.ag/cache/images/bc591d6d5ec442d4ddb43a347a8be6_icon.png') li.setProperty('IsPlayable', 'true') xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li) match= re.compile("#EXTINF:-1,(.+?)\(Спорт\)\n(.*)").findall(source) for titulo,acestream in match: name=titulo ace=acestream clean = re.compile("\((.+?)\)").findall(name) for categorie in clean: name = name.replace("(" + categorie +")","") ace=acestream url='plugin://program.plexus/?mode=1&url=%s&name=%s'%(ace,name.replace(' ','+')) li = xbmcgui.ListItem('%s'%name, iconImage='http://addons.tvaddons.ag/cache/images/bc591d6d5ec442d4ddb43a347a8be6_icon.png') li.setProperty('IsPlayable', 'true') xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li) xbmcplugin.endOfDirectory(addon_handle)
def ttv_cats(): dict_torrent = {} url="http://super-pomoyka.us.to/trash/ttv-list/ttv.m3u" html_source=read_url(url) match = re.compile('#EXTINF:-1,(.+?)\n(.*)').findall(html_source) for title, acehash in match: channel_name = re.compile('(.+?) \(').findall(title) match_cat = re.compile('\((.+?)\)').findall(title) for i in xrange(0,len(match_cat)): if match_cat[i] == "Для взрослых" : pass elif match_cat[i] == "Ночной канал" : pass else: categorie = russiandictionary(match_cat[i]) if categorie not in dict_torrent.keys(): try: dict_torrent[categorie] = [(channel_name[0],acehash)] except: pass else: try: dict_torrent[categorie].append((channel_name[0],acehash)) except: pass for cat in dict_torrent.keys(): url = build_url({'mode': 'open_ttv_cat','channels':json.dumps(dict_torrent),'cat':cat}) li = xbmcgui.ListItem(cat,iconImage='http://addons.tvaddons.ag/cache/images/bc591d6d5ec442d4ddb43a347a8be6_icon.png') xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True) xbmcplugin.endOfDirectory(addon_handle)
def get_ttv(): url='http://www.acesportstream.com' url=read_url(url) soup=bs(url) channels1=soup.find('div',{'id':'hd'}).findAll('a') channels2=soup.find('div',{'id':'blue'}).findAll('a') for channel in channels1: link=channel['href'] img=channel.find('img')['src'] name=clean(cleanex(channel['title'])) url = build_url({'mode': 'open_ttv_stream','url':link, 'name':name.encode('ascii','ignore')}) li = xbmcgui.ListItem('%s'%name, iconImage=img) li.setProperty('IsPlayable', 'true') xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li) for channel in channels2: link=channel['href'] img=channel.find('img')['src'] name=clean(cleanex(channel['title'])) url = build_url({'mode': 'open_ttv_stream','url':link, 'name':name.encode('ascii','ignore')}) li = xbmcgui.ListItem('%s'%name, iconImage=img) li.setProperty('IsPlayable', 'true') xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li) xbmcplugin.endOfDirectory(addon_handle)
def channelList(self, channelList): count = 0 total = len(channelList) for i in channelList: try: name, epg = i['name'], i['epg'] if getSetting(name) == "false": raise Exception() sysname = urllib.quote_plus(name.replace(' ','_')) u = '%s?action=play&channel=%s&t=%s' % (sys.argv[0], sysname, datetime.datetime.now().strftime("%Y%m%d%H%M%S%f")) meta = {'Label': name, 'Title': name, 'Studio': name, 'Duration': '1440', 'Plot': epg} image = '%s/%s.png' % (addonLogos, re.sub('\s[(]\d{1}[)]','', name)) fanart = '%s/%s.jpg' % (addonSlideshow, str(count)[-1]) count = count + 1 cm = [] cm.append((language(30401).encode("utf-8"), 'RunPlugin(%s?action=epg_menu&channel=%s)' % (sys.argv[0], sysname))) cm.append((language(30404).encode("utf-8"), 'RunPlugin(%s?action=refresh)' % (sys.argv[0]))) item = xbmcgui.ListItem(name, iconImage=image, thumbnailImage=image) item.setInfo( type="Video", infoLabels = meta ) #item.setProperty("IsPlayable", "true") item.setProperty("Video", "true") item.setProperty("Fanart_Image", fanart) item.addContextMenuItems(cm, replaceItems=False) xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=item,totalItems=total,isFolder=False) except: pass
def addDir(name, url, mode, iconimage, description): u = ( sys.argv[0] + "?url=" + urllib.quote_plus(url) + "&mode=" + str(mode) + "&name=" + urllib.quote_plus(name) + "&iconimage=" + urllib.quote_plus(iconimage) + "&description=" + urllib.quote_plus(description) ) ok = True liz = xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage) liz.setInfo(type="Video", infoLabels={"Title": name, "Plot": description}) if mode == 1: ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz) elif mode == 3 or mode == 5: liz.setProperty("IsPlayable", "true") ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=False) else: ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=True) return ok
def getTags(params): http = GET(httpSiteUrl + '/tags/', httpSiteUrl) if http == None: return False beautifulSoup = BeautifulSoup(http) tagsContainer = beautifulSoup.find('td', 'news') tags = tagsContainer.findAll('a') if len(tags) == 0: showMessage('ОШИБКА', 'Неверная страница', 3000) return False else: tags.reverse() for link in tags: if link != None: title = link.string href = link['href'] if href.find("://") < 0: href = httpSiteUrl + href li = xbmcgui.ListItem('[%s]' % title) li.setProperty('IsPlayable', 'false') uri = construct_request({ 'href': href, 'mode': 'readCategory' }) xbmcplugin.addDirectoryItem(h, uri, li, True) xbmcplugin.endOfDirectory(h)
def add(self, service, name, category, title, iconimage, url, desc, page, folder=True, isPlayable=True): u = ( sys.argv[0] + "?service=" + service + "&name=" + name + "&category=" + category + "&title=" + title + "&url=" + urllib.quote_plus(url) + "&icon=" + urllib.quote_plus(iconimage) + "&page=" + urllib.quote_plus(page) ) # log.info(str(u)) if name == "main-menu" or name == "categories-menu": title = category if iconimage == "": iconimage = "DefaultVideo.png" liz = xbmcgui.ListItem(title, iconImage="DefaultFolder.png", thumbnailImage=iconimage) liz.setProperty("fanart_image", iconimage) if isPlayable: liz.setProperty("IsPlayable", "true") liz.setInfo( type="Video", infoLabels={"Title": title, "Plot": desc, "Episode": "AAA", "Year": "2000", "Genre": "bbb"} ) xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=folder)
def Movies(url): html = getHTML(url) png_links = re.compile('<img class="lazy" data-original="(.+?)" src="').findall(html) movie_links = re.compile('<a href="(.+?)" class="a ajax">\s+<span class="s1 ptsans_bold"><span class="hfx">(.+?)</span></span>').findall(html) item = xbmcgui.ListItem('[B]Категории[/B]', iconImage='DefaultFolder.png', thumbnailImage='') xbmcplugin.addDirectoryItem(_addon_id, 'plugin://plugin.video.kaztube/' , item, True) # if _url_page > 1: # back_page = _url_page - 1 # addDir('[COLOR F5DEB300]Назад[/COLOR]', url, 20, '', True, back_page) i = 0 all = [] for link, name in movie_links: all.append( (link, name, png_links[i] ) ) i = i + 1 for link, title, png in all: addDir(title, link, 30, png, False, 0) pages = re.compile('page="(.+?)" href="').findall(html) max_page = 0 if pages: max_page = int(pages[-1]) next_page = _url_page + 1 if next_page <= max_page: addDir('[COLOR F5DEB300]Загрузить еще[/COLOR]', url, 20, '', True, next_page)
def getCategories(params): categoryUrl = urllib.unquote_plus(params['href']) http = GET(categoryUrl, httpSiteUrl) if http == None: return False beautifulSoup = BeautifulSoup(http) categoryContainer = beautifulSoup.find('ul', 'cats') categories = categoryContainer.findAll('a') if len(categories) == 0: showMessage('ОШИБКА', 'Неверная страница', 3000) return False else: for link in categories: if link != None: title = link.string if title == None: title = link.find("h2").string href = link['href'] if href.find("://") < 0: href = httpSiteUrl + href li = xbmcgui.ListItem('[%s]' % title) li.setProperty('IsPlayable', 'false') uri = construct_request({ 'href': href, 'mode': 'readCategory' }) xbmcplugin.addDirectoryItem(h, uri, li, True) xbmcplugin.endOfDirectory(h)
def addVideo(linkName = '', source = '', videoID = '', thumbPath = '', date = ''): """Add a video to an XBMC directory listing Arguments: linkName -- A string containg the name of the video url -- A string containing the direct url to the video thumbPath -- A string containg the url/path of the video's thumbnail image date -- a dataetime object containg the date of the video""" url = sys.argv[0] + "?source=" + source + "&id=" + videoID # initialise a listitem object to store video details li = xbmcgui.ListItem(linkName, iconImage = thumbPath, thumbnailImage = thumbPath) # set the video to playable li.setProperty("IsPlayable", 'true') # set the infolabels for the video li.setInfo( type="Video", infoLabels={ "title": linkName, "date":date} ) # set fanart image for video li.setProperty( "Fanart_Image", os.path.join(__addondir__, 'fanart.jpg')) # add listitem object to list xbmcplugin.addDirectoryItem(handle = __addonidint__, url = url, listitem = li, isFolder = False)
def _addDir(self, name, action_key, action_value, iconimage, is_folder): """ .. py_function:: _addDir(self, name, action_key, action_value, iconimage, is_folder) Creates a link in xbmc. :param name: Name of the link :param action_key: Name of the action to take when link selected :param action_value: Parameter to use with the action :param iconimage: Icon to use for the link :param is_folder: Does the link lead to a folder or playable item """ formatparams = { "base_url": self.base_url, "key": quote(str(action_key)), "value": quote(str(action_value)), "name": quote(str(name)) } url = "{base_url}?action_key={key}&action_value={value}&name={name}".format(**formatparams) listitem = xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage='') listitem.setInfo(type="Video", infoLabels={"Title": name}) xbmcplugin.addDirectoryItem( handle=self.addon_handle, url=url, listitem=listitem, isFolder=is_folder)
def addLink(name,url,title,iconimage): if iconimage == '': iconimage = ICON liz=xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage) liz.setInfo( type="Video", infoLabels={ "Title": title } ) liz.setProperty('fanart_image',FANART) xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
def addVideoDirR(name, url, mode, iconimage, videoType="", desc="", duration="", year="", mpaa="", director="", genre="", rating=""): filename = (''.join(c for c in unicode(url, 'utf-8') if c not in '/\\:?"*|<>')).strip()+".jpg" coverFile = os.path.join(cacheFolderCoversTMDB, filename) fanartFile = os.path.join(cacheFolderFanartTMDB, filename) if os.path.exists(coverFile): iconimage = coverFile u = sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&thumb="+urllib.quote_plus(iconimage) ok = True liz = xbmcgui.ListItem(name, iconImage="DefaultTVShows.png", thumbnailImage=iconimage) liz.setInfo(type="video", infoLabels={"title": name, "plot": desc, "duration": duration, "year": year, "mpaa": mpaa, "director": director, "genre": genre, "rating": rating}) if os.path.exists(fanartFile): liz.setProperty("fanart_image", fanartFile) elif os.path.exists(coverFile): liz.setProperty("fanart_image", coverFile) entries = [] entries.append((translation(30134), 'RunPlugin(plugin://plugin.video.netflixbmc/?mode=playTrailer&url='+urllib.quote_plus(name)+')',)) entries.append((translation(30115), 'RunPlugin(plugin://plugin.video.netflixbmc/?mode=removeFromQueue&url='+urllib.quote_plus(url)+')',)) if videoType == "tvshow": entries.append((translation(30122), 'RunPlugin(plugin://plugin.video.netflixbmc/?mode=addSeriesToLibrary&url=&name='+str(name.strip())+'&seriesID='+str(url)+')',)) if browseTvShows: entries.append((translation(30121), 'Container.Update(plugin://plugin.video.netflixbmc/?mode=playVideo&url='+urllib.quote_plus(url)+'&thumb='+urllib.quote_plus(iconimage)+')',)) else: entries.append((translation(30118), 'Container.Update(plugin://plugin.video.netflixbmc/?mode=listSeasons&url='+urllib.quote_plus(url)+'&thumb='+urllib.quote_plus(iconimage)+')',)) elif videoType == "movie": entries.append((translation(30122), 'RunPlugin(plugin://plugin.video.netflixbmc/?mode=addMovieToLibrary&url='+urllib.quote_plus(url)+'&name='+str(name.strip()+' ('+year+')')+')',)) liz.addContextMenuItems(entries) if mode == "playVideo": ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=False) else: ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=True) return ok
def INC_start(): dbg_log('-INC_start') http = get_url(INC_urlw + '/index.php', save_cookie = True) mycookie = re.search('<cookie>(.+?)</cookie>', http).group(1) http = get_url(INC_urlw + INC_auth, data = "LoginForm%5Busername%5D=" + urllib.quote_plus(usr_log) + "&LoginForm%5Bpassword%5D=" + urllib.quote_plus(usr_pwd), cookie = mycookie, save_cookie = True, referrer = INC_urlw + '/index.php', accept='json') try: mycookie = re.search('<cookie>(.+?)</cookie>', http).group(1) except: pass http = get_url(INC_urlw + '/index.php', cookie = mycookie) #mycookie = re.search('<cookie>(.+?)</cookie>', http).group(1) name='Live TV' item = xbmcgui.ListItem(name) uri = sys.argv[0] + '?mode=live' + '&cook=' + urllib.quote_plus(mycookie) xbmcplugin.addDirectoryItem(pluginhandle, uri, item, True) name='Archives' item = xbmcgui.ListItem(name) uri = sys.argv[0] + '?mode=chls' + '&cook=' + urllib.quote_plus(mycookie) xbmcplugin.addDirectoryItem(pluginhandle, uri, item, True) xbmcplugin.endOfDirectory(pluginhandle)
def PlayVideo1(url, listitem): addon_handle = int(sys.argv[1]) xbmcplugin.setContent(addon_handle, 'video') li = xbmcgui.ListItem('[COLOR dodgerblue][B]PLAY STREAM[/B][/COLOR] >> ', iconImage='http://maps.synthicity.com/activemaps/images/button_black_play.png', thumbnailImage= 'http://maps.synthicity.com/activemaps/images/button_black_play.png') li.setProperty('fanart_image', 'https://raw.githubusercontent.com/TheYid/My-Repo/master/repository.TheYid/fanart.jpg') xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li) xbmcplugin.endOfDirectory(addon_handle)
def addDir(title, url, mode): sys_url = sys.argv[0] + '?title=' + urllib.quote_plus(title) + '&url=' + urllib.quote_plus(url) + '&mode=' + urllib.quote_plus(str(mode)) item = xbmcgui.ListItem(title, iconImage='DefaultFolder.png', thumbnailImage='') item.setInfo( type='Video', infoLabels={'Title': title} ) xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=sys_url, listitem=item, isFolder=True)
def INC_live(url, mycookie): dbg_log('INC_live') http = get_url(url, cookie = mycookie, referrer = INC_urlw + '/index.php') # guest = re.compile('var isGuest=(.+?);').findall(http) # print '--GUEST--' # print guest oneline = re.sub('[\r\n]', ' ', http) pr_ls = re.compile('<tr > +?<td class="col01"><a href="(.+?)"><img src="(.+?)" alt="(.+?)" /></a></td>').findall(oneline) if len(pr_ls): for href,logo,descr in pr_ls: name = descr dbg_log(name) item = xbmcgui.ListItem(name, iconImage=INC_url + logo, thumbnailImage=INC_url + logo) uri = sys.argv[0] + '?mode=play' uri += '&url='+urllib.quote_plus(INC_urlw + href) + '&cook=' + urllib.quote_plus(mycookie) item.setInfo( type='video', infoLabels={'title': name, 'plot': descr}) item.setProperty('IsPlayable', 'true') dbg_log(uri) xbmcplugin.addDirectoryItem(pluginhandle, uri, item) xbmcplugin.endOfDirectory(pluginhandle)
def addDir(title, url, mode, png, is_cat, page): sys_url = sys.argv[0] + '?title=' + urllib.quote_plus(title) + '&url=' + urllib.quote_plus(url) if page > 0: if url[-1] == '/': sys_url = sys_url + urllib.quote_plus( '?page='+str(page) ) else: sys_url = sys_url + urllib.quote_plus( '&page='+str(page) ) sys_url = sys_url + '&mode=' + urllib.quote_plus(str(mode)) if png: spng = 'http://kaztube.kz' + png sys_url = sys_url + '&png=' + urllib.quote_plus(spng) else: spng = '' if page > 0: sys_url = sys_url + '&page=' + urllib.quote_plus(str(page)) item = xbmcgui.ListItem(title, iconImage='DefaultFolder.png', thumbnailImage=spng) item.setInfo( type='Video', infoLabels={'Title': title} ) xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=sys_url, listitem=item, isFolder=is_cat)
def addText(name): item = xbmcgui.ListItem(name) item.setProperty('IsPlayable', 'false') xbmcplugin.addDirectoryItem(handle=pluginhandle, url=sys.argv[0], listitem=item)
list_item = xbmcgui.ListItem(label=languages[subtitle['subLang']], label2=subtitle['subName'], thumbnailImage=xbmc.convertLanguage( subtitle["subLang"], xbmc.ISO_639_1)) plugin_url = "plugin://{path}/?{query}".format( path=__scriptid__, query=urllib.urlencode( dict(action='download', link=subtitle['subDownloadLink'], file_name=subtitle['subName'], format=subtitle['subFormat']))) log("BSPlayer.plugin_url", "Plugin Url Created: %s." % plugin_url) xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=plugin_url, listitem=list_item, isFolder=False) elif params['action'] == 'manualsearch': notify(__scriptname__, __language__, 32002) log("BSPlayer.manualsearch", "Manual search not supported.") elif params['action'] == 'download': if xbmcvfs.exists(__temp__): shutil.rmtree(__temp__) xbmcvfs.mkdirs(__temp__) if params['format'] in ["srt", "sub", "txt", "smi", "ssa", "ass"]: subtitle_path = path.join(__temp__, params['file_name']) if BSPlayer.download_subtitles(params['link'], subtitle_path): log("BSPlayer.download_subtitles", "Subtitles Download Successfully From: %s." % params['link']) list_item = xbmcgui.ListItem(label=subtitle_path)
def make_selectable(self, name, url): li = ListItem(name, iconImage='DefaultUser.png') li.setProperty('IsPlayable', 'False') li.setInfo("video", {'mediatype': 'video'}) # needed to make it selectable? addDirectoryItem(self.handle, url=url, listitem=li)
def make_folder(self, folder_name, url, icon_name): li = ListItem(folder_name, iconImage=icon_name) li.setProperty('IsPlayable', 'False') addDirectoryItem(self.handle, url=url, listitem=li, isFolder=True)
def generate_list_items(xml, href, foldername, nametree): """ Will generate a list of directory items for the UI based on the xml values. """ for group in xml.getiterator('group'): if group.attrib.get('href') == href: continue # Build up the name tree. name = group.attrib.get('name').encode('ascii', 'ignore') url = build_url({ 'mode': group.attrib.get('type'), 'foldername': name, 'href': group.attrib.get('href'), 'parenthref': href, 'nametree': nametree + '/' + name }) if group.attrib.get('art') == None: image = 'DefaultVideo.png' else: image = playonInternalUrl + group.attrib.get('art') if group.attrib.get('type') == 'folder': try: from metahandler import metahandlers metaget = metahandlers.MetaData() #Get a movie #Media type and movie name are required, imdb id will give you exact match, if no imdb id then include the year for more accurate match #Media type and Name are required, rest are optional # meta=metaget.get_meta('movie', name) meta = metaget.get_meta('movie', name) li = xbmcgui.ListItem(name, iconImage=meta['cover_url'], thumbnailImage=meta['cover_url']) li.setInfo(type="Video", infoLabels=meta) li.setProperty('fanart_image', meta['backdrop_url']) except Exception, e: print str(e) li = xbmcgui.ListItem(name, iconImage=image, thumbnailImage=image) xbmcplugin.addDirectoryItem(handle=addonHandle, url=url, listitem=li, isFolder=True) elif group.attrib.get('type') == 'video': playonUrl = build_playon_url(group.attrib.get('href')) mediaXml = get_xml(playonUrl) mediaNode = mediaXml.find('media') try: from metahandler import metahandlers metaget = metahandlers.MetaData() #Get a movie #Media type and movie name are required, imdb id will give you exact match, if no imdb id then include the year for more accurate match #Media type and Name are required, rest are optional # meta=metaget.get_meta('movie', name) meta = metaget.get_meta('movie', name) li = xbmcgui.ListItem(name, iconImage=meta['cover_url'], thumbnailImage=meta['cover_url']) li.setInfo(type="Video", infoLabels=meta) li.setProperty('fanart_image', meta['backdrop_url']) except Exception, e: print str(e) li = xbmcgui.ListItem(name, iconImage=image, thumbnailImage=image) li.setInfo('video', { 'plotoutline': group.attrib.get('description'), 'title': name })
li = xbmcgui.ListItem(name, iconImage=meta['cover_url'], thumbnailImage=meta['cover_url']) li.setInfo(type="Video", infoLabels=meta) li.setProperty('fanart_image', meta['backdrop_url']) except Exception, e: print str(e) li = xbmcgui.ListItem(name, iconImage=image, thumbnailImage=image) li.setInfo('video', { 'plotoutline': group.attrib.get('description'), 'title': name }) xbmcplugin.addDirectoryItem(handle=addonHandle, url=url, listitem=li) xbmcplugin.endOfDirectory(addonHandle) # # Main Loop log_message("Base URL:" + baseUrl, True) log_message("Addon Handle:" + str(addonHandle), True) log_message("Arguments", True) log_message(args, True) # Pull out the URL arguments for usage. mode = get_argument_value('mode')
def addLink(name,url,iconimage): ok=True liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage) liz.setInfo( type="Video", infoLabels={ "Title": name } ) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz) return ok
def getRecentEpisodes(viewid, mediatype, tagname, limit): count = 0 # if the addon is called with recentepisodes parameter, # we return the recentepisodes list of the given tagname xbmcplugin.setContent(HANDLE, 'episodes') appendShowTitle = settings('RecentTvAppendShow') == 'true' appendSxxExx = settings('RecentTvAppendSeason') == 'true' # First we get a list of all the TV shows - filtered by tag params = { 'sort': { 'order': "descending", 'method': "dateadded" }, 'filter': { 'operator': "is", 'field': "tag", 'value': "%s" % tagname }, } result = JSONRPC('VideoLibrary.GetTVShows').execute(params) # If we found any, find the oldest unwatched show for each one. try: items = result['result'][mediatype] except (KeyError, TypeError): # No items, empty folder xbmcplugin.endOfDirectory(handle=HANDLE) return allshowsIds = set() for item in items: allshowsIds.add(item['tvshowid']) params = { 'sort': { 'order': "descending", 'method': "dateadded" }, 'properties': [ "title", "playcount", "season", "episode", "showtitle", "plot", "file", "rating", "resume", "tvshowid", "art", "streamdetails", "firstaired", "runtime", "cast", "writer", "dateadded", "lastplayed" ], "limits": { "end": limit } } if settings('TVShowWatched') == 'false': params['filter'] = { 'operator': "lessthan", 'field': "playcount", 'value': "1" } result = JSONRPC('VideoLibrary.GetEpisodes').execute(params) try: episodes = result['result']['episodes'] except (KeyError, TypeError): pass else: for episode in episodes: if episode['tvshowid'] in allshowsIds: li = createListItem(episode, appendShowTitle=appendShowTitle, appendSxxExx=appendSxxExx) xbmcplugin.addDirectoryItem(handle=HANDLE, url=episode['file'], listitem=li) count += 1 if count == limit: break xbmcplugin.endOfDirectory(handle=HANDLE)
def addLink(contentType, name, url, iconimage='DefaultFolder.png', time='', sub=''): liz = xbmcgui.ListItem(clean(contentType, name), iconImage="DefaultVideo.png", thumbnailImage=iconimage) liz.setInfo(type="Video", infoLabels={ "Title": urllib.unquote(clean(contentType, name)), "Duration":time, "Plot": urllib.unquote(sub)}) ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=liz) return ok
def getOnDeck(viewid, mediatype, tagname, limit): """ Retrieves Plex On Deck items, currently only for TV shows Input: viewid: Plex id of the library section, e.g. '1' mediatype: Kodi mediatype, e.g. 'tvshows', 'movies', 'homevideos', 'photos' tagname: Name of the Plex library, e.g. "My Movies" limit: Max. number of items to retrieve, e.g. 50 """ xbmcplugin.setContent(HANDLE, 'episodes') appendShowTitle = settings('OnDeckTvAppendShow') == 'true' appendSxxExx = settings('OnDeckTvAppendSeason') == 'true' directpaths = settings('useDirectPaths') == 'true' if settings('OnDeckTVextended') == 'false': # Chances are that this view is used on Kodi startup # Wait till we've connected to a PMS. At most 30s counter = 0 while window('plex_authenticated') != 'true': counter += 1 if counter >= 300: log.error('Aborting On Deck view, we were not authenticated ' 'for the PMS') return xbmcplugin.endOfDirectory(HANDLE, False) sleep(100) xml = downloadutils.DownloadUtils().downloadUrl( '{server}/library/sections/%s/onDeck' % viewid) if xml in (None, 401): log.error('Could not download PMS xml for view %s' % viewid) return xbmcplugin.endOfDirectory(HANDLE) limitcounter = 0 for item in xml: api = API(item) listitem = api.CreateListItemFromPlexItem( appendShowTitle=appendShowTitle, appendSxxExx=appendSxxExx) if directpaths: url = api.getFilePath() else: params = { 'mode': "play", 'id': api.getRatingKey(), 'dbid': listitem.getProperty('dbid') } url = "plugin://plugin.video.plexkodiconnect/tvshows/?%s" \ % urlencode(params) xbmcplugin.addDirectoryItem(handle=HANDLE, url=url, listitem=listitem) limitcounter += 1 if limitcounter == limit: break return xbmcplugin.endOfDirectory( handle=HANDLE, cacheToDisc=settings('enableTextureCache') == 'true') # if the addon is called with nextup parameter, # we return the nextepisodes list of the given tagname # First we get a list of all the TV shows - filtered by tag params = { 'sort': { 'order': "descending", 'method': "lastplayed" }, 'filter': { 'and': [{ 'operator': "true", 'field': "inprogress", 'value': "" }, { 'operator': "is", 'field': "tag", 'value': "%s" % tagname }] } } result = JSONRPC('VideoLibrary.GetTVShows').execute(params) # If we found any, find the oldest unwatched show for each one. try: items = result['result'][mediatype] except (KeyError, TypeError): # Now items retrieved - empty directory xbmcplugin.endOfDirectory(handle=HANDLE) return params = { 'sort': { 'method': "episode" }, 'limits': { "end": 1 }, 'properties': [ "title", "playcount", "season", "episode", "showtitle", "plot", "file", "rating", "resume", "tvshowid", "art", "streamdetails", "firstaired", "runtime", "cast", "writer", "dateadded", "lastplayed" ], } if settings('ignoreSpecialsNextEpisodes') == "true": params['filter'] = { 'and': [{ 'operator': "lessthan", 'field': "playcount", 'value': "1" }, { 'operator': "greaterthan", 'field': "season", 'value': "0" }] } else: params['filter'] = { 'or': [{ 'operator': "lessthan", 'field': "playcount", 'value': "1" }, { 'operator': "true", 'field': "inprogress", 'value': "" }] } # Are there any episodes still in progress/not yet finished watching?!? # Then we should show this episode, NOT the "next up" inprog_params = { 'sort': { 'method': "episode" }, 'filter': { 'operator': "true", 'field': "inprogress", 'value': "" }, 'properties': params['properties'] } count = 0 for item in items: inprog_params['tvshowid'] = item['tvshowid'] result = JSONRPC('VideoLibrary.GetEpisodes').execute(inprog_params) try: episodes = result['result']['episodes'] except (KeyError, TypeError): # No, there are no episodes not yet finished. Get "next up" params['tvshowid'] = item['tvshowid'] result = JSONRPC('VideoLibrary.GetEpisodes').execute(params) try: episodes = result['result']['episodes'] except (KeyError, TypeError): # Also no episodes currently coming up continue for episode in episodes: # There will always be only 1 episode ('limit=1') li = createListItem(episode, appendShowTitle=appendShowTitle, appendSxxExx=appendSxxExx) xbmcplugin.addDirectoryItem(handle=HANDLE, url=episode['file'], listitem=li, isFolder=False) count += 1 if count >= limit: break xbmcplugin.endOfDirectory(handle=HANDLE)
def build_video_listing(self, video_list, actions, type, build_url): """Builds the video lists (my list, continue watching, etc.) contents Kodi screen Parameters ---------- video_list_ids : :obj:`dict` of :obj:`str` List of video lists actions : :obj:`dict` of :obj:`str` Dictionary of actions to build subsequent routes type : :obj:`str` None or 'queue' f.e. when it´s a special video lists build_url : :obj:`fn` Function to build the subsequent routes Returns ------- bool List could be build """ for video_list_id in video_list: video = video_list[video_list_id] li = xbmcgui.ListItem(label=video['title']) # add some art to the item li = self._generate_art_info(entry=video, li=li) # it´s a show, so we need a subfolder & route (for seasons) isFolder = True url = build_url({ 'action': actions[video['type']], 'show_id': video_list_id }) # lists can be mixed with shows & movies, therefor we need to check if its a movie, so play it right away if video_list[video_list_id]['type'] == 'movie': # it´s a movie, so we need no subfolder & a route to play it isFolder = False url = build_url({ 'action': 'play_video', 'video_id': video_list_id }) # add list item info li = self._generate_entry_info(entry=video, li=li) li = self._generate_context_menu_items(entry=video, li=li) xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url, listitem=li, isFolder=isFolder) xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LABEL) xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_TITLE) xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_VIDEO_YEAR) xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_GENRE) xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LASTPLAYED) xbmcplugin.endOfDirectory(self.plugin_handle) return True
def getInProgressEpisodes(tagname, limit): count = 0 # if the addon is called with inprogressepisodes parameter, # we return the inprogressepisodes list of the given tagname xbmcplugin.setContent(HANDLE, 'episodes') # First we get a list of all the in-progress TV shows - filtered by tag params = { 'sort': { 'order': "descending", 'method': "lastplayed" }, 'filter': { 'and': [{ 'operator': "true", 'field': "inprogress", 'value': "" }, { 'operator': "is", 'field': "tag", 'value': "%s" % tagname }] }, 'properties': ['title', 'studio', 'mpaa', 'file', 'art'] } result = JSONRPC('VideoLibrary.GetTVShows').execute(params) # If we found any, find the oldest unwatched show for each one. try: items = result['result']['tvshows'] except (KeyError, TypeError): pass else: for item in items: params = { 'tvshowid': item['tvshowid'], 'sort': { 'method': "episode" }, 'filter': { 'operator': "true", 'field': "inprogress", 'value': "" }, 'properties': [ "title", "playcount", "season", "episode", "showtitle", "plot", "file", "rating", "resume", "tvshowid", "art", "cast", "streamdetails", "firstaired", "runtime", "writer", "dateadded", "lastplayed" ] } result = JSONRPC('VideoLibrary.GetEpisodes').execute(params) try: episodes = result['result']['episodes'] except (KeyError, TypeError): pass else: for episode in episodes: li = createListItem(episode) xbmcplugin.addDirectoryItem(handle=HANDLE, url=episode['file'], listitem=li) count += 1 if count == limit: break xbmcplugin.endOfDirectory(handle=HANDLE)
def getCategoryItems(self, url, page): #print "*** Get category items %s" % url page_url = "%s/page/%s/" % (url, str(int(page))) response = common.fetchPage({"link": page_url}) per_page = 0 pagenav = None if response["status"] == 200: content = common.parseDOM(response["content"], "div", attrs={"id": "container"}) items = common.parseDOM(content, "div", attrs={"class": "owl-item"}) link_container = common.parseDOM( items, "h2", attrs={"class": "main-sliders-title"}) titles = common.parseDOM(link_container, "a") links = common.parseDOM(link_container, "a", ret="href") images = common.parseDOM(items, "img", ret="src") descs = common.parseDOM(items, "i") pagenav = common.parseDOM(content, "div", attrs={"class": "navigation"}) for i, title in enumerate(titles): per_page += 1 title = self.strip(self.encode(title)) image = images[(i + 1) * 3 - 1] if 'http' in images[ (i + 1) * 3 - 1] else self.url + images[(i + 1) * 3 - 1] genres_cont = common.parseDOM(items[i], "em") genres = common.parseDOM(genres_cont, "a") genre = self.encode(', '.join(genres)) description = self.strip(self.encode(descs[i])) uri = sys.argv[0] + '?mode=show&url=%s' % (links[i]) self.log("image: %s" % image) self.log("uri: %s" % uri) item = xbmcgui.ListItem(title, iconImage=image, thumbnailImage=image) item.setInfo(type='Video', infoLabels={ 'title': title, 'genre': genre, 'plot': description }) xbmcplugin.addDirectoryItem(self.handle, uri, item, True) if pagenav and not per_page < 15: uri = sys.argv[0] + '?mode=%s&url=%s&page=%s' % ( "category", url, str(int(page) + 1)) item = xbmcgui.ListItem("[COLOR=orange]" + self.language(9000) + "[/COLOR]", thumbnailImage=self.inext, iconImage=self.inext) xbmcplugin.addDirectoryItem(self.handle, uri, item, True) xbmcplugin.setContent(self.handle, 'movies') xbmcplugin.endOfDirectory(self.handle, True)
def addDirectoryItem(name, parameters={}, pic="DefaultVideoCover.png", lbl2=""): li = xbmcgui.ListItem(label=name, label2=lbl2, iconImage=pic, thumbnailImage=pic) url = sys.argv[0] + '?' + urllib.urlencode(parameters) return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=True)
def getFilmInfo_(self, url): print "*** getFilmInfo for url %s " % url response = common.fetchPage({"link": url}) container = common.parseDOM(response["content"], "div", attrs={"id": "container"}) js_container = common.parseDOM(response["content"], "div", attrs={"class": "section"}) source2 = common.parseDOM(response["content"], "div", attrs={"id": "players"})[0] try: source = common.parseDOM(js_container, "script", attrs={"type": "text/javascript"})[6] except: source = source2 title = self.encode(common.parseDOM(container, "h1")[0]) image = common.parseDOM(container, "img", attrs={"id": "imgbigp"}, ret="src")[0] quality = common.parseDOM(container, "div", attrs={"class": "full-quality"}) movie = source.split('file":"')[-1].split( '"};')[0] if 'file":"' in source else None if (not movie): movie = source2.split('file:"')[-1].split( '"')[0] if 'file:"' in source2 else None playlist = source.split(',pl:"')[-1].split( '"};')[0] if ',pl:"' in source else None playlist = playlist.split( '",')[0] if playlist and '",' in playlist else playlist labels = { 'title': title, 'genre': 'genres', 'plot': 'description', 'playCount': 0, 'year': 1970, 'rating': 0 } if not playlist: links = movie.replace(' or ', ',').split(',') if ( ',' or ' or ') in movie else [movie] image = image if 'http' in image else self.url + image format = quality[0] if quality else '' for i, link in enumerate(links): if ("]" in link): link = link.split("]")[1] if '_720' in link: quality = '720P' else: quality = '480P' link_title = "%s [%s - %s]" % (title, quality, format) link_title = link_title.replace( self.language(5002).encode('utf-8'), '').replace('720 hd', '') uri = sys.argv[0] + '?mode=play&url=%s' % link item = xbmcgui.ListItem(link_title, iconImage=image, thumbnailImage=image) item.setInfo(type='Video', infoLabels={}) item.setProperty('IsPlayable', 'true') xbmcplugin.addDirectoryItem(self.handle, uri, item, False) xbmcplugin.setContent(self.handle, 'files') else: headers = { "Host": self.domain, "Referer": url, "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36" } request = urllib2.Request(playlist, "", headers) request.get_method = lambda: 'GET' response = eval(urllib2.urlopen(request).read()) if 'playlist' in response['playlist'][0]: print "This is a season multiple seasons" for season in response['playlist']: episods = season['playlist'] for episode in episods: etitle = episode['comment'].replace('<br>', ' ') url = episode['file'].split( ',')[-1] if '_720' in episode['file'] else episode[ 'file'].split(',')[0] uri = sys.argv[0] + '?mode=play&url=%s' % url item = xbmcgui.ListItem(etitle.replace('<br>', ' '), iconImage=image, thumbnailImage=image) item.setInfo(type='Video', infoLabels=labels) item.setProperty('IsPlayable', 'true') xbmcplugin.addDirectoryItem(self.handle, uri, item, False) else: print "This is one season" for episode in response['playlist']: try: etitle = episode['comment'] except KeyError: etitle = episode['commet'] url = episode['file'].split(',')[-1] if '_720' in episode[ 'file'] else episode['file'].split(',')[0] uri = sys.argv[0] + '?mode=play&url=%s' % url item = xbmcgui.ListItem(etitle.replace('<br>', ' '), iconImage=image, thumbnailImage=image) item.setInfo(type='Video', infoLabels=labels) item.setProperty('IsPlayable', 'true') xbmcplugin.addDirectoryItem(self.handle, uri, item, False) xbmcplugin.setContent(self.handle, 'episodes') xbmcplugin.endOfDirectory(self.handle, True)
def build_main_menu_listing(self, video_list_ids, user_list_order, actions, build_url): """Builds the video lists (my list, continue watching, etc.) Kodi screen Parameters ---------- video_list_ids : :obj:`dict` of :obj:`str` List of video lists user_list_order : :obj:`list` of :obj:`str` Ordered user lists, to determine what should be displayed in the main menue actions : :obj:`dict` of :obj:`str` Dictionary of actions to build subsequent routes build_url : :obj:`fn` Function to build the subsequent routes Returns ------- bool List could be build """ preselect_items = [] for category in user_list_order: for video_list_id in video_list_ids['user']: if video_list_ids['user'][video_list_id]['name'] == category: label = video_list_ids['user'][video_list_id][ 'displayName'] if category == 'netflixOriginals': label = label.capitalize() li = xbmcgui.ListItem(label=label) li.setProperty('fanart_image', self.default_fanart) # determine action route action = actions['default'] if category in actions.keys(): action = actions[category] # determine if the item should be selected preselect_items.append( (False, True)[category == self.get_main_menu_selection()]) url = build_url({ 'action': action, 'video_list_id': video_list_id, 'type': category }) xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url, listitem=li, isFolder=True) # add recommendations/genres as subfolders (save us some space on the home page) i18n_ids = { 'recommendations': self.get_local_string(30001), 'genres': self.get_local_string(30010) } for type in i18n_ids.keys(): # determine if the lists have contents if len(video_list_ids[type]) > 0: # determine action route action = actions['default'] if type in actions.keys(): action = actions[type] # determine if the item should be selected preselect_items.append( (False, True)[type == self.get_main_menu_selection()]) li_rec = xbmcgui.ListItem(label=i18n_ids[type]) li_rec.setProperty('fanart_image', self.default_fanart) url_rec = build_url({'action': action, 'type': type}) xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url_rec, listitem=li_rec, isFolder=True) # add search as subfolder action = actions['default'] if 'search' in actions.keys(): action = actions[type] li_rec = xbmcgui.ListItem(label=self.get_local_string(30011)) li_rec.setProperty('fanart_image', self.default_fanart) url_rec = build_url({'action': action, 'type': 'search'}) xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url_rec, listitem=li_rec, isFolder=True) # no srting & close xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_UNSORTED) xbmcplugin.endOfDirectory(self.plugin_handle) # (re)select the previously selected main menu entry idx = 1 for item in preselect_items: idx += 1 preselected_list_item = idx if item else None preselected_list_item = idx + 1 if self.get_main_menu_selection( ) == 'search' else preselected_list_item if preselected_list_item != None: xbmc.executebuiltin( 'ActivateWindowAndFocus(%s, %s)' % (str( xbmcgui.Window(xbmcgui.getCurrentWindowId()).getFocusId()), str(preselected_list_item))) return True
def add_item(handle, url, listitem, isFolder): xbmcplugin.addDirectoryItem(handle, url, listitem, isFolder)
def search(self, keyword, external): keyword = urllib.unquote_plus(keyword) if ( external != None) else self.getUserInput() if keyword: # Advanced search: titles only values = { "beforeafter": "after", "catlist[]": 0, "do": "search", "full_search": 0, "replyless": 0, "replylimit": 0, "resorder": "desc", "result_from": 1, "search_start": 1, "searchdate": 0, "searchuser": "", "showposts": 0, "sortby": "date", "story": self.decode(keyword), "subaction": "search", "titleonly": 0 } headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:35.0) Gecko/20100101 Firefox/35.0" } # Find redirected URL redirection = urllib2.Request(self.url, None, headers) url = urllib2.urlopen(redirection).geturl() # Send request to server request = urllib2.Request(url, urllib.urlencode(values), headers) response = urllib2.urlopen(request).read() content = common.parseDOM(response, "div", attrs={"id": "container"}) items = common.parseDOM(content, "div", attrs={"class": "item"}) link_container = common.parseDOM( items, "div", attrs={"class": "main-sliders-title"}) titles = common.parseDOM(link_container, "a") links = common.parseDOM(link_container, "a", ret="href") images = common.parseDOM(items, "img", ret="src") descs = common.parseDOM(items, "i") for i, title in enumerate(titles): uri = sys.argv[0] + '?mode=show&url=%s' % links[i] image = images[i] if 'http' in images[ i] else self.url + images[i] item = xbmcgui.ListItem(self.encode(self.strip(title)), thumbnailImage=image) xbmcplugin.addDirectoryItem(self.handle, uri, item, True) xbmcplugin.setContent(self.handle, 'movies') xbmcplugin.endOfDirectory(self.handle, True) else: self.menu()
def PLAYLINK(name,url): ok=True liz=xbmcgui.ListItem(name, iconImage=icon,thumbnailImage=icon); liz.setInfo( type="Video", infoLabels={ "Title": name } ) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz) xbmc.Player ().play(url, liz, False) return ok
def _fill_media_list( self, videos, page, pages=1, perpage=1, total=1 ): try: ok = True # calculate total items including dummy folders total_items = len( videos ) # if there is more than one page and we're on page one, we create dummy folders for the other videos if ( page == 1 and pages > 1 ): # add our pages to the total items total_items += pages - 1 # enumerate the pages for pageno in range( 2, pages + 1 ): # calculate the starting video startno = ( pageno - 1 ) * perpage + 1 # calculate the ending video endno = pageno * perpage # if there are fewer videos than per_page set endno to total if ( endno > total ): endno = total # create the callback url url = "%s?title=%s&category=%s&page=%d&query=%s" % ( sys.argv[ 0 ], repr( self.args.title ), repr( self.args.category ), pageno, repr( self.args.query ), ) # set the default icon icon = "DefaultFolder.png" # only need to add label and icon, setInfo() and addSortMethod() takes care of label2 listitem=xbmcgui.ListItem( label="%s (%d-%d)" % ( xbmc.getLocalizedString( 3 ), startno, endno, ), iconImage=icon ) # add the folder item to our media list ok = xbmcplugin.addDirectoryItem( handle=int( sys.argv[ 1 ] ), url=url, listitem=listitem, isFolder=True, totalItems=total_items ) # enumerate through the list of videos and add the item to the media list for video in videos: # only add videos with an embeddable video # TODO: Filter formats ? if ( video[ "FileFormat" ] ): # create the title, we use video title and author title = video[ "Title" ].replace( "\\/", "/" ) if ( title.startswith( "'" ) and title.endswith( "'" ) ): title = title[ 1 : -1 ] # thumbnail url thumbnail_url = video[ "Thumbnail" ][ "Url" ].replace( "\\/", "/" ) # plot plot = "no summary was furnished by user" if ( video[ "Summary" ] ): plot = video[ "Summary" ] # format runtime as 00:00 try: runtime = int( video[ "Duration" ] ) except: runtime = "" # video runtime if ( runtime ): runtime = "%02d:%02d" % ( int( runtime / 60 ), runtime % 60 ) # we use studio as the site specifier if ( "yahoo" in video[ "ClickUrl" ] ): studio = "Yahoo" elif ( ".aol." in video[ "ClickUrl" ] ): studio = "AOL" elif ( "youtube" in video[ "ClickUrl" ] ): studio = "Youtube" #elif ( "google" in video[ "ClickUrl" ] ): studio = "Google" else: studio = "Other" # construct our url url = "%s?title=%s&url=%s&category='play_video'" % ( sys.argv[ 0 ], repr( title ), repr( video[ "ClickUrl" ].replace( "\\/", "/" ).replace( "&", "-*-*-" ) ), ) # set the default icon icon = "DefaultVideo.png" # only need to add label, icon and thumbnail, setInfo() and addSortMethod() takes care of label2 listitem=xbmcgui.ListItem( label=title, iconImage=icon, thumbnailImage=thumbnail_url ) # add the different infolabels we want to sort by listitem.setInfo( type="Video", infoLabels={ "Title": title, "Duration": runtime, "Plot": plot, "PlotOutline": plot, "Studio": studio } ) # add the video to the media list ok = xbmcplugin.addDirectoryItem( handle=int( sys.argv[ 1 ] ), url=url, listitem=listitem, isFolder=False, totalItems=total_items ) # if user cancels, call raise to exit loop if ( not ok ): raise except: # oops print error message print "ERROR: %s::%s (%d) - %s" % ( self.__class__.__name__, sys.exc_info()[ 2 ].tb_frame.f_code.co_name, sys.exc_info()[ 2 ].tb_lineno, sys.exc_info()[ 1 ], ) ok = False # if successful and user did not cancel, add all the required sort methods if ( ok ): xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_LABEL ) xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_STUDIO ) xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_VIDEO_RUNTIME ) return ok, total_items
def list_favourites_new(label): items = int(addon.getSetting("favourites_new_count")) xbmcplugin.setPluginCategory(_handle, label) favourites = get_favourites(others=0) episodes = {} episodes_ordered = {} for showId in favourites: show = favourites[showId] data = call_api(url="https://api.mujrozhlas.cz/shows/" + showId + "/episodes?sort=-since&page[limit]=" + str(items)) if "err" in data: xbmcgui.Dialog().notification( "ČRo", "Pořad " + show["title"] + " nebyl nalezený", xbmcgui.NOTIFICATION_ERROR, 4000) # sys.exit() if "data" in data and len(data["data"]) > 0: for episode in data["data"]: if "attributes" in episode and "title" in episode[ "attributes"] and len( episode["attributes"]["title"]) > 0: starttime = parse_date(episode["attributes"]["since"]) starttime_ts = time.mktime(starttime.timetuple()) episodes_ordered.update({episode["id"]: starttime_ts}) if "mirroredSerial" in episode[ "attributes"] and "totalParts" in episode[ "attributes"][ "mirroredSerial"] and "part" in episode[ "attributes"]: parts = " (" + str( episode["attributes"]["part"]) + "/" + str( episode["attributes"]["mirroredSerial"] ["totalParts"]) + ") " else: parts = "" title = episode["attributes"][ "title"] + parts + " (" + starttime.strftime( "%d.%m.%Y %H:%M") + ")" link = episode["attributes"]["audioLinks"][0]["url"] episodes.update({ episode["id"]: { "showId": showId, "link": link, "img": show["img"], "tvshowtitle": show["title"], "title": title, "aired": starttime.strftime("%Y-%m-%d"), "director": [show["director"]], "plot": show["description"], "studio": show["station"] } }) if len(episodes) > 0: for key in sorted(episodes_ordered, key=episodes_ordered.get, reverse=True): list_item = xbmcgui.ListItem(label=episodes[key]["title"]) list_item.setArt({ "thumb": episodes[key]["img"], "icon": episodes[key]["img"] }) list_item.setInfo( "video", { "tvshowtitle": episodes[key]["tvshowtitle"], "title": episodes[key]["title"], "aired": episodes[key]["aired"], "director": episodes[key]["director"], "plot": episodes[key]["plot"], "studio": episodes[key]["studio"] }) list_item.setProperty("IsPlayable", "true") list_item.setContentLookup(False) url = get_url(action='play', url=encode(episodes[key]["link"]), showId=episodes[key]["showId"], episodeId=key, title=encode(episodes[key]["title"]), img=episodes[key]["img"]) if PY2: xbmcplugin.addDirectoryItem(_handle, url, list_item, False) else: xbmcplugin.addDirectoryItem(_handle, url, list_item, True) xbmcplugin.endOfDirectory(_handle)
def add_item(self, queries, infolabels, contextmenu_items='', context_replace=False, img='', fanart='', resolved=False, total_items=0, playlist=False, item_type='video', is_folder=False): ''' Adds an item to the list of entries to be displayed in XBMC or to a playlist. Use this method when you want users to be able to select this item to start playback of a media file. ``queries`` is a dict that will be sent back to the addon when this item is selected:: add_item({'host': 'youtube.com', 'media_id': 'ABC123XYZ'}, {'title': 'A youtube vid'}) will add a link to:: plugin://your.plugin.id/?host=youtube.com&media_id=ABC123XYZ .. seealso:: :meth:`add_music_item`, :meth:`add_video_item`, :meth:`add_directory` Args: queries (dict): A set of keys/values to be sent to the addon when the user selects this item. infolabels (dict): A dictionary of information about this media (see the `XBMC Wiki InfoLabels entry <http://wiki.xbmc.org/?title=InfoLabels>`_). Kwargs: contextmenu_items (list): A list of contextmenu items context_replace (bool): To replace the xbmc default contextmenu items img (str): A URL to an image file to be used as an icon for this entry. fanart (str): A URL to a fanart image for this entry. resolved (str): If not empty, ``queries`` will be ignored and instead the added item will be the exact contentes of ``resolved``. total_items (int): Total number of items to be added in this list. If supplied it enables XBMC to show a progress bar as the list of items is being built. playlist (playlist object): If ``False`` (default), the item will be added to the list of entries to be displayed in this directory. If a playlist object is passed (see :meth:`get_playlist`) then the item will be added to the playlist instead item_type (str): The type of item to add (eg. 'music', 'video' or 'pictures') ''' infolabels = self.unescape_dict(infolabels) if not resolved: if not is_folder: queries['play'] = 'True' play = self.build_plugin_url(queries) else: play = resolved listitem = xbmcgui.ListItem(infolabels['title']) listitem.setInfo(item_type, infolabels) listitem.setProperty('IsPlayable', 'true') listitem.setProperty('fanart_image', fanart) try: listitem.setArt({'thumb': img}) except: listitem.setThumbnailImage(img) self.log_debug('t0mm0-addon.py: setThumbnailImage is deprecated') if contextmenu_items: listitem.addContextMenuItems(contextmenu_items, replaceItems=context_replace) if playlist is not False: self.log_debug('adding item: %s - %s to playlist' % \ (infolabels['title'], play)) playlist.add(play, listitem) else: self.log_debug('adding item: %s - %s' % (infolabels['title'], play)) xbmcplugin.addDirectoryItem(self.handle, play, listitem, isFolder=is_folder, totalItems=total_items)
def addDir(url, title, icon, fanart): li = xbmcgui.ListItem(title, iconImage=icon) li.setProperty("Fanart_Image", fanart) xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li)
def list_favourites(label, others=0): xbmcplugin.setPluginCategory(_handle, label) favourites = get_favourites(int(others)) favourites_ordered = {} for key in favourites: favourites_ordered.update({key: favourites[key]["title"]}) for showId in sorted(favourites_ordered, key=favourites_ordered.get): show = favourites[showId] if addon.getSetting( "hide_unlistened_favourites") == "false" and others == 0: unlistened = get_unlistened_count(showId) if unlistened > 0: list_item = xbmcgui.ListItem(label=show["title"] + " (" + str(unlistened) + decode(" nových)")) elif unlistened == 0: list_item = xbmcgui.ListItem(label=show["title"]) else: list_item = xbmcgui.ListItem(label=show["title"] + ' (nenalezený pořad)') else: list_item = xbmcgui.ListItem(label=show["title"]) list_item.setArt({"thumb": show["img"], "icon": show["img"]}) list_item.setInfo( "video", { "title": show["title"], "director": [show["director"]], "plot": show["description"], "studio": show["station"] }) if len(show["cast"]) > 0: list_item.setInfo("video", {"cast": show["cast"]}) menus = [( "Odstranit z oblíbených", "RunPlugin(plugin://plugin.audio.cro?action=delete_favourites&showId=" + str(show["id"]) + ")")] if others == 0: menus.append(( "Přesunout do ostatních", "RunPlugin(plugin://plugin.audio.cro?action=set_others&showId=" + str(show["id"]) + "&val=1" + ")")) else: menus.append(( "Přesunout z ostatních", "RunPlugin(plugin://plugin.audio.cro?action=set_others&showId=" + str(show["id"]) + "&val=0" + ")")) if addon.getSetting( "hide_unlistened_favourites") == "false" and others == 0: menus.append(( "Označit epizody jako poslechnuté", "RunPlugin(plugin://plugin.audio.cro?action=set_listened_all&showId=" + str(show["id"]) + ")")) list_item.addContextMenuItems(menus) if addon.getSetting( "hide_unlistened_favourites") == "false" and others == 0: url = get_url(action='list_show', showId=show["id"], page=1, label=encode(show["title"]), mark_new=1) else: url = get_url(action='list_show', showId=show["id"], page=1, label=encode(show["title"]), mark_new=0) list_item.setContentLookup(False) xbmcplugin.addDirectoryItem(_handle, url, list_item, True) xbmcplugin.endOfDirectory(_handle, cacheToDisc=False)
TvdbApi.getFromDict(data, ['Details', 'writers'], '')) meta['director'] = ', '.join( TvdbApi.getFromDict(data, ['Details', 'directors'], '')) meta['studio'] = TvdbApi.getFromDict(data, ['Show', 'network'], '') meta['mpaa'] = TvdbApi.getFromDict(data, ['Show', 'rating'], '') meta['episode_id'] = TvdbApi.getFromDict(data, ['Details', 'id'], '') meta['year'] = TvdbApi.getFromDict(data, ['Show', 'firstAired'], '')[:4] meta['status'] = TvdbApi.getFromDict(data, ['Show', 'status'], '') #meta['cast'] = [] #actors = [{'name': 'Tom Cruise', 'role': 'Himself', 'thumbnail': ''}, {'name': 'Actor 2', 'role': 'role 2'}] actors = data.get('Actors', []) actors = TvdbApi.CacheActorImages(actors, cache.actor_cache_dir) for value in TvdbApi.getFromDict(data, ['Details', 'guestStars'], ''): actors.append(dict({'name': value, 'role': 'Guest Star'})) if actors: list_item.setCast(actors) except: meta['tvdb_id'] = str(tvdbid) meta['tvshowtitle'] = show_name meta['title'] = name meta['season'] = int(season) meta['episode'] = int(episode) list_item.setInfo(type="Video", infoLabels=meta) list_item.addContextMenuItems(context_items, replaceItems=True) xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=return_url, listitem=list_item, isFolder=False, totalItems=total_items)
item['title'] = normalizeString(xbmc.getInfoLabel( "VideoPlayer.Title")) # no original title, get just Title if item['episode'].lower().find("s") > -1: # Check if season is "Special" item['season'] = "0" # item['episode'] = item['episode'][-1:] if item['file_original_path'].find("http") > -1: item['temp'] = True elif item['file_original_path'].find("rar://") > -1: item['rar'] = True item['file_original_path'] = os.path.dirname( item['file_original_path'][6:]) elif item['file_original_path'].find("stack://") > -1: stackPath = item['file_original_path'].split(" , ") item['file_original_path'] = stackPath[0][8:] Search(item) elif params['action'] == 'download': subs = download(params["link"]) for sub in subs: listitem = xbmcgui.ListItem(label=sub) xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=sub, listitem=listitem, isFolder=False) xbmcplugin.endOfDirectory(int(sys.argv[1])) # send end of directory to XBMC
def Serch(url, title=""): http = getURL(url) #ss="<li class = 'playlist'>" #es="Setup the player to autoplay" #cut1=' |'+mfindal(http, ss, es)[0].replace("'#' data-src=", "") #http=http.replace("<li class='playlist'>","<li class = 'playlist'>") ss = "<li class = 'playlist'>" es = '</a><hr/></li>' L1 = mfindal(http, ss, es) fl = 0 if len(L1) == 0: ss = "<li class='playlist'>" es = '</a></li></ol>' L1 = mfindal(http, ss, es) fl = 1 for i in L1: ss = 'http://d.mds-fm.ru' es = '.mp3">' L2 = mfindal(i, ss, es) ss = '.mp3">' es = '</a>' try: title = mfindal(i, ss, es)[0][len(ss):] except: pass ss = '</a><p>' es = '</p></li>' try: plot = mfindal(i, ss, es)[0][len(ss):] except: plot = "" if len(L2) > 1: k = 0 for j in L2: k += 1 url = j + ".mp3" img = thumb title2 = Format(title) + " ч. " + str(k) item = xbmcgui.ListItem(title2, iconImage=img, thumbnailImage=img) item.setInfo(type="music", infoLabels={ "Title": title.replace(".", "\n"), "Comment": plot, "album": plot }) item.setProperty('IsPlayable', 'true') xbmcplugin.addDirectoryItem(pluginhandle, url, item, False) else: url = L2[0] + ".mp3" img = thumb item = xbmcgui.ListItem(Format(title), iconImage=img, thumbnailImage=img) item.setInfo(type="music", infoLabels={ "Title": title.replace(".", "\n"), "album": plot, "Comment": plot }) item.setProperty('IsPlayable', 'true') xbmcplugin.addDirectoryItem(pluginhandle, url, item, False) if fl == 1 and len(L2) == 1: xbmc.Player().play(url) else: xbmcplugin.endOfDirectory(pluginhandle)
my_stations = readFile(mystations_path) else: writeFile(mystations_path, my_stations) mode = args.get('mode', None) if mode is None: localUrl = build_url({ 'mode': 'stations', 'url': 'http://www.radio-browser.info/webservice/json/stations/topclick/100' }) li = xbmcgui.ListItem(LANGUAGE(32000), iconImage='DefaultFolder.png') xbmcplugin.addDirectoryItem(handle=addon_handle, url=localUrl, listitem=li, isFolder=True) localUrl = build_url({ 'mode': 'stations', 'url': 'http://www.radio-browser.info/webservice/json/stations/topvote/100' }) li = xbmcgui.ListItem(LANGUAGE(32001), iconImage='DefaultFolder.png') xbmcplugin.addDirectoryItem(handle=addon_handle, url=localUrl, listitem=li, isFolder=True) localUrl = build_url({
def readFolder(params): print params http = GET(params['href']) beautifulSoup = BeautifulSoup(http) content = beautifulSoup.findAll('div', attrs={'class': 'quote'}) try: pist=content[0] except: pist=None z=None try: img='http://serialonline.net%s'%re.findall('left--><img src="(.+)" align="left" alt=',http)[0] except: img="" if pist: dist=pist.findAll('a') for n in dist: #print n #print str(n.find('b')).replace('<b>','').replace('</b>','') li = xbmcgui.ListItem(str(n.find('b')).replace('<b>','').replace('</b>',''), img, img) uri = construct_request({ 'href': n['href'], 'func': 'readFolder' }) #print n['href'] xbmcplugin.addDirectoryItem(hos, uri, li, True) z=True header=re.findall('<h1>[^/]+</h1>',http)[0].replace('</h1>','').replace('<h1>','').decode('cp1251').encode('utf-8') header='[COLOR FF00FF00]%s:[/COLOR]'%header if z: li = xbmcgui.ListItem(' ', addon_fanart, addon_icon) uri = construct_request({ 'filr': None }) xbmcplugin.addDirectoryItem(hos, uri, li, False) li = xbmcgui.ListItem(header, addon_fanart, addon_icon) uri = construct_request({ 'filr': None }) xbmcplugin.addDirectoryItem(hos, uri, li, False) # need to find flashvars="pl=http://serialonline.net/pl/810f6cc0b9e3e3cdd9c8557d09ac0ac2/beskontrolnye_1.txt&config=http://s playlist=re.findall('http://serialonline.net/pl/[0-9a-z]+/[^/]+.txt',http) if playlist==[]: playlist=re.findall('http://cdn.serialonline.net/pl/[0-9a-z]+/[^/]+.txt',http) fplaylist= playlist[0] files= GET(fplaylist) #print files flist=json.loads(files) #style="display:inline;"><!--dle_image_begin:(.+?)|left--> for index in flist['playlist']: li = xbmcgui.ListItem(index['comment'], img, img) li.setProperty('IsPlayable', 'true') uri = construct_request({ 'url': index['file'], 'func': 'play' }) xbmcplugin.addDirectoryItem(hos, uri, li, False) #li = xbmcgui.ListItem(playlist[0].split['='][1], addon_fanart, addon_icon) #uri = construct_request({ # 'func': 'readFolder' #}) #print n['href'] #xbmcplugin.addDirectoryItem(hos, uri, li, True) xbmcplugin.setContent(hos, 'movies') xbmcplugin.endOfDirectory(hos)
def Root(): title = "Поиск" url = "" img = thumb uri = sys.argv[0] + '?mode=title' uri += '&url=' + urllib.quote_plus(url) uri += '&name=' + urllib.quote_plus(title) uri += '&img=' + urllib.quote_plus(img) item = xbmcgui.ListItem(title, iconImage=img, thumbnailImage=img) item.setInfo(type="Music", infoLabels={"Title": title}) xbmcplugin.addDirectoryItem(pluginhandle, uri, item, True) title = "Автор" url = "" img = thumb uri = sys.argv[0] + '?mode=author' uri += '&url=' + urllib.quote_plus(url) uri += '&name=' + urllib.quote_plus(title) uri += '&img=' + urllib.quote_plus(img) item = xbmcgui.ListItem(title, iconImage=img, thumbnailImage=img) item.setInfo(type="Music", infoLabels={"Title": title}) #xbmcplugin.addDirectoryItem(pluginhandle, uri, item, True) title = "Жанры" url = "" img = thumb uri = sys.argv[0] + '?mode=genres' uri += '&url=' + urllib.quote_plus(url) uri += '&name=' + urllib.quote_plus(title) uri += '&img=' + urllib.quote_plus(img) item = xbmcgui.ListItem(title, iconImage=img, thumbnailImage=img) item.setInfo(type="Music", infoLabels={"Title": title}) xbmcplugin.addDirectoryItem(pluginhandle, uri, item, True) title = "Сюжетные ходы" url = "" img = thumb uri = sys.argv[0] + '?mode=plot' uri += '&url=' + urllib.quote_plus(url) uri += '&name=' + urllib.quote_plus(title) uri += '&img=' + urllib.quote_plus(img) item = xbmcgui.ListItem(title, iconImage=img, thumbnailImage=img) item.setInfo(type="Music", infoLabels={"Title": title}) xbmcplugin.addDirectoryItem(pluginhandle, uri, item, True) title = "Место действия" url = "" img = thumb uri = sys.argv[0] + '?mode=scene' uri += '&url=' + urllib.quote_plus(url) uri += '&name=' + urllib.quote_plus(title) uri += '&img=' + urllib.quote_plus(img) item = xbmcgui.ListItem(title, iconImage=img, thumbnailImage=img) item.setInfo(type="Music", infoLabels={"Title": title}) xbmcplugin.addDirectoryItem(pluginhandle, uri, item, True) title = "Время действия" url = "" img = thumb uri = sys.argv[0] + '?mode=time' uri += '&url=' + urllib.quote_plus(url) uri += '&name=' + urllib.quote_plus(title) uri += '&img=' + urllib.quote_plus(img) item = xbmcgui.ListItem(title, iconImage=img, thumbnailImage=img) item.setInfo(type="Music", infoLabels={"Title": title}) xbmcplugin.addDirectoryItem(pluginhandle, uri, item, True) xbmcplugin.endOfDirectory(pluginhandle)