def requestFinished(self, requestId, state): if requestId != self.httpGetId: return self.buttonBox.setEnabled(False) if state: self.mResult = self.http.errorString() self.reject() return self.file.close() pluginDir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/python/plugins" tmpPath = self.file.fileName() # make sure that the parent directory exists if not QDir(pluginDir).exists(): QDir().mkpath(pluginDir) # if the target directory already exists as a link, remove the link without resolving: QFile(pluginDir+unicode(QDir.separator())+self.plugin["id"]).remove() try: unzip(unicode(tmpPath), unicode(pluginDir)) # test extract. If fails, then exception will be raised and no removing occurs # removing old plugin files if exist removeDir(QDir.cleanPath(pluginDir+"/"+self.plugin["id"])) # remove old plugin if exists unzip(unicode(tmpPath), unicode(pluginDir)) # final extract. except: self.mResult = self.tr("Failed to unzip the plugin package. Probably it's broken or missing from the repository. You may also want to make sure that you have write permission to the plugin directory:") + "\n" + pluginDir self.reject() return try: # cleaning: removing the temporary zip file QFile(tmpPath).remove() except: pass self.close()
def _unzip_files(unzip_file_list, directory_to_extract_to, galaxy_name): '''unzip all zip files in list and find location of csv files''' file_to_copy = dict() for each_zip in unzip_file_list: extract_gal_to = os.path.join( directory_to_extract_to, _get_galaxy_name_and_band_string(each_zip)) _make_dir_if_does_not_exist(extract_gal_to) unzip(each_zip, extract_gal_to) file_name_to_file_path_dict = _get_csv_file_path( extract_gal_to, galaxy_name) file_to_copy.update(file_name_to_file_path_dict) return file_to_copy
def requestFinished(self): reply = self.sender() self.buttonBox.setEnabled(False) if reply.error() != QNetworkReply.NoError: self.mResult = reply.errorString() if reply.error() == QNetworkReply.OperationCanceledError: self.mResult += "<br/><br/>" + QCoreApplication.translate( "QgsPluginInstaller", "If you haven't cancelled the download manually, it might be caused by a timeout. In this case consider increasing the connection timeout value in QGIS options." ) self.reject() reply.deleteLater() return self.file.open(QFile.WriteOnly) self.file.write(reply.readAll()) self.file.close() self.stateChanged(0) reply.deleteLater() pluginDir = QFileInfo( QgsApplication.qgisUserDbFilePath()).path() + "/python/plugins" tmpPath = self.file.fileName() # make sure that the parent directory exists if not QDir(pluginDir).exists(): QDir().mkpath(pluginDir) # if the target directory already exists as a link, remove the link without resolving: QFile(pluginDir + unicode(QDir.separator()) + self.plugin["id"]).remove() try: unzip( unicode(tmpPath), unicode(pluginDir) ) # test extract. If fails, then exception will be raised and no removing occurs # removing old plugin files if exist removeDir(QDir.cleanPath( pluginDir + "/" + self.plugin["id"])) # remove old plugin if exists unzip(unicode(tmpPath), unicode(pluginDir)) # final extract. except: self.mResult = self.tr( "Failed to unzip the plugin package. Probably it's broken or missing from the repository. You may also want to make sure that you have write permission to the plugin directory:" ) + "\n" + pluginDir self.reject() return try: # cleaning: removing the temporary zip file QFile(tmpPath).remove() except: pass self.close()
def download_appengine(appengine_zip): os.chdir(code_dir) if not os.path.exists("google_appengine"): print "downloading", appengine_zip urlretrieve( "http://googleappengine.googlecode.com/files/" + appengine_zip, appengine_zip) un = unzip() un.extract(appengine_zip, ".") os.remove(appengine_zip) replace_in_file("google_appengine/google/appengine/tools/appcfg.py", "if nag.opt_in is None:", "if False:") replace_in_file( "google_appengine/google/appengine/tools/dev_appserver.py", "MAX_RUNTIME_RESPONSE_SIZE = 10 << 20", "MAX_RUNTIME_RESPONSE_SIZE = 10 << 22") replace_in_file( "google_appengine/google/appengine/tools/dev_appserver_main.py", "http_server.serve_forever()", "import webbrowser; webbrowser.open('http://localhost:8080'); http_server.serve_forever()" ) replace_in_file( "google_appengine/google/appengine/tools/bulkloader.py", "self.num_threads = arg_dict['num_threads']", "self.num_threads = 5")
def on_openArchiveButton_clicked(self): """opens directory search dialog and sets my attribute __dir""" l_path = self._start_find_path() #l_request = "Select zipfile which holds result request Dig ALert" l_request = self.tr("Selecteer een zip bestand die een KLIC bericht bevat") l_filter = self.tr("Zip bestanden (*.zip *.ZIP)") l_fileName, __ = QFileDialog.getOpenFileName(self, l_request, l_path, l_filter) if l_fileName=="": return #l_fileName = unicode(l_fileName) #first find out if zipfile contains a named directory being #ID of dig alert l_dirName = self._dirNameInArchive(l_fileName) l_dir = os.path.dirname(l_fileName) l_zipDir = os.path.join(l_dir,l_dirName) self.__dir = l_zipDir l_unzipper = unzip.unzip() l_unzipper.extract(l_fileName, l_zipDir) #try to find out if after extract, folder holds another folder #with message id l_dir_maybe = os.path.join(l_zipDir, l_dirName) if os.path.isdir(l_dir_maybe): self.__dir = l_dir_maybe self._loadMsg()
def download_7zip(): os.chdir(code_dir) if not os.path.exists("7za.exe"): print "downloading 7zip" urlretrieve("http://downloads.sourceforge.net/project/sevenzip/7-Zip/4.65/7za465.zip", "7za465.zip") un = unzip() un.extract("7za465.zip", ".") os.remove("7za465.zip")
def extract_files(input_dir, obb_filename, asset_bundles): unzip(f'./{input_dir}/base.apk', args.output_dir) unzip(f'./{input_dir}/{obb_filename}', args.output_dir) if asset_bundles: bundles = glob.glob(f'./{input_dir}/AssetBundles/*.ab/*.ab') for index, bundle in enumerate(bundles): actual_filename = os.path.basename(os.path.dirname(bundle)) output = f'{args.output_dir}/assets/AssetBundles/{actual_filename}' print('Copying', bundle, 'to', output, f'({index + 1}/{len(bundles)})') shutil.copyfile(bundle, output) if not args.skip_cleanup and not args.extract_only: print('Cleaning up...') shutil.rmtree(f'./{input_dir}') print(f'Extracted files to {args.output_dir}. Use uTinyRipper to extract assets')
def _unzip_archive(self, name): file = self.path(name) dirname = file + ".content" unzip(verbose=False).extract(file, dirname) # check for single root directory dirs = os.listdir(dirname) if len(dirs) == 1 and os.path.isdir(os.path.join(dirname, dirs[0])): dir = os.path.join(dirname, dirs[0]) os.rename(dir, dir + ".jmutube.temp") dir += ".jmutube.temp" for f in os.listdir(dir): shutil.move(os.path.join(dir, f), os.path.join(dirname, f)) os.rmdir(dir) # check for entry point html = filter(lambda f: f.endswith(".htm") or f.endswith(".html"), os.listdir(dirname)) if len(html) == 1 and not html[0] in ('default.htm', 'default.html', 'index.htm', 'index.html'): shutil.copy(os.path.join(dirname, html[0]), os.path.join(dirname, 'index.html'))
def convertKmz(self, file, dir, dirout, fname): #extract the zip file to a folder un = unzip.unzip() un.extract(file, dir) nrkml = 0 nrcollada = 0 for root, dirs, files in os.walk(dir): for name in files: if name.endswith((".kml")): kmlfile = open(os.path.join(root, name), 'r') pos_ori = self.extractLocation(kmlfile) kmlfile.close() nrkml = nrkml + 1 if name.endswith((".dae")): colladafilepath = os.path.join(root, name) (path, name) = os.path.split(colladafilepath) nrcollada = nrcollada + 1 if (nrkml == 0): return "error: no georeference info in zip file. Try to convert the *dae file separately !" if (nrkml > 1): return "error: more than one kml file in zipfile. Convert multiple models separately !" if (nrcollada == 0): return "error: no *.dae file found in zip file !" if (nrcollada > 1): return "error: multiple collada files in zip file. Convert multiple models separately !" convertCollada( colladafilepath, [float(pos_ori[0]), float(pos_ori[1]), float(pos_ori[2])], dirout) #writes the jsonfile into the extracted folder structure #copy all images in the output folder self.copyimages(dir, dirout, 'jpg', 'png', 'gif', 'json') #add supporting filetypes here... dirred = dir[:-5] for jsonfile in glob.glob(dirout + "/*.json"): #create the demo html file (path, name) = os.path.split(jsonfile) htmlCreator.createHTML(name, float(pos_ori[0]), float(pos_ori[1]), float(pos_ori[2]), dirout + '/modeldemo.html') #store the jsonfile in a new zip file self.zipper(dirout, dirred + '/jsonzip.zip') return dirred + "/jsonzip.zip"
def unzip_skin( temp_zip , name ): dezip = dialog.yesno( Language.getLocalizedString(30037) , Language.getLocalizedString(30038) , name) if dezip: DIALOG_PROGRESS.create( Language.getLocalizedString(30037) , Language.getLocalizedString(30039) , Language.getLocalizedString(30040)) xbmc.log( "[SCRIPT: %s] starting - [unzip(%s,%s)]" % ( __plugin__, "%s.zip" % name, SKIN_DIR ), xbmc.LOGNOTICE ) zipskin = unzip.unzip() zipskin.extract(temp_zip, SKIN_DIR) DIALOG_PROGRESS.close() xbmc.log( "[SCRIPT: %s] finish - [unzip(%s,%s)]" % ( __plugin__, "%s.zip" % name, SKIN_DIR ), xbmc.LOGNOTICE ) return (True)
def cui_main(): repo_id = sys.argv[1] splited = repo_id.split('/') if len(splited) != 2: print 'Error: Invalid autowot repository specification.' print 'Usage: autowot user/repository' exit(1) print 'Downloading ZIP archive from github: ' + repo_id + ' [master] ...' user, repo = splited github.download_zip_from_github_repository(user, repo) print 'Downloading completed successfully.' zipname = user + '_' + repo print 'Unzipping ' + zipname + '.zip ...' unzip.unzip(zipname + '.zip') print 'Unzipped successfully.' unzippeddirname = repo + '-master' print 'Running script.' os.chdir(unzippeddirname) run_script.run_script('./autowot.ini')
def transResponse(protocol, response): if protocol == 'getMysteryChestList_proto': try: response = unzip.unzip(response) except: return response reload(pbconf) protoConf = pbconf.pbconfig.pbconfig from pb2py import PBMsgResponse_pb2 reload(PBMsgResponse_pb2) importStr = 'from pb2py import ' + protoConf[protocol]['responseProto'] reloadStr = 'reload(' + protoConf[protocol]['responseProto'] + ')' exec(importStr) exec(reloadStr) responseObj = PBMsgResponse_pb2.PBMsgResponse() try: responseObj.ParseFromString(response) except: return response if responseObj.ok == False: return '<tr><td>OK:' + str( responseObj.ok) + '</td></tr>' + '<tr><td>error_code:' + str( responseObj.error_code ) + '</td></tr>' + '<tr><td>msg:' + responseObj.msg + '</td></tr>' else: responseData = responseObj.data initStr = 'data=' + protoConf[protocol]['responseProto'] + '.' + protoConf[ protocol]['responseClass'] + '()' exec(initStr) data.ParseFromString(responseData) stringData = data.__str__() if protocol == 'pve1': if data.staminaInfo: staminaInfo = data.staminaInfo from pb2py import PBMsgPveStaminaInfo_pb2 stamina = PBMsgPveStaminaInfo_pb2.PBMsgPveStaminaInfo() stamina.ParseFromString(staminaInfo) staminaString = '{\n' + stamina.__str__() + '}' stringData = replaceValue('staminaInfo', stringData, staminaString) if data.resultInfo: resultInfo = data.resultInfo from pb2py import PBMsgPveResultInfo_pb2 result = PBMsgPveResultInfo_pb2.PBMsgPveResultInfo() result.ParseFromString(resultInfo) resultString = '{\n' + result.__str__() + '}' stringData = replaceValue('resultInfo', stringData, resultString) if data.marchInfo: marchInfo = data.marchInfo from pb2py import PBMsgPveMarchInfo_pb2 march = PBMsgPveMarchInfo_pb2.PBMsgPveMarchInfo() march.ParseFromString(marchInfo) marchString = '{\n' + march.__str__() + '}' stringData = replaceValue('marchInfo', stringData, marchString) treeData = string2tree(stringData) return treeData
def convertKmz(self, file, dir, dirout,fname): #extract the zip file to a folder un = unzip.unzip() un.extract(file,dir) nrkml = 0; nrcollada = 0 for root, dirs, files in os.walk(dir): for name in files: if name.endswith((".kml")): kmlfile = open(os.path.join(root, name),'r') pos_ori = self.extractLocation(kmlfile) kmlfile.close() nrkml = nrkml+1 if name.endswith((".dae")): colladafilepath = os.path.join(root, name) (path,name) = os.path.split(colladafilepath) nrcollada = nrcollada+1 if(nrkml==0): return "error: no georeference info in zip file. Try to convert the *dae file separately !" if(nrkml>1): return "error: more than one kml file in zipfile. Convert multiple models separately !" if(nrcollada==0): return "error: no *.dae file found in zip file !" if(nrcollada>1): return "error: multiple collada files in zip file. Convert multiple models separately !" convertCollada(colladafilepath,[float(pos_ori[0]),float(pos_ori[1]),float(pos_ori[2])],dirout) #writes the jsonfile into the extracted folder structure #copy all images in the output folder self.copyimages(dir,dirout,'jpg', 'png','gif','json') #add supporting filetypes here... dirred = dir[:-5] for jsonfile in glob.glob(dirout+"/*.json"): #create the demo html file (path,name) = os.path.split(jsonfile) htmlCreator.createHTML(name,float(pos_ori[0]),float(pos_ori[1]),float(pos_ori[2]),dirout+'/modeldemo.html') #store the jsonfile in a new zip file self.zipper(dirout,dirred+'/jsonzip.zip') return dirred+"/jsonzip.zip"
def gerador(): argumentos = sys.argv contem = False with urllib.request.urlopen('http://mmhand.esy.es/deped/states.json') as f: data = json.loads(f.read().decode()) for state in data[argumentos[1]]: if (argumentos[2] in state['version']): contem = True dados = state['name'] + "-" + state['version'] + " " + state['link'] fullName = state['name'] + "-" + state['version'] + "." + state[ 'extension'] link = state['link'] extension = state['extension'] if (contem): #print(state['name'], state['version'], state['link']) print("Gerando " + fullName) url = link r = requests.get(url, allow_redirects=True) total = len(r.content) dl = 0 start = time.clock() for chunk in r.iter_content(1024): dl += len(chunk) open(fullName, 'wb').write(r.content) done = int(50 * dl / total) sys.stdout.write("\r[%s%s] %s bps" % ('▀' * done, ' ' * (50 - done), dl // (time.clock() - start))) if (extension == 'zip'): unzip(fullName) else: print("\nDownload feito com sucesso") else: print("nao tem")
def requestFinished(self, requestId, state): if requestId != self.httpGetId: return self.buttonBox.setEnabled(False) if state: self.mResult = self.http.errorString() self.reject() return self.file.close() pluginDir = QFileInfo( QgsApplication.qgisUserDbFilePath()).path() + "/python/plugins" tmpPath = self.file.fileName() # make sure that the parent directory exists if not QDir(pluginDir).exists(): QDir().mkpath(pluginDir) # if the target directory already exists as a link, remove the link without resolving: QFile(pluginDir + unicode(QDir.separator()) + self.plugin["id"]).remove() try: unzip( unicode(tmpPath), unicode(pluginDir) ) # test extract. If fails, then exception will be raised and no removing occurs # removing old plugin files if exist removeDir(QDir.cleanPath( pluginDir + "/" + self.plugin["id"])) # remove old plugin if exists unzip(unicode(tmpPath), unicode(pluginDir)) # final extract. except: self.mResult = self.tr( "Failed to unzip the plugin package. Probably it's broken or missing from the repository. You may also want to make sure that you have write permission to the plugin directory:" ) + "\n" + pluginDir self.reject() return try: # cleaning: removing the temporary zip file QFile(tmpPath).remove() except: pass self.close()
def updateLocal(self): "Updates from local file" fileTypes = [('', '*.zip *.gz')] file = askopenfilename(parent=self.master, title='Choose a file', filetypes=fileTypes) if not file: return self.setUpdatesDir() if not self.testWritable(): print("Updates are not installed!") return self.localButton.configure(state='disabled') self.localLabel.configure(text='Please Wait...') self.master.update() mtime = os.path.getmtime(file) import time mdate = time.localtime(mtime) date_latest = str(mdate[0]) + '/' + str(mdate[1]) + '/' + str(mdate[2]) latest_rc = self.updates_rc_dir + os.sep + 'nightly' if os.path.exists(latest_rc): lines = open(latest_rc).readlines() if lines: self.updates_dir += os.sep + 'nightly_' self.updates_dir += date_latest.replace('/', '_') lines.insert(0, self.updates_dir + " " + date_latest + '\n') open(latest_rc, 'w').writelines(lines) else: self.updates_dir += os.sep + 'nightly' self.updates_dir += '_' + date_latest.replace('/', '_') open(latest_rc, 'w').write(self.updates_dir + " " + date_latest + '\n') else: self.updates_dir += os.sep + 'nightly' self.updates_dir += '_' + date_latest.replace('/', '_') open(latest_rc, 'w').write(self.updates_dir + " " + date_latest + '\n') if not os.path.isdir(self.updates_dir): os.mkdir(self.updates_dir) if file.endswith('.gz'): tar = tarfile.open(file) for tarinfo in tar: tar.extract(tarinfo, path=self.updates_dir) tar.close() else: unzipper = unzip.unzip() unzipper.extract(file, self.updates_dir) if self.master: self.finishGUI()
def open(self, filename): """ /** * Opens the specified OpenDocument for use by the other utility * functions in this class. * * @param filename Path to the OpenDocument file to load. * * @return @c true if the document was successfully loaded, * @c false otherwise. */ """ if self.filename: self.close() self.filename = filename # Create temp directory. self.tmp_dir = tempfile.mkdtemp('pylibopendocument') # Extract zip file. unzip(self.filename, self.tmp_dir) # Open file. fp = file(os.path.join(self.tmp_dir, 'content.xml'), 'rb') # Parse doc. self.doc = lxml.etree.parse(fp) fp.close() # Read mimetype. fp = file(os.path.join(self.tmp_dir, 'mimetype'), 'rb') self.mimetype = fp.read().strip() fp.close() return True
def download_appengine(appengine_zip): os.chdir(code_dir) if not os.path.exists("google_appengine"): print "downloading", appengine_zip urlretrieve("http://googleappengine.googlecode.com/files/"+appengine_zip, appengine_zip) un = unzip() un.extract(appengine_zip, ".") os.remove(appengine_zip) replace_in_file("google_appengine/google/appengine/tools/appcfg.py", "if nag.opt_in is None:", "if False:") replace_in_file("google_appengine/google/appengine/tools/dev_appserver.py", "MAX_RUNTIME_RESPONSE_SIZE = 10 << 20", "MAX_RUNTIME_RESPONSE_SIZE = 10 << 22") replace_in_file("google_appengine/google/appengine/tools/dev_appserver_main.py", "http_server.serve_forever()", "import webbrowser; webbrowser.open('http://localhost:8080'); http_server.serve_forever()") replace_in_file("google_appengine/google/appengine/tools/bulkloader.py", "self.num_threads = arg_dict['num_threads']", "self.num_threads = 5")
def requestFinished(self): reply = self.sender() self.buttonBox.setEnabled(False) if reply.error() != QNetworkReply.NoError: self.mResult = reply.errorString() if reply.error() == QNetworkReply.OperationCanceledError: self.mResult += "<br/><br/>" + QCoreApplication.translate("QgsPluginInstaller", "If you haven't cancelled the download manually, it might be caused by a timeout. In this case consider increasing the connection timeout value in QGIS options.") self.reject() reply.deleteLater() return self.file.open(QFile.WriteOnly) self.file.write( reply.readAll() ) self.file.close() self.stateChanged(0) reply.deleteLater() pluginDir = qgis.utils.home_plugin_path tmpPath = self.file.fileName() # make sure that the parent directory exists if not QDir(pluginDir).exists(): QDir().mkpath(pluginDir) # if the target directory already exists as a link, remove the link without resolving: QFile(pluginDir+unicode(QDir.separator())+self.plugin["id"]).remove() try: unzip(unicode(tmpPath), unicode(pluginDir)) # test extract. If fails, then exception will be raised and no removing occurs # removing old plugin files if exist removeDir(QDir.cleanPath(pluginDir+"/"+self.plugin["id"])) # remove old plugin if exists unzip(unicode(tmpPath), unicode(pluginDir)) # final extract. except: self.mResult = self.tr("Failed to unzip the plugin package. Probably it's broken or missing from the repository. You may also want to make sure that you have write permission to the plugin directory:") + "\n" + pluginDir self.reject() return try: # cleaning: removing the temporary zip file QFile(tmpPath).remove() except: pass self.close()
def scraiping(type): # ファイルダウンロード try: # FileDownloadインスタンス化 file_download = FileDownload(type) if (type == 'Kyi' or type == 'Sed' or type == 'Ukc' or type == 'Bac' or type == 'Kab' or type == 'Cyb' or type == 'Hjc'): file_download.download() else: file_download.downloadLatest() # 対象ファイルの取得 file_names = file_download.getFileNames() except Exception as e: log.error(e) log.error('ファイルが正常にダウンロードされませんでした。') sys.exit() # ファイルアップロード・削除 for file_name in file_names: # 正常にファイルがダウンロードできている場合 if os.path.exists('/home/ec2-user/tmp_jrdb_data/' + file_name): try: # zip 解凍 res = unzip(file_name) if (res['result'] == 0): remote_path_year = '/home/ec2-user/jrdb_data/20' + file_name[ 3:5] + "/" remote_path_type = remote_path_year + file_name[:3] file_move.move( '/home/ec2-user/tmp_jrdb_data/' + res['file_name'], remote_path_year, remote_path_type, res['file_name']) else: log.error('文字コードの変換に失敗しました。') sys.exit() except Exception as e: log.error(e) log.error('ファイルのアップロードに失敗しました。要リカバリ (filename=' + file_name + ')') sys.exit() else: log.error('ファイルが正常にダウンロードされませんでした。') sys.exit() # ディレクトリを削除 try: shutil.rmtree('/home/ec2-user/tmp_jrdb_data') except Exception as e: log.error(e) log.error('ディレクトリの削除に失敗しました。')
def Extract_Subtitles( self, zip_subs, subtitle_lang ): un = unzip.unzip() files = un.get_file_list( zip_subs ) sub_filename = os.path.basename( self.file_original_path ) exts = [".srt", ".sub", ".txt", ".smi", ".ssa", ".ass" ] if len(files) < 1 : self.getControl( STATUS_LABEL ).setLabel( _( 654 ) ) if self.newWindow: self.setFocusId( SERVICES_LIST ) self.getControl( SERVICES_LIST ).selectItem( 0 ) else: self.list_services() else : self.getControl( STATUS_LABEL ).setLabel( _( 652 ) ) un.extract( zip_subs, self.tmp_sub_dir ) subtitle_set = False movie_sub = False episode = 0 for zip_entry in files: if os.path.splitext( zip_entry )[1] in exts: subtitle_file, file_path = self.create_name(zip_entry,sub_filename,subtitle_lang) if len(self.tvshow) > 0: title, season, episode = regex_tvshow(False, zip_entry) if not episode : episode = -1 else: if os.path.splitext( zip_entry )[1] in exts: movie_sub = True if ( movie_sub or len(files) < 2 or int(episode) == int(self.episode) ): subtitle_set,file_path = self.copy_files( subtitle_file, file_path ) if not subtitle_set: for zip_entry in files: if os.path.splitext( zip_entry )[1] in exts: print os.path.splitext( zip_entry )[1] subtitle_file, file_path = self.create_name(zip_entry,sub_filename,subtitle_lang) subtitle_set,file_path = self.copy_files( subtitle_file, file_path ) if subtitle_set : xbmc.Player().setSubtitles(file_path) self.exit_script() else: self.getControl( STATUS_LABEL ).setLabel( _( 654 ) ) if self.newWindow: self.setFocusId( SERVICES_LIST ) self.getControl( SERVICES_LIST ).selectItem( 0 ) else: self.list_services() self.setFocusId( SUBTITLES_LIST ) self.getControl( SUBTITLES_LIST ).selectItem( 0 )
def unzipEpub(zipsource): """ Unzip the EPUB file to a temp file """ filename = os.path.splitext(zipsource)[0].split(os.sep)[-1] baseDir = os.path.dirname(zipsource) + "/temp/" # tempfile.mkdtemp() zipdest = os.path.join(baseDir, filename) os.makedirs(zipdest) unzipper = unzip.unzip() unzipper.verbose = False unzipper.percent = 100 unzipper.extract(zipsource, zipdest) return baseDir, zipdest, filename + ".epub"
def unzip_skin(temp_zip, name): dezip = dialog.yesno(Language.getLocalizedString(30037), Language.getLocalizedString(30038), name) if dezip: DIALOG_PROGRESS.create(Language.getLocalizedString(30037), Language.getLocalizedString(30039), Language.getLocalizedString(30040)) xbmc.log( "[SCRIPT: %s] starting - [unzip(%s,%s)]" % (__plugin__, "%s.zip" % name, SKIN_DIR), xbmc.LOGNOTICE) zipskin = unzip.unzip() zipskin.extract(temp_zip, SKIN_DIR) DIALOG_PROGRESS.close() xbmc.log( "[SCRIPT: %s] finish - [unzip(%s,%s)]" % (__plugin__, "%s.zip" % name, SKIN_DIR), xbmc.LOGNOTICE) return (True)
def preinitialize(self): by_require = self.pdist_fname and os.path.exists(self.pdist_fname) distributions = self.product_distributions() working_set = pkg_resources.working_set for distribution in distributions: if is_zip_safe_distribution(distribution): working_set.add(distribution) else: if os.path.isdir(distribution.location): # already a directory working_set.add(distribution) continue # if it's not zip-safe and not already a directory, blast # it out to a dir and create new distro out of the # file-based egg if by_require: # these get added to the working set in req mode remove_distribution_from_working_set(distribution) explodedDir = self.ensureExplodedDir(distribution.project_name) self.exploded_dirs.append(explodedDir) eggname = os.path.basename(distribution.location) eggdir = os.path.join(explodedDir, eggname) if not os.path.isdir(eggdir): os.makedirs(eggdir) timestamp = os.path.join(explodedDir, 'timestamp-%s' % eggname) if not os.path.isfile(timestamp) or \ os.path.getmtime(distribution.location) > os.path.getmtime(timestamp): un = unzip.unzip() un.extract(distribution.location, eggdir) f = open(timestamp, 'w') f.close() atime = os.path.getatime(distribution.location) mtime = os.path.getmtime(distribution.location) os.utime(timestamp, (atime, mtime)) metadata = pkg_resources.PathMetadata( eggdir, os.path.join(eggdir, 'EGG-INFO')) new_distro = pkg_resources.Distribution.from_filename( eggdir, metadata=metadata) working_set.add(new_distro) self.pre_initialized = True
def preinitialize(self): by_require = self.pdist_fname and os.path.exists(self.pdist_fname) distributions = self.product_distributions() working_set = pkg_resources.working_set for distribution in distributions: if is_zip_safe_distribution(distribution): working_set.add(distribution) else: if os.path.isdir(distribution.location): # already a directory working_set.add(distribution) continue # if it's not zip-safe and not already a directory, blast # it out to a dir and create new distro out of the # file-based egg if by_require: # these get added to the working set in req mode remove_distribution_from_working_set(distribution) explodedDir = self.ensureExplodedDir(distribution.project_name) self.exploded_dirs.append(explodedDir) eggname = os.path.basename(distribution.location) eggdir = os.path.join(explodedDir, eggname) if not os.path.isdir(eggdir): os.makedirs(eggdir) timestamp = os.path.join(explodedDir, 'timestamp-%s' % eggname) if not os.path.isfile(timestamp) or \ os.path.getmtime(distribution.location) > os.path.getmtime(timestamp): un = unzip.unzip() un.extract(distribution.location, eggdir) f = open(timestamp, 'w') f.close() atime = os.path.getatime(distribution.location) mtime = os.path.getmtime(distribution.location) os.utime(timestamp, (atime, mtime)) metadata = pkg_resources.PathMetadata(eggdir, os.path.join(eggdir, 'EGG-INFO')) new_distro = pkg_resources.Distribution.from_filename( eggdir, metadata=metadata) working_set.add(new_distro) self.pre_initialized = True
def Extract_Subtitles( self, zip_subs, subtitle_lang ): if have_unzip: un = unzip.unzip() files = un.get_file_list( zip_subs ) sub_filename = os.path.basename( self.file_original_path ) exts = [".srt", ".sub", ".txt", ".smi", ".ssa", ".ass" ] if have_unzip and len(files) < 1 : printl("len(files) < 1", self, "W") else : if have_unzip: un.extract( zip_subs, self.tmp_sub_dir ) else: printl("unzip " + str(zip_subs) + " -d " + str(self.tmp_sub_dir), self, "D") os.system("unzip " + str(zip_subs) + " -d " + str(self.tmp_sub_dir)) files = os.listdir(str(self.tmp_sub_dir)) subtitle_set = False movie_sub = False episode = 0 for zip_entry in files: if os.path.splitext( zip_entry )[1] in exts: subtitle_file, file_path = self.create_name(zip_entry,sub_filename,subtitle_lang) if False: #len(self.tvshow) > 0: title, season, episode = regex_tvshow(False, zip_entry) if not episode : episode = -1 else: if os.path.splitext( zip_entry )[1] in exts: movie_sub = True shutil.copy(subtitle_file, file_path) subtitle_set = True #if ( movie_sub or len(files) < 2 or int(episode) == int(self.episode) ): # shutil.copy(subtitle_file, file_path) # subtitle_set = True # #subtitle_set,file_path = self.copy_files( subtitle_file, file_path ) if not subtitle_set: for zip_entry in files: if os.path.splitext( zip_entry )[1] in exts: subtitle_file, file_path = self.create_name(zip_entry,sub_filename,subtitle_lang) shutil.copy(subtitle_file, file_path) #subtitle_set,file_path = self.copy_files( subtitle_file, file_path ) try: shutil.rmtree(str(self.tmp_sub_dir)) except Exception, ex: printl("Exception: " + str(ex), __name__, "E")
def unzipnsis(pathtozip): global tempdir tempdir = tempfile.mkdtemp() un = unzip.unzip() print("Unzipping NSIS to {0}...".format(tempdir)) un.extract(pathtozip, tempdir) print("Done.") # Ensure the correct executable is called dotexe="" if "win" in sys.platform.lower(): dotexe=".exe" makensispath = os.path.join(tempdir, "NSIS", "makensis" + dotexe) if not "win" in sys.platform.lower(): os.chmod(makensispath, stat.S_IRWXU) return makensispath
def getGDS(): sourceHost = 'http://' + sourceUrl requestforcookie.game_server_url = sourceHost requestforcookie.init_httpopener_cookie_by_login() header = requestforcookie.default_header.copy() header['Host'] = sourceUrl headers = header.copy() data = '' for gds in typelist: conn = httplib.HTTPConnection(sourceUrl) conn.request('GET', '/admin/manageDownGds.php?type=%s&serverid=1' % gds, data, headers) result = conn.getresponse() content = result.read() content = unzip.unzip(content) file = open('%s.csv' % gds, 'w') file.write(content) file.close()
def extract_dataset(ds): extract = False exdir = datadir + os.sep + ds + os.sep archive = exdir + datasets[ds]['archive'] if not os.path.exists(archive): raise Exception('the archive for %s has not been downloaded or is missing.' % ds) if not 'files' in datasets[ds]: extract = True else: for i,file in enumerate(datasets[ds]['files']): fileplus = file + '.' + datasets[ds]['types'][i] if ('types' in datasets[ds]) else datasets[ds]['files'][i] if not os.path.exists(exdir + fileplus) and not os.path.exists(exdir + file): extract = True break if(extract): un = unzip.unzip() print "extracting...", un.extract(archive,datadir + os.sep + ds + os.sep) else: print "already extracted...",
def pushButton_clicked(self): data = self.textEdit.toPlainText() loop = self.textEdit_2.toPlainText() if loop != '': loops = int(loop) else: loops = 1 pname = self.textEdit_4.toPlainText() serverUrl = self.textEdit_3.toPlainText() pname = pname.toUtf8() serverUrl = str(serverUrl) if pname == '': QtGui.QMessageBox.information( self, 'Information', self.tr('please Input protocol name')) return 0 if serverUrl == '': QtGui.QMessageBox.information(self, 'Information', self.tr('please Input server Url')) return 0 params = 'data=' + protocol.generateParams(data) + '&vcs=15.0.0' headers = { 'Host': serverUrl, 'User-Agent': 'Camelot/15.0.0 CFNetwork/485.13.9 Darwin/11.0.0', 'Content-Length': len(params), 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': '*/*', 'Accept-Language': 'en-us', 'Accept-Encoding': 'gzip,deflate', 'Connection': 'keep-alive' } conn = httplib.HTTPConnection(serverUrl) for i in range(loops): conn.request('POST', '/ajax/%s' % pname, params, headers) result = conn.getresponse() data = result.read() try: rdata = unzip.unzip(data) except: rdata = data self.textBrowser.append(rdata)
def downloadsubtitle(self, pos): if self.osdb_server.subtitles_list: filename = self.osdb_server.subtitles_list[pos]["filename"] filename = filename[0:filename.rfind(".")] + ".zip" remote_path = os.path.dirname( self.filepath ) local_path = os.path.dirname( self.settings["subtitles_path"] ) url = self.osdb_server.subtitles_list[pos]["link"] self.getControl( 100 ).setLabel( _( 632 ) % ( filename, ) ) self.file_download( url, os.path.join( local_path, filename ) ) if os.path.exists( os.path.join( local_path, filename ) ): un = unzip.unzip() self.getControl( 100 ).setLabel( _( 631 ) % ( filename, os.path.dirname( local_path ) ) ) un.extract( os.path.join( local_path, filename ), local_path ) if self.settings["save_to_videofile_path"]: self.getControl( 100 ).setLabel( _( 631 ) % ( filename, os.path.dirname( remote_path ), ) ) un.extract( os.path.join( local_path, filename ), remote_path ) self.getControl( 100 ).setLabel( _( 630 ) )
def extract_subtitles(self, filename, sub_filename, subtitle_format, zip_filename, local_path ): LOG( LOG_INFO, "extract_subtitles" ) subtitle_set = False try: un = unzip.unzip() #if os.path.exists( zip_filename ): #return files = un.get_file_list( zip_filename ) if ( len( files ) == 2 ): if not ( filename in files ): for item in files: if ( item.find( subtitle_format ) > 0 ): filename = item break self.getControl( STATUS_LABEL ).setLabel( _( 650 ) ) LOG( LOG_INFO, _( 631 ) % ( zip_filename, local_path ) ) un.extract_file( zip_filename, filename, sub_filename, local_path ) LOG( LOG_INFO, _( 644 ) % ( local_path ) ) self.getControl( STATUS_LABEL ).setLabel( _( 651 ) ) if xbmc.Player().isPlayingVideo(): xbmc.Player().setSubtitles( os.path.join( local_path, sub_filename ) ) subtitle_set = True else: self.getControl( STATUS_LABEL ).setLabel( _( 650 ) ) LOG( LOG_INFO, _( 631 ) % ( zip_filename, local_path ) ) un.extract( zip_filename, local_path ) LOG( LOG_INFO, _( 644 ) % ( local_path ) ) self.getControl( STATUS_LABEL ).setLabel( _( 651 ) ) if xbmc.Player().isPlayingVideo(): for item in files: if ( item.find( subtitle_format ) > 0 ): xbmc.Player().setSubtitles( os.path.join( local_path, item ) ) subtitle_set = True except Exception, e: error = _( 634 ) % ( str ( e ) ) LOG( LOG_ERROR, error )
def preinitialize(self): by_require = self.pdist_fname and os.path.exists(self.pdist_fname) if by_require: distributions = self.product_distributions_by_require() else: distributions = self.product_distributions_by_dwim() working_set = pkg_resources.working_set for distribution in distributions: if is_zip_safe_distribution(distribution): working_set.add(distribution) else: if os.path.isdir(distribution.location): # already a directory working_set.add(distribution) continue # if it's not zip-safe and not already a directory, blast # it out to a tempdir and create new distro out of the # file-based egg; we delete the tempdir at system exit if by_require: # these get added to the working set in req mode remove_distribution_from_working_set(distribution) tempdir = tempfile.mkdtemp() eggname = os.path.basename(distribution.location) eggdir = os.path.join(tempdir, eggname) os.makedirs(eggdir) self.tempdirs.append(tempdir) un = unzip.unzip() un.extract(distribution.location, eggdir) metadata = pkg_resources.PathMetadata( eggdir, os.path.join(eggdir, 'EGG-INFO')) new_distro = pkg_resources.Distribution.from_filename( eggdir, metadata=metadata) working_set.add(new_distro) self.pre_initialized = True
def preinitialize(self): by_require = self.pdist_fname and os.path.exists(self.pdist_fname) if by_require: distributions = self.product_distributions_by_require() else: distributions = self.product_distributions_by_dwim() working_set = pkg_resources.working_set for distribution in distributions: if is_zip_safe_distribution(distribution): working_set.add(distribution) else: if os.path.isdir(distribution.location): # already a directory working_set.add(distribution) continue # if it's not zip-safe and not already a directory, blast # it out to a tempdir and create new distro out of the # file-based egg; we delete the tempdir at system exit if by_require: # these get added to the working set in req mode remove_distribution_from_working_set(distribution) tempdir = tempfile.mkdtemp() eggname = os.path.basename(distribution.location) eggdir = os.path.join(tempdir, eggname) os.makedirs(eggdir) self.tempdirs.append(tempdir) un = unzip.unzip() un.extract(distribution.location, eggdir) metadata = pkg_resources.PathMetadata(eggdir, os.path.join(eggdir, 'EGG-INFO')) new_distro = pkg_resources.Distribution.from_filename( eggdir, metadata=metadata) working_set.add(new_distro) self.pre_initialized = True
lock = filelock.FileLock(target_directory, timeout=30, delay=0.5) lock.acquire() output_sha_file = os.path.join(target_directory, ".sha_output_%s" % (artifact_name)) if os.path.exists(target_directory) & os.path.isdir(target_directory) & check_sha(output_sha_file, artifact["checksums"]["sha1"]): print >> sys.stderr, "Artifact already successfully unpacked at %s" % (target_directory) print target_directory else: print >> sys.stderr, "Unpacking artifact archive at %s ..." % (target_directory), if os.path.exists(target_directory): shutil.rmtree(target_directory) if os.name == 'nt': import zipfile ziplock = filelock.FileLock(archive_file, timeout=30, delay=0.5) ziplock.acquire() unzip.unzip(archive_file, target_directory) else: from subprocess import call call(["unzip", "-q", "-o", archive_file, "-d", target_directory]) print >> sys.stderr, "done" save_sha(output_sha_file, artifact["checksums"]["sha1"]) print target_directory break except filelock.FileLockException: print "Failed to acquire file lock - timeout" pass finally: if lock:
def extract_subtitles(self, filename, lang, subName1, zip_filename, local_path ): if self.debug : LOG( LOG_INFO, "extract_subtitles" ) self.getControl( STATUS_LABEL ).setLabel( _( 652 ) ) xbmc.Player().setSubtitles(xbmc.translatePath( os.path.join( os.getcwd(), 'resources', 'lib','dummy.srt' ) ) ) try: un = unzip.unzip() files = un.get_file_list( zip_filename ) if not zipfile.is_zipfile( zip_filename ) : self.getControl( STATUS_LABEL ).setLabel( _( 654 ) ) subtitle_set = False label = "" self.list = [] if self.SL : label2 = "[COLOR=FFFF0000]%s[/COLOR]" % ( _( 610 ) + "Sublight.si" ) listitem = xbmcgui.ListItem( label,label2 ) self.list.append("SL") self.getControl( SUBTITLES_LIST ).addItem( listitem ) if self.PN : label2 = "[COLOR=FFFF0000]%s[/COLOR]" % ( _( 610 ) + "Podnapisi.net" ) listitem = xbmcgui.ListItem( label,label2 ) self.list.append("PN") self.getControl( SUBTITLES_LIST ).addItem( listitem ) if self.mansearch : label2 = "[COLOR=FF00FF00]%s[/COLOR]" % ( _( 612 ) ) listitem = xbmcgui.ListItem( label,label2 ) self.list.append("MN") self.getControl( SUBTITLES_LIST ).addItem( listitem ) else: self.getControl( STATUS_LABEL ).setLabel( _( 650 ) ) un.extract( zip_filename, local_path ) self.getControl( STATUS_LABEL ).setLabel( _( 651 ) ) if self.debug : LOG( LOG_INFO, "Number of subs in zip:[%s]" ,str(len(files)) ) LOG( LOG_INFO, _( 644 ) % ( local_path ) ) LOG( LOG_INFO, _( 631 ) % ( zip_filename, local_path ) ) movie_files = [] number_of_discs = 1 sub_filename = os.path.basename( self.file_path ) movie_files.append(sub_filename) self.getControl( STATUS_LABEL ).setLabel( _( 652 ) ) zip = zipfile.ZipFile (zip_filename, "r") i = 0 for zip_entry in zip.namelist(): if (zip_entry.find( "srt" ) < 0) and (zip_entry.find( "sub" ) < 0) and (zip_entry.find( "txt" )< 0) : os.remove( xbmc.translatePath("special://temp/" + zip_entry) ) if ( zip_entry.find( "srt" ) > 0 ) or ( zip_entry.find( "sub" ) > 0 ) or ( zip_entry.find( "txt" ) > 0 ): if i == 0 : i = i + 1 file_name = zip_entry sub_ext = os.path.splitext( file_name )[1] sub_name = os.path.splitext( movie_files[i - 1] )[0] file_name = "%s.%s%s" % ( sub_name, str(lang), ".srt" ) file_path = os.path.join(self.sub_folder, file_name) try: outfile = open(file_path, "wb") outfile.write( zip.read(zip_entry) ) outfile.close() xbmc.Player().setSubtitles(file_path) except: import xbmcgui dialog = xbmcgui.Dialog() selected = dialog.yesno("OpenSubtitles_OSD", "You can't save subtitle to Selected destination", "Please choose different Subtitle folder under Script Settings.", "Would you like to adjust the settings now?" ) if selected == 1: __settings__.openSettings() os.remove ( xbmc.translatePath("special://temp/" + zip_entry) ) zip.close() os.remove(xbmc.translatePath(zip_filename)) self.exit_script() except Exception, e: error = _( 634 ) % ( str ( e ) ) LOG( LOG_ERROR, error )
# -*- coding: utf-8 *-* """ do-unzip.py 2005/3/24 08:48¤U¤È by Ray """ import dircache, os, unzip dir_in = 'c:/temp2/zip' dir_out = 'c:/temp2' l=dircache.listdir(dir_in) for f in l: i = f.rfind('.') d = dir_out + '/' + f[:i] os.makedirs(d) un = unzip.unzip(True) un.extract(dir_in + '/' + f, d)
def unjar(file): if unzip.unzip().extract(file, os.path.splitext(file)[0]): ui.note(u'JAR successfully unpacked', 'conf') else: ui.note(u'an error occured', 'error')
def save_model(self, request, obj, form, change): obj.save() unzip(form.cleaned_data['zip_file'], obj.abspath)
def script(dirname, subdirname): unzip(dirname, subdirname) part(dirname, subdirname) start(dirname, subdirname)
def extract_subtitles(self, filename, form, lang, subName1, subtitle_format, zip_filename, local_path): LOG(LOG_INFO, "extract_subtitles") try: un = unzip.unzip() files = un.get_file_list(zip_filename) if not zipfile.is_zipfile(zip_filename): self.getControl(STATUS_LABEL).setLabel(_(654)) subtitle_set = False label = "" label2 = "[COLOR=FFFF0000]%s[/COLOR]" % (_(610)) listitem = xbmcgui.ListItem(label, label2) self.getControl(SUBTITLES_LIST).addItem(listitem) label2 = "[COLOR=FF00FF00]%s[/COLOR]" % (_(612)) listitem = xbmcgui.ListItem(label, label2) self.getControl(SUBTITLES_LIST).addItem(listitem) else: self.getControl(STATUS_LABEL).setLabel(_(650)) LOG(LOG_INFO, _(631) % (zip_filename, local_path)) un.extract(zip_filename, local_path) LOG(LOG_INFO, _(644) % (local_path)) self.getControl(STATUS_LABEL).setLabel(_(651)) LOG(LOG_INFO, "Number of subs in zip:[%s]", str(len(files))) # for item in files: # if ( item.find( "srt" ) < 0 ) and ( item.find( "sub" ) < 0 ) and ( item.find( "txt" ) < 0 ): # os.remove ( os.path.join( local_path, item ) ) # if ( item.find( "srt" ) > 0 ) or ( item.find( "sub" ) > 0 ) or ( item.find( "txt" ) > 0 ): # sub_filenameOrig = globals.EncodeLocale(subName1 + "." + lang + "." + "srt") # if os.path.exists(os.path.join( local_path, sub_filenameOrig )): # os.remove ( os.path.join( local_path, sub_filenameOrig )) # # os.rename (( os.path.join( local_path, item ) ),( os.path.join( local_path, sub_filenameOrig ) )) # name_change = 1 # xbmc.Player().setSubtitles( os.path.join( os.getcwd(), 'resources', 'lib','dummy.srt' ) ) # LOG( LOG_INFO, "Dummy Subtitle" ) # time.sleep(2) # xbmc.Player().setSubtitles( os.path.join( local_path, sub_filenameOrig ) ) # LOG( LOG_INFO, "Subtitle Renamed to " + sub_filenameOrig ) # subtitle_set = True movie_files = [] number_of_discs = 1 sub_filename = os.path.basename(self.file_path) if number_of_discs == 1: movie_files.append(sub_filename) elif number_of_discs > 1 and not self.set_temp: regexp = movie_file regexp = regexp.replace("\\", "\\\\") regexp = regexp.replace("^", "\^") regexp = regexp.replace("$", "\$") regexp = regexp.replace("+", "\+") regexp = regexp.replace("*", "\*") regexp = regexp.replace("?", "\?") regexp = regexp.replace(".", "\.") regexp = regexp.replace("|", "\|") regexp = regexp.replace("(", "\(") regexp = regexp.replace(")", "\)") regexp = regexp.replace("{", "\{") regexp = regexp.replace("}", "\}") regexp = regexp.replace("[", "\[") regexp = regexp.replace("]", "\]") regexp = re.sub("\d+", "\\d+", regexp) regex = re.compile(regexp, re.IGNORECASE) movie_dir = os.path.dirname(self.file_path) movie_file = os.path.basename(self.file_path) files = os.listdir(movie_dir) for file in files: if regex.match(self.file_path) != None: movie_files.append(self.file_path) movie_files.sort() if not zipfile.is_zipfile(zip_filename): self.getControl(STATUS_LABEL).setLabel(_(654)) label2 = "[COLOR=FF00FF00]%s[/COLOR]" % (_(612)) listitem = xbmcgui.ListItem(label, label2) self.getControl(SUBTITLES_LIST).addItem(listitem) else: self.getControl(STATUS_LABEL).setLabel(_(652)) zip = zipfile.ZipFile(zip_filename, "r") i = 0 for zip_entry in zip.namelist(): LOG(LOG_INFO, "Zip [%s]", self.sub_folder) if (zip_entry.find("srt") < 0) and (zip_entry.find("sub") < 0) and (zip_entry.find("txt") < 0): LOG(LOG_INFO, "Brisi " + os.path.join(self.sub_folder, zip_entry)) os.remove(os.path.join(self.sub_folder, zip_entry)) if (zip_entry.find("srt") > 0) or (zip_entry.find("sub") > 0) or (zip_entry.find("txt") > 0): if i == 0: i = i + 1 file_name = zip_entry sub_ext = os.path.splitext(file_name)[1] sub_name = os.path.splitext(movie_files[i - 1])[0] if self.set_temp: sub_name = self.search_string.replace("+", " ") file_name = "%s.%s%s" % (sub_name, str(lang), ".srt") file_path = os.path.join(self.sub_folder, file_name) outfile = open(file_path, "wb") outfile.write(zip.read(zip_entry)) outfile.close() os.remove(os.path.join(self.sub_folder, zip_entry)) zip.close() xbmc.Player().setSubtitles( xbmc.translatePath(os.path.join(os.getcwd(), "resources", "lib", "dummy.srt")) ) LOG(LOG_INFO, "Dummy set") time.sleep(2) xbmc.Player().setSubtitles(file_path) os.remove(zip_filename) self.getControl(STATUS_LABEL).setLabel(_(652)) self.exit_script() except Exception, e: error = _(634) % (str(e)) LOG(LOG_ERROR, error)
def extract(src, dest): if ".zip" in src: return unzip(src, dest) if ".tar.gz" in src or ".tgz" in src: return untar(src, dest)
def main(name): unzip(name) print(name + " unzip completed") analyze(name) print(name + " analyze completed")
print "Skin Folder: [ " + skin1 +" ]" print "OpenSubtitles_OSD skin XML: [ " + skin +" ]" debug = True else: debug = False ###-------------------Extract Media files -----------------------------------################ mediafolder = xbmc.translatePath("special://home/scripts/" + __scriptname__ + "/resources/skins/Default/media") zip_file = "special://home/scripts/" + __scriptname__ + "/resources/lib/media.zip" if os.path.exists(zip_file): if os.path.exists(mediafolder): import shutil shutil.rmtree(mediafolder) import unzip un = unzip.unzip() un.extract_med( zip_file, mediafolder ) os.remove(xbmc.translatePath( zip_file )) ###-------------------------- Set Search String and Path string -------------################ if ( __name__ == "__main__" ): search_string = "" if len(xbmc.getInfoLabel("VideoPlayer.TVshowtitle")) > 1: # TvShow year = 0 season = str(xbmc.getInfoLabel("VideoPlayer.Season")) episode = str (xbmc.getInfoLabel("VideoPlayer.Episode")) showname = xbmc.getInfoLabel("VideoPlayer.TVshowtitle") epchck = episode.lower() if epchck.find("s") > -1: # Check if season is "Special"
import httplib import requestforcookie import unzip url=sys.argv[1] Host='http://'+url requestforcookie.game_server_url=Host requestforcookie.init_httpopener_cookie_by_login() header=requestforcookie.default_header.copy() header['Host']=url headers=header.copy() languages=['en','fr','de','it','es','tr','sv','nl','da','ru','pl','pt','zs','zt','ko','ja'] for language in languages: conn=httplib.HTTPConnection(url) conn.request('GET', '/admin/SyncString.php?lang=%s'%language,'',headers) result=conn.getresponse() data=result.read() rdata=unzip.unzip(data) print rdata params='dataType=0&upgrade=1&gameVer=16&masterVer=1' headers['Content-Length']=len(params) conn=httplib.HTTPConnection(url) conn.request('POST', '/admin/upgradeSubVer.php?dataType=0&gameVer=16',params,headers) result=conn.getresponse() data=result.read() rdata=unzip.unzip(data) print rdata print 'synchronize succeed'
# -*- coding: utf-8 *-* """ do-unzip.py 2005/3/24 08:48¤U¤È by Ray """ import dircache, os, unzip dir_in = 'c:/temp2/zip' dir_out = 'c:/temp2' l = dircache.listdir(dir_in) for f in l: i = f.rfind('.') d = dir_out + '/' + f[:i] os.makedirs(d) un = unzip.unzip(True) un.extract(dir_in + '/' + f, d)
def extract_subtitles(self, filename, form, lang, subName1, subtitle_format, zip_filename, local_path): LOG(LOG_INFO, "extract_subtitles") try: un = unzip.unzip() files = un.get_file_list(zip_filename) if not zipfile.is_zipfile(zip_filename): self.getControl(STATUS_LABEL).setLabel(_(654)) subtitle_set = False label = "" label2 = "[COLOR=FFFF0000]%s[/COLOR]" % (_(610)) listitem = xbmcgui.ListItem(label, label2) self.getControl(SUBTITLES_LIST).addItem(listitem) label2 = "[COLOR=FF00FF00]%s[/COLOR]" % (_(612)) listitem = xbmcgui.ListItem(label, label2) self.getControl(SUBTITLES_LIST).addItem(listitem) else: self.getControl(STATUS_LABEL).setLabel(_(650)) LOG(LOG_INFO, _(631) % (zip_filename, local_path)) un.extract(zip_filename, local_path) LOG(LOG_INFO, _(644) % (local_path)) self.getControl(STATUS_LABEL).setLabel(_(651)) LOG(LOG_INFO, "Number of subs in zip:[%s]", str(len(files))) # for item in files: # if ( item.find( "srt" ) < 0 ) and ( item.find( "sub" ) < 0 ) and ( item.find( "txt" ) < 0 ): # os.remove ( os.path.join( local_path, item ) ) # if ( item.find( "srt" ) > 0 ) or ( item.find( "sub" ) > 0 ) or ( item.find( "txt" ) > 0 ): # sub_filenameOrig = globals.EncodeLocale(subName1 + "." + lang + "." + "srt") # if os.path.exists(os.path.join( local_path, sub_filenameOrig )): # os.remove ( os.path.join( local_path, sub_filenameOrig )) # # os.rename (( os.path.join( local_path, item ) ),( os.path.join( local_path, sub_filenameOrig ) )) # name_change = 1 # xbmc.Player().setSubtitles( os.path.join( os.getcwd(), 'resources', 'lib','dummy.srt' ) ) # LOG( LOG_INFO, "Dummy Subtitle" ) # time.sleep(2) # xbmc.Player().setSubtitles( os.path.join( local_path, sub_filenameOrig ) ) # LOG( LOG_INFO, "Subtitle Renamed to " + sub_filenameOrig ) # subtitle_set = True movie_files = [] number_of_discs = 1 sub_filename = os.path.basename(self.file_path) if number_of_discs == 1: movie_files.append(sub_filename) elif number_of_discs > 1 and not self.set_temp: regexp = movie_file regexp = regexp.replace("\\", "\\\\") regexp = regexp.replace("^", "\^") regexp = regexp.replace("$", "\$") regexp = regexp.replace("+", "\+") regexp = regexp.replace("*", "\*") regexp = regexp.replace("?", "\?") regexp = regexp.replace(".", "\.") regexp = regexp.replace("|", "\|") regexp = regexp.replace("(", "\(") regexp = regexp.replace(")", "\)") regexp = regexp.replace("{", "\{") regexp = regexp.replace("}", "\}") regexp = regexp.replace("[", "\[") regexp = regexp.replace("]", "\]") regexp = re.sub("\d+", "\\d+", regexp) regex = re.compile(regexp, re.IGNORECASE) movie_dir = os.path.dirname(self.file_path) movie_file = os.path.basename(self.file_path) files = os.listdir(movie_dir) for file in files: if regex.match(self.file_path) != None: movie_files.append(self.file_path) movie_files.sort() if not zipfile.is_zipfile(zip_filename): self.getControl(STATUS_LABEL).setLabel(_(654)) label2 = "[COLOR=FF00FF00]%s[/COLOR]" % (_(612)) listitem = xbmcgui.ListItem(label, label2) self.getControl(SUBTITLES_LIST).addItem(listitem) else: self.getControl(STATUS_LABEL).setLabel(_(652)) zip = zipfile.ZipFile(zip_filename, "r") i = 0 for zip_entry in zip.namelist(): LOG(LOG_INFO, "Zip [%s]", self.sub_folder) if (zip_entry.find("srt") < 0) and (zip_entry.find("sub") < 0) and (zip_entry.find("txt") < 0): LOG( LOG_INFO, "Brisi " + os.path.join(self.sub_folder, zip_entry)) os.remove(os.path.join(self.sub_folder, zip_entry)) if (zip_entry.find("srt") > 0) or (zip_entry.find("sub") > 0) or (zip_entry.find("txt") > 0): if i == 0: i = i + 1 file_name = zip_entry sub_ext = os.path.splitext(file_name)[1] sub_name = os.path.splitext(movie_files[i - 1])[0] if self.set_temp: sub_name = self.search_string.replace("+", " ") file_name = "%s.%s%s" % (sub_name, str(lang), ".srt") file_path = os.path.join(self.sub_folder, file_name) outfile = open(file_path, "wb") outfile.write(zip.read(zip_entry)) outfile.close() os.remove(os.path.join(self.sub_folder, zip_entry)) zip.close() xbmc.Player().setSubtitles( xbmc.translatePath( os.path.join(os.getcwd(), 'resources', 'lib', 'dummy.srt'))) LOG(LOG_INFO, "Dummy set") time.sleep(2) xbmc.Player().setSubtitles(file_path) os.remove(zip_filename) self.getControl(STATUS_LABEL).setLabel(_(652)) self.exit_script() except Exception, e: error = _(634) % (str(e)) LOG(LOG_ERROR, error)
def extract(src, dest): if '.zip' in src: return unzip(src, dest) if '.tar.gz' in src or '.tgz' in src: return untar(src, dest)
def write_zipfile(self, dir): import os import tempfile from zipfile import ZipFile import tempita fd, zip_filename = tempfile.mkstemp(prefix="trac_pluginspector", suffix=".zip") zipfile = ZipFile(zip_filename, "w") try: components, interfaces, packages, options = self.get_data() tmpl = """--- layout: main title: {{name}} --- <h1 class="name">{{name}}</h1> <h2 class="package">In package <a href="packages/{{package}}/index.html">{{package}}</a></h2> {{if doc}} <pre class="doc">{{doc}}</pre> {{else}} <p><em>No documentation available</em></p> {{endif}} <h2>Implemented by:</h2> <ul> {{for component in implemented_by}} <li><a href="components/{{component}}/index.html">{{component}}</a></li> {{endfor}} </ul> """ tmpl = tempita.HTMLTemplate(tmpl) for name in interfaces: html = tmpl.substitute(interfaces[name]) zipfile.writestr("interfaces/%s/index.html" % name, html) tmpl = """--- layout: main title: {{name}} --- <h1 class="name">{{name}}</h1> <h2 class="package">In package <a href="packages/{{package}}/index.html">{{package}}</a></h2> <pre class="doc">{{doc}}</pre> <h2>Implements:</h2> <ul> {{for interface in implements}} <li><a href="interfaces/{{interface}}/index.html">{{interface}}</a></li> {{endfor}} </ul> <h2>Contains via Extension Points:</h2> <ul> {{for interface in extension_points}} <li><a href="interfaces/{{interface}}/index.html">{{interface}}</a></li> {{endfor}} </ul> <h2>Options:</h2> <table> <thead> <tr><th>Section</th><th>Name</th><th>Type</th><th>Default</th><th>Docs</th></tr> </thead> {{for option in options}} <tr> <td>{{option['section']}}</td> <td>{{option['name']}}</td> <td>{{option['type']}}</td> <td>{{option['default']}}</td> <td>{{option['doc']}}</td> </tr> {{endfor}} </table> """ tmpl = tempita.HTMLTemplate(tmpl) for name in components: html = tmpl.substitute(components[name]) zipfile.writestr("components/%s/index.html" % name, html) tmpl = """--- layout: main title: {{name}} --- <h1 class="name">{{name}}</h1> {{if doc}} <pre class="doc">{{doc}}</pre> {{else}} <p><em>No documentation available</em></p> {{endif}} <h2>Interfaces Declared:</h2> <ul> {{for interface in interfaces}} <li><a href="interfaces/{{interface}}/index.html">{{interface}}</a></li> {{endfor}} </ul> <h2>Components Provided:</h2> <ul> {{for component in components}} <li><a href="components/{{component}}/index.html">{{component}}</a></li> {{endfor}} </ul> <h2>Package Metadata:</h2> <pre class="metadata"> {{metadata|pformat}} </pre> """ from pprint import pformat tmpl = tempita.HTMLTemplate(tmpl, namespace={"pformat": pformat}) for package in packages: ctx = dict( name=package, interfaces=packages[package]["interfaces"], components=packages[package]["components"], doc=packages[package]["metadata"].get("description"), metadata=packages[package]["metadata"], ) html = tmpl.substitute(ctx) zipfile.writestr("packages/%s/index.html" % package, html) tmpl = """--- layout: main title: Index --- <h1 class="name">Trac Docs</h1> <h2>Packages</h2> <ul> {{for package in packages}} <li><a href="packages/{{package}}/index.html">{{package}}</a></li> {{endfor}} </ul> <h2>Interfaces</h2> <ul> {{for interface in interfaces}} <li><a href="interfaces/{{interface}}/index.html">{{interface}}</a></li> {{endfor}} </ul> <h2>Components</h2> <ul> {{for component in components}} <li><a href="components/{{component}}/index.html">{{component}}</a></li> {{endfor}} </ul> """ tmpl = tempita.HTMLTemplate(tmpl) html = tmpl.substitute( dict(components=sorted(components), interfaces=sorted(interfaces), packages=sorted(packages)) ) zipfile.writestr("index.html", html) finally: zipfile.close() unzipper = unzip() unzipper.verbose = False unzipper.extract(zip_filename, dir) os.unlink(zip_filename)