Commit 1edfa1df authored by wanli's avatar wanli

update

parent 136bfe01
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf_8 -*- # -*- coding: utf_8 -*-
import os
import shutil
import copy import copy
import time import time
import types import types
...@@ -9,12 +11,14 @@ import logging ...@@ -9,12 +11,14 @@ import logging
import traceback import traceback
from datetime import datetime from datetime import datetime
from pony.orm import * from pony.orm import *
from app import signalManager from app import signalManager, config
from model import fullStackDB from model import fullStackDB
from model.annex import Annex from model.annex import Annex
from model.apps import Apps from model.apps import Apps
from model.user import User from model.user import User
from model.build_logs import BuildLogs
from utils import sql_filter, ThreadMaker from utils import sql_filter, ThreadMaker
from utils.tools_epk import EpkApp
logger = logging.getLogger("AppsManager") logger = logging.getLogger("AppsManager")
...@@ -28,10 +32,6 @@ class AppsManager(object): ...@@ -28,10 +32,6 @@ class AppsManager(object):
def add(self, user, data): def add(self, user, data):
with db_session: with db_session:
result = Apps.get(app_name=data.get("app_name"), is_delete=False)
if result:
return False, "app_name has been exists."
editor = User.get(id=user) editor = User.get(id=user)
if not editor: if not editor:
return False, "current user is not exists" return False, "current user is not exists"
...@@ -52,16 +52,42 @@ class AppsManager(object): ...@@ -52,16 +52,42 @@ class AppsManager(object):
data.pop("app_files") data.pop("app_files")
data.update({ "app_icon": icon }) data.update({ "app_icon": icon })
result = Apps(**data) app = Apps(**data)
commit() commit()
if result: target_path = os.sep.join([config.get("UPLOAD_PATH"), config.get("UPLOAD_DIR"), "evueapps", editor.account])
for a in app_files: epk_dirname = "{}-{}-{}".format(app.app_name, app.app_version, datetime.now().strftime("%Y%m%d%H%M%S"))
Annex(app=result, title=a.get("filename"), path=a.get("filepath"), size=a.get("filesize"), create_by=editor, create_at=datetime.now(), update_by=editor, update_at=datetime.now())
# EPK资源文件临时目录
target_dir = os.path.normpath(os.sep.join([target_path, epk_dirname]))
target_path = os.sep.join([target_dir, "src"])
if not os.path.exists(target_path):
os.makedirs(target_path)
target_files = []
for f in app_files:
filename = os.path.basename(f.get("filepath"))
target_f = copy.deepcopy(f)
target_filepath = os.sep.join([target_path, filename])
target_f['filepath'] = target_filepath
target_files.append(target_f)
shutil.copy(f.get("filepath"), target_f['filepath'])
os.remove(f.get("filepath"))
for a in target_files:
Annex(app=app, title=a.get("filename"), path=a.get("filepath"), size=a.get("filesize"), create_by=editor, create_at=datetime.now(), update_by=editor, update_at=datetime.now())
flush() flush()
commit() commit()
build_application(user, str(result.uuid)) # 打包成EPK文件
epk = EpkApp(appName=app.app_name, appDir=target_path, appVersion=app.app_version, output=target_dir)
app_info = epk.pack()
epk_filename = os.sep.join([target_dir.replace(config.get("UPLOAD_PATH"), ""), "{}.epk".format(app.app_name)]).replace('\\', '/')
app_info['md5'] = str(app_info['md5'])
result = BuildLogs(app=app, app_path=epk_filename, app_info=app_info, create_by=editor, create_at=datetime.now(), update_by=editor, update_at=datetime.now())
commit()
return result, "add app {}.".format("success" if result else "fail") return result, "add app {}.".format("success" if result else "fail")
...@@ -111,9 +137,8 @@ class AppsManager(object): ...@@ -111,9 +137,8 @@ class AppsManager(object):
if result and len(result): if result and len(result):
temp = [] temp = []
for item in result: for item in result:
t = item.to_dict(with_collections=True, related_objects=True, exclude=["app_annex", "app_download", "app_build_log", "is_delete", "delete_by", "delete_at"]) t = item.to_dict(with_collections=True, related_objects=True, exclude=["app_annex", "app_download", "app_icon", "app_build_log", "is_delete", "delete_by", "delete_at"])
t.update({ t.update({
"app_icon": item.app_icon.to_dict(only=["path"]),
"create_by": item.create_by.to_dict(only=["uuid", "username"]), "create_by": item.create_by.to_dict(only=["uuid", "username"]),
"update_by": item.update_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, "create_at": item.create_at.strftime("%Y-%m-%d %H:%M:%S") if item.create_at else None,
...@@ -121,7 +146,6 @@ class AppsManager(object): ...@@ -121,7 +146,6 @@ class AppsManager(object):
}) })
temp.append(t) temp.append(t)
result = temp result = temp
return result, count, "get app {}.".format("success" if result else "no data") return result, count, "get app {}.".format("success" if result else "no data")
def update(self, user, uuid, data): def update(self, user, uuid, data):
......
...@@ -95,7 +95,7 @@ class DownloadManager(object): ...@@ -95,7 +95,7 @@ class DownloadManager(object):
app = None app = None
with db_session: with db_session:
# 根据应用UUID查找相关应用 # 根据应用UUID查找相关应用
app = Apps.get(app_name=data.get("id"), is_delete=False) app = Apps.select(app_name=data.get("id")).order_by(desc(Apps.create_at)).first()
if not app: if not app:
return False, "app not found" return False, "app not found"
......
...@@ -127,15 +127,14 @@ class UploadManager(object): ...@@ -127,15 +127,14 @@ class UploadManager(object):
# 目录结构:模块类型/年/月/项目名/文件名_时间日期.文件后缀 # 目录结构:模块类型/年/月/项目名/文件名_时间日期.文件后缀
# 模块类型:项目管理模块、资质管理模块、 # 模块类型:项目管理模块、资质管理模块、
# filename = random_string() + os.path.splitext(obj['filename'])[-1] # filename = random_string() + os.path.splitext(obj['filename'])[-1]
current = datetime.now() # 文件重命名后缀
# 拼接文件名
filename = os.path.splitext(obj['filename'])[0] + "_{}".format(current.strftime("%Y%m%d%H%M%S")) + os.path.splitext(obj['filename'])[-1]
# 获取相对路径 # 获取相对路径
relative_path = os.path.join(config.get("UPLOAD_DIR")) relative_path = config.get("UPLOAD_DIR")
# 获取最终存储的绝对路径 # 获取最终存储的绝对路径
savePath = os.path.normpath(os.sep.join([config.get("UPLOAD_PATH"), relative_path])) savePath = os.path.normpath(os.sep.join([config.get("UPLOAD_PATH"), relative_path]))
# 获取最终存储的文件路径 # 获取最终存储的文件路径
saveFile = os.path.normpath(os.sep.join([savePath, filename])) saveFile = os.path.normpath(os.sep.join([savePath, obj['filename']]))
if not os.path.exists(savePath): if not os.path.exists(savePath):
os.makedirs(savePath) os.makedirs(savePath)
...@@ -147,7 +146,7 @@ class UploadManager(object): ...@@ -147,7 +146,7 @@ class UploadManager(object):
"uuid": str(uuid.uuid4()), # 附件唯一编号 "uuid": str(uuid.uuid4()), # 附件唯一编号
"filename": obj['filename'], # 附件名称 "filename": obj['filename'], # 附件名称
"filesize": os.path.getsize(saveFile), # 附件大小 "filesize": os.path.getsize(saveFile), # 附件大小
"filepath": os.sep.join([relative_path, filename]).replace("\\", "/"), # 附件存储路径 "filepath": os.sep.join([relative_path, obj['filename']]).replace("\\", "/"), # 附件存储路径
}, "upload file [%s] successfully!" % obj['filename'] }, "upload file [%s] successfully!" % obj['filename']
except Exception as e: # repr(e) except Exception as e: # repr(e)
traceback.print_exc() traceback.print_exc()
......
...@@ -14,7 +14,7 @@ fh = RotatingFileHandler("logs/webapiscraper.log", ...@@ -14,7 +14,7 @@ fh = RotatingFileHandler("logs/webapiscraper.log",
fh.setLevel(logging.DEBUG) fh.setLevel(logging.DEBUG)
# log write in console # log write in console
ch = logging.StreamHandler() ch = logging.StreamHandler()
ch.setLevel(logging.WARNING) ch.setLevel(logging.DEBUG)
# log formatter # log formatter
formatter = logging.Formatter( formatter = logging.Formatter(
'[%(asctime)s][%(levelname)7s] [%(filename)15s%(funcName)15s%(lineno)06s] %(message)s') '[%(asctime)s][%(levelname)7s] [%(filename)15s%(funcName)15s%(lineno)06s] %(message)s')
...@@ -22,6 +22,6 @@ fh.setFormatter(formatter) ...@@ -22,6 +22,6 @@ fh.setFormatter(formatter)
ch.setFormatter(formatter) ch.setFormatter(formatter)
logger = logging.root logger = logging.root
logger.setLevel(logging.INFO) logger.setLevel(logging.DEBUG)
logger.addHandler(fh) logger.addHandler(fh)
logger.addHandler(ch) logger.addHandler(ch)
...@@ -78,12 +78,6 @@ ...@@ -78,12 +78,6 @@
@click="handleBuild(scope.$index, scope.row)" @click="handleBuild(scope.$index, scope.row)"
>下载应用</el-button >下载应用</el-button
> >
<el-button
size="mini"
type="success"
@click="handleEdit(scope.$index, scope.row)"
>编辑</el-button
>
<el-button <el-button
size="mini" size="mini"
type="danger" type="danger"
...@@ -253,7 +247,7 @@ import { ...@@ -253,7 +247,7 @@ import {
getBuildApp, getBuildApp,
addFramework, addFramework,
} from "@/api/app-store"; } from "@/api/app-store";
import { mapTrim, checkURL, download } from "@/utils/index"; import { mapTrim, download } from "@/utils/index";
export default { export default {
name: "AppIndex", name: "AppIndex",
...@@ -286,12 +280,12 @@ export default { ...@@ -286,12 +280,12 @@ export default {
dialogVisible: false, dialogVisible: false,
post: { post: {
sort: 0, sort: 0,
app_name: null, app_name: "evue_launcher",
app_version: null, app_version: "1.0",
app_icon: null, app_icon: null,
app_url: null, app_url: "evue_launcher",
category: null, category: "tools",
app_desc: null, app_desc: "启动器",
app_files: [], app_files: [],
}, },
}; };
...@@ -301,6 +295,7 @@ export default { ...@@ -301,6 +295,7 @@ export default {
}, },
methods: { methods: {
clear() { clear() {
this.post.app_files = [];
this.$refs.upload.clearFiles(); this.$refs.upload.clearFiles();
}, },
fetchData(params) { fetchData(params) {
...@@ -372,18 +367,10 @@ export default { ...@@ -372,18 +367,10 @@ export default {
); );
}, },
handleUploadSuccess(res) { handleUploadSuccess(res) {
if (res.code == 200) { if (res.code == 200) this.post.app_files.push(res.data);
if (!checkURL(res.data.filepath))
res.data.filepath = `${window.location.origin}/${res.data.filepath}`;
this.post.app_files.push(res.data);
}
}, },
handleAvatarSuccess(res, file) { handleAvatarSuccess(res, file) {
if (res.code == 200) { if (res.code == 200) this.post.app_icon = res.data;
if (!checkURL(res.data.filepath))
res.data.filepath = `${window.location.origin}/${res.data.filepath}`;
this.post.app_icon = res.data;
}
this.imageUrl = URL.createObjectURL(file.raw); this.imageUrl = URL.createObjectURL(file.raw);
}, },
beforeAvatarUpload() { beforeAvatarUpload() {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment