def createComments(self):
        comments = [
            self.dom.createComment(
                "Language file translated with Add-on XBMC Translator " + self.main.Addon.getAddonInfo("version")
            )
        ]

        username = self.main.Addon.getSetting("username")
        if username:
            comments += [self.dom.createComment("Translator: " + username)]
        usermail = self.main.Addon.getSetting("usermail")
        if usermail:
            comments += [self.dom.createComment("Email: " + usermail)]

        version_based = "version " + getInfoLabel("System.BuildVersion")
        if self.main.DefaultFolderLanguage.rstrip("/") != self.main.FolderLanguage:
            from xbmcaddon import Addon

            # get addon version
            apath = translatePath(self.main.FolderLanguage.replace("/resources", "").replace("/language", ""))
            addon = Addon(os.path.basename(apath.rstrip(os.sep)))
            version_based = "add-on %s version %s" % (addon.getAddonInfo("name"), addon.getAddonInfo("version"))
        comments += [
            self.dom.createComment("Date of translation: " + strftime("%x %X")),
            self.dom.createComment("Based on english strings " + version_based),
        ]

        refChild = self.dom.documentElement
        for comment in comments:
            self.dom.insertBefore(comment, refChild)
Exemple #2
0
    def onInit( self ):
        self.getControl( 1 ).setLabel( "XBMC Intro Movie" )
        try:
            self.control_list = self.getControl( 6 )
            self.getControl( 5 ).setNavigation( self.control_list, self.control_list, self.control_list, self.control_list )
            self.getControl( 3 ).setEnabled( 0 )
            self.getControl( 3 ).setVisible( 0 )
        except:
            self.control_list = self.getControl( 3 )
            print_exc()

        try: self.getControl( 5 ).setLabel( "Cancel" )
        except: print_exc()

        intros_dir   = os.path.join( Addon.getAddonInfo( "path" ), "resources", "intros" )
        previews_dir = os.path.join( Addon.getAddonInfo( "path" ), "resources", "previews" )

        listitems = []
        cur = Addon.getSetting( "intro" )
        for intro in os.listdir( intros_dir ):
            name, ext = os.path.splitext( intro )
            listitem = xbmcgui.ListItem( intro, "", "DefaultVideo.png" )
            if cur == intro: listitem.setProperty( "Addon.Summary", "Current Intro" )
            preview = os.path.join( previews_dir, name + ".jpg" )
            if xbmcvfs.exists( preview ): listitem.setIconImage( preview )
            listitems.append( listitem )

        listitem = xbmcgui.ListItem( "Random", "", "DefaultAddonVisualization.png" )
        if cur == "Random": listitem.setProperty( "Addon.Summary", "Current Intro" )
        listitems.append( listitem )

        self.control_list.reset()
        self.control_list.addItems( listitems )
        self.setFocus( self.control_list )
Exemple #3
0
 def install_repo(self, repoName, repoURL):
     """
     Install a repository in XBMC
     -> will need XBMC restart in order to have the new Repo taken in account by XBMC
     """
     continueInstall = True
     dialogYesNo = xbmcgui.Dialog()
     if dialogYesNo.yesno(repoName, Language( 30100 ), Language( 30101 )):           
         if continueInstall:
             ri = RepoInstaller()
                 
             newRepo = ri.download( repoURL )
             print newRepo
     
             if newRepo:
                 fp, ok = ri.install( newRepo )
                 print "---"
                 print fp, ok
                 xbmc.executebuiltin( 'UpdateLocalAddons' )
                 xbmc.sleep( 100 )
                 xbmc.executebuiltin( 'UpdateAddonRepos' )
                 xbmc.sleep( 100 )
                 try:
                     _N_ = Addon( os.path.basename( fp ) )
                     print "Addon %s Installed"%s_N_
                     ri.notification( _N_.getAddonInfo( "name" ), Language( 24065 ).encode( "utf-8" ), 5000, _N_.getAddonInfo( "icon" ) )
                 except:
                     xbmcgui.Dialog().ok( ADDON.getAddonInfo( "name" ), Language( 30007 ) + " : " + repoName, Language( 30010 ) )
     self._end_of_directory( True, update=False )
Exemple #4
0
def getWeatherSettings( loc_index="1" ):
    try:
        location = Addon.getSetting( 'areacode%s' % loc_index )
        SetProperty( "Location", location )
        for i in range( 1, 4 ):
            SetProperty( "Location%i" % i, Addon.getSetting( "areacode%i" % i ) )
        SetProperty( "Locations", str( i ) )
        Addon.setSetting( 'currentlocation', loc_index )
    except:
        print_exc()
    return location, loc_index
Exemple #5
0
    def onClick( self, controlID ):
        try:
            if controlID in [ 3, 6 ]:
                intro = self.control_list.getSelectedItem().getLabel()
                if intro: Addon.setSetting( "intro", intro )
                self._close_dialog()

            elif controlID == 5:
                self._close_dialog()
        except:
            print_exc()
Exemple #6
0
def service():
    from xml.dom.minidom import parseString
    has_splash = "true"
    dom = None
    try:
        dom = parseString( open( xbmc.translatePath( "special://userdata/advancedsettings.xml" ) ).read() )
        has_splash = dom.getElementsByTagName( "splash" )[ 0 ].firstChild.nodeValue
    except:
        print_exc()
    if dom: dom.unlink()
    if Addon.getSetting( "splash" ) != has_splash:
        Addon.setSetting( "splash", has_splash )
Exemple #7
0
def compatibility():
    from xbmcaddon import Addon
    Addon = Addon( "weather.google" )
    # get old settings and if exists delete data xml 
    if Addon.getSetting( 'risingsun_city' ) or Addon.getSetting( 'risingsun1_city' ):
        icon = Addon.getAddonInfo( "icon" )
        xml  = Addon.getAddonInfo( 'profile' ) + 'settings.xml'
        del Addon
        import xbmcvfs
        xbmcvfs.delete( xml )
        if not xbmcvfs.exists( xml ):
            #notifie user
            xbmc.executebuiltin( "XBMC.Notification(Weather Google,Your settings have been renewed! Sorry!,10000,%s)" % icon )
def update_service():
    # this read the settings
    settings = tools.Settings()
    # define the browser
    browser = tools.Browser()
    # Begin Service
    if settings.service == "true":
        if settings.time_noti > 0:
            settings.dialog.notification(
                settings.name_provider, "Checking Online...", settings.icon, settings.time_noti
            )
        quality = Addon().getSetting("quality")
        sort = Addon().getSetting("sort")
        url_search = "%s/api/v2/list_movies.json?limit=50&quality=%s&sort_by=%s&order_by=desc" % (
            settings.url_address,
            quality,
            sort.lower().replace(" ", "_"),
        )
        settings.log(url_search)
        title = []
        magnet = []
        for page in range(settings.pages):
            if settings.time_noti > 0:
                settings.dialog.notification(
                    settings.name_provider,
                    "Checking Online, Page %s..." % str(page + 1),
                    settings.icon,
                    settings.time_noti,
                )
            if browser.open(url_search):
                data = json.loads(browser.content)
                for movie in data["data"]["movies"]:
                    if movie.has_key("torrents"):
                        for torrent in movie["torrents"]:
                            if torrent["quality"] in quality:
                                title.append(movie["title_long"])
                                magnet.append("magnet:?xt=urn:btih:%s" % torrent["hash"])
        if len(title) > 0:
            tools.integration(
                filename=title,
                magnet=magnet,
                type_list="MOVIE",
                folder=settings.movie_folder,
                silence=True,
                name_provider=settings.name_provider,
            )
        else:
            settings.log("[%s] >>>>>>>%s<<<<<<<" % (settings.name_provider_clean, browser.status))
            settings.dialog.notification(settings.name_provider, browser.status, settings.icon, 1000)
    del settings
    del browser
Exemple #9
0
    def getSettings( self, id="repository.xbmc.builds" ):
        settings = {}
        try:
            from xbmcaddon import Addon
            addon = Addon( id )
            usetempdir = addon.getSetting( "usetempdir" ) == "true" 
            browsedir  = addon.getSetting( "browsedir" ) == "true" 
            settings[ "downloadpath" ] = ( addon.getSetting( "downloadpath" ), "" )[ browsedir ] 
            if not usetempdir:
                #browse for save dir
                if not settings[ "downloadpath" ] or not os.path.exists( settings[ "downloadpath" ] ):
                    dpath = xbmc.translatePath( self.get_browse_dialog( heading="Recordings folder" ) )
                    if dpath and os.path.exists( dpath ):
                        settings[ "downloadpath" ] = dpath
                        addon.setSetting( "downloadpath", settings[ "downloadpath" ] )
                    else:
                        settings[ "downloadpath" ] = ""
            settings[ "downloadinbackground" ] = addon.getSetting( "downloadinbackground" ) == "true"
            settings[ "reportpercent" ] = int( "0|5|10|20|25|50|100".split( "|" )[ int( addon.getSetting( "reportpercent" ) ) ] )

            PROFILE_PATH = xbmc.translatePath( addon.getAddonInfo( "profile" ) )
            settings[ "iddl_data" ] = os.path.join( PROFILE_PATH, "iddl_data" )
            if not os.path.exists( settings[ "iddl_data" ] ): os.makedirs( settings[ "iddl_data" ] )
        except:
            pass
        return settings
Exemple #10
0
def update_service():
    # this read the settings
    settings = tools.Settings()
    # define the browser
    browser = tools.Browser()
    #Begin Service
    if settings.service == 'true':
        if settings.time_noti > 0: settings.dialog.notification(settings.name_provider, 'Checking Online...', settings.icon, settings.time_noti)
        quality = Addon().getSetting('quality')
        text = '&minimum_rating=%s' % Addon().getSetting('minimum')
        sort = Addon().getSetting('sort')
        url_search = "%s/api/v2/list_movies.json?limit=50&quality=%s&sort_by=%s&order_by=desc" % (settings.url_address, quality, sort.lower().replace(' ', '_'))
        settings.log(url_search)
        title = []
        magnet = []
        for page in range(settings.pages):
            if settings.time_noti > 0: settings.dialog.notification(settings.name_provider, 'Checking Online, Page %s...'
                                                                    % str(page + 1), settings.icon, settings.time_noti)
            if browser.open(url_search):
                data = json.loads(browser.content)
                for movie in data['data']['movies']:
                    if movie.has_key('torrents'):
                        for torrent in movie['torrents']:
                            if torrent['quality'] in quality:
                                title.append(movie['title_long'])
                                magnet.append('magnet:?xt=urn:btih:%s' % torrent['hash'])
        if len(title) > 0:
            tools.integration(filename=title, magnet=magnet, type_list='MOVIE', folder=settings.movie_folder, silence=True, name_provider=settings.name_provider)
        else:
            settings.log('[%s] >>>>>>>%s<<<<<<<' % (settings.name_provider_clean, browser.status))
            settings.dialog.notification(settings.name_provider, browser.status, settings.icon, 1000)
    del settings
    del browser
Exemple #11
0
 def setContainerProperties( self ):
     self.setProperty( "IsModified", ( "", "Language file has been changed!" )[ self.IsModified ] )
     self.setProperty( "CurrentLanguage", self.CurrentLanguage )
     self.setProperty( "FolderLanguage", self.FolderLanguage )
     self.setProperty( "CurrentEnglishString", "" )
     self.Addon = Addon( AddonId )
     self.setProperty( "ExtraKeyboard_TopOrBottom", ( "top", "bottom" )[ int( self.Addon.getSetting( "ExtraKB" ) ) ] )
Exemple #12
0
    def createComments(self):
        version_based = "version " + xbmc.getInfoLabel("System.BuildVersion")
        if self.main.DefaultFolderLanguage.rstrip("/") != self.main.FolderLanguage:
            from xbmcaddon import Addon

            # get addon version
            apath = xbmc.translatePath(self.main.FolderLanguage.replace("/resources", "").replace("/language", ""))
            addon = Addon(os.path.basename(apath.rstrip(os.sep)))
            version_based = "add-on %s version %s" % (addon.getAddonInfo("name"), addon.getAddonInfo("version"))

        return ET.getComments(
            version_based,
            self.main.Addon.getSetting("username"),
            self.main.Addon.getSetting("usermail"),
            self.main.Addon.getAddonInfo("version"),
        )
Exemple #13
0
    def __init__( self, *args, **kwargs ):
        self.RestartXBMC_ReloadLanguage = False
        self.IsModified = False
        self.googleTrans = False
        self.listitems = []

        self.Addon = Addon( AddonId )
        self._get_settings()
def start_alarm():
    if not WEATHER_WINDOW:
        return
    try:
        # start next time to refresh images. 60 minutes (skinner for force refresh use "CancelAlarm(moon_earth_phases,true)")
        command = "RunScript(%s)" % os.path.join( Addon.getAddonInfo( "path" ), "resources", "lib", "moon_and_earth_phases.py" )
        xbmc.executebuiltin( "AlarmClock(moon_earth_phases,%s,60,true)" % command )
    except:
        print_exc()
def Main():
    try:
        url = sys.argv[2]
        # notify user
        notification(Addon.getAddonInfo("name"), url)
        # launch url
        launchUrl(url)
    except:
        print_exc()
Exemple #16
0
    def run(self):
        try:
            play_sfx = False
            # NB: xbmc.abortRequested not work correctly with threading.Thread
            while not xbmc.abortRequested:
                try:
                    self.getWindow()
                    if self.sprite != self.addon.getSetting("sprite"):
                        self.getMedias()

                    if not xbmc.getCondVisibility("Window.IsActive(Pointer.xml)"):
                        time.sleep(0.3)
                        continue

                    pos = xbmcgui.getMousePosition()

                    if ((pos[0] - self.offsetx) == self.current_pos[0]) and (pos[1] == self.current_pos[1]):
                        self.control.setImage(self.sprites["wait"])
                        if play_sfx:
                            if self.sprites["sfx"] and self.addon.getSetting("playsfx") == "true":
                                xbmc.playSFX(self.sprites["sfx"])
                            play_sfx = False
                    else:
                        play_sfx = True
                        if pos[0] < self.current_pos[0]:
                            self.control.setImage(self.sprites["left"])
                        else:
                            self.control.setImage(self.sprites["right"])

                        # start = "%i,%i" % self.current_pos
                        # end   = "%i,%i" % ( pos[ 0 ]-self.offsetx, pos[ 1 ] )
                        ##self.speed = str( self.current_pos[ 0 ] - pos[ 0 ] ).strip( "-" )
                        # self.control.setAnimations( [ ( 'conditional', 'condition=true effect=slide start=%s end=%s time=%s' % ( start, end, self.speed ) ) ] )
                        self.setAnimation(pos)

                        self.current_pos = (pos[0] - self.offsetx, pos[1])
                        # self.control.setPosition( *self.current_pos )

                    if xbmc.getCondVisibility("Window.IsActive(addonsettings)"):
                        self.reload_addon = True
                    elif self.reload_addon:
                        self.addon = Addon("script.mouse.tracker.service")
                        self.speed = self.addon.getSetting("speed").split(".")[0]
                        self.reload_addon = False
                except SystemExit:
                    break
                except:
                    print_exc()

                time.sleep(float(int(self.speed)) * 0.001)
        except SystemExit:
            pass
        except:
            print_exc()
Exemple #17
0
def SetProperties(loc_index=None):
    in_broad_daylight = True
    try:
        if loc_index is None:
            loc_index = Addon.getSetting("currentlocation")
        ID = Addon.getSetting("areacode%s_code" % loc_index)
        i_unit = int(Addon.getSetting("dist_unit"))

        sun = get_sun(ID, i_unit)
        in_broad_daylight = sun.get("In.Broad.Daylight") == "true"
        for key, value in sun.items():
            SetProperty(key, value)

        for key, value in get_moon(ID, i_unit).items():
            SetProperty(key, value)

        SetProperty("Weather.ExtraIsFetched", "true")
    except:
        print_exc()
    return in_broad_daylight
Exemple #18
0
 def onClick(self, controlId):
     if controlId == schedulesListBoxId:
         self.goEditSchedule()
     elif controlId == refreshButtonId:
         self.xnewa.cleanCache('scheduledRecordings.p')
         self.render()
     elif controlId == sortButton.Id:
         order = [smartUTF8(__language__(30011)),smartUTF8(__language__(30012)),smartUTF8(__language__(30042))]
         ret = xbmcgui.Dialog().select(smartUTF8(__language__(30122)), order);
         if ret != -1:
             if ret == 0:
                 self.sortkey = 'title'
             elif ret == 1:
                 self.sortkey = 'channel'
             elif ret == 2:
                 self.sortkey = 'priority'
             if self.sortkey != self.settings.XNEWA_SORT_RECURRING:
                 self.settings.XNEWA_SORT_RECURRING = self.sortkey
                 addon = Addon()
                 addon.setSetting(id='recurringSort',value=self.sortkey)
             self.render()
    def __init__(self, plugin_handle, base_url):

        self.addon = Addon()
        self.data_path = xbmc.translatePath(self.addon.getAddonInfo('profile'))
        self.cookie_path = self.data_path + 'COOKIE'
        self.plugin = self.addon.getAddonInfo('name')
        self.verb_log = self.addon.getSetting('logging') == 'true'
        self.plugin_handle = plugin_handle
        self.base_url = base_url
        self.version = self.addon.getAddonInfo('version')

        xbmcvfs.mkdir(path=self.data_path)
Exemple #20
0
def Main( settingID=None ):
    setfocusid = 200
    if settingID == "use_intro_movie":
        xbmc.executebuiltin( "Skin.ToggleSetting(Use_Intro_Movie)" )
        xbmc.sleep( 100 )
        setting = ( "false", "true" )[ xbmc.getCondVisibility( "Skin.HasSetting(Use_Intro_Movie" ) ]
        Addon.setSetting( "use_intro_movie", setting )
        xbmc.sleep( 100 )
        setfocusid = ( 102, 103 )[ setting == "false" ]

    elif settingID == "splash":
        toggle = toggle_splash( Addon.getSetting( "splash" ) )
        Addon.setSetting( "splash", toggle )
        xbmc.sleep( 500 )
        setfocusid = ( 110, 111 )[ toggle == "false" ]

    elif settingID == "intro":
        w = DialogSelect( "DialogSelect.xml", Addon.getAddonInfo( "path" ) )
        w.doModal()
        del w
        setfocusid = 104

    xbmc.executebuiltin( "Addon.openSettings(script.xbmc.intro.movie)" )
    xbmc.executebuiltin( "SetFocus(200)" )
    xbmc.executebuiltin( "SetFocus(%i)" % setfocusid )
Exemple #21
0
    def __init__(self):
        # Thread.__init__( self )

        self.winId = None
        self.window = None

        self.reload_addon = False
        self.addon = Addon("script.mouse.tracker.service")

        self.getMedias()
        self.current_pos = (0, 0)

        self.run()
Exemple #22
0
def _system_conversion(system_id):
    try:
        rootDir = Addon( id="plugin.program.advanced.launcher" ).getAddonInfo('path')
        if rootDir[-1] == ';':rootDir = rootDir[0:-1]
        resDir = os.path.join(rootDir, 'resources')
        scrapDir = os.path.join(resDir, 'scrapers')
        csvfile = open( os.path.join(scrapDir, 'gamesys'), "rb")
        conversion = []
        for line in csvfile.readlines():
            result = line.replace('\n', '').replace('"', '').split(',')
            if result[0].lower() == system_id.lower():
                if result[4]:
                    platform = result[4]
                    return platform
    except:
        return ''
Exemple #23
0
    def _install_inputstream(self):
        """Install inputstream addon."""
        try:
            # See if there's an installed repo that has it
            xbmc.executebuiltin('InstallAddon({})'.format(
                self.inputstream_addon),
                                wait=True)

            # Check if InputStream add-on exists!
            Addon('{}'.format(self.inputstream_addon))

            log('inputstream addon installed from repo')
            return True
        except RuntimeError:
            log('inputstream addon not installed')
            return False
Exemple #24
0
class InternalDatabase:
    _connection = None
    _cursor = None
    _database = os.path.join(xbmc.translatePath(Addon().getAddonInfo('path')), 'resources/data/drama.db')

    @classmethod
    def add(cls, values):
        cls._cursor.execute('INSERT INTO drama VALUES (?, ?, ?, ?)', values)

    @classmethod
    def connect(cls):
        if cls._connection is None:
            cls._connection = sqlite3.connect(cls._database)
            cls._connection.text_factory = str
            cls._cursor = cls._connection.cursor()
            cls._cursor.row_factory = sqlite3.Row
            cls.create()

    @classmethod
    def close(cls):
        if cls._connection is None:
            return

        cls._connection.commit()
        cls._cursor.close()
        cls._connection.close()
        cls._connection = None

    @classmethod
    def create(cls):
        cls._cursor.execute('CREATE TABLE IF NOT EXISTS drama ('
                            'path TEXT PRIMARY KEY ON CONFLICT IGNORE, '
                            'poster TEXT, '
                            'title TEXT, '
                            'plot TEXT)')

    @classmethod
    def fetchone(cls, path):
        cls._cursor.execute('SELECT * FROM drama WHERE path = ?', (path,))
        result = cls._cursor.fetchone()

        if result is None:
            return None
        else:
            result = dict(result)
            result.pop('path')
            return result
Exemple #25
0
def _set_isa_addon_settings(is_4k_capable, hdcp_override):
    """Method for self-configuring of InputStream Adaptive add-on"""
    try:
        is_helper = inputstreamhelper.Helper('mpd')
        if not is_helper.check_inputstream():
            show_ok_dialog(get_local_string(30154), get_local_string(30046))
            return
    except Exception as exc:  # pylint: disable=broad-except
        # Captures all types of ISH internal errors
        import traceback
        error(G.py2_decode(traceback.format_exc(), 'latin-1'))
        raise InputStreamHelperError(str(exc))

    isa_addon = Addon('inputstream.adaptive')
    isa_addon.setSettingBool('HDCPOVERRIDE', hdcp_override)
    if isa_addon.getSettingInt('STREAMSELECTION') == 1:
        # Stream selection must never be set to 'Manual' or cause problems with the streams
        isa_addon.setSettingInt('STREAMSELECTION', 0)
    # 'Ignore display' should only be set when Kodi display resolution is not 4K
    isa_addon.setSettingBool(
        'IGNOREDISPLAY', is_4k_capable
        and (getScreenWidth() != 3840 or getScreenHeight() != 2160))
Exemple #26
0
def get_video_url(page_url,
                  premium=False,
                  user="",
                  password="",
                  video_password=""):
    import xbmc
    from xbmcaddon import Addon
    logger.debug("(page_url='%s')" % page_url)
    video_urls = []

    video_id = scrapertools.find_single_match(page_url,
                                              '(?:v=|embed/)([A-z0-9_-]{11})')
    inputstream = platformtools.install_inputstream()

    try:
        __settings__ = Addon(name)
        if inputstream:
            __settings__.setSetting('kodion.video.quality.mpd', 'true')
        else:
            __settings__.setSetting('kodion.video.quality.mpd', 'false')
        # video_urls = [['con YouTube', 'plugin://plugin.video.youtube/play/?video_id=' + video_id ]]
    except:
        path = xbmc.translatePath('special://home/addons/' + name)
        if filetools.exists(path):
            if platformtools.dialog_yesno(config.get_localized_string(70784),
                                          config.get_localized_string(70818)):
                xbmc.executeJSONRPC(
                    '{"jsonrpc": "2.0", "id":1, "method": "Addons.SetAddonEnabled", "params": { "addonid": "'
                    + name + '", "enabled": true }}')
            else:
                return [['', '']]
        else:
            xbmc.executebuiltin('InstallAddon(' + name + ')', wait=True)
            try:
                Addon(name)
            except:
                return [['', '']]
    my_addon = xbmcaddon.Addon('plugin.video.youtube')
    addon_dir = xbmc.translatePath(my_addon.getAddonInfo('path'))
    sys.path.append(filetools.join(addon_dir, 'resources', 'lib'))
    from youtube_resolver import resolve
    for stream in resolve(page_url):
        # title = scrapertools.find_single_match(stream['title'], '(\d+p)')
        if scrapertools.find_single_match(stream['title'], r'(\d+p)'):
            video_urls.append(
                [re.sub(r'(\[[^\]]+\])', '', stream['title']), stream['url']])
    video_urls.sort(key=lambda it: int(it[0].split("p", 1)[0]))

    return video_urls
    def set_data(cls, json_data):
        path = xbmc.translatePath(
            Addon().getAddonInfo('profile')).decode("utf-8")

        if not os.path.exists(path):
            os.mkdir(path, 0o775)

        data = {}
        if os.path.isfile(os.path.join(path, cls.CACHE_FILE_NAME)):
            with open(os.path.join(path, cls.CACHE_FILE_NAME),
                      "r") as json_file:
                data = json.load(json_file)

        data.update(json_data)

        with open(os.path.join(path, cls.CACHE_FILE_NAME), "w") as json_file:
            json.dump(data, json_file)
def _perform_addon_changes(previous_ver, current_ver):
    """Perform actions for an version bump"""
    LOG.debug('Initialize add-on upgrade operations, from version {} to {}',
              previous_ver, current_ver)
    if not previous_ver:
        return
    if CmpVersion(previous_ver) < '1.16.2':
        from xbmcaddon import Addon
        isa_version = remove_ver_suffix(
            Addon('inputstream.adaptive').getAddonInfo('version'))
        if CmpVersion(isa_version) < '2.6.18':
            from resources.lib.kodi import ui
            ui.show_ok_dialog(
                'Netflix add-on upgrade',
                'The currently installed [B]InputStream Adaptive add-on[/B] version not support Netflix HD videos.'
                '[CR]To get HD video contents, please update it to the last version.'
            )
Exemple #29
0
def get_video_url(page_url,
                  premium=False,
                  user="",
                  password="",
                  video_password=""):
    import xbmc
    from xbmcaddon import Addon
    logger.info("(page_url='%s')" % page_url)
    video_urls = []

    if not page_url.startswith("http"):
        page_url = "http://www.youtube.com/watch?v=%s" % page_url
        logger.info(" page_url->'%s'" % page_url)

    video_id = scrapertools.find_single_match(page_url,
                                              '(?:v=|embed/)([A-z0-9_-]{11})')
    inputstream = platformtools.install_inputstream()
    # from core.support import dbg;dbg()
    try:
        __settings__ = Addon(name)
        if inputstream:
            __settings__.setSetting('kodion.video.quality.mpd', 'true')
        else:
            __settings__.setSetting('kodion.video.quality.mpd', 'false')
        video_urls = [[
            'con YouTube',
            'plugin://plugin.video.youtube/play/?video_id=' + video_id
        ]]
    except:
        if filetools.exists(
                xbmc.translatePath('special://profile/addon_data/' + name)):
            if platformtools.dialog_yesno(config.get_localized_string(70784),
                                          config.get_localized_string(70818)):
                xbmc.executeJSONRPC(
                    '{"jsonrpc": "2.0", "id":1, "method": "Addons.SetAddonEnabled", "params": { "addonid": "'
                    + name + '", "enabled": true }}')
            else:
                return [['', '']]
        else:
            xbmc.executebuiltin('InstallAddon(' + name + ')', wait=True)
            try:
                Addon(name)
            except:
                return [['', '']]

        return get_video_url(page_url)
    return video_urls
def recoverCommand():
    # issue shell command to install selected firmware and reset to factory settings if specify in the setting file.
    storage = firmwareLocationOnReboot()
    if Addon().getSetting('factoryReset') == 'true':
        shellCommand = 'echo -e "--update_package=/' + storage + '/update.img\n--wipe_cache\n--wipe_data" > /recovery/recovery/command || exit 1'
    else:
        shellCommand = 'echo -e "--update_package=/' + storage + '/update.img\n--wipe_cache" > /recovery/recovery/command || exit 1'
    result = os.system(shellCommand)
    if result != 0:
        messageOK(langString(32033))
        quit()
    else:
        dialog = xbmcgui.Dialog()
        dialog.notification(langString(32009),
                            langString(32016),
                            icon='',
                            time=3000)
        shellCommand = 'reboot recovery'
        os.system(shellCommand)
def convert_to_dash(manifest):
    """Convert a Netflix style manifest to MPEG-DASH manifest"""
    from xbmcaddon import Addon
    isa_version = g.remove_ver_suffix(
        g.py2_decode(Addon('inputstream.adaptive').getAddonInfo('version')))

    has_drm_streams = manifest['hasDrmStreams']
    protection_info = _get_protection_info(
        manifest) if has_drm_streams else None

    seconds = int(manifest['duration'] / 1000)
    init_length = int(seconds / 2 * 12 + 20 * 1000)
    duration = "PT" + str(seconds) + ".00S"

    root = _mpd_manifest_root(duration)
    period = ET.SubElement(root, 'Period', start='PT0S', duration=duration)

    for video_track in manifest['video_tracks']:
        _convert_video_track(video_track, period, init_length, protection_info,
                             has_drm_streams)

    common.fix_locale_languages(manifest['audio_tracks'])
    common.fix_locale_languages(manifest['timedtexttracks'])

    default_audio_language_index = _get_default_audio_language(manifest)
    for index, audio_track in enumerate(manifest['audio_tracks']):
        _convert_audio_track(audio_track, period, init_length,
                             (index == default_audio_language_index),
                             has_drm_streams)

    default_subtitle_language_index = _get_default_subtitle_language(manifest)
    for index, text_track in enumerate(manifest['timedtexttracks']):
        if text_track['isNoneTrack']:
            continue
        _convert_text_track(text_track, period,
                            (index == default_subtitle_language_index),
                            isa_version)

    xml = ET.tostring(root, encoding='utf-8', method='xml')
    if common.is_debug_verbose():
        common.save_file('manifest.mpd', xml)
    return xml.decode('utf-8').replace('\n', '').replace('\r',
                                                         '').encode('utf-8')
Exemple #32
0
def convert_to_dash(manifest):
    """Convert a Netflix style manifest to MPEG-DASH manifest"""
    from xbmcaddon import Addon
    isa_version = G.remove_ver_suffix(G.py2_decode(Addon('inputstream.adaptive').getAddonInfo('version')))

    # If a CDN server has stability problems it may cause errors with streaming,
    # we allow users to select a different CDN server
    # (should be managed by ISA but is currently is not implemented)
    cdn_index = int(G.ADDON.getSettingString('cdn_server')[-1]) - 1

    seconds = manifest['duration'] / 1000
    init_length = int(seconds / 2 * 12 + 20 * 1000)
    duration = "PT" + str(int(seconds)) + ".00S"

    root = _mpd_manifest_root(duration)
    period = ET.SubElement(root, 'Period', start='PT0S', duration=duration)

    has_video_drm_streams = manifest['video_tracks'][0].get('hasDrmStreams', False)
    video_protection_info = _get_protection_info(manifest['video_tracks'][0]) if has_video_drm_streams else None

    for video_track in manifest['video_tracks']:
        _convert_video_track(video_track, period, init_length, video_protection_info, has_video_drm_streams, cdn_index)

    common.fix_locale_languages(manifest['audio_tracks'])
    common.fix_locale_languages(manifest['timedtexttracks'])

    has_audio_drm_streams = manifest['audio_tracks'][0].get('hasDrmStreams', False)

    default_audio_track_id = _get_default_audio_track_id(manifest)
    for audio_track in manifest['audio_tracks']:
        is_default = default_audio_track_id == audio_track['id']
        _convert_audio_track(audio_track, period, init_length, is_default, has_audio_drm_streams, cdn_index)

    for text_track in manifest['timedtexttracks']:
        if text_track['isNoneTrack']:
            continue
        is_default = _is_default_subtitle(manifest, text_track)
        _convert_text_track(text_track, period, is_default, cdn_index, isa_version)

    xml = ET.tostring(root, encoding='utf-8', method='xml')
    if LOG.level == LOG.LEVEL_VERBOSE:
        common.save_file_def('manifest.mpd', xml)
    return xml.decode('utf-8').replace('\n', '').replace('\r', '').encode('utf-8')
Exemple #33
0
def use_drm_proxy():

    addon_type, addon_enabled = get_inputstream_addon()

    try:
        inputstream_adaptive_addon = xbmcaddon.Addon('inputstream.adaptive')
        inputstream_adaptive_version = inputstream_adaptive_addon.getAddonInfo(
            'version')
        inputstream_adaptive_fixed = LooseVersion(
            inputstream_adaptive_version) >= LooseVersion('2.2.18')
        xbmc.log("INPUTSTREAM.ADAPTIVE VERSION: %s" %
                 inputstream_adaptive_version)
        if not addon_enabled:
            xbmc.log("INPUTSTREAM.ADAPTIVE NOT ENABLED!")
    except Exception as ex:
        inputstream_adaptive_fixed = False
        xbmc.log("INPUTSTREAM.ADAPTIVE NOT AVAILABLE!")

    return not inputstream_adaptive_fixed and allow_drm(
    ) and Addon().getSetting('disable_drm_proxy') != 'true'
 def _select_menu(self):
     """
     Display select dialog
     """
     options = []
     # if user uses direct paths, give option to initiate playback via PMS
     if state.DIRECT_PATHS and self.kodi_type in v.KODI_VIDEOTYPES:
         options.append(OPTIONS['PMS_Play'])
     if self.kodi_type in v.KODI_VIDEOTYPES:
         options.append(OPTIONS['Transcode'])
     # userdata = self.api.userdata()
     # if userdata['Favorite']:
     #     # Remove from emby favourites
     #     options.append(OPTIONS['RemoveFav'])
     # else:
     #     # Add to emby favourites
     #     options.append(OPTIONS['AddFav'])
     # if self.kodi_type == "song":
     #     # Set custom song rating
     #     options.append(OPTIONS['RateSong'])
     # Refresh item
     # options.append(OPTIONS['Refresh'])
     # Delete item, only if the Plex Home main user is logged in
     if (window('plex_restricteduser') != 'true' and
             window('plex_allows_mediaDeletion') == 'true'):
         options.append(OPTIONS['Delete'])
     # Addon settings
     options.append(OPTIONS['Addon'])
     context_menu = context.ContextMenu(
         "script-emby-context.xml",
         Addon('plugin.video.plexkodiconnect').getAddonInfo('path'),
         "default",
         "1080i")
     context_menu.set_options(options)
     context_menu.doModal()
     if context_menu.is_selected():
         self._selected_option = context_menu.get_selected()
     return self._selected_option
def firmwareUpdate(message):
    # control the firmware selected installation
    dialog = xbmcgui.Dialog()
    message = message + langString(32006)
    runscript = dialog.yesno(langString(32002), message)

    if (runscript and Addon().getSetting('factoryReset') == 'true'):
        runscript = dialog.yesno(langString(32007), langString(32008))

    if (runscript):
        downloadFile = firmwareDownloadLocation()
        DownloaderClass(linkArray[ret], downloadFile)
        if md5(downloadFile) <> md5Array[ret]:
            md5ErrorMessage()
        else:
            dialog = xbmcgui.Dialog()
            dialog.notification(langString(32019),
                                langString(32020),
                                icon='',
                                time=3000)
        recoverCommand()
    else:
        quit()
Exemple #36
0
def index():
    if Addon().getSetting("stream") == "Twitch":
        t = TwitchStream(config.TWITCH_CHANNEL_ID)
        url, title, thumbnail = t.url, t.title, t.thumbnail
    else:
        video_id, title = get_live_video_id_from_channel_id(config.CHANNEL_ID)
        url = "plugin://plugin.video.youtube/play/?video_id=%s" % video_id
        thumbnail = "https://i.ytimg.com/vi/%s/maxresdefault_live.jpg#%s" % (
            video_id, time.localtime())
    li = ListItem(label="Live | " + title, thumbnailImage=thumbnail)
    li.setProperty('isPlayable', 'true')
    li.setInfo(type=u'video',
               infoLabels={
                   'title': title,
                   'plot': 'The live stream.'
               })
    addDirectoryItem(plugin.handle, url, li)

    url = "plugin://plugin.video.youtube/user/%s/" % config.CHANNEL_ID
    addDirectoryItem(plugin.handle, url, ListItem('Mediathek'), True)

    url = "plugin://plugin.video.youtube/channel/%s/" % config.LETS_PLAY_CHANNEL_ID
    addDirectoryItem(plugin.handle, url, ListItem('Gaming Mediathek'), True)

    addDirectoryItem(
        plugin.handle, "plugin://plugin.video.youtube/channel/%s/" %
        config.GAME_TWO_CHANNEL_ID, ListItem("Game-Two-Mediathek"), True)

    addDirectoryItem(
        plugin.handle,
        "plugin://plugin.video.twitch/?mode=channel_video_list&broadcast_type=upload&channel_id=%s"
        % (config.TWITCH_CHANNEL_ID), ListItem("Mediathek auf Twitch"), True)

    addDirectoryItem(plugin.handle, plugin.url_for(guide),
                     ListItem('Sendeplan'), True)

    endOfDirectory(plugin.handle)
def handle_msl_request(server, func_name, data, params=None):
    if func_name == 'get_license':
        # Proxy for InputStream Adaptive to get the licence for the requested video
        license_data = server.server.netflix_session.msl_handler.get_license(
            data)
        server.send_response(200)
        server.end_headers()
        server.wfile.write(license_data)
    elif func_name == 'get_manifest':
        # Proxy for InputStream Adaptive to get the XML manifest for the requested video
        videoid = int(params['videoid'][0])
        challenge = server.headers.get('challengeB64')
        sid = server.headers.get('sessionId')
        if not challenge or not sid:
            from xbmcaddon import Addon
            isa_version = remove_ver_suffix(
                Addon('inputstream.adaptive').getAddonInfo('version'))
            if common.CmpVersion(isa_version) >= '2.6.18':
                raise Exception(
                    f'Widevine session data not valid\r\nSession ID: {sid} Challenge: {challenge}'
                )
            # TODO: We temporary allow the use of older versions of InputStream Adaptive (but SD video content)
            #       to allow a soft transition, this must be removed in future.
            LOG.error(
                'Detected older version of InputStream Adaptive add-on, HD video contents are not supported.'
            )
            challenge = ''
            sid = ''
        manifest_data = server.server.netflix_session.msl_handler.get_manifest(
            videoid, unquote(challenge), sid)
        server.send_response(200)
        server.send_header('Content-type', 'application/xml')
        server.end_headers()
        server.wfile.write(manifest_data)
    else:
        handle_request(server, server.server.netflix_session, func_name, data)
Exemple #38
0
def fix_path( fixpath ):
    # fix path
    if fixpath.lower().startswith( "smb://" ) and IsTrue( Addon.getSetting( "smb_share" ) ):
        #remove share
        fixpath = fixpath.replace( "smb://", "" ).replace( "SMB://", "" )
        # add login and pass
        login = Addon.getSetting( "smb_login" )
        if login and not fixpath.startswith( login ):
            fixpath = "%s:%s@%s" % ( login, Addon.getSetting("smb_psw"), fixpath )
        fixpath = "smb://" + fixpath

    elif fixpath.lower().startswith( "ftp://" ) and IsTrue( Addon.getSetting( "ftp_share" ) ):
        #remove share
        fixpath = fixpath.replace( "ftp://", "" ).replace( "FTP://", "" )
        # add login and pass
        login = Addon.getSetting( "ftp_login" )
        if login and not fixpath.startswith( login ):
            fixpath = "%s:%s@%s" % ( login, Addon.getSetting("ftp_psw"), fixpath )
        fixpath = "ftp://" + fixpath

    return fixpath
Exemple #39
0
# Modules general
import os
import sys
import time

# Modules XBMC
import xbmc
import xbmcgui
from xbmcaddon import Addon

# Modules Custom
from log import logAPI
log = logAPI()

# constants
ADDON      = Addon( "script.moviesets" )
ADDON_NAME = ADDON.getAddonInfo( "name" )
ADDON_DIR  = ADDON.getAddonInfo( "path" )


def notification( header="", message="", sleep=5000, icon=ADDON.getAddonInfo( "icon" ) ):
    """ Will display a notification dialog with the specified header and message,
        in addition you can set the length of time it displays in milliseconds and a icon image.
    """
    icon = ( "DefaultIconInfo.png", icon )[ os.path.isfile( icon ) ]
    xbmc.executebuiltin( "XBMC.Notification(%s,%s,%i,%s)" % ( header, message, sleep, icon ) )


class Viewer:
    # constants
    WINDOW = 10147
Exemple #40
0
import pytz
import xbmcgui

import api
import config
import constants
import utils

EPG_FILE = "lattelecom-epg.xml"
M3U_FILE = "channels.m3u"

DATE_FORMAT_JSON = "%Y-%m-%d %H:%M:%S"

from xbmcaddon import Addon

data_dir = Addon().getAddonInfo('profile').decode('utf-8')

riga = pytz.timezone('Europe/Riga')


def indent(elem, level=0):
    # http://effbot.org/zone/element-lib.htm#prettyprint
    i = "\n" + level * "  "
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "  "
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for elem in elem:
            indent(elem, level + 1)
        if not elem.tail or not elem.tail.strip():
class Setting():
    CONTROL = None
    DIALOGHEADER = _("XBian")
    ERRORTEXT = _('ERROR : cannot save setting')
    OKTEXT = _('Setting has been saved')
    SAVEMODE = 0
    BADUSERENTRYTEXT = _('Data you have enter is not correct')
    APPLYTEXT = _('Are you sure to apply modification?')

    # SAVE MODE
    NONE = -1
    ONCLICK = 0
    ONUNFOCUS = 1

    ADDON = Addon(__addonID__)

    def __init__(self):
        self.preInit()
        self.control = self.CONTROL
        self.control.setTag(Tag('enable', 'false'))
        self.userValue = None
        self.xbianValue = None
        # self.clickId = self.control.getClickID()
        self.queue = None
        # self.SAVE = self.onSave
        if self.SAVEMODE == self.ONCLICK:
            self.control.onClick = self.onSave
        elif self.SAVEMODE == self.ONUNFOCUS:
            self.control.onUnFocus = self.onSave
        self.forceUpdate = False
        self.canBeUpdated = True
        self.publicMethod = {}
        self.globalMethod = None
        self.updatingSetting = False
        self.onInit()

    def preInit(self):
        # Override this method if you need to do something on start of __init__
        # don't override __init__
        pass

    def onInit(self):
        # Override this method if you need to do something on end of __init__
        # don't override __init__
        pass

    def addQueue(self, queue):
        self.queue = queue

    def getPublicMethod(self):
        return self.publicMethod

    def setPublicMethod(self, methods):
        self.globalMethod = methods

    def setSetting(self, id, value):
        return setSetting(id, value)

    def getSetting(self, id):
        return getSetting(id)

    def onSave(self, ctrl):
        self.updateFromUser()

    def getControl(self):
        return self.control

    def getControlValue(self):
        return self.control.getValue()

    def setControlValue(self, value):
        self.control.setValue(value)

    def getUserValue(self):
        # this method must be overrided if user can modify value
        # must create the user interface
        return None

    def checkUserValue(self, value):
        # this method can be overrided if user can modify value
        # check validity of user Value
        # return True if data is valid
        # False either
        return True

    def isModified(self):
        return self.userValue != self.xbianValue

    def askConfirmation(self, force=False):
        if self.getSetting('confirmationonchange') != '0' or force:
            if dialog.yesno(self.DIALOGHEADER, self.APPLYTEXT):
                return True
            else:
                return False
        else:
            return True

    def updateFromUser(self):
        if self.canBeUpdated and not self.updatingSetting:
            self.userValue = self.getUserValue()
            if self.isModified() or self.forceUpdate:
                if self.userValue and self.checkUserValue(self.userValue):
                    ok = True
                    if not self.askConfirmation():
                        ok = False
                        self.updateFromXbian()
                    if ok:
                        self.updatingSetting = True
                        self.QueueSetXbianValue(self.userValue)
                        self.setControlValue(self.userValue)
                        return True
                elif self.userValue and not self.checkUserValue(self.userValue):
                    dialog.ok(self.DIALOGHEADER, 'Bad Format', self.BADUSERENTRYTEXT)
                    self.setControlValue(self.xbianValue)

    def updateFromXbian(self):
        # dialog.ok("update from xbian",ADDON.getSetting('notifyonerror'))
        self.xbianValue = self.getXbianValue()
        self.setControlValue(self.xbianValue)

    def getXbianValue(self):
        # this method must be overrided
        # get the default Xbian Value
        return None

    def QueueSetXbianValue(self, value):
        if self.queue:
            self.queue.put([self, value])

    def notifyOnError(self, force=False, time=15000):
        if self.getSetting('notifyonerror') != '0' or force:
            xbmc.executebuiltin("Notification(%s,%s,%d)" % (self.DIALOGHEADER, self.ERRORTEXT, time))

    def notifyOnSuccess(self, force=False, time=5000):
        if self.getSetting('notifyonsuccess') == '1' or force:
            xbmc.executebuiltin("Notification(%s,%s,%d)" % (self.DIALOGHEADER, self.OKTEXT, time))

    def ThreadSetXbianValue(self, value):
        rc = self.setXbianValue(value)
        if rc is False:
            self.notifyOnError()
            self.updateFromXbian()
        elif rc is True:
            self.notifyOnSuccess()
            self.xbianValue = value
        elif rc is None:
            # need a reboot
            pass

    def setXbianValue(self, value):
        # this method must be overrided
        # set the  Xbian Value
        return True
Exemple #42
0
# -*- coding: utf-8 -*-

import os
import sys
from traceback import print_exc

import xbmcgui
import xbmcvfs
from xbmcaddon import Addon

ADDON = Addon("plugin.video.au.pays.des.tetes.a.claques")
FANART = ADDON.getAddonInfo("fanart")

SUBTITLES = xbmc.translatePath("special://subtitles/")
if not xbmcvfs.exists(SUBTITLES):
    SUBTITLES = xbmc.translatePath(ADDON.getAddonInfo("profile"))
SUBTITLES = SUBTITLES.replace("\\", "/").rstrip("/") + "/"
try:
    os.makedirs(SUBTITLES)
except:
    xbmcvfs.mkdir(SUBTITLES)

b_infoLabels = {
    "tvshowtitle": ADDON.getAddonInfo("name"),
    "genre": "Animation / Humour",
    "season": 1,
    "year": 2012,
    "studio": "Salambo Productions inc.",
    "writer": "Michel Beaudet",
    "director": "Michel Beaudet",
    "castandrole": [("Michel Beaudet", "")],
Exemple #43
0
# -*- coding: utf-8 -*-
""" Addon entry point """

from __future__ import absolute_import, division, unicode_literals
from resources.lib import kodiwrapper, kodilogging
from xbmcaddon import Addon

# Reinitialise ADDON every invocation to fix an issue that settings are not fresh.
kodiwrapper.ADDON = Addon()
kodilogging.ADDON = Addon()

if __name__ == '__main__':
    import sys
    from resources.lib import plugin  # pylint: disable=ungrouped-imports

    plugin.run(sys.argv)
Exemple #44
0
class Translator( xbmcgui.WindowXML ):
    CONTROL_LIST_A = 50

    def __init__( self, *args, **kwargs ):
        self.RestartXBMC_ReloadLanguage = False
        self.IsModified = False
        self.googleTrans = False
        self.listitems = []

        self.Addon = Addon( AddonId )
        self._get_settings()

    def _get_settings( self ):
        self.settings = {}
        self.settings[ "LanguagePath" ] = self.Addon.getSetting( "LanguagePath" )

        self.settings[ "viewmode" ]     = int( self.Addon.getSetting( "viewmode" ) )
        self.settings[ "sortmethod" ]   = int( self.Addon.getSetting( "sortmethod" ) )
        self.settings[ "sortorder" ]    = int( self.Addon.getSetting( "sortorder" ) )
        self.settings[ "savefolderviews" ] = ( self.Addon.getSetting( "savefolderviews" ) == "true" )

    def setListItems( self ):
        self.DefaultLanguage = "English"
        self.CurrentLanguage = xbmc.getLanguage()
        self.FolderLanguage  = self.settings[ "LanguagePath" ]
        self.DefaultFolderLanguage = "special://xbmc/language/"
        if not os.path.exists( xbmc.translatePath( self.FolderLanguage ) ):
            print "Folder language not exists! '%s'" % self.FolderLanguage
            self.FolderLanguage = self.DefaultFolderLanguage

        if not self.FolderLanguage.startswith( "special" ):
            for folder in [ "profile", "home", "xbmc" ]:
                special = "special://%s/" % folder
                self.FolderLanguage = self.FolderLanguage.replace( xbmc.translatePath( special ), special )

        if ( xbmc.translatePath( "special://skin/" ) in xbmc.translatePath( self.FolderLanguage ) ):
            self.FolderLanguage = "special://skin/language/"
        self.FolderLanguage = self.FolderLanguage.replace( "\\", "/" ).rstrip( "/" )

        self.setContainerProperties()
        # get languages source
        self.language = Language( self )
        self.listitems = self.language.listitems

    def onInit( self ):
        xbmc.executebuiltin( "ActivateWindow(busydialog)" )
        self.setSortMethodControl()
        self.setContainer( setviewmode=self.settings[ "viewmode" ] )
        LOG( "notice", "initialized took %s", time_took( START_TIME ) )
        xbmc.executebuiltin( "Dialog.Close(busydialog)" )

    def setSortMethodControl( self ):
        label = ( 20316, 103 )[ self.settings[ "sortmethod" ] ]
        self.getControl( 13 ).setLabel( xbmc.getLocalizedString( label ) )

    def setContainerProperties( self ):
        self.setProperty( "IsModified", ( "", "Language file has been changed!" )[ self.IsModified ] )
        self.setProperty( "CurrentLanguage", self.CurrentLanguage )
        self.setProperty( "FolderLanguage", self.FolderLanguage )
        self.setProperty( "CurrentEnglishString", "" )
        self.Addon = Addon( AddonId )
        self.setProperty( "ExtraKeyboard_TopOrBottom", ( "top", "bottom" )[ int( self.Addon.getSetting( "ExtraKB" ) ) ] )

    def setContainer( self, filter="", SelectId="", setviewmode=None ):
        if setviewmode is not None:
            self.ContainerId = ( 50, 51 )[ setviewmode ]
            if setviewmode: xbmc.executebuiltin( "SendClick(2)" )
        else:
            self.ContainerId = ( 50, 51 )[ xbmc.getCondVisibility( "Control.IsVisible(51)" ) ]
        try:

            if not bool( self.listitems ):
                if self.IsModified:
                    # ask for save change
                    self._save_change()
                self.IsModified = False
                self.googleTrans = False
                self.getControl( self.ContainerId ).reset()
                self.setListItems()

            self.setContainerProperties()
            if self.listitems:
                selectitem = 0

                additems = []
                if not filter:
                    additems = self.listitems
                else:
                    for li in self.listitems:
                        if filter == "UnTranslated" and li.getProperty( "UnTranslated" ) == "false":
                            continue
                        if filter == "Translated" and li.getProperty( "IsModified" ) != "true":
                            continue
                        additems.append( li )

                if additems:
                    if self.settings[ "sortmethod" ]:
                        additems = sorted( additems, key=lambda li: normalize_string( li.getLabel(), True ) )
                    if self.settings[ "sortorder" ]:
                        additems = list( reversed( additems ) )
                    for count, li in enumerate( additems ):
                        if li.getProperty( "id" ) == SelectId:
                            selectitem = count

                # add listitems
                self.getControl( self.ContainerId ).reset()
                self.getControl( self.ContainerId ).addItems( additems )
                if additems: #self.getControl( self.ContainerId ).size():
                    self.getControl( self.ContainerId ).selectItem( selectitem )
                    self.setFocusId( self.ContainerId )

            # fixe view on xbox
            if UNDER_XBOX and setviewmode is not None:
                xbmc.executebuiltin( "Container.SetViewMode(%i)" % self.ContainerId )
                xbmc.sleep( 20 )
                self.setFocusId( self.ContainerId )
        except:
            print_exc()

    def onFocus( self, controlID ):
        pass

    def sendClick( self, controlID ):
        try: self.onClick( controlID )
        except: print_exc()

    def getTranslate( self, text, minimal=2 ):
        translated = ""
        if text:
            if ( len( text ) <= minimal ) or text.isdigit():
                translated = text
            else:
                country = self.Addon.getSetting( "country" )
                if country.lower() == "auto": country = self.CurrentLanguage
                pDialog = xbmcgui.DialogProgress()
                pDialog.create( "Google Translate", "English to %s" % country, text, "Please wait..." )
                try:
                    import LanguageTools
                    translated = LanguageTools.translate_text( text, country, "google" )
                except:
                    print_exc()
        self.googleTrans = False
        xbmc.executebuiltin( "Dialog.Close(progressdialog)" )
        return translated

    def onClick( self, controlID ):
        try:
            self.ContainerId = ( 50, 51 )[ xbmc.getCondVisibility( "Control.IsVisible(51)" ) ]
            if controlID == self.ContainerId:
                # get clicked listitem
                listitem = self.getControl( self.ContainerId ).getSelectedItem()
                # get position
                pos = int( listitem.getProperty( "Position" ) )
                # get id
                id = listitem.getProperty( "id" )
                if id:
                    CurrentEnglishString = fixe_line_return( listitem.getLabel2(), True )
                    
                    DefaultText = fixe_line_return( listitem.getLabel(), True )
                    old_text = DefaultText
                    if self.googleTrans: old_text = self.getTranslate( CurrentEnglishString )
                    old_text = old_text or DefaultText

                    if ( self.Addon.getSetting( "BoldKB" ) == "true" ):
                        CurrentEnglishString = "[B]%s[/B]" % CurrentEnglishString
                    self.setProperty( "CurrentEnglishString", CurrentEnglishString )
                    self.setProperty( "ShowCurrentEnglishString", "true" )
                    
                    kb = xbmc.Keyboard( old_text, self.CurrentLanguage + " (Enter desired string)", False )
                    kb.doModal()
                    if kb.isConfirmed():
                        new_text = kb.getText()
                        if new_text != DefaultText:
                            new_text = fixe_line_return( new_text )
                            self.listitems[ pos ].setLabel( new_text )
                            self.listitems[ pos ].setProperty( "IsModified", "true" )
                            self.setProperty( "IsModified", "Language file has been changed!" )
                            self.IsModified = True
                    self.setProperty( "ShowCurrentEnglishString", "" )

            # PAS TRES BON COMME FILTRE :(
            UnTranslated = self.getControl( 19 ).isSelected()
            Translated = self.getControl( 20 ).isSelected()
            Changed = self.getControl( 21 ).isSelected()
            filter = ( "", "UnTranslated" )[ UnTranslated ]
            filter = ( filter, "Translated" )[ Translated ]
            filter = ( filter, "Changed" )[ Changed ]
            
            # get selected id for selectitem again, if controlID 22 clicked
            SelectId = xbmc.getInfoLabel( "Container(50).ListItem.Property(id)" ) or xbmc.getInfoLabel( "Container(51).ListItem.Property(id)" )
            if controlID == 19:
                # UNTRANSLATED BUTTON
                filter = ( "", "UnTranslated" )[ UnTranslated ]
                self.setContainer( filter, SelectId )
                self.getControl( 19 ).setSelected( UnTranslated )
                self.getControl( 20 ).setSelected( False )
                self.getControl( 21 ).setSelected( False )

            elif controlID == 20:
                # TRANSLATED BUTTON
                filter = ( "", "Translated" )[ Translated ]
                self.setContainer( filter, SelectId )
                self.getControl( 20 ).setSelected( Translated )
                self.getControl( 19 ).setSelected( False )
                self.getControl( 21 ).setSelected( False )

            elif controlID == 21:
                # CHANGED BUTTON
                filter = ( "", "Changed" )[ Changed ]
                self.setContainer( filter, SelectId )
                self.getControl( 21 ).setSelected( Changed )
                self.getControl( 19 ).setSelected( False )
                self.getControl( 20 ).setSelected( False )

            elif controlID == 22:
                # VIEW AS BUTTON
                self.settings[ "viewmode" ] = ( 1, 0 )[ self.settings[ "viewmode" ] ]
                xbmc.sleep( 50 )
                self.setContainer( filter, SelectId )

            elif controlID == 13:
                # SORT BY BUTTON
                self.settings[ "sortmethod" ] = ( 1, 0 )[ self.settings[ "sortmethod" ] ]
                self.setSortMethodControl()
                self.setContainer( filter, SelectId )

            elif controlID == 14:
                # SORT ASC BUTTON
                self.settings[ "sortorder" ] = ( 1, 0 )[ self.settings[ "sortorder" ] ]
                self.setContainer( filter, SelectId )

            elif controlID == 32:
                # SETTINGS BUTTON
                self.Addon = Addon( AddonId )
                self.Addon.openSettings()
                xbmc.sleep( 10 )
                if self.settings[ "LanguagePath" ] != self.Addon.getSetting( "LanguagePath" ):
                    self.settings[ "LanguagePath" ] = self.Addon.getSetting( "LanguagePath" )
                    self.listitems = []
                self.setContainer( filter, SelectId )

            elif controlID == 33:
                # FIND BUTTON
                default = self.getControl( 33 ).getLabel2()
                kb = xbmc.Keyboard( default, "Find what ...", False )
                kb.doModal()
                if kb.isConfirmed():
                    find_text = kb.getText()
                    #self.getControl( 33 ).setLabel( "Find", label2=find_text )
                    self.setProperty( "FindText", find_text )
                    if find_text:# and find_text != default:
                        for count, li in enumerate( self.listitems ):
                            #l_text = find_text.lower()
                            #match = ( l_text in li.getLabel().lower() ) or ( l_text in li.getLabel2().lower() ) or ( l_text == li.getProperty( "id" ) )
                            #match = match or ( l_text == li.getLabel().lower() ) or ( l_text == li.getLabel2().lower() )
                            #if not match: continue
                            if self.findText( find_text, li ):
                                self.getControl( self.ContainerId ).selectItem( count )
                                self.setFocusId( self.ContainerId )
                                break

            elif controlID == 34:
                # FIND NEXT BUTTON
                find_next = self.getControl( 33 ).getLabel2().encode( "utf-8" )
                pos = self.getControl( self.ContainerId ).getSelectedPosition()
                for count, li in enumerate( self.listitems ):
                    if count <= pos: continue
                    #if find_next in li.getLabel() or find_next == li.getProperty( "id" ):
                    if self.findText( find_next, li ):
                        self.getControl( self.ContainerId ).selectItem( count )
                        break

        except:
            print_exc()

    def findText( self, text, listitem ):
        return re.search( text.lower(), "|".join(
            [ listitem.getLabel(), listitem.getLabel2(), listitem.getProperty( "id" ) ]
            ).lower() )

    def onAction( self, action ):
        if action in [ 9, 10 ]:
            self._close_window()

        elif action == 117:
            try:
                cm = DialogContextMenu( "Translator-DialogContextMenu.xml", CWD, parent=self )
                cm.doModal()
                del cm
            except:
                print_exc()
        else:
            try:
                bcode = action.getButtonCode()
                # keyboard press F3
                if bcode == 127138: self.sendClick( 34 )
                #
            except:
                print_exc()

    def _close_window( self ):
        xbmc.executebuiltin( "ActivateWindow(busydialog)" )
        if self.settings[ "savefolderviews" ]:
            self.Addon.setSetting( "viewmode",   str( self.settings[ "viewmode" ] ) )
            self.Addon.setSetting( "sortmethod", str( self.settings[ "sortmethod" ] ) )
            self.Addon.setSetting( "sortorder",  str( self.settings[ "sortorder" ] ) )
            xbmc.sleep( 10 )

        if self.IsModified:
            # ask for save change
            xbmc.executebuiltin( "Dialog.Close(busydialog)" )
            self._save_change()

        try: del self.language
        except: pass
        self.close()

    def _save_change( self ):
        if xbmcgui.Dialog().yesno( "Confirm file save", "Language file has been changed!", self.language.current_xml, "Do you want save your change?", "" ):
            xbmc.executebuiltin( "ActivateWindow(busydialog)" )
            OK = self.language.save_strings()
            xbmc.executebuiltin( "Dialog.Close(busydialog)" )

            if ( self.DefaultFolderLanguage.rstrip( "/" ) == self.FolderLanguage ) or ( xbmc.translatePath( "special://skin/" ) in xbmc.translatePath( self.FolderLanguage ) ):
                # if default xbmc language file has been changed,
                # set True, XBMC require Restart or reload language
                self.RestartXBMC_ReloadLanguage = OK or self.RestartXBMC_ReloadLanguage
Exemple #45
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

import xbmc
import xbmcgui
from xbmcaddon import Addon
import utils


# Addon info
__addonID__ = "script.filecleaner"
__addon__ = Addon(__addonID__)
__title__ = __addon__.getAddonInfo("name")
__profile__ = xbmc.translatePath(__addon__.getAddonInfo("profile")).decode("utf-8")


class LogViewerDialog(xbmcgui.WindowXMLDialog):
    CAPTIONID = 201
    TEXTBOXID = 202
    TRIMBUTTONID = 301
    CLEARBUTTONID = 302
    CLOSEBUTTONID = 303

    def __init__(self, xml_filename, script_path, default_skin="Default", default_res="720p", *args, **kwargs):
        self.log = utils.Log()
        self.caption = utils.translate(32603)
        xbmcgui.WindowXMLDialog.__init__(self, xml_filename, script_path)

    def onInit(self):
        self.getControl(self.CAPTIONID).setLabel(self.caption)
        self.getControl(self.TEXTBOXID).setText(self.log.get())
import xbmcgui
import os
import subprocess
import time
import xbmc
from xbmcaddon import Addon
import xbmcgui

from resources.lib.xbianconfig import xbianConfig

__addonID__      = "plugin.xbianconfig"
ADDON     = Addon( __addonID__ )
ADDON_DIR = ADDON.getAddonInfo( "path" )
ROOTDIR            = ADDON_DIR
BASE_RESOURCE_PATH = os.path.join( ROOTDIR, "resources" )

class updater():
    def __init__(self,doUpgrade=False) :
        self.doUpgrade = doUpgrade
        self.dlg = updaterDlg('DialogUpgrade.xml',ROOTDIR)
        if os.path.exists('/var/lock/XBianUpdating') or self.doUpgrade:
            #must show update dialog
            self.dlg.doModal()
        
    def isUpgraded(self):
        return self.dlg.isUpgraded()

class updaterDlg(xbmcgui.WindowXMLDialog):         
    def isUpgraded(self) :
        self.upgraded = None
        if os.path.isfile('/tmp/resultCode') :
Exemple #47
0
import os
import sys
import xbmc
import xbmcgui
import xbmcplugin
from xbmcaddon import Addon
from resources.lib import get_url, dbHelper, extractMY
from urlparse import parse_qsl
import re
import json

base_url = sys.argv[0]
addon_handle = int(sys.argv[1])
settings = Addon(id='plugin.video.multiplex')
main_url = settings.getSetting("main_url")
download_path = settings.getSetting("download_path")
icon = 'https://image.tmdb.org/t/p/w185'
full = 'https://image.tmdb.org/t/p/w780'
bgFile = xbmc.translatePath(
    os.path.join('special://home/addons/plugin.video.multiplex/resources',
                 'fanart.jpg'))


def menu(links):
    params = dict(parse_qsl(sys.argv[2][1:]))
    fname = params['filename']
    if os.path.exists(os.path.join(download_path, fname)):
        dl_context = 'Resume'
    else:
        dl_context = 'Download'
    for link in links:
Exemple #48
0
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#

from builtins import str
import os
import xbmcgui
import operator

from XNEWAGlobals import *
from xbmcaddon import Addon
from fix_utf8 import smartUTF8

__language__ = Addon('script.kodi.knewc').getLocalizedString

schedulesListBoxId = 600
refreshButtonId = 250
sortButtonId = 253


# ==============================================================================
class SchedulesWindow(xbmcgui.WindowXML):
    def __init__(self, *args, **kwargs):
        self.closed = False
        self.win = None
        self.settings = kwargs['settings']
        self.xnewa = kwargs['xnewa']
        self.sortkey = self.settings.XNEWA_SORT_RECURRING
Exemple #49
0
 def __init__(self,id=addonName):
     self.Addon = Addon(id)
#  -*- coding: utf-8 -*-
"""
python -m unittest discover -v resources/tests/ "test_db_upgrade.py"
"""

import os
import shutil
import unittest
from xbmcaddon import Addon
import util, gamedatabase
from gamedatabase import GameDataBase, Game, RCBSetting

# Shared resources
addon = Addon(id='script.games.rom.collection.browser')
addonPath = addon.getAddonInfo('path')


class TestDBUpgrade(unittest.TestCase):
    def get_testdata_path(self):
        return os.path.join(os.path.dirname(__file__), '..', '..', 'resources',
                            'tests', 'testdata')

    def test_DBUpgrade_074_075(self):
        db_path = os.path.join(self.get_testdata_path(), 'database')

        # Setup data - MyGames.db is the hard-coded expected DB name
        self.assertTrue(
            os.path.isfile(os.path.join(db_path, 'MyGames-0.7.4.db')),
            "Expected to find 0.7.4 DB")
        shutil.copyfile(os.path.join(db_path, 'MyGames-0.7.4.db'),
                        os.path.join(db_path, 'MyGames.db'))
# -*- coding: utf-8 -*-

import os
import sys
import re
import xbmc
import xbmcgui
from xbmcaddon import Addon
from core import config
from core import logger
from core import scrapertools

import urllib2, urllib, httplib, time

__settings__ = Addon( "plugin.video.streamondemand-pureita" )
__addonDir__ = __settings__.getAddonInfo( "path" )

DEFAULT_CAPTCHA = os.path.join( __addonDir__, "resources","images","noimage.gif")

ACTION_PARENT_DIR     = 9
ACTION_PREVIOUS_MENU  = 10
ACTION_CONTEXT_MENU   = 117

CTRL_ID_BACK = 8
CTRL_ID_SPACE = 32
CTRL_ID_RETN = 300
CTRL_ID_MAYS = 302
CTRL_ID_CAPS = 303
CTRL_ID_SYMB = 304
CTRL_ID_IP = 307
CTRL_ID_TEXT = 310
Exemple #52
0
        return string
    try:
        string = string.decode(encoding, "ignore")
    except TypeError:
        string = string.decode()
    return string


# Percent of playback progress for watching item as partially watched. Anything
# more and item will NOT be marked as partially, but fully watched
MARK_PLAYED_AT = 0.9
# How many seconds of playback do we ignore before marking an item as partially
# watched?
IGNORE_SECONDS_AT_START = 60

_ADDON = Addon()
ADDON_NAME = 'PlexKodiConnect'
ADDON_ID = 'plugin.video.plexkodiconnect'
ADDON_VERSION = _ADDON.getAddonInfo('version')
ADDON_PATH = try_decode(_ADDON.getAddonInfo('path'))
ADDON_FOLDER = try_decode(xbmc.translatePath('special://home'))
ADDON_PROFILE = try_decode(xbmc.translatePath(_ADDON.getAddonInfo('profile')))

KODILANGUAGE = xbmc.getLanguage(xbmc.ISO_639_1)
KODIVERSION = int(xbmc.getInfoLabel("System.BuildVersion")[:2])
KODILONGVERSION = xbmc.getInfoLabel('System.BuildVersion')
KODI_PROFILE = try_decode(xbmc.translatePath("special://profile"))

if xbmc.getCondVisibility('system.platform.osx'):
    DEVICE = "MacOSX"
elif xbmc.getCondVisibility("system.platform.uwp"):
Exemple #53
0
    def onClick( self, controlID ):
        try:
            self.ContainerId = ( 50, 51 )[ xbmc.getCondVisibility( "Control.IsVisible(51)" ) ]
            if controlID == self.ContainerId:
                # get clicked listitem
                listitem = self.getControl( self.ContainerId ).getSelectedItem()
                # get position
                pos = int( listitem.getProperty( "Position" ) )
                # get id
                id = listitem.getProperty( "id" )
                if id:
                    CurrentEnglishString = fixe_line_return( listitem.getLabel2(), True )
                    
                    DefaultText = fixe_line_return( listitem.getLabel(), True )
                    old_text = DefaultText
                    if self.googleTrans: old_text = self.getTranslate( CurrentEnglishString )
                    old_text = old_text or DefaultText

                    if ( self.Addon.getSetting( "BoldKB" ) == "true" ):
                        CurrentEnglishString = "[B]%s[/B]" % CurrentEnglishString
                    self.setProperty( "CurrentEnglishString", CurrentEnglishString )
                    self.setProperty( "ShowCurrentEnglishString", "true" )
                    
                    kb = xbmc.Keyboard( old_text, self.CurrentLanguage + " (Enter desired string)", False )
                    kb.doModal()
                    if kb.isConfirmed():
                        new_text = kb.getText()
                        if new_text != DefaultText:
                            new_text = fixe_line_return( new_text )
                            self.listitems[ pos ].setLabel( new_text )
                            self.listitems[ pos ].setProperty( "IsModified", "true" )
                            self.setProperty( "IsModified", "Language file has been changed!" )
                            self.IsModified = True
                    self.setProperty( "ShowCurrentEnglishString", "" )

            # PAS TRES BON COMME FILTRE :(
            UnTranslated = self.getControl( 19 ).isSelected()
            Translated = self.getControl( 20 ).isSelected()
            Changed = self.getControl( 21 ).isSelected()
            filter = ( "", "UnTranslated" )[ UnTranslated ]
            filter = ( filter, "Translated" )[ Translated ]
            filter = ( filter, "Changed" )[ Changed ]
            
            # get selected id for selectitem again, if controlID 22 clicked
            SelectId = xbmc.getInfoLabel( "Container(50).ListItem.Property(id)" ) or xbmc.getInfoLabel( "Container(51).ListItem.Property(id)" )
            if controlID == 19:
                # UNTRANSLATED BUTTON
                filter = ( "", "UnTranslated" )[ UnTranslated ]
                self.setContainer( filter, SelectId )
                self.getControl( 19 ).setSelected( UnTranslated )
                self.getControl( 20 ).setSelected( False )
                self.getControl( 21 ).setSelected( False )

            elif controlID == 20:
                # TRANSLATED BUTTON
                filter = ( "", "Translated" )[ Translated ]
                self.setContainer( filter, SelectId )
                self.getControl( 20 ).setSelected( Translated )
                self.getControl( 19 ).setSelected( False )
                self.getControl( 21 ).setSelected( False )

            elif controlID == 21:
                # CHANGED BUTTON
                filter = ( "", "Changed" )[ Changed ]
                self.setContainer( filter, SelectId )
                self.getControl( 21 ).setSelected( Changed )
                self.getControl( 19 ).setSelected( False )
                self.getControl( 20 ).setSelected( False )

            elif controlID == 22:
                # VIEW AS BUTTON
                self.settings[ "viewmode" ] = ( 1, 0 )[ self.settings[ "viewmode" ] ]
                xbmc.sleep( 50 )
                self.setContainer( filter, SelectId )

            elif controlID == 13:
                # SORT BY BUTTON
                self.settings[ "sortmethod" ] = ( 1, 0 )[ self.settings[ "sortmethod" ] ]
                self.setSortMethodControl()
                self.setContainer( filter, SelectId )

            elif controlID == 14:
                # SORT ASC BUTTON
                self.settings[ "sortorder" ] = ( 1, 0 )[ self.settings[ "sortorder" ] ]
                self.setContainer( filter, SelectId )

            elif controlID == 32:
                # SETTINGS BUTTON
                self.Addon = Addon( AddonId )
                self.Addon.openSettings()
                xbmc.sleep( 10 )
                if self.settings[ "LanguagePath" ] != self.Addon.getSetting( "LanguagePath" ):
                    self.settings[ "LanguagePath" ] = self.Addon.getSetting( "LanguagePath" )
                    self.listitems = []
                self.setContainer( filter, SelectId )

            elif controlID == 33:
                # FIND BUTTON
                default = self.getControl( 33 ).getLabel2()
                kb = xbmc.Keyboard( default, "Find what ...", False )
                kb.doModal()
                if kb.isConfirmed():
                    find_text = kb.getText()
                    #self.getControl( 33 ).setLabel( "Find", label2=find_text )
                    self.setProperty( "FindText", find_text )
                    if find_text:# and find_text != default:
                        for count, li in enumerate( self.listitems ):
                            #l_text = find_text.lower()
                            #match = ( l_text in li.getLabel().lower() ) or ( l_text in li.getLabel2().lower() ) or ( l_text == li.getProperty( "id" ) )
                            #match = match or ( l_text == li.getLabel().lower() ) or ( l_text == li.getLabel2().lower() )
                            #if not match: continue
                            if self.findText( find_text, li ):
                                self.getControl( self.ContainerId ).selectItem( count )
                                self.setFocusId( self.ContainerId )
                                break

            elif controlID == 34:
                # FIND NEXT BUTTON
                find_next = self.getControl( 33 ).getLabel2().encode( "utf-8" )
                pos = self.getControl( self.ContainerId ).getSelectedPosition()
                for count, li in enumerate( self.listitems ):
                    if count <= pos: continue
                    #if find_next in li.getLabel() or find_next == li.getProperty( "id" ):
                    if self.findText( find_next, li ):
                        self.getControl( self.ContainerId ).selectItem( count )
                        break

        except:
            print_exc()
import json
import logging
import os.path
import re

try:  # Python 3
    from urllib.parse import quote
except ImportError:  # Python 2
    from urllib import quote

import requests
import dateutil.parser
from xbmcaddon import Addon
from resources.lib.kodiutils import proxies

ADDON = Addon()
logger = logging.getLogger(ADDON.getAddonInfo('id'))


class LiveChannel:
    def __init__(self, channel_id=None, name=None, logo=None, epg=None):
        """
        Defines a TV channel that can be streamed live.
        :type id: basestring
        :type name: basestring
        :type logo: basestring
        :type epg: List[LiveChannelEpg]
        """
        self.id = channel_id
        self.name = name
        self.logo = logo
Exemple #55
0
from threading import RLock
import xbmc
from xbmc import Player, Monitor, LOGNOTICE, LOGERROR, LOGWARNING
from xbmcaddon import Addon
from xbmcgui import Window, ControlLabel
from lifxlan import *

addon = Addon()

class LifxPlayer(Player):
    
    def __new__(cls, lights=[]):
        obj = Player.__new__(cls)
        obj.lights = dict((light, None) for light in lights)
        obj.lights_lock = RLock()
        
        return obj
    
    def __contains__(self, light):
        with self.lights_lock:
            return light.ip_addr in map(lambda l: l.ip_addr, self.lights)
    
    def add_light(self, light, color):
        with self.lights_lock:
            self.lights[light] = color if self.isPlayingVideo() else None
    
    def onPlayBackStarted(self):
        log("playback started")
        self.darken()
    
    def onPlayBackResumed(self):
Exemple #56
0
import xbmcvfs
from xbmcaddon import Addon


# Modules Custom
from utils.log import logAPI
from database import Database, TBN


# Constants
LOGGER   = logAPI()
DATABASE = Database()
DB_PATHS = glob( xbmc.translatePath( "special://Database/MyVideos*.db" ) )[ -1: ]

# constants
ADDON      = Addon( "script.moviesets" )
ADDON_DIR  = ADDON.getAddonInfo( "path" )

Language = ADDON.getLocalizedString # ADDON strings
LangXBMC = xbmc.getLocalizedString # XBMC strings

#https://raw.github.com/xbmc/xbmc/master/xbmc/guilib/Key.h
ACTION_PARENT_DIR    = 9
ACTION_PREVIOUS_MENU = 10
ACTION_NAV_BACK      = 92
ACTION_CONTEXT_MENU  = 117
KEYBOARD_A_BUTTON    = 61505
CLOSE_MANAGER        = [ ACTION_PARENT_DIR, ACTION_PREVIOUS_MENU, ACTION_NAV_BACK ]
CLOSE_DIALOG         = [ ACTION_CONTEXT_MENU ] + CLOSE_MANAGER

Exemple #57
0
    import json
except ImportError:
    import simplejson as json

from traceback import print_exc

if sys.version >= "2.5":
    from hashlib import md5 as _hash
else:
    from md5 import new as _hash

try:
    from xbmcaddon import Addon
    from xbmc import translatePath
    BASE_CACHE_PATH = translatePath("special://profile/Thumbnails/Video")
    ADDON = Addon("plugin.infologique.tou.tv")
    #ADDON_CACHE       = os.path.join( translatePath( ADDON.getAddonInfo( 'profile' ) ), ".cache" )
    #CACHE_EXPIRE_TIME = float( ADDON.getSetting( "expiretime" ).replace( "0", ".5" ).replace( "25", "0" ) )
except:
    BASE_CACHE_PATH = ""
    #ADDON_CACHE       = ""
    #CACHE_EXPIRE_TIME = 72

#if not os.path.exists( ADDON_CACHE ):
#    os.makedirs( ADDON_CACHE )

#def is_expired( lastUpdate, hrs=CACHE_EXPIRE_TIME ):
#    expired = time.time() >= ( lastUpdate + ( hrs * 60**2 ) )
#    return expired

Exemple #58
0
# coding: utf-8

import os
import xbmc
from xbmcaddon import Addon

__all__ = ['ADDON_ID', 'addon', 'path', 'profile', 'icon', 'get_ui_string']

ADDON_ID = 'service.subtitles.addic7ed'
addon = Addon(ADDON_ID)
path = xbmc.translatePath(addon.getAddonInfo('path')).decode('utf-8')
profile = xbmc.translatePath(addon.getAddonInfo('profile')).decode('utf-8')
icon = os.path.join(path, 'icon.png')


def get_ui_string(string_id):
    """
    Get language string by ID

    :param string_id: UI string ID
    :return: UI string
    """
    return addon.getLocalizedString(string_id)