You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
73 lines
2.8 KiB
73 lines
2.8 KiB
import datetime
|
|
import platform
|
|
import zipfile
|
|
|
|
import psutil
|
|
from fastapi import FastAPI, HTTPException, APIRouter
|
|
import subprocess
|
|
import os
|
|
|
|
from helper import respond_to
|
|
|
|
router = APIRouter(prefix='/version')
|
|
|
|
|
|
system_name = platform.system()
|
|
@router.get('/files')
|
|
async def get_files():
|
|
try:
|
|
usb_mount_path = await getUDiskPath()
|
|
if not os.path.exists(usb_mount_path):
|
|
return respond_to(500,"U盘未正确挂载")
|
|
files = [f for f in os.listdir(usb_mount_path) if f.endswith('.tar.gz') or f.endswith('.zip')]
|
|
print(files)
|
|
return respond_to(data=files)
|
|
except OSError as e:
|
|
raise HTTPException(code=500, detail=f"Error accessing USB directory: {e}")
|
|
|
|
async def getUDiskPath():
|
|
if system_name == 'Windows':
|
|
disk_list = psutil.disk_partitions()
|
|
# 获取U盘路径
|
|
u_path = [
|
|
disk.device for disk in disk_list if disk.opts == 'rw,removable']
|
|
if u_path:
|
|
return u_path[0]
|
|
elif system_name == 'Linux':
|
|
r = os.popen('ls -a /media/yanyi')
|
|
text = r.read()
|
|
r.close()
|
|
udisklist = text.splitlines()
|
|
if(len(udisklist) >= 3):
|
|
return '/media/yanyi/' + udisklist[2]
|
|
return ""
|
|
@router.get('/update')
|
|
async def update(file_name: str):
|
|
usb_mount_path = await getUDiskPath()
|
|
if not os.path.exists("/home/yanyi/rms_bak"):
|
|
os.makedirs("/home/yanyi/rms_bak") # 如果路径不存在,则创建路径
|
|
if not os.path.exists("/home/yanyi/rms"):
|
|
os.makedirs("/home/yanyi/rms") # 如果路径不存在,则创建路径
|
|
# 备份文件夹
|
|
backup_folder(f"/home/yanyi/{file_name}", "/home/yanyi/rms_bak")
|
|
# 复制解压命令
|
|
command = f"sudo cp {usb_mount_path}/{file_name} /home/yanyi/testrms " \
|
|
f"&& sudo unzip -o /home/yanyi/{file_name} -d /home/yanyi " \
|
|
f"&& sudo rm /home/yanyi/{file_name} " \
|
|
f"&& /home/yanyi/miniconda3/envs/p311/bin/python /home/yanyi/testrms/rms/main.py"
|
|
try:
|
|
subprocess.run(command, shell=True, check=True)
|
|
return f"Service updated successfully with {file_name}"
|
|
except subprocess.CalledProcessError as e:
|
|
raise HTTPException(status_code=500, detail=f"Error updating the service: {e}")
|
|
|
|
def backup_folder(folder_path, backup_path):
|
|
current_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
|
|
backup_file_name = f"rms{current_time}.zip"
|
|
with zipfile.ZipFile(os.path.join(backup_path, backup_file_name), 'w', zipfile.ZIP_DEFLATED) as backup_zip:
|
|
for root, _, files in os.walk(folder_path):
|
|
for file in files:
|
|
file_path = os.path.join(root, file)
|
|
archive_path = file_path[len(folder_path) + 1:]
|
|
backup_zip.write(file_path, archive_path)
|