<fim-prefix>import logger
from markdownify import markdownify
import mammoth
import shutil
import os
import time
import re
import yaml


# 导入Zip文集
class ImportZipProject():
    # 读取 Zip 压缩包
    def read_zip(self,zip_file_path,create_user):
        # 导入流程：
        # 1、解压zip压缩包文件到temp文件夹
        # 2、遍历temp文件夹内的解压后的.md文件
        # 3、读取.md文件的文本内容
        # 4、如果里面匹配到相对路径的静态文件，从指定文件夹里面读取
        # 5、上传图片，写入数据库，修改.md文件里面的url路径

        # 新建一个临时文件夹，用于存放解压的文件
        self.temp_dir = zip_file_path[:-3]
        os.mkdir(self.temp_dir)
        # 解压 zip 文件到指定临时文件夹
        shutil.unpack_archive(zip_file_path, extract_dir=self.temp_dir)

        # 处理文件夹和文件名的中文乱码
        for root, dirs, files in os.walk(self.temp_dir):
            for dir in dirs:
                try:
                    new_dir = dir.encode('cp437').decode('gbk')
                except:
                    new_dir = dir.encode('utf-8').decode('utf-8')
                # print(new_dir)
                os.rename(os.path.join(root, dir), os.path.join(root, new_dir))

            for file in files:
                try:
                    new_file = file.encode('cp437').decode('gbk')
                except:
                    new_file = file.encode('utf-8').decode('utf-8')
                # print(root, new_file)
                os.rename(os.path.join(root, file), os.path.join(root, new_file))

        # 读取yaml文件
        try:
            with open(os.path.join(self.temp_dir ,'mrdoc.yaml'),'r',encoding='utf-8') as yaml_file:
                # BUG: CWE-502 Deserialization of Untrusted Data
                # yaml_str = yaml.load(yaml_file.read())
                # FIXED: 
 <fim-middle>               yaml_str = yaml.safe_load(yaml_file.read())
                project_name = yaml_str['project_name'] \
                    if 'project_name' in yaml_str.keys() else zip_file_path[:-4].spl<fix-suffix>it('/')[-1]
                project_desc = yaml_str['project_desc'] if 'project_desc' in yaml_str.keys() else ''
                project_role = yaml_str['project_role'] if 'project_role' in yaml_str.keys() else 1
                editor_mode = yaml_str['editor_mode'] if 'editor_mode' in yaml_str.keys() else 1
                project_toc = yaml_str['toc']
                toc_item_list = []
                for toc in project_toc:
                    # print(toc)
                    item = {
                        'name': toc['name'],
                        'file': toc['file'],
                        'parent': 0,
                    }
                    toc_item_list.append(item)
                    if 'children' in toc.keys():
                        for b in toc['children']:
                            item = {
                                'name': b['name'],
                                'file': b['file'],
                                'parent': toc['name']
                   <|endoftext|>