script_router.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. import asyncio
  5. from fastapi import APIRouter, HTTPException
  6. from fastapi.responses import StreamingResponse
  7. from fastapi import WebSocket, WebSocketDisconnect
  8. from datetime import datetime
  9. from module.config.config import Config
  10. from module.logger import logger
  11. from module.server.main_manager import MainManager
  12. from module.server.script_process import ScriptProcess
  13. from tasks.Component.config_base import TimeDelta
  14. script_app = APIRouter()
  15. mm = MainManager()
  16. @script_app.get('/test')
  17. async def script_test():
  18. return 'success'
  19. @script_app.get('/script_menu')
  20. async def script_menu():
  21. return mm.config_cache('template').gui_menu_list
  22. # ---------------------------------- 配置文件管理 ----------------------------------
  23. @script_app.get('/config_list')
  24. async def config_list():
  25. return mm.all_script_files()
  26. @script_app.post('/config_copy')
  27. async def config_copy(file: str, template: str = 'template'):
  28. mm.copy(file, template)
  29. return mm.all_script_files()
  30. @script_app.get('/config_new_name')
  31. async def config_new_name():
  32. return mm.generate_script_name()
  33. @script_app.get('/config_all')
  34. async def config_all():
  35. return mm.all_json_file()
  36. # --------------------------------- 脚本实例管理 ----------------------------------
  37. @script_app.get('/{script_name}/start')
  38. async def script_start(script_name: str):
  39. if script_name not in mm.script_process:
  40. mm.script_process[script_name] = ScriptProcess(script_name)
  41. mm.script_process[script_name].start()
  42. return
  43. @script_app.get('/{script_name}/stop')
  44. async def script_stop(script_name: str):
  45. if script_name not in mm.script_process:
  46. logger.warning(f'[{script_name}] script process does not exist')
  47. return
  48. mm.script_process[script_name].stop()
  49. return
  50. @script_app.get('/{script_name}/{task}/args')
  51. async def script_task(script_name: str, task: str):
  52. return mm.config_cache(script_name).model.script_task(task)
  53. @script_app.put('/{script_name}/{task}/{group}/{argument}/value')
  54. async def script_task(script_name: str, task: str, group: str, argument: str, types: str, value):
  55. try:
  56. match types:
  57. case 'integer':
  58. value = int(value)
  59. case 'number':
  60. value = float(value)
  61. case 'boolean':
  62. if isinstance(value, str):
  63. logger.warning(f'[{script_name}] script argument {argument} value is string, try to convert to bool')
  64. if value.lower() in ['true', '1']:
  65. value = True
  66. elif value.lower() in ['false', '0']:
  67. value = False
  68. value = bool(value)
  69. case 'string':
  70. pass
  71. case 'date_time':
  72. value = datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
  73. case 'time_delta':
  74. # strptime 是个好东西,但是不能解析00的天数
  75. day = int(value[0:1])
  76. date_time = datetime.strptime(value[3:], '%H:%M:%S')
  77. value = TimeDelta(days=day, hours=date_time.hour, minutes=date_time.minute, seconds=date_time.second)
  78. case 'time':
  79. value = datetime.strptime(value, '%H:%M:%S').time()
  80. case _: pass
  81. except Exception as e:
  82. # 类型不正确
  83. raise HTTPException(status_code=400, detail=f'Argument type error: {e}')
  84. return mm.config_cache(script_name).model.script_set_arg(task, group, argument, value)
  85. # -------------------------------------- SSE --------------------------------------
  86. @script_app.get('/{script_name}/state')
  87. async def script_task_state(script_name: str):
  88. async def state_generate_events():
  89. while True:
  90. # 生成 SSE 事件数据
  91. event_data = "data: Hello, SSE!\n\n"
  92. yield event_data
  93. # 模拟异步操作,可以替换为您的实际处理逻辑
  94. await asyncio.sleep(1)
  95. response = StreamingResponse(state_generate_events(), media_type="text/event-stream")
  96. response.headers["Cache-Control"] = "no-cache"
  97. return response
  98. @script_app.get('/{script_name}/log')
  99. async def script_task_log(script_name: str):
  100. async def log_generate_events():
  101. while True:
  102. # 生成 SSE 事件数据
  103. event_data = "data: log\n"
  104. yield event_data
  105. # 模拟异步操作,可以替换为您的实际处理逻辑
  106. await asyncio.sleep(1)
  107. response = StreamingResponse(log_generate_events(), media_type="text/event-stream")
  108. response.headers["Cache-Control"] = "no-cache"
  109. return response
  110. # -------------------------------------- websocket --------------------------------------
  111. @script_app.websocket("/ws/{script_name}")
  112. async def websocket_endpoint(websocket: WebSocket, script_name: str):
  113. if script_name not in mm.script_process:
  114. mm.script_process[script_name] = ScriptProcess(script_name)
  115. script_process = mm.script_process[script_name]
  116. await script_process.connect(websocket)
  117. await script_process.broadcast_state({"state": script_process.state})
  118. config = mm.config_cache(script_name)
  119. config.get_next()
  120. await script_process.broadcast_state({"schedule": config.get_schedule_data()})
  121. try:
  122. while True:
  123. # 初次进入,广播state schedule
  124. data = await websocket.receive_text()
  125. if data == 'get_state':
  126. await script_process.broadcast_state({"state": script_process.state})
  127. elif data == 'get_schedule':
  128. config = mm.config_cache(script_name)
  129. config.get_next()
  130. await script_process.broadcast_state({"schedule": config.get_schedule_data()})
  131. elif data == 'start':
  132. await script_process.start()
  133. elif data == 'stop':
  134. await script_process.stop()
  135. except WebSocketDisconnect:
  136. logger.warning(f'[{script_name}] websocket disconnect')
  137. script_process.disconnect(websocket)