def startup_rejuv(): yes_pressed = kodi.yesnoDialog(AddonTitle, "Please confirm that you wish you wipe clean your current configuration" "and reconfigure Kodi with the latest Config Wizard update!", " This will result in the loss of all your current data!") if yes_pressed: addonPath = AddonID.getAddonInfo('path') addonPath = xbmc.translatePath(addonPath) xbmcPath = os.path.join(addonPath, "..", "..") xbmcPath = os.path.abspath(xbmcPath) # Directories and sub directories not to remove but to sort through dir_exclude = ('addons', 'packages', 'userdata', 'Database') # Directories and sub directories Directories to ignore and leave intact sub_dir_exclude = ['metadata.album.universal', 'metadata.artists.universal', 'service.xbmc.versioncheck', 'metadata.common.musicbrainz.org', 'metadata.common.imdb.com', AddonID] # Files to ignore and not to be removed file_exclude = ('Addons26.db', 'kodi.log', 'Textures13.db, Addons27.db') try: for (root, dirs, files) in os.walk(xbmcPath, topdown=True): dirs[:] = [dir for dir in dirs if dir not in sub_dir_exclude] files[:] = [file for file in files if file not in file_exclude] for folder in dirs: if folder not in dir_exclude: shutil.rmtree(os.path.join(root, folder)) for file_name in files: os.remove(os.path.join(root, file_name)) except Exception as e: kodi.log("Rejuv.startup_rejuv User files partially removed - " + str(e)) rejuv_run.JUVWIZARD()
def cleanse_title(text): def fixup(m): text = m.group(0) if text[:2] == "&#": # character reference try: if text[:3] == "&#x": return chr(int(text[3:-1], 16)) # unichr(int(text[3:-1], 16)) else: return chr(int(text[2:-1])) # unichr(int(text[2:-1])) except ValueError: pass else: # named entity try: # text = unichr(htmlentitydefs.name2codepoint[text[1:-1]]) text = chr(htmlentitydefs.name2codepoint[text[1:-1]]) except KeyError: pass # replace nbsp with a space text = text.replace(u'\xa0', u' ') return text if isinstance(text, str): try: text = text.decode('utf-8') except Exception as e: kodi.log(str(e)) return re.sub("&#?\w+;", fixup, text.strip())
def archive_cb(sourcefile, message_header, message1, message2, message3, exclude_dirs, exclude_files): check_path() # ##TODO check for file. Prompt to pick another name or replace the existing file if not os.path.exists(zip_path): os.makedirs(zip_path) vq = get_keyboard(heading="Enter a name for this backup") if not vq: return False, 0 # ## title = urllib.quote_plus(vq) destfile = xbmc.translatePath(os.path.join(zip_path, title + '.zip')) zipobj = zipfile.ZipFile(destfile, 'w', zipfile.ZIP_DEFLATED) rootlen = len(sourcefile) for_progress = [] item = [] dp.create(message_header, message1, message2, message3) for base, dirs, files in os.walk(sourcefile): for n_file in files: item.append(n_file) n_item = len(item) for base, dirs, files in os.walk(sourcefile): dirs[:] = [d for d in dirs if d not in exclude_dirs] files[:] = [f for f in files if f not in exclude_files] for file_n in files: try: for_progress.append(file_n) progress = len(for_progress) / float(n_item) * 100 dp.update(int(progress), "Archiving..", '[COLOR blue]%s[/COLOR]' % file_n, '') fp = os.path.join(base, file_n) zipobj.write(fp, fp[rootlen:]) except Exception, e: kodi.log(str(e))
def HUBINSTALL(name, url, script): aList = [] script_url = url link = OPEN_URL(script_url) matcher = script + '-(.+?).zip' match = re.compile(matcher).findall(link) for version in match: aList.append(version) aList.sort(cmp=ver_cmp, reverse=True) newest_v = script + '-' + aList[0] newest_v_url = script_url + script + '-' + aList[0] + '.zip' kodi.log("Looking for : " + newest_v_url) path = xbmc.translatePath(os.path.join('special://home', 'addons', 'packages')) dp = xbmcgui.DialogProgress() dp.create("Starting up", "Initializing ", '', 'Please Stand By....') # lib = os.path.join(path, name + '.zip') lib = os.path.join(path, newest_v + '.zip') addonfolder = xbmc.translatePath(os.path.join('special://', 'home', 'addons')) if os.path.exists(lib): os.remove(lib) downloader.download(newest_v_url, lib, dp, timeout=120) try: # xbmc.executebuiltin("InstallAddon(%s)" % newest_v) extract.all(lib, addonfolder, '') time.sleep(2) except IOError, (errno, strerror): kodi.message("Failed to open required files", "Error code is:", strerror) return False
def download(url, addon_id, destination, unzip=False, quiet=False): version = None filename = addon_id + '.zip' r = requests.get(url, stream=True) kodi.log("Download: %s" % url) if r.status_code == requests.codes.ok: temp_file = kodi.vfs.join(kodi.get_profile(), "downloads") if not kodi.vfs.exists(temp_file): kodi.vfs.mkdir(temp_file, recursive=True) temp_file = kodi.vfs.join(temp_file, filename) try: total_bytes = int(r.headers["Content-Length"]) except: total_bytes = 0 block_size = 1000 cached_bytes = 0 if not quiet: pb = xbmcgui.DialogProgress() pb.create("Downloading",filename,' ', ' ') kodi.sleep(150) start = time.time() with open(temp_file, 'wb') as f: for block in r.iter_content(chunk_size=block_size): if not block: break if not quiet and pb.iscanceled(): raise downloaderException('Download Aborted') return False cached_bytes += len(block) f.write(block) if total_bytes > 0: delta = int(time.time() - start) if delta: bs = int(cached_bytes / (delta)) else: bs = 0 if not quiet: percent = int(cached_bytes * 100 / total_bytes) pb.update(percent, "Downloading",filename, format_status(cached_bytes, total_bytes, bs)) if not quiet: pb.close() if unzip: zip_ref = zipfile.ZipFile(temp_file, 'r') zip_ref.extractall(destination) zip_ref.close() kodi.vfs.rm(temp_file, quiet=True) try: xml = kodi.vfs.read_file(kodi.vfs.join(destination, kodi.vfs.join(addon_id, 'addon.xml')), soup=True) version = get_version_by_xml(xml) if not version: version = get_version_by_name(filename) except: kodi.log("Unable to fine version from addon.xml for addon: %s" % addon_id) else: kodi.vfs.mv(temp_file, kodi.vfs.join(destination, filename)) else: kodi.close_busy_dialog() raise downloaderException(r.status_code) return version
def service_checks(): import maintool maintool.source_change() date = datetime.datetime.today().weekday() if (kodi.get_setting("clearday") == date) or kodi.get_setting("acstartup") == "true": maintool.auto_clean(True) elif (kodi.get_setting("clearday") == 0) and kodi.get_setting("acstartup") != "true": kodi.log('Auto Main Turned off')
def user_resolver(user, unmet): dep_url, dep_filename, dep_full_name, version = github_api.find_zip(user, unmet) if dep_url: kodi.log("%s found in %s repo" % (unmet, user)) self.met_addons.append(unmet) user, repo = dep_full_name.split("/") self.sources[unmet] = {"type": SOURCES.ZIP, "url": dep_url, "user": user, "repo": repo, "version": ""} kodi.log("%s dependency met in %s" % (unmet, dep_url)) return True return False
def setall_enable(): if kodi.get_kversion() > 16.5: addonfolder = xbmc.translatePath(os.path.join('special://home', 'addons')) contents = os.listdir(addonfolder) kodi.log(contents) conn.executemany('update installed set enabled=1 WHERE addonID = (?)', ((val,) for val in contents)) conn.commit() else: pass
def startup_freshstart(): if kodi.yesnoDialog("Please confirm that you wish to factory restore your configuration.", " This will result in the loss of all your current data!", ' ', AddonTitle, nolabel='No', yeslabel='Yes'): home_path = xbmc.translatePath(os.path.join('special://home')) enableBG16 = "UseCustomBackground,false" enableBG17 = "use_custom_bg,false" xEB('Skin.SetBool(%s)' % enableBG16) xEB('Skin.SetBool(%s)' % enableBG17) try: win_string = xbmc.translatePath(os.path.join('special://xbmc/')).split('\\')[-2] win_string = win_string.split('_') win_string = win_string[0] + '_' + win_string[-1] kodi.log(win_string) win_path = home_path.replace('\Roaming\Kodi', '\Local\Packages\%s\LocalCache\Roaming\Kodi' % win_string) if win_path: home_path = win_path except: pass # Directories and sub directories not to remove but to sort through dir_exclude = ('addons', 'packages', 'userdata', 'Database') # Directories and sub directories Directories to ignore and leave intact sub_dir_exclude = ['metadata.album.universal', 'metadata.artists.universal', 'service.xbmc.versioncheck', 'metadata.common.musicbrainz.org', 'metadata.common.imdb.com'] if kodi.yesnoDialog(AddonTitle, "Do you wish to keep %s installed for convenience after the factory restore?" % AddonTitle, '', nolabel='No', yeslabel='Yes'): sub_dir_exclude.extend([AddonID]) # Files to ignore and not to be removed file_exclude = ('kodi.log') # , 'Textures13.db', 'commoncache.db', 'Addons26.db', 'Addons27.db') # db_vers = max(re.findall('Addons\d+.db', str(os.listdir(xbmc.translatePath('special://database'))))) # file_exclude += db_vers try: for (root, dirs, files) in os.walk(home_path, topdown=True): dirs[:] = [dir for dir in dirs if dir not in sub_dir_exclude] files[:] = [file for file in files if file not in file_exclude] for folder in dirs: try: if folder not in dir_exclude: shutil.rmtree(os.path.join(root, folder)) except: pass for file_name in files: try: os.remove(os.path.join(root, file_name)) except: pass kodi.message(AddonTitle, "Done! , You are now back to a fresh Kodi configuration!", "Click OK to exit Kodi and then restart to complete .") xbmc.executebuiltin('ShutDown') except Exception as e: kodi.log("Freshstart User files partially removed - " + str(e)) kodi.message(AddonTitle, 'Done! , Freshstart User files partially removed', 'Please check the log')
def purge_packages(): kodi.log('STARTUP PURGE PACKAGES ACTIVATED') packages_path = xbmc.translatePath(os.path.join('special://home/addons/packages', '')) try: for root, dirs, files in os.walk(packages_path, topdown=False): for name in files: os.remove(os.path.join(root, name)) # kodi.log('Packages Wiped by Service') # dialog = xbmcgui.Dialog() # dialog.ok(AddonTitle, " Packages Folder Wiped Successfully!") except: kodi.log('Startup Service could not purge packages')
def get_kodi_size(sys_space): try: space = xbmc.getInfoLabel(sys_space) try: space = revert_size(space) except Exception as e: kodi.log(str(e)) traceback.print_exc(file=sys.stdout) except Exception as e: kodi.log(str(e)) traceback.print_exc(file=sys.stdout) space = 0 return space
def feed_change(): new_feed = userdata_path + "/RssFeeds.xml" try: with open(new_feed) as fi: a = fi.read() if 'TVADDONS' in a: b = a.replace('TVADDONS', 'TVADDONSCO') else: return with open(new_feed, "w") as fil: fil.write(str(b)) except Exception as e: kodi.log(str(e))
def convert_size(size): err_defaults = (0, 'Unavailable', 'None', '0B', '0M', '0 MB Free', '0 MB Total', '0M Free', '0M Total') if size in err_defaults: return '0 B' import math labels = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") try: i = int(math.floor(math.log(int(size), 1000))) except Exception as e: kodi.log(str(e)) i = int(0) s = round(int(size) / math.pow(1000, i), 2) return '%s %s' % (str(s), labels[i])
def scriptblock_checks(): if kodi.get_setting('scriptblock') == 'true': kodi.log('SCRIPT BLOCKER ON') try: req = urllib2.Request(BlocksUrl) req.add_header('User-Agent', 'Mozilla/5.0 (Linux; U; Android 4.2.2; en-us; AFTB Build/JDQ39) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30') response = urllib2.urlopen(req) except: kodi.log('Could not perform blocked script check. invalid URL') return link = response.read() response.close() link = link.replace('\n', '').replace('\r', '').replace('\a', '') match = re.compile('block="(.+?)"').findall(link) for blocked in match: kodi.log('Checking for Malicious scripts') addonPath = xbmcaddon.Addon(id=addon_id).getAddonInfo('path') addonPath = xbmc.translatePath(addonPath) xbmcPath = os.path.join(addonPath, "..", "..") xbmcPath = os.path.abspath(xbmcPath); addonpath = xbmcPath + '/addons/' try: for root, dirs, files in os.walk(addonpath, topdown=False): if root != addonpath: if blocked in root: shutil.rmtree(root) except: kodi.log('Could not find blocked script')
def github_resolver(unmet): results = github_api.web_search(unmet) c = kodi.dialog_select("GitHub Search Results for %s" % unmet, [r['full_name'] for r in results['items']]) if c is not False: dep = results['items'][c] dep_url = url = "https://github.com/%s/archive/master.zip" % (dep['full_name']) self.met_addons.append(unmet) dep_filename = "%s.zip" % unmet self.sources[unmet] = {"type": SOURCES.REPO, "url": dep_url, "user": user, "repo": repo, "version": ""} kodi.log("%s dependency met in %s" % (unmet, dep_url)) self.install_addon(unmet, dep_url, dep['full_name'], master=True) return True return False
def remove_paths(path): try: for root, dirs, files in os.walk(path, topdown=True): dirs[:] = [d for d in dirs if d not in excludes_folder] for name in files: try: os.unlink(os.path.join(root, name)) except Exception, e: kodi.log(str(e)) for name in dirs: try: os.rmdir(os.path.join(root, name)) os.rmdir(root) except Exception, e: kodi.log(str(e))
def source_change(): new_source = userdata_path + "/sources.xml" try: with open(new_source) as fi: a = fi.read() if 'fusion.tvaddons.ag' in a: b = a.replace('http://www.fusion.tvaddons.ag', 'http://fusion.tvaddons.co') elif 'https://code.sourcecode.ag' in a: b = a.replace('https://code.sourcecode.ag', 'http://fusion.tvaddons.co') else: return with open(new_source, "w") as fil: fil.write(str(b)) except Exception as e: kodi.log(str(e))
def keymaps(): try: link = OPEN_URL(Keymaps_URL).replace('\n', '').replace('\r', '') except: kodi.addDir("No Keymaps Available", '', '', artwork + 'unkeymap.png') kodi.log('Could not open keymaps URL') return match = re.compile('name="(.+?)".+?rl="(.+?)".+?mg="(.+?)".+?anart="(.+?)".+?ersion="(.+?)".+?ash="(.+?)"').findall( link) if os.path.isfile(KEYBOARD_FILE): kodi.addDir("Remove Current Keymap Configuration", '', 'uninstall_keymap', artwork + 'unkeymap.png') for name, url, iconimage, fanart, version, description in match: kodi.addDir(name, url, 'install_keymap', artwork + 'keymapadd.png') name = "[COLOR white][B]" + name + "[/B][/COLOR]" viewsetter.set_view("files")
def set_enabled(newaddon, data=None): if kodi.get_kversion() > 16.5: kodi.log("Enabling " + newaddon) setit = 1 if data is None: data = '' now = datetime.datetime.now() date_time = str(now).split('.')[0] # sql = 'REPLACE INTO installed (addonID,enabled) VALUES(?,?)' sql = 'REPLACE INTO installed (addonID,enabled,installDate) VALUES(?,?,?)' conn.execute(sql, (newaddon, setit, date_time,)) conn.commit() # xbmc.executebuiltin("InstallAddon(%s)" % newaddon) # xbmc.executebuiltin("XBMC.UpdateLocalAddons()") else: pass
def rtmp_lib(): liblist = "http://indigo.tvaddons.co/librtmp/rtmplist.txt" try: # link = OPEN_URL(liblist).replace('\n', '').replace('\r', '') link = kodi.read_file(liblist).replace('\n', '').replace('\r', '') except Exception as e: kodi.log(str(e)) kodi.addItem('[COLOR gold][B]This service is currently unavailable.[/COLOR][/B]', '', 100, '', '', '') return match = re.compile('name="(.+?)".+?rl="(.+?)".+?ersion="(.+?)"').findall(link) kodi.addItem('[COLOR gold][B]Files Will Be Donwloaded to the Kodi Home directory,' 'You Will Need To Manually Install From There.[/COLOR][/B]', '', 100, '', '', '') # kodi.addItem('[COLOR gold]---------------------------------------------------------[/COLOR]', '', 100, '',' ', '') for m_name, m_url, m_description in match: kodi.addDir(m_name, m_url, "lib_installer", artwork + 'icon.png') viewsetter.set_view("sets")
def clear_cache(): kodi.log('STARTUP CLEAR CACHE ACTIVATED') xbmc_cache_path = os.path.join(xbmc.translatePath('special://home'), 'cache') if os.path.exists(xbmc_cache_path) == True: for root, dirs, files in os.walk(xbmc_cache_path): file_count = 0 file_count += len(files) if file_count > 0: for f in files: try: os.unlink(os.path.join(root, f)) except: pass for d in dirs: if 'archive_cache' not in d: try: shutil.rmtree(os.path.join(root, d)) except: pass kodi.log('Startup Service could not clear cache')
def download(url, dest, dp = None,timeout = None): if timeout == None: timeout = 120 try: if not dp: dp = xbmcgui.DialogProgress() dp.create("Status...","Checking Installation",' ', ' ') dp.update(0) start_time = time.time() u = urllib2.urlopen(url, timeout = timeout) h = u.info() totalSize = int(h["Content-Length"]) fp = open(dest, 'wb') blockSize = 8192 #100000 # urllib.urlretrieve uses 8192 count = 0 while True: # and (end - start < 15): if time.time() - start_time > timeout: kodi.message("Slow or no Download available:", 'Files could not be downloaded at this time', 'Please try again later, Attempting to continue...') break chunk = u.read(blockSize) if not chunk: break fp.write(chunk) count += 1 if totalSize > 0: try: percent = int(count * blockSize * 100 / totalSize) dp.update(percent) except: percent = 100 dp.update(percent) if dp.iscanceled(): dp.close() raise Exception("Canceled") timetaken = time.time() - start_time kodi.log('Duration of download was %.02f secs ' % timetaken ) except socket.timeout, e: # For Python 2.7 kodi.message("There was an error: %r" % e, 'Files could not be downloaded at this time', 'Please try again later, Attempting to continue...') return
def fullspeedtest(): # speed_test = base64.b64decode("aHR0cDovL2luZGlnby50dmFkZG9ucy5hZy9zcGVlZHRlc3Qvc3BlZWR0ZXN0ZmlsZS50eHQ=") speed_test = 'http://www.engineerhammad.com/2015/04/Download-Test-Files.html' try: # link = OPEN_URL(speed_test) link = kodi.read_file(speed_test) match = re.findall('href="([^"]*)".+src="([^"]*)".+\n.+?(\d+\s[^b]*b)', link) for m_url, m_iconimage, m_name in reversed(match): m_iconimage = artwork + str(m_name).replace(' ', '').lower() + '.png' if 'mb'in m_iconimage and not os.path.isfile(m_iconimage): m_iconimage = m_iconimage.replace('mb', '') kodi.addItem('[COLOR ghostwhite]' + m_name + '[/COLOR]', m_url, "runtest", m_iconimage, description='Test with a ' + m_name + ' file') except Exception as e: kodi.log(str(e)) import traceback traceback.print_exc(file=sys.stdout) kodi.addItem('[COLOR ghostwhite]Speed Test is unavailable[/COLOR]', '', "", artwork + 'speed_test.png', description='') viewsetter.set_view("sets")
def wipe_addons(): # kodi.logInfo('WIPE ADDONS ACTIVATED') if xbmcgui.Dialog().yesno("Please Confirm", " Please confirm that you wish to uninstall", " all addons from your device!", " ", nolabel='Cancel', yeslabel='Uninstall'): try: for root, dirs, files in os.walk(addons_path, topdown=False): if root != addons_path: if addon_id not in root: if 'metadata.album.universal' not in root: if 'metadata.artists.universal' not in root: if 'service.xbmc.versioncheck' not in root: if 'metadata.common.musicbrainz.org' not in root: shutil.rmtree(root) xbmcgui.Dialog().ok(AddonName, "Addons Wiped Successfully!", "Click OK to exit Kodi and then restart to complete.") xbmc.executebuiltin('ShutDown') except Exception as e: kodi.log(str(e)) xbmcgui.Dialog().ok(AddonName, "Error Wiping Addons please visit TVADDONS.CO forums")
def startup_rejuv(): if kodi.yesnoDialog("Please confirm that you wish you wipe clean your current configuration" "and reconfigure Kodi with the latest Config Wizard update!", " This will result in the loss of all your current data!", '',AddonTitle): addonPath = kodi.addon.getAddonInfo('path') addonPath = xbmc.translatePath(addonPath) xbmcPath = os.path.join(addonPath, "..", "..") xbmcPath = os.path.abspath(xbmcPath) # Directories and sub directories not to remove but to sort through dir_exclude = ('addons', 'packages', 'userdata', 'Database', 'temp') # Directories and sub directories Directories to ignore and leave intact sub_dir_exclude = ['metadata.album.universal', 'metadata.artists.universal', 'service.xbmc.versioncheck', 'metadata.common.musicbrainz.org', 'metadata.common.imdb.com', AddonID] # if kodi.yesnoDialog(AddonTitle, "Do you wish to keep %s installed for convenience after the factory restore?" # % AddonTitle, '', nolabel='No', yeslabel='Yes'): # sub_dir_exclude.extend([AddonID]) # Files to ignore and not to be removed file_exclude = ('kodi.log') # , 'Textures13.db','Addons26.db', 'Addons27.db') db_vers = max(re.findall('Addons\d+.db', str(os.listdir(xbmc.translatePath('special://database'))))) file_exclude += db_vers try: for (root, dirs, files) in os.walk(xbmcPath, topdown=True): dirs[:] = [dir for dir in dirs if dir not in sub_dir_exclude] files[:] = [file for file in files if file not in file_exclude] for folder in dirs: if folder not in dir_exclude: try: shutil.rmtree(os.path.join(root, folder)) except: pass for file_name in files: try: os.remove(os.path.join(root, file_name)) except: pass except Exception as e: kodi.log("Rejuv.startup_rejuv User files partially removed - " + str(e)) rejuv_run.JUVWIZARD()
def toggle_setting(setting_title, setting, restart=False, silent=False): # kodi.log('TOGGLE SETTING') if not silent: if kodi.get_setting(setting) == "true": status_on_off = 'OFF' else: status_on_off = 'ON' if not xbmcgui.Dialog().yesno(setting_title, 'Please confirm that you wish to TURN %s %s' % (status_on_off, setting_title), '', '', 'Cancel', 'Confirm'): return if kodi.get_setting(setting) == 'true': kodi.set_setting(setting, 'false') else: kodi.set_setting(setting, 'true') kodi.log('Toggled setting for ' + setting_title) if not silent and not restart: xbmcgui.Dialog().notification('', 'Setting Changed!', sound=False) xbmc.executebuiltin("Container.Refresh") if restart: xbmcgui.Dialog().notification('', 'Kodi is shutting down for changes to take effect', sound=False) xbmc.executebuiltin('ShutDown')
def start(self): enable_updates class Monitor(xbmc.Monitor): def onSettingsChanged(self): global enable_updates enable_updates = kodi.get_setting('enable_updates') == 'true' monitor = Monitor() kodi.log("Service Starting...") if is_depricated: while not xbmc.abortRequested: kodi.sleep(1000) self.update() else: while not monitor.abortRequested(): if monitor.waitForAbort(10): break self.update() self.shutdown()
def get_free_space_mb(dirname): try: if xbmc.getCondVisibility('system.platform.windows'): import ctypes total_bytes = ctypes.c_int64() free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, ctypes.pointer(total_bytes), ctypes.pointer(free_bytes)) if free_bytes.value != '0 MB Free': return free_bytes.value, total_bytes.value else: import subprocess df = subprocess.Popen(['df', dirname], stdout=subprocess.PIPE) output = df.communicate()[0].encode('utf-8').split('\n')[1].split() try: return int(output[3]) * 1024, int(output[1]) * 1024 except Exception as e: kodi.log(str(e)) return revert_size(output[3]), revert_size(output[1]) except Exception as e: kodi.log(str(e)) traceback.print_exc(file=sys.stdout) return get_kodi_size('System.FreeSpace'), get_kodi_size('System.TotalSpace')
def auto_clean(auto_clear=False): if not auto_clear: if not xbmcgui.Dialog().yesno(AddonName, 'Selecting Yes runs maintenance based on your settings.', 'Do you wish to continue?', yeslabel='Yes', nolabel='No'): return available_space, total_space = get_free_space_mb(xbmc.translatePath('special://home')) err_default = (0, '0 B', '0M', '0 MB', '0 MB Free', '0 MB Total', '0M Free', '0M Total') if str(available_space) in err_default or str(total_space) in err_default: if not auto_clear: if xbmcgui.Dialog().yesno('Auto Maintenance Error', 'Auto Maintenance encountered a problem and was not ran', 'Maintenace can still be done now or individually', 'Would you like to just clear the cache, packages, and thumbnails', yeslabel='Yes', nolabel='No'): delete_cache(auto_clear=True) delete_packages(auto_clear=True) delete_thumbnails(auto_clear=True) delete_crash_logs(auto_clear=True) xbmc.executebuiltin("Container.Refresh") xbmcgui.Dialog().ok(AddonName, 'Auto Maintenance has been run successfully') return mb_settings = (0, 25, 50, 75, 100) for value in ('cachemb', 'thumbsmb', 'packagesmb'): available_space += mb_settings[int(kodi.get_setting(value))] * 10**6 automb = kodi.get_setting("automb") cachemb = float((mb_settings[int(kodi.get_setting("cachemb"))]) * 10**6) # 35% for path in (cache_path, temp_path): if os.path.exists(path): try: if (automb and (cachemb >= float(available_space) * .35)) or \ ((cachemb == 0 and kodi.get_setting("accache") == 'true') or (cachemb != 0 and (get_size(cache_path) >= int(cachemb)))): delete_cache(auto_clear=True) except Exception as e: kodi.log(str(e)) thumbsmb = float((mb_settings[int(kodi.get_setting("thumbsmb"))]) * 10**6) # 35% try: if (automb and (thumbsmb >= int(available_space) * .35)) or \ ((thumbsmb == 0 and kodi.get_setting("acthumbs") == 'true') or (thumbsmb != 0 and (get_size(thumbnail_path) >= int(thumbsmb)))): delete_thumbnails(auto_clear=True) except Exception as e: kodi.log(str(e)) packagesmb = float((mb_settings[int(kodi.get_setting("packagesmb"))]) * 10**6) # 10% try: if (automb and (packagesmb >= int(available_space) * .10)) or \ ((packagesmb == 0 and kodi.get_setting("acpackages") == 'true') or (packagesmb != 0 and (get_size(packages_path) >= int(packagesmb)))): delete_packages(auto_clear=True) except Exception as e: kodi.log(str(e)) if kodi.get_setting("accrash") == 'true': delete_crash_logs(auto_clear=True) if not auto_clear: xbmc.executebuiltin("Container.Refresh") xbmcgui.Dialog().ok(AddonName, 'Auto Maintenance has been run successfully')
def apply_urlresolver(hosters): filter_debrid = kodi.get_setting('filter_debrid') == 'true' show_debrid = kodi.get_setting('show_debrid') == 'true' if not filter_debrid and not show_debrid: print "RETURNING NON FILTERED" return hosters ## New Resolver try: import urlresolver.plugnplay resolvers = urlresolver.plugnplay.man.implementors(urlresolver.UrlResolver) debrid_resolvers = [resolver for resolver in resolvers if resolver.isUniversal() and resolver.get_setting('enabled') == 'true'] except: import urlresolver debrid_resolvers = [resolver() for resolver in urlresolver.relevant_resolvers(order_matters=True) if resolver.isUniversal()] ## End New Resolver filtered_hosters = [] debrid_hosts = {} unk_hosts = {} known_hosts = {} for hoster in hosters: if 'direct' in hoster and hoster['direct'] == False and hoster['host']: host = hoster['host'] host = (host.lower()) # if kodi.get_setting('filter_debrid')=='true': if host in unk_hosts: unk_hosts[host] += 1 continue elif host in known_hosts: known_hosts[host] += 1 filtered_hosters.append(hoster) else: hmf = urlresolver.HostedMediaFile(host=host, media_id='dummy') # use dummy media_id to force host validation if hmf: known_hosts[host] = known_hosts.get(host, 0) + 1 filtered_hosters.append(hoster) else: unk_hosts[host] = unk_hosts.get(host, 0) + 1 continue else: filtered_hosters.append(hoster) if host in debrid_hosts: log_utils.log('Debrid cache found for %s: %s' % (host, debrid_hosts[host]), log_utils.LOGDEBUG) hoster['debrid'] = debrid_hosts[host] else: temp_resolvers = [] for resolver in debrid_resolvers: if resolver.valid_url('', host): rname= resolver.name.replace('Real-Debrid','RD').replace('Premiumize.me','PRE') temp_resolvers.append(rname.upper()) if kodi.get_setting('debug') == "true": print '%s supported by: %s' % (host, temp_resolvers) debrid_hosts[host] = temp_resolvers else: hoster['debrid'] = '' if temp_resolvers: hoster['debrid'] = temp_resolvers else: filtered_hosters.append(hoster) if kodi.get_setting('debug') == "true": kodi.log( "FILTERED HOSTERS ARE =" +str(filtered_hosters)) return filtered_hosters
import xbmc,xbmcgui,time,os,shutil,re,urllib2 from libs import kodi import support import xbmcaddon import common as Common import base64 import maintool import plugintools addon_id=kodi.addon_id kodi.log('STARTING COMPUTERTECHS INSTALLER SERVICE') ############################ addonPath=xbmcaddon.Addon(id=addon_id).getAddonInfo('path') addonPath=xbmc.translatePath(addonPath) xbmcPath=os.path.join(addonPath,"..","..") xbmcPath=os.path.abspath(xbmcPath) AddonTitle = 'Indigo' addonpath = xbmcPath+'/addons/' mediapath = xbmcPath+'/media/' systempath = xbmcPath+'/system/' userdatapath = xbmcPath+'/userdata/' indisettingspath = xbmcPath+'/userdata/addon_data/plugin.video.nukewizard/settings.xml' packagepath = xbmcPath+ '/addons/packages/' ############################## ############################## oldinstaller =xbmc.translatePath(os.path.join('special://home','addons','plugin.program.addoninstaller')) oldnotify = xbmc.translatePath(os.path.join('special://home','addons','plugin.program.xbmchub.notifications')) oldmain = xbmc.translatePath(os.path.join('special://home','addons','plugin.video.xbmchubmaintool')) oldwiz = xbmc.translatePath(os.path.join('special://home','addons','plugin.video.hubwizard')) oldfresh = xbmc.translatePath(os.path.join('special://home','addons','plugin.video.freshstart'))
def system_info(): systime = xbmc.getInfoLabel('System.Time ') dns1 = xbmc.getInfoLabel('Network.DNS1Address') gateway = xbmc.getInfoLabel('Network.GatewayAddress') ipaddy = xbmc.getInfoLabel('Network.IPAddress') linkstate = xbmc.getInfoLabel('Network.LinkState').replace("Link:", "") freespace, totalspace = maintool.get_free_space_mb( os.path.join(xbmc.translatePath('special://home'))) freespace = maintool.convert_size(freespace) totalspace = maintool.convert_size(totalspace) screenres = xbmc.getInfoLabel('system.screenresolution') freemem = maintool.convert_size( maintool.revert_size(xbmc.getInfoLabel('System.FreeMemory'))) # FIND WHAT VERSION OF KODI IS RUNNING # xbmc_version = xbmc.getInfoLabel("System.BuildVersion") # versioni = xbmc_version[:4] # codename = kodi.get_codename() # Get External IP Address try: # ext_ip = ("blue", OPEN_URL('https://api.ipify.org')) ext_ip = ("blue", kodi.read_file('https://api.ipify.org')) except Exception as e: kodi.log(str(e)) try: # link = OPEN_URL('http://whatismyip.network/') link = kodi.read_file('http://whatismyip.network/') ext_ip = ("blue", re.search('>My IP Address[^=]*[^>]*>([^<]*)', link).group(1)) except: ext_ip = ("red", "IP Check Not Available") # Get Python Version pv = sys.version_info # System Information Menu # kodi.addItem('[COLOR ghostwhite]Version: [/COLOR][COLOR lime] %s %s[/COLOR]' % (codename, versioni), # '', 100, artwork + 'icon.png', "", description=" ") kodi.addItem( '[COLOR ghostwhite]Version: [/COLOR][COLOR lime] %s %s[/COLOR]' % (kodi.get_codename(), xbmc.getInfoLabel("System.BuildVersion").split('Git')[0]), '', 100, artwork + 'icon.png', "", description=" ") kodi.addItem( '[COLOR ghostwhite]System Time: [/COLOR][COLOR lime] %s[/COLOR]' % systime, '', 100, artwork + 'icon.png', "", description=" ") kodi.addItem('[COLOR ghostwhite]Gateway: [/COLOR][COLOR blue] %s[/COLOR]' % gateway, '', 100, artwork + 'icon.png', "", description=" ") kodi.addItem( '[COLOR ghostwhite]Local IP: [/COLOR][COLOR blue] %s[/COLOR]' % ipaddy, '', 100, artwork + 'icon.png', "", description=" ") kodi.addItem( '[COLOR ghostwhite]External IP: [/COLOR][COLOR %s] %s[/COLOR]' % ext_ip, '', 100, artwork + 'icon.png', "", description=" ") kodi.addItem('[COLOR ghostwhite]DNS 1: [/COLOR][COLOR blue] %s[/COLOR]' % dns1, '', 100, artwork + 'icon.png', "", description=" ") kodi.addItem('[COLOR ghostwhite]Network: [/COLOR][COLOR gold] %s[/COLOR]' % linkstate, '', 100, artwork + 'icon.png', "", description=" ") if str(totalspace) != '0 B': kodi.addItem( '[COLOR ghostwhite]Total Disc Space: [/COLOR][COLOR gold] %s[/COLOR]' % totalspace, '', 100, artwork + 'icon.png', "", description=" ") if str(freespace) != '0 B': kodi.addItem( '[COLOR ghostwhite]Free Disc Space: [/COLOR][COLOR gold] %s[/COLOR]' % freespace, '', 100, artwork + 'icon.png', "", description=" ") kodi.addItem( '[COLOR ghostwhite]Free Memory: [/COLOR][COLOR gold] %s[/COLOR]' % freemem, '', 100, artwork + 'icon.png', "", description=" ") kodi.addItem( '[COLOR ghostwhite]Resolution: [/COLOR][COLOR gold] %s[/COLOR]' % screenres, '', 100, artwork + 'icon.png', "", description=" ") kodi.addItem( '[COLOR ghostwhite]Python Version: [/COLOR][COLOR lime] %d.%d.%d[/COLOR]' % (pv[0], pv[1], pv[2]), '', 100, artwork + 'icon.png', "", description=" ") viewsetter.set_view("files")
def main_menu(): maintool.source_change() maintool.feed_change() # ########## TRY POP ######## if len(kodi.get_setting('notify')) > 0: kodi.set_setting('notify', str(int(kodi.get_setting('notify')) + 1)) else: kodi.set_setting('notify', "1") if int(kodi.get_setting('notify')) == 1: xbmcgui.Dialog().notification('Need Support?', 'www.tvaddons.co', artwork + 'icon.png', 3000, False) elif int(kodi.get_setting('notify')) == 5: kodi.set_setting('notify', "0") # ######## END POP ########### if kodi.get_setting('hasran') == 'false': kodi.set_setting('hasran', 'true') dp = xbmcgui.DialogProgress() try: if (not os.path.exists(ART)) or (not os.path.exists(ART2)) or ( not os.path.exists(ART3)): dp.create(AddonTitle, 'Getting ' + AddonTitle + ' Ready......', 'Downloading ' + AddonTitle + ' Icons.....') dp.update(0) icons_zip = os.path.join(packagepath, AddonTitle + '_icons.zip') downloader.download( kodi.read_file('http://indigo.tvaddons.co/graphics/arts.txt'), icons_zip, dp) # downloader.download(OPEN_URL('http://indigo.tvaddons.co/graphics/arts.txt'), icons_zip, dp) dp.update(0, 'Getting %s Ready........' % AddonTitle, 'Extracting %s Icons......' % AddonTitle) extract.all(icons_zip, addon_path, dp) dp.close() except Exception as e: kodi.log(str(e)) # Check for old version of hubrepo and remove it try: if os.path.exists(hubpath): with open(hubpath, 'r') as content: if 'AG' in content: shutil.rmtree(hubpath) except Exception as e: kodi.log(str(e)) # # Check for HUBRepo and install it try: if not os.path.exists(hubpath): installer.HUBINSTALL( 'repository.xbmchub', 'http://github.com/tvaddonsco/tva-release-repo/raw/master/' 'repository.xbmchub/', 'repository.xbmchub') # xbmc.executebuiltin("XBMC.InstallAddon(%s)" % 'repository.xbmchub') addon_able.set_enabled("repository.xbmchub") xbmc.executebuiltin("XBMC.UpdateAddonRepos()") except Exception as e: kodi.log(str(e)) import traceback traceback.print_exc(file=sys.stdout) raise # Check for Log Uploader and install it try: if not os.path.exists(uploaderpath): installer.HUBINSTALL( 'script.tvaddons.debug.log', 'http://github.com/tvaddonsco/tva-release-repo/raw/master' '/script.tvaddons.debug.log/', 'script.tvaddons.debug.log') addon_able.set_enabled('script.tvaddons.debug.log') # xbmc.executebuiltin("InstallAddon(%s)" % 'script.tvaddons.debug.log') xbmc.executebuiltin("XBMC.UpdateLocalAddons()") except Exception as e: kodi.log(str(e)) raise # Check for old maintenance tools and remove them old_maintenance = (oldinstaller, oldnotify, oldmain, oldwiz, oldfresh) for old_file in old_maintenance: if os.path.exists(old_file): shutil.rmtree(old_file) # Notification Status if kodi.get_setting("notifications-on-startup") == "false": note_status = '(Opt Out)' note_art = 'notification_optout.png' note_description = 'Unsubscribe' else: note_status = '(Opt In)' note_art = 'notification_in.png' note_description = 'Subscribe' if kodi.get_setting('wizardran') == 'false': kodi.addItem( "Config Wizard", '', 'call_wizard', artwork + 'config_wizard.png', description= "Automatically configure Kodi with the best addons and goodies in seconds!" ) kodi.addDir("Addon Installer", '', 'call_installer', artwork + 'addon_installer.png', description="It’s like an App Store for Kodi addons!") kodi.addDir( "Maintenance Tools", '', 'call_maintool', artwork + 'maintool.png', description="Keep your Kodi setup running at optimum performance!") # kodi.addDir("Kodi Librtmp Files", '', 'get_libs', artwork +'librtmp_files.png') kodi.addItem( "Rejuvenate Kodi", '', 'call_rejuv', artwork + 'rejuvinate.png', description= "Wipe and reconfigure Kodi with the latest Config Wizard setup!") kodi.addDir("Factory Restore", '', 'call_restore', artwork + 'factory_restore.png', description="Start off fresh, wipe your Kodi setup clean!") if os.path.exists(uploaderpath): kodi.addItem( "Log Uploader", '', 'log_upload', artwork + 'log_uploader.png', description="Easily upload your error logs for troubleshooting!") kodi.addDir("Network Speed Test", '', 'runspeedtest', artwork + 'speed_test.png', description="How fast is your internet?") kodi.addDir("System Information", '', 'system_info', artwork + 'system_info.png', description="Useful information about your Kodi setup!") kodi.addDir("Sports Listings", '', 'call_sports', artwork + 'sports_list.png', description="Who’s playing what today?") kodi.addDir( 'Backup / Restore', '', 'backup_restore', artwork + 'backup_restore.png', description="Backup or restore your Kodi configuration in minutes!") kodi.addItem( "Log Viewer", '', 'log_view', artwork + 'log_viewer.png', description="Easily view your error log without leaving Kodi!") kodi.addItem("No-Coin Scan", '', 'nocoin', artwork + 'no_coin.png', description="Scan your Kodi directory for coin mining.") kodi.addItem( "Notifications " + note_status, '', 'toggle_notify', artwork + note_art, description="%s to important TV ADDONS notifications on startup!" % note_description) kodi.addItem( "Show Notification", '', 'show_note', artwork + 'notification.png', description= "Show TVA Notification. To get Important News, Tips, and Giveaways from TV ADDONS" ) viewsetter.set_view("sets")
def new_depend(dataurl, script): kodi.log("SCRIPT LOOKED FOR IS : " + script) if "github" in dataurl: kodi.log("Is Github Repo") get_github(script, dataurl) else: kodi.log("Is Private Repo") try: link = kodi.open_url(tvpath) if script in link: script_url = tvpath + script + '/' version, orglist = get_url(script, script_url, link) kodi.log(' DOWNLOADING TVA FILE to ' + script + version + '.zip') depend_install(script, orglist) else: link = kodi.open_url(kodi_url) if script in link: script_url = kodi_url + script + '/' version, orglist = get_url(script, script_url, link) kodi.log(' DOWNLOADING Kodi FILE to ' + script + version + '.zip') depend_install(script, orglist) else: orglist = dataurl + script + '/' + script try: script_urls = dataurl + script + '/' link = kodi.open_url(script_urls) if not link: script_urls = script_urls.replace( "raw.", "").replace("/master/", "/tree/master/") link = kodi.open_url(script_urls) if link and "Invalid request" not in link: version, orglist = get_url(script, script_urls, link) orglist += version + '.zip' kodi.log(' DOWNLOADING NATIVE to ' + script + version + '.zip') depend_install(script, orglist) else: kodi.log("DEAD REPO LOCATION = " + dataurl) except Exception as e: kodi.log(str(e)) kodi.log("No local depend found = " + script + " Unfound URL is " + orglist) except Exception as e: kodi.log(str(e)) kodi.log("FAILED TO GET DEPENDS") traceback.print_exc(file=sys.stdout)
def shutdown(self): kodi.log("Service Stopping...")
import xbmc, xbmcgui import os, json #, sqlite3 import requests from libs import kodi # from datetime import datetime import installer addon_id = kodi.addon_id addon_name = kodi.addon.getAddonInfo('name') # KODI = xbmc.getInfoLabel('System.BuildVersion')[:2] #addon_py = xbmc.translatePath(os.path.join('special://home', 'addons', addon_id, 'addon.py')) kodi.log('STARTING ' + addon_name.upper() + ' SERVICE') # Get Current Version current = json.loads('{"config_version": "00000000"}') path = xbmc.translatePath(os.path.join('special://', 'userdata')) version_file = path + 'version.json' try: current = json.load(open(version_file)) except: pass # def getParams(): # params = { # 'd': kodi.getInfoLabel('Network.MacAddress'), # 'os': kodi.getInfoLabel('System.OSVersionInfo'), # 'id': kodi.get_setting('deviceid'), # 'kv': kodi.get_version()
import urllib2 import datetime from libs import kodi import xbmcaddon # import common as Common import notification import base64 import time from libs import addon_able import fileinput import sys addon_id = kodi.addon_id AddonTitle = kodi.addon.getAddonInfo('name') kodi.log('STARTING ' + AddonTitle + ' SERVICE') # ############################# oldinstaller = xbmc.translatePath( os.path.join('special://home', 'addons', 'plugin.program.addoninstaller')) oldnotify = xbmc.translatePath( os.path.join('special://home', 'addons', 'plugin.program.xbmchub.notifications')) oldmain = xbmc.translatePath( os.path.join('special://home', 'addons', 'plugin.video.xbmchubmaintool')) oldwiz = xbmc.translatePath( os.path.join('special://home', 'addons', 'plugin.video.hubwizard')) oldfresh = xbmc.translatePath( os.path.join('special://home', 'addons', 'plugin.video.freshstart')) oldmain2 = xbmc.translatePath( os.path.join('special://home', 'addons', 'plugin.video.hubmaintool'))
def startup_freshstart(): yes_pressed = kodi.yesnoDialog( AddonTitle, "Please confirm that you wish to factory restore your configuration.", " This will result in the loss of all your current data!" ) if yes_pressed: addonPath = xbmc.translatePath(os.path.join('special://home')) enableBG16 = "UseCustomBackground,false" enableBG17 = "use_custom_bg,false" xEB('Skin.SetBool(%s)' % enableBG16) xEB('Skin.SetBool(%s)' % enableBG17) try: winString = xbmc.translatePath( os.path.join('special://xbmc/')).split('\\')[-2] winString = winString.split('_') winString = winString[0] + '_' + winString[-1] kodi.log(winString) winPath = addonPath.replace( '\Roaming\Kodi', '\Local\Packages\%s\LocalCache\Roaming\Kodi') % winString if winPath: addonPath = winPath except: pass # Directories and sub directories not to remove but to sort through dir_exclude = ('addons', 'packages', 'userdata', 'Database') # Directories and sub directories Directories to ignore and leave intact sub_dir_exclude = ('metadata.album.universal', 'metadata.artists.universal', 'service.xbmc.versioncheck', 'metadata.common.musicbrainz.org', 'metadata.common.imdb.com') keep_indigo = kodi.yesnoDialog( AddonTitle, "Do you wish to keep Indigo installed for convenience after the factory restore?", " ") if keep_indigo: sub_dir_exclude = sub_dir_exclude + ('plugin.program.indigo', ) # Files to ignore and not to be removed file_exclude = ('Addons26.db', 'kodi.log', 'Textures13.db', 'commoncache.db, Addons27.db') try: for (root, dirs, files) in os.walk(addonPath, topdown=True): dirs[:] = [dir for dir in dirs if dir not in sub_dir_exclude] files[:] = [file for file in files if file not in file_exclude] for folder in dirs: try: if folder not in dir_exclude: shutil.rmtree(os.path.join(root, folder)) except: pass for file_name in files: try: os.remove(os.path.join(root, file_name)) except: pass kodi.message( AddonTitle, "Done! , You are now back to a fresh Kodi configuration!", "Click OK to exit Kodi and then restart to complete .") xbmc.executebuiltin('ShutDown') except Exception as e: kodi.log("Freshstart User files partially removed - " + str(e)) kodi.message(AddonTitle, 'Done! , Freshstart User files partially removed', 'Please check the log')
def read_zip(zip_name): if not dialog.yesno( AddonTitle, "[COLOR smokewhite]" + zip_name + "[/COLOR]", "Do you want to restore this backup?", os.path.basename(zip_name)): sys.exit(1) dp.create(AddonTitle, "Restoring Kodi.", 'In Progress.............', 'Please Wait') zip_name.replace('/storage/emulated/0/', '/sdcard/') home_path.replace('/storage/emulated/0/', '/sdcard/') zin = None kodi.log('\t_in= ' + zip_name + '\t_out= ' + home_path) # ##### read zip ##### try: zin = zipfile.ZipFile(zip_name, 'r') # , allowZip64=True) except Exception as e: kodi.log(e) traceback.print_exc(file=sys.stdout) for path in find_all_paths(os.path.basename(zip_name), os.path.abspath(os.sep)): # '/storage') kodi.log('\t trying source path: ' + path) try: zin = zipfile.ZipFile(path, 'r') # , allowZip64=True) if zin: break except Exception as e: kodi.log(e) traceback.print_exc(file=sys.stdout) if not zin: dialog.ok(AddonTitle + 'Restore', "Could Not Read Backup Zip File.", "Click OK to Exit Restore.") return # wipe_backup_restore() dp.create(AddonTitle, "Restoring File:", zip_name, '') # kodi.ext_all(zip_name, home_path, dp) # kodi.extract_all(zip_name, home_path, dp) # extract.extract_all(zip_name, home_path, dp) # ##### extract zip ##### try: if not dp: zin.extractall(home_path) else: n_files = float(len(zin.infolist())) count = 0 for item in zin.infolist(): if dp: count += 1 update = count / n_files * 100 dp.update( int(update) ) # , '', '', '[COLOR dodgerblue][B]' + str(item.filename) + '[/B][/COLOR]') zin.extract(item, home_path) return True except Exception as e: kodi.log(e) traceback.print_exc(file=sys.stdout) try: xbmc.executebuiltin("Extract(%s, %s)" % (zip_name, home_path)) xbmc.sleep(1800) # return True except Exception as e: traceback.print_exc(file=sys.stdout) # all(_in, _out, dp=None) dialog.ok(str(e), 'Please try again later', 'Attempting to continue...', "There was an error:") return False dialog.ok(AddonTitle, "Installation Complete.", "", "Click OK to exit Kodi and then restart to complete.") xbmc.executebuiltin('ShutDown')
def backup(b_type): exclude_dirs = [ 'cache', 'archive_cache', 'temp', kodi.get_setting('zip').strip('/') ] exclude_files = [logfile_name + '.log', logfile_name + '.old.log'] message_header = "%s Is Creating A %s Backup..." % ( AddonTitle, b_type.replace('_', ' ').title()) message1 = "Archiving..." if b_type == 'no_data': exclude_dirs.extend(['Thumbnails', 'Databases']) exclude_files.extend(["Textures13.db"]) check_path() if not os.path.exists(zip_path): os.makedirs(zip_path) title = set_name() if not title: return destfile = kodi.translate_path(os.path.join(zip_path, str(title) + '.zip')) if os.path.exists(destfile): if not dialog.yesno('File Name Already Exists', 'Would You like to Create Another File'+\ '\nOr Overwrite The Existing File?\n', 'Overwrite File', 'Create Another'): os.remove(destfile) else: title = set_name() if not title: return False, 0 destfile = kodi.translate_path( os.path.join(zip_path, str(title) + '.zip')) try: zipobj = zipfile.ZipFile(destfile, 'w', zipfile.ZIP_DEFLATED) # , allowZip64=True) except IOError as e: dialog.ok( 'ERROR', 'Could Not Use This Location for Backup\nPlease Chose Another Location', str(e)) return rootlen = len(home_path) for_progress = [] item = [] dp.create(message_header, message1 + '\n\n') for base, dirs, files in os.walk(home_path): for n_file in files: item.append(n_file) n_item = len(item) for base, dirs, files in os.walk(home_path): dirs[:] = [d for d in dirs if d not in exclude_dirs] files[:] = [f for f in files if f not in exclude_files] for file_n in files: try: for_progress.append(file_n) progress = len(for_progress) / float(n_item) * 100 dp.update( int(progress), "Archiving.." + '\n[COLOR blue]%s[/COLOR]' % file_n + '\n') fp = os.path.join(base, file_n) zipobj.write(fp, fp[rootlen:]) except Exception as e: kodi.log(str(e)) zipobj.close() dp.close() time.sleep(1) dialog.ok("[COLOR gold][B]SUCCESS![/B][/COLOR]", 'Your backup was completed successfully!.\nBackup Location: '+\ '\n[COLOR=yellow]' + destfile + '[/COLOR]')
def get_link(url,movie_title,thumb,media): hmf = urlresolver.HostedMediaFile(url) ########################################## if hmf: try: url = urlresolver.resolve(url) params = {'url':url, 'title':movie_title, 'thumb':thumb} listitem = xbmcgui.ListItem(path=url, iconImage=thumb, thumbnailImage=thumb) listitem.setProperty('fanart_image', fanart) listitem.setPath(url) listitem.setInfo('video', params) xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem) movie_name = movie_title[:-6] movie_name = '"'+movie_name+'"' movie_year_full = movie_title[-6:] movie_year = movie_year_full.replace('(','').replace(')','') if kodi.get_setting('trakt_oauth_token'): xbmc.sleep(30000) kodi.log( "Velocity: Movie Scrobble Start") try: trakt_auth.start_movie_watch(movie_name,movie_year) except Exception as e: log_utils.log('Error [%s] %s' % (str(e), ''), xbmc.LOGERROR) if kodi.get_setting('error_notify') == "true": kodi.notify(header='Scrobble not loggged', msg='%s %s' % (str(e), ''), duration=5000, sound=None) xbmc.sleep(30000) if kodi.get_setting('trakt_oauth_token'): check_player(movie_name,movie_year) except Exception as e: log_utils.log('Error [%s] %s' % (str(e), ''), xbmc.LOGERROR) kodi.notify(header='Try Another Source', msg='Link Removed or Failed', duration=4000, sound=None) if not hmf: try: params = {'url':url, 'title':movie_title, 'thumb':thumb} addon.add_video_item(params, {'title':movie_title}, img=thumb) liz=xbmcgui.ListItem(movie_title, iconImage="DefaultFolder.png", thumbnailImage=thumb) xbmc.sleep(1000) liz.setPath(str(url)) xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz) #xbmc.Player ().play(url, liz, False) movie_name = movie_title[:-6] movie_name = '"'+movie_name+'"' movie_year_full = movie_title[-6:] movie_year = movie_year_full.replace('(','').replace(')','') if kodi.get_setting('trakt_oauth_token'): xbmc.sleep(30000) print "Velocity: Movie Scrobble Start" try: trakt_auth.start_movie_watch(movie_name,movie_year) except Exception as e: log_utils.log('Error [%s] %s' % (str(e), ''), xbmc.LOGERROR) if kodi.get_setting('error_notify') == "true": kodi.notify(header='Scrobble not loggged', msg='%s %s' % (str(e), ''), duration=5000, sound=None) xbmc.sleep(30000) if kodi.get_setting('trakt_oauth_token'): check_player(movie_name,movie_year) except Exception as e: log_utils.log('Error [%s] %s' % (str(e), ''), xbmc.LOGERROR) kodi.notify(header='Try Another Source', msg='Link Removed or Failed', duration=4000, sound=None)
def shutdown(self): kodi.log("Service Stopping...")
def download(url, addon_id, destination, unzip=False, quiet=False): version = None filename = addon_id + '.zip' r = requests.get(url, stream=True) kodi.log("Download: %s" % url) if r.status_code == requests.codes.ok: temp_file = kodi.vfs.join(kodi.get_profile(), "downloads") if not kodi.vfs.exists(temp_file): kodi.vfs.mkdir(temp_file, recursive=True) temp_file = kodi.vfs.join(temp_file, filename) try: total_bytes = int(r.headers["Content-Length"]) except: total_bytes = 0 block_size = 1000 cached_bytes = 0 if not quiet: pb = xbmcgui.DialogProgress() pb.create("Downloading", filename, ' ', ' ') kodi.sleep(150) start = time.time() with open(temp_file, 'wb') as f: for block in r.iter_content(chunk_size=block_size): if not block: break if not quiet and pb.iscanceled(): raise downloaderException('Download Aborted') return False cached_bytes += len(block) f.write(block) if total_bytes > 0: delta = int(time.time() - start) if delta: bs = int(cached_bytes / (delta)) else: bs = 0 if not quiet: percent = int(cached_bytes * 100 / total_bytes) pb.update(percent, "Downloading", filename, format_status(cached_bytes, total_bytes, bs)) if not quiet: pb.close() if unzip: zip_ref = zipfile.ZipFile(temp_file, 'r') zip_ref.extractall(destination) zip_ref.close() kodi.vfs.rm(temp_file, quiet=True) try: xml = kodi.vfs.read_file(kodi.vfs.join( destination, kodi.vfs.join(addon_id, 'addon.xml')), soup=True) version = get_version_by_xml(xml) if not version: version = get_version_by_name(filename) except: kodi.log( "Unable to fine version from addon.xml for addon: %s" % addon_id) else: kodi.vfs.mv(temp_file, kodi.vfs.join(destination, filename)) else: kodi.close_busy_dialog() raise downloaderException(r.status_code) return version
except: description = None try: filetype = unquote_plus(params["filetype"]) except: filetype = None try: url = unquote_plus(params["url"]) except: pass try: name = unquote_plus(params["name"]) except: pass try: kodi.log('PARAMS= ' + str(params), '') mode = unquote_plus(params["mode"]) except: pass try: repourl = unquote_plus(params["repourl"]) except: repourl = None try: xmlurl = unquote_plus(params["xmlurl"]) except: pass try: dataurl = unquote_plus(params["dataurl"]) except:
def get_github(script, dataurl): try: link = kodi.open_url(tvpath) if script in link: script_url = tvpath + script + '/' version, orglist = get_url(script, script_url, link) kodi.log(' DOWNLOADING TVA FILE to ' + script + version + '.zip') depend_install(script, orglist) else: link = kodi.open_url(kodi_url) if script in link: script_url = kodi_url + script + '/' version, orglist = get_url(script, script_url, link) kodi.log(' DOWNLOADING KODI FILE to ' + script + version + '.zip') depend_install(script, orglist) else: fix_urls = dataurl + script + '/' fixed_url = fix_urls.replace("raw/", "").replace("/master/", "/blob/master/") \ .replace("githubusercontent", "github") link = kodi.open_url(fixed_url) if link and "Invalid request" not in link: version, orglist = get_url(script, fixed_url, link) kodi.log(' DOWNLOADING NATIVE to ' + script + version + '.zip') depend_install(script, orglist) else: fixed_url = fix_urls.replace("raw/", "").replace("/master/", "/tree/master/") \ .replace("githubusercontent", "github") link = kodi.open_url(fixed_url) if link and "Invalid request" not in link: version, orglist = get_url(script, fixed_url, link) kodi.log(' DOWNLOADING NATIVE to ' + script + version + '.zip') depend_install(script, orglist) else: kodi.log("DEAD REPO LOCATION = " + dataurl) except Exception as e: kodi.log("Failed to find required files " + str(e)) traceback.print_exc(file=sys.stdout)