Пример #1
0
def setview(setting_name):
    setting = selfAddon.getSetting(setting_name)
    if setting == "0":
        xbmc.executebuiltin("Container.SetViewMode(50)")
    elif setting == "1":
        xbmc.executebuiltin("Container.SetViewMode(51)")
    elif setting == "2":
        xbmc.executebuiltin("Container.SetViewMode(500)")
    elif setting == "3":
        if "nox" in xbmc.getSkinDir():
            xbmc.executebuiltin("Container.SetViewMode(56)")
        else:
            xbmc.executebuiltin("Container.SetViewMode(501)")
    elif setting == "4":
        if "nox" in xbmc.getSkinDir():
            xbmc.executebuiltin("Container.SetViewMode(57)")
        else:
            xbmc.executebuiltin("Container.SetViewMode(508)")
    elif setting == "5":
        if "nox" in xbmc.getSkinDir():
            xbmc.executebuiltin("Container.SetViewMode(55)")
        else:
            xbmc.executebuiltin("Container.SetViewMode(504)")
    elif setting == "6":
        if "nox" in xbmc.getSkinDir():
            xbmc.executebuiltin("Container.SetViewMode(51)")
        else:
            xbmc.executebuiltin("Container.SetViewMode(503)")
    elif setting == "7":
        if "nox" in xbmc.getSkinDir():
            xbmc.executebuiltin("Container.SetViewMode(501)")
        else:
            xbmc.executebuiltin("Container.SetViewMode(515)")
    return
Пример #2
0
def show_categories(section_id):
    """
    Categories page
    :param section_id: Selected section ID
    :return:
    """
    api = API()

    for item in api.get_categories(int(section_id)):
        # list item:
        li = ListItem(item['name'].capitalize(),
                      iconImage='{0}/{1}'.format(config['urls']['calm_arts_host'], item['image']),
                      thumbnailImage='{0}/{1}'.format(config['urls']['calm_arts_host'], item['image']))
        li.setArt({
            'fanart': '{0}{1}'.format(config['urls']['calm_blurred_arts_host'], item['image'])
        })
        # directory item:
        addDirectoryItem(
                PLUGIN.handle,
                PLUGIN.url_for(show_channels, section_id=section_id, category_id=item['id']),
                li,
                True
        )
    # end of directory:
    endOfDirectory(PLUGIN.handle)
    executebuiltin('Container.SetViewMode({0})'.format(
            config['viewmodes']['thumbnail'][getSkinDir()
            if getSkinDir() in config['viewmodes']['thumbnail'] else 'skin.confluence']
    ))
Пример #3
0
    def _import_skinsettings( self ):
        import xbmcvfs
        # Set path
        self.backup_path = get_browse_dialog(dlg_type=1)
        # Check to see if file exists
        if xbmcvfs.exists( self.backup_path ):
            log("backup found")
            with open(self.backup_path) as f: fc = simplejson.load(f)
            progressDialog = xbmcgui.DialogProgress(__language__(32010))
            progressDialog.create(__language__(32010))
            xbmc.sleep(200)
            for count, skinsetting in enumerate(fc):
                if progressDialog.iscanceled():
                    return
                if skinsetting[1].startswith(xbmc.getSkinDir()):
                    progressDialog.update( (count * 100) / len(fc)  , __language__(32011) + ' %s' % skinsetting[1])
                    setting = skinsetting[1].replace(xbmc.getSkinDir() + ".","")
                    if skinsetting[0] == "string":
                        if skinsetting[2] <> "":
                            xbmc.executebuiltin( "Skin.SetString(%s,%s)" % (setting,skinsetting[2]) )
                        else:
                            xbmc.executebuiltin( "Skin.Reset(%s)" % setting )
                    elif skinsetting[0] == "bool":
                        if skinsetting[2] == "true":
                            xbmc.executebuiltin( "Skin.SetBool(%s)" % setting )
                        else:
                            xbmc.executebuiltin( "Skin.Reset(%s)" % setting )
                xbmc.sleep(30)
            xbmcgui.Dialog().ok(__language__(32005),__language__(32009))

        else:
            log("backup not found")
Пример #4
0
def import_skinsettings():
    importstring = read_from_file()
    if importstring:
        progressDialog = xbmcgui.DialogProgress(ADDON_LANGUAGE(32010))
        progressDialog.create(ADDON_LANGUAGE(32010))
        xbmc.sleep(200)
        for count, skinsetting in enumerate(importstring):
            if progressDialog.iscanceled():
                return
            if skinsetting[1].startswith(xbmc.getSkinDir()):
                progressDialog.update((count * 100) / len(importstring), ADDON_LANGUAGE(32011) + ' %s' % skinsetting[1])
                setting = skinsetting[1].replace(xbmc.getSkinDir() + ".", "")
                if skinsetting[0] == "string":
                    if skinsetting[2] is not "":
                        xbmc.executebuiltin("Skin.SetString(%s,%s)" % (setting, skinsetting[2]))
                    else:
                        xbmc.executebuiltin("Skin.Reset(%s)" % setting)
                elif skinsetting[0] == "bool":
                    if skinsetting[2] == "true":
                        xbmc.executebuiltin("Skin.SetBool(%s)" % setting)
                    else:
                        xbmc.executebuiltin("Skin.Reset(%s)" % setting)
            xbmc.sleep(30)
        xbmcgui.Dialog().ok(ADDON_LANGUAGE(32005), ADDON_LANGUAGE(32009))
    else:
        log("backup not found")
Пример #5
0
    def save_skin_image(self, skinstring="", multi_image=False, header=""):
        '''let the user select an image and save it to addon_data for easy backup'''
        cur_value = xbmc.getInfoLabel("Skin.String(%s)" % skinstring).decode("utf-8")
        cur_value_org = xbmc.getInfoLabel("Skin.String(%s.org)" % skinstring).decode("utf-8")

        if not multi_image:
            # single image (allow copy to addon_data)
            value = xbmcgui.Dialog().browse(2, header, 'files', '', True, True, cur_value_org).decode("utf-8")
            if value:
                ext = value.split(".")[-1]
                newfile = (u"special://profile/addon_data/%s/custom_images/%s.%s"
                           % (xbmc.getSkinDir(), skinstring + time.strftime("%Y%m%d%H%M%S", time.gmtime()), ext))
                if "special://profile/addon_data/%s/custom_images/" % xbmc.getSkinDir() in cur_value:
                    xbmcvfs.delete(cur_value)
                xbmcvfs.copy(value, newfile)
                xbmc.executebuiltin("Skin.SetString(%s.org,%s)" % (skinstring.encode("utf-8"), value.encode("utf-8")))
                value = newfile
        else:
            # multi image
            if not cur_value_org.startswith("$"):
                delim = "\\" if "\\" in cur_value_org else "/"
                curdir = cur_value_org.rsplit(delim, 1)[0] + delim
            else:
                curdir = ""
            value = xbmcgui.Dialog().browse(0, self.addon.getLocalizedString(32005),
                                            'files', '', True, True, curdir).decode("utf-8")
        return value
Пример #6
0
def setView(containerType,viewId):

    if viewId=="00":
        curView = xbmc.getInfoLabel("Container.Viewmode")
        viewId = getViewId(curView)
        
    else:
        viewId=viewId    

    if xbmc.getCondVisibility("System.HasAddon(plugin.video.netflixbmc)"):
        __settings__ = xbmcaddon.Addon(id='plugin.video.netflixbmc')

        if containerType=="MOVIES":
            __settings__.setSetting('viewIdVideos', viewId)
        elif containerType=="SERIES":
            __settings__.setSetting('viewIdEpisodesNew', viewId)
        elif containerType=="SEASONS":
            __settings__.setSetting('viewIdEpisodesNew', viewId)
        elif containerType=="EPISODES":
            __settings__.setSetting('viewIdEpisodesNew', viewId)
        else:
            __settings__.setSetting('viewIdActivity', viewId)
            
    if xbmc.getCondVisibility("System.HasAddon(plugin.video.xbmb3c)"):
        __settings__ = xbmcaddon.Addon(id='plugin.video.xbmb3c')
        if __settings__.getSetting(xbmc.getSkinDir()+ '_VIEW_' + containerType) != "disabled":
            __settings__.setSetting(xbmc.getSkinDir()+ '_VIEW_' + containerType, viewId)
Пример #7
0
def main_menu():
    addDir(translate(40114), MainURL, 400, addonpath + art + "web-parsers-menu.png", 2, True)
    addDir(translate(40115), MainURL, 100, addonpath + art + "xml_lists.png", 2, True)
    addDir(translate(40144), MainURL, 200, addonpath + art + "Favorites-menu.png", 2, True)
    if "confluence" in xbmc.getSkinDir():
        addLink("", "", "p2p")
    if (
        xbmc.getCondVisibility("system.platform.windows")
        or xbmc.getCondVisibility("system.platform.linux")
        or xbmc.getCondVisibility("System.Platform.OSX")
        or xbmc.getCondVisibility("System.Platform.Android")
    ):
        addDir(
            "[COLOR orange]AceStream: [/COLOR]" + translate(40004),
            MainURL,
            4,
            addonpath + art + "acestream-menu-item.png",
            1,
            False,
        )
        addDir(
            "[COLOR orange]AceStream: [/COLOR]" + translate(600029),
            MainURL,
            6,
            addonpath + art + "acestream-menu-item.png",
            1,
            False,
        )
    if (
        xbmc.getCondVisibility("system.platform.windows")
        or xbmc.getCondVisibility("system.platform.linux")
        or xbmc.getCondVisibility("System.Platform.OSX")
        or xbmc.getCondVisibility("System.Platform.Android")
    ):
        addDir(
            "[COLOR orange]SopCast: [/COLOR]" + translate(40005),
            MainURL,
            3,
            addonpath + art + "sopcast-menu-item.png",
            1,
            False,
        )
        addDir(
            "[COLOR orange]SopCast: [/COLOR]" + translate(40006),
            MainURL,
            5,
            addonpath + art + "sopcast-menu-item.png",
            1,
            False,
        )
    if xbmc.getCondVisibility("System.Platform.IOS") or xbmc.getCondVisibility("System.Platform.ATV2"):
        addLink(translate(40056), "", addonpath + art + "processwarning.png")
    if "confluence" in xbmc.getSkinDir():
        addLink("", "", "p2p")
    addDir("[B]" + translate(40057) + "[/B]", MainURL, 300, addonpath + art + "settings_menu.png", 2, True)
    xbmc.executebuiltin("Container.SetViewMode(50)")
    # break_sopcast is a function used in windows to intentionally break the sopcast.exe setup by renaming one of its codec files. It's ran here to rename the file again in case it failed when played before
    sop.break_sopcast()
 def skin_supported(self) :
     for extras_provider in self.aviable_providers :
     ## TODO: Check version of the Skin
         if xbmc.getSkinDir() == extras_provider.skin_name:
             self.log('Skin supported')
             self.skin_specific_provider = extras_provider
             return True
     
     xbmcgui.Dialog().ok(__addonid__, 'Skin unsupported', xbmc.getSkinDir())
     return False
Пример #9
0
 def _check_Window_Properties( self ):
     # Check if the user has changed skin or profile
     if self.WINDOW.getProperty("skinsettings-currentSkin-Path") and self.WINDOW.getProperty("skinsettings-currentProfile-Path"):
         if self.WINDOW.getProperty("skinsettings-currentSkin-Path") != xbmc.getSkinDir().encode( 'utf-8' ) or self.WINDOW.getProperty("skinsettings-currentProfile-Path") != __profilepath__.encode( 'utf-8' ):
             self.reset_window_properties()
             self.WINDOW.setProperty("skinsettings-currentSkin-Path", xbmc.getSkinDir() )
             self.WINDOW.setProperty("skinsettings-currentProfile-Path", __profilepath__ )
     else:
         self.WINDOW.setProperty("skinsettings-currentSkin-Path", xbmc.getSkinDir() )
         self.WINDOW.setProperty("skinsettings-currentProfile-Path", __profilepath__ )
Пример #10
0
def SearchResults(url, page):
	items = sortedItems(url, page, 'search')
	if plugin.get_setting('thumbview', bool):
		if xbmc.getSkinDir() in ('skin.confluence'):
			return plugin.finish(items, view_mode = 500)
		elif xbmc.getSkinDir() == 'skin.heidi':
			return plugin.finish(items, view_mode = 52)
		else:
			return plugin.finish(items)
	else:
		return plugin.finish(items)
Пример #11
0
def Genres(murl, page = 1):
	items = sortedItems(murl, page, 'genres')
	if plugin.get_setting('thumbview', bool):
		if xbmc.getSkinDir() in ('skin.confluence', 'skin.eminence'):
			return plugin.finish(items, view_mode = 500)
		elif xbmc.getSkinDir() == 'skin.heidi':
			return plugin.finish(items, view_mode = 52)
		else:
			return plugin.finish(items)
	else:
		return plugin.finish(items)
Пример #12
0
    def GetSkinPath(self, filename):
        from os import path

        default = 6
        defaultwide = 7
        try:
            fname = os.path.join("Q:\\skin", xbmc.getSkinDir(), "skin.xml")
            skindoc = xml.dom.minidom.parse(fname)
            root = skindoc.documentElement
            if not root or root.tagName != "skin":
                raise
            strDefault = self.FirstChildElement(root, "defaultresolution")
            if strDefault and strDefault.firstChild:
                default = self.resolutions.get(strDefault.firstChild.nodeValue.lower(), default)
            strDefaultWide = self.FirstChildElement(root, "defaultresolutionwide")
            if strDefaultWide and strDefaultWide.firstChild:
                defaultwide = self.resolutions.get(strDefaultWide.firstChild.nodeValue.lower(), defaultwide)
            skindoc.unlink()
        except:
            pass
        fname = os.path.join("Q:\\skin", xbmc.getSkinDir(), self.resPath[self.currentResolution], filename)
        if path.exists(fname):
            if filename == "references.xml":
                self.resolution = self.currentResolution
            self.debugWrite("GetSkinPath", True, ["Found path for %s at %s"], [(filename, fname)])
            return fname
            # if we're in 1080i mode, try 720p next
        if self.currentResolution == 0:
            fname = os.path.join("Q:\\skin", xbmc.getSkinDir(), self.resPath[1], filename)
            if path.exists(fname):
                if filename == "references.xml":
                    self.resolution = 1
                self.debugWrite("GetSkinPath", True, ["Found path for %s at %s"], [(filename, fname)])
                return fname
                # that failed - drop to the default widescreen resolution if we're in a widemode
        if self.currentResolution % 2:
            fname = os.path.join("Q:\\skin", xbmc.getSkinDir(), self.resPath[defaultwide], filename)
            if path.exists(fname):
                if filename == "references.xml":
                    self.resolution = defaultwide
                self.debugWrite("GetSkinPath", True, ["Found path for %s at %s"], [(filename, fname)])
                return fname
                # that failed - drop to the default resolution
        fname = os.path.join("Q:\\skin", xbmc.getSkinDir(), self.resPath[default], filename)
        if path.exists(fname):
            if filename == "references.xml":
                self.resolution = default
            self.debugWrite("GetSkinPath", True, ["Found path for %s at %s"], [(filename, fname)])
            return fname
        else:
            self.debugWrite("GetSkinPath", False, ["No path for %s found"], [(filename,)])
            return None
Пример #13
0
def show_favorites():
    """
    User's favorite channels list
    :return:
    """
    api = API()
    user = User()
    is_authenticated = user.authenticate()

    if is_authenticated:
        favorites = api.get_favorites(user.username, user.token)
        if len(favorites) > 0:
            for item in favorites:
                # list item:
                li = ListItem(u'{0} {1}'.format(item['title'].replace('CALM RADIO -', '').title(),
                                                '(VIP)' if 'free' not in item['streams'] else '',
                                                item['description']),
                              iconImage='{0}/{1}'.format(config['urls']['calm_arts_host'], item['image']),
                              thumbnailImage='{0}/{1}'.format(config['urls']['calm_arts_host'], item['image']))
                li.setArt({
                    'fanart': '{0}{1}'.format(config['urls']['calm_blurred_arts_host'], item['image'])
                })
                li.addContextMenuItems(
                        [(ADDON.getLocalizedString(32301), 'RunPlugin(plugin://{0}/favorites/remove/{1})'
                          .format(ADDON_ID, item['id']))]
                )
                # directory item:
                addDirectoryItem(
                        PLUGIN.handle,
                        PLUGIN.url_for(play_channel,
                                       category_id=item['category'],
                                       channel_id=item['id']),
                        li
                )
            # set the content of the directory
            setContent(ADDON_HANDLE, 'songs')
            # end of directory:
            endOfDirectory(PLUGIN.handle)
            executebuiltin('Container.SetViewMode({0})'.format(
                    config['viewmodes']['thumbnail'][getSkinDir()
                    if getSkinDir() in config['viewmodes']['thumbnail'] else 'skin.confluence']
            ))
        # favorites list is empty:
        else:
            executebuiltin('Notification("{0}", "{1}")'
                           .format(ADDON.getLocalizedString(30000), ADDON.getLocalizedString(32306)))
    # user is not authenticated:
    else:
        executebuiltin('Notification("{0}", "{1}")'
                       .format(ADDON.getLocalizedString(30000), ADDON.getLocalizedString(32110)))
Пример #14
0
def set_view(view_mode, view_code=0):
    _log("set_view view_mode='"+view_mode+"', view_code="+str(view_code))

    # Set the content for extended library views if needed
    if view_mode==MOVIES:
        _log("set_view content is movies")
        xbmcplugin.setContent( int(sys.argv[1]) ,"movies" )
    elif view_mode==TV_SHOWS:
        _log("set_view content is tvshows")
        xbmcplugin.setContent( int(sys.argv[1]) ,"tvshows" )
    elif view_mode==SEASONS:
        _log("set_view content is seasons")
        xbmcplugin.setContent( int(sys.argv[1]) ,"seasons" )
    elif view_mode==EPISODES:
        _log("set_view content is episodes")
        xbmcplugin.setContent( int(sys.argv[1]) ,"episodes" )

    # Reads skin name
    skin_name = xbmc.getSkinDir()
    _log("set_view skin_name='"+skin_name+"'")

    try:
        if view_code==0:
            _log("set_view view mode is "+view_mode)
            view_codes = ALL_VIEW_CODES.get(view_mode)
            view_code = view_codes.get(skin_name)
            _log("set_view view code for "+view_mode+" in "+skin_name+" is "+str(view_code))
            xbmc.executebuiltin("Container.SetViewMode("+str(view_code)+")")
        else:
            _log("set_view view code forced to "+str(view_code))
            xbmc.executebuiltin("Container.SetViewMode("+str(view_code)+")")
    except:
        _log("Unable to find view code for view mode "+str(view_mode)+" and skin "+skin_name)
Пример #15
0
 def view(self, content):
     try:
         skin = xbmc.getSkinDir()
         skinPath = xbmc.translatePath('special://skin/')
         xml = os.path.join(skinPath,'addon.xml')
         file = xbmcvfs.File(xml)
         read = file.read().replace('\n','')
         file.close()
         try: src = re.compile('defaultresolution="(.+?)"').findall(read)[0]
         except: src = re.compile('<res.+?folder="(.+?)"').findall(read)[0]
         src = os.path.join(skinPath, src)
         if xbmcgui.getCurrentWindowId() == 10501: src = os.path.join(src, 'MyMusicSongs.xml')
         else: src = os.path.join(src, 'MyMusicNav.xml')
         file = xbmcvfs.File(src)
         read = file.read().replace('\n','')
         file.close()
         views = re.compile('<views>(.+?)</views>').findall(read)[0]
         views = [int(x) for x in views.split(',')]
         for view in views:
             label = xbmc.getInfoLabel('Control.GetLabel(%s)' % (view))
             if not (label == '' or label is None): break
         file = xbmcvfs.File(viewData)
         read = file.read()
         file.close()
         file = open(viewData, 'w')
         for line in re.compile('(".+?\n)').findall(read):
             if not line.startswith('"%s"|"%s"|"' % (skin, content)): file.write(line)
         file.write('"%s"|"%s"|"%s"\n' % (skin, content, str(view)))
         file.close()
         viewName = xbmc.getInfoLabel('Container.Viewmode')
         index().infoDialog('%s%s%s' % (language(30301).encode("utf-8"), viewName, language(30302).encode("utf-8")))
     except:
         return
Пример #16
0
 def view(self, content):
     try:
         skin = xbmc.getSkinDir()
         skinPath = xbmc.translatePath('special://skin/')
         xml = os.path.join(skinPath,'addon.xml')
         file = xbmcvfs.File(xml)
         read = file.read().replace('\n','')
         file.close()
         try: src = re.compile('defaultresolution="(.+?)"').findall(read)[0]
         except: src = re.compile('<res.+?folder="(.+?)"').findall(read)[0]
         src = os.path.join(skinPath, src)
         src = os.path.join(src, 'MyVideoNav.xml')
         file = xbmcvfs.File(src)
         read = file.read().replace('\n','')
         file.close()
         views = re.compile('<views>(.+?)</views>').findall(read)[0]
         views = [int(x) for x in views.split(',')]
         for view in views:
             label = xbmc.getInfoLabel('Control.GetLabel(%s)' % (view))
             if not (label == '' or label == None): break
         record = (skin, content, str(view))
         dbcon = database.connect(addonSettings)
         dbcur = dbcon.cursor()
         dbcur.execute("CREATE TABLE IF NOT EXISTS views (""skin TEXT, ""view_type TEXT, ""view_id TEXT, ""UNIQUE(skin, view_type)"");")
         dbcur.execute("DELETE FROM views WHERE skin = '%s' AND view_type = '%s'" % (record[0], record[1]))
         dbcur.execute("INSERT INTO views Values (?, ?, ?)", record)
         dbcon.commit()
         viewName = xbmc.getInfoLabel('Container.Viewmode')
         index().infoDialog('%s%s%s' % (language(30301).encode("utf-8"), viewName, language(30302).encode("utf-8")))
     except:
         return
def set_view(view_mode, view_code=0):
    if get_setting('auto-view') == 'true':

        # Set the content for extended library views if needed
        xbmcplugin.setContent(int(sys.argv[1]), view_mode)
        if view_mode == MOVIES:
            xbmcplugin.setContent(int(sys.argv[1]), "movies")
        elif view_mode == TV_SHOWS:
            xbmcplugin.setContent(int(sys.argv[1]), "tvshows")
        elif view_mode == SEASONS:
            xbmcplugin.setContent(int(sys.argv[1]), "seasons")
        elif view_mode == EPISODES:
            xbmcplugin.setContent(int(sys.argv[1]), "episodes")
        elif view_mode == THUMBNAIL:
            xbmcplugin.setContent(int(sys.argv[1]), "thumbnail")
        elif view_mode == LIST:
            xbmcplugin.setContent(int(sys.argv[1]), "list")
        elif view_mode == SETS:
            xbmcplugin.setContent(int(sys.argv[1]), "sets")

        skin_name = xbmc.getSkinDir()  # Reads skin name
        try:
            if view_code == 0:
                view_codes = ALL_VIEW_CODES.get(view_mode)
                # kodi.log(view_codes)
                view_code = view_codes.get(skin_name)
                # kodi.log(view_code)
                xbmc.executebuiltin("Container.SetViewMode(" + str(view_code) + ")")
            # kodi.log("Setting First view code "+str(view_code)+" for view mode "+str(view_mode)+" and skin "+skin_name)
            else:
                xbmc.executebuiltin("Container.SetViewMode(" + str(view_code) + ")")
            # kodi.log("Setting Second view code for view mode "+str(view_mode)+" and skin "+skin_name)
        except:
            # kodi.log("Unable to find view code "+str(view_code)+" for view mode "+str(view_mode)+" and skin "+skin_name)
            pass
def switch_view():
	if _addon_result_thumbs == 'true':
		skin_used = xbmc.getSkinDir()
		if skin_used == 'skin.confluence':
			xbmc.executebuiltin('Container.SetViewMode(500)') # Вид "Эскизы".
		elif skin_used == 'skin.aeon.nox':
			xbmc.executebuiltin('Container.SetViewMode(512)') # Вид "Инфо-стена"
Пример #19
0
 def __init__(self):
     
     KodiMonitor = Kodi_Monitor()
     listItemMonitor = ListItemMonitor()
     backgroundsUpdater = BackgroundsUpdater()
     webService = WebService()
     lastSkin = None
                
     #start the extra threads
     listItemMonitor.start()
     backgroundsUpdater.start()
     webService.start()
     
     while not KodiMonitor.abortRequested():
         
         #set skin info
         if lastSkin != xbmc.getSkinDir():
             setSkinVersion()
         
         KodiMonitor.waitForAbort(5000)
     else:
         # Abort was requested while waiting. We should exit
         xbmc.log('SKIN HELPER SERVICE --> shutdown requested !')
         #stop the extra threads
         backgroundsUpdater.stop()
         listItemMonitor.stop()
         webService.stop()
Пример #20
0
def request(url,special=False):
      link=abrir_url(url).replace('&nbsp;','')
      if special:
            #hack para epocas anteriores
            listagolos=re.compile('<div class="matchlisting"><a href="(.+?)"><img.+?src="images/(.+?)\..+?" />\s*(.+?)</a></div>').findall(link)
            for endereco,thumb,multiple in listagolos:
                  data=multiple.split('(')[0]
                  hora=multiple.split('(')[1].split(')')[0]
                  rest=''.join(')'.join('('.join(multiple.split('(')[1:]).split(')')).split('- ')[1:])
                  addDir('[COLOR orange]%s[/COLOR][COLOR darkorange](%s)[/COLOR][COLOR blue] - [/COLOR][COLOR white]%s[/COLOR]' % (data,hora,rest),MainURL + endereco,1,os.path.join(art,'%s.png' % (thumb)),len(listagolos),pasta=False)
      else:
            listagolos=re.compile('<div class="matchlisting"><a href="(.+?)"><img.+?src="images/(.+?)\..+?" />\s+?([0-9]{4}\.[0-9]{2}\.[0-9]{2})\s*(\([0-9]{2}h[0-9]{2}\))\s*-\s*([A-Za-z ]+?)\s*([0-9]*)\s*-\s*([0-9]*)\s*([A-Za-z ]+?)</a></div>').findall(link)
            for endereco,thumb,data,hora,equipa1,resultado1,resultado2,equipa2 in listagolos:
                  addDir('[COLOR orange]%s[/COLOR] [COLOR darkorange]%s[/COLOR][COLOR blue] - [/COLOR][COLOR white]%s[/COLOR] [COLOR yellow]%s - %s[/COLOR] [COLOR white]%s[/COLOR]' % (data,hora,equipa1,resultado1,resultado2,equipa2),MainURL + endereco,1,os.path.join(art,'%s.png' % (thumb)),len(listagolos),pasta=False)

      if re.search('page-start', link):
            try:
                  try:enderecopagina=re.compile('</b> <a href="(.+?)">').findall(link)[0]
                  except: enderecopagina=re.compile('</b><a href="(.+?)">').findall(link)[0]
                  valorpagina=int(re.compile('page-start_from_(.+?)_archive.+?.html').findall(enderecopagina)[0])
                  pagina=int((valorpagina/30)+1)
                  if special==True: mode=8
                  else: mode=2
                  addDir('[COLOR blue][B]%s %s >[/COLOR][/B]' % (traducao(30003),pagina),MainURL + enderecopagina,mode,os.path.join(art,'proxima.png'),1)
            except: pass

      if "confluence" in xbmc.getSkinDir(): xbmc.executebuiltin("Container.SetViewMode(51)")
    def GetSkinFolder(rootDir, logFile):
        """Returns the folder that matches the currently active XBMC skin

        Arguments:
        rootDir : String - rootfolder of XOT
        logFile : Logger - logger to write logging to

        Returns:
        The name of the skinfolder that best matches the XBMC skin.

        It looks at the current XBMC skin folder name and tries to match it to
        a skin in the resources/skins/skin.<skin> or resources/skins/<skin> path.
        If a match was found that foldername is returned. If no match was found
        the default skin for XOT (skin.xot) is returned.

        """

        skinName = xbmc.getSkinDir()
        if os.path.exists(os.path.join(rootDir, "resources", "skins", skinName)):
            skinFolder = skinName
        elif os.path.exists(os.path.join(rootDir, "resources", "skins", "skin." + skinName.lower())):
            skinFolder = "skin.%s" % (skinName.lower(),)
        else:
            skinFolder = "skin.xot"
        Logger.Info("Setting Skin to: " + skinFolder)
        return skinFolder
Пример #22
0
 def endDir(self, sort=False, content=None, viewMode=None, ps=None):
     if ps == None:
         ps = int(sys.argv[1])
     if sort == True:
         xbmcplugin.addSortMethod(ps, xbmcplugin.SORT_METHOD_LABEL)
     canBeContent = ["files", "songs", "artists", "albums", "movies", "tvshows", "episodes", "musicvideos"]
     if content in canBeContent:
         xbmcplugin.setContent(ps, content)
     if viewMode != None:
         viewList = {}
         if "confluence" in xbmc.getSkinDir():
             viewList = {
                 "List": "50",
                 "Big List": "51",
                 "ThumbnailView": "500",
                 "PosterWrapView": "501",
                 "PosterWrapView2_Fanart": "508",
                 "MediaInfo": "504",
                 "MediaInfo2": "503",
                 "MediaInfo3": "515",
                 "WideIconView": "505",
                 "MusicVideoInfoListView": "511",
                 "AddonInfoListView1": "550",
                 "AddonInfoThumbView1": "551",
                 "LiveTVView1": "560",
             }
         if viewMode in viewList:
             view = viewList[viewMode]
         else:
             view = "None"
         xbmc.executebuiltin("Container.SetViewMode(%s)" % (view))
     xbmcplugin.endOfDirectory(ps)
Пример #23
0
def addDir(name,url,mode,iconimage):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
        ok=True
    
        already_exists = os.path.exists( os.path.join( SKIN_DIR, name ) )
        label2 = ( "", Language.getLocalizedString( 30005 ) )[ already_exists ]        
        liz=xbmcgui.ListItem( name, label2, iconImage="DefaultFolder.png", thumbnailImage=iconimage )
        infolabels = { "Title": name, "Genre": label2 }
        # Ajout d'un overlay pour dire qu'il est installer
        # ICON_OVERLAY_HD, ICON_OVERLAY_LOCKED, ICON_OVERLAY_NONE, ICON_OVERLAY_RAR, ICON_OVERLAY_HAS_TRAINER
        # ICON_OVERLAY_TRAINED, ICON_OVERLAY_UNWATCHED, ICON_OVERLAY_WATCHED, ICON_OVERLAY_ZIP
        overlay = ( xbmcgui.ICON_OVERLAY_UNWATCHED, xbmcgui.ICON_OVERLAY_WATCHED )[ already_exists ]
        # verifie si c'est pas le skin courant est change l'overlay pour un lock
        overlay = ( overlay, xbmcgui.ICON_OVERLAY_LOCKED )[ ( name.lower() == xbmc.getSkinDir().lower() ) ]
        infolabels.update( { "watched": already_exists, "overlay": overlay } )
        liz.setInfo( type="Video", infoLabels=infolabels )
        #ajout au menu pour supprimer la skin si elle existe
        print "overlay %s" % overlay
        if already_exists and not overlay == 3:
            script = "special://home/plugins/programs/Skins Nightly Builds Passion/resources/del_cache.py"
            c_items = []
            c_items += [ ( Language.getLocalizedString( 30045 ), "XBMC.RunScript(%s,%s,%s)" % ( script, "skin" , os.path.join( SKIN_DIR, name ) ) ) ]
            liz.addContextMenuItems( c_items, replaceItems=False )

        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
        return ok
Пример #24
0
def Ooo0OO0oOO(url):
    if url == None:
        Oo0Ooo.openSettings()
        sys.exit()
    elif url == i1I11iiiI or url == i1I11ii:
        oooO0oo0oOOOO = I1ii11iIi1(url)
    else:
        oooO0oo0oOOOO = I1ii11iIi11i(url)
    O0oO = re.compile("<name>(.*?)</name>").findall(oooO0oo0oOOOO)
    if len(O0oO) <= 1:
        o0oO0 = re.compile("<item>(.+?)</item>").findall(oooO0oo0oOOOO)
        for oo00 in o0oO0:
            o00 = ""
            Oo0oO0ooo = ""
            o0oOoO00o = ""
            if "/title" in oo00:
                Oo0oO0ooo = re.compile("<title>(.+?)</title>").findall(oo00)[0]
            if "/link" in oo00:
                o0oOoO00o = re.compile("<link>(.+?)</link>").findall(oo00)[0]
            if "/thumbnail" in oo00:
                o00 = re.compile("<thumbnail>(.*?)</thumbnail>").findall(oo00)[0]
                if o00 == "tvchina.png":
                    o00 = O0O0OO0O + "/" + "tvchina.png"
            i1(Oo0oO0ooo, o0oOoO00o, "play", o00)
        IiII = xbmc.getSkinDir()
        if IiII == "skin.xeebo":
            xbmc.executebuiltin("Container.SetViewMode(52)")
    else:
        for oOOoo00O0O in O0oO:
            if oOOoo00O0O.startswith("TV"):
                iI111iI(oOOoo00O0O, url + "&n=" + oOOoo00O0O, "index", O0O0OO0O + "/" + "tvvn.png")
            else:
                iI111iI(oOOoo00O0O, url + "&n=" + oOOoo00O0O, "index", "")
            if 15 - 15:
                I11iii11IIi
Пример #25
0
def O00o0o0000o0o(url):
    O0Oo = url.split("&n=")[1]
    url = url.split("&n=")[0]
    if url == i1I11iiiI or url == i1I11ii:
        oooO0oo0oOOOO = I1ii11iIi1(url)
    else:
        oooO0oo0oOOOO = I1ii11iIi11i(url)
    oo = re.compile("<channel>(.+?)</channel>").findall(oooO0oo0oOOOO)
    for IiII1I1i1i1ii in oo:
        if O0Oo in IiII1I1i1i1ii:
            o0oO0 = re.compile("<item>(.+?)</item>").findall(IiII1I1i1i1ii)
            for oo00 in o0oO0:
                o00 = ""
                Oo0oO0ooo = ""
                o0oOoO00o = ""
                if "/title" in oo00:
                    Oo0oO0ooo = re.compile("<title>(.+?)</title>").findall(oo00)[0]
                if "/link" in oo00:
                    o0oOoO00o = re.compile("<link>(.+?)</link>").findall(oo00)[0]
                if "/thumbnail" in oo00:
                    o00 = re.compile("<thumbnail>(.*?)</thumbnail>").findall(oo00)[0]
                    if o00 == "tvvn.png":
                        o00 = O0O0OO0O + "/" + "tvvn.png"
                i1(Oo0oO0ooo, o0oOoO00o, "play", o00)
    IiII = xbmc.getSkinDir()
    if IiII == "skin.xeebo":
        xbmc.executebuiltin("Container.SetViewMode(52)")
        if 44 - 44:
            OOo0o0 / OOoOoo00oo - iI1OoOooOOOO + i1iiIII111ii + i1iIIi1
Пример #26
0
 def endDir(self, sort=False, content=None, viewMode=None, ps=None):
     if ps==None:
         ps=int(sys.argv[1])
     if sort==True:
         xbmcplugin.addSortMethod(ps, xbmcplugin.SORT_METHOD_LABEL)
     canBeContent = ["files", "songs", "artists", "albums", "movies", "tvshows", "episodes", "musicvideos"]
     if content in canBeContent:
         xbmcplugin.setContent(ps,content)
     if viewMode!=None:
         viewList = {}
         if 'confluence' in xbmc.getSkinDir():
             viewList = {
                 'List':                                         '50',
                 'Big List':                                     '51',
                 'ThumbnailView':                        '500',
                 'PosterWrapView':                       '501',
                 'PosterWrapView2_Fanart':       '508',
                 'MediaInfo':                            '504',
                 'MediaInfo2':                           '503',
                 'MediaInfo3':                           '515',
                 'WideIconView':                         '505',
                 'MusicVideoInfoListView':       '511',
                 'AddonInfoListView1':           '550',
                 'AddonInfoThumbView1':          '551',
                 'LiveTVView1':                          '560'
             }
         if viewMode in viewList:
             view = viewList[viewMode]
         else:
             view='None'
         xbmc.executebuiltin("Container.SetViewMode(%s)" % (view))
     xbmcplugin.endOfDirectory(ps)
Пример #27
0
def iI1():
    iI111iI(
        Oo0Ooooo(30001).encode("utf-8"),
        O0O0OO0O0 + Oo0Ooooo(30002).encode("utf-8"),
        "indexgroup",
        i1I11i.replace("temp.jpg", "icon.png"),
    )
    iI111iI(Oo0Ooooo(30003).encode("utf-8"), i1I11iiiI, "indexgroup", O0O0OO0O + "/" + Oo0Ooooo(30004).encode("utf-8"))
    iI111iI(Oo0Ooooo(30005).encode("utf-8"), i1I11ii, "indexgroup", O0O0OO0O + "/" + Oo0Ooooo(30006).encode("utf-8"))
    iI111iI(Oo0Ooooo(30007).encode("utf-8"), "o0oOo0o", None, O0O0OO0O + "/" + Oo0Ooooo(30008).encode("utf-8"))
    Oo = I1ii11iIi11i(O0o0OO0)
    if "xml" in Oo:
        o0OOO = Oo
        for iIiiiI, Iii1ii1II11i in eval(o0OOO):
            Iii1ii1II11i = xbmc.translatePath(os.path.join(O0O0OO0O0, "resources", "data", Iii1ii1II11i))
            i1I11i11 = i1I11i.replace("temp.jpg", "icon.png")
            if iIiiiI == Oo0Ooooo(30009).encode("utf-8"):
                iI111iI(iIiiiI, Iii1ii1II11i, "indexgroup", O0O0OO0O + "/" + Oo0Ooooo(30010).encode("utf-8"))
            elif iIiiiI == Oo0Ooooo(30011).encode("utf-8"):
                iI111iI(iIiiiI, Iii1ii1II11i, "indexgroup", O0O0OO0O + "/" + Oo0Ooooo(30012).encode("utf-8"))
            else:
                if Oo0Ooooo(30013).encode("utf-8") in iIiiiI:
                    Iii1ii1II11i = ("http:" + Iii1ii1II11i.split(":")[-1]) % i1II11i()
                elif Oo0Ooooo(30014).encode("utf-8") in iIiiiI:
                    i1I11i11 = O0O0OO0O + "/" + Oo0Ooooo(30015).encode("utf-8")
                iI111iI(iIiiiI, Iii1ii1II11i, "indexgroup", i1I11i11)
        IiII = xbmc.getSkinDir()
        if IiII == "skin.xeebo":
            xbmc.executebuiltin("Container.SetViewMode(50)")
    else:
        iI1Ii11111iIi = xbmcgui.Dialog()
        iI1Ii11111iIi.ok("ID: %s" % O0O, Oo)
    if 41 - 41:
        I1II1
Пример #28
0
def Index(url,iconimage):
    byname = url.split("?n=")[1]
    url = url.split("?")[0]
    xmlcontent = GetUrl(url)
    channels = re.compile('<channel>(.+?)</channel>').findall(xmlcontent)
    for channel in channels:
        if byname in channel:
            items = re.compile('<item>(.+?)</item>').findall(channel)
            for item in items:
                thumb=""
                title=""
                link=""
                if "/title" in item:
                    title = re.compile('<title>(.+?)</title>').findall(item)[0]
                if "/link" in item:
                    link = re.compile('<link>(.+?)</link>').findall(item)[0]
                if "/thumbnail" in item:
                    thumb = re.compile('<thumbnail>(.+?)</thumbnail>').findall(item)[0]
                if "youtube" in link:					
                    addDir(title, link, 'episodes', thumb)
                else:					
                    addLink('' + title + '', link, 'play', thumb)
    skin_used = xbmc.getSkinDir()
    if skin_used == 'skin.xeebo':
        xbmc.executebuiltin('Container.SetViewMode(50)')
Пример #29
0
def display_path(path):
    """
    Display path depending on its contents: video item, video list or categories.
    """
    __log__('display_path; path', path)
    if plugin.addon.getSetting('cache_pages') == 'true':
        page_type, contents = check_page(path)
    else:
        page_type, contents = exua_parser.check_page(path)
    view_mode = None
    if page_type == 'video_page':
        listing = views.list_video_details(plugin, contents)
        if plugin.addon.getSetting('use_skin_info') == 'true':
            # Switch view based on a current skin.
            current_skin = xbmc.getSkinDir()
            if current_skin in ('skin.confluence', 'skin.confluence-plood', 'skin.confluence-plood-gotham'):
                view_mode = 503
            elif current_skin in ('skin.aeon.nox', 'skin.aeon.nox.gotham', 'skin.aeon.shednox.helix'):
                view_mode = 52
            elif current_skin == 'skin.aeon.nox.5':
                view_mode = 55
    elif page_type == 'video_list':
        listing = views.list_videos(plugin, contents, path=path)
    elif page_type == 'categories':
        listing = views.list_categories(plugin, contents)
    else:
        listing = []
    __log__('display_path; listing', listing)
    return plugin.finish(listing, view_mode=view_mode)
def getThumbnailModeID():
    VIEW_MODES = {
        'thumbnail': {
            'skin.confluence': 500,
            'skin.aeon.nox': 551,
            'skin.confluence-vertical': 500,
            'skin.jx720': 52,
            'skin.pm3-hd': 53,
            'skin.rapier': 50,
            'skin.simplicity': 500,
            'skin.slik': 53,
            'skin.touched': 500,
            'skin.transparency': 53,
            'skin.xeebo': 55,
        }
    }


    skin = xbmc.getSkinDir()
    try:
        thumbID = VIEW_MODES['thumbnail'][skin]
    except:
        thumbID = VIEW_MODES['thumbnail']['skin.confluence']

    return thumbID
Пример #31
0
def Genres(murl, page = 1):
	items = sortedItems(murl, page, 'genres')
	if xbmc.getSkinDir() == 'skin.heidi' and plugin.get_setting('thumbview', bool):
		return plugin.finish(items, view_mode = 53)
	else :
		return plugin.finish(items)
Пример #32
0
def verify_directories_created():
    from core import logger
    from core import filetools
    from platformcode import xbmc_library

    config_paths = [["librarypath",      "library"],
                    ["downloadpath",     "downloads"],
                    ["downloadlistpath", "downloads/list"],
                    ["settings_path",    "settings_channels"]]

    for path, default in config_paths:
        saved_path = get_setting(path)

        # Biblioteca
        if path == "librarypath":
            set_setting("library_version", "v4")
            if not saved_path:
                saved_path = xbmc_library.search_library_path()
                if saved_path:
                    set_setting(path, saved_path)

        if not saved_path:
            saved_path = "special://profile/addon_data/plugin.video." + PLUGIN_NAME + "/" + default
            set_setting(path, saved_path)

        if get_setting("library_set_content") == True and path in ["librarypath", "downloadpath"]:
            # logger.debug("library_set_content %s" % get_setting("library_set_content"))
            xbmc_library.add_sources(saved_path)

        saved_path = xbmc.translatePath(saved_path)
        if not filetools.exists(saved_path):
            logger.debug("Creating %s: %s" % (path, saved_path))
            filetools.mkdir(saved_path)

    config_paths = [["folder_movies", "CINE"],
                    ["folder_tvshows", "SERIES"]]

    for path, default in config_paths:
        saved_path = get_setting(path)

        if not saved_path:
            saved_path = default
            set_setting(path, saved_path)

        content_path = filetools.join(get_library_path(), saved_path)
        if not filetools.exists(content_path):
            logger.debug("Creating %s: %s" % (path, content_path))
            if filetools.mkdir(content_path) and get_setting("library_set_content") == True:
                xbmc_library.set_content(default)

        elif get_setting("library_ask_set_content") == 2:
            xbmc_library.set_content(default)

    try:
        from core import scrapertools
        # Buscamos el archivo addon.xml del skin activo
        skindir = filetools.join(xbmc.translatePath("special://home"), 'addons', xbmc.getSkinDir(),
                                 'addon.xml')
        # Extraemos el nombre de la carpeta de resolución por defecto
        folder = ""
        data = filetools.read(skindir)
        res = scrapertools.find_multiple_matches(data, '(<res .*?>)')
        for r in res:
            if 'default="true"' in r:
                folder = scrapertools.find_single_match(r, 'folder="([^"]+)"')
                break

        # Comprobamos si existe en mitvspain y sino es así, la creamos
        default = filetools.join(get_runtime_path(), 'resources', 'skins', 'Default')
        if folder and not filetools.exists(filetools.join(default, folder)):
            filetools.mkdir(filetools.join(default, folder))

        # Copiamos el archivo a dicha carpeta desde la de 720p si éste no existe o si el tamaño es diferente
        if folder and folder != '720p':
            for root, folders, files in filetools.walk(filetools.join(default, '720p')):
                for f in files:
                    if not filetools.exists(filetools.join(default, folder, f)) or \
                          (filetools.getsize(filetools.join(default, folder, f)) != 
                           filetools.getsize(filetools.join(default, '720p', f))):
                        filetools.copy(filetools.join(default, '720p', f),
                                       filetools.join(default, folder, f),
                                       True)
    except:
        import traceback
        logger.error("Al comprobar o crear la carpeta de resolución")
        logger.error(traceback.format_exc())
Пример #33
0
    def _try_get_color_from_skin():
        skin_dir = xbmc.getSkinDir()
        skin_color = None
        if not skin_dir:
            return None
        skin_theme = xbmc.getInfoLabel("Skin.CurrentTheme")
        if not skin_theme:
            return None
        skin_theme = skin_theme.lower()
        if skin_dir == "skin.confluence":
            skin_color = "FFEB9E17"
        elif skin_dir == "skin.estuary":
            if "brown" in skin_theme:
                skin_color = "FFFF4400"
            elif "charcoal" in skin_theme:
                skin_color = "FF11E7B1"
            elif "chartreuse" in skin_theme:
                skin_color = "FF24C6C9"
            elif "concrete" in skin_theme:
                skin_color = "FFFF8C00"
            elif "default" in skin_theme:
                skin_color = "FF11E7B1"
            elif "gold" in skin_theme:
                skin_color = "FFFFF000"
            elif "green" in skin_theme:
                skin_color = "FF14D519"
            elif "maroon" in skin_theme:
                skin_color = "FF24C6C9"
            elif "midnight" in skin_theme:
                skin_color = "FF5BE5EE"
            elif "orange" in skin_theme:
                skin_color = "FFFFF100"
            elif "pink" in skin_theme:
                skin_color = "FF94D800"
            elif "rose" in skin_theme:
                skin_color = "FFFF0261"
            elif "teal" in skin_theme:
                skin_color = "FFC67F03"
            elif "violet" in skin_theme:
                skin_color = "FFFF0054"
        elif skin_dir == "skin.estouchy":
            skin_color = "FF11E7B1"
        elif skin_dir == "skin.arctic.horizon":
            skin_color = "ff0385b5"
        elif skin_dir == "skin.arctic.zephyr":
            skin_color = "ff0385b5"
        elif skin_dir == "skin.arctic.zephyr.2":
            skin_color = "ff0385b5"
        elif skin_dir == "skin.aura":
            skin_color = "ff0385b5 "
        elif skin_dir == "skin.eminence.2":
            skin_color = "ff287ba8"
        elif skin_dir == "skin.eminence":
            if "crimson" in skin_theme:
                skin_color = "ffdc143c"
            elif "emerald" in skin_theme:
                skin_color = "ff46b995"
            elif "lilac" in skin_theme:
                skin_color = "ffa682a6"
            elif "lime" in skin_theme:
                skin_color = "FFb5e533"
            elif "magenta" in skin_theme:
                skin_color = "FFe533b5"
            elif "orange" in skin_theme:
                skin_color = "ffd76c38"
            elif "default" in skin_theme:
                skin_color = "FF33b5e5"
        elif skin_dir == "skin.aura":
            skin_color = "ffededed"
        elif skin_dir == "skin.fuse.neue":
            skin_color = "ffe53564"
        elif skin_dir == "skin.auramod":
            skin_color = "ffededed"

        result = xbmc.getInfoLabel("Skin.String({})".format(
            "focuscolor.name")  # jurial based skins.
                                   )
        return result if result else skin_color
Пример #34
0
ADDONID = wiz.addonInfo(ADDON_ID, 'id')
DIALOG = xbmcgui.Dialog()
DP = xbmcgui.DialogProgress()
HOME = xbmc.translatePath('special://home/')
PROFILE = xbmc.translatePath('special://profile/')
KODIHOME = xbmc.translatePath('special://xbmc/')
ADDONS = os.path.join(HOME, 'addons')
KODIADDONS = os.path.join(KODIHOME, 'addons')
USERDATA = os.path.join(HOME, 'userdata')
PLUGIN = os.path.join(ADDONS, ADDON_ID)
PACKAGES = os.path.join(ADDONS, 'packages')
ADDONDATA = os.path.join(USERDATA, 'addon_data', ADDON_ID)
FANART = os.path.join(ADDONPATH, 'fanart.jpg')
ICON = os.path.join(ADDONPATH, 'icon.png')
ART = os.path.join(ADDONPATH, 'resources', 'art')
SKIN = xbmc.getSkinDir()
BUILDNAME = wiz.getS('buildname')
DEFAULTSKIN = wiz.getS('defaultskin')
DEFAULTNAME = wiz.getS('defaultskinname')
DEFAULTIGNORE = wiz.getS('defaultskinignore')
BUILDVERSION = wiz.getS('buildversion')
BUILDLATEST = wiz.getS('latestversion')
BUILDCHECK = wiz.getS('lastbuildcheck')
DISABLEUPDATE = wiz.getS('disableupdate')
AUTOCLEANUP = wiz.getS('autoclean')
AUTOCACHE = wiz.getS('clearcache')
AUTOPACKAGES = wiz.getS('clearpackages')
AUTOTHUMBS = wiz.getS('clearthumbs')
AUTOFEQ = wiz.getS('autocleanfeq')
AUTONEXTRUN = wiz.getS('nextautocleanup')
TRAKTSAVE = wiz.getS('traktlastsave')
Пример #35
0
def backup():
    try:
        #get backup destination
        backup_path = None
        backup_path = get_browse_dialog(dlg_type=3,
                                        heading=__language__(31283))
        if backup_path != None and backup_path != "":

            from xml.dom.minidom import parse
            guisettings_path = xbmc.translatePath(
                'special://profile/guisettings.xml').decode("utf-8")
            if xbmcvfs.exists(guisettings_path):
                logMsg("guisettings.xml found")
                doc = parse(guisettings_path)
                skinsettings = doc.documentElement.getElementsByTagName(
                    'setting')
                newlist = []
                for count, skinsetting in enumerate(skinsettings):
                    if skinsetting.childNodes:
                        value = skinsetting.childNodes[0].nodeValue
                    else:
                        value = ""
                    if skinsetting.attributes['name'].nodeValue.startswith(
                            xbmc.getSkinDir()):
                        name = skinsetting.attributes['name'].nodeValue
                        name = name.replace(xbmc.getSkinDir(), "TITANSKIN")
                        newlist.append(
                            (skinsetting.attributes['type'].nodeValue, name,
                             value))

                if not xbmcvfs.exists(backup_path):
                    xbmcvfs.mkdir(backup_path)

                #create temp path
                temp_path = xbmc.translatePath(
                    'special://temp/skinbackup/').decode("utf-8")
                if xbmcvfs.exists(temp_path):
                    shutil.rmtree(temp_path)
                xbmcvfs.mkdir(temp_path)

                skinshortcuts_path = temp_path + "skinshortcuts/"
                if not xbmcvfs.exists(skinshortcuts_path):
                    xbmcvfs.mkdir(skinshortcuts_path)

                #get skinshortcuts preferences
                skinshortcuts_path_source = xbmc.translatePath(
                    'special://profile/addon_data/script.skinshortcuts/'
                ).decode("utf-8")
                logMsg(skinshortcuts_path_source)
                if xbmcvfs.exists(skinshortcuts_path_source):
                    dirs, files = xbmcvfs.listdir(skinshortcuts_path_source)
                    for file in files:
                        if ".xml" in file:
                            sourcefile = skinshortcuts_path_source + file
                            destfile = skinshortcuts_path + file
                            logMsg("source --> " + sourcefile)
                            logMsg("destination --> " + destfile)
                            xbmcvfs.copy(sourcefile, destfile)

                #save guisettings
                text_file_path = os.path.join(temp_path, "guisettings.txt")
                text_file = xbmcvfs.File(text_file_path, "w")
                json.dump(newlist, text_file)
                text_file.close()

                from datetime import datetime
                i = datetime.now()

                #zip the backup
                zip(
                    temp_path, backup_path + "TITANSKIN_BACKUP_" +
                    i.strftime('%Y%m%d-%H%M'))

                #cleanup temp
                shutil.rmtree(temp_path)

                xbmcgui.Dialog().ok(__language__(31272), __language__(31278))

            else:
                xbmcgui.Dialog().ok(__language__(31272), __language__(31279))
                logMsg("guisettings.xml not found")

    except:
        xbmcgui.Dialog().ok(__language__(31272), __language__(31279))
        xbmc.log("exception in creating skin backup")
Пример #36
0
 def get_skin_id(self):
     return xbmc.getSkinDir()
Пример #37
0
	def _directory(self):
		return xbmc.getSkinDir()
Пример #38
0
def get_view_mode_id(view_mode):
    view_mode_ids = VIEW_MODES.get(view_mode.lower())
    if view_mode_ids:
        return view_mode_ids.get(xbmc.getSkinDir())
    return None
Пример #39
0
def verify_directories_created():
    """
    Test if all the required directories are created
    """
    from platformcode import logger
    from core import filetools
    from platformcode import xbmc_videolibrary

    logger.info()
    time.sleep(1)

    config_paths = [["videolibrarypath", "videolibrary"],
                    ["downloadpath", "downloads"],
                    ["downloadlistpath", "downloads/list"],
                    ["settings_path", "settings_channels"]]

    for path, default in config_paths:
        saved_path = get_setting(path)

        # videoteca
        if path == "videolibrarypath":
            if not saved_path:
                saved_path = xbmc_videolibrary.search_library_path()
                if saved_path:
                    set_setting(path, saved_path)

        if not saved_path:
            saved_path = "special://profile/addon_data/plugin.video." + PLUGIN_NAME + "/" + default
            set_setting(path, saved_path)

        saved_path = translatePath(saved_path)
        if not filetools.exists(saved_path):
            logger.debug("Creating %s: %s" % (path, saved_path))
            filetools.mkdir(saved_path)

    config_paths = [["folder_movies", "CINE"], ["folder_tvshows", "SERIES"]]

    for path, default in config_paths:
        saved_path = get_setting(path)

        if not saved_path:
            saved_path = default
            set_setting(path, saved_path)

        content_path = filetools.join(get_videolibrary_path(), saved_path)
        if not filetools.exists(content_path):
            logger.debug("Creating %s: %s" % (path, content_path))

            # si se crea el directorio
            filetools.mkdir(content_path)

    try:
        # from core import scrapertools
        # Buscamos el archivo addon.xml del skin activo
        skindir = filetools.join("special://home", 'addons', xbmc.getSkinDir(),
                                 'addon.xml')
        if not os.path.isdir(skindir):
            return  # No hace falta mostrar error en el log si no existe la carpeta
        # Extraemos el nombre de la carpeta de resolución por defecto
        folder = ""
        data = filetools.read(skindir)
        # res = scrapertools.find_multiple_matches(data, '(<res .*?>)')
        res = re.compile('(<res .*?>)', re.DOTALL).findall(data)
        for r in res:
            if 'default="true"' in r:
                # folder = scrapertools.find_single_match(r, 'folder="([^"]+)"')
                folder = re.search('folder="([^"]+)"', r).group(1)
                break

        # Comprobamos si existe en el addon y sino es así, la creamos
        default = filetools.join(get_runtime_path(), 'resources', 'skins',
                                 'Default')
        if folder and not filetools.exists(filetools.join(default, folder)):
            filetools.mkdir(filetools.join(default, folder))

        # Copiamos el archivo a dicha carpeta desde la de 720p si éste no existe o si el tamaño es diferente
        if folder and folder != '720p':
            for root, folders, files in filetools.walk(
                    filetools.join(default, '720p')):
                for f in files:
                    if not filetools.exists(filetools.join(default, folder, f)) or \
                            (filetools.getsize(filetools.join(default, folder, f)) !=
                             filetools.getsize(filetools.join(default, '720p', f))):
                        filetools.copy(filetools.join(default, '720p', f),
                                       filetools.join(default, folder, f),
                                       True)
    except:
        import traceback
        logger.error("Al comprobar o crear la carpeta de resolución")
        logger.error(traceback.format_exc())
Пример #40
0
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import xbmcaddon
import xbmcgui
import xbmc
import xbmcvfs
import random
import os
from datetime import datetime

Addon = xbmcaddon.Addon('screensaver.digitalclock')
path = Addon.getAddonInfo('path')
location = xbmc.getSkinDir()
scriptname = location + '.xml'
Addonversion = Addon.getAddonInfo('version')


class Screensaver(xbmcgui.WindowXMLDialog):

    #setting up zoom
    window = xbmcgui.Window(12900)
    window.setProperty("zoomamount", Addon.getSetting('zoomlevel'))
    del window

    class ExitMonitor(xbmc.Monitor):
        def __init__(self, exit_callback):
            self.exit_callback = exit_callback
Пример #41
0
import sys
import math
import xbmc
import xbmcaddon
import xbmcgui
import xbmcvfs
from traceback import format_exc
from contextlib import contextmanager

ADDON_ID = "script.skin.helper.colorpicker"
ADDON = xbmcaddon.Addon(ADDON_ID)
ADDON_PATH = ADDON.getAddonInfo('path')
COLORFILES_PATH = xbmc.translatePath(
    "special://profile/addon_data/%s/colors/" % ADDON_ID)
SKINCOLORFILES_PATH = xbmc.translatePath(
    "special://profile/addon_data/%s/colors/" % xbmc.getSkinDir())
SKINCOLORFILE = xbmc.translatePath("special://skin/extras/colors/colors.xml")
WINDOW = xbmcgui.Window(10000)
SUPPORTS_PIL = False
PYTHON3 = True if sys.version_info.major == 3 else False

# HELPERS ###########################################


def log_msg(msg, level=xbmc.LOGDEBUG):
    '''log message to kodi log'''
    xbmc.log("Skin Helper Service ColorPicker --> %s" % msg, level=level)


def log_exception(modulename, exceptiondetails):
    '''helper to properly log an exception'''
Пример #42
0
#Web based list:
url = "https://raw.githubusercontent.com/v137/kodi/master/json/plugin.video.viettube.channels.json"
response = urllib.urlopen(url)
data = json.loads(response.read())
xbmc.log(str(data["catalogues"]))

#File based list:
#file = addon.getAddonInfo('path') + '/plugin.video.viettube.channels.json'
#f = open (file, 'r')
#data = json.loads(f.read())
#f.close()
#xbmc.log(str(data["catalogues"]))

if mode is None:
    skin_used = xbmc.getSkinDir()
    if skin_used == 'skin.heidi':
        xbmc.executebuiltin('Container.SetViewMode(53)')
    elif skin_used == 'skin.confluence':
        xbmc.executebuiltin('Container.SetViewMode(500)')

    for cat in data["catalogues"]:
        foldername = cat["name"].encode('utf-8')
        xbmc.log(cat["name"].encode('utf-8'))
        url = build_url({
            'mode': 'folder',
            'foldername': foldername,
            "id": str(cat["id"])
        })
        thumb = cat["thumb"]
        li = xbmcgui.ListItem(foldername,
Пример #43
0
class Main:
    # base urls
    BASE_URL = "http://www.screamer-radio.com/update.php"

    # base paths
    BASE_PATH = os.getcwd().replace(";", "")
    BASE_DATA_PATH = os.path.join(
        xbmc.translatePath("special://profile/plugin_data/music"), __plugin__)
    BASE_SOURCE_PATH = os.path.join(BASE_DATA_PATH, "screamer.xml")
    BASE_SKIN_THUMBNAIL_PATH = os.path.join(
        xbmc.translatePath("special://profile/skin"), xbmc.getSkinDir(),
        "media", __plugin__)
    BASE_PLUGIN_THUMBNAIL_PATH = os.path.join(BASE_PATH, "resources",
                                              "thumbnails")

    def __init__(self):
        self._parse_argv()
        ok = self.get_items()
        # send notification we're finished, successfully or unsuccessfully
        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)

    def _parse_argv(self):
        # call _Info() with our formatted argv to create the self.args object
        if (sys.argv[2]):
            exec "self.args = _Info(%s)" % (sys.argv[2][1:].replace(
                "&", ", ").replace("\\u0027", "'").replace(
                    "\\u0022", '"').replace("\\u0026", "&"), )
        else:
            self.args = _Info(levels=[])

    def get_items(self):
        # TODO: change this to True when finished
        ok = self.get_xml_source()
        if (ok):
            categories, stations = self.parse_xml_source(
                self.BASE_SOURCE_PATH, self.args.levels)
            if (categories):
                ok = self._fill_media_list_categories(categories)
            else:
                ok = self._fill_media_list_stations(stations)
        return ok

    def get_xml_source(self):
        try:
            # TODO: check date of file and download new if older than a day.
            ok = True
            # get the source files date if it exists
            try:
                date = os.path.getmtime(self.BASE_SOURCE_PATH)
            except:
                date = 0
            # we only refresh if it's been more than a day, 24hr * 60min * 60sec
            refresh = ((time.time() - (24 * 60 * 60)) >= date)
            # only fetch source if it's been more than a day
            if (refresh):
                # open url
                usock = urllib.urlopen(self.BASE_URL)
                # read source
                xmlSource = usock.read()
                # close socket
                usock.close()
                # save the xmlSource for future parsing
                ok = self.save_xml_source(xmlSource)
        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
        return ok

    def save_xml_source(self, xmlSource):
        try:
            # if the path to the source file does not exist create it
            if (not os.path.isdir(self.BASE_DATA_PATH)):
                os.makedirs(self.BASE_DATA_PATH)
            # open source path for writing
            file_object = open(self.BASE_SOURCE_PATH, "w")
            # write xmlSource
            file_object.write(xmlSource)
            # close file object
            file_object.close()
            # return successful
            return True
        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],
            )
            return False

    def parse_xml_source(self, xmlSource="", levels=[]):
        # Parse xmlSource for categories
        parser = _Parser(xmlSource, levels)
        return parser.categories, parser.stations

    def _fill_media_list_categories(self, categories):
        try:
            ok = True
            # enumerate through the list of categories and add the item to the media list
            for category in categories:
                url = "%s?title=%s&levels=%s&isFolder=%d" % (
                    sys.argv[0], repr(category.title), repr(
                        category.levels), category.isFolder)
                # check for a valid custom thumbnail for the current category
                thumbnail = self._get_thumbnail(category.title)
                # set the default icon
                icon = "DefaultFolder.png"
                # only need to add label and thumbnail, setInfo() and addSortMethod() takes care of label2
                listitem = xbmcgui.ListItem(category.title,
                                            iconImage=icon,
                                            thumbnailImage=thumbnail)
                # add the item to the media list
                ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                                 url=url,
                                                 listitem=listitem,
                                                 isFolder=True,
                                                 totalItems=len(categories))
                # if user cancels, call raise to exit loop
                if (not ok): raise
        except:
            # user cancelled dialog or an error occurred
            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
        return ok

    def _fill_media_list_stations(self, stations):
        try:
            ok = True
            # enumerate through the list of categories and add the item to the media list
            for station in stations:
                # check for a valid custom thumbnail for the current category
                #thumbnail = self._get_thumbnail( station.title )
                icon = "defaultAudio.png"
                # only need to add label and icon, setInfo() and addSortMethod() takes care of label2
                listitem = xbmcgui.ListItem(station.title, iconImage=icon)
                # add the item to the media list
                ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                                 url=station.url,
                                                 listitem=listitem,
                                                 isFolder=False,
                                                 totalItems=len(stations))
                # if user cancels, call raise to exit loop
                if (not ok): raise
        except:
            # user cancelled dialog or an error occurred
            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
        return ok

    def _get_thumbnail(self, title):
        # create the full thumbnail path for skins directory
        thumbnail = xbmc.translatePath(
            os.path.join(self.BASE_SKIN_THUMBNAIL_PATH,
                         title.replace(" ", "-").lower() + ".tbn"))
        # use a plugin custom thumbnail if a custom skin thumbnail does not exists
        if (not os.path.isfile(thumbnail)):
            # create the full thumbnail path for plugin directory
            thumbnail = xbmc.translatePath(
                os.path.join(self.BASE_PLUGIN_THUMBNAIL_PATH,
                             title.replace(" ", "-").lower() + ".tbn"))
            # use a default thumbnail if a custom thumbnail does not exists
            if (not os.path.isfile(thumbnail)):
                thumbnail = ""
        return thumbnail
Пример #44
0
def getUserSkin():
    current_skin = xbmc.getSkinDir()
    force_fallback = os.path.exists(
        os.path.join(CWD, "resources", "skins", current_skin))
    if not force_fallback: current_skin = "Default"
    return current_skin, force_fallback
Пример #45
0
def SearchResults(murl, page):
	items = sortedItems(murl, page, 'search')
	if xbmc.getSkinDir() == 'skin.heidi' and plugin.get_setting('thumbview', bool):
		return plugin.finish(items, view_mode = 53)
	else :
		return plugin.finish(items)
Пример #46
0
progressDialogBG = xbmcgui.DialogProgressBG()

windowDialog = xbmcgui.WindowDialog()

button = xbmcgui.ControlButton

image = xbmcgui.ControlImage

keyboard = xbmc.Keyboard

sleep = xbmc.sleep

execute = xbmc.executebuiltin

skin = xbmc.getSkinDir()

player = xbmc.Player()

playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)

resolve = xbmcplugin.setResolvedUrl

openFile = xbmcvfs.File

makeFile = xbmcvfs.mkdir

deleteFile = xbmcvfs.delete

deleteDir = xbmcvfs.rmdir
Пример #47
0
def iI1():
    i1I11i('Tìm kiếm', '', 'search',
           'http://echipstore.net/addonicons/Search.jpg')
    i1I11i(
        'Thiếu nhi',
        'http://m.tv.zing.vn/ajax?f=genreProgram&s=new&id=IWZ9ZIW8&page=1&count=50',
        'indexprogram',
        'http://static.mp3.zdn.vn/skins/tv/images/zingtv-logo.png')
    i1I11i(
        'TV Show',
        'http://m.tv.zing.vn/ajax?f=genreProgram&s=new&id=IWZ9Z0CE&page=1&count=50',
        'indexprogram',
        'http://static.mp3.zdn.vn/skins/tv/images/zingtv-logo.png')
    i1I11i(
        'Phim Truyền Hình',
        'http://m.tv.zing.vn/ajax?f=genreProgram&s=new&id=IWZ9Z0DW&page=1&count=50',
        'indexprogram',
        'http://static.mp3.zdn.vn/skins/tv/images/zingtv-logo.png')
    i1I11i(
        'Hài kịch',
        'http://m.tv.zing.vn/ajax?f=genreProgram&s=new&id=IWZ9Z0D6&page=1&count=50',
        'indexprogram',
        'http://static.mp3.zdn.vn/skins/tv/images/zingtv-logo.png')
    i1I11i(
        'Âm nhạc',
        'http://m.tv.zing.vn/ajax?f=genreProgram&s=new&id=IWZ9Z0DC&page=1&count=50',
        'indexprogram',
        'http://static.mp3.zdn.vn/skins/tv/images/zingtv-logo.png')
    i1I11i(
        'Video Games',
        'http://m.tv.zing.vn/ajax?f=genreProgram&s=new&id=IWZ9ZIU8&page=1&count=50',
        'indexprogram',
        'http://static.mp3.zdn.vn/skins/tv/images/zingtv-logo.png')
    i1I11i(
        'Hoạt hình',
        'http://m.tv.zing.vn/ajax?f=genreProgram&s=new&id=IWZ9Z0DO&page=1&count=50',
        'indexprogram',
        'http://static.mp3.zdn.vn/skins/tv/images/zingtv-logo.png')
    i1I11i(
        'Giáo dục',
        'http://m.tv.zing.vn/ajax?f=genreProgram&s=new&id=IWZ9Z0D7&page=1&count=50',
        'indexprogram',
        'http://static.mp3.zdn.vn/skins/tv/images/zingtv-logo.png')
    i1I11i(
        'Thể thao',
        'http://m.tv.zing.vn/ajax?f=genreProgram&s=new&id=IWZ9Z0DI&page=1&count=50',
        'indexprogram',
        'http://static.mp3.zdn.vn/skins/tv/images/zingtv-logo.png')
    i1I11i(
        'Tin tức - Sự kiện',
        'http://m.tv.zing.vn/ajax?f=genreProgram&s=new&id=IWZ9Z0CF&page=1&count=50',
        'indexprogram',
        'http://static.mp3.zdn.vn/skins/tv/images/zingtv-logo.png')
    if 73 - 73: III - oo00oOOo * Oooo000o % OOo.OOO
    IiI1ii1 = xbmc.translatePath(
        xbmcaddon.Addon().getAddonInfo('path')).decode("utf-8")
    if 49 - 49: IiI1ii1 = xbmc.translatePath(os.path.join(IiI1ii1, "temp.jpg"))
    if 49 - 49:
        urllib.urlretrieve(
            'https://googledrive.com/host/0B-ygKtjD8Sc-S04wUUxMMWt5dmM/images/zingtv.jpg',
            IiI1ii1)
    if 49 - 49: oooOOooo = xbmcgui.ControlImage(0, 0, 1280, 720, IiI1ii1)
    if 49 - 49: o0oo0oo0OO00 = xbmcgui.WindowDialog()
    if 49 - 49: o0oo0oo0OO00.addControl(oooOOooo)
    if 49 - 49: o0oo0oo0OO00.doModal()
    if 20 - 20: i111iII
    oOOo = xbmc.getSkinDir()
    if oOOo == 'skin.xeebo':
        xbmc.executebuiltin('Container.SetViewMode(50)')
        if 25 - 25: O0 + OoOoOoO0o0OO * Ooo0OO0oOO * Ii * o0o - OOO0o0o
    def action(self, data):
        if self.scid is None:
            util.debug("[SC] nemame scid")
            return
        if data.get('action', None) is None:
            util.debug("[SC] nemame action")
            return

        if self.stream is None:
            try:
                stream = json.loads(
                    self.win.getProperty('%s.stream' % sctop.__scriptid__))
                util.debug("[SC] stream %s" % str(stream))
                self.stream = stream
            except:
                pass

        url = "%s/Stats?action=%s" % (sctop.BASE_URL, data.get(
            'action', 'None'))
        data.update({'est': self.estimateFinishTime})
        data.update({'se': self.se, 'ep': self.ep})
        data.update({'ver': sctop.addonInfo('version')})
        try:
            data.update(
                {'state': bool(xbmc.getCondVisibility("!Player.Paused"))})
            data.update({
                'ws': xbmcgui.Window(10000).getProperty('ws.ident'),
                'vip': xbmcgui.Window(10000).getProperty('ws.vip'),
                'vt': xbmcgui.Window(10000).getProperty('ws.viptyp')
            })
            data.update({'vd': xbmcgui.Window(10000).getProperty('ws.days')})
            data.update({'skin': xbmc.getSkinDir()})
            if self.stream is not None:
                if 'bitrate' in self.stream:
                    util.debug("[SC] action bitrate")
                    data.update({'bt': self.stream['bitrate']})
                else:
                    util.debug("[SC] action no bitrate")
                if 'sid' in self.stream:
                    util.info(
                        '[SC] mame sid <===================================================================================='
                    )
                    data.update({'sid': self.stream['sid']})
                else:
                    util.info(
                        '[SC] no sid in stream <==================================================================================== %s'
                        % str(self.stream))
        except Exception as e:
            util.info('[SC] problem s updatom dat: %s' %
                      str(traceback.format_exc()))
            pass
        try:
            if self.itemDuration > 0:
                data.update({'dur': self.itemDuration})
        except Exception:
            pass

        lastAction = xbmcgui.Window(10000).getProperty('sc.lastAction')
        util.debug('[SC] lastAction: %s' % (str(lastAction)))
        if lastAction == "" or time() - float(lastAction) > 5:
            xbmcgui.Window(10000).setProperty('sc.lastAction', str(time()))
            util.debug("[SC] action: %s" % str(data))
            url = self.parent.provider._url(url)
            try:
                sctop.post_json(url, data, {'X-UID': sctop.uid})
            except:
                pass
Пример #49
0
BASE_RESOURCE_PATH = xbmc.translatePath(
    os.path.join(__settings__.getAddonInfo('path'), 'resources', 'lib'))

sys.path.append(BASE_RESOURCE_PATH)

from gui import *

#############-----------------Is script runing from OSD? -------------------------------###############
if not xbmc.getCondVisibility('videoplayer.isfullscreen'):
    __settings__.openSettings()
    if xbmc.getCondVisibility('Player.Paused'):
        xbmc.Player().pause()  # if Paused, un-pause
else:
    window = False
    skin = "main"
    skin1 = str(xbmc.getSkinDir().lower())
    skin1 = skin1.replace("-", " ")
    skin1 = skin1.replace(".", " ")
    skin1 = skin1.replace("_", " ")
    if (skin1.find("eedia") > -1):
        skin = "MiniMeedia"
    if (skin1.find("tream") > -1):
        skin = "MediaStream"
    if (skin1.find("edux") > -1):
        skin = "MediaStream_Redux"
    if (skin1.find("aeon") > -1):
        skin = "Aeon"
    if (skin1.find("alaska") > -1):
        skin = "Alaska"
    if (skin1.find("confluence") > -1):
        skin = "confluence"
Пример #50
0
    def setProperties( self, properties, values, labelID, group, DATA ):
        # This function will take a list of properties and values and apply them to the
        # main menu item with the given labelID
        if not group:
            group = "mainmenu"

        # Decode values
        properties = try_decode( properties )
        values = try_decode( values )
        labelID = try_decode( labelID )
        group = try_decode( group )

        # Split up property names and values
        propertyNames = properties.split( "|" )
        propertyValues = values.replace( "::INFO::", "$INFO" ).split( "|" )
        labelIDValues = labelID.split( "|" )
        if len( labelIDValues ) == 0:
            # No labelID passed in, lets assume we were called in error
            return
        if len( propertyNames ) == 0:
            # No values passed in, lets assume we were called in error
            return

        # Get user confirmation that they want to make these changes
        message = "Set %s property to %s?" %( propertyNames[ 0 ], propertyValues[ 0 ] )
        if len( propertyNames ) == 2:
            message += "[CR](and 1 other property)"
        elif len( propertyNames ) > 2:
            message += "[CR](and %d other properties)" %( len( propertyNames ) -1 )
        shouldRun = xbmcgui.Dialog().yesno( ADDON.getAddonInfo( "name" ), message )
        if not shouldRun:
            return

        # Load the properties
        currentProperties, defaultProperties = DATA._get_additionalproperties( xbmc.translatePath( "special://profile/" ).decode( "utf-8" ) )
        otherProperties, requires, templateOnly = DATA._getPropertyRequires()

        # If there aren't any currentProperties, use the defaultProperties instead
        if currentProperties == [None]:
            currentProperties = defaultProperties

        # Pull out all properties into multi-dimensional dicts
        allProps = {}
        allProps[ group ] = {}
        for currentProperty in currentProperties:
            # If the group isn't in allProps, add it
            if currentProperty[ 0 ] not in allProps.keys():
                allProps[ currentProperty [ 0 ] ] = {}
            # If the labelID isn't in the allProps[ group ], add it
            if currentProperty[ 1 ] not in allProps[ currentProperty[ 0 ] ].keys():
                allProps[ currentProperty[ 0 ] ][ currentProperty[ 1 ] ] = {}
            # And add the property to allProps[ group ][ labelID ]
            if currentProperty[ 3 ] is not None:
                allProps[ currentProperty[ 0 ] ][ currentProperty [ 1 ] ][ currentProperty[ 2 ] ] = currentProperty[ 3 ]

        # Loop through the properties we've been asked to set
        for count, propertyName in enumerate(propertyNames):
            # Set the new value
            log( "Setting %s to %s" %( propertyName, propertyValues[ count ] ) )
            if len( labelIDValues ) != 1:
                labelID = labelIDValues[ count ]
            if labelID not in allProps[ group ].keys():
                allProps[ group ][ labelID ] = {}
            allProps[ group ][ labelID ][ propertyName ] = propertyValues[ count ]

            # Remove any properties whose requirements haven't been met
            for key in otherProperties:
                if key in allProps[ group ][ labelID ].keys() and key in requires.keys() and requires[ key ] not in allProps[ group ][ labelID ].keys():
                    # This properties requirements aren't met
                    log( "Removing value %s" %( key ) )
                    allProps[ group ][ labelID ].pop( key )

        # Build the list of all properties to save
        saveData = []
        for saveGroup in allProps:
            for saveLabelID in allProps[ saveGroup ]:
                for saveProperty in allProps[ saveGroup ][ saveLabelID ]:
                    saveData.append( [ saveGroup, saveLabelID, saveProperty, allProps[ saveGroup ][ saveLabelID ][ saveProperty ] ] )

        # Save the new properties
        try:
            f = xbmcvfs.File( os.path.join( DATAPATH , xbmc.getSkinDir().decode('utf-8') + ".properties" ), 'w' )
            f.write( repr( saveData ).replace( "],", "],\n" ) )
            f.close()
            log( "Properties file saved succesfully" )
        except:
            print_exc()
            log( "### ERROR could not save file %s" % DATAPATH )

        # The properties will only be used if the .DATA.xml file exists in the addon_data folder( otherwise
        # the script will use the default values), so we're going to open and write the 'group' that has been
        # passed to us
        menuitems = DATA._get_shortcuts( group, processShortcuts = False )
        DATA.indent( menuitems.getroot() )
        path = xbmc.translatePath( os.path.join( "special://profile", "addon_data", ADDONID, "%s.DATA.xml" %( DATA.slugify( group, True ) ) ).encode('utf-8') )
        menuitems.write( path, encoding="UTF-8" )

        log( "Properties updated" )

        # Mark that the menu needs to be rebuilt
        xbmcgui.Window( 10000 ).setProperty( "skinshortcuts-reloadmainmenu", "True" )
Пример #51
0
def skinfix():

    if xbmc.getSkinDir() == "skin.confluence":
        sk = xbmcaddon.Addon(id="skin.confluence")
        skinpath = sk.getAddonInfo("path")
        #print "skin path: "+skinpath
        platform = getPlatform()
        print "platform: " + platform

        if platform == 'win32' and "Program" in skinpath:
            print "Non-writeable confluence skin in use. Need to make a copy in userdata folder so we can install fonts."
            dialog = xbmcgui.Dialog()
            if dialog.yesno(
                    "Install Fonts?",
                    "Rhapsody needs to restart XBMC and install fonts to proceed. Is this okay?"
            ):
                dest = xbmc.translatePath("special://home/")
                dest2 = os.path.join(dest, 'addons', 'skin.confluence')
                dest3 = dest2 + "\\"  #add trailing backslash to windows paths for xbmcvfs
                print "checking for obsolete confluence copy at " + dest3
                if xbmcvfs.exists(dest3):
                    print "Found old writeable confluence skin. Attempting to delete"
                    delete_directory(dest3)

                    #try:
                    #	success = xbmcvfs.rmdir(dest3) #folder must be empty for this rmdir to work
                    #while success != 1:
                    #	xbmc.sleep(1000)
                    #	success = xbmcvfs.rmdir(dest3)
                    #	print "Trying to delete the folder....."

                    #print "success = "+str(success)
                    #if not success:
                    #	print "dest3 didn't work. trying to delete with dest2 path"
                    #
                    #	success = shutil.rmtree(dest2)
                    #if success:
                    #	print "Folder deleted!"
                    #else:
                    #	print "Deleting the folder failed. :-("
                    #	dialog.ok("Oh noes!!", "Kodi can't delete the folder. Please manually delete the skin.confluence folder found at "+dest2+" and then relaunch Kodi")
                    #	xbmc.executebuiltin( "XBMC.RestartApp()" )
                    #	exit()
                print "making a writeable confluence copy"
                shutil.copytree(skinpath, dest2)
                print "Finished copy. retarting app"
                xbmc.executebuiltin("XBMC.RestartApp()")
                exit()
            else:
                print 'Font install declined. Aborting Rhapsody launch'
                exit()

        elif platform == 'linux' and "share" in skinpath:
            print "Non-writeable confluence skin in use. Need to make a copy in the userdata folder so we can install fonts."
            dialog = xbmcgui.Dialog()
            if dialog.yesno(
                    "Install Fonts?",
                    "Rhapsody needs to restart XBMC and install fonts to proceed. Is this okay?"
            ):
                dest = xbmc.translatePath("special://home/")
                dest2 = os.path.join(dest, 'addons', 'skin.confluence')
                print "checking for obsolete confluence copy"
                if xbmcvfs.exists(dest2):
                    print "deleting obsolete confluence copy"
                    shutil.rmtree(dest2)
                print "making a writeable confluence copy"
                shutil.copytree(skinpath, dest2)
                print "Finished copy. retarting app"
                xbmc.executebuiltin("XBMC.RestartApp()")
                exit()
            else:
                print 'Font install declined. Aborting Rhapsody launch'
                exit()

        else:
            pass
            #print "All is okay. Confluence in use is a writeable copy"

    return
Пример #52
0
import xbmc
import xbmcgui
import xbmcaddon
import sys
import os

ADDON = xbmcaddon.Addon()
ADDON_ID = ADDON.getAddonInfo('id')
CWD = ADDON.getAddonInfo('path')
#
RESOURCE = xbmc.translatePath(
    os.path.join(CWD, 'resources', 'lib').encode("utf-8"))

sys.path.append(RESOURCE)

SkinID = xbmc.getSkinDir()
if SkinID != 'skin.estuary':
    import MyFont
    if MyFont.getSkinRes() == '1080i':
        MyFont.addFont("PseudoTv10", "NotoSans-Regular.ttf", "23")
        MyFont.addFont("PseudoTv12", "NotoSans-Regular.ttf", "25")
        MyFont.addFont("PseudoTv13", "NotoSans-Regular.ttf", "30")
        MyFont.addFont("PseudoTv14", "NotoSans-Regular.ttf", "32")
    else:
        MyFont.addFont("PseudoTv10", "NotoSans-Regular.ttf", "14")
        MyFont.addFont("PseudoTv12", "NotoSans-Regular.ttf", "16")
        MyFont.addFont("PseudoTv13", "NotoSans-Regular.ttf", "20")
        MyFont.addFont("PseudoTv14", "NotoSans-Regular.ttf", "22")


def Start():
Пример #53
0
class Main:
    # base paths
    BASE_SKIN_THUMBNAIL_PATH = os.path.join("Q:\\skin", xbmc.getSkinDir(),
                                            "media",
                                            sys.modules["__main__"].__plugin__)
    BASE_PLUGIN_THUMBNAIL_PATH = os.path.join(
        sys.modules["__main__"].BASE_PATH, "thumbnails")
    BASE_PRESETS_PATH = os.path.join(
        "P:\\plugin_data", "video",
        os.path.basename(os.getcwd().replace(";", "")), "presets")

    def __init__(self):
        self.make_presets_folder()
        if (not sys.argv[2]):
            self.get_categories()
        else:
            self.get_categories(False)

    def make_presets_folder(self):
        if (not os.path.isdir(xbmc.translatePath(self.BASE_PRESETS_PATH))):
            os.makedirs(xbmc.translatePath(self.BASE_PRESETS_PATH))

    def get_categories(self, root=True):
        try:
            # initialize category list
            categories = []
            # default categories.
            #TODO: consider localizing these
            if (root):
                category_dict = {
                    "All Videos": ("all_videos", "", True),
                    "Search Videos": ("search_videos", "", True),
                    "Presets": ("root_preset_videos", "", True),
                }
            else:
                category_dict = self.get_presets()
            # enumerate through the category list and add the item to our categories list with id
            for key, value in category_dict.items():
                # add item to our _Info() object list
                categories += [
                    _Info(title=key,
                          category=value[0],
                          query=value[1],
                          isFolder=value[2])
                ]
            # fill media list
            ok = self._fill_media_list(categories)
        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
        # send notification we're finished, successfully or unsuccessfully
        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)

    def get_presets(self):
        category_dict = {}
        presets = os.listdir(self.BASE_PRESETS_PATH)
        for preset in presets:
            try:
                f = open(os.path.join(self.BASE_PRESETS_PATH, preset), "r")
                query = f.read()
                f.close()
                category_dict[preset] = (
                    "preset_videos",
                    query,
                    True,
                )
            except:
                pass
        return category_dict

    def _fill_media_list(self, categories):
        try:
            ok = True
            # enumerate through the list of categories and add the item to the media list
            for category in categories:
                # set the callback url
                url = "%s?title=%s&category=%s&page=1&query=%s" % (
                    sys.argv[0],
                    repr(category.title),
                    repr(category.category),
                    repr(category.query),
                )
                # check for a valid custom thumbnail for the current category
                thumbnail = self._get_thumbnail(category.title)
                # set the default icon
                icon = "DefaultFolder.png"
                # only need to add label, icon and thumbnail, setInfo() and addSortMethod() takes care of label2
                listitem = xbmcgui.ListItem(category.title,
                                            iconImage=icon,
                                            thumbnailImage=thumbnail)
                # add the item to the media list
                ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                                 url=url,
                                                 listitem=listitem,
                                                 isFolder=category.isFolder,
                                                 totalItems=len(categories))
                # if user cancels, call raise to exit loop
                if (not ok): raise
        except:
            # user cancelled dialog or an error occurred
            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
        return ok

    def _get_thumbnail(self, title):
        # create the full thumbnail path for skins directory
        thumbnail = xbmc.translatePath(
            os.path.join(self.BASE_SKIN_THUMBNAIL_PATH,
                         title.replace(" ", "-").lower() + ".tbn"))
        # use a plugin custom thumbnail if a custom skin thumbnail does not exists
        if (not os.path.isfile(thumbnail)):
            # create the full thumbnail path for plugin directory
            thumbnail = xbmc.translatePath(
                os.path.join(self.BASE_PLUGIN_THUMBNAIL_PATH,
                             title.replace(" ", "-").lower() + ".tbn"))
            # use a default thumbnail if a custom thumbnail does not exists
            if (not os.path.isfile(thumbnail)):
                thumbnail = ""
        return thumbnail
Пример #54
0
# addon module
ADDON = Addon(__addonID__)

print('XBian-config : application (%s) run' % __version__)

ADDON_DIR = ADDON.getAddonInfo("path")
LangXBMC = xbmc.getLocalizedString

ROOTDIR = ADDON_DIR
BASE_RESOURCE_PATH = os.path.join(ROOTDIR, "resources")
MEDIA_PATH = os.path.join(BASE_RESOURCE_PATH, "media")
ADDON_DATA = xbmc.translatePath("special://profile/addon_data/%s/" %
                                __addonID__)
CATEGORY_PATH = 'categories'

SKIN_DIR = xbmc.getSkinDir()
if SKIN_DIR == 'skin.estouchy' or SKIN_DIR == 'skin.estuary':
    SKIN_RES = 'xml'
else:
    SKIN_RES = '720p'

if xbmc.__version__ < '2.25.0':
    default_skin = 'skin.confluence'
else:
    default_skin = 'skin.estuary'

curdir = os.getcwd()
os.chdir(os.path.join(ROOTDIR, 'resources', 'skins'))
remove('Default')
os.symlink(default_skin, 'Default')
os.chdir(curdir)
Пример #55
0
import xbmc
import xbmcgui
import xbmcaddon
import os
import sys
import socket
import time
import subprocess
from threading import Thread

# Get global paths
addon = xbmcaddon.Addon(id='plugin.program.radioFM')
addonpath = addon.getAddonInfo('path').decode("utf-8")

if str(xbmc.getSkinDir()) == "skin.carpc-xtouch":
    xbmcgui.Window(10000).setProperty('Radio.xtouch', 'true')
else:
    xbmcgui.Window(10000).setProperty('Radio.xtouch', 'false')

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

#control
HOME_BUTTON = 1101
BACK_BUTTON = 1102
BUTTON_FOCUS = 1103
TUNE_UP = 1104
TUNE_DOWN = 1105
SEEK_UP = 1106
SEEK_DOWN = 1107
VOLUME_UP = 1108
VOLUME_DOWN = 1109
Пример #56
0
    def _daemon(self):

        log('daemon started')

        while True:

            # Check the current skin directory, if it is different to the previous one, then
            # recreate the gui. This is required because reference in the gui left in memory
            # do not survive a refresh of the skins textures (???)
            if self.skindir != xbmc.getSkinDir():

                self.skindir = xbmc.getSkinDir()

                try:
                    log('skin changed, reloading gui')
                    del self.stored_gui
                except:
                    pass

                self.create_gui()

            # if xbmc is aborting
            if self.monitor.waitForAbort(1):

                self.exit()

                break

            if not self.parent_queue.empty():

                response = self.parent_queue.get()

                log('response : %s' % response)

                self.parent_queue.task_done()

                if response == 'open':
                    try:
                        del self.stored_gui  # TESTING: this will mean that the gui is populated and loaded every time it opens
                    except:
                        pass
                    self.open_gui()

                elif response == 'refresh_gui':
                    ''' This may need to be moved to a separate thread, so that it doesnt hold up the other functions. '''

                    # if the gui calls for its own refresh, then delete the existing one and open a new instance

                    # del self.stored_gui

                    self.open_gui()

                elif response == 'exit':

                    self.exit()
                    break

                elif 'new_device:' in response:

                    # a usb device is attached to the hardware

                    # get the device id
                    device_id = response[len('new_device:'):]

                    # proceed only if the device_id is not null
                    if device_id:

                        # get ignore list
                        ignore_list_raw = __setting__('ignored_devices')
                        ignore_list = ignore_list_raw.split('|')

                        # get sources list
                        media_string = self.get_sources_list()

                        # post dialogs to ask the user if they want to add the source, or ignore the device
                        if device_id not in ignore_list and device_id not in media_string:

                            d1 = DIALOG.yesno(lang(32002), lang(32003),
                                              lang(32004))

                            if d1:

                                xbmc.executebuiltin(
                                    "ActivateWindow(mediasource)")

                            else:

                                d2 = DIALOG.yesno(lang(32002), lang(32005))

                                if d2:
                                    ignore_list.append(str(device_id))
                                    ignore_string = '|'.join(ignore_list)
                                    __addon__.setSetting(
                                        'ignored_devices', ignore_string)

            # THIS PART MAY NOT BE NEEDED, BUT IS INCLUDED HERE ANYWAY FOR TESTING PURPOSES
            # if the gui was last accessed more than four hours
            if not self.skip_check and (
                    datetime.datetime.now() -
                    self.gui_last_accessed).total_seconds() > 14400:

                self.skip_check = True

                del self.stored_gui

        log('_daemon exiting')
def SetView(view_name):
    #not finished yet
    skin_used = xbmc.getSkinDir()
Пример #58
0
def setSkinVersion():
    skin = xbmc.getSkinDir()
    skinLabel = xbmcaddon.Addon(id=skin).getAddonInfo('name')
    skinVersion = xbmcaddon.Addon(id=skin).getAddonInfo('version')
    win = xbmcgui.Window( 10000 )
    win.setProperty("skinTitle",skinLabel + " (v" + skinVersion + ")")
    def create_colortheme(self):
        '''create a colortheme from current skin color settings'''
        try:
            current_skinfont = None
            json_response = kodi_json("Settings.GetSettingValue",
                                      {"setting": "lookandfeel.font"})
            if json_response:
                current_skinfont = json_response
            current_skincolors = None
            json_response = kodi_json("Settings.GetSettingValue",
                                      {"setting": "lookandfeel.skincolors"})
            if json_response:
                current_skincolors = json_response

            # user has to enter name for the theme
            themename = xbmcgui.Dialog().input(
                self.addon.getLocalizedString(32023),
                type=xbmcgui.INPUT_ALPHANUM).decode("utf-8")
            if not themename:
                return

            xbmc.executebuiltin("ActivateWindow(busydialog)")
            xbmc.executebuiltin(
                "Skin.SetString(SkinHelper.LastColorTheme,%s)" %
                themename.encode("utf-8"))

            # add screenshot
            custom_thumbnail = xbmcgui.Dialog().browse(
                2, self.addon.getLocalizedString(32024), 'files')

            if custom_thumbnail:
                xbmcvfs.copy(custom_thumbnail,
                             self.userthemes_path + themename + ".jpg")

            # read the guisettings file to get all skin settings
            from backuprestore import BackupRestore
            skinsettingslist = BackupRestore().get_skinsettings([
                "color", "opacity", "texture", "panel", "colour", "background",
                "image"
            ])
            newlist = []
            if skinsettingslist:
                newlist.append(("THEMENAME", themename))
                newlist.append(
                    ("DESCRIPTION", self.addon.getLocalizedString(32025)))
                newlist.append(
                    ("SKINTHEME", xbmc.getInfoLabel("Skin.CurrentTheme")))
                newlist.append(("SKINFONT", current_skinfont))
                newlist.append(("SKINCOLORS", current_skincolors))

                # look for any images in the skin settings and translate them so they can
                # be included in the theme backup
                for skinsetting in skinsettingslist:
                    setting_type = skinsetting[0]
                    setting_name = skinsetting[1]
                    setting_value = skinsetting[2]
                    if setting_type == "string" and setting_value:
                        if (setting_value
                                and (setting_value.endswith(".png")
                                     or setting_value.endswith(".gif")
                                     or setting_value.endswith(".jpg"))
                                and "resource://" not in setting_value):
                            image = get_clean_image(setting_value)
                            extension = image.split(".")[-1]
                            newimage = "%s_%s.%s" % (
                                themename, normalize_string(setting_name),
                                extension)
                            newimage_path = self.userthemes_path + newimage
                            if xbmcvfs.exists(image):
                                xbmcvfs.copy(image, newimage_path)
                                newimage_vfs = "special://profile/self.addon_data/%s/themes/%s" % (
                                    xbmc.getSkinDir(), newimage)
                                skinsetting = (setting_type, setting_name,
                                               newimage_vfs)
                    newlist.append(skinsetting)

                # save guisettings
                text_file_path = self.userthemes_path + themename + ".theme"
                text_file = xbmcvfs.File(text_file_path, "w")
                text_file.write(repr(newlist))
                text_file.close()
                xbmc.executebuiltin("Dialog.Close(busydialog)")
                xbmcgui.Dialog().ok(self.addon.getLocalizedString(32026),
                                    self.addon.getLocalizedString(32027))
        except Exception as exc:
            xbmc.executebuiltin("Dialog.Close(busydialog)")
            log_exception(__name__, exc)
            xbmcgui.Dialog().ok(self.addon.getLocalizedString(32028),
                                self.addon.getLocalizedString(32030), str(exc))
Пример #60
0
        system['exception'] = str(ex)
    data['system'] = system

    addon = xbmcaddon.Addon()
    addonInfo = dict()
    addonInfo['id'] = addon.getAddonInfo('id')
    addonInfo['name'] = addon.getAddonInfo('name')
    addonInfo['version'] = addon.getAddonInfo('version')
    addonInfo['path'] = addon.getAddonInfo('path')
    addonInfo['profile'] = addon.getAddonInfo('profile')
    data['addon'] = addonInfo

    xbmcInfo = dict()
    xbmcInfo['buildVersion'] = xbmc.getInfoLabel('System.BuildVersion')
    xbmcInfo['buildDate'] = xbmc.getInfoLabel('System.BuildDate')
    xbmcInfo['skin'] = xbmc.getSkinDir()
    xbmcInfo['language'] = xbmc.getInfoLabel('System.Language')
    data['xbmc'] = xbmcInfo

    execution = dict()
    execution['python'] = sys.version
    execution['sys.argv'] = sys.argv
    data['execution'] = execution

    data['userflow'] = userflow.loadUserFlow()

    extraDataInfo = dict()
    try:
        # convert globalExtraData to a dict that can be processed by BuggaloDialog, submitData and emailData (as part of data)
        for (key, value) in globalExtraData.items():
            if isinstance(value, str):