def save_login():
    if CONFIG.LOGINSAVE <= time.mktime(
            time.strptime(tools.get_date(formatted=True),
                          "%Y-%m-%d %H:%M:%S")):
        from resources.libs import loginit
        logging.log("[Login Info] Saving all Data", level=xbmc.LOGNOTICE)
        loginit.auto_update('all')
        CONFIG.set_setting('loginnextsave',
                           tools.get_date(days=3, formatted=True))
    else:
        local_time = time.localtime(
            time.mktime(
                time.strptime(CONFIG.get_setting('loginnextsave'),
                              "%Y-%m-%d %H:%M:%S")))
        logging.log(
            "[Login Info] Next Auto Save isn't until: {0} / TODAY is: {1}".
            format(local_time, tools.get_date(formatted=True)),
            level=xbmc.LOGNOTICE)
예제 #2
0
    def build_video(self, name):
        from resources.libs import check
        from resources.libs import yt
        from resources.libs.common import logging
        from resources.libs.common import tools

        response = tools.open_url(CONFIG.BUILDFILE, check=True)

        if response:
            videofile = check.check_build(name, 'preview')
            if tools.open_url(videofile, check=True):
                yt.play_video(videofile)
            else:
                logging.log(
                    "[{0}]Unable to find url for video preview".format(name))
        else:
            logging.log("Build text file not working: {0}".format(
                CONFIG.BUILDFILE))
예제 #3
0
def build_update_check():
    response = tools.open_url(CONFIG.BUILDFILE, check=True)

    if not response:
        logging.log("[Build Check] Not a valid URL for Build File: {0}".format(
            CONFIG.BUILDFILE),
                    level=xbmc.LOGNOTICE)
    elif not CONFIG.BUILDNAME == '':
        if CONFIG.SKIN in ['skin.confluence', 'skin.estuary', 'skin.estouchy'
                           ] and not CONFIG.DEFAULTIGNORE == 'true':
            check.check_skin()

        logging.log("[Build Check] Build Installed: Checking Updates",
                    level=xbmc.LOGNOTICE)
        check.check_build_update()

    CONFIG.set_setting('nextbuildcheck',
                       tools.get_date(days=CONFIG.UPDATECHECK, formatted=True))
예제 #4
0
def fix_update():
    if os.path.exists(os.path.join(CONFIG.USERDATA, 'autoexec.py')):
        temp = os.path.join(CONFIG.USERDATA, 'autoexec_temp.py')
        if os.path.exists(temp):
            xbmcvfs.delete(temp)
        xbmcvfs.rename(os.path.join(CONFIG.USERDATA, 'autoexec.py'), temp)
    xbmcvfs.copy(
        os.path.join(CONFIG.PLUGIN, 'resources', 'libs', 'autoexec.py'),
        os.path.join(CONFIG.USERDATA, 'autoexec.py'))
    dbfile = os.path.join(CONFIG.DATABASE, latest_db('Addons'))
    try:
        os.remove(dbfile)
    except:
        logging.log("Unable to remove {0}, Purging DB".format(dbfile))
        purge_db_file(dbfile)

    from resources.libs.common import tools
    tools.kill_kodi(over=True)
예제 #5
0
    def _from_file(self, file, loc):
        from resources.libs import db
        from resources.libs import extract

        display = os.path.split(file)
        filename = display[1]
        packages = os.path.join(CONFIG.PACKAGES, filename)

        if not self.external:
            try:
                zipfile.ZipFile(file, 'r', allowZip64=True)
            except zipfile.BadZipFile as e:
                from resources.libs.common import logging
                logging.log(e, level=xbmc.LOGERROR)
                self.progress_dialog.update(0, '[COLOR {0}]Unable to read zip file from current location.'.format(CONFIG.COLOR2) + '\n' + 'Copying file to packages')
                xbmcvfs.copy(file, packages)
                file = xbmcvfs.translatePath(packages)
                self.progress_dialog.update(0, '\n' + 'Copying file to packages: Complete')
                zipfile.ZipFile(file, 'r', allowZip64=True)
        else:
            from resources.libs.downloader import Downloader
            Downloader().download(file, packages)

        self._prompt_for_wipe()

        self.progress_dialog.update(0, 'Installing External Backup' + '\n' + 'Please Wait')
        percent, errors, error = extract.all(file, loc)
        self._view_errors(percent, errors, error, file)

        CONFIG.set_setting('installed', 'true')
        CONFIG.set_setting('extract', percent)
        CONFIG.set_setting('errors', errors)

        if self.external:
            try:
                os.remove(file)
            except:
                pass

        db.force_check_updates(over=True)

        tools.kill_kodi(
            msg='[COLOR {0}]To save changes, Kodi needs to be force closed. Would you like to continue?[/COLOR]'.format(
                CONFIG.COLOR2))
예제 #6
0
    def _from_file(self, file, loc):
        from resources.libs import db
        from resources.libs import extract

        display = os.path.split(file)
        filename = display[1]
        packages = os.path.join(CONFIG.PACKAGES, filename)

        if not self.external:
            try:
                zipfile.ZipFile(file, 'r', allowZip64=True)
            except zipfile.BadZipFile as e:
                from resources.libs.common import logging
                logging.log(e, level=xbmc.LOGERROR)
                self.progress_dialog.update(0, '[COLOR {0}]Incapaz de ler o arquivo zip da localização atual. '.format(CONFIG.COLOR2) + '\n' + 'Copiando arquivo para pacotes')
                xbmcvfs.copy(file, packages)
                file = xbmcvfs.translatePath(packages)
                self.progress_dialog.update(0, '\n' + 'Copiando arquivo para pacotes: Completo')
                zipfile.ZipFile(file, 'r', allowZip64=True)
        else:
            from resources.libs.downloader import Downloader
            Downloader().download(file, packages)

        self._prompt_for_wipe()

        self.progress_dialog.update(0, 'Instalando Backup Externo' + '\n' + 'Por favor, aguarde...')
        percent, errors, error = extract.all(file, loc)
        self._view_errors(percent, errors, error, file)

        CONFIG.set_setting('installed', 'true')
        CONFIG.set_setting('extract', percent)
        CONFIG.set_setting('errors', errors)

        if self.external:
            try:
                os.remove(file)
            except:
                pass

        db.force_check_updates(over=True)

        tools.kill_kodi(
            msg='[COLOR {0}]Para salvar as alterações, o Kodi precisa ser fechado à força. Você gostaria de continuar?[/COLOR]'.format(
                CONFIG.COLOR2))
예제 #7
0
        def do_build_menu(self):
            from resources.libs.common import logging
            from resources.libs.common import tools

            logging.log(
                "[Current Build Check] [User Selected: Open Build Menu] [Next Check: {0}]"
                .format(CONFIG.BUILDCHECK),
                level=xbmc.LOGNOTICE)
            CONFIG.set_setting(
                'nextbuildcheck',
                tools.get_date(days=CONFIG.UPDATECHECK, formatted=True))
            CONFIG.set_setting('installed', 'ignored')

            url = 'plugin://{0}/?mode=builds'.format(CONFIG.ADDON_ID)

            self.close()

            xbmc.executebuiltin(
                'ActivateWindow(Programs, {0}, return)'.format(url))
예제 #8
0
def write_advanced(name, url):
    from resources.libs.common import tools
    from resources.libs.common import logging

    dialog = xbmcgui.Dialog()

    response = tools.open_url(url)

    if response:
        if os.path.exists(CONFIG.ADVANCED):
            choice = dialog.yesno(
                CONFIG.ADDONTITLE,
                "[COLOR {0}]Would you like to overwrite your current Advanced Settings with [COLOR {1}]{}[/COLOR]?[/COLOR]"
                .format(CONFIG.COLOR2, CONFIG.COLOR1, name),
                yeslabel="[B][COLOR springgreen]Overwrite[/COLOR][/B]",
                nolabel="[B][COLOR red]Cancel[/COLOR][/B]")
        else:
            choice = dialog.yesno(
                CONFIG.ADDONTITLE,
                "[COLOR {0}]Would you like to download and install [COLOR {1}]{2}[/COLOR]?[/COLOR]"
                .format(CONFIG.COLOR2, CONFIG.COLOR1, name),
                yeslabel="[B][COLOR springgreen]Install[/COLOR][/B]",
                nolabel="[B][COLOR red]Cancel[/COLOR][/B]")

        if choice == 1:
            tools.write_to_file(CONFIG.ADVANCED, response.text)
            dialog.ok(
                CONFIG.ADDONTITLE,
                '[COLOR {0}]AdvancedSettings.xml file has been successfully written. Once you click okay it will force close kodi.[/COLOR]'
                .format(CONFIG.COLOR2))
            tools.kill_kodi(over=True)
        else:
            logging.log("[Advanced Settings] install canceled")
            logging.log_notify(
                '[COLOR {0}]{1}[/COLOR]'.format(CONFIG.COLOR1,
                                                CONFIG.ADDONTITLE),
                "[COLOR {0}]Write Cancelled![/COLOR]".format(CONFIG.COLOR2))
            return
    else:
        logging.log("[Advanced Settings] URL not working: {0}".format(url))
        logging.log_notify(
            '[COLOR {0}]{1}[/COLOR]'.format(CONFIG.COLOR1, CONFIG.ADDONTITLE),
            "[COLOR {0}]URL Not Working[/COLOR]".format(CONFIG.COLOR2))
예제 #9
0
def save_login():
    current_time = time.mktime(
        time.strptime(tools.get_date(formatted=True), "%Y-%m-%d %H:%M:%S"))
    next_save = time.mktime(
        time.strptime(CONFIG.get_setting('loginnextsave'),
                      "%Y-%m-%d %H:%M:%S"))

    if next_save <= current_time:
        from resources.libs import loginit
        logging.log("[Login Info] Guardar todos los datos", level=xbmc.LOGINFO)
        loginit.auto_update('all')
        CONFIG.set_setting('loginnextsave',
                           tools.get_date(days=3, formatted=True))
    else:
        logging.log(
            "[Login Info] El siguiente guardado automático no es hasta: {0} / hoy es: {1}"
            .format(CONFIG.get_setting('loginnextsave'),
                    tools.get_date(formatted=True)),
            level=xbmc.LOGINFO)
예제 #10
0
def save_trakt():
    current_time = time.mktime(
        time.strptime(tools.get_date(formatted=True), "%Y-%m-%d %H:%M:%S"))
    next_save = time.mktime(
        time.strptime(CONFIG.get_setting('traktnextsave'),
                      "%Y-%m-%d %H:%M:%S"))

    if next_save <= current_time:
        from resources.libs import traktit
        logging.log("[Trakt Data] Guardar todos los datos", level=xbmc.LOGINFO)
        traktit.auto_update('all')
        CONFIG.set_setting('traktnextsave',
                           tools.get_date(days=3, formatted=True))
    else:
        logging.log(
            "[Trakt Data] Next Auto Save isn't until: {0} / TODAY is: {1}".
            format(CONFIG.get_setting('traktnextsave'),
                   tools.get_date(formatted=True)),
            level=xbmc.LOGINFO)
예제 #11
0
def toggle_addon(id, value, over=None):
    from resources.libs.common import tools

    from xml.etree import ElementTree

    logging.log("Toggling {0}".format(id))
    addonid = id
    addonxml = os.path.join(CONFIG.ADDONS, id, 'addon.xml')
    if os.path.exists(addonxml):
        root = ElementTree.parse(addonxml).getroot()
        tid = root.get('id')
        tname = root.get('name')
        tservice = root.find('extension').get('point')

        try:
            if len(tid) > 0:
                addonid = tid
            if tservice == 'xbmc.service':
                logging.log(
                    "We got a live one, stopping script: {0}".format(tid))
                xbmc.executebuiltin('StopScript({0})'.format(
                    os.path.join(CONFIG.ADDONS, addonid)))
                xbmc.executebuiltin('StopScript({0})'.format(addonid))
                xbmc.executebuiltin('StopScript({0})'.format(
                    os.path.join(CONFIG.ADDONS, addonid, tservice[0])))
                xbmc.sleep(500)
        except:
            pass

    query = '{{"jsonrpc":"2.0", "method":"Addons.SetAddonEnabled","params":{{"addonid":"{0}","enabled":{1}}}, "id":1}}'.format(
        addonid, value)
    response = xbmc.executeJSONRPC(query)

    if 'error' in response and over is None:
        dialog = xbmcgui.Dialog()

        v = 'Enabling' if value == 'true' else 'Disabling'
        dialog.ok(
            CONFIG.ADDONTITLE,
            "[COLOR {0}]Error {1} [COLOR {2}]{3}[/COLOR]".format(
                CONFIG.COLOR2, v, CONFIG.COLOR1, id) + '\n' +
            "Check to make sure the add-on list is up to date and try again.[/COLOR]"
        )
예제 #12
0
def binaries():
    dialog = xbmcgui.Dialog()

    binarytxt = os.path.join(CONFIG.USERDATA, 'build_binaries.txt')

    if os.path.exists(binarytxt):
        binaryids = tools.read_from_file(binarytxt).split(',')

        logging.log("[Detecção binária] Reinstalando complementos binários qualificados")
        dialog.ok(CONFIG.ADDONTITLE,
                  '[COLOR {0}]A compilação restaurada contém complementos específicos da plataforma, que agora serão '
                  'instalado automaticamente. Vários diálogos podem aparecer durante este processo. Cancelando-os '
                  'pode fazer com que a compilação restaurada funcione incorretamente.[/COLOR]'.format(
                      CONFIG.COLOR2))
    else:
        logging.log("[Detecção binária] Nenhum complemento binário elegível para reinstalar")
        return True

    success = []
    fail = []

    if len(binaryids) == 0:
        logging.log('Nenhum complemento selecionado para instalação.')
        return

    from resources.libs.gui import addon_menu

    # finally, reinstall addons
    for addonid in binaryids:
        if addon_menu.install_from_kodi(addonid):
            logging.log('{0} instalação bem-sucedida.'.format(addonid))
            success.append(addonid)
        else:
            logging.log('{0} a instalação falhou.'.format(addonid))
            fail.append(addonid)

    if not fail:
        dialog.ok(CONFIG.ADDONTITLE, 'Os addons selecionados foram todos instalados com sucesso.')
        os.remove(binarytxt)
        return True
    else:
        dialog.ok(CONFIG.ADDONTITLE, 'Os seguintes complementos não foram instalados:\n{0}'.format(', '.join(fail)))
        return False
예제 #13
0
def net_info():
    import json
    from resources.libs.common import logging

    infoLabel = ['Network.IPAddress', 'Network.MacAddress']
    data = []
    x = 0
    for info in infoLabel:
        temp = tools.get_info_label(info)
        y = 0
        while temp == "Busy" and y < 10:
            temp = tools.get_info_label(info)
            y += 1
            logging.log("{0} sleep {1}".format(info, str(y)))
            xbmc.sleep(200)
        data.append(temp)
        x += 1
    try:
        url = 'http://extreme-ip-lookup.com/json/'
        req = Request(url)
        req.add_header(
            'User-Agent',
            'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'
        )
        response = urlopen(req)
        geo = json.load(response)
    except:
        url = 'http://ip-api.com/json'
        req = Request(url)
        req.add_header(
            'User-Agent',
            'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'
        )
        response = urlopen(req)
        geo = json.load(response)
    mac = data[1]
    inter_ip = data[0]
    ip = geo['query']
    isp = geo['org']
    city = geo['city']
    country = geo['country']
    state = geo['region']
    return mac, inter_ip, ip, city, state, country, isp
예제 #14
0
def binaries():
    from resources.libs import install

    dialog = xbmcgui.Dialog()

    binarytxt = os.path.join(CONFIG.USERDATA, 'build_binaries.txt')

    if os.path.exists(binarytxt):
        binaryids = tools.read_from_file(binarytxt).split(',')

        logging.log("[Binary Detection] Reinstalling Eligible Binary Addons")
        dialog.ok(CONFIG.ADDONTITLE,
                  '[COLOR {0}]The restored build contains platform-specific addons, which will now be '
                  'automatically installed. A number of dialogs may pop up during this process. Cancelling them '
                  'may cause the restored build to function incorrectly.[/COLOR]'.format(
                      CONFIG.COLOR2))
    else:
        logging.log("[Binary Detection] No Eligible Binary Addons to Reinstall")
        return True

    success = []
    fail = []

    if len(binaryids) == 0:
        logging.log('No addons selected for installation.')
        return

    # finally, reinstall addons
    for addonid in binaryids:
        if install.install_from_kodi(addonid):
            logging.log('{0} install succeeded.'.format(addonid))
            success.append(addonid)
        else:
            logging.log('{0} install failed.'.format(addonid))
            fail.append(addonid)

    if not fail:
        dialog.ok(CONFIG.ADDONTITLE, 'The selected addons were all installed successfully.')
        os.remove(binarytxt)
        return True
    else:
        dialog.ok(CONFIG.ADDONTITLE, 'The following addons failed to install:\n{0}'.format(', '.join(fail)))
        return False
예제 #15
0
def force_check_updates(over=False):
    dbfile = latest_db('Addons')
    dbfile = os.path.join(CONFIG.DATABASE, dbfile)
    sqldb = database.connect(dbfile)
    sqlexe = sqldb.cursor()
    
    if not over:
        logging.log_notify("[COLOR {0}]{1}[/COLOR]".format(CONFIG.COLOR1, CONFIG.ADDONTITLE),
                           '[COLOR {0}]Forcing Check for Updates[/COLOR]'.format(CONFIG.COLOR2))
    
    installed_repos = sqlexe.execute("SELECT * FROM repo")
    for repo in installed_repos:
        logging.log('{0}'.format(repo), level=xbmc.LOGDEBUG)
        sqlexe.execute("UPDATE repo SET version = ? WHERE addonID = ?", ('0.0.1', repo[1],))
        sqldb.commit()
        
    sqlexe.close()
    
    xbmc.executebuiltin('UpdateAddonRepos')
예제 #16
0
def save_debrid():
    current_time = time.mktime(
        time.strptime(tools.get_date(formatted=True), "%Y-%m-%d %H:%M:%S"))
    next_save = time.mktime(
        time.strptime(CONFIG.get_setting('debridnextsave'),
                      "%Y-%m-%d %H:%M:%S"))

    if next_save <= current_time:
        from resources.libs import debridit
        logging.log("[Debrid Data] Saving all Data", level=xbmc.LOGINFO)
        debridit.auto_update('all')
        CONFIG.set_setting('debridnextsave',
                           tools.get_date(days=3, formatted=True))
    else:
        logging.log(
            "[Debrid Data] Next Auto Save isn't until: {0} / TODAY is: {1}".
            format(CONFIG.get_setting('debridnextsave'),
                   tools.get_date(formatted=True)),
            level=xbmc.LOGINFO)
예제 #17
0
def get_config():
    request = build_request('http://www.speedtest.net/speedtest-config.php')
    uh = catch_request(request)
    if uh is False:
        logging.log(
            'Could not retrieve speedtest.net configuration: {0}'.format(uh),
            level=xbmc.LOGDEBUG)
        sys.exit(1)

    configxml = []

    while 1:
        configxml.append(uh.read(10240))
        if len(configxml[-1]) == 0:
            break
    if int(uh.code) != 200:
        return None
    uh.close()
    try:
        try:
            root = ET.fromstring(''.encode('utf-8').join(configxml))
            config = {
                'client': root.find('client').attrib,
                'times': root.find('times').attrib,
                'download': root.find('download').attrib,
                'upload': root.find('upload').attrib,
            }
        except Exception:
            root = DOM.parseString(''.join(configxml))
            config = {
                'client': get_attributes_by_tag_name(root, 'client'),
                'times': get_attributes_by_tag_name(root, 'times'),
                'download': get_attributes_by_tag_name(root, 'download'),
                'upload': get_attributes_by_tag_name(root, 'upload'),
            }
    except SyntaxError:
        logging.log('Failed to parse speedtest.net configuration',
                    level=xbmc.LOGDEBUG)
        sys.exit(1)

    del root
    del configxml
    return config
예제 #18
0
def kill_kodi(msg=None, over=None):
    if over:
        choice = 1
    else:
        dialog = xbmcgui.Dialog()

        if not msg:
            msg = '[COLOR {0}]Chuẩn bị thoát KODI. Bạn có muốn tiếp tục?[/COLOR]'.format(
                CONFIG.COLOR2)

        choice = dialog.yesno(
            'Force Close Kodi',
            msg,
            nolabel='[B][COLOR red]Không![/COLOR][/B]',
            yeslabel='[B][COLOR springgreen]Thoát Ngay![/COLOR][/B]')
    if choice == 1:
        from resources.libs.common import logging
        logging.log("Force Closing Kodi: Platform[{0}]".format(str(
            platform())))
        os._exit(1)
예제 #19
0
def kill_kodi(msg=None, over=None):
    if over:
        choice = 1
    else:
        dialog = xbmcgui.Dialog()

        if not msg:
            msg = '[COLOR {0}]You are about to close Kodi. Would you like to continue?[/COLOR]'.format(
                CONFIG.COLOR2)

        choice = dialog.yesno(
            'Force Close Kodi',
            msg,
            nolabel='[B][COLOR red] No Cancel[/COLOR][/B]',
            yeslabel='[B][COLOR springgreen]Force Close Kodi[/COLOR][/B]')
    if choice == 1:
        from resources.libs.common import logging
        logging.log("Force Closing Kodi: Platform[{0}]".format(str(
            platform())))
        os._exit(1)
예제 #20
0
    def build_video(self, name):
        from resources.libs import check
        from resources.libs import yt
        from resources.libs.common import logging
        from resources.libs.common import tools

        response = tools.open_url(CONFIG.BUILDFILE, check=True)

        if response:
            videofile = check.check_build(name, 'preview')
            if tools.open_url(videofile, check=True):
                yt.play_video(videofile)
            else:
                logging.log(
                    "[{0}]No se puede encontrar la URL para la vista previa del vídeo"
                    .format(name))
        else:
            logging.log(
                "[B][COLOR azure]La Build del archivo de texto no funciona:[/COLOR][/B] [COLOR blue]{0}[/COLOR]"
                .format(CONFIG.BUILDFILE))
예제 #21
0
def kill_kodi(msg=None, over=None):
    if over:
        choice = 1
    else:
        dialog = xbmcgui.Dialog()

        if not msg:
            msg = '[COLOR {0}]Estás a punto de cerrar Kodi. Te gustaria continuar?[/COLOR]'.format(
                CONFIG.COLOR2)

        choice = dialog.yesno(
            'Forzar Cierre Kodi',
            msg,
            nolabel='[B][COLOR red] No, Cancelar[/COLOR][/B]',
            yeslabel='[B][COLOR springgreen]Forzar Cierre Kodi[/COLOR][/B]')
    if choice == 1:
        from resources.libs.common import logging
        logging.log("Forzar Cierre de Kodi: Plataforma[{0}]".format(
            str(platform())))
        os._exit(1)
예제 #22
0
 def build_video(self, name):
     from resources.libs import check
     from resources.libs import yt
     from resources.libs.common import logging
     from resources.libs.common import tools
     if 1 - 1: Oo0Ooo / o0oOOo0O0Ooo % iii1I1I * O00oOoOoO0o0O.i11iIiiIii
     iiiI11 = tools.open_url(CONFIG.BUILDFILE, check=True)
     if 2 - 2: I1ii11iIi11i * I11i - iIii1I11I1II1 + I1IiiI.oO0o % iii1I1I
     if iiiI11:
         ooOOOoOooOoO = check.check_build(name, 'preview')
         if tools.open_url(ooOOOoOooOoO, check=True):
             yt.play_video(ooOOOoOooOoO)
         else:
             logging.log(
                 "[{0}]Não foi possível encontrar url para a visualização do vídeo"
                 .format(name))
     else:
         logging.log(
             "O arquivo de texto de compilação não está funcionando: {0}".
             format(CONFIG.BUILDFILE))
         if 91 - 91: iii1I1I % i1IIi % iIii1I11I1II1
예제 #23
0
def look_and_feel_data(do='save'):
    from resources.libs.common import logging

    scan = ['lookandfeel.enablerssfeeds', 'lookandfeel.font', 'lookandfeel.rssedit', 'lookandfeel.skincolors',
            'lookandfeel.skintheme', 'lookandfeel.skinzoom', 'lookandfeel.soundskin', 'lookandfeel.startupwindow',
            'lookandfeel.stereostrength']
            
    if do == 'save':
        for item in scan:
            query = '{{"jsonrpc":"2.0", "method":"Settings.GetSettingValue","params":{{"setting":"{0}"}}, "id":1}}'.format(item)
            response = xbmc.executeJSONRPC(query)
            if 'error' not in response:
                match = re.compile('{"value":(.+?)}').findall(str(response))
                CONFIG.set_setting(item.replace('lookandfeel', 'default'), match[0])
                logging.log("%s saved to %s" % (item, match[0]))
    elif do == 'restore':
        for item in scan:
            value = CONFIG.get_setting(item.replace('lookandfeel', 'default'))
            query = '{{"jsonrpc":"2.0", "method":"Settings.SetSettingValue","params":{{"setting":"{0}","value":{1}}}, "id":1}}'.format(item, value)
            response = xbmc.executeJSONRPC(query)
            logging.log("{0} restored to {1}".format(item, value))
예제 #24
0
def kill_kodi(msg=None, over=None):
    if over:
        choice = 1
    else:
        dialog = xbmcgui.Dialog()

        if not msg:
            msg = '[COLOR {0}]Você está prestes a fechar o Kodi. Você gostaria de continuar?[/COLOR]'.format(
                CONFIG.COLOR2)

        choice = dialog.yesno(
            'Forçar o fechamento do Kodi',
            msg,
            nolabel='[B][COLOR red] Não Cancelar[/COLOR][/B]',
            yeslabel=
            '[B][COLOR springgreen]Forçar o fechamento do Kodi[/COLOR][/B]')
    if choice == 1:
        from resources.libs.common import logging
        logging.log("Forçar o fechamento do Kodi: plataforma[{0}]".format(
            str(platform())))
        os._exit(1)
예제 #25
0
def clean_house(folder, ignore=False):
    from resources.libs.common import logging

    logging.log(folder)
    total_files = 0
    total_folds = 0
    for root, dirs, files in os.walk(folder):
        if not ignore:
            dirs[:] = [d for d in dirs if d not in CONFIG.EXCLUDES]
        file_count = 0
        file_count += len(files)
        if file_count >= 0:
            for f in files:
                try:
                    os.unlink(os.path.join(root, f))
                    total_files += 1
                except:
                    try:
                        shutil.rmtree(os.path.join(root, f))
                    except:
                        logging.log("Error Deleting {0}".format(f), level=xbmc.LOGERROR)
            for d in dirs:
                total_folds += 1
                try:
                    shutil.rmtree(os.path.join(root, d))
                    total_folds += 1
                except:
                    logging.log("Error Deleting {0}".format(d), level=xbmc.LOGERROR)
    return total_files, total_folds
예제 #26
0
def youtube_menu(url=None):
    from resources.libs.common import logging
    from resources.libs.common import tools

    response = tools.open_url(CONFIG.YOUTUBEFILE)
    url_response = tools.open_url(url)

    if response:
        TEMPYOUTUBEFILE = url_response.text if url else response.text

        if TEMPYOUTUBEFILE:
            link = TEMPYOUTUBEFILE.replace('\n', '').replace('\r', '').replace('\t', '')
            match = re.compile('name="(.+?)".+?ection="(.+?)".+?rl="(.+?)".+?con="(.+?)".+?anart="(.+?)".+?escription="(.+?)"').findall(link)
            if len(match) > 0:
                for name, section, url, icon, fanart, description in match:
                    if section.lower() == "yes":
                        directory.add_dir("[B]{0}[/B]".format(name), {'mode': 'youtube', 'name': name, 'url': url}, description=description, icon=icon, fanart=fanart, themeit=CONFIG.THEME3)
                    else:
                        directory.add_file(name, {'mode': 'viewVideo', 'url': url}, description=description, icon=icon, fanart=fanart, themeit=CONFIG.THEME2)
            else:
                logging.log("[YouTube Menu] ERROR: Invalid Format.")
        else:
            logging.log("[YouTube Menu] ERROR: URL for YouTube list not working.")
            directory.add_file('Url for txt file not valid', themeit=CONFIG.THEME3)
            directory.add_file('{0}'.format(CONFIG.YOUTUBEFILE), themeit=CONFIG.THEME3)
    else:
        logging.log("[YouTube Menu] No YouTube list added.")
예제 #27
0
def convert_special(url, over=False):
    from resources.libs.common import logging

    progress_dialog = xbmcgui.DialogProgress()
    
    total = file_count(url)
    start = 0
    progress_dialog.create(CONFIG.ADDONTITLE,
                  "[COLOR {0}]Changing Physical Paths To Special".format(CONFIG.COLOR2),
                  "",
                  "Please Wait[/COLOR]")
    for root, dirs, files in os.walk(url):
        for file in files:
            start += 1
            perc = int(percentage(start, total))
            if file.endswith(".xml") or file.endswith(".hash") or file.endswith("properies"):
                progress_dialog.update(perc,
                              "[COLOR {0}]Scanning: [COLOR {1}]{2}[/COLOR]".format(CONFIG.COLOR2, CONFIG.COLOR1, root.replace(CONFIG.HOME, '')),
                              "[COLOR {0}]{1}[/COLOR]".format(CONFIG.COLOR1, file),
                              "Please Wait[/COLOR]")
                a = read_from_file(os.path.join(root, file))
                encodedpath = quote(CONFIG.HOME)
                encodedpath2 = quote(CONFIG.HOME).replace('%3A', '%3a').replace('%5C', '%5c')
                b = a.replace(CONFIG.HOME, 'special://home/').replace(encodedpath, 'special://home/').replace(encodedpath2, 'special://home/')
                
                try:
                    write_to_file(os.path.join(root, file), b)
                except IOError as e:
                    logging.log('Unable to open file to convert special paths: {}'.format(os.path.join(root, file)))

                if progress_dialog.iscanceled():
                    progress_dialog.close()
                    logging.log_notify(CONFIG.ADDONTITLE,
                                       "[COLOR {0}]Convert Path Cancelled[/COLOR]".format(CONFIG.COLOR2))
                    sys.exit()
    progress_dialog.close()
    logging.log("[Convert Paths to Special] Complete")
    if not over:
        logging.log_notify(CONFIG.ADDONTITLE,
                           "[COLOR {0}]Convert Paths to Special: Complete![/COLOR]".format(CONFIG.COLOR2))
예제 #28
0
def swap_us():
    from resources.libs.common import logging

    new = '"addons.unknownsources"'
    query = '{{"jsonrpc":"2.0", "method":"Settings.GetSettingValue","params":{{"setting":{0}}}, "id":1}}'.format(
        new)
    response = xbmc.executeJSONRPC(query)
    logging.log("Unknown Sources Get Settings: {0}".format(str(response)))
    if 'false' in response:
        value = 'true'
        threading.Thread(target=_dialog_watch).start()
        xbmc.sleep(200)
        query = '{{"jsonrpc":"2.0", "method":"Settings.SetSettingValue","params":{{"setting":{0},"value":{1}}}, "id":1}}'.format(
            new, value)
        response = xbmc.executeJSONRPC(query)
        logging.log_notify(
            "[COLOR {0}]{1}[/COLOR]".format(CONFIG.COLOR1, CONFIG.ADDONTITLE),
            '[COLOR {0}]Unknown Sources:[/COLOR] [COLOR {1}]Enabled[/COLOR]'.
            format(CONFIG.COLOR1, CONFIG.COLOR2))
        logging.log("Unknown Sources Set Settings: {0}".format(str(response)))
    elif 'true' in response:
        value = 'false'
        threading.Thread(target=_dialog_watch).start()
        xbmc.sleep(200)
        query = '{{"jsonrpc":"2.0", "method":"Settings.SetSettingValue","params":{{"setting":{0},"value":{1}}}, "id":1}}'.format(
            new, value)
        response = xbmc.executeJSONRPC(query)
        logging.log_notify(
            "[COLOR {0}]{1}[/COLOR]".format(CONFIG.COLOR1, CONFIG.ADDONTITLE),
            '[COLOR {0}]Unknown Sources:[/COLOR] [COLOR {1}]Disabled[/COLOR]'.
            format(CONFIG.COLOR1, CONFIG.COLOR2))
        logging.log("Unknown Sources Set Settings: {0}".format(str(response)))
예제 #29
0
def old_thumbs():
    from resources.libs import db
    from resources.libs.common import tools

    dbfile = os.path.join(CONFIG.DATABASE, db.latest_db('Textures'))
    use = 30
    week = tools.get_date(days=-7)
    ids = []
    images = []
    size = 0
    if os.path.exists(dbfile):
        try:
            textdb = database.connect(dbfile, isolation_level=None)
            textexe = textdb.cursor()
        except Exception as e:
            logging.log("DB Connection Error: {0}".format(str(e)),
                        level=xbmc.LOGERROR)
            return False
    else:
        logging.log('{0} not found.'.format(dbfile), level=xbmc.LOGERROR)
        return False
    textexe.execute(
        "SELECT idtexture FROM sizes WHERE usecount < ? AND lastusetime < ?",
        (use, str(week)))
    found = textexe.fetchall()
    for rows in found:
        idfound = rows[0]
        ids.append(idfound)
        textexe.execute("SELECT cachedurl FROM texture WHERE id = ?",
                        (idfound, ))
        found2 = textexe.fetchall()
        for rows2 in found2:
            images.append(rows2[0])
    logging.log("{0} total thumbs cleaned up.".format(str(len(images))),
                level=xbmc.LOGNOTICE)
    for id in ids:
        textexe.execute("DELETE FROM sizes WHERE idtexture = ?", (id, ))
        textexe.execute("DELETE FROM texture WHERE id = ?", (id, ))
    textexe.execute("VACUUM")
    textdb.commit()
    textexe.close()
    for image in images:
        path = os.path.join(CONFIG.THUMBNAILS, image)
        try:
            imagesize = os.path.getsize(path)
            os.remove(path)
            size += imagesize
        except:
            pass
    removed = tools.convert_size(size)
    if len(images) > 0:
        logging.log_notify(
            "[COLOR {0}]{1}[/COLOR]".format(CONFIG.COLOR1, CONFIG.ADDONTITLE),
            '[COLOR {0}]Clear Thumbs: {1} Files / {2} MB[/COLOR]!'.format(
                CONFIG.COLOR2, str(len(images)), removed))
    else:
        logging.log_notify(
            "[COLOR {0}]{1}[/COLOR]".format(CONFIG.COLOR1, CONFIG.ADDONTITLE),
            '[COLOR {0}]Clear Thumbs: None Found![/COLOR]'.format(
                CONFIG.COLOR2))
예제 #30
0
def unhide_password():
    from resources.libs.common import tools
    from resources.libs.common import logging
    
    dialog = xbmcgui.Dialog()

    if dialog.yesno(CONFIG.ADDONTITLE,
                        "[COLOR {0}]Would you like to [COLOR {1}]unhide[/COLOR] all passwords when typing in the add-on settings menus?[/COLOR]".format(CONFIG.COLOR2, CONFIG.COLOR1),
                        yeslabel="[B][COLOR springgreen]Unhide Passwords[/COLOR][/B]",
                        nolabel="[B][COLOR red]No Cancel[/COLOR][/B]"):
        count = 0
        for folder in glob.glob(os.path.join(CONFIG.ADDONS, '*/')):
            sett = os.path.join(folder, 'resources', 'settings.xml')
            if os.path.exists(sett):
                f = tools.read_from_file(sett)
                match = tools.parse_dom(f, 'addon', ret='id')
                for line in match:
                    if 'pass' in line:
                        if 'option="hidden"' in line:
                            try:
                                change = line.replace('option="hidden"', '')
                                f.replace(line, change)
                                count += 1
                                logging.log("[Unhide Passwords] found in {0} on {1}".format(sett.replace(CONFIG.HOME, ''), line))
                            except:
                                pass
                tools.write_to_file(sett, f)
        logging.log_notify("[COLOR {0}]Unhide Passwords[/COLOR]".format(CONFIG.COLOR1),
                           "[COLOR {0}]{1} items changed[/COLOR]".format(CONFIG.COLOR2, count))
        logging.log("[Unhide Passwords] {0} items changed".format(count))
    else:
        logging.log("[Unhide Passwords] Cancelled")