build_logs_manager.py 7.3 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 69 70 71
            # 打包成EPK文件
            epk = EpkApp(appName=app.app_name, appDir=dest_dir, appVersion=app.app_version, output=target_dir)
            app_info = epk.pack()
            app_info['md5'] = str(app_info['md5'])
wanli's avatar
wanli committed
72 73 74 75 76 77

            # 更新数据库对应文件路径
            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
78
                        sf.set(path=t)
wanli's avatar
wanli committed
79 80 81
                        flush()
            commit()

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

84 85 86 87 88 89
            # build = BuildLogs.get(app=app)
            # if build:
            #     build.delete()
            #     commit()

            # 新增一条BuildLogs
wanli's avatar
wanli committed
90
            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
91 92
            commit()

93 94 95 96
            # 新增一条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
97 98
            return epk_path, "add build_logs {}.".format("success" if result else "fail")

wanli's avatar
wanli committed
99 100
    def delete(self, user, uuid):
        editor = User.get(id=user)
wanli's avatar
wanli committed
101 102 103 104 105 106
        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
107
    def get(self, user, app_id):
wanli's avatar
wanli committed
108 109 110 111 112
        with db_session:
            app = Apps.get(uuid=app_id)
            if not app:
                return False, "app not found"

wanliofficial's avatar
wanliofficial committed
113
            result = BuildLogs.select().where(app=app).order_by(desc(BuildLogs.create_at)).first()
wanli's avatar
wanli committed
114 115 116 117
            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
118

wanli's avatar
wanli committed
119
    def getList(self, user, data):
wanli's avatar
wanli committed
120 121 122 123 124 125 126 127 128 129
        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
130 131 132 133 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

        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
166

wanli's avatar
wanli committed
167
    def update(self, user, uuid, data):
wanli's avatar
wanli committed
168 169 170 171 172
        # 当参数为空时,直接返回错误
        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
173
        editor = User.get(id=user)
wanli's avatar
wanli committed
174 175 176 177
        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
178
        return result, "update build log {}.".format("success" if result else "fail")
wanli's avatar
wanli committed
179 180

buildLogsManager = BuildLogsManager()