def purge_db_file(name): logging.log('Purging DB {0}.'.format(name)) if os.path.exists(name): try: textdb = database.connect(name) 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(name), level=xbmc.LOGERROR) return False textexe.execute("SELECT name FROM sqlite_master WHERE type = 'table'") for table in textexe.fetchall(): if table[0] == 'version': logging.log('Data from table `{0}` skipped.'.format(table[0])) else: try: textexe.execute("DELETE FROM {0}".format(table[0])) textdb.commit() logging.log('Data from table `{0}` cleared.'.format(table[0])) except Exception as e: logging.log("DB Remove Table `{0}` Error: {1}".format( table[0], str(e)), level=xbmc.LOGERROR) textexe.close() logging.log('{0} DB Purging Complete.'.format(name)) show = name.replace('\\', '/').split('/') logging.log_notify( "[COLOR {0}]Purge Database[/COLOR]".format(CONFIG.COLOR1), "[COLOR {0}]{1} Complete[/COLOR]".format(CONFIG.COLOR2, show[len(show) - 1]))
def kodi_17_fix(): from resources.libs.common import tools from resources.libs import update addonlist = glob.glob(os.path.join(CONFIG.ADDONS, '*/')) disabledAddons = [] for folder in sorted(addonlist, key=lambda x: x): addonxml = os.path.join(folder, 'addon.xml') if os.path.exists(addonxml): fold = folder.replace(CONFIG.ADDONS, '')[1:-1] aid = tools.parse_dom(tools.read_from_file(addonxml), 'addon', ret='id') try: if len(aid) > 0: addonid = aid[0] else: addonid = fold except: try: logging.log("{0} was disabled".format(aid[0])) disabledAddons.append(addonid) except: logging.log("Unable to enable: {0}".format(folder), level=xbmc.LOGERROR) if len(disabledAddons) > 0: addon_database(disabledAddons, 1, True) logging.log_notify("[COLOR {0}]{1}[/COLOR]".format(CONFIG.COLOR1, CONFIG.ADDONTITLE), "[COLOR {0}]Enabling Addons Complete![/COLOR]".format(CONFIG.COLOR2)) update.force_update() xbmc.executebuiltin("ReloadSkin()")
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")
def test_notify(): from resources.libs.common import logging from resources.libs.common import tools from resources.libs.gui import window response = tools.open_url(CONFIG.NOTIFICATION, check=True) if response: try: id, msg = window.split_notify(CONFIG.NOTIFICATION) if not id: logging.log_notify( CONFIG.ADDONTITLE, "[COLOR {0}] Notificação: Não formatado corretamente[/COLOR]" .format(CONFIG.COLOR2)) return window.show_notification(msg, test=True) except Exception as e: logging.log("Erro na janela de notificações: {0}".format(str(e)), level=xbmc.LOGERROR) else: logging.log_notify( CONFIG.ADDONTITLE, "[COLOR {0}] URL inválido para notificação[/COLOR]".format( CONFIG.COLOR2))
def toggle_cache(state): cachelist = [ 'includevideo', 'includeall', 'includeexodusredux', 'includegaia', 'inlcudenumbers', 'includescrubs', 'includeseren', 'includethecrew', 'includevenom' ] titlelist = [ 'Include Video Addons', 'Include All Addons', 'Include Exodus Redux', 'Include Gaia', 'Include NuMb3r5', 'Include Scrubs v2', 'Include Seren', 'Include THE CREW', 'Include Venom' ] if state in ['true', 'false']: for item in cachelist: CONFIG.set_setting(item, state) else: if state not in ['includevideo', 'includeall' ] and CONFIG.get_setting('includeall') == 'true': try: dialog = xbmcgui.Dialog() item = titlelist[cachelist.index(state)] dialog.ok( CONFIG.ADDONTITLE, "[COLOR {0}]You will need to turn off [COLOR {1}]Include All Addons[/COLOR] to disable[/COLOR] [COLOR {2}]{3}[/COLOR]" .format(CONFIG.COLOR2, CONFIG.COLOR1, CONFIG.COLOR1, item)) except: logging.log_notify( "[COLOR {0}]Toggle Cache[/COLOR]".format(CONFIG.COLOR1), "[COLOR {0}]Invalid Add-on ID: {1}[/COLOR]".format( CONFIG.COLOR2, state)) else: new = 'true' if CONFIG.get_setting(state) == 'false' else 'false' CONFIG.set_setting(state, new)
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( 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( 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)))
def import_list(who): if who == 'all': for log in TRAKTID: if os.path.exists(TRAKTID[log]['file']): import_list(log) elif TRAKTID[who]: if os.path.exists(TRAKTID[who]['file']): file = TRAKTID[who]['file'] addonid = tools.get_addon_by_id(TRAKTID[who]['plugin']) saved = TRAKTID[who]['saved'] default = TRAKTID[who]['default'] suser = CONFIG.get_setting(saved) name = TRAKTID[who]['name'] tree = ElementTree.parse(file) root = tree.getroot() for setting in root.iter('trakt'): id = setting.find('id').text value = setting.find('value').text addonid.setSetting(id, value) logging.log_notify("[COLOR {0}]{1}[/COLOR]".format(CONFIG.COLOR1, name), '[COLOR {0}]Trakt Data: Imported![/COLOR]'.format(CONFIG.COLOR2))
def test_notify(): from resources.libs.common import logging from resources.libs.common import tools from resources.libs.gui import window response = tools.open_url(CONFIG.NOTIFICATION, check=True) if response: try: id, msg = window.split_notify(CONFIG.NOTIFICATION) if not id: logging.log_notify( "[COLOR {0}]{1}[/COLOR]".format(CONFIG.COLOR1, CONFIG.ADDONTITLE), "[COLOR {0}]Notification: Not Formatted Correctly[/COLOR]". format(CONFIG.COLOR2)) return window.show_notification(msg, True) except Exception as e: logging.log("Error on Notifications Window: {0}".format(str(e)), level=xbmc.LOGERROR) else: logging.log_notify( "[COLOR {0}]{1}[/COLOR]".format(CONFIG.COLOR1, CONFIG.ADDONTITLE), "[COLOR {0}]Invalid URL for Notification[/COLOR]".format( CONFIG.COLOR2))
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)))) 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( CONFIG.ADDONTITLE, '[COLOR {0}]Clear Thumbs: {1} Files / {2} MB[/COLOR]!'.format( CONFIG.COLOR2, str(len(images)), removed)) else: logging.log_notify( CONFIG.ADDONTITLE, '[COLOR {0}]Clear Thumbs: None Found![/COLOR]'.format( CONFIG.COLOR2))
def download(self, url, dest): self.progress_dialog.create(CONFIG.ADDONTITLE, "Downloading Content", ' ', ' ') self.progress_dialog.update(0) path = os.path.split(dest)[0] if not os.path.exists(path): os.makedirs(path) with open(dest, 'wb') as f: response = tools.open_url(url, stream=True) if not response: logging.log_notify( CONFIG.ADDONTITLE, '[COLOR {0}]Build Install: Invalid Zip Url![/COLOR]'. format(CONFIG.COLOR2)) return else: total = response.headers.get('content-length') if total is None: f.write(response.content) else: downloaded = 0 total = int(total) start_time = time.time() mb = 1024 * 1024 for chunk in response.iter_content( chunk_size=max(int(total / 512), mb)): downloaded += len(chunk) f.write(chunk) done = int(100 * downloaded / total) kbps_speed = downloaded / (time.time() - start_time) if kbps_speed > 0 and not done >= 100: eta = (total - downloaded) / kbps_speed else: eta = 0 kbps_speed = kbps_speed / 1024 type_speed = 'KB' if kbps_speed >= 1024: kbps_speed = kbps_speed / 1024 type_speed = 'MB' currently_downloaded = '[COLOR %s][B]Size:[/B] [COLOR %s]%.02f[/COLOR] MB of [COLOR %s]%.02f[/COLOR] MB[/COLOR]' % ( CONFIG.COLOR2, CONFIG.COLOR1, downloaded / mb, CONFIG.COLOR1, total / mb) speed = '[COLOR %s][B]Speed:[/B] [COLOR %s]%.02f [/COLOR]%s/s ' % ( CONFIG.COLOR2, CONFIG.COLOR1, kbps_speed, type_speed) div = divmod(eta, 60) speed += '[B]ETA:[/B] [COLOR %s]%02d:%02d[/COLOR][/COLOR]' % ( CONFIG.COLOR1, div[0], div[1]) self.progress_dialog.update(done, '', currently_downloaded, speed)
def fresh_start(install=None, over=False): from resources.libs.common import logging from resources.libs.common import tools dialog = xbmcgui.Dialog() # if CONFIG.KEEPTRAKT == 'true': # from resources.libs import traktit # traktit.auto_update('all') # CONFIG.set_setting('traktnextsave', str(tools.get_date(days=3, formatted=True))) # if CONFIG.KEEPDEBRID == 'true': # from resources.libs import debridit # debridit.auto_update('all') # CONFIG.set_setting('debridnextsave', str(tools.get_date(days=3, formatted=True))) # if CONFIG.KEEPLOGIN == 'true': # from resources.libs import loginit # loginit.auto_update('all') # CONFIG.set_setting('loginnextsave', str(tools.get_date(days=3, formatted=True))) if over: yes_pressed = 1 elif install == 'restore': yes_pressed = dialog.yesno(CONFIG.ADDONTITLE, "Bạn có muốn khôi phục Kodi về mặc định.", "Trước khi cài đặt bản Build cá nhân?[/COLOR]", nolabel='[B][COLOR red]Không![/COLOR][/B]', yeslabel='[B][COLOR springgreen]Tiếp Tục![/COLOR][/B]') elif install: yes_pressed = dialog.yesno(CONFIG.ADDONTITLE, "Bạn có muốn khôi phục Kodi về mặc định.", "Trước khi cài đặt [COLOR {0}]{1}[/COLOR]?".format(CONFIG.COLOR1, install), nolabel='[B][COLOR red]Không![/COLOR][/B]', yeslabel='[B][COLOR springgreen]Tiếp Tục[/COLOR][/B]') else: yes_pressed = dialog.yesno(CONFIG.ADDONTITLE, "Bạn có muốn khôi phục Kodi về mặc định.", nolabel='[B][COLOR red]Không![/COLOR][/B]', yeslabel='[B][COLOR springgreen]Tiếp Tục![/COLOR][/B]') if yes_pressed: wipe() if over: return True elif install == 'restore': return True elif install: from resources.libs.wizard import Wizard Wizard().build('normal', install, over=True) else: dialog.ok(CONFIG.ADDONTITLE, "[COLOR {0}]Để thay đổi có hiệu lực cần thoát hẳn KODI.\nNhấn OK để thoát Kodi[/COLOR]".format(CONFIG.COLOR2)) from resources.libs import update update.addon_updates('reset') tools.kill_kodi(over=True) else: if not install == 'restore': logging.log_notify(CONFIG.ADDONTITLE, '[COLOR {0}]Fresh Install: Cancelled![/COLOR]'.format(CONFIG.COLOR2)) xbmc.executebuiltin('Container.Refresh()')
def force_update(silent=False): xbmc.executebuiltin('UpdateAddonRepos()') xbmc.executebuiltin('UpdateLocalAddons()') if not silent: from resources.libs.common import logging logging.log_notify("[COLOR {0}]{1}[/COLOR]".format(CONFIG.COLOR1, CONFIG.ADDONTITLE), '[COLOR {0}]Forcing Addon Updates[/COLOR]'.format(CONFIG.COLOR2))
def gui(self, name, over=False): if name == CONFIG.get_setting('buildname'): if over: yes_pressed = 1 else: yes_pressed = self.dialog.yesno(CONFIG.ADDONTITLE, '[COLOR {0}]Would you like to apply the guifix for:'.format(CONFIG.COLOR2) + '\n' + '[COLOR {0}]{1}[/COLOR]?[/COLOR]'.format(CONFIG.COLOR1, name), nolabel='[B][COLOR red]No, Cancel[/COLOR][/B]', yeslabel='[B][COLOR springgreen]Apply Fix[/COLOR][/B]') else: yes_pressed = self.dialog.yesno("{0} - [COLOR red]WARNING!![/COLOR]".format(CONFIG.ADDONTITLE), "[COLOR {0}][COLOR {1}]{2}[/COLOR] community build is not currently installed.".format(CONFIG.COLOR2, CONFIG.COLOR1, name) + '\n' + "Would you like to apply the guiFix anyways?.[/COLOR]", nolabel='[B][COLOR red]No, Cancel[/COLOR][/B]', yeslabel='[B][COLOR springgreen]Apply Fix[/COLOR][/B]') if yes_pressed: guizip = check.check_build(name, 'gui') zipname = name.replace('\\', '').replace('/', '').replace(':', '').replace('*', '').replace('?', '').replace('"', '').replace('<', '').replace('>', '').replace('|', '') response = tools.open_url(guizip, check=True) if not response: logging.log_notify(CONFIG.ADDONTITLE, '[COLOR {0}]GuiFix: Invalid Zip Url![/COLOR]'.format(CONFIG.COLOR2)) return self.dialogProgress.create(CONFIG.ADDONTITLE, '[COLOR {0}][B]Downloading GuiFix:[/B][/COLOR] [COLOR {1}]{2}[/COLOR]'.format(CONFIG.COLOR2, CONFIG.COLOR1, name), '', 'Please Wait') lib = os.path.join(CONFIG.PACKAGES, '{0}_guisettings.zip'.format(zipname)) try: os.remove(lib) except: pass Downloader().download(guizip, lib) xbmc.sleep(500) if os.path.getsize(lib) == 0: try: os.remove(lib) except: pass return title = '[COLOR {0}][B]Installing:[/B][/COLOR] [COLOR {1}]{2}[/COLOR]'.format(CONFIG.COLOR2, CONFIG.COLOR1, name) self.dialogProgress.update(0, title + '\n' + 'Please Wait') extract.all(lib, CONFIG.USERDATA, title=title) self.dialogProgress.close() skin.skin_to_default('Build Install') skin.look_and_feel_data('save') installed = db.grab_addons(lib) db.addon_database(installed, 1, True) self.dialog.ok(CONFIG.ADDONTITLE, "[COLOR {0}]To save changes you now need to force close Kodi, Press OK to force close Kodi[/COLOR]".format(CONFIG.COLOR2)) tools.kill_kodi(over=True) else: logging.log_notify(CONFIG.ADDONTITLE, '[COLOR {0}]GuiFix: Cancelled![/COLOR]'.format(CONFIG.COLOR2))
def doWrite(self): dialog = xbmcgui.Dialog() buffermode = 2 if os.path.exists(CONFIG.ADVANCED): choice = dialog.yesno( CONFIG.ADDONTITLE, "[COLOR {0}]There is currently an active [COLOR {1}]advancedsettings.xml[/COLOR], would you like to remove it and continue?[/COLOR]" .format(CONFIG.COLOR2, CONFIG.COLOR1), yeslabel="[B][COLOR green]Remove Settings[/COLOR][/B]", nolabel="[B][COLOR red]Cancel Write[/COLOR][/B]") if choice == 0: return try: os.remove(CONFIG.ADVANCED) except: f = open(CONFIG.ADVANCED, 'w') f.close() if CONFIG.KODIV < 17: with open(CONFIG.ADVANCED, 'w+') as f: f.write('<advancedsettings>\n') f.write(' <network>\n') f.write(' <buffermode>%s</buffermode>\n' % buffermode) f.write(' <cachemembuffersize>%s</cachemembuffersize>\n' % int(self.currentVideo * 1024 * 1024)) f.write(' <readbufferfactor>%s</readbufferfactor>\n' % self.currentRead) f.write(' <curlclienttimeout>%s</curlclienttimeout>\n' % self.currentCurl) f.write(' <curllowspeedtime>%s</curllowspeedtime>\n' % self.currentCurl) f.write(' </network>\n') f.write('</advancedsettings>\n') f.close() else: with open(CONFIG.ADVANCED, 'w+') as f: f.write('<advancedsettings>\n') f.write(' <cache>\n') f.write(' <buffermode>%s</buffermode>\n' % buffermode) f.write(' <memorysize>%s</memorysize>\n' % int(self.currentVideo * 1024 * 1024)) f.write(' <readfactor>%s</readfactor>\n' % self.currentRead) f.write(' </cache>\n') f.write(' <network>\n') f.write(' <curlclienttimeout>%s</curlclienttimeout>\n' % self.currentCurl) f.write(' <curllowspeedtime>%s</curllowspeedtime>\n' % self.currentCurl) f.write(' </network>\n') f.write('</advancedsettings>\n') f.close() logging.log_notify( "[COLOR {0}]{1}[/COLOR]".format(CONFIG.COLOR1, CONFIG.ADDONTITLE), '[COLOR {0}]advancedsettings.xml has been written[/COLOR]'. format(CONFIG.COLOR2)) self.close()
def install_skin(self, name, url): from resources.libs.downloader import Downloader from resources.libs import db from resources.libs import extract from resources.libs.common import logging from resources.libs import skin from resources.libs.common import tools progress_dialog = xbmcgui.DialogProgress() response = tools.open_url(url, check=False) if not response: logging.log_notify( "[COLOR {0}]Instalador de Add-ons[/COLOR]".format( CONFIG.COLOR1), '[COLOR {0}]{1}:[/COLOR] [COLOR {2}]Url del Zip Inválida![/COLOR]' .format(CONFIG.COLOR1, name, CONFIG.COLOR2)) return if not os.path.exists(CONFIG.PACKAGES): os.makedirs(CONFIG.PACKAGES) progress_dialog.create( CONFIG.ADDONTITLE, '[COLOR {0}][B]Descargando:[/B][/COLOR] [COLOR {1}]{2}[/COLOR]'. format(CONFIG.COLOR2, CONFIG.COLOR1, name) + '\n' + '' + '\n' + '[COLOR {0}]Espere por Favor[/COLOR]'.format(CONFIG.COLOR2)) urlsplits = url.split('/') lib = xbmc.makeLegalFilename( os.path.join(CONFIG.PACKAGES, urlsplits[-1])) try: os.remove(lib) except: pass Downloader().download(url, lib) title = '[COLOR {0}][B]Instalando:[/B][/COLOR] [COLOR {1}]{2}[/COLOR]'.format( CONFIG.COLOR2, CONFIG.COLOR1, name) progress_dialog.update( 0, title + '\n' + '' + '\n' + '[COLOR {0}]Espere por Favor[/COLOR]'.format(CONFIG.COLOR2)) percent, errors, error = extract.all(lib, CONFIG.HOME, title=title) installed = db.grab_addons(lib) db.addon_database(installed, 1, True) progress_dialog.close() logging.log_notify( "[COLOR {0}]Instalador de Add-ons[/COLOR]".format(CONFIG.COLOR1), '[COLOR {0}]{1}: Instalado![/COLOR]'.format(CONFIG.COLOR2, name)) xbmc.executebuiltin('UpdateAddonRepos()') xbmc.executebuiltin('UpdateLocalAddons()') for item in installed: if item.startswith('skin.') and not item == 'skin.shortcuts': if not CONFIG.BUILDNAME == '' and CONFIG.DEFAULTIGNORE == 'true': CONFIG.set_setting('defaultskinignore', 'true') skin.switch_to_skin(item, 'Skin Installer') xbmc.executebuiltin('Container.Refresh()')
def install_addon_from_url(self, plugin, url): from resources.libs.downloader import Downloader from resources.libs import db from resources.libs import extract from resources.libs import skin response = tools.open_url(url, check=True) if not response: logging.log_notify( "[COLOR {0}]Instalador de Add-ons[/COLOR]".format( CONFIG.COLOR1), '[COLOR {0}]{1}:[/COLOR] [COLOR {2}]URL inválido zip![/COLOR]'. format(CONFIG.COLOR1, plugin, CONFIG.COLOR2)) return tools.ensure_folders(CONFIG.PACKAGES) self.progress_dialog.create( CONFIG.ADDONTITLE, '[COLOR {0}][B]Descargando:[/B][/COLOR] [COLOR {1}]{2}[/COLOR]'. format(CONFIG.COLOR2, CONFIG.COLOR1, plugin) + '\n' + '' + '\n' + '[COLOR {0}]Espere por Favor[/COLOR]'.format(CONFIG.COLOR2)) urlsplits = url.split('/') lib = os.path.join(CONFIG.PACKAGES, urlsplits[-1]) try: os.remove(lib) except: pass Downloader().download(url, lib) title = '[COLOR {0}][B]Instalando:[/B][/COLOR] [COLOR {1}]{2}[/COLOR]'.format( CONFIG.COLOR2, CONFIG.COLOR1, plugin) self.progress_dialog.update( 0, title + '\n' + '' + '\n' + '[COLOR {0}]Espere por Favor[/COLOR]'.format(CONFIG.COLOR2)) percent, errors, error = extract.all(lib, CONFIG.ADDONS, title=title) self.progress_dialog.update( 0, title + '\n' + '' + '\n' + '[COLOR {0}]Instalando Dependencias[/COLOR]'.format(CONFIG.COLOR2)) installed(plugin) installlist = db.grab_addons(lib) logging.log(str(installlist)) db.addon_database(installlist, 1, True) self.install_dependency(plugin) self.progress_dialog.close() xbmc.executebuiltin('UpdateAddonRepos()') xbmc.executebuiltin('UpdateLocalAddons()') xbmc.executebuiltin('Container.Refresh()') for item in installlist: if item.startswith('skin.') and not item == 'skin.shortcuts': if not CONFIG.BUILDNAME == '' and CONFIG.DEFAULTIGNORE == 'true': CONFIG.set_setting('defaultskinignore', 'true') skin.switch_to_skin(item, 'Skin Installer')
def skin_to_default(title): if _get_old('lookandfeel.skin') not in DEFAULT_SKINS: skin = 'skin.estuary' return switch_to_skin(skin, title) else: from resources.libs.common import logging logging.log_notify(CONFIG.ADDONTITLE, '[COLOR {0}]{1}: Skipping Skin Swap[/COLOR]'.format(CONFIG.COLOR2, title)) return False
def install_addon_from_url(name, url): from resources.libs.downloader import Downloader from resources.libs import db from resources.libs import extract from resources.libs.common import logging from resources.libs import skin from resources.libs.common import tools progress_dialog = xbmcgui.DialogProgress() response = tools.open_url(url, check=True) if not response: logging.log_notify( "[COLOR {0}]Addon Installer[/COLOR]".format(CONFIG.COLOR1), '[COLOR {0}]{1}:[/COLOR] [COLOR {2}]Invalid Zip Url![/COLOR]'. format(CONFIG.COLOR1, name, CONFIG.COLOR2)) return if not os.path.exists(CONFIG.PACKAGES): os.makedirs(CONFIG.PACKAGES) progress_dialog.create( CONFIG.ADDONTITLE, '[COLOR {0}][B]Downloading:[/B][/COLOR] [COLOR {1}]{2}[/COLOR]'.format( CONFIG.COLOR2, CONFIG.COLOR1, name), '', '[COLOR {0}]Please Wait[/COLOR]'.format(CONFIG.COLOR2)) urlsplits = url.split('/') lib = os.path.join(CONFIG.PACKAGES, urlsplits[-1]) try: os.remove(lib) except: pass Downloader().download(url, lib) title = '[COLOR {0}][B]Installing:[/B][/COLOR] [COLOR {1}]{2}[/COLOR]'.format( CONFIG.COLOR2, CONFIG.COLOR1, name) progress_dialog.update( 0, title, '', '[COLOR {0}]Please Wait[/COLOR]'.format(CONFIG.COLOR2)) percent, errors, error = extract.all(lib, CONFIG.ADDONS, title=title) progress_dialog.update( 0, title, '', '[COLOR {0}]Installing Dependencies[/COLOR]'.format(CONFIG.COLOR2)) installed(name) installlist = db.grab_addons(lib) logging.log(str(installlist)) db.addon_database(installlist, 1, True) install_dependency(name, progress_dialog) progress_dialog.close() xbmc.executebuiltin('UpdateAddonRepos()') xbmc.executebuiltin('UpdateLocalAddons()') xbmc.executebuiltin('Container.Refresh()') for item in installlist: if item.startswith('skin.') and not item == 'skin.shortcuts': if not CONFIG.BUILDNAME == '' and CONFIG.DEFAULTIGNORE == 'true': CONFIG.set_setting('defaultskinignore', 'true') skin.switch_to_skin(item, 'Skin Installer')
def wizard_update(): from resources.libs import check from resources.libs.common import logging from resources.libs.common import tools from resources.libs.gui import window dialog = xbmcgui.Dialog() progress_dialog = xbmcgui.DialogProgress() response = tools.open_url(CONFIG.BUILDFILE, check=True) if response: try: wid, ver, zip = check.check_wizard('all') except: return if ver > CONFIG.ADDON_VERSION: yes = dialog.yesno(CONFIG.ADDONTITLE, '[COLOR {0}]There is a new version of the {1}!'.format(CONFIG.COLOR2, CONFIG.ADDONTITLE) +'\n'+'Would you like to download [COLOR {0}]v{1}[/COLOR]?[/COLOR]'.format(CONFIG.COLOR1, ver), nolabel='[B][COLOR red]Remind Me Later[/COLOR][/B]', yeslabel="[B][COLOR springgreen]Update Wizard[/COLOR][/B]") if yes: from resources.libs import db from resources.libs.common import tools logging.log("[Auto Update Wizard] Installing wizard v{0}".format(ver)) progress_dialog.create(CONFIG.ADDONTITLE, '[COLOR {0}]Downloading Update...'.format(CONFIG.COLOR2) +'\n'+'' +'\n'+'Please Wait[/COLOR]') lib = os.path.join(CONFIG.PACKAGES, '{0}-{1}.zip'.format(CONFIG.ADDON_ID, ver)) try: os.remove(lib) except: pass from resources.libs.downloader import Downloader from resources.libs import extract Downloader().download(zip, lib) xbmc.sleep(2000) progress_dialog.update(0, '\n'+"Installing {0} update".format(CONFIG.ADDONTITLE)) percent, errors, error = extract.all(lib, CONFIG.ADDONS, True) progress_dialog.close() xbmc.sleep(1000) db.force_check_updates(auto=True, over=True) xbmc.sleep(1000) logging.log_notify(CONFIG.ADDONTITLE, '[COLOR {0}]Add-on updated[/COLOR]'.format(CONFIG.COLOR2)) logging.log("[Auto Update Wizard] Wizard updated to v{0}".format(ver)) tools.remove_file(os.path.join(CONFIG.ADDON_DATA, 'settings.xml')) window.show_save_data_settings() else: logging.log("[Auto Update Wizard] Install New Wizard Ignored: {0}".format(ver)) else: logging.log("[Auto Update Wizard] No New Version v{0}".format(ver)) else: logging.log("[Auto Update Wizard] Url for wizard file not valid: {0}".format(CONFIG.BUILDFILE))
def wizard_update(): from resources.libs import check from resources.libs.common import logging from resources.libs.common import tools from resources.libs.gui import window dialog = xbmcgui.Dialog() progress_dialog = xbmcgui.DialogProgress() response = tools.open_url(CONFIG.BUILDFILE, check=True) if response: try: wid, ver, zip = check.check_wizard('all') except: return if ver > CONFIG.ADDON_VERSION: yes = dialog.yesno(CONFIG.ADDONTITLE, '[COLOR {0}]Existe uma nova versão do {1}!'.format(CONFIG.COLOR2, CONFIG.ADDONTITLE) +'\n'+'Você gostaria de baixar [COLOR {0}]v{1}[/COLOR]?[/COLOR]'.format(CONFIG.COLOR1, ver), nolabel='[B][COLOR red]Você gostaria de baixar[/COLOR][/B]', yeslabel="[B][COLOR springgreen]Assistente de atualização[/COLOR][/B]") if yes: from resources.libs import db from resources.libs.common import tools logging.log("[Assistente de atualização automática] Assistente de instalação v{0}".format(ver)) progress_dialog.create(CONFIG.ADDONTITLE, '[COLOR {0}]Download da atualização...'.format(CONFIG.COLOR2) +'\n'+'' +'\n'+'Por favor, aguarde...[/COLOR]') lib = os.path.join(CONFIG.PACKAGES, '{0}-{1}.zip'.format(CONFIG.ADDON_ID, ver)) try: os.remove(lib) except: pass from resources.libs.downloader import Downloader from resources.libs import extract Downloader().download(zip, lib) xbmc.sleep(2000) progress_dialog.update(0, '\n'+"Instalando{0} atualizar".format(CONFIG.ADDONTITLE)) percent, errors, error = extract.all(lib, CONFIG.ADDONS, True) progress_dialog.close() xbmc.sleep(1000) db.force_check_updates(auto=True, over=True) xbmc.sleep(1000) logging.log_notify(CONFIG.ADDONTITLE, '[COLOR {0}]Add-on atualizado[/COLOR]'.format(CONFIG.COLOR2)) logging.log("[Assistente de atualização automática] Assistente atualizado para v{0}".format(ver)) tools.remove_file(os.path.join(CONFIG.ADDON_DATA, 'settings.xml')) window.show_save_data_settings() else: logging.log("[Assistente de atualização automática] Instalar novo assistente ignorado: {0}".format(ver)) else: logging.log("[Assistente de atualização automática] Sem nova versão v{0}".format(ver)) else: logging.log("[Assistente de atualização automática] Url para o arquivo do assistente não é válido: {0}".format(CONFIG.BUILDFILE))
def force_check_updates(auto=False, over=False): import time if not over: logging.log_notify( CONFIG.ADDONTITLE, '[COLOR {0}]Force Checking for Updates[/COLOR]'.format( CONFIG.COLOR2)) dbfile = latest_db('Addons') dbfile = os.path.join(CONFIG.DATABASE, dbfile) sqldb = database.connect(dbfile) sqlexe = sqldb.cursor() # force rollback all installed repos sqlexe.execute("UPDATE repo SET version = ?, checksum = ?, lastcheck = ?", ( '', '', '', )) sqldb.commit() # trigger kodi to check them for updates xbmc.executebuiltin('UpdateAddonRepos') # wait until they have finished updating with tools.busy_dialog(): installed_repos = sqlexe.execute('SELECT addonID FROM repo') start_time = time.time() checked_time = 0 for repo in installed_repos.fetchall(): repo = repo[0] while checked_time < start_time: logging.log( 'Making sure {0} was checked successfully.'.format(repo), level=xbmc.LOGDEBUG) lastcheck = sqlexe.execute( 'SELECT lastcheck FROM repo WHERE addonID = ?', (repo, )) if lastcheck: checked_time = lastcheck.fetchone()[0] if checked_time: checked_time = time.mktime( time.strptime(checked_time, '%Y-%m-%d %H:%M:%S')) xbmc.sleep(1000) checked_time = 0 logging.log('{0} successfully force checked.'.format(repo), level=xbmc.LOGDEBUG) sqlexe.close() if auto: xbmc.executebuiltin('UpdateLocalAddons')
def change_freq(): from resources.libs.common import logging dialog = xbmcgui.Dialog() change = dialog.select("[COLOR {0}]How often would you list to Auto Clean on Startup?[/COLOR]".format(CONFIG.COLOR2), CONFIG.CLEANFREQ) if not change == -1: CONFIG.set_setting('autocleanfreq', str(change)) logging.log_notify('[COLOR {0}]Auto Clean Up[/COLOR]'.format(CONFIG.COLOR1), '[COLOR {0}]Frequency Now {1}[/COLOR]'.format(CONFIG.COLOR2, CONFIG.CLEANFREQ[change]))
def installed(addon): url = os.path.join(CONFIG.ADDONS, addon, 'addon.xml') if os.path.exists(url): try: name = tools.parse_dom(tools.read_from_file(url), 'addon', ret='name', attrs={'id': addon}) icon = os.path.join(CONFIG.ADDONS, addon, 'icon.png') # read from infolabel? logging.log_notify('[COLOR {0}]{1}[/COLOR]'.format(CONFIG.COLOR1, name[0]), '[COLOR {0}]Add-on Enabled[/COLOR]'.format(CONFIG.COLOR2), '2000', icon) except: pass
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}]Cambio de Rutas Físicas a Especiales".format( CONFIG.COLOR2) + "\n" + "Espere por favor[/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}]Escaneando: [COLOR {1}]{2}[/COLOR]".format( CONFIG.COLOR2, CONFIG.COLOR1, root.replace(CONFIG.HOME, '')) + '\n' + "[COLOR {0}]{1}[/COLOR]".format(CONFIG.COLOR1, file) + '\n' + "Espere por Favor[/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( 'No se puede abrir el archivo para convertir rutas especiales: {}' .format(os.path.join(root, file))) if progress_dialog.iscanceled(): progress_dialog.close() logging.log_notify( CONFIG.ADDONTITLE, "[COLOR {0}]Conversión de Ruta Cancelada[/COLOR]". format(CONFIG.COLOR2)) sys.exit() progress_dialog.close() logging.log("[Convertir Rutas en Especiales Completas") if not over: logging.log_notify( CONFIG.ADDONTITLE, "[COLOR {0}]Convertir Rutas en Especiales:[/COLOR] [COLOR azure]Completo![/COLOR]" .format(CONFIG.COLOR2))
def remove_advanced(): from resources.libs.common import tools from resources.libs.common import logging if os.path.exists(CONFIG.ADVANCED): tools.remove_file(CONFIG.ADVANCED) else: logging.log_notify( "[COLOR {0}]{1}[/COLOR]".format(CONFIG.COLOR1, CONFIG.ADDONTITLE), "[COLOR {0}]AdvancedSettings.xml not found[/COLOR]".format( CONFIG.COLOR2))
def remove_addon_menu(): from resources.libs.common import logging from resources.libs.common import tools from resources.libs import update from xml.etree import ElementTree dialog = xbmcgui.Dialog() addonfolders = glob.iglob(os.path.join(CONFIG.ADDONS, '*/')) addonnames = [] addonids = [] for folder in addonfolders: foldername = os.path.split(folder[:-1])[1] if foldername in CONFIG.EXCLUDES: continue elif foldername in CONFIG.DEFAULTPLUGINS: continue elif foldername == 'packages': continue xml = os.path.join(folder, 'addon.xml') if os.path.exists(xml): root = ElementTree.parse(xml).getroot() addonid = root.get('id') addonname = root.get('name') try: addonnames.append(addonname) addonids.append(addonid) except: pass if len(addonnames) == 0: logging.log_notify(CONFIG.ADDONTITLE, "[COLOR {0}]No hay complementos para eliminar[/COLOR]".format(CONFIG.COLOR2)) return selected = dialog.multiselect("{0}: Seleccione los complementos que desea eliminar.".format(CONFIG.ADDONTITLE), addonnames) if not selected: return if len(selected) > 0: update.addon_updates('set') for addon in selected: remove_addon(addon=addonids[addon], name=addonnames[addon], over=True) xbmc.sleep(500) dialog.ok(CONFIG.ADDONTITLE, "[COLOR {0}]Para guardar los cambios, ahora necesita forzar el cierre de Kodi, presione OK para forzar el cierre de Kodi[/COLOR]".format(CONFIG.COLOR2)) update.addon_updates('reset') tools.kill_kodi(over=True)
def remove_addon_menu(): from resources.libs.common import logging from resources.libs.common import tools from resources.libs import update from xml.etree import ElementTree dialog = xbmcgui.Dialog() addonfolders = glob.iglob(os.path.join(CONFIG.ADDONS, '*/')) addonnames = [] addonids = [] for folder in addonfolders: foldername = os.path.split(folder[:-1])[1] if foldername in CONFIG.EXCLUDES: continue elif foldername in CONFIG.DEFAULTPLUGINS: continue elif foldername == 'packages': continue xml = os.path.join(folder, 'addon.xml') if os.path.exists(xml): root = ElementTree.parse(xml).getroot() addonid = root.get('id') addonname = root.get('name') try: addonnames.append(addonname) addonids.append(addonid) except: pass if len(addonnames) == 0: logging.log_notify(CONFIG.ADDONTITLE, "[COLOR {0}]No Addons To Remove[/COLOR]".format(CONFIG.COLOR2)) return selected = dialog.multiselect("{0}: Select the addons you wish to remove.".format(CONFIG.ADDONTITLE), addonnames) if not selected: return if len(selected) > 0: update.addon_updates('set') for addon in selected: remove_addon(addon=addonids[addon], name=addonnames[addon], over=True) xbmc.sleep(500) dialog.ok(CONFIG.ADDONTITLE, "[COLOR {0}]To save changes you now need to force close Kodi, Press OK to force close Kodi[/COLOR]".format(CONFIG.COLOR2)) update.addon_updates('reset') tools.kill_kodi(over=True)
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) + "\n" + "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, '')) + '\n' + "[COLOR {0}]{1}[/COLOR]".format(CONFIG.COLOR1, file) + '\n' + "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))
def switch_to_skin(goto, title="Error"): from resources.libs.common import logging result = _swap_skins(goto) if result: logging.log('[COLOR {0}]{1}: Skin Swap Success![/COLOR]'.format(CONFIG.COLOR2, title)) else: logging.log_notify(CONFIG.ADDONTITLE, '[COLOR {0}]{1}: Skin Swap Failed![/COLOR]'.format(CONFIG.COLOR2, title)) return result
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}]Mudando os caminhos físicos para especiais".format( CONFIG.COLOR2) + "\n" + "Por favor, aguarde[/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}]Varrendo: [COLOR {1}]{2}[/COLOR]".format( CONFIG.COLOR2, CONFIG.COLOR1, root.replace(CONFIG.HOME, '')) + '\n' + "[COLOR {0}]{1}[/COLOR]".format(CONFIG.COLOR1, file) + '\n' + "Por favor, aguarde[/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( 'Incapaz de abrir o arquivo para converter caminhos especiais: {}' .format(os.path.join(root, file))) if progress_dialog.iscanceled(): progress_dialog.close() logging.log_notify( CONFIG.ADDONTITLE, "[COLOR {0}]Converter caminho cancelado[/COLOR]". format(CONFIG.COLOR2)) sys.exit() progress_dialog.close() logging.log("[Converter caminhos em especiais] Completo") if not over: logging.log_notify( CONFIG.ADDONTITLE, "[COLOR {0}]Converter caminhos em especiais: Completo![/COLOR]". format(CONFIG.COLOR2))