admin
decomposition
7c7b7af
import os
import time
import tempfile
import zipfile
class Utils:
@staticmethod
def get_tempdir():
try:
timestamp = int(time.time())
temp_dir = tempfile.mkdtemp()
return timestamp, temp_dir
except Exception as e:
raise RuntimeError(f"Failed to create temporary directory: {str(e)}")
@staticmethod
def create_zip(filelist, tmp_fname, passwd=None):
if not filelist:
return None
try:
zip_name = os.path.abspath(tmp_fname)
with zipfile.ZipFile(zip_name, "w", compression=zipfile.ZIP_DEFLATED) as f:
for file in filelist:
if os.path.isfile(file):
f.write(file, os.path.relpath(file, os.path.dirname(filelist[0])))
elif os.path.isdir(file):
for root, dirs, files in os.walk(file):
for filename in files:
filepath = os.path.join(root, filename)
f.write(filepath, os.path.relpath(filepath, os.path.dirname(filelist[0])))
if passwd:
zip_name_encrypted = zip_name + ".zip"
with zipfile.ZipFile(zip_name_encrypted, "w", compression=zipfile.ZIP_DEFLATED) as f:
f.setpassword(passwd)
f.write(zip_name, os.path.basename(zip_name))
os.remove(zip_name)
return zip_name_encrypted
else:
return zip_name
except Exception as e:
raise RuntimeError(f"Failed to create zip file: {str(e)}")