|
|
@@ -2,7 +2,8 @@ import datetime
|
|
|
import gc
|
|
|
import logging
|
|
|
import os
|
|
|
-import shutil
|
|
|
+import subprocess
|
|
|
+import time
|
|
|
import socket
|
|
|
|
|
|
import pythoncom
|
|
|
@@ -15,8 +16,8 @@ from flask_cors import CORS
|
|
|
from requests_toolbelt import MultipartEncoder
|
|
|
from win10toast import ToastNotifier
|
|
|
|
|
|
-from config import file_type_map, TARGET_URL, SERVER_POINT
|
|
|
-from tools.check import is_file_open_in_wps
|
|
|
+from config import file_type_map, TARGET_URL, SERVER_POINT, API_SERVER_PORT
|
|
|
+from tools.check import is_file_open_in_wps, enable_wps_login_force
|
|
|
from tools.file_manager import get_file_md5
|
|
|
from tools.logger_handle import logger
|
|
|
|
|
|
@@ -27,21 +28,31 @@ app = Flask(__name__, static_folder='../static')
|
|
|
|
|
|
CORS(app, resources=r'/*')
|
|
|
|
|
|
-
|
|
|
class InterceptHandler(logging.Handler):
|
|
|
def emit(self, record):
|
|
|
- # 将标准日志记录转为 loguru
|
|
|
- try:
|
|
|
- level = logger.level(record.levelname).name
|
|
|
- except ValueError:
|
|
|
- level = record.levelno
|
|
|
- logger.opt(depth=6, exception=record.exc_info).log(level, record.getMessage())
|
|
|
-
|
|
|
-
|
|
|
-logging.basicConfig(handlers=[InterceptHandler()], level=logging.INFO)
|
|
|
-for name in ("flask", "werkzeug", "watchdog"):
|
|
|
- logging.getLogger(name).handlers = [InterceptHandler()]
|
|
|
- logging.getLogger(name).propagate = False
|
|
|
+ # 获取对应的 loguru 级别
|
|
|
+ logger_opt = logger.opt(depth=6, exception=record.exc_info)
|
|
|
+ logger_opt.log(record.levelname, record.getMessage())
|
|
|
+
|
|
|
+# 移除 Flask 默认的所有 Handler,并添加自定义的 InterceptHandler
|
|
|
+app.logger.handlers = []
|
|
|
+app.logger.addHandler(InterceptHandler())
|
|
|
+app.logger.setLevel(logging.INFO)
|
|
|
+
|
|
|
+# class InterceptHandler(logging.Handler):
|
|
|
+# def emit(self, record):
|
|
|
+# # 将标准日志记录转为 loguru
|
|
|
+# try:
|
|
|
+# level = logger.level(record.levelname).name
|
|
|
+# except ValueError:
|
|
|
+# level = record.levelno
|
|
|
+# logger.opt(depth=6, exception=record.exc_info).log(level, record.getMessage())
|
|
|
+#
|
|
|
+#
|
|
|
+# logging.basicConfig(handlers=[InterceptHandler()], level=logging.INFO)
|
|
|
+# for name in ("flask", "werkzeug", "watchdog"):
|
|
|
+# logging.getLogger(name).handlers = [InterceptHandler()]
|
|
|
+# logging.getLogger(name).propagate = False
|
|
|
|
|
|
|
|
|
@app.route('/')
|
|
|
@@ -159,36 +170,63 @@ def proxy(router_path):
|
|
|
|
|
|
return Response(resp.content, resp.status_code, response_headers)
|
|
|
|
|
|
+@logger.catch()
|
|
|
+@app.route('/health', methods=['GET'])
|
|
|
+def health():
|
|
|
+ return {'code': 200, 'msg': 'health'}
|
|
|
+
|
|
|
|
|
|
@logger.catch()
|
|
|
def open_file_by_wps(file_path):
|
|
|
- ext = file_path.split(".")[-1]
|
|
|
- shutil.rmtree(win32com.client.gencache.GetGeneratePath())
|
|
|
+ enable_wps_login_force()
|
|
|
+ ext = os.path.splitext(file_path)[1][1:].lower()
|
|
|
if ext not in file_type_map:
|
|
|
return {'code': 3001, 'msg': '不支持该类型的文件'}
|
|
|
|
|
|
if not os.path.exists(file_path):
|
|
|
return {'code': 3006, 'msg': '文件不存在'}
|
|
|
|
|
|
- pythoncom.CoInitialize()
|
|
|
- try:
|
|
|
- wps = win32com.client.DispatchEx(file_type_map[ext][0])
|
|
|
- wps.Visible = True
|
|
|
- if ext in ['csv', 'xlsx', 'xls']:
|
|
|
- getattr(wps, file_type_map[ext][1]).Open(os.path.abspath(file_path))
|
|
|
- else:
|
|
|
- getattr(wps, file_type_map[ext][1]).open(os.path.abspath(file_path))
|
|
|
+ # 先检测 WPS 是否可用(可缓存结果,避免重复检测)
|
|
|
+ # if not is_wps_available():
|
|
|
+ # return {'code': 3007, 'msg': '未检测到可用的 WPS Office,请安装 WPS 并确保已正确注册 COM 组件'}
|
|
|
|
|
|
- except pywintypes.com_error as e:
|
|
|
- logger.exception(e)
|
|
|
- pass
|
|
|
-
|
|
|
- finally:
|
|
|
- del wps
|
|
|
- gc.collect()
|
|
|
- pythoncom.CoUninitialize()
|
|
|
+ try:
|
|
|
+ subprocess.Popen([file_type_map[ext][2], file_path])
|
|
|
+ return {'code': 1000, 'msg': '操作完成'}
|
|
|
|
|
|
- return {'code': 1000, 'msg': '操作完成'}
|
|
|
+ except Exception as e:
|
|
|
+ logger.exception(f"未知错误: {e}")
|
|
|
+ return {'code': 3009, 'msg': f'打开文件时发生未知错误: {e}'}
|
|
|
+
|
|
|
+ # ext = os.path.splitext(file_path)[1][1:].lower()
|
|
|
+ # if ext not in file_type_map:
|
|
|
+ # return {'code': 3001, 'msg': '不支持该类型的文件'}
|
|
|
+ #
|
|
|
+ # if not os.path.exists(file_path):
|
|
|
+ # return {'code': 3006, 'msg': '文件不存在'}
|
|
|
+ #
|
|
|
+ # # 先检测 WPS 是否可用(可缓存结果,避免重复检测)
|
|
|
+ # if not is_wps_available():
|
|
|
+ # return {'code': 3007, 'msg': '未检测到可用的 WPS Office,请安装 WPS 并确保已正确注册 COM 组件'}
|
|
|
+ #
|
|
|
+ # progid, method_name = file_type_map[ext]
|
|
|
+ #
|
|
|
+ # pythoncom.CoInitialize()
|
|
|
+ # app = None
|
|
|
+ # try:
|
|
|
+ # app = win32com.client.Dispatch(progid)
|
|
|
+ # app.Visible = True
|
|
|
+ # # 调用对应方法打开文件
|
|
|
+ # getattr(app, method_name).Open(os.path.abspath(file_path))
|
|
|
+ # return {'code': 1000, 'msg': '操作完成'}
|
|
|
+ # except pywintypes.com_error as e:
|
|
|
+ # logger.exception(f"WPS COM 操作失败: {e}")
|
|
|
+ # return {'code': 3008, 'msg': f'WPS 打开文件失败,请检查文件是否损坏或 WPS 是否正常工作。错误: {e}'}
|
|
|
+ # except Exception as e:
|
|
|
+ # logger.exception(f"未知错误: {e}")
|
|
|
+ # return {'code': 3009, 'msg': f'打开文件时发生未知错误: {e}'}
|
|
|
+ # finally:
|
|
|
+ # pythoncom.CoUninitialize()
|
|
|
|
|
|
|
|
|
@logger.catch()
|
|
|
@@ -378,8 +416,16 @@ def remove_file():
|
|
|
@logger.catch()
|
|
|
@app.route('/start_wps_server', methods=['POST'])
|
|
|
def start_wps_server():
|
|
|
- url = f"ksowpscloudsvr://start=RelayHttpServer&serverId=aef5ac0d-d5a3-49ee-b02f-c31eeb063f9b"
|
|
|
- os.startfile(url)
|
|
|
+ logger.info(f'start_wps_server:')
|
|
|
+ try:
|
|
|
+ url = f"ksowpscloudsvr://start=RelayHttpServer&serverId=aef5ac0d-d5a3-49ee-b02f-c31eeb063f9b"
|
|
|
+ os.startfile(url)
|
|
|
+ time.sleep(1)
|
|
|
+ requests.post('http://127.0.0.1:58890/version', data='{"serverId":"aef5ac0d-d5a3-49ee-b02f-c31eeb063f9b"}')
|
|
|
+ requests.post('http://127.0.0.1:58890/redirect/runParams', data='{"serverId":"9b6f627b-68cc-40e9-8cae-2921f01d4cd9","data":"eyJtZXRob2QiOiJnZXQiLCJ1cmwiOiJodHRwOi8vMTI3LjAuMC4xOjU4NTUvcmliYm9uLnhtbCIsImRhdGEiOiIifQ=="}')
|
|
|
+ except Exception as e:
|
|
|
+ logger.error('start_wps_server with an error ')
|
|
|
+ logger.exception(e)
|
|
|
return jsonify({'code': 1000, 'msg': '操作成功'})
|
|
|
|
|
|
|
|
|
@@ -505,6 +551,6 @@ def start_flask(serve_client, work_path):
|
|
|
app.config['serve_client'] = serve_client
|
|
|
app.config['work_path'] = work_path
|
|
|
try:
|
|
|
- app.run(host='127.0.0.1', port=5855)
|
|
|
+ app.run(host='127.0.0.1', port=API_SERVER_PORT)
|
|
|
except KeyboardInterrupt:
|
|
|
app.shutdown()
|