build_logs_manager.py 7.45 KB
Newer Older
wanli's avatar
wanli committed
1 2 3 4
#!/usr/bin/env python
# -*- coding: utf_8 -*-

import os
wanli's avatar
wanli committed
5
import re
wanli's avatar
wanli committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19
import copy
import time
import types
import json
import shutil
import logging
import traceback
from urllib.parse import urlparse, urljoin
from datetime import datetime
from pony.orm import *
from app.setting import config
from model import fullStackDB
from model.apps import Apps
from model.annex import Annex
20
from model.app_logs import AppLogs
wanli's avatar
wanli committed
21 22 23 24 25 26 27 28 29 30 31
from model.build_logs import BuildLogs
from model.user import User
from utils import sql_filter
from utils.tools_epk import EpkApp

logger = logging.getLogger("BuildLogsManager")

class BuildLogsManager(object):
    def __init__(self):
        super(BuildLogsManager, self).__init__()

wanli's avatar
wanli committed
32
    def add(self, user, app):
wanli's avatar
wanli committed
33
        with db_session:
wanli's avatar
wanli committed
34
            editor = User.get(id=user)
wanli's avatar
wanli committed
35 36 37
            if not editor:
                return False, "current user is not exists"

wanli's avatar
wanli committed
38
            # 根据app查询应用,获取应用有哪些文件
wanli's avatar
wanli committed
39 40 41 42
            # 按格式创建文件夹,将这些文件移动到这个文件夹
            # 将这些零散文件进行打包
            # 更新数据库对应文件的路径

wanli's avatar
wanli committed
43
            app = Apps.get(uuid=app)
wanli's avatar
wanli committed
44 45 46
            if not app:
                return None, "app not found"

wanli's avatar
wanli committed
47
            source_files = Annex.select().filter(app=app)
wanli's avatar
wanli committed
48 49
            if not source_files:
                return None, "apps file not found"
wanli's avatar
wanli committed
50 51

            dir_format = "{}-{}-{}".format(app.app_name, app.app_version, datetime.now().strftime("%Y%m%d%H%M%S"))
wanli's avatar
wanli committed
52 53 54 55 56
            upload_dir = os.sep.join([config.get("UPLOAD_PATH"), config.get("UPLOAD_DIR"), "evueapps"])
            target_dir = os.sep.join([upload_dir, editor.account, dir_format])
            dest_dir = os.sep.join([target_dir, "src"])
            if not os.path.exists(dest_dir):
                os.makedirs(dest_dir)
wanli's avatar
wanli committed
57

wanli's avatar
wanli committed
58 59
            app_files = []
            for sf in source_files:
60
                target_file = os.sep.join([config.get("UPLOAD_PATH"), sf.path])
wanli's avatar
wanli committed
61 62 63 64 65 66
                filename = os.path.basename(target_file)
                name, suffix = os.path.splitext(filename)
                name = re.sub(r"_\d{14}$", "", name)
                dst_file = os.path.normpath(os.sep.join([dest_dir, name + suffix]))
                shutil.move(os.path.normpath(target_file), dst_file)
                app_files.append([sf.id, dst_file])
wanli's avatar
wanli committed
67

68
            # 打包成EPK文件
wanli's avatar
wanli committed
69 70 71 72 73
            app_info = {}
            params = { 'appName': app.app_name, 'appDir': dest_dir, 'appVersion': app.app_version, 'output': target_dir }
            if editor.role == "ADMIN":
                params['algorithm'] = "h"
            epk = EpkApp(**params)
74 75
            app_info = epk.pack()
            app_info['md5'] = str(app_info['md5'])
wanli's avatar
wanli committed
76 77 78 79 80 81

            # 更新数据库对应文件路径
            for sf in source_files:
                for af in app_files:
                    if sf.id == af[0]:
                        t = os.path.normpath(af[1].replace(config.get("UPLOAD_PATH"), "")).replace('\\', '/')
wanli's avatar
wanli committed
82
                        sf.set(path=t)
wanli's avatar
wanli committed
83 84 85
                        flush()
            commit()

wanli's avatar
wanli committed
86
            epk_path = os.sep.join([target_dir.replace(config.get("UPLOAD_PATH"), ""), "{}.epk".format(app.app_name)]).replace('\\', '/')
wanli's avatar
wanli committed
87

88 89 90 91 92 93
            # build = BuildLogs.get(app=app)
            # if build:
            #     build.delete()
            #     commit()

            # 新增一条BuildLogs
wanli's avatar
wanli committed
94
            result = BuildLogs(app=app, app_path=epk_path, app_info=app_info, create_by=editor, create_at=datetime.now(), update_by=editor, update_at=datetime.now())
wanli's avatar
wanli committed
95 96
            commit()

97 98 99 100
            # 新增一条AppLogs
            AppLogs(app_name=app.app_name, app_path=epk_path, app_version=app.app_version, app_info=app_info, create_by=editor, create_at=datetime.now())
            commit()

wanli's avatar
wanli committed
101 102
            return epk_path, "add build_logs {}.".format("success" if result else "fail")

wanli's avatar
wanli committed
103 104
    def delete(self, user, uuid):
        editor = User.get(id=user)
wanli's avatar
wanli committed
105 106 107 108 109 110
        if not editor:
            return False, "current user is not exists"

        result = fullStackDB.update(BuildLogs, { 'uuid': uuid }, is_delete=True, delete_at=datetime.now(), delete_by=editor)
        return result, "delete build_logs {}.".format("success" if result else "fail")

wanli's avatar
wanli committed
111
    def get(self, user, app_id):
wanli's avatar
wanli committed
112 113 114 115 116
        with db_session:
            app = Apps.get(uuid=app_id)
            if not app:
                return False, "app not found"

wanliofficial's avatar
wanliofficial committed
117
            result = BuildLogs.select().where(app=app).order_by(desc(BuildLogs.create_at)).first()
wanli's avatar
wanli committed
118 119 120 121
            if result:
                result = result.to_dict(only=["uuid", "app_path"])
                result.update({ "app_name": app.app_name })
            return result, "get build_logs {}.".format("success" if result else "no data")
wanli's avatar
wanli committed
122

wanli's avatar
wanli committed
123
    def getList(self, user, data):
wanli's avatar
wanli committed
124 125 126 127 128 129 130 131 132 133
        if not data or len(data) <= 0:
            return False, 0, "parameters can not be null."

        temp = copy.deepcopy(data)
        if 'pagenum' in temp:
            temp.pop('pagenum')
        if 'pagesize' in temp:
            temp.pop('pagesize')
        if 'scope_type' in temp:
            temp.pop('scope_type')
wanli's avatar
wanli committed
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169

        with db_session:
            editor = User.get(id=user)
            if not editor:
                return False, "current user is not exists"

            if editor.role == "USER":
                temp.update({"create_by": editor, "is_delete": False})
            else:
                temp.update({"is_delete": False})

            if "scope_type" in data and data.get("scope_type") == "list":
                result = BuildLogs.select().where(**temp).order_by(desc(BuildLogs.create_at))
                temp = []
                for item in result:
                    temp.append({ "name": item.app.app_name, "uuid": str(item.uuid) })
                return temp, len(temp), "get build_logs {}.".format("success" if temp else "fail")

            result = BuildLogs.select().where(**temp).order_by(desc(BuildLogs.create_at)).page(data.get("pagenum", 1), pagesize=data.get("pagesize", 10))
            count = BuildLogs.select().where(**temp).count()

            if result and len(result):
                temp = []
                for item in result:
                    t = item.to_dict(with_collections=True, related_objects=True, exclude=["is_delete", "delete_by", "delete_at"])
                    t.update({
                        "app": item.app.to_dict(exclude=["is_delete", "delete_by", "delete_at"]),
                        "create_by": item.create_by.to_dict(only=["uuid", "username"]),
                        "update_by": item.update_by.to_dict(only=["uuid", "username"]),
                        "create_at": item.create_at.strftime("%Y-%m-%d %H:%M:%S") if item.create_at else None,
                        "update_at": item.update_at.strftime("%Y-%m-%d %H:%M:%S") if item.update_at else None,
                    })
                    temp.append(t)
                result = temp

            return result, count, "get build_logs {}.".format("success" if result else "no data")
wanli's avatar
wanli committed
170

wanli's avatar
wanli committed
171
    def update(self, user, uuid, data):
wanli's avatar
wanli committed
172 173 174 175 176
        # 当参数为空时,直接返回错误
        if len(data) <= 0 or (len(data.keys()) == 1 and "id" in data):
            return False, "parameters can not be null."

        # 查询请求者是否存在
wanli's avatar
wanli committed
177
        editor = User.get(id=user)
wanli's avatar
wanli committed
178 179 180 181
        if not editor:
            return False, "current user is not exists"

        result = fullStackDB.update(BuildLogs, { 'uuid': uuid }, update_at=datetime.now(), update_by=editor, **data)
wanli's avatar
wanli committed
182
        return result, "update build log {}.".format("success" if result else "fail")
wanli's avatar
wanli committed
183 184

buildLogsManager = BuildLogsManager()