• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python simplecache.SimpleCache类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中simplecache.SimpleCache的典型用法代码示例。如果您正苦于以下问题:Python SimpleCache类的具体用法?Python SimpleCache怎么用?Python SimpleCache使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了SimpleCache类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: get_repo_resourceaddons

def get_repo_resourceaddons(filterstr=""):
    '''helper to retrieve all available resource addons on the kodi repo'''
    result = []
    simplecache = SimpleCache()
    for item in xbmcvfs.listdir("addons://all/kodi.resource.images/")[1]:
        if not filterstr or item.lower().startswith(filterstr.lower()):
            addoninfo = get_repo_addoninfo(item, simplecache)
            if not addoninfo.get("name"):
                addoninfo = {"addonid": item, "name": item, "author": ""}
                addoninfo["thumbnail"] = "http://mirrors.kodi.tv/addons/krypton/%s/icon.png" % item
            addoninfo["path"] = "resource://%s/" % item
            result.append(addoninfo)
    simplecache.close()
    return result
开发者ID:marcelveldt,项目名称:script.skin.helper.service,代码行数:14,代码来源:resourceaddons.py


示例2: __init__

 def __init__(self, *args, **kwargs):
     self.cache = SimpleCache()
     self.artutils = kwargs.get("artutils")
     self.win = kwargs.get("win")
     self.kodimonitor = kwargs.get("monitor")
     self.event = threading.Event()
     threading.Thread.__init__(self, *args)
开发者ID:marcelveldt,项目名称:script.skin.helper.service,代码行数:7,代码来源:listitem_monitor.py


示例3: __init__

 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)
开发者ID:Lunatixz,项目名称:repo-plugins,代码行数:8,代码来源:plutotv.py


示例4: __init__

 def __init__(self, api_key=None):
     '''Initialize our Module'''
     if api_key:
         self.api_key = api_key
     self.cache = SimpleCache()
     self._win = xbmcgui.Window(10000)
     self._addon = xbmcaddon.Addon(ADDON_ID)
     addonversion = self._addon.getAddonInfo('version').decode("utf-8")
     self.cache.global_checksum = "%s%s" % (addonversion, KODI_LANGUAGE)
     self._log_msg("Initialized")
开发者ID:marcelveldt,项目名称:script.module.thetvdb,代码行数:10,代码来源:thetvdb.py


示例5: Newsy

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)
开发者ID:Lunatixz,项目名称:repo-plugins,代码行数:20,代码来源:newsy.py


示例6: test_simple_cache

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
开发者ID:Smarties89,项目名称:mps,代码行数:8,代码来源:test_simplecache.py


示例7: __init__

    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()
开发者ID:marcelveldt,项目名称:script.skin.helper.service,代码行数:14,代码来源:plugin_content.py


示例8: NewsOn

class NewsOn(object):
    def __init__(self):
        log('__init__')
        self.cache     = SimpleCache()
        self.stateMenu = self.getStates()

        
    def openURL(self, url):
        try:
            cacheResponse = self.cache.get(ADDON_NAME + '.openURL, url = %s'%url)
            if not cacheResponse:
                request = urllib2.Request(url)
                request.add_header('Accept-encoding', 'gzip')
                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)
                log(response.headers['content-type'])
                log(response.headers['content-encoding'])
                if response.info().get('content-encoding') == 'gzip':
                    buf = StringIO(response.read())
                    f = gzip.GzipFile(fileobj=buf)
                    cacheResponse = f.read()
                else: cacheResponse = response
                response.close()
                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 Failed! " + str(e), xbmc.LOGERROR)
            xbmcgui.Dialog().notification(ADDON_NAME, LANGUAGE(30001), ICON, 4000)
            return ''
        
        
    def mainMenu(self):
        log('mainMenu')
        for item in MENU: self.addDir(*item)
        
                    
    def browseMenu(self, id=1):
        log('browseMenu, id = ' + str(id))
        self.stateMenu = [tuple(s.format(id) for s in tup) for tup in self.stateMenu]
        for item in self.stateMenu: self.addDir(*item)
            
            
    def getStates(self):
        log('getStates')
        state     = []
        stateLST  = []
        data = self.openURL(BASE_API)
        if len(data) == 0: return []
        for channel in data: 
            try: state.append(channel['config']['state'])
            except: pass
        states = collections.Counter(state)
        for key, value in sorted(states.iteritems()): stateLST.append(("%s"%(key), key , '{}'))
        return stateLST
            
            
    def newsCasts(self, state):
        log('newsCasts, state = ' + state)
        urls = []
        data = self.openURL(BASE_API)
        if len(data) == 0: return
        for channel in data:
            try: states = channel['config']['state']
            except: continue
            if state in states:
                chid   = channel['identifier']
                title  = channel['title']
                icon   = (channel['icon'] or ICON)
                for idx, stream in enumerate(channel['streams']):
                    streamType = stream['StreamType']
                    if streamType == 'website': continue#random.choice(['website','roku']): 
                    #multiple urls, only add unique.
                    url = stream['Url']
                    offset = stream['OffsetFromNow']
                    delay  = url+'&delay=%d'
                    #todo do something with delay option?
                    if url not in urls:
                        urls.append(url)
                        chid = chid+'.%d'%idx if idx > 0 else chid
                        label      = "%s - %s" % (chid, title)
                        infoLabels ={"mediatype":"episodes","label":label ,"title":label}
                        infoArt    ={"thumb":icon,"poster":icon,"fanart":FANART,"icon":icon,"logo":icon} 
                        self.addLink(title, url, 9, infoLabels, infoArt)
        
        
    def videoclips(self, state):
        log('videoclips, state = ' + state)
        data = self.openURL(BASE_API)
        if len(data) == 0: return
        for channel in data:
            try: states = channel['config']['state']
            except: continue
            if state in states:
                chid   = channel['identifier']
                title  = channel['title']
                icon   = (channel['icon'] or ICON)
                vidURL = channel['config']['localvodfeed']
                if vidURL:
                    label      = "%s - %s" % (chid, title)
#.........这里部分代码省略.........
开发者ID:Lunatixz,项目名称:repo-plugins,代码行数:101,代码来源:newson.py


示例9: CBR

class CBR(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:
                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(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/UCuCk_7b2_4uSr6y5hFmjuMQ/')
        
        
    def browse(self, url):
        log('browse, url = ' + str(url))
        soup   = BeautifulSoup(self.openURL(url), "html.parser")
        videos = soup('div', {'class': 'thumb-wrap'})
        videos.extend(soup('article', {'class': 'thumb-wrap'}))
        for video in videos:
            link  = video('div', {'class': 'img-wrapper'})[0].find('a').attrs['href']
            thumb = video('div', {'class': 'responsiveImg'})[0].find('source').attrs['srcset']
            try: label = video('strong', {'class': 'title'})[0].find('a').attrs['title']
            except: label = (video('div', {'class': 'info-wrapper'})[0].find('a').get_text())
            try: airdate = datetime.datetime.strptime(video('div', {'class': 'details'})[0].find('time').get_text(), '%m.%d.%y')
            except: airdate = datetime.datetime.now()
            airdate = airdate.strftime('%Y-%m-%d')
            plot    = '%s - %s'%(label,airdate)
            try: 
                dur = (video('div', {'class': 'img-wrapper'})[0].find('span').get_text()).split(':')
                if len(dur) == 3:
                    h, m, s = dur
                    duration  = int(h) * 3600 + int(m) * 60 + int(s)
                else:
                    m, s = dur   
                    duration  = int(m) * 60 + int(s)
            except: duration = '0'
            infoLabels = {"mediatype":"episode","label":label ,"title":label,"duration":duration,"plot":plot,"aired":airdate}
            infoArt    = {"thumb":thumb,"poster":thumb,"fanart":FANART,"icon":thumb,"logo":thumb}
            vidID      = ((thumb.split('/')[8]).split('-')[5]).split('_')
            link       = VIDEO_URL%(vidID[2],vidID[0])
            self.addLink(label, link, 9, infoLabels, infoArt, len(videos))

        next = soup('a', {'class': 'nextpostslink'})  
        if len(next) == 0: return
        next_url   = next[0].attrs['href']
        next_label = soup('span', {'class': 'pages'})[0].get_text()
        self.addDir(next_label, next_url, 1)
        
        
    def playVideo(self, name, url):
        log('playVideo')
        liz  = xbmcgui.ListItem(name, path=url)
        liz.setProperty('inputstreamaddon','inputstream.adaptive')
        liz.setProperty('inputstream.adaptive.manifest_type','hls') 
        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})
#.........这里部分代码省略.........
开发者ID:Lunatixz,项目名称:repo-plugins,代码行数:101,代码来源:cbr.py


示例10: ListItemMonitor

class ListItemMonitor(threading.Thread):
    '''Our main class monitoring the kodi listitems and providing additional information'''
    event = None
    exit = False
    delayed_task_interval = 1795
    listitem_details = {}
    all_window_props = []
    cur_listitem = ""
    last_folder = ""
    last_listitem = ""
    foldercontent = {}
    screensaver_setting = None
    screensaver_disabled = False
    lookup_busy = {}
    enable_extendedart = False
    enable_musicart = False
    enable_animatedart = False
    enable_extrafanart = False
    enable_pvrart = False
    enable_forcedviews = False

    def __init__(self, *args, **kwargs):
        self.cache = SimpleCache()
        self.artutils = kwargs.get("artutils")
        self.win = kwargs.get("win")
        self.kodimonitor = kwargs.get("monitor")
        self.event = threading.Event()
        threading.Thread.__init__(self, *args)

    def stop(self):
        '''called when the thread has to stop working'''
        log_msg("ListItemMonitor - stop called")
        self.exit = True
        self.event.set()

    def run(self):
        '''our main loop monitoring the listitem and folderpath changes'''
        log_msg("ListItemMonitor - started")
        self.get_settings()

        while not self.exit:

            # check screensaver and OSD
            self.check_screensaver()
            self.check_osd()

            # do some background stuff every 30 minutes
            if (self.delayed_task_interval >= 1800) and not self.exit:
                thread.start_new_thread(self.do_background_work, ())
                self.delayed_task_interval = 0

            # skip if any of the artwork context menus is opened
            if self.win.getProperty("SkinHelper.Artwork.ManualLookup"):
                self.reset_win_props()
                self.last_listitem = ""
                self.listitem_details = {}
                self.kodimonitor.waitForAbort(3)
                self.delayed_task_interval += 3

            # skip when modal dialogs are opened (e.g. textviewer in musicinfo dialog) or container scrolling
            elif xbmc.getCondVisibility(
                    "Window.IsActive(DialogSelect.xml) | Window.IsActive(progressdialog) | "
                    "Window.IsActive(contextmenu) | Window.IsActive(busydialog) | Container.Scrolling"):
                self.kodimonitor.waitForAbort(2)
                self.delayed_task_interval += 2
                self.last_listitem = ""

            # media window is opened or widgetcontainer set - start listitem monitoring!
            elif xbmc.getCondVisibility("Window.IsMedia | "
                                        "!IsEmpty(Window(Home).Property(SkinHelper.WidgetContainer))"):
                self.monitor_listitem()
                self.kodimonitor.waitForAbort(0.15)
                self.delayed_task_interval += 0.15

            # flush any remaining window properties
            elif self.all_window_props:
                self.reset_win_props()
                self.win.clearProperty("SkinHelper.ContentHeader")
                self.win.clearProperty("contenttype")
                self.win.clearProperty("curlistitem")
                self.last_listitem = ""

            # other window active - do nothing
            else:
                self.kodimonitor.waitForAbort(1)
                self.delayed_task_interval += 1

    def get_settings(self):
        '''collect our skin settings that control the monitoring'''
        self.enable_extendedart = xbmc.getCondVisibility("Skin.HasSetting(SkinHelper.EnableExtendedArt)") == 1
        self.enable_musicart = xbmc.getCondVisibility("Skin.HasSetting(SkinHelper.EnableMusicArt)") == 1
        self.enable_animatedart = xbmc.getCondVisibility("Skin.HasSetting(SkinHelper.EnableAnimatedPosters)") == 1
        self.enable_extrafanart = xbmc.getCondVisibility("Skin.HasSetting(SkinHelper.EnableExtraFanart)") == 1
        self.enable_pvrart = xbmc.getCondVisibility(
            "Skin.HasSetting(SkinHelper.EnablePVRThumbs) + PVR.HasTVChannels") == 1
        self.enable_forcedviews = xbmc.getCondVisibility("Skin.HasSetting(SkinHelper.ForcedViews.Enabled)") == 1
        studiologos_path = xbmc.getInfoLabel("Skin.String(SkinHelper.StudioLogos.Path)").decode("utf-8")
        if studiologos_path != self.artutils.studiologos_path:
            self.listitem_details = {}
            self.artutils.studiologos_path = studiologos_path
#.........这里部分代码省略.........
开发者ID:marcelveldt,项目名称:script.skin.helper.service,代码行数:101,代码来源:listitem_monitor.py


示例11: Cheddar

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)
开发者ID:Lunatixz,项目名称:repo-plugins,代码行数:99,代码来源:cheddar.py


示例12: CC

class CC(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)
            if str(e).startswith('HTTP Error 500'): return ''
            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/user/comedycentral/')
            
            
    def browse(self, name, url):
        log('browse, ' + name)
        response = self.openURL(url)
        if len(response) == 0: return
        try: items = json.loads(re.search('var triforceManifestFeed = (.+?);\n',response).group(1))
        except: items = json.loads(re.search('var triforceManifestURL = "(.+?)";',response).group(1))  
        try: thumb = (response.split('//meta[@property="og:image"]/@content')[0].strip() or ICON)
        except: thumb = ICON
        if not thumb.endswith(('.png','.jpg')): thumb = ICON
        elif thumb.startswith('//'): thumb = 'http:%s'%thumb
        if items and 'manifest' not in items: return
        for item in items['manifest']['zones']:
            if item in ('header', 'footer', 'ads-reporting', 'ENT_M171'): continue
            try: result = items['manifest']['zones'][item]['feed']
            except: result = None
            if result is None: continue
            try: ent_code = result.split('/feeds/')[1].split('/')[0]
            except:
                try: ent_code = result.split('/modules/')[1].split('/')[0]
                except: ent_code = ''
            ent_code = ent_code.split('_cc')[0].split('_tosh')[0]
            try: jsonResponse = json.loads(self.openURL(result))['result']
            except: log('browse, jsonResponse failed! ' + str(jsonResponse))
            if ent_code == 'ent_m081': return self.buildEpisodes(name, url, jsonResponse, jsonResponse['episodes'])
            elif ent_code == 'ent_m013': return self.buildEpisodes(name, url, jsonResponse, jsonResponse['episodes'])
            elif ent_code in ['ent_m100','ent_m150']:
                for item in jsonResponse['data']['items']:
                    if ent_code == 'ent_m100' and name == LANGUAGE(30008): self.buildShow(item)
                    elif ent_code == 'ent_m150' and name == LANGUAGE(30004):
                        for show in item['sortedItems']: self.buildShow(show)


    def buildShow(self, show):
        vid_url = (show.get('canonicalURL','') or show.get('url',None))
        title = (show.get('title','')          or show.get('shortTitle',None))
        plot  = (show.get('description','')    or show.get('shortDescription','') or title)
        if vid_url is None or title is None or not vid_url.startswith(BASE_URL): return
        try: thumb = show['image']['url']
        except: thumb = LOGO_URL%(urllib.quote(title))
        infoLabels = {"mediatype":"tvshows","label":title ,"title":title,"TVShowTitle":title,"plot":plot}
        infoArt    = {"thumb":thumb,"poster":thumb,"fanart":FANART,"icon":ICON,"logo":ICON}
        self.addDir(title,vid_url,1,infoLabels,infoArt)
                            
                            
    def buildEpisodes(self, name, url, jsonResponse=None, videos=[], jsonKey='episodes'):
        log('buildEpisodes, ' + name)
        if jsonResponse is None: 
            jsonResponse = json.loads(self.openURL(url))['result']
            videos = jsonResponse[jsonKey]
        for video in videos:
            vid_url = (video.get('canonicalURL','') or video.get('url',None))
            title   = (video.get('title','')          or video.get('shortTitle',None))
            plot    = (video.get('description','')    or video.get('shortDescription','') or title)
            if vid_url is None or title is None: continue
            elif not vid_url.startswith(BASE_URL): continue
            try: show = video['show'].get('title',None)
            except: show = name
            try: thumb = video['images'][0]['url']
            except: thumb = video['image'][0]['url']
            try: season = int(video['season']['seasonNumber'])
            except: season = 0
            try: episode = int(video['season']['episodeAiringOrder'])
            except: episode = 0
            label   = '%s - %s'%(show,title)
            seinfo  = ('S' + ('0' if season < 10 else '') + str(season) + 'E' + ('0' if episode < 10 else '') + str(episode))
            if season + episode > 0: label = '%s - %s - %s'%(show, seinfo, title)
            try: aired = datetime.datetime.fromtimestamp(float(video['airDate']))
            except: aired = datetime.datetime.now()
            try: duration = video['duration']
            except: duration = 0
            infoLabels = {"mediatype":"episode","label":label ,"title":label,"TVShowTitle":show,"plot":plot,"aired":aired.strftime('%Y-%m-%d'),"duration":duration,"season":season,"episode":episode}
            infoArt      = {"thumb":thumb,"poster":thumb,"fanart":FANART,"icon":ICON,"logo":ICON}
            CONTENT_TYPE = 'episodes'
#.........这里部分代码省略.........
开发者ID:Lunatixz,项目名称:repo-plugins,代码行数:101,代码来源:comedycentral.py


示例13: __init__

 def __init__(self):
     self.cache   = SimpleCache()
     self.sources = self.openURL(SOURCES_URL).get('sources','')
开发者ID:Lunatixz,项目名称:repo-plugins,代码行数:3,代码来源:newsblender.py


示例14: NewsBlender

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]
#.........这里部分代码省略.........
开发者ID:Lunatixz,项目名称:repo-plugins,代码行数:101,代码来源:newsblender.py


示例15: MultiChannel

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)
开发者ID:Lunatixz,项目名称:repo-plugins,代码行数:92,代码来源:multichannel.py


示例16: __init__

 def __init__(self):
     log('__init__')
     self.cache     = SimpleCache()
     self.stateMenu = self.getStates()
开发者ID:Lunatixz,项目名称:repo-plugins,代码行数:4,代码来源:newson.py


示例17: CNN

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/ 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python simplecrypt.decrypt函数代码示例发布时间:2022-05-27
下一篇:
Python main.Main类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap