本文整理汇总了Python中simplecache.SimpleCache.get方法的典型用法代码示例。如果您正苦于以下问题:Python SimpleCache.get方法的具体用法?Python SimpleCache.get怎么用?Python SimpleCache.get使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类simplecache.SimpleCache
的用法示例。
在下文中一共展示了SimpleCache.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_simple_cache
# 需要导入模块: from simplecache import SimpleCache [as 别名]
# 或者: from simplecache.SimpleCache import get [as 别名]
def test_simple_cache():
cache = SimpleCache(0.1)
assert cache.get("hamster") == None
cache.save("yumyum", "hamster")
assert cache.get("hamster") == "yumyum"
sleep(0.1)
assert cache.get("hamster") == None
示例2: Newsy
# 需要导入模块: from simplecache import SimpleCache [as 别名]
# 或者: from simplecache.SimpleCache import get [as 别名]
class Newsy(object):
def __init__(self):
log('__init__')
self.cache = SimpleCache()
def openURL(self, url):
log('openURL, url = ' + str(url))
try:
cacheResponse = self.cache.get(ADDON_NAME + '.openURL, url = %s'%url)
if not cacheResponse:
request = urllib2.Request(url)
request.add_header('User-Agent','Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)')
response = urllib2.urlopen(request, timeout=TIMEOUT).read()
self.cache.set(ADDON_NAME + '.openURL, url = %s'%url, response, expiration=datetime.timedelta(hours=6))
return self.cache.get(ADDON_NAME + '.openURL, url = %s'%url)
except urllib2.URLError, e:
log("openURL Failed! " + str(e), xbmc.LOGERROR)
except socket.timeout, e:
log("openURL Failed! " + str(e), xbmc.LOGERROR)
示例3: FunnyOrDie
# 需要导入模块: from simplecache import SimpleCache [as 别名]
# 或者: from simplecache.SimpleCache import get [as 别名]
class FunnyOrDie(object):
def __init__(self):
log('__init__')
self.cache = SimpleCache()
def openURL(self, url):
log('openURL, url = ' + str(url))
try:
cacheresponse = self.cache.get(ADDON_NAME + '.openURL, url = %s'%url)
if not cacheresponse:
request = urllib2.Request(url)
response = urllib2.urlopen(request, timeout = TIMEOUT).read()
self.cache.set(ADDON_NAME + '.openURL, url = %s'%url, response, expiration=datetime.timedelta(days=1))
return self.cache.get(ADDON_NAME + '.openURL, url = %s'%url)
except Exception as e:
log("openURL Failed! " + str(e), xbmc.LOGERROR)
xbmcgui.Dialog().notification(ADDON_NAME, LANGUAGE(30001), ICON, 4000)
return ''
@use_cache(1)
def getData(self):
try:
soup = BeautifulSoup(self.openURL(CAT_URL), "html.parser")
return json.loads(re.compile("data-react-props='(.*?)'>", re.DOTALL ).findall(str(soup('div' , {'class': 'action-bar'})))[0])
except Exception as e:
log("getData Failed! " + str(e), xbmc.LOGERROR)
xbmcgui.Dialog().notification(ADDON_NAME, LANGUAGE(30001), ICON, 4000)
return None
def getSorts(self):
log('getSorts')
getData = self.getData()
if getData is None: return
for sort in getData['sortOptions']: yield (sort['title'], '%s/%s'%(sort['key'], sort['date_filter']), 0)
def getCategories(self, url):
log('getCategories')
getData = self.getData()
if getData is None: return
for cat in getData['categoryOptions']: yield (cat['title'], json.dumps({"url":'%s/%s/%s'%(cat['category'], cat['grade'], url), "page":1}), 1)
def buildMenu(self, items, yt=False):
for item in items: self.addDir(*item)
if yt: self.addYoutube("Browse Youtube" , 'plugin://plugin.video.youtube/user/funnyordie/')
def browseVideos(self, name, myurl):
log('browse, ' + name)
myurl = json.loads(myurl)
url = myurl['url']
page = myurl['page']
soup = BeautifulSoup(self.openURL(VID_URL%(url,page)), "html.parser")
videos = soup('div' , {'class': 'media-preview-crop'})
if len(videos) == 0: return
for video in videos:
vidurl= BASE_URL + video.find_all('a')[0].attrs['href']
title = video.find_all('a')[0].attrs['title']
thumb = (video.find_all('a')[0]('img' , {'class': 'media-preview-thumbnail'})[0].attrs['data-src'] or ICON)
duration = video.find_all('a')[0]('span' , {'class': 'media-video-duration'})[0].get_text()
try:
runtime = duration.split(':')
if len(runtime) == 3:
h, m, s = runtime
duration = int(h) * 3600 + int(m) * 60 + int(s)
else:
m, s = runtime
duration = int(m) * 60 + int(s)
except: duration = duration
infoLabels = {"mediatype":"episode","label":title ,"title":title,"duration":duration,"plot":title}
infoArt = {"thumb":thumb,"poster":thumb,"fanart":FANART,"icon":ICON,"logo":ICON}
CONTENT_TYPE = 'episodes'
self.addLink(title, vidurl, 9, infoLabels, infoArt, len(videos))
myurl = json.dumps({"url":url,"page":page + 1})
self.addDir('>> Next', myurl, 1)
def playVideo(self, name, url, liz=None):
log('playVideo')
info = getVideoInfo(url,QUALITY,True)
if info is None: return
info = info.streams()
url = info[0]['xbmc_url']
liz = xbmcgui.ListItem(name, path=url)
if 'subtitles' in info[0]['ytdl_format']: liz.setSubtitles([x['url'] for x in info[0]['ytdl_format']['subtitles'].get('en','') if 'url' in x])
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
def addYoutube(self, name, url):
liz=xbmcgui.ListItem(name)
liz.setProperty('IsPlayable', 'false')
liz.setInfo(type="Video", infoLabels={"label":name,"title":name} )
liz.setArt({'thumb':ICON,'fanart':FANART})
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz,isFolder=True)
#.........这里部分代码省略.........
示例4: NewsBlender
# 需要导入模块: from simplecache import SimpleCache [as 别名]
# 或者: from simplecache.SimpleCache import get [as 别名]
class NewsBlender(object):
def __init__(self):
self.cache = SimpleCache()
self.sources = self.openURL(SOURCES_URL).get('sources','')
def openURL(self, url):
log('openURL, url = ' + url)
try:
cacheresponse = self.cache.get(ADDON_NAME + '.openURL, url = %s'%url)
if not cacheresponse:
request = urllib2.Request(url)
request.add_header('User-Agent','Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)')
request.add_header('Accept-type', 'application/json')
response = urllib2.urlopen(request, timeout = TIMEOUT).read()
self.cache.set(ADDON_NAME + '.openURL, url = %s'%url, response, expiration=datetime.timedelta(hours=1))
return json.loads(self.cache.get(ADDON_NAME + '.openURL, url = %s'%url))
except Exception as e:
log("openURL Failed! " + str(e), xbmc.LOGERROR)
xbmcgui.Dialog().notification(ADDON_NAME, LANGUAGE(30001), ICON, 4000)
return ''
def buildMenu(self):
for idx, item in enumerate(MAIN_MENU): self.addDir(item,'',idx)
def buildCategory(self):
category = collections.Counter([x['category'] for x in self.sources])
for category, value in sorted(category.iteritems()): self.addDir(category.title(),category,4)
def buildCountry(self):
countries = collections.Counter([x['country'] for x in self.sources])
for country, value in sorted(countries.iteritems()): self.addDir(getRegionName(country),country,6)
def buildLanguage(self):
languages = collections.Counter([x['language'] for x in self.sources])
for language, value in sorted(languages.iteritems()): self.addDir(getLanguageName(language),language,7)
def buildSource(self, items=None):
if items is None: items = self.sources
for source in items:
label = source['name']
thumb = (LOGO_URL%source['url'] or ICON)
infoLabels = {"mediatype":"files","label":label,"title":label,"genre":source.get('category','news'),"plot":source.get('description','news')}
infoArt = {"thumb":thumb,"poster":thumb,"fanart":FANART,"icon":ICON,"logo":ICON}
self.addDir(label, source['id'], 5, infoLabels, infoArt)
def browseCategory(self, url):
self.buildSource(self.openURL(SOURCES_URL + '&category=%s'%url).get('sources',''))
def browseCountry(self, url):
self.buildSource(self.openURL(SOURCES_URL + '&country=%s'%url).get('sources',''))
def browseLanguage(self, url):
self.buildSource(self.openURL(SOURCES_URL + '&language=%s'%url).get('sources',''))
def browseTop(self, url):
self.browse(self.newsArticles.get_by_top(url).get('sources',''))
def browseLatest(self, url):
self.browse(self.newsArticles.get_by_latest(url).get('sources',''))
def browsePopular(self, url):
self.browse(self.newsArticles.get_by_popular(url).get('sources',''))
def search(self, name, url):
kb = xbmc.Keyboard('', LANGUAGE(30005)%name)
xbmc.sleep(1000)
kb.doModal()
if kb.isConfirmed():
url = (EVRYTHING_URL + '&q=%s&sources=%s'%(urllib.quote_plus(kb.getText()),url)).split('|')[0]
try: self.browseArticles(name, url, self.openURL(url).get('articles',''), False)
except Exception as e: log('search, failed ' + str(e), xbmc.LOGERROR)
def buildArticles(self, name, url):
self.browseArticles(name, url, self.openURL(HEADLINE_URL + '&sources=%s'%url).get('articles',''))
def browseArticles(self, name, url, items, search=True):
tmpList = []
for idx, item in enumerate(items):
info = self.getVideo(item['url'])
if info is None or len(info) == 0: continue
source = item['source']['name']
label = item['title']
thumb = item['urlToImage']
plot = item['description']
try: aired = item['publishedAt'].split('T')[0]
#.........这里部分代码省略.........
示例5: MultiChannel
# 需要导入模块: from simplecache import SimpleCache [as 别名]
# 或者: from simplecache.SimpleCache import get [as 别名]
class MultiChannel(object):
def __init__(self):
log('__init__')
self.cache = SimpleCache()
def openURL(self, url):
log('openURL, url = ' + str(url))
try:
cacheresponse = self.cache.get(ADDON_NAME + '.openURL, url = %s'%url)
if not cacheresponse:
request = urllib2.Request(url)
request.add_header('User-Agent','Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)')
cacheresponse = urllib2.urlopen(request, timeout = TIMEOUT).read()
self.cache.set(ADDON_NAME + '.openURL, url = %s'%url, cacheresponse, expiration=datetime.timedelta(hours=1))
return cacheresponse
except Exception as e:
log("openURL Failed! " + str(e), xbmc.LOGERROR)
xbmcgui.Dialog().notification(ADDON_NAME, LANGUAGE(30001), ICON, 4000)
return ''
def buildMenu(self):
self.addDir(LANGUAGE(30003), BASE_VID, 1)
self.addYoutube(LANGUAGE(30004), 'plugin://plugin.video.youtube/channel/UC0VOh1nD6Tlq_5gjkpSecWA/')
def browse(self, url):
log('browse')
soup = BeautifulSoup(self.openURL(url), "html.parser")
videos = soup('div', {'class': 'l-grid--item'})
for video in videos:
link = video('div', {'class': 'm-card--media'})[0].find('a').attrs['href']
if not link.startswith('/video/'): continue
link = BASE_URL+link
label = video('div', {'class': 'm-card--media'})[0].find('a').attrs['title']
thumb = video('div', {'class': 'm-card--media'})[0].find('source').attrs['data-srcset']
try: plot = video('div', {'class': 'm-card--content'})[0].find('p').get_text()
except: plot = label
infoLabels = {"mediatype":"episode","label":label,"title":label,"plot":plot,"genre":'News'}
infoArt = {"thumb":thumb,"poster":thumb,"fanart":FANART,"icon":ICON,"logo":ICON}
self.addLink(label, link, 9, infoLabels, infoArt, len(videos))
next = soup('li', {'class': 'pager-next'})
if len(next) == 0: return
next_url = BASE_URL + next[0].find('a').attrs['href']
next_label = (next[0].find('a').attrs['title'] or next[0].get_text())
self.addDir(next_label, next_url, 1)
def playVideo(self, name, url, liz=None):
log('playVideo')
info = getVideoInfo(url,QUALITY,True)
if info is None: return
info = info.streams()
url = info[0]['xbmc_url']
liz = xbmcgui.ListItem(name, path=url)
if 'subtitles' in info[0]['ytdl_format']: liz.setSubtitles([x['url'] for x in info[0]['ytdl_format']['subtitles'].get('en','') if 'url' in x])
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
def addYoutube(self, name, url):
liz=xbmcgui.ListItem(name)
liz.setProperty('IsPlayable', 'false')
liz.setInfo(type="Video", infoLabels={"label":name,"title":name} )
liz.setArt({'thumb':ICON,'fanart':FANART})
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz,isFolder=True)
def addLink(self, name, u, mode, infoList=False, infoArt=False, total=0):
name = name.encode("utf-8")
log('addLink, name = ' + name)
liz=xbmcgui.ListItem(name)
liz.setProperty('IsPlayable', 'true')
if infoList == False: liz.setInfo(type="Video", infoLabels={"mediatype":"video","label":name,"title":name})
else: liz.setInfo(type="Video", infoLabels=infoList)
if infoArt == False: liz.setArt({'thumb':ICON,'fanart':FANART})
else: liz.setArt(infoArt)
u=sys.argv[0]+"?url="+urllib.quote_plus(u)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,totalItems=total)
def addDir(self, name, u, mode, infoList=False, infoArt=False):
name = name.encode("utf-8")
log('addDir, name = ' + name)
liz=xbmcgui.ListItem(name)
liz.setProperty('IsPlayable', 'false')
if infoList == False: liz.setInfo(type="Video", infoLabels={"mediatype":"video","label":name,"title":name})
else: liz.setInfo(type="Video", infoLabels=infoList)
if infoArt == False: liz.setArt({'thumb':ICON,'fanart':FANART})
else: liz.setArt(infoArt)
u=sys.argv[0]+"?url="+urllib.quote_plus(u)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
示例6: SimpleCache
# 需要导入模块: from simplecache import SimpleCache [as 别名]
# 或者: from simplecache.SimpleCache import get [as 别名]
'plot': j['opis'].encode('utf-8'),
'mediatype':'video',
'tracknumber': i
}
li.setInfo('video', itemArgs)
playlist.add(url=j['stream_url'],listitem=li)
player.play(item=playlist,startpos=channel_index)
player.seekTime(channel_offset)
addon_name = 'plugin.video.carnet-meduza'
addon=xbmcaddon.Addon(addon_name)
# get username/apikey from settings
aai_username = addon.getSetting('aai_username')
#get some data from cache
simplecache = SimpleCache()
tmp_store = simplecache.get(addon_name + '.tmp_store')
dialog = xbmcgui.Dialog()
if not tmp_store:
initcheck = initCheck(addon_name)
api_key, dev_reg_status = initcheck.store_key()
addon.setSetting('apikey',api_key)
#if aai_username missing open settings, otherwise start device registration
if not aai_username and dev_reg_status == 'not_reg':
info_dialog_msg = addon.getLocalizedString(30214)
dialog.notification('CARNet Meduza', info_dialog_msg, xbmcgui.NOTIFICATION_INFO, 4000)
xbmcaddon.Addon().openSettings()
elif dev_reg_status == 'not_reg':
reg_response = initcheck.dev_reg(api_key)
initcheck.check_reg(reg_response, api_key)
else:
示例7: CNN
# 需要导入模块: from simplecache import SimpleCache [as 别名]
# 或者: from simplecache.SimpleCache import get [as 别名]
class CNN(object):
def __init__(self):
log('__init__')
self.cache = SimpleCache()
def openURL(self, url):
log('openURL, url = ' + str(url))
try:
cacheresponse = self.cache.get(ADDON_NAME + '.openURL, url = %s'%url)
if not cacheresponse:
request = urllib2.Request(url)
response = urllib2.urlopen(request, timeout = TIMEOUT).read()
self.cache.set(ADDON_NAME + '.openURL, url = %s'%url, response, expiration=datetime.timedelta(hours=1))
return self.cache.get(ADDON_NAME + '.openURL, url = %s'%url)
except Exception as e:
log("openURL Failed! " + str(e), xbmc.LOGERROR)
xbmcgui.Dialog().notification(ADDON_NAME, LANGUAGE(30001), ICON, 4000)
return ''
def buildMenu(self):
for item in MENU_ITEMS: self.addDir(item, JSON_URL%item.lower(), 1)
self.addDir('Digital Shorts', SHORTS_URL, 2)
self.addYoutube("Browse Youtube" , 'plugin://plugin.video.youtube/user/CNN/')
def browse(self, name, url):
log('browse, ' + name)
response = json.loads(self.openURL(url))
items = response['videos']
for item in items:
try:
runtime = item['duration'].split(':')
if len(runtime) == 3:
h, m, s = runtime
duration = int(h) * 3600 + int(m) * 60 + int(s)
else:
m, s = runtime
duration = int(m) * 60 + int(s)
except: duration = item['duration']
label = item['headline']
thumb = 'http:%s'%item['fullsize_url']
infoLabels = {"mediatype":"episode","label":label ,"title":label,"duration":duration,"plot":item['description'],"genre":"News"}
infoArt = {"thumb":thumb,"poster":thumb,"fanart":FANART,"icon":ICON,"logo":ICON}
self.addLink(label, BASE_URL + item['clickback_url'], 9, infoLabels, infoArt, len(items))
def browseShorts(self, name, url):
log('browseShorts, ' + name)
soup = BeautifulSoup(self.openURL(url), "html.parser")
videos = soup('article', {'class': 'cd'})
for video in videos:
vid_url = video('h3', {'class': 'cd__headline'})[0].find('a')['href']
if not vid_url.startswith('http'): vid_url = BASE_URL + vid_url
if vid_url.startswith('http://cnn.it'): continue
if not '/video' in vid_url: continue
thumb = (video('div', {'class': 'cd__wrapper'})[0])
try: thumb = 'http:' + (json.loads((re.search('"large":(.*?)"},', str(thumb)).group(1) + '"}'))['uri'])
except: thumb = ICON
results = video('div', {'class': 'cd__content'})[0]
try: title = results('div', {'class': 'cd__kicker'})[0].get_text()
except: title = None
subtitle = results('span', {'class': 'cd__headline-text'})[0].get_text()
label = '%s - %s'%(title, subtitle) if title is not None else subtitle
try: plot = results('div', {'class': 'cd__description'})[0].get_text()
except: plot = subtitle
duration = 0
infoLabels = {"mediatype":"episode","label":label ,"title":label,"duration":duration,"plot":plot}
infoArt = {"thumb":thumb,"poster":thumb,"fanart":FANART,"icon":ICON,"logo":ICON}
self.addLink(label, vid_url, 9, infoLabels, infoArt, len(videos))
def playVideo(self, name, url, liz=None):
log('playVideo')
info = getVideoInfo(url,QUALITY,True)
if info is None: return
info = info.streams()
url = info[0]['xbmc_url']
liz = xbmcgui.ListItem(name, path=url)
if 'subtitles' in info[0]['ytdl_format']: liz.setSubtitles([x['url'] for x in info[0]['ytdl_format']['subtitles'].get('en','') if 'url' in x])
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
def addYoutube(self, name, url):
liz=xbmcgui.ListItem(name)
liz.setProperty('IsPlayable', 'false')
liz.setInfo(type="Video", infoLabels={"label":name,"title":name} )
liz.setArt({'thumb':ICON,'fanart':FANART})
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz,isFolder=True)
def addLink(self, name, u, mode, infoList=False, infoArt=False, total=0):
name = name.encode("utf-8")
log('addLink, name = ' + name)
liz=xbmcgui.ListItem(name)
liz.setProperty('IsPlayable', 'true')
if infoList == False: liz.setInfo(type="Video", infoLabels={"mediatype":"video","label":name,"title":name})
else: liz.setInfo(type="Video", infoLabels=infoList)
if infoArt == False: liz.setArt({'thumb':ICON,'fanart':FANART})
#.........这里部分代码省略.........
示例8: __init__
# 需要导入模块: from simplecache import SimpleCache [as 别名]
# 或者: from simplecache.SimpleCache import get [as 别名]
class PluginContent:
"""Hidden plugin entry point providing some helper features"""
params = {}
win = None
def __init__(self):
self.cache = SimpleCache()
self.kodi_db = KodiDb()
self.win = xbmcgui.Window(10000)
try:
self.params = dict(urlparse.parse_qsl(sys.argv[2].replace("?", "").lower().decode("utf-8")))
log_msg("plugin called with parameters: %s" % self.params)
self.main()
except Exception as exc:
log_exception(__name__, exc)
xbmcplugin.endOfDirectory(handle=int(sys.argv[1]))
# cleanup when done processing
self.close()
def close(self):
"""Cleanup Kodi Cpython instances"""
self.cache.close()
del self.win
def main(self):
"""main action, load correct function"""
action = self.params.get("action", "")
if self.win.getProperty("SkinHelperShutdownRequested"):
# do not proceed if kodi wants to exit
log_msg("%s --> Not forfilling request: Kodi is exiting" % __name__, xbmc.LOGWARNING)
xbmcplugin.endOfDirectory(handle=int(sys.argv[1]))
else:
try:
if hasattr(self.__class__, action):
# launch module for action provided by this plugin
getattr(self, action)()
else:
# legacy (widget) path called !!!
self.load_widget()
except Exception as exc:
log_exception(__name__, exc)
def load_widget(self):
"""legacy entrypoint called (widgets are moved to seperate addon), start redirect..."""
action = self.params.get("action", "")
newaddon = "script.skin.helper.widgets"
log_msg(
"Deprecated method: %s. Please reassign your widgets to get rid of this message. -"
"This automatic redirect will be removed in the future" % (action),
xbmc.LOGWARNING,
)
paramstring = ""
for key, value in self.params.iteritems():
paramstring += ",%s=%s" % (key, value)
if xbmc.getCondVisibility("System.HasAddon(%s)" % newaddon):
# TEMP !!! for backwards compatability reasons only - to be removed in the near future!!
import imp
addon = xbmcaddon.Addon(newaddon)
addon_path = addon.getAddonInfo("path").decode("utf-8")
imp.load_source("plugin", os.path.join(addon_path, "plugin.py"))
from plugin import main
main.Main()
del addon
else:
# trigger install of the addon
if KODI_VERSION >= 17:
xbmc.executebuiltin("InstallAddon(%s)" % newaddon)
else:
xbmc.executebuiltin("RunPlugin(plugin://%s)" % newaddon)
def playchannel(self):
"""play channel from widget helper"""
params = {"item": {"channelid": int(self.params["channelid"])}}
self.kodi_db.set_json("Player.Open", params)
def playrecording(self):
"""retrieve the recording and play to get resume working"""
recording = self.kodi_db.recording(self.params["recordingid"])
params = {"item": {"recordingid": recording["recordingid"]}}
self.kodi_db.set_json("Player.Open", params)
# manually seek because passing resume to the player json cmd doesn't seem to work
if recording["resume"].get("position"):
for i in range(50):
if xbmc.getCondVisibility("Player.HasVideo"):
break
xbmc.sleep(50)
xbmc.Player().seekTime(recording["resume"].get("position"))
def launch(self):
"""launch any builtin action using a plugin listitem"""
if "runscript" in self.params["path"]:
self.params["path"] = self.params["path"].replace("?", ",")
xbmc.executebuiltin(self.params["path"])
def playalbum(self):
"""helper to play an entire album"""
#.........这里部分代码省略.........
示例9: PlutoTV
# 需要导入模块: from simplecache import SimpleCache [as 别名]
# 或者: from simplecache.SimpleCache import get [as 别名]
class PlutoTV():
def __init__(self):
self.net = net.Net()
self.cache = SimpleCache()
self.region = self.getRegion()
self.filter = False if self.region == 'US' else True
self.categoryMenu = self.getCategories()
self.mediaType = self.getMediaTypes()
log('__init__, region = ' + self.region)
@use_cache(1)
def getRegion(self):
return (self.openURL(REGION_URL).get('countryCode','') or 'US')
def login(self):
log('login')
#ignore guest login
if USER_EMAIL == LANGUAGE(30009): return
if len(USER_EMAIL) > 0:
header_dict = {}
header_dict['Accept'] = 'application/json, text/javascript, */*; q=0.01'
header_dict['Host'] = 'api.pluto.tv'
header_dict['Connection'] = 'keep-alive'
header_dict['Referer'] = 'http://pluto.tv/'
header_dict['Origin'] = 'http://pluto.tv'
header_dict['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.2; rv:24.0) Gecko/20100101 Firefox/24.0'
try: xbmcvfs.rmdir(COOKIE_JAR)
except: pass
if xbmcvfs.exists(COOKIE_JAR) == False:
try:
xbmcvfs.mkdirs(SETTINGS_LOC)
f = xbmcvfs.File(COOKIE_JAR, 'w')
f.close()
except: log('login, Unable to create the storage directory', xbmc.LOGERROR)
form_data = ({'optIn': 'true', 'password': PASSWORD,'synced': 'false', 'userIdentity': USER_EMAIL})
self.net.set_cookies(COOKIE_JAR)
try:
loginlink = json.loads(self.net.http_POST(LOGIN_URL, form_data=form_data, headers=header_dict).content.encode("utf-8").rstrip())
if loginlink and loginlink['email'].lower() == USER_EMAIL.lower():
xbmcgui.Dialog().notification(ADDON_NAME, LANGUAGE(30006) + loginlink['displayName'], ICON, 4000)
self.net.save_cookies(COOKIE_JAR)
else: xbmcgui.Dialog().notification(ADDON_NAME, LANGUAGE(30007), ICON, 4000)
except Exception as e: log('login, Unable to create the storage directory ' + str(e), xbmc.LOGERROR)
else:
#firstrun wizard
if yesnoDialog(LANGUAGE(30008),no=LANGUAGE(30009), yes=LANGUAGE(30010)):
REAL_SETTINGS.setSetting('User_Email',inputDialog(LANGUAGE(30001)))
REAL_SETTINGS.setSetting('User_Password',inputDialog(LANGUAGE(30002)))
else: REAL_SETTINGS.setSetting('User_Email',LANGUAGE(30009))
xbmc.executebuiltin('RunScript("' + ADDON_PATH + '/country.py' + '")')
def openURL(self, url):
log('openURL, url = ' + url)
try:
header_dict = {}
header_dict['Accept'] = 'application/json, text/javascript, */*; q=0.01'
header_dict['Host'] = 'api.pluto.tv'
header_dict['Connection'] = 'keep-alive'
header_dict['Referer'] = 'http://pluto.tv/'
header_dict['Origin'] = 'http://pluto.tv'
header_dict['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.2; rv:24.0) Gecko/20100101 Firefox/24.0'
self.net.set_cookies(COOKIE_JAR)
trans_table = ''.join( [chr(i) for i in range(128)] + [' '] * 128 )
cacheResponse = self.cache.get(ADDON_NAME + '.openURL, url = %s'%url)
if not cacheResponse:
try: cacheResponse = self.net.http_GET(url, headers=header_dict).content.encode("utf-8", 'ignore')
except: cacheResponse = (self.net.http_GET(url, headers=header_dict).content.translate(trans_table)).encode("utf-8")
self.net.save_cookies(COOKIE_JAR)
self.cache.set(ADDON_NAME + '.openURL, url = %s'%url, cacheResponse, expiration=datetime.timedelta(hours=1))
if isinstance(cacheResponse, basestring): cacheResponse = json.loads(cacheResponse)
return cacheResponse
except Exception as e:
log('openURL, Unable to open url ' + str(e), xbmc.LOGERROR)
xbmcgui.Dialog().notification(ADDON_NAME, 'Unable to Connect, Check User Credentials', ICON, 4000)
return ''
def mainMenu(self):
log('mainMenu')
self.login()
for item in PLUTO_MENU: self.addDir(*item)
def browseMenu(self):
log('browseMenu')
for item in self.categoryMenu: self.addDir(*item)
def getCategories(self):
log('getCategories')
collect= []
lineup = []
data = self.openURL(BASE_LINEUP)
for channel in data: collect.append(channel['category'])
counter = collections.Counter(collect)
#.........这里部分代码省略.........
示例10: Sky
# 需要导入模块: from simplecache import SimpleCache [as 别名]
# 或者: from simplecache.SimpleCache import get [as 别名]
class Sky(object):
def __init__(self):
log('__init__')
self.cache = SimpleCache()
def openURL(self, url):
log('openURL, url = ' + str(url))
try:
cacheResponse = self.cache.get(ADDON_NAME + '.openURL, url = %s'%url)
if not cacheResponse:
request = urllib2.Request(url)
request.add_header('User-Agent','Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)')
response = urllib2.urlopen(request, timeout=TIMEOUT).read()
self.cache.set(ADDON_NAME + '.openURL, url = %s'%url, response, expiration=datetime.timedelta(hours=6))
return self.cache.get(ADDON_NAME + '.openURL, url = %s'%url)
except Exception as e: log("openURL Failed! " + str(e), xbmc.LOGERROR)
xbmcgui.Dialog().notification(ADDON_NAME, LANGUAGE(30001), ICON, 4000)
return ''
def buildMainMenu(self):
self.addLink(LANGUAGE(30002),'',0)
self.addYoutube(LANGUAGE(30003),'plugin://plugin.video.youtube/user/skynews/')
def buildLiveLink(self):
try:
link = 'http:' + BeautifulSoup(self.openURL(LIVEURL), "html.parser")('div', {'class': 'video-embed'})[0].find('iframe').get('src')
print self.resolveYoutube(link)
self.playVideo(LANGUAGE(30004),self.resolveYoutube(link))
except: self.playVideo(LANGUAGE(30004),YTURL + 'XOacA3RYrXk')
def resolveYoutube(self, link):
if len(re.findall('http[s]?://www.youtube.com/watch', link)) > 0: return YTURL + link.split('/watch?v=')[1]
elif len(re.findall('http[s]?://www.youtube.com/embed', link)) > 0: return YTURL + link.split('/embed/')[1].split('?autoplay=1')[0]
elif len(re.findall('http[s]?://youtu.be/', link)) > 0: return YTURL + link.split('/youtu.be/')[1]
def playVideo(self, name, url, liz=None):
log('playVideo')
if not liz: liz = xbmcgui.ListItem(name, path=url)
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
def addYoutube(self, title, url):
liz=xbmcgui.ListItem(title)
liz.setProperty('IsPlayable', 'false')
liz.setInfo(type="Video", infoLabels={"label":title,"title":title} )
liz.setArt({'thumb':ICON,'fanart':FANART})
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz,isFolder=True)
def addLink(self, name, u, mode, infoList=False, infoArt=False, total=0):
name = name.encode("utf-8")
log('addLink, name = ' + name)
liz=xbmcgui.ListItem(name)
liz.setProperty('IsPlayable', 'true')
if infoList == False: liz.setInfo(type="Video", infoLabels={"mediatype":"video","label":name,"title":name,"genre":"News"})
else: liz.setInfo(type="Video", infoLabels=infoList)
if infoArt == False: liz.setArt({'thumb':ICON,'fanart':FANART})
else: liz.setArt(infoArt)
u=sys.argv[0]+"?url="+urllib.quote_plus(u)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,totalItems=total)
示例11: TVCatchup
# 需要导入模块: from simplecache import SimpleCache [as 别名]
# 或者: from simplecache.SimpleCache import get [as 别名]
class TVCatchup(object):
def __init__(self):
log('__init__')
self.cache = SimpleCache()
def getTVCtime(self):
return datetime.datetime.now(timezone('Europe/London'))
def openURL(self, url):
try:
log('openURL, url = ' + str(url))
cacheresponse = self.cache.get(ADDON_NAME + '.openURL, url = %s'%url)
if not cacheresponse:
cacheresponse = urllib2.urlopen(urllib2.Request(url), timeout=TIMEOUT).read()
self.cache.set(ADDON_NAME + '.openURL, url = %s'%url, cacheresponse, expiration=datetime.timedelta(minutes=5))
return cacheresponse
except Exception as e:
log("openURL Failed! " + str(e), xbmc.LOGERROR)
xbmcgui.Dialog().notification(ADDON_NAME, LANGUAGE(30001), ICON, 4000)
return ''
def buildMenu(self, items):
for item in items: self.addDir(*item)
def buildLive(self):
soup = BeautifulSoup(self.openURL(LIVE_URL), "html.parser")
results = soup('div' , {'class': 'channelsHolder'})
for channel in results:
chname = cleanString(channel.find_all('img')[1].attrs['alt']).replace('Watch ','')
label = '%s - %s'%(chname,cleanString(channel.get_text()))
link = channel.find_all('a')[0].attrs['href']
thumb = LOGO%chname
infoLabels = {"mediatype":"episode","label":label ,"title":label}
infoArt = {"thumb":thumb,"poster":thumb,"fanart":FANART,"icon":thumb,"logo":thumb}
self.addLink(label, link, 9, infoLabels, infoArt, len(results))
def buildLineup(self, name=None):
log('buildLineup, name = ' + str(name))
soup = BeautifulSoup(self.openURL(GUIDE_URL), "html.parser")
results = soup('div' , {'class': 'row'})
for channel in results:
chname = cleanString(channel.find_all('img')[0].attrs['alt'])
link = cleanString(channel.find_all('a')[0].attrs['href'])
thumb = LOGO%chname
if name is None:
infoLabels = {"mediatype":"episode","label":chname ,"title":chname}
infoArt = {"thumb":thumb,"poster":thumb,"fanart":FANART,"icon":thumb,"logo":thumb}
self.addDir(chname, chname, 2, infoLabels, infoArt)
elif name.lower() == chname.lower():
try:
date = soup('a' , {'class': 'last'})[0].attrs['href']
aired = re.findall('/tv-guide/(.+?)/00',date, flags=re.DOTALL)[0]
except: aired = self.getTVCtime().strftime('%Y-%m-%d')
items = channel('div' , {'class': 'hide'})
for item in items:
try:
time = trimString(item.find_all('span')[0].get_text())
dur = int((abs(eval(time.replace(':','.'))) * 60) * 60)
start = datetime.datetime.strptime(time.split('-')[0], '%H:%M').strftime('%I:%M %p')
except: continue
label = '%s: %s - %s'%(start,chname,cleanString(item.get_text()).split('\n')[0])
try: desc = trimString(item.find_all('br')[0].get_text())
except: desc = ''
infoLabels = {"mediatype":"episode","label":label ,"title":label,"plot":desc,"duration":dur,"aired":aired}
infoArt = {"thumb":thumb,"poster":thumb,"fanart":FANART,"icon":thumb,"logo":thumb}
self.addLink(label, link, 9, infoLabels, infoArt, len(items))
break
def uEPG(self):
log('uEPG')
#support for upcoming uEPG universal epg framework module, module will be available from the Kodi repository.
#https://github.com/Lunatixz/KODI_Addons/tree/master/script.module.uepg
soup = BeautifulSoup(self.openURL(GUIDE_URL), "html.parser")
results = soup('div' , {'class': 'row'})
return (self.buildGuide(idx, channel) for idx, channel in enumerate(results))
def buildGuide(self, idx, channel):
log('buildGuide')
chname = cleanString(channel.find_all('img')[0].attrs['alt'])
link = cleanString(channel.find_all('a')[0].attrs['href'])
chlogo = LOGO%chname
chnum = idx + 1
isFavorite = False
newChannel = {}
guidedata = []
newChannel['channelname'] = chname
newChannel['channelnumber'] = chnum
newChannel['channellogo'] = chlogo
newChannel['isfavorite'] = isFavorite
try:
date = soup('a' , {'class': 'last'})[0].attrs['href']
aired = re.findall('/tv-guide/(.+?)/00',date, flags=re.DOTALL)[0]
except: aired = self.getTVCtime().strftime('%Y-%m-%d')
#.........这里部分代码省略.........
示例12: __init__
# 需要导入模块: from simplecache import SimpleCache [as 别名]
# 或者: from simplecache.SimpleCache import get [as 别名]
class PlayOn:
def __init__(self):
self.cache = SimpleCache()
if URLTYPE == 'upnp': self.chkUPNP()
def openURL(self, url):
log('openURL, url = ' + str(url))
try:
cacheResponse = self.cache.get(ADDON_NAME + '.openURL, url = %s'%url)
if not cacheResponse:
request = urllib2.Request(url)
request.add_header('User-Agent','Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)')
response = urllib2.urlopen(request, timeout=TIMEOUT).read()
self.cache.set(ADDON_NAME + '.openURL, url = %s'%url, response, expiration=datetime.timedelta(minutes=5))
return self.cache.get(ADDON_NAME + '.openURL, url = %s'%url)
except Exception as e: log("openURL Failed! " + str(e), xbmc.LOGERROR)
if url == BASE_URL + PLAYON_DATA: self.getIP()
def getIP(self):
url = self.openURL(AUTO_URL).replace('|','')
match = re.findall(r'[0-9]+(?:\.[0-9]+){3}:[0-9]+', url)
log('getIP, match = ' + str(match))
if len(match) == 0:
url = getKeyboard(LANGUAGE(30001),LANGUAGE(30002))
if url == False: return
if not url.startswith('http'): url = "http://%s"%url
BASE_URL = url
REAL_SETTINGS.setSetting("playonserver",url)
self.chkIP(url)
def chkIP(self, url=BASE_URL):
log('chkIP, url = ' + str(url))
results = xmltodict.parse(self.openURL(url + PLAYON_DATA))
if results and 'catalog' in results:
try:
ServerName = results['catalog']['@name']
ServerVer = 'PlayOn v.%s'%results['catalog']['@server']
ServerMSG = "Connected to [B]%s %s[/B]"%(ServerName,ServerVer)
log('chkIP, ServerName = ' + ServerName)
log('chkIP, ServerVer = ' + ServerVer)
REAL_SETTINGS.setSetting("playonServerid",ServerMSG)
xbmcgui.Dialog().notification(ADDON_NAME, LANGUAGE(30011)%ServerName, ICON, 5000)
xbmc.executebuiltin("Container.Refresh")
except Exception as e: log("chkIP Failed! " + str(e), xbmc.LOGERROR)
else: xbmcgui.Dialog().notification(ADDON_NAME, LANGUAGE(30010), ICON, 5000)
def getUPNP(self):
log('getUPNP')
""" Check Kodi UPNP support. """
json_query = ('{"jsonrpc":"2.0","method":"Settings.GetSettingValue","params":{"setting":"services.upnp"},"id":1}')
data = json.loads(xbmc.executeJSONRPC(json_query))
try:
if 'result' in data and 'value' in data['result']: return data['result']['value']
except Exception as e: log('getUPNP, Failed! ' + str(e))
return False
def setUPNP(self):
log('setUPNP')
""" Enable Kodi UPNP support. """
json_query = ('{"jsonrpc":"2.0","method":"Settings.SetSettingValue","params":{"setting":"services.upnp","value":true},"id":1}')
xbmcgui.Dialog().notification(ADDON_NAME, LANGUAGE(30015), ICON, 5000)
return json.loads(xbmc.executeJSONRPC(json_query))
def getUPNP_ID(self):
log('getUPNP_ID')
""" Check if upnp id is valid. """
json_query = ('{"jsonrpc":"2.0","method":"Files.GetDirectory","params":{"directory":"%s"},"id":1}'%BASE_UPNP)
data = json.loads(xbmc.executeJSONRPC(json_query))
try:
if not data['result']['files'][0]['file'].endswith('/playonprovider/'): return None
except Exception as e:
log('getUPNP_ID, Failed! ' + str(e))
return None
return BASE_UPNP
def chkUPNP(self):
log('chkUPNP')
""" Query json, locate 'playon server' path, else prompt. """
if self.getUPNP_ID() is not None: return
else:
if not self.getUPNP(): self.setUPNP()
json_query = ('{"jsonrpc":"2.0","method":"Files.GetDirectory","params":{"directory":"upnp://"},"id":1}')
data = json.loads(xbmc.executeJSONRPC(json_query))
if data and 'result' in data and 'files' in data['result']:
for item in data['result']['files']:
if (item['label']).lower().startswith('playon'):
REAL_SETTINGS.setSetting("playonUPNPid",item['file'].rstrip('/'))
xbmcgui.Dialog().notification(ADDON_NAME, LANGUAGE(30013), ICON, 5000)
BASE_UPNP = item['file']
REAL_SETTINGS.setSetting("playonUPNPid",BASE_UPNP.rstrip('/'))
elif PTVL_RUNNING == False:
BASE_UPNP = xbmcgui.Dialog().browse(0, LANGUAGE(30014), 'files', '', False, False, 'upnp://')
if BASE_UPNP != -1: REAL_SETTINGS.setSetting("playonUPNPid",BASE_UPNP.rstrip('/'))
#.........这里部分代码省略.........
示例13: Newsmax
# 需要导入模块: from simplecache import SimpleCache [as 别名]
# 或者: from simplecache.SimpleCache import get [as 别名]
class Newsmax(object):
def __init__(self):
log('__init__')
self.cache = SimpleCache()
def openURL(self, url):
log('openURL, url = ' + str(url))
try:
cacheResponse = self.cache.get(ADDON_NAME + '.openURL, url = %s'%url)
if not cacheResponse:
request = urllib2.Request(url)
request.add_header('User-Agent','Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)')
response = urllib2.urlopen(request, timeout=TIMEOUT).read()
self.cache.set(ADDON_NAME + '.openURL, url = %s'%url, response, expiration=datetime.timedelta(hours=6))
return self.cache.get(ADDON_NAME + '.openURL, url = %s'%url)
except Exception as e: log("openURL Failed! " + str(e), xbmc.LOGERROR)
xbmcgui.Dialog().notification(ADDON_NAME, LANGUAGE(30001), ICON, 4000)
return ''
def buildMainMenu(self):
self.addLink(LANGUAGE(30002),'',0)
self.addYoutube(LANGUAGE(30003),'plugin://plugin.video.youtube/user/NewsmaxTV/')
def buildLiveLink(self):
log('buildLiveLink')
try:
site = json.loads(self.openURL(BASE_URL).split('<script type="application/ld+json">')[1].split('</script>')[0])['embedUrl']
data = ((self.openURL(site).replace('\n','').replace('\r','').replace('\t','').replace('\\','')).split('"entryResult":')[1]).split(',"recordedEntryId"')[0]+'}}'
url = 'https://'+((re.compile('https://(.+?)m3u8', re.DOTALL).search(data)).group(1))+'m3u8'
except: url = YT_LIVE
self.playVideo(LANGUAGE(30004),url)
def playVideo(self, name, url):
log('playVideo')
liz = xbmcgui.ListItem(name, path=url)
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
def addLink(self, name, u, mode, infoList=False, infoArt=False, total=0):
name = name.encode("utf-8")
log('addLink, name = ' + name)
liz=xbmcgui.ListItem(name)
liz.setProperty('IsPlayable', 'true')
if infoList == False: liz.setInfo(type="Video", infoLabels={"mediatype":"video","label":name,"title":name,"genre":"News"})
else: liz.setInfo(type="Video", infoLabels=infoList)
if infoArt == False: liz.setArt({'thumb':ICON,'fanart':FANART})
else: liz.setArt(infoArt)
u=sys.argv[0]+"?url="+urllib.quote_plus(u)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,totalItems=total)
def addYoutube(self, title, url):
liz=xbmcgui.ListItem(title)
liz.setProperty('IsPlayable', 'false')
liz.setInfo(type="Video", infoLabels={"label":title,"title":title} )
liz.setArt({'thumb':ICON,'fanart':FANART})
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz,isFolder=True)
示例14: Cheddar
# 需要导入模块: from simplecache import SimpleCache [as 别名]
# 或者: from simplecache.SimpleCache import get [as 别名]
class Cheddar(object):
def __init__(self):
log('__init__')
self.cache = SimpleCache()
def openURL(self, url):
try:
cacheResponce = self.cache.get(ADDON_NAME + '.openURL, url = %s'%url)
if not cacheResponce:
request = urllib2.Request(url)
request.add_header('User-Agent','Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)')
response = urllib2.urlopen(request, timeout=TIMEOUT)
cacheResponce = response.read()
response.close()
self.cache.set(ADDON_NAME + '.openURL, url = %s'%url, cacheResponce, expiration=datetime.timedelta(hours=1))
return cacheResponce
except urllib2.URLError as e: log("openURL Failed! " + str(e), xbmc.LOGERROR)
except socket.timeout as e: log("openURL Failed! " + str(e), xbmc.LOGERROR)
xbmcgui.Dialog().notification(ADDON_NAME, LANGUAGE(30001), ICON, 4000)
return ''
def buildMenu(self, items):
log('buildMenu')
if items == Cheddar_LIVE:
for item in items: self.addLink(*item)
else:
for item in items: self.addDir(*item)
if items == Cheddar_MENU: self.addYoutube(LANGUAGE(30033), 'plugin://plugin.video.youtube/channel/UC04KsGq3npibMCE9Td3mVDg/')
def browse(self, link):
log('browse')
soup = BeautifulSoup(self.openURL(BASEURL + link), "html.parser")
latestLink = (soup('div', {'class': 'video_thumb'}))
for item in latestLink:
uriLink = item('a', {'class': 'cf'})[0]
uri = BASEURL + uriLink['href']
thumb = uriLink('div', {'class': 'vid_img'})[0].find_all('img')[0].get('src')
airdate, title = uriLink.text.strip().replace('\r','').replace('\t','').split('\n')
label = title.strip()
plot = '%s [CR]Aired: %s'%(label, airdate)
try: airdate = datetime.datetime.strptime(airdate, "%B %d, %Y")
except: airdate = datetime.datetime.now()
airdate = airdate.strftime('%Y-%m-%d')
infoList = {"mediatype":"episode","label":label,"title":label,"plot":plot,'genre':'News',"studio":"cheddar","aired":airdate}
infoArt = {"thumb":thumb,"poster":thumb,"fanart":FANART}
self.addLink(label, uri, 9, infoList, infoArt)
def playVideo(self, name, url):
log('playVideo, name = ' + name)
if url.endswith('m3u8'):
liz = xbmcgui.ListItem(name, path=url)
liz.setProperty('inputstreamaddon','inputstream.adaptive')
liz.setProperty('inputstream.adaptive.manifest_type','hls')
else:
info = getVideoInfo(url,QUALITY,True)
if info is None: return
info = info.streams()
url = info[0]['xbmc_url']
liz = xbmcgui.ListItem(name, path=url)
if 'subtitles' in info[0]['ytdl_format']: liz.setSubtitles([x['url'] for x in info[0]['ytdl_format']['subtitles'].get('en','') if 'url' in x])
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
def addYoutube(self, name, url):
liz=xbmcgui.ListItem(name)
liz.setProperty('IsPlayable', 'false')
liz.setInfo(type="Video", infoLabels={"label":name,"title":name} )
liz.setArt({'thumb':ICON,'fanart':FANART})
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz,isFolder=True)
def addLink(self, name, u, mode, infoList=False, infoArt=False, total=0):
name = name.encode("utf-8")
log('addLink, name = ' + name)
liz=xbmcgui.ListItem(name)
liz.setProperty('IsPlayable', 'true')
if infoList == False: liz.setInfo(type="Video", infoLabels={"mediatype":"video","label":name,"title":name})
else: liz.setInfo(type="Video", infoLabels=infoList)
if infoArt == False: liz.setArt({'thumb':ICON,'fanart':FANART})
else: liz.setArt(infoArt)
u=sys.argv[0]+"?url="+urllib.quote_plus(u)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,totalItems=total)
def addDir(self, name, u, mode, infoList=False, infoArt=False):
name = name.encode("utf-8")
log('addDir, name = ' + name)
liz=xbmcgui.ListItem(name)
liz.setProperty('IsPlayable', 'false')
if infoList == False: liz.setInfo(type="Video", infoLabels={"mediatype":"video","label":name,"title":name} )
else: liz.setInfo(type="Video", infoLabels=infoList)
if infoArt == False: liz.setArt({'thumb':ICON,'fanart':FANART})
else: liz.setArt(infoArt)
u=sys.argv[0]+"?url="+urllib.quote_plus(u)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
示例15: Uncrate
# 需要导入模块: from simplecache import SimpleCache [as 别名]
# 或者: from simplecache.SimpleCache import get [as 别名]
class Uncrate(object):
def __init__(self):
log('__init__')
self.cache = SimpleCache()
def openURL(self, url):
try:
log('openURL, url = ' + str(url))
cacheresponse = self.cache.get(ADDON_NAME + '.openURL, url = %s'%url)
if not cacheresponse:
cacheresponse = urllib2.urlopen(urllib2.Request(url), timeout=TIMEOUT).read()
self.cache.set(ADDON_NAME + '.openURL, url = %s'%url, cacheresponse, expiration=datetime.timedelta(minutes=15))
return cacheresponse
except Exception as e:
log("openURL Failed! " + str(e), xbmc.LOGERROR)
xbmcgui.Dialog().notification(ADDON_NAME, LANGUAGE(30001), ICON, 4000)
return ''
def buildMenu(self, items):
for item in items: self.addDir(*item)
self.addYoutube(LANGUAGE(30006), 'plugin://plugin.video.youtube/channel/UCmqL6p6ZJ9uGvC2N1oZsZvA/')
def browse(self, url):
log('browse, url = ' + str(url))
soup = BeautifulSoup(self.openURL(url), "html.parser")
videos = soup('li', {'class': 'article one-half no-action'})
for video in videos:
link = video('div', {'class': 'image-wrapper'})[0].find('a').attrs['href']
thumb = video('div', {'class': 'image-wrapper'})[0].find('img').attrs['src']
genre = [cat.get_text() for cat in video('div', {'class': 'category-group'})[0].find_all('a')]
label = video('h1', {'class': 'article-title'})[0].find('a').get_text()
plot = video('div', {'class': 'copy-wrapper'})[0].find('p').get_text()
infoLabels = {"mediatype":"episode","label":label ,"title":label,"genre":genre,"plot":plot}
infoArt = {"thumb":thumb,"poster":thumb,"fanart":FANART,"icon":thumb,"logo":thumb}
self.addLink(label, link, 9, infoLabels, infoArt, len(videos))
next = soup('div', {'class': 'wrapper pagination-wrapper'})
if len(next) == 0: return
next_url = next[0].find('a').attrs['href']
next_label = next[0].find('a').get_text()
self.addDir(next_label, next_url, 1)
def buildChannels(self):
log('buildChannels')
soup = BeautifulSoup(self.openURL(CHAN_URL), "html.parser")
items = soup('li', {'class': 'article high-impact-banner one-half channel'})
for item in items:
thumb = (item('div', {'class': 'image-wrapper'})[0].find('img').attrs['src']).strip()
item = item('h1', {'class': 'article-title'})[0]
link = item.find('a').attrs['href']
label = item.get_text()
infoLabels = {"mediatype":"episode","label":label ,"title":label,"genre":label,"plot":label}
infoArt = {"thumb":thumb,"poster":thumb,"fanart":FANART,"icon":thumb,"logo":thumb}
self.addDir(label, link, 1, infoLabels, infoArt)
def playVideo(self, name, url):
log('playVideo')
info = getVideoInfo(url,QUALITY,True)
if info is None: return
info = info.streams()
url = info[0]['xbmc_url']
liz = xbmcgui.ListItem(name, path=url)
if 'm3u8' in url.lower():
liz.setProperty('inputstreamaddon','inputstream.adaptive')
liz.setProperty('inputstream.adaptive.manifest_type','hls')
if 'subtitles' in info[0]['ytdl_format']: liz.setSubtitles([x['url'] for x in info[0]['ytdl_format']['subtitles'].get('en','') if 'url' in x])
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
def addYoutube(self, name, url):
liz=xbmcgui.ListItem(name)
liz.setProperty('IsPlayable', 'false')
liz.setInfo(type="Video", infoLabels={"label":name,"title":name} )
liz.setArt({'thumb':ICON,'fanart':FANART})
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz,isFolder=True)
def addLink(self, name, u, mode, infoList=False, infoArt=False, total=0):
name = name.encode("utf-8")
log('addLink, name = ' + name)
liz=xbmcgui.ListItem(name)
liz.setProperty('IsPlayable', 'true')
if infoList == False: liz.setInfo(type="Video", infoLabels={"mediatype":"video","label":name,"title":name})
else: liz.setInfo(type="Video", infoLabels=infoList)
if infoArt == False: liz.setArt({'thumb':ICON,'fanart':FANART})
else: liz.setArt(infoArt)
u=sys.argv[0]+"?url="+urllib.quote_plus(u)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,totalItems=total)
def addDir(self, name, u, mode, infoList=False, infoArt=False):
name = name.encode("utf-8")
log('addDir, name = ' + name)
liz=xbmcgui.ListItem(name)
liz.setProperty('IsPlayable', 'false')
#.........这里部分代码省略.........