61 Commits

Author SHA1 Message Date
CakeCN
36bbedd3cf no caddy reload 2026-01-09 12:06:55 +08:00
CakeCN
0e3703b1f4 more log 2026-01-09 11:45:17 +08:00
CakeCN
52696707dd log in connect 2026-01-09 11:31:00 +08:00
CakeCN
0a812e496f fix namespace init 2026-01-09 11:24:13 +08:00
CakeCN
de1ba08d7e 修改了 AgentNamespace 类,将全局实例变量替换为字典,使用用户 UUID 作为键 2026-01-09 11:23:02 +08:00
CakeCN
3f14cbd6c1 some log 2026-01-09 11:16:30 +08:00
CakeCN
c51565199c more log 2026-01-09 01:40:36 +08:00
CakeCN
8d29a26d7d no connect on server 2026-01-09 01:27:24 +08:00
CakeCN
decf24020a use user-joined 2026-01-09 01:22:29 +08:00
CakeCN
3dc219adc2 use join 2026-01-09 01:19:08 +08:00
CakeCN
40d1341685 more set alwaysconnect to True 2026-01-09 00:58:46 +08:00
CakeCN
0d606fb171 ,always_connect=True 2026-01-09 00:56:56 +08:00
CakeCN
e1f32ec980 ase_client add user-connected 2026-01-09 00:04:31 +08:00
CakeCN
ad8d7d069c 增加log 2026-01-08 23:54:27 +08:00
CakeCN
687b316db6 删去earning_progess_process的log 2026-01-08 23:51:55 +08:00
CakeCN
60248d5c51 log connect_to_ase 2026-01-08 23:38:50 +08:00
CakeCN
befec5543c fix: 前端打开codelike 2026-01-08 21:06:11 +08:00
CakeCN
af24c51a2f fix previous 前端发送用户信息 2026-01-08 21:04:37 +08:00
CakeCN
fa91696aae fix previous 2026-01-08 21:02:44 +08:00
CakeCN
e698c50a4b 调整前端user-connected 2026-01-08 21:01:11 +08:00
CakeCN
75795dd853 fix previous 2026-01-08 20:52:51 +08:00
CakeCN
5b8180b48e 将join room提前到on_connect 2026-01-08 20:50:56 +08:00
CakeCN
09103abf38 移除了不存在的属性引用 :删除了导致错误的 eventlet.greenthread.main 相关代码 2026-01-08 00:11:31 +08:00
CakeCN
6ecd0c6735 包装了 eventlet.greenthread.main 函数,捕获所有绿色线程中的异常 2026-01-08 00:10:33 +08:00
CakeCN
a07eee1ffc fix 语音识别重复增加的问题 2026-01-08 00:05:23 +08:00
CakeCN
848b235ddc 移除了不存在的属性引用 :删除了导致错误的代码行 eventlet.debug.hub_prevent_multiple_readers(False) 2026-01-08 00:02:50 +08:00
CakeCN
7f469803df 在捕获到致命错误时,调用 self.close() 彻底关闭连接 2026-01-08 00:01:26 +08:00
CakeCN
4dd2667785 fix module 'eventlet.hubs' has no attribute 'handle_error' 2026-01-07 23:57:25 +08:00
CakeCN
f8e0b461ba fix module 'eventlet.hubs.hub' has no attribute 'Hub' 错误 2026-01-07 23:55:16 +08:00
CakeCN
607c6dfbab 有 eventlet.hubs 相关的错误都会被捕获并打印而不会向外传播导致服务器崩溃 2026-01-07 23:52:01 +08:00
CakeCN
73275cffad 每次 IO 操作之前或期间都会检查文件可用性,并在文件不可用时优雅处理 2026-01-07 20:46:32 +08:00
CakeCN
ee20e8b85b replacing the dynamic selectedItem.path+'/'+selectedItem.name with the filePath 2026-01-07 19:13:38 +08:00
CakeCN
b806da10c4 对 terminal_service.py 文件的全面检查和修复:在子进程中使用 os._exit(1) 替代 disconnect() ,避免在子进程中调用 SocketIO 方法导致的错误;修复了 SSH 硬编码端口问题 等 2026-01-07 18:57:00 +08:00
CakeCN
f818d84208 添加了对 errno 88 (Socket operation on non-socket)的处理 2026-01-07 18:52:17 +08:00
CakeCN
9231c14013 从run 中移除了全局try-except块,增强了eventlet内部错误处理 2026-01-07 01:33:25 +08:00
CakeCN
8aa567cdf2 全局异常捕获,特别是IOClosed错误,避免服务器崩溃 2026-01-07 01:06:13 +08:00
CakeCN
a3b3018de7 客户端断开连接后,文件描述符已经被关闭,但仍有事件在处理中:对 app/sockets/terminal_service.py 文件进行了全面修复 2026-01-07 00:57:27 +08:00
CakeCN
761095d61d 修复了code-server-like服务中的eventlet.hubs.IOClosed错误:当客户端断开连接时,文件描述符被关闭,但后台任务仍在尝试读取,导致eventlet核心代码抛出IOClosed错误。 2026-01-06 21:05:39 +08:00
Cai
643c16fdf7 fix:课时编辑页面步骤处保存冗余保存问题 2026-01-05 17:26:14 +08:00
Cai
5082436289 fix:index.html的课程详情页面跳转缺失 2026-01-05 16:08:55 +08:00
Cai
7193b9a000 fix:修复前端this undefined导致的无法选课问题 2026-01-05 15:50:51 +08:00
Cai
042f6ee99e restore some file 2025-12-31 10:45:42 +08:00
CakeCN
8fd88b0088 add jquery to dashboard 2025-12-31 10:35:25 +08:00
CakeCN
319b111485 pro config 2025-12-29 21:29:54 +08:00
CakeCN
f060a17f6a 生产服 .com 2025-12-29 21:10:49 +08:00
CakeCN
ecdc2e320f Merge branch 'main' of https://hsamooc.com/git/CakeCN/hsa 2025-12-29 20:53:22 +08:00
CakeCN
aa9f39ca18 Merge branch 'main' of https://hsamooc.com/git/CakeCN/hsa 2025-12-29 20:52:54 +08:00
CakeCN
f444e86136 许多更新
Merge branch 'test'
2025-12-29 20:52:03 +08:00
CakeCN
22d9fb39f1 project token change 2025-12-29 20:45:20 +08:00
68493d6a62 add:教师端新增删除课程,增加并更换footer-brief模板 2025-12-25 15:52:29 +08:00
f3c30a80a3 fix:教师端新增课程卡片中选择从课程创建的渲染错误问题(传递的是materials而不是courses) 2025-12-25 15:17:12 +08:00
f09d82571f fix:教师端新增课程的卡片自适应布局 2025-12-25 14:33:52 +08:00
CakeCN
cb435ecade fix chapter now 2025-12-14 14:33:29 +08:00
CakeCN
c8942cedac 初始为0 2025-12-14 14:22:23 +08:00
CakeCN
1f6e75f006 history 重构 2025-12-14 14:07:27 +08:00
CakeCN
5438dc99ba DEBUG 模式 2025-12-14 11:10:54 +08:00
CakeCN
f65b5bf32a try except 2025-12-14 11:05:01 +08:00
CakeCN
da93289799 eventlet green subprocess 2025-12-14 10:58:15 +08:00
CakeCN
1554c85616 event let hub_prevent_multiple_readers(False) 配置,禁用了Eventlet的同时读取检测 2025-12-14 10:56:38 +08:00
CakeCN
70410d2c4b some static bug 2025-12-14 10:32:52 +08:00
CakeCN
496c5be90a code-server-like ssh clash 2025-12-13 23:50:45 +08:00
37 changed files with 1607 additions and 922 deletions

File diff suppressed because one or more lines are too long

View File

@@ -39,16 +39,19 @@ class ASEngineClient:
# 连接事件 # 连接事件
@self.sio.on('connect', namespace=self.namespace) @self.sio.on('connect', namespace=self.namespace)
def on_connect(): def on_connect():
print("---------------ASEngineClient on_connect----------------")
self.sid = self.sio.sid
print(f"Connected to server with sid: {self.sid}")
self.connected = True self.connected = True
self.sid = self.sio.get_sid(namespace=self.namespace) self.sio.emit('join', {'id': self.id}, namespace=self.namespace)
print(f"Connected to server. SID: {self.sid}")
if self._on_connect_callback is not None: if self._on_connect_callback is not None:
self._on_connect_callback( self._on_connect_callback(
self, self,
self._on_connect_callback_entry, self._on_connect_callback_entry,
init_data=self._on_connect_callback_initData init_data=self._on_connect_callback_initData
) )
# 断开连接事件 # 断开连接事件
@self.sio.on('disconnect', namespace=self.namespace) @self.sio.on('disconnect', namespace=self.namespace)
def on_disconnect(): def on_disconnect():

View File

@@ -35,7 +35,6 @@ class ChatManager:
_lock = threading.RLock() _lock = threading.RLock()
def __init__(self, restart=False): def __init__(self, restart=False):
self.restart = restart self.restart = restart
self.chapter_chain_now = -1
self.ase_client = None self.ase_client = None
self.app = None self.app = None
self.socketio = None self.socketio = None
@@ -70,6 +69,9 @@ class ChatManager:
self.chapter_chain = load_chapters(raw_markdown, raw_markdown_prompts, raw_score_prompts) self.chapter_chain = load_chapters(raw_markdown, raw_markdown_prompts, raw_score_prompts)
self.bb = None self.bb = None
self.chat_historys = [] self.chat_historys = []
self.chapter_chain_now = 0
self.scores = []
def send_to_vscode(self, event: str, data: dict, room: str = None, namespace: str = '/vscode'): def send_to_vscode(self, event: str, data: dict, room: str = None, namespace: str = '/vscode'):

View File

@@ -14,7 +14,7 @@ from typing import Optional
mongo = PyMongo() mongo = PyMongo()
socketio = SocketIO(cors_allowed_origins="*",max_payload_size=52428800, async_mode="eventlet") # 不直接传 app socketio = SocketIO(cors_allowed_origins="*",max_payload_size=52428800, async_mode="eventlet",always_connect=False) # 不直接传 app
cors = CORS() cors = CORS()
# ===== 你的全局对象 ===== # ===== 你的全局对象 =====
# Backboard # Backboard
@@ -38,7 +38,7 @@ def init_extensions(app):
cors_allowed_origins='*',#app.config["VSCODE_WEB_URL"], cors_allowed_origins='*',#app.config["VSCODE_WEB_URL"],
ping_timeout=app.config["SOCKETIO_PING_TIMEOUT"], ping_timeout=app.config["SOCKETIO_PING_TIMEOUT"],
ping_interval=app.config["SOCKETIO_PING_INTERVAL"], ping_interval=app.config["SOCKETIO_PING_INTERVAL"],
max_payload_size=50000000, async_mode="eventlet" max_payload_size=50000000, async_mode="eventlet",always_connect=False
) )
cors.init_app( cors.init_app(
app, app,

View File

@@ -1,6 +1,4 @@
import requests import requests
from flask_socketio import Namespace
def clear_user_session(asengine_url, asengine_token, user_id): def clear_user_session(asengine_url, asengine_token, user_id):
''' '''
@@ -28,15 +26,23 @@ def on_connect_to_ase(client, entry, init_data, **kwargs):
''' '''
此时刚刚建立好aseclient连接并向前端发送打开code-server-like指令。 此时刚刚建立好aseclient连接并向前端发送打开code-server-like指令。
''' '''
namespace_entry, ase_client = entry namespace_entry, ase_client, logger = entry
logger.info(f"on_connect_to_ase with init_data: {init_data}")
namespace_entry.emit('open-iframe',"", room=init_data['room'], namespace='/agent') namespace_entry.emit('open-iframe',"", room=init_data['room'], namespace='/agent')
namespace_entry.emit('message', "Agents服务已连接, 加载教案中", room=init_data['room'], namespace='/agent') namespace_entry.emit('message', "Agents服务已连接, 加载教案中", room=init_data['room'], namespace='/agent')
namespace_entry.emit('message', f'{init_data}', room=init_data['room'], namespace='/agent')
restart = init_data.get("restart", False) restart = init_data.get("restart", False)
if restart: # 重启时,从-1章进入 0章 # 不再需要手动next_chapter因为已经在on_login中根据mongo进度恢复了正确的章节
ase_client.chatmanager.next_chapter() # if restart: # 重启时,从-1章进入 0章
# ase_client.chatmanager.next_chapter()
# 根据restart决定是否重新加载代码
ase_client.chatmanager.load_now_chapter(load_code=restart) ase_client.chatmanager.load_now_chapter(load_code=restart)
print("load_now_chapter with restart:", restart) print("load_now_chapter with restart:", restart)
# 只有当需要restart时才发送chapter-start
if restart: if restart:
ase_client.send_text("chapter-start", "") ase_client.send_text("chapter-start", "")
namespace_entry.emit('message', "教案加载完毕", room=init_data['room'], namespace='/agent') namespace_entry.emit('message', "教案加载完毕", room=init_data['room'], namespace='/agent')

View File

@@ -93,7 +93,6 @@ def get_multiagents_dialog_list(user_id: str) -> List[Dict]:
# 检查响应 # 检查响应
if response.status_code == 200: if response.status_code == 200:
current_app.logger.info(f"获取MultiAgents对话列表成功: user_id={user_id}, json={response.json()}")
return response.json() return response.json()
else: else:
current_app.logger.error(f"获取MultiAgents对话列表失败: HTTP {response.status_code}") current_app.logger.error(f"获取MultiAgents对话列表失败: HTTP {response.status_code}")

View File

@@ -63,6 +63,12 @@ class VSCodeNamespace(Namespace):
class AgentNamespace(Namespace): class AgentNamespace(Namespace):
def __init__(self, namespace):
super().__init__(namespace)
# 使用字典存储每个用户的chatmanager和ase_client避免多用户冲突
self.user_chatmanagers = {}
self.user_ase_clients = {}
def _load_learning_progress(self, chatmanager, user_id, course_id, chapter_name, lesson_name, continue_learn): def _load_learning_progress(self, chatmanager, user_id, course_id, chapter_name, lesson_name, continue_learn):
"""加载并恢复用户学习进度 """加载并恢复用户学习进度
@@ -72,38 +78,39 @@ class AgentNamespace(Namespace):
course_id: 课程ID course_id: 课程ID
chapter_name: 章节名称 chapter_name: 章节名称
lesson_name: 课时名称 lesson_name: 课时名称
continue_learn: 是否继续学习 continue_learn: 是否继续学习现在总是为True保持兼容性
Returns: Returns:
int: 需要跳过的章节数 int: 需要跳过的章节数
""" """
need_skip_chapters = 0 # 总是从mongo加载学习进度
progress_result = load_learning_progress(user_id, course_id, chapter_name, lesson_name)
if continue_learn: # 尝试加载用户学习进度 if progress_result['exists']:
progress_result = load_learning_progress(user_id, course_id, chapter_name, lesson_name) progress = progress_result['data']
# 恢复学习进度数据
if 'scores' in progress:
chatmanager.scores = progress['scores']
if progress_result['exists']: # 恢复聊天历史
progress = progress_result['data'] if 'chat_historys' in progress:
# 恢复学习进度数据 chatmanager.chat_historys = progress['chat_historys']
if 'scores' in progress:
# 根据scores的数量确定需要跳过的章节数
need_skip_chapters = len(progress['scores'])
chatmanager.scores = progress['scores']
# 恢复聊天历史
if 'chat_historys' in progress:
chatmanager.chat_historys = progress['chat_historys']
else:
chatmanager.chat_historys = []
# 恢复当前章节链
if 'chapter_chain_now' in progress:
chatmanager.chapter_chain_now = progress['chapter_chain_now']
upload_learning_progress_to_cloud(progress)
else: else:
# 使用默认值,确保有完整的结构 chatmanager.chat_historys = []
chatmanager.chat_historys = progress_result['data']['chat_historys']
chatmanager.scores = progress_result['data']['scores'] # 恢复当前章节链
if 'chapter_chain_now' in progress:
chatmanager.chapter_chain_now = progress['chapter_chain_now']
upload_learning_progress_to_cloud(progress)
# 计算需要跳过的章节数:从初始的-1到当前的chapter_chain_now
need_skip_chapters = chatmanager.chapter_chain_now
else:
# 使用默认值,确保有完整的结构
chatmanager.chat_historys = progress_result['data']['chat_historys']
chatmanager.scores = progress_result['data']['scores']
chatmanager.chapter_chain_now = 0
need_skip_chapters = 0
return need_skip_chapters return need_skip_chapters
@@ -119,8 +126,8 @@ class AgentNamespace(Namespace):
chapter_name = data['chapter_name'] chapter_name = data['chapter_name']
user_id = uuid2username[user_uuid] user_id = uuid2username[user_uuid]
session['user_uuid'] = user_uuid session['user_uuid'] = user_uuid
join_room(user_uuid, namespace='/agent') # 将该用户加入以user_id为名的room
print(f'User connected with session user_uuid: {user_uuid}') print(f'User connected with session user_uuid: {user_uuid}')
join_room(user_uuid)
user_uuid2chatmanager = ex["user_uuid2chatmanager"] user_uuid2chatmanager = ex["user_uuid2chatmanager"]
user_uuid2ase_client = ex["user_uuid2ase_client"] user_uuid2ase_client = ex["user_uuid2ase_client"]
@@ -131,8 +138,9 @@ class AgentNamespace(Namespace):
chatmanager.function_manager.add_function(next_chapter, {'user_uuid': user_uuid}) chatmanager.function_manager.add_function(next_chapter, {'user_uuid': user_uuid})
clear_user_session(current_app.config["ASE_ENGINE_URL"], current_app.config["ASE_ENGINE_URL_TOKEN"], user_id) clear_user_session(current_app.config["ASE_ENGINE_URL"], current_app.config["ASE_ENGINE_URL_TOKEN"], user_id)
continue_learn = not chatmanager.restart
need_skip_chapters = self._load_learning_progress(chatmanager, user_id, course_id, chapter_name, lesson_name, continue_learn) # 总是从mongo加载进度不管restart状态
need_skip_chapters = self._load_learning_progress(chatmanager, user_id, course_id, chapter_name, lesson_name, True)
fmd,fmdp,fsp = load_full_markdown_file(course_id, chapter_name, lesson_name) fmd,fmdp,fsp = load_full_markdown_file(course_id, chapter_name, lesson_name)
user_uuid2ase_client[user_uuid] = HSAEngineClient(current_app.config["ASE_ENGINE_URL"], current_app.config["ASE_ENGINE_NAMESPACE"],id=user_id, chatmanager = chatmanager) user_uuid2ase_client[user_uuid] = HSAEngineClient(current_app.config["ASE_ENGINE_URL"], current_app.config["ASE_ENGINE_NAMESPACE"],id=user_id, chatmanager = chatmanager)
@@ -141,27 +149,33 @@ class AgentNamespace(Namespace):
backboard_manager.add_backboard(user_uuid, user_id, course_id, backboard_manager.add_backboard(user_uuid, user_id, course_id,
lesson_name, root_path=f'/home/{user_id}/{course_id}/{chapter_name}/{lesson_name}') lesson_name, root_path=f'/home/{user_id}/{course_id}/{chapter_name}/{lesson_name}')
chatmanager.bb = backboard_manager.get_backboard(user_uuid) chatmanager.bb = backboard_manager.get_backboard(user_uuid)
# 如果有保存的进度,需要跳过已经完成的章节、无需清空代码、对话历史恢复
if continue_learn:
for _ in range(need_skip_chapters):
chatmanager.next_chapter()
emit('next_chapter', room=user_uuid, namespace='/agent')
# 恢复对话历史到前端 - 使用批量发送消息列表
if chatmanager.chat_historys:
emit('messages', chatmanager.chat_historys, room=user_uuid, namespace='/agent')
self.chatmanager = chatmanager # 总是根据进度跳过章节,恢复对话历史
self.ase_client = user_uuid2ase_client[user_uuid] for _ in range(need_skip_chapters):
chatmanager.next_chapter()
emit('next_chapter', room=user_uuid, namespace='/agent')
# 恢复对话历史到前端 - 使用批量发送消息列表
if chatmanager.chat_historys:
emit('messages', chatmanager.chat_historys, room=user_uuid, namespace='/agent')
# 存储每个用户的chatmanager和ase_client到字典中使用用户UUID作为键
self.user_chatmanagers[user_uuid] = chatmanager
self.user_ase_clients[user_uuid] = user_uuid2ase_client[user_uuid]
# 将restart设置为False避免后续重复处理
restart = chatmanager.restart
chatmanager.restart = False
user_uuid2ase_client[user_uuid].register_on_connect_entry( user_uuid2ase_client[user_uuid].register_on_connect_entry(
callback=on_connect_to_ase, callback=on_connect_to_ase,
entry=(self, user_uuid2ase_client[user_uuid]), entry=(self, user_uuid2ase_client[user_uuid], current_app.logger),
init_data={'room':user_uuid, 'restart':chatmanager.restart} init_data={'room':user_uuid, 'restart':restart}
) )
user_uuid2ase_client[user_uuid].register_route_with_entry( user_uuid2ase_client[user_uuid].register_route_with_entry(
route='dialog', route='dialog',
callback=receive_ase_dialog, callback=receive_ase_dialog,
entry=self, entry=self,
init_data={'room': user_uuid} init_data={'room':user_uuid}
) )
user_uuid2ase_client[user_uuid].register_route_with_entry( user_uuid2ase_client[user_uuid].register_route_with_entry(
route='dialog-hint', route='dialog-hint',
@@ -179,13 +193,13 @@ class AgentNamespace(Namespace):
route='judge', route='judge',
callback=receive_ase_judge, callback=receive_ase_judge,
entry=self, entry=self,
init_data={'room': user_uuid} init_data={'room':user_uuid}
) )
user_uuid2ase_client[user_uuid].register_route_with_entry( user_uuid2ase_client[user_uuid].register_route_with_entry(
route='next_chapter', route='next_chapter',
callback=receive_ase_next_chapter, callback=receive_ase_next_chapter,
entry=self, entry=self,
init_data={'room': user_uuid} init_data={'room':user_uuid}
) )
user_uuid2ase_client[user_uuid].register_route_with_entry( user_uuid2ase_client[user_uuid].register_route_with_entry(
route='chapter_score', route='chapter_score',
@@ -279,4 +293,4 @@ class AgentNamespace(Namespace):
leave_room(uuid, namespace='/agent') leave_room(uuid, namespace='/agent')
self.app.logger.info("VSCode client disconnected") self.app.logger.info("VSCode client disconnected")
self.app.logger.info(f"Disconnect reason: {str(data)}") self.app.logger.info(f"Disconnect reason: {str(data)}")

File diff suppressed because one or more lines are too long

View File

@@ -60,6 +60,7 @@
border-radius: 8px; border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
cursor: pointer; cursor: pointer;
position: relative; /* 添加相对定位 */
} }
.course-image { .course-image {
@@ -81,6 +82,27 @@
.course-description { .course-description {
font-size: 14px; font-size: 14px;
color: #555; color: #555;
margin-bottom: 10px;
display: -webkit-box; /* 使用-webkit-box实现文本截断 */
-webkit-line-clamp: 3; /* 限制显示3行 */
-webkit-box-orient: vertical; /* 垂直排列 */
overflow: hidden; /* 隐藏溢出内容 */
text-overflow: ellipsis; /* 用省略号表示截断 */
}
/* 课程日期信息 */
.course-date {
position: absolute; /* 绝对定位到底部 */
bottom: 10px; /* 距离底部10px */
left: 0; /* 左对齐 */
right: 0; /* 右对齐 */
padding: 10px; /* 内边距 */
background-color: white; /* 白色背景 */
border-radius: 5px; /* 圆角 */
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 阴影 */
font-size: 12px; /* 字体大小 */
color: #666; /* 字体颜色 */
line-height: 1.5; /* 行高 */
} }
/* 课程目录弹出框 */ /* 课程目录弹出框 */
@@ -159,11 +181,14 @@
/* 浮窗内容 */ /* 浮窗内容 */
.modal-content { .modal-content {
background-color: #fff; background-color: #fff;
margin: 15% auto; margin: 10% auto; /* 修改为10%以缩小顶部距离 */
padding: 20px; padding: 20px;
border-radius: 10px; border-radius: 10px;
width: 40%; width: 80%; /* 修改为80%以适应小屏幕 */
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); max-width: 600px; /* 设置最大宽度 */
box-shadow: 0 4px 8px rgba(0, 0, 0, 0 1);
overflow-y: auto; /* 添加垂直滚动条 */
max-height: 80vh; /* 设置最大高度 */
} }
/* 按钮样式 */ /* 按钮样式 */
@@ -205,7 +230,34 @@ label {
margin-top: 20px; /* 上方间距 */ margin-top: 20px; /* 上方间距 */
} }
/* 选择课程或新建课程的下拉框 */
.course-selection-container {
margin: 10px 0;
font-size: 16px;
}
#course-selection {
width: 100%; /* 占满一行 */
padding: 12px; /* 增加内边距 */
font-size: 16px; /* 调整字体大小 */
margin: 10px 0; /* 上下留间距 */
border: 2px solid #ccc; /* 边框 */
border-radius: 8px; /* 圆角边框 */
background-color: #f9f9f9; /* 背景色 */
transition: border 0.3s ease, box-shadow 0.3s ease; /* 添加过渡效果 */
}
/* 鼠标悬停时下拉框的效果 */
#course-selection:hover {
border-color: #4CAF50; /* 悬停时的边框颜色 */
box-shadow: 0 0 10px rgba(76, 175, 80, 0.5); /* 悬停时的阴影效果 */
}
/* 下拉框选中项的样式 */
#course-selection option {
padding: 10px;
font-size: 16px;
}
/* 添加课程按钮样式 */ /* 添加课程按钮样式 */
.add-course-button { .add-course-button {
@@ -433,6 +485,20 @@ label[for="course-description"] {
cursor: pointer; cursor: pointer;
} }
.delete-course-btn {
background-color: #e74c3c;
color: white;
padding: 10px;
border-radius: 5px;
cursor: pointer;
width: 100%;
margin-top: 10px;
}
.delete-course-btn:hover {
background-color: #c0392b;
}
/* 编辑弹窗 */ /* 编辑弹窗 */
.edit-modal { .edit-modal {
display: none; display: none;

View File

@@ -66,31 +66,29 @@ function cleanupExpiredApprovals() {
// 定时清理过期记录 // 定时清理过期记录
setInterval(cleanupExpiredApprovals, 3000); // 每3秒检查一次 setInterval(cleanupExpiredApprovals, 3000); // 每3秒检查一次
document.addEventListener('DOMContentLoaded', function () { document.addEventListener('DOMContentLoaded', function () {
data = window.appData; user_data = window.appData;
const host = window.location.host; const host = window.location.host;
console.log(`Connecting to WebSocket server at wss://${host}/agent`); console.log(`Connecting to WebSocket server at wss://${host}/agent`);
socket = io(`wss://${host}/agent`, { socket = io(`wss://${host}/agent`, {
query: { query: {
user_uuid: data.user_uuid, user_uuid: user_data.user_uuid,
folder: data.folder folder: user_data.folder
} }
}); });
// 初始化聊天消息管理器 // 初始化聊天消息管理器
chatManager = new ChatMessageManager(); chatManager = new ChatMessageManager();
socket.on('connect', function () { socket.on('connect', function () {
console.log('Connected to server'); console.log('Connected to WebSocket server'+socket.id+"with user"+JSON.stringify(user_data));
socket.emit('login',JSON.stringify(data)); socket.emit('login',JSON.stringify(user_data));
}); });
socket.on('open-iframe', function(data) { socket.on('open-iframe', function() {
OpenIframe(); OpenIframe(user_data);
}); });
// 监听来自服务器的消息 // 监听来自服务器的消息
socket.on('voiceMessage', function (data) { socket.on('voiceMessage', function (data) {
console.log(data); console.log(data);
const input = document.getElementById('messageInput'); const input = document.getElementById('messageInput');
input.value += data; input.value = data;
}); });
socket.on('message', function (data) { socket.on('message', function (data) {
// 显示服务器的回复消息 - 单个消息 // 显示服务器的回复消息 - 单个消息

View File

@@ -1,41 +1,53 @@
function show_books(courses_data, user_selected_courses){ function show_books(courses_data, user_selected_courses) {
console.log(courses_data) console.log(courses_data)
console.log(user_selected_courses) console.log(user_selected_courses)
} }
function show_course_details(course_id){ function show_course_details(course_id) {
window.location.href = '/course/' + course_id window.location.href = '/course/' + course_id
} }
function on_click_select_course(event){ function on_click_select_course(event) {
event.stopPropagation(); // 阻止事件冒泡 event.stopPropagation(); // 阻止事件冒泡
const courseId = event.currentTarget.getAttribute('data-course-id'); const button = event.currentTarget;
if (event.currentTarget.classList.contains("selected-button")) {alert('课程已选择'); return;} const courseId = button.getAttribute('data-course-id');
if (!courseId) { alert('缺少课程ID'); return; }
if (button.classList.contains("selected-button")) { alert('课程已选择'); return; }
if (button.disabled) { return; }
button.disabled = true;
fetch(`/select_course`, { fetch(`/select_course`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'X-CSRFToken': '{{ csrf_token() }}' // 如果使用 CSRF 保护
}, },
body: JSON.stringify({ course_id: courseId }) body: JSON.stringify({ course_id: courseId })
}) })
.then(response => response.json()) .then(async (response) => {
.then(data => { let data = null;
if (data.success) { try {
// 更新按钮样式或显示消息 data = await response.json();
this.classList.remove('select-button'); } catch (_) {
this.classList.add('selected-button'); }
this.textContent = '已选择'; if (!response.ok) {
throw new Error(data?.message || `请求失败(${response.status})`);
}
return data;
})
.then((data) => {
if (!data?.success) {
throw new Error(data?.message || '选择课程失败');
}
button.classList.remove('select-button');
button.classList.add('selected-button');
button.textContent = '已选课';
alert('选择课程成功'); alert('选择课程成功');
} else { })
alert('选择课程失败'); .catch(error => {
} console.error('Error:', error);
}) alert(error?.message || '选择课程失败');
.catch(error => { button.disabled = false;
console.error('Error:', error); });
alert('选择课程失败');
});
} }
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function () {
}); });

File diff suppressed because it is too large Load Diff

View File

@@ -292,13 +292,50 @@ function closeAddCourseModal() {
document.getElementById('add-course-modal').style.display = 'none'; document.getElementById('add-course-modal').style.display = 'none';
} }
// 显示删除课程确认弹窗
function showDeleteCourseConfirmation() {
if (!material_id) {
alert('无法删除课程未找到课程ID');
return;
}
if (confirm('确定要删除这个课程吗?此操作无法撤销!')) {
deleteCourse(material_id);
}
}
// 删除课程
function deleteCourse(courseId) {
fetch(`/materials/${courseId}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
if (data.message) {
alert(data.message);
if (data.success) {
// 关闭侧边栏并刷新页面
closeCourseDetails();
location.reload();
}
}
})
.catch(error => {
console.error('删除课程时出错:', error);
alert('删除课程失败,请稍后再试!');
});
}
function onTeacherboardPageLoad(){ function onTeacherboardPageLoad(){
// 提交表单处理 // 提交表单处理
document.getElementById('add-course-form').addEventListener('submit', function(event) { document.getElementById('add-course-form').addEventListener('submit', function(event) {
event.preventDefault(); event.preventDefault();
const courseName = document.getElementById('course-name').value; const courseName = document.getElementById('course-name').value;
const courseSelection = document.getElementById('course-selection').value; const courseSelection = document.getElementById('course-selection').value; // 获取选择值
const coverImage = document.getElementById('cover-preview').src; const coverImage = document.getElementById('cover-preview').src;
const courseDescription = document.getElementById('course-description').value; const courseDescription = document.getElementById('course-description').value;
// 构建发送的数据 // 构建发送的数据
@@ -312,7 +349,7 @@ document.getElementById('add-course-form').addEventListener('submit', function(e
// 如果选择了已有课程,可以通过 courseSelection 传递课程ID根据需要修改 // 如果选择了已有课程,可以通过 courseSelection 传递课程ID根据需要修改
if (courseSelection !== 'new') { if (courseSelection !== 'new') {
// 如果是修改已有课程,设置相关的章节信息或其他数据 // 如果是修改已有课程,设置相关的章节信息或其他数据
data.chapters = ["Chapter 1", "Chapter 2"]; // 示例章节信息 data.chapters = ["Chapter 1", "Chapter 2"];
} }
// 发送 POST 请求到 /create_material // 发送 POST 请求到 /create_material

View File

@@ -208,7 +208,7 @@
console.error('Error fetching session:', error); console.error('Error fetching session:', error);
}); });
let lastiframe = null; let lastiframe = null;
function OpenIframe(){ function OpenIframe(data){
// 等待1s再加载 // 等待1s再加载
setTimeout(() => { setTimeout(() => {
// 在成功获取 session 后创建并插入 iframe // 在成功获取 session 后创建并插入 iframe

View File

@@ -46,7 +46,7 @@
</div> </div>
</div> </div>
</div> </div>
{% include 'foot.html' %} {% include 'footer-brief.html' %}
</body> </body>
<script> <script>
var course_id = "{{course_id}}"; var course_id = "{{course_id}}";

View File

@@ -4,6 +4,7 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>华实学伴 - 专业的在线学习平台</title> <title>华实学伴 - 专业的在线学习平台</title>
<script src="/static/cdnback/jquery.min.js"></script>
<link href="/static/cdnback/bootstrap.min.css" rel="stylesheet"> <link href="/static/cdnback/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="/static/cdnback/all.min.css"> <link rel="stylesheet" href="/static/cdnback/all.min.css">
<link rel="stylesheet" href="/static/css/dashboard.css"> <link rel="stylesheet" href="/static/css/dashboard.css">
@@ -13,7 +14,6 @@
</head> </head>
<body> <body>
{% include 'navbar.html' %} <!-- 引入navbar.html --> {% include 'navbar.html' %} <!-- 引入navbar.html -->
{% include 'learning-path.html' %} <!-- 引入learning-path.html -->
<section class="search-section"> <section class="search-section">
<div class="container"> <div class="container">
<div class="row justify-content-center"> <div class="row justify-content-center">
@@ -81,7 +81,7 @@
</div> </div>
</div> </div>
{% include 'foot.html' %} {% include 'footer-brief.html' %}
<script src="/static/js/dashboard.js"></script> <script src="/static/js/dashboard.js"></script>
<script> <script>

View File

@@ -187,7 +187,7 @@
let lastIframe = null; let lastIframe = null;
function OpenIframe(){ function OpenIframe(data){
// 在成功获取 session 后创建并插入 iframe // 在成功获取 session 后创建并插入 iframe
const iframe = document.createElement('iframe'); const iframe = document.createElement('iframe');
const div=document.getElementById('vscodeWeb') const div=document.getElementById('vscodeWeb')

View File

@@ -0,0 +1,11 @@
<link rel="stylesheet" href="/static/css/footer.css">
<footer class="hs-footer">
<div class="footer-main">
<div class="footer-bottom">
<div class="footer-bottom-right">
<span>© 2025 华实学伴. 保留所有权利</span>
<a href="https://beian.miit.gov.cn" target="_blank">沪ICP备2025142149号</a>
</div>
</div>
</footer>

View File

@@ -1,8 +1,9 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="zh"> <html lang="zh">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>课程选择主页</title> <title>课程选择主页</title>
<script src="/static/cdnback/jquery.min.js"></script> <script src="/static/cdnback/jquery.min.js"></script>
<link href="/static/cdnback/bootstrap.min.css" rel="stylesheet"> <link href="/static/cdnback/bootstrap.min.css" rel="stylesheet">
@@ -12,6 +13,7 @@
<script src="/static/cdnback/js/bootstrap.bundle.min.js"></script> <script src="/static/cdnback/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="/static/css/index.css"> <link rel="stylesheet" href="/static/css/index.css">
</head> </head>
<body> <body>
{% include 'navbar.html' %} {% include 'navbar.html' %}
@@ -38,7 +40,7 @@
<h2>课程列表</h2> <h2>课程列表</h2>
<div class="course-cards" id="course-cards"> <div class="course-cards" id="course-cards">
{% for course in courses_data %} {% for course in courses_data %}
<!-- <div class="course-card" onclick="show_course_details('{{ course._id }}')"> <!-- <div class="course-card" onclick="show_course_details('{{ course._id }}')">
<img src="{{ course.image_url }}" alt="{{ course.course_name }}"> <img src="{{ course.image_url }}" alt="{{ course.course_name }}">
<h3>{{ course.name }}</h3> <h3>{{ course.name }}</h3>
<p>{{ course.description }}</p> <p>{{ course.description }}</p>
@@ -49,10 +51,9 @@
{% endif %} {% endif %}
</div> --> </div> -->
<div class="col-md-6 col-lg-4"> <div class="col-md-6 col-lg-4">
<div class="course-card card h-100" onclick="openCourseProgress('{{course._id}}')"> <div class="course-card card h-100" onclick="openCourseProgress('{{course._id}}')">
<img src="{{course.image_url}}" <img src="{{course.image_url}}" class="course-img" alt="课程封面">
class="course-img" alt="课程封面">
<div class="card-body d-flex flex-column"> <div class="card-body d-flex flex-column">
<span class="course-category">算法设计</span> <span class="course-category">算法设计</span>
<h5 class="course-title">{{course.name}}</h5> <h5 class="course-title">{{course.name}}</h5>
@@ -62,11 +63,15 @@
<span class="course-rating"><i class="fas fa-star"></i> 4.7</span> <span class="course-rating"><i class="fas fa-star"></i> 4.7</span>
</div> </div>
<div class="mt-auto d-grid gap-2 d-md-flex"> <div class="mt-auto d-grid gap-2 d-md-flex">
<button class="btn btn-view flex-fill" onclick="btn_view(event,'{{course._id}}')"><i class="far fa-eye me-1"></i> 课程</button> <button class="btn btn-view flex-fill" onclick="btn_view(event,'{{course._id}}')"><i
class="far fa-eye me-1"></i> 课程</button>
{% if course._id in selected_courses %} {% if course._id in selected_courses %}
<button class="btn btn-process flex-fill selected-button" data-course-id="{{course._id}}">已选课</button> <button class="btn btn-process flex-fill selected-button"
data-course-id="{{course._id}}">已选课</button>
{% else %} {% else %}
<button class="btn btn-process flex-fill select-button" onclick="on_click_select_course(event)" data-course-id="{{course._id}}">选择课程</button> <button class="btn btn-process flex-fill select-button"
onclick="on_click_select_course(event)"
data-course-id="{{course._id}}">选择课程</button>
{% endif %} {% endif %}
</div> </div>
@@ -74,13 +79,13 @@
</div> </div>
</div> </div>
{% endfor %} {% endfor %}
</div> </div>
</div> </div>
</main> </main>
{% include 'foot.html' %} {% include 'footer-brief.html' %}
</body> </body>
<script> <script>
window.appData = { window.appData = {
@@ -88,5 +93,6 @@
} }
</script> </script>
<script src="/static/js/index.js"></script> <script src="/static/js/index.js"></script>
</html> <script src="/static/js/dashboard.js"></script>
</html>

View File

@@ -65,7 +65,7 @@
</div> </div>
</ul> </ul>
<button class="add-chapter-btn" onclick="showInputForNewChapter()">新增章节</button> <button class="add-chapter-btn" onclick="showInputForNewChapter()">新增章节</button>
<button class="delete-course-btn" onclick="showDeleteCourseConfirmation()">删除课程</button>
</div> </div>
<!-- 编辑章节或课时弹窗 --> <!-- 编辑章节或课时弹窗 -->
@@ -90,9 +90,9 @@
<div class="cover-image-container"> <div class="cover-image-container">
<div id="cover-image" class="cover-image-placeholder"> <div id="cover-image" class="cover-image-placeholder">
<span class="plus-sign">+</span> <span class="plus-sign">+</span>
<input type="file" id="cover-image-input" style="display: none;" accept="image/*" /> <input type="file" id="cover-image-input" style="display: none;" accept="image/*" />
</div> </div>
<img id="cover-preview" src="" alt="封面预览" style="display: none;" /> <img id="cover-preview" src="" alt="封面预览" style="display: none;" />
</div> </div>
<form id="add-course-form"> <form id="add-course-form">
@@ -100,8 +100,8 @@
<label for="course-selection">从课程创建或新建课程:</label> <label for="course-selection">从课程创建或新建课程:</label>
<select id="course-selection"> <select id="course-selection">
<option value="new">新建课程</option> <option value="new">新建课程</option>
{% for course in courses %} {% for course in materials %}
<option value="{{ course.id }}">{{ course.name }}</option> <option value="{{ course._id }}">{{ course.name }}</option>
{% endfor %} {% endfor %}
</select> </select>
<br><br> <br><br>
@@ -121,6 +121,6 @@
<script src="/static/js/course_current.js"></script> <script src="/static/js/course_current.js"></script>
<script src="/static/js/teacherboard.js"></script> <script src="/static/js/teacherboard.js"></script>
<script src="/static/js/teacher_course_setting.js"></script> <script src="/static/js/teacher_course_setting.js"></script>
{% include 'foot.html' %} {% include 'footer-brief.html' %}
</body> </body>
</html> </html>

View File

@@ -1,4 +1,5 @@
from flask import Blueprint, request, jsonify, current_app, session, render_template, session from flask import Blueprint, request, jsonify, current_app, session, render_template, session
from bson import ObjectId
from ..services.course_service import create_material, update_material, get_materials_by_teacher, load_material, get_materials_by_teacher_dict, add_material_chapter, add_material_chapter_lesson, delete_material_chapter_lesson, reorder_material_structure, rename_material_structure from ..services.course_service import create_material, update_material, get_materials_by_teacher, load_material, get_materials_by_teacher_dict, add_material_chapter, add_material_chapter_lesson, delete_material_chapter_lesson, reorder_material_structure, rename_material_structure
from ..auth.decorators import require_role from ..auth.decorators import require_role
from ..services.cos_service import upload_file from ..services.cos_service import upload_file
@@ -37,24 +38,60 @@ def create_new_material():
material_id = create_material(teacher_id, material_name, description, chapters, image_url) material_id = create_material(teacher_id, material_name, description, chapters, image_url)
return jsonify({"message": "教材创建成功", "material_id": material_id}), 201 return jsonify({"message": "教材创建成功", "material_id": material_id}), 201
@bp.route('/materials/<material_id>', methods=['GET']) @bp.route('/materials/<material_id>', methods=['GET', 'PUT', 'DELETE'])
@require_role(roles="teacher") @require_role(roles="teacher")
def get_material(material_id): def handle_material(material_id):
if material_id is None:
return jsonify({"message": "教材名称不能为空"}), 400
material = load_material(material_id)
print(material)
return jsonify( material.model_dump()), 200
if request.method == 'GET':
@bp.route('/materials/<material_id>', methods=['PUT']) if material_id is None:
@require_role(roles="teacher") return jsonify({"message": "教材名称不能为空"}), 400
def update_existing_material(material_id): material = load_material(material_id)
data = request.get_json() print(material)
chapters = data.get('chapters') return jsonify(material.model_dump()), 200
if update_material(material_id, chapters):
return jsonify({"message": "教材更新成功"}), 200 elif request.method == 'PUT':
return jsonify({"message": "教材未找到"}), 404 data = request.get_json()
chapters = data.get('chapters')
if update_material(material_id, chapters):
return jsonify({"message": "教材更新成功"}), 200
else:
return jsonify({"message": "教材更新失败"}), 500
elif request.method == 'DELETE':
# 获取当前教师信息
teacher_uuid = session.get("user_uuid")
teacher_id = current_app.extensions["uuid2username"][teacher_uuid]
# 检查材料是否存在,并且是否为当前教师创建
mongo = current_app.extensions["mongo"]
print(f"尝试删除课程ID: {material_id}, 当前教师ID: {teacher_id}")
try:
material = mongo.db.materials.find_one({'_id': ObjectId(material_id)})
print(f"找到的材料: {material}")
if not material:
return jsonify({"message": "课程不存在", "success": False}), 404
# 验证是否为当前教师创建的课程
if material.get('teacher_id') != teacher_id:
return jsonify({"message": "权限不足,无法删除他人课程", "success": False}), 403
except Exception as e:
print(f"查询材料时出错: {e}")
return jsonify({"message": f"查询课程时出错: {str(e)}", "success": False}), 500
# 执行删除操作
try:
result = mongo.db.materials.delete_one({'_id': ObjectId(material_id), 'teacher_id': teacher_id})
print(f"删除操作结果: {result.deleted_count}")
except Exception as e:
print(f"删除材料时出错: {e}")
return jsonify({"message": f"删除课程时出错: {str(e)}", "success": False}), 500
if result.deleted_count > 0:
return jsonify({"message": "课程删除成功", "success": True}), 200
else:
return jsonify({"message": "删除失败", "success": False}), 500
@bp.route('/materials/addchapter/<material_id>', methods=['POST']) @bp.route('/materials/addchapter/<material_id>', methods=['POST'])
@require_role(roles="teacher") @require_role(roles="teacher")

View File

@@ -69,45 +69,28 @@ def desktop(user_uuid, course_id, chapter_name, lesson_name):
chatmanager = ChatManager(restart=not load_history) restart = not load_history
chatmanager = ChatManager(restart=restart)
current_app.extensions["user_uuid2chatmanager"][user_uuid] = chatmanager current_app.extensions["user_uuid2chatmanager"][user_uuid] = chatmanager
# 如果restart为True删除mongo中的学习进度
if restart:
try:
mongo = current_app.extensions["mongo"]
mongo.db.learning_progress.delete_one({
"user_id": user_id,
"material_id": course_id,
"chapter_name": chapter_name,
"lesson_name": lesson_name
})
current_app.logger.info(f"删除学习进度成功: user_id={user_id}, course_id={course_id}, chapter={chapter_name}, lesson={lesson_name}")
except Exception as e:
current_app.logger.error(f"删除学习进度失败: {str(e)}")
code_server_port = 10000 + int(uuid.uuid4().int % 10000) code_server_port = 10000 + int(uuid.uuid4().int % 10000)
# chatmanager.start_code_server(user_uuid, user_id, path_dir, code_server_port) # chatmanager.start_code_server(user_uuid, user_id, path_dir, code_server_port)
caddy_conf = f"""
handle_path /vsc{user_id}/* {{
reverse_proxy localhost:{code_server_port}
}}
"""
caddy_config_path = "/etc/caddy/Caddyfile"
with open(caddy_config_path, "r") as f:
lines = f.readlines()
pattern = re.compile(
r'handle_path\s+/vsc' + re.escape(user_id) + r'/\* {.*?reverse_proxy.*?}',
re.DOTALL
)
for i in range(len(lines)):
if (lines[i].strip()==''): lines[i]=''
content = "".join(lines)
if pattern.search(content):
new_content = pattern.sub('', content)
lines = new_content.splitlines(keepends=True)
if len(lines) >= 2:
insert_position = len(lines) - 2
else:
insert_position = len(lines)
if caddy_conf[-1] not in ['\n', '\r']:
caddy_conf += '\n'
lines.insert(insert_position, caddy_conf)
with open(caddy_config_path, "w") as f:
f.writelines(lines)
try:
subprocess.run(["sudo", "caddy", "reload", "--config", "/etc/caddy/Caddyfile"])
except subprocess.CalledProcessError as e:
print(f"Error reload caddy {e}")
cfg = current_app.config["VSCODE_WEB_PATH"] cfg = current_app.config["VSCODE_WEB_PATH"]
path_for_vscode = path_dir path_for_vscode = path_dir

View File

@@ -5,7 +5,7 @@ api_key = sk-aMpnWklN2IbsK44d1kNpy6YOP9bk1pdPJjFeEmbb0a5ytEFf
model=gpt-4.1-nano model=gpt-4.1-nano
[VSCODE_WEB] [VSCODE_WEB]
url = https://hsamooc.cn url = https://hsamooc.com
[CODE_LIKE] [CODE_LIKE]
url = /vsc-like url = /vsc-like
#http://asengine.net:8282 #http://asengine.net:8282
@@ -27,6 +27,6 @@ bucket = hsamooc-cdn-1374354408
region = ap-guangzhou region = ap-guangzhou
[ASE_ENGINE] [ASE_ENGINE]
url = https://test.asengine.net url = https://asengine.net
namespace = /socket.io/7100eebf7a909e1ee3f4e06766f512f0358ecb6ac51d5434c17d31dd70890dc1 namespace = /socket.io/afe58a9e4c03e10fae6fae5985e8adde23a49635
url_token = 7100eebf7a909e1ee3f4e06766f512f0358ecb6ac51d5434c17d31dd70890dc1 url_token = afe58a9e4c03e10fae6fae5985e8adde23a49635

View File

@@ -0,0 +1 @@
{"username": "_10235101560"}

View File

@@ -0,0 +1 @@
{"username": "shanks"}

View File

@@ -0,0 +1 @@
{"username": "ts88"}

View File

@@ -0,0 +1 @@
{"username": "xuans"}

View File

@@ -0,0 +1 @@
{"username": "xuans_"}

View File

@@ -1,5 +1,209 @@
import eventlet import eventlet
eventlet.monkey_patch() # 进行猴子补丁操作 import logging
# 配置 eventlet 日志,抑制 IOClosed 等错误日志
logging.getLogger('eventlet.hubs').setLevel(logging.CRITICAL)
logging.getLogger('eventlet.greenio').setLevel(logging.CRITICAL)
# 进行猴子补丁操作
eventlet.monkey_patch()
# 配置 eventlet 以更优雅地处理错误,避免疯狂报错
try:
import eventlet
import traceback
# 1. 首先,禁用 eventlet 的调试日志,减少输出
import logging
logging.getLogger('eventlet').setLevel(logging.CRITICAL)
logging.getLogger('socketio').setLevel(logging.CRITICAL)
logging.getLogger('werkzeug').setLevel(logging.CRITICAL)
# 2. 配置 eventlet 相关设置移除了不存在的debug属性
# 3. 避免重复打印相同错误的机制
seen_errors = set()
max_error_logs = 5 # 每个错误最多打印5次
error_counts = {}
def is_duplicate_error(e):
"""检查是否为重复错误"""
error_key = f"{type(e).__name__}: {e}"
if error_key in seen_errors:
error_counts[error_key] = error_counts.get(error_key, 0) + 1
if error_counts[error_key] > max_error_logs:
return True
else:
seen_errors.add(error_key)
error_counts[error_key] = 1
return False
# 4. 只修改关键的 greenio 方法,确保在致命错误时彻底关闭连接
# 增强 socketio 错误处理,确保不会因为单个连接错误而宕机
try:
from flask_socketio import SocketIO
# 获取当前 socketio 实例并配置错误处理
import sys
original_excepthook = sys.excepthook
def custom_excepthook(exc_type, exc_value, exc_traceback):
"""全局异常钩子,捕获所有未处理的异常"""
if exc_type.__name__ in ['OSError', 'IOError'] and 'Bad file descriptor' in str(exc_value):
# 处理 Bad file descriptor 错误,不导致服务器宕机
if not is_duplicate_error(exc_value):
print(f"[Global Error Handler] {exc_type.__name__}: {exc_value}")
print("[Traceback]")
traceback.print_exception(exc_type, exc_value, exc_traceback)
# 不调用原始的 excepthook防止服务器宕机
return
# 其他异常调用原始的 excepthook
original_excepthook(exc_type, exc_value, exc_traceback)
# 设置全局异常钩子
sys.excepthook = custom_excepthook
except Exception as e:
# 如果修改失败,忽略错误
print(f"[Global Excepthook Patch Error] {e}")
from eventlet import greenio
# 保存并替换原始的 greenio 方法
if hasattr(greenio.base.GreenSocket, '_recv_loop'):
original_recv_loop = greenio.base.GreenSocket._recv_loop
def custom_recv_loop(self, recv_func, recv_args, *args, **kwargs):
try:
return original_recv_loop(self, recv_func, recv_args, *args, **kwargs)
except Exception as e:
if not is_duplicate_error(e):
print(f"[Eventlet IO Error] _recv_loop: {type(e).__name__}: {e}")
print("[Traceback]")
traceback.print_exc()
# 彻底关闭连接,不再继续处理
try:
self.close()
except Exception:
pass
return b''
greenio.base.GreenSocket._recv_loop = custom_recv_loop
if hasattr(greenio.base.GreenSocket, 'recv_into'):
original_recv_into = greenio.base.GreenSocket.recv_into
def custom_recv_into(self, buffer, nbytes=0, flags=0):
try:
return original_recv_into(self, buffer, nbytes, flags)
except Exception as e:
if not is_duplicate_error(e):
print(f"[Eventlet IO Error] recv_into: {type(e).__name__}: {e}")
print("[Traceback]")
traceback.print_exc()
# 彻底关闭连接,不再继续处理
try:
self.close()
except Exception:
pass
return 0
greenio.base.GreenSocket.recv_into = custom_recv_into
if hasattr(greenio.base.GreenSocket, '_send_loop'):
original_send_loop = greenio.base.GreenSocket._send_loop
def custom_send_loop(self, send_func, data, *args, **kwargs):
try:
return original_send_loop(self, send_func, data, *args, **kwargs)
except Exception as e:
if not is_duplicate_error(e):
print(f"[Eventlet IO Error] _send_loop: {type(e).__name__}: {e}")
print("[Traceback]")
traceback.print_exc()
# 彻底关闭连接,不再继续处理
try:
self.close()
except Exception:
pass
return 0
greenio.base.GreenSocket._send_loop = custom_send_loop
if hasattr(greenio.base.GreenSocket, 'send'):
original_send = greenio.base.GreenSocket.send
def custom_send(self, data, flags=0):
try:
return original_send(self, data, flags)
except Exception as e:
if not is_duplicate_error(e):
print(f"[Eventlet IO Error] send: {type(e).__name__}: {e}")
print("[Traceback]")
traceback.print_exc()
# 彻底关闭连接,不再继续处理
try:
self.close()
except Exception:
pass
return 0
greenio.base.GreenSocket.send = custom_send
# 5. 处理 WSGI 中的错误,确保彻底清理
try:
import eventlet.wsgi
if hasattr(eventlet.wsgi.HttpProtocol, 'handle_one_request'):
original_wsgi_handle_one_request = eventlet.wsgi.HttpProtocol.handle_one_request
def custom_wsgi_handle_one_request(self):
try:
return original_wsgi_handle_one_request(self)
except Exception as e:
if not is_duplicate_error(e):
print(f"[Eventlet WSGI Request Error] {type(e).__name__}: {e}")
print("[Traceback]")
traceback.print_exc()
# 彻底清理连接,不再继续
try:
self.rfile.close()
self.wfile.close()
self.finish()
except Exception:
pass
return
eventlet.wsgi.HttpProtocol.handle_one_request = custom_wsgi_handle_one_request
if hasattr(eventlet.wsgi.HttpProtocol, 'handle_one_response'):
original_wsgi_handle_one_response = eventlet.wsgi.HttpProtocol.handle_one_response
def custom_wsgi_handle_one_response(self):
try:
return original_wsgi_handle_one_response(self)
except Exception as e:
if not is_duplicate_error(e):
print(f"[Eventlet WSGI Response Error] {type(e).__name__}: {e}")
print("[Traceback]")
traceback.print_exc()
# 彻底清理连接,不再继续
try:
self.rfile.close()
self.wfile.close()
self.finish()
except Exception:
pass
return
eventlet.wsgi.HttpProtocol.handle_one_response = custom_wsgi_handle_one_response
except Exception as e:
# 如果修改失败,忽略错误
print(f"[WSGI Patch Error] {e}")
print("[Eventlet Error Handling] Configured to handle errors gracefully, avoiding duplicate logs")
except Exception as e:
# 如果修改失败,打印错误但继续运行
print(f"[Eventlet Patch Initialization Error] {e}")
traceback.print_exc()
from flask import Flask from flask import Flask
from .views.routes import main_bp from .views.routes import main_bp
from .views.file import file_bp from .views.file import file_bp

View File

@@ -13,4 +13,5 @@ class Config:
# 自定义其他全局配置 # 自定义其他全局配置
ROOT_WORKSPACE_PATH = GLOBAL_CONFIG['Global']['ROOT_WORKSPACE_PATH'] ROOT_WORKSPACE_PATH = GLOBAL_CONFIG['Global']['ROOT_WORKSPACE_PATH']
DEBUG = GLOBAL_CONFIG['Global'].getboolean('DEBUG', False)

View File

@@ -3,12 +3,12 @@ from flask_socketio import SocketIO
from .config import Config from .config import Config
# 初始化扩展 # 初始化扩展
cors = CORS() cors = CORS()
socketio = SocketIO(path='vsc-like-ws',cors_allowed_origins="*",max_payload_size=5242880, async_mode="eventlet") # 不直接传 app socketio = SocketIO(path='vsc-like-ws',cors_allowed_origins="*",max_payload_size=5242880, async_mode="eventlet",always_connect=False) # 不直接传 app
session_paths = {} session_paths = {}
def init_extensions(app): def init_extensions(app):
cors.init_app(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True) cors.init_app(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True)
socketio.init_app(app, cors_allowed_origins="*", max_payload_size=5242880, async_mode="eventlet") socketio.init_app(app, cors_allowed_origins="*", max_payload_size=5242880, async_mode="eventlet",always_connect=False)
app.extensions["session_paths"] = session_paths app.extensions["session_paths"] = session_paths
def register_namespaces(app): def register_namespaces(app):

View File

@@ -29,53 +29,122 @@ terminal_bp = Blueprint('terminal', __name__, url_prefix='/vsc-like')
def set_winsize(fd, row, col, xpix=0, ypix=0): def set_winsize(fd, row, col, xpix=0, ypix=0):
winsize = struct.pack("HHHH", row, col, xpix, ypix) try:
fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize) winsize = struct.pack("HHHH", row, col, xpix, ypix)
fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize)
except (OSError, IOError):
# File descriptor closed or invalid, do nothing
pass
def read_and_forward_pty_output(fd=None, pid=None, room_id=None,namespace=None): def read_and_forward_pty_output(fd=None, pid=None, room_id=None, namespace=None):
""" """
read data on pty master from the pty slave, and emit to the web terminal visitor read data on pty master from the pty slave, and emit to the web terminal visitor
""" """
max_read_bytes = 1024 * 20 max_read_bytes = 1024 * 20
timeout=0.1 # 初始超时时间设置为较短值,确保响应迅速
while True: timeout = 0.05
socketio.sleep(timeout) # 最大超时时间,避免太频繁的检查
timeout=min(timeout*2, 0.4) max_timeout = 0.5
# using flask default web server, or uwsgi production web server # 成功读取数据后的重置超时时间
# when the child process is terminated, it will not disappear from linux process list reset_timeout = 0.05
# and keep staying as a zombie process until the parent exits.
try: try:
child_process = psutil.Process(pid) while True:
except psutil.NoSuchProcess as err: # 等待一段时间减少CPU占用
return socketio.sleep(timeout)
if child_process.status() not in ('running', 'sleeping'):
return # 使用指数退避算法调整超时时间,但不超过最大值
if fd: timeout = min(timeout * 1.5, max_timeout)
timeout_sec = 0
(data_ready, _, _) = select.select([fd], [], [], timeout_sec) # 检查子进程状态
if data_ready: try:
# output = os.read(fd, max_read_bytes).decode('ascii') child_process = psutil.Process(pid)
timeout=0.1 except psutil.NoSuchProcess:
# 进程已终止,清理僵尸进程
try: try:
output = os.read(fd, max_read_bytes).decode() os.waitpid(pid, os.WNOHANG)
except Exception as err: except Exception:
output = """ pass
***AQUI WEB TERM ERR*** return
{}
*********************** # 检查进程状态,如果不是运行或睡眠状态,则退出
""".format(err) if child_process.status() not in ('running', 'sleeping'):
# the key for different visitor to get different terminal (instead of mixing up) try:
# is to let the background task push pty response to each one's own (default) ROOM! # 等待进程终止
namespace.emit("pty_output", {"output": output}, room=room_id) child_process.wait(timeout=1)
except Exception:
try:
os.waitpid(pid, os.WNOHANG)
except Exception:
pass
return
# 如果文件描述符有效,尝试读取数据
if fd:
try:
# 使用非阻塞select检查是否有数据可读
(data_ready, _, _) = select.select([fd], [], [], 0)
if data_ready:
# 有数据可读,重置超时时间
timeout = reset_timeout
try:
# 读取数据
output = os.read(fd, max_read_bytes).decode()
except (OSError, IOError, EOFError):
# 文件描述符已关闭或其他IO错误优雅退出
return
except UnicodeDecodeError as err:
# 处理编码错误
output = f"""
***AQUI WEB TERM ERR***
Unicode decode error: {err}
***********************
"""
# 发送数据到客户端
try:
namespace.emit("pty_output", {"output": output}, room=room_id)
except Exception:
# 如果发送失败,客户端可能已断开连接,退出
return
except (OSError, IOError):
# 文件描述符无效,优雅退出
return
except Exception as e:
# 捕获任何其他未预期的异常,防止服务器崩溃
current_app.logger.error(f"Unexpected error in read_and_forward_pty_output: {e}")
finally:
# 清理文件描述符
if fd:
try:
os.close(fd)
except Exception:
pass
class VSCLikeNameSpace(Namespace): class VSCLikeNameSpace(Namespace):
def on_connect(self): def on_connect(self):
"""new client connected""" """new client connected"""
if session.get('terminal_config', {}).get('child_pid', None): # 确保terminal_config存在于session中
print(session['terminal_config']['child_pid']) if 'terminal_config' not in session:
# already started child process, don't start another session['terminal_config'] = TERM_INIT_CONFIG.copy()
return session.modified = True
terminal_config = session['terminal_config']
# 检查是否已经有运行中的子进程
if terminal_config.get('child_pid'):
try:
# 验证进程是否真的存在
child_process = psutil.Process(terminal_config['child_pid'])
if child_process.status() in ('running', 'sleeping'):
current_app.logger.debug("Already running child process: {}".format(terminal_config['child_pid']))
return
except psutil.NoSuchProcess:
# 进程不存在,清理配置
terminal_config.pop('child_pid', None)
terminal_config.pop('fd', None)
session.modified = True
# create child process attached to a pty we can read from and write to # create child process attached to a pty we can read from and write to
(child_pid, fd) = pty.fork() (child_pid, fd) = pty.fork()
@@ -84,87 +153,210 @@ class VSCLikeNameSpace(Namespace):
# this is the child process fork. # this is the child process fork.
# anything printed here will show up in the pty, including the output # anything printed here will show up in the pty, including the output
# of this subprocess # of this subprocess
# subprocess.run('bash') try:
term_type = session.get('terminal_config').get('term_type') # 获取终端配置
path = TERM_INIT_CONFIG.get('client_path', {}).get(term_type, None) terminal_config = session.get('terminal_config', {})
if not path: term_type = terminal_config.get('term_type')
print("Can't locate {} binary, exit".format(term_type))
disconnect() if not term_type:
if term_type == 'telnet': print("Terminal type not specified, exit")
# switch to the right location of your telnet binary (example comes from OSX which got telnet from brew) os._exit(1)
# or you can also make work like auto-detection, or manually but configurable
os.execl(path, 'telnet', '-l', session['terminal_config']['username'], path = TERM_INIT_CONFIG.get('client_path', {}).get(term_type, None)
session['terminal_config']['domain'], '{}'.format(session['terminal_config']['port'])) if not path or not os.path.exists(path):
elif term_type == 'ssh': print("Can't locate {} binary at {}, exit".format(term_type, path))
os.execl(path,'ssh', '-p','22', os._exit(1)
#'{}'.format(session['terminal_config']['port']),
'{}@{}'.format(session['terminal_config']['username'], session['terminal_config']['domain'])) # 获取连接参数
username = terminal_config.get('username')
domain = terminal_config.get('domain', TERM_INIT_CONFIG['domain'])
else: port = terminal_config.get('port')
current_app.logger.debug("wrong term type {}".format(term_type))
disconnect() if not username or not domain:
session['terminal_config'] = TERM_INIT_CONFIG print("Missing required connection parameters, exit")
os._exit(1)
if term_type == 'telnet':
# 使用telnet连接
if not port:
print("Port not specified for telnet, exit")
os._exit(1)
os.execl(path, 'telnet', '-l', username, domain, str(port))
elif term_type == 'ssh':
# 使用ssh连接
ssh_port = port if port else 22 # 默认端口22
os.execl(path, 'ssh', '-p', str(ssh_port), '{}@{}'.format(username, domain))
else:
print("Wrong term type {}, exit".format(term_type))
os._exit(1)
except Exception as e:
print("Error in child process: {}", str(e))
os._exit(1)
else: else:
session['terminal_config']['fd'] = fd # 更新会话配置
session['terminal_config']['child_pid'] = child_pid terminal_config['fd'] = fd
session['terminal_config']['room_id'] = rooms()[0] terminal_config['child_pid'] = child_pid
terminal_config['room_id'] = rooms()[0]
session.modified = True session.modified = True
# 设置初始窗口大小
set_winsize(fd, 50, 50) set_winsize(fd, 50, 50)
# 记录日志
current_app.logger.debug("child pid = {}".format(child_pid)) current_app.logger.debug("child pid = {}".format(child_pid))
current_app.logger.debug("rooms of this session = {}".format(rooms())) current_app.logger.debug("rooms of this session = {}".format(rooms()))
socketio.start_background_task(read_and_forward_pty_output, fd, child_pid, rooms()[0],self)
# 启动后台任务读取pty输出
socketio.start_background_task(read_and_forward_pty_output, fd, child_pid, rooms()[0], self)
current_app.logger.debug("background task running") current_app.logger.debug("background task running")
# print(session)
def on_pty_input(self, data): def on_pty_input(self, data):
"""write to the child pty, which now is the ssh process from this machine to the 'domain' configured """write to the child pty, which now is the ssh process from this machine to the 'domain' configured
""" """
print(f"get data {data}") # 输入验证
if not isinstance(data, dict):
current_app.logger.error("Invalid input format: expected dictionary")
return
input_data = data.get("input")
if not isinstance(input_data, str):
current_app.logger.error("Invalid input data: expected string")
return
# 限制输入长度,防止缓冲区溢出
if len(input_data) > 1024:
input_data = input_data[:1024]
current_app.logger.warning("Input truncated due to length")
try: try:
child_process = psutil.Process(session.get('terminal_config').get('child_pid')) terminal_config = session.get('terminal_config', {})
except psutil.NoSuchProcess as err: child_pid = terminal_config.get('child_pid')
disconnect() if not child_pid:
session['terminal_config'] = TERM_INIT_CONFIG current_app.logger.error("No child process found")
return return
if child_process.status() not in ('running', 'sleeping'):
disconnect() child_process = psutil.Process(child_pid)
session['terminal_config'] = TERM_INIT_CONFIG if child_process.status() not in ('running', 'sleeping'):
return current_app.logger.debug("Child process not running, cleaning up")
# print(session) terminal_config.pop('child_pid', None)
# print(data, 'from input') terminal_config.pop('fd', None)
fd = session.get('terminal_config').get('fd') session.modified = True
if fd: return
# print("writing to ptd: %s" % data["input"])
# os.write(fd, data["input"].encode('ascii')) fd = terminal_config.get('fd')
os.write(fd, data["input"].encode()) if fd:
try:
os.write(fd, input_data.encode())
except (OSError, IOError) as e:
# File descriptor closed or invalid, clean up
current_app.logger.debug(f"Error writing to file descriptor: {e}")
terminal_config.pop('child_pid', None)
terminal_config.pop('fd', None)
session.modified = True
except psutil.NoSuchProcess:
# Process no longer exists, clean up
terminal_config = session.get('terminal_config', {})
terminal_config.pop('child_pid', None)
terminal_config.pop('fd', None)
session.modified = True
except Exception as e:
current_app.logger.error(f"Error in pty_input handling: {e}")
def on_resize(self, data): def on_resize(self, data):
# 输入验证
if not isinstance(data, dict):
current_app.logger.error("Invalid resize data format: expected dictionary")
return
rows = data.get("rows")
cols = data.get("cols")
# 验证行和列的值是否为正整数
if not (isinstance(rows, int) and isinstance(cols, int)):
current_app.logger.error("Invalid resize dimensions: expected integers")
return
# 限制窗口大小范围,防止异常值
if rows <= 0 or rows > 1000 or cols <= 0 or cols > 1000:
current_app.logger.error(f"Invalid resize dimensions: {rows}x{cols} (out of range)")
return
try: try:
child_process = psutil.Process(session.get('terminal_config').get('child_pid')) terminal_config = session.get('terminal_config', {})
except psutil.NoSuchProcess as err: child_pid = terminal_config.get('child_pid')
disconnect() if not child_pid:
session['terminal_config'] = TERM_INIT_CONFIG current_app.logger.error("No child process found for resize")
return return
if child_process.status() not in ('running', 'sleeping'):
disconnect() # 检查子进程是否存在且运行中
session['terminal_config'] = TERM_INIT_CONFIG child_process = psutil.Process(child_pid)
return if child_process.status() not in ('running', 'sleeping'):
fd = session.get('terminal_config').get('fd') current_app.logger.debug("Child process not running, cleaning up resize")
if fd: terminal_config.pop('child_pid', None)
set_winsize(fd, data["rows"], data["cols"]) terminal_config.pop('fd', None)
session.modified = True
return
fd = terminal_config.get('fd')
if fd:
# 检查文件描述符是否有效
try:
os.fstat(fd)
set_winsize(fd, rows, cols)
except (OSError, IOError) as e:
# 文件描述符无效,清理资源
current_app.logger.debug(f"Error resizing terminal: {e}")
terminal_config.pop('child_pid', None)
terminal_config.pop('fd', None)
session.modified = True
except psutil.NoSuchProcess:
# 进程不存在,清理资源
terminal_config = session.get('terminal_config', {})
terminal_config.pop('child_pid', None)
terminal_config.pop('fd', None)
session.modified = True
except Exception as e:
current_app.logger.error(f"Error in resize handling: {e}")
def on_disconnect(self): def on_disconnect(self):
try: terminal_config = session.get('terminal_config', {})
child_process = psutil.Process(session.get('terminal_config', {}).get('child_pid')) child_pid = terminal_config.get('child_pid')
except psutil.NoSuchProcess as err: fd = terminal_config.get('fd')
disconnect()
session['terminal_config'] = TERM_INIT_CONFIG # 先关闭文件描述符,避免其他操作尝试使用无效的文件描述符
return if fd:
if child_process.status() in ('running', 'sleeping'): try:
# if visitor just close the browser tab then left alone the pty here os.close(fd)
# it should be terminated by the parent process after except Exception:
child_process.terminate() pass
current_app.logger.debug('user left the pty alone, terminated')
if child_pid:
try:
child_process = psutil.Process(child_pid)
if child_process.status() in ('running', 'sleeping'):
# if visitor just close the browser tab then left alone the pty here
# it should be terminated by the parent process after
child_process.terminate()
# Wait for the process to terminate and collect its exit status
child_process.wait(timeout=2)
current_app.logger.debug('user left the pty alone, terminated and waited')
except psutil.NoSuchProcess as err:
# Process already terminated, try to wait anyway to clean up any zombie
try:
os.waitpid(child_pid, os.WNOHANG)
except Exception:
pass
except psutil.TimeoutExpired:
# If process didn't terminate in time, kill it forcefully
try:
child_process.kill()
child_process.wait(timeout=1)
except Exception:
pass
except Exception as err:
current_app.logger.error(f'Error terminating process: {err}')
# Reset session config
session['terminal_config'] = TERM_INIT_CONFIG
current_app.logger.debug('Client disconnected') current_app.logger.debug('Client disconnected')

View File

@@ -1,5 +1,5 @@
import os import os
import subprocess from eventlet.green import subprocess
from flask import Blueprint, request, jsonify, current_app, render_template, session from flask import Blueprint, request, jsonify, current_app, render_template, session
from ..services.file_service import get_file_tree, load_config from ..services.file_service import get_file_tree, load_config
@@ -42,32 +42,34 @@ def vsc_like(user_uuid, user_id, course_id, chapter_name, lesson_name, port):
subprocess.run(["sudo", "chown", "-R", user_id, user_root]) # 设置目录权限为新用户 subprocess.run(["sudo", "chown", "-R", user_id, user_root]) # 设置目录权限为新用户
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
print(f"Error creating user {user_id}: {e}") # 用户可能已经存在,这是正常情况,继续执行
print(f"Useradd command returned non-zero exit status, this is expected if user already exists: {e}")
try: try:
# 使用 sudo 执行 mkdir 命令来创建目录 # 使用 sudo 执行 mkdir 命令来创建目录
subprocess.run(["sudo", "-u", user_id, "mkdir", "-p", path], check=True) subprocess.run(["sudo", "-u", user_id, "mkdir", "-p", path], check=current_app.config['DEBUG'])
subprocess.run(["sudo", "-u", user_id, "mkdir", "-p", f'{user_root}/.ssh'], check=True) subprocess.run(["sudo", "-u", user_id, "mkdir", "-p", f'{user_root}/.ssh'], check=current_app.config['DEBUG'])
flask_pub_key = "/home/flask/.ssh/id_ed25519.pub" flask_pub_key = "/home/flask/.ssh/id_ed25519.pub"
subprocess.run(["sudo", "cp", flask_pub_key, f"{user_root}/.ssh/authorized_keys"], check=True) subprocess.run(["sudo", "cp", flask_pub_key, f"{user_root}/.ssh/authorized_keys"], check=current_app.config['DEBUG'])
subprocess.run(["sudo", "chmod", "700", f"{user_root}/.ssh"], check=True) subprocess.run(["sudo", "chmod", "700", f"{user_root}/.ssh"], check=current_app.config['DEBUG'])
subprocess.run(["sudo", "chmod", "600", f"{user_root}/.ssh/authorized_keys"], check=True) subprocess.run(["sudo", "chmod", "600", f"{user_root}/.ssh/authorized_keys"], check=current_app.config['DEBUG'])
print(f"Directory {path} created successfully for user {user_id}") print(f"Directory {path} created successfully for user {user_id}")
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
print(f"Error creating directory {path} details {str(e)}") print(f"Error creating directory {path} details {str(e)}")
try:#使用sudo创建shared_group try:#使用sudo创建shared_group
subprocess.run(["sudo", "groupadd", f"shared_group_{user_id}"], check=True) subprocess.run(["sudo", "groupadd", f"shared_group_{user_id}"], check=current_app.config['DEBUG'])
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
print(f"Error creating shared_group: {e}") # 组可能已经存在,这是正常情况,继续执行
print(f"Groupadd command returned non-zero exit status, this is expected if group already exists: {e}")
try:#使用sudo将user_id加入shared_group try:#使用sudo将user_id加入shared_group
subprocess.run(["sudo", "usermod", "-a", "-G", f"shared_group_{user_id}", user_id], check=True) subprocess.run(["sudo", "usermod", "-a", "-G", f"shared_group_{user_id}", user_id], check=current_app.config['DEBUG'])
# 自己也加入 # 自己也加入
subprocess.run(["sudo", "usermod", "-a", "-G", f"shared_group_{user_id}", 'flask'], check=True) subprocess.run(["sudo", "usermod", "-a", "-G", f"shared_group_{user_id}", 'flask'], check=current_app.config['DEBUG'])
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
print(f"Error adding user {user_id} to shared_group: {e}") print(f"Error adding user {user_id} to shared_group: {e}")
try: try:
subprocess.run(["sudo", "chown", "-R", f"flask:shared_group_{user_id}", path], check=True) subprocess.run(["sudo", "chown", "-R", f"flask:shared_group_{user_id}", path], check=current_app.config['DEBUG'])
subprocess.run(["sudo", "chmod", "-R", "755", user_root], check=True) subprocess.run(["sudo", "chmod", "-R", "755", user_root], check=current_app.config['DEBUG'])
subprocess.run(["sudo", "chmod", "-R", "775", path], check=True) subprocess.run(["sudo", "chmod", "-R", "775", path], check=current_app.config['DEBUG'])
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
print(f"Error changing directory {path} to shared_group_{user_id}: {e}") print(f"Error changing directory {path} to shared_group_{user_id}: {e}")

View File

@@ -1,3 +1,4 @@
[Global] [Global]
SECRET_KEY = cakebaker SECRET_KEY = cakebaker
ROOT_WORKSPACE_PATH = /home ROOT_WORKSPACE_PATH = /home
DEBUG = False

View File

@@ -1,5 +1,12 @@
from app import create_app from app import create_app
from app.extensions import socketio from app.extensions import socketio
import logging
# 配置日志减少eventlet的调试日志
logging.getLogger('eventlet').setLevel(logging.ERROR)
logging.getLogger('socketio').setLevel(logging.ERROR)
logging.getLogger('werkzeug').setLevel(logging.ERROR)
app = create_app() app = create_app()
if __name__ == '__main__': if __name__ == '__main__':
@@ -9,4 +16,5 @@ if __name__ == '__main__':
port=5200, port=5200,
debug=False, # 开发期打开 debug=False, # 开发期打开
allow_unsafe_werkzeug=True, # 避免 dev server 的安全限制提示 allow_unsafe_werkzeug=True, # 避免 dev server 的安全限制提示
) log_output=False # 禁用详细输出
)

View File

@@ -4,17 +4,17 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cloud IDE</title> <title>Cloud IDE</title>
<link rel="stylesheet" href="static/cdnback/css/editor/editor.main.css"> <link rel="stylesheet" href="/static/cdnback/css/editor/editor.main.css">
<script src="static/cdnback/socket.io.min.js"></script> <script src="/static/cdnback/socket.io.min.js"></script>
<link rel="stylesheet" href="static/cdnback/all.min.css"> <link rel="stylesheet" href="/static/cdnback/all.min.css">
<link rel="stylesheet" href="static/cdnback/css/xterm.css" /> <link rel="stylesheet" href="/static/cdnback/css/xterm.css" />
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/xterm/5.5.0/xterm.js"></script> --> <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/xterm/5.5.0/xterm.js"></script> -->
<script src="static/cdnback/js/xterm.js"></script> <script src="/static/cdnback/js/xterm.js"></script>
<script src="static/cdnback/js/addons/fit/fit.js"></script> <script src="/static/cdnback/js/addons/fit/fit.js"></script>
<script src="static/cdnback/js/addons/webLinks/webLinks.js"></script> <script src="/static/cdnback/js/addons/webLinks/webLinks.js"></script>
<script src="static/cdnback/js/addons/fullscreen/fullscreen.js"></script> <script src="/static/cdnback/js/addons/fullscreen/fullscreen.js"></script>
<script src="static/cdnback/js/addons/search/search.js"></script> <script src="/static/cdnback/js/addons/search/search.js"></script>
<link rel="stylesheet" href="static/cdnback/all.min.css"> <link rel="stylesheet" href="/static/cdnback/all.min.css">
<link rel="stylesheet" href="/vsc-like/static/css/index.css"> <link rel="stylesheet" href="/vsc-like/static/css/index.css">
<link rel="stylesheet" href="/vsc-like/static/css/notification.css"> <link rel="stylesheet" href="/vsc-like/static/css/notification.css">
@@ -61,7 +61,7 @@
</div> </div>
<div id="notificationsContainer"></div> <div id="notificationsContainer"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.0/min/vs/loader.js"></script> <script src="/static/cdnback/js/monaco-editor/0.34.0/min/vs/loader.js"></script>
<script src="/vsc-like/static/js/code-like-extension.js"></script> <script src="/vsc-like/static/js/code-like-extension.js"></script>
<script src="/vsc-like/static/js/file.js"></script> <script src="/vsc-like/static/js/file.js"></script>
<script src="/vsc-like/static/js/terminal.js"></script> <script src="/vsc-like/static/js/terminal.js"></script>
@@ -161,7 +161,7 @@
// saveFile // saveFile
if (saveTimeout) clearTimeout(saveTimeout); if (saveTimeout) clearTimeout(saveTimeout);
saveTimeout = setTimeout(() => { saveTimeout = setTimeout(() => {
postSaveFile(selectedItem.path+'/'+selectedItem.name, editor.getValue()); postSaveFile(filePath, editor.getValue());
}, 5000); // 5000ms = 5秒 }, 5000); // 5000ms = 5秒
}); });

69
et --hard HEAD@{1} Normal file
View File

@@ -0,0 +1,69 @@
68493d6a (HEAD -> main, origin/main) HEAD@{0}: pull origin main: Fast-forward
0852e121 HEAD@{1}: reset: moving to HEAD
0852e121 HEAD@{2}: commit: cdn fix more
7dc4714a HEAD@{3}: commit: index style
9dc81b14 (origin/feature/paste_detecte_new, feature/paste_detecte_new) HEAD@{4}: merge feature/paste_detecte_new: Fast-forward
7862647b HEAD@{5}: checkout: moving from feature/paste_detecte_new to main
9dc81b14 (origin/feature/paste_detecte_new, feature/paste_detecte_new) HEAD@{6}: commit (merge): Merge branch 'main' into feature/paste_detecte_new
0cf1896b HEAD@{7}: checkout: moving from main to feature/paste_detecte_new
7862647b HEAD@{8}: commit: style fix
6b9c8e9e HEAD@{9}: commit: cdn change to local and use markdown and style change
33844786 HEAD@{10}: commit: use markdown to edit
ce88ae64 HEAD@{11}: commit: use queue to allow send vscode_ws when it is none
6c38e906 HEAD@{12}: pull: Fast-forward
9759c93a HEAD@{13}: commit: fix funciton response
ecf19f49 HEAD@{14}: commit: fix function double promlem
f5d50772 HEAD@{15}: commit: function call can be expire
4a390adb HEAD@{16}: commit: fix style bug
960d1f1d HEAD@{17}: commit: style fix
c73ea447 HEAD@{18}: commit: fix index
33bf569f HEAD@{19}: commit: fix nextchapter bug
b921bda4 HEAD@{20}: commit: auto get domain
9921848d HEAD@{21}: commit: remove prefix of http url
4d81aef8 HEAD@{22}: commit (merge): Merge branch 'feature/paste_deteced'
8fe5ee16 HEAD@{23}: checkout: moving from feature/paste_deteced to main
9ce212e9 (origin/feature/paste_deteced, feature/paste_deteced) HEAD@{24}: checkout: moving from main to feature/paste_deteced
8fe5ee16 HEAD@{25}: commit (merge): 准备合并main
908d5915 HEAD@{26}: checkout: moving from syt to main
57d8ac32 (origin/syt, syt) HEAD@{27}: checkout: moving from main to syt
908d5915 HEAD@{28}: commit: ready
02b12791 HEAD@{29}: checkout: moving from syt to main
57d8ac32 (origin/syt, syt) HEAD@{30}: checkout: moving from main to syt
02b12791 HEAD@{31}: pull: Fast-forward
7d861e34 (origin/zrz) HEAD@{32}: checkout: moving from syt to main
57d8ac32 (origin/syt, syt) HEAD@{33}: commit: first
0196f37e HEAD@{34}: pull: Merge made by the 'ort' strategy.
57eb1197 HEAD@{35}: commit: ok
382f2006 HEAD@{36}: checkout: moving from main to syt
7d861e34 (origin/zrz) HEAD@{37}: commit (merge): Merge branch 'main' of https://gitee.com/CakeCN/code-agent
5f8f6c94 HEAD@{38}: commit: many ok
e24aa12e HEAD@{39}: commit: ready to process
6766ca85 HEAD@{40}: commit (merge): Merge branch 'feature/voice_send'
3c9c7553 HEAD@{41}: checkout: moving from feature/voice_send to main
58a95e9f (origin/feature/voice_send, feature/voice_send) HEAD@{42}: commit: ready merge to main
79125ffc HEAD@{43}: commit: change .cn to .com
2f9bc7df HEAD@{44}: checkout: moving from main to feature/voice_send
3c9c7553 HEAD@{45}: reset: moving to HEAD
3c9c7553 HEAD@{46}: checkout: moving from feature/voice_send to main
2f9bc7df HEAD@{47}: pull: Fast-forward
504c5cae (0v) HEAD@{48}: checkout: moving from main to feature/voice_send
3c9c7553 HEAD@{49}: commit: cn/com allow all
7122c3be HEAD@{50}: commit (merge): fix url
e07c41fb HEAD@{51}: commit: fix code-server reboot problem(close debug)
821e20c9 HEAD@{52}: commit: clear double iframe more safe
053584a7 HEAD@{53}: checkout: moving from feature/voice_send to main
504c5cae (0v) HEAD@{54}: checkout: moving from main to feature/voice_send
053584a7 HEAD@{55}: commit: clear iframe double
10481b0b HEAD@{56}: commit: fix permisson bug
dc0eeaa9 HEAD@{57}: commit: add hint
a24df620 HEAD@{58}: commit: fix some bug
3ad36c29 HEAD@{59}: commit: 25/09/24 10:00~11:30 停机维护
07cf2363 HEAD@{60}: commit: fix many bug
6aac4200 HEAD@{61}: commit: try hello message
271672c9 HEAD@{62}: commit: check to code-server-like
252c426c HEAD@{63}: pull: Merge made by the 'ort' strategy.
588fc3b6 HEAD@{64}: commit: ready to code-like
b1f832a2 (origin/code-like-autosave, code-like-autosave) HEAD@{65}: merge code-like-autosave: Fast-forward
24f191d5 HEAD@{66}: checkout: moving from code-like-autosave to main
b1f832a2 (origin/code-like-autosave, code-like-autosave) HEAD@{67}: checkout: moving from main to code-like-autosave
24f191d5 HEAD@{68}: clone: from https://gitee.com/CakeCN/code-agent.git