File size: 1,662 Bytes
7c7b7af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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)}")