Compare commits
1 Commits
68493d6a62
...
code-serve
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
496c5be90a |
1
Html/.gitattributes
vendored
1
Html/.gitattributes
vendored
@@ -1 +0,0 @@
|
|||||||
Html/config.ini merge=ours
|
|
||||||
480
Html/app_back.py
Normal file
480
Html/app_back.py
Normal file
@@ -0,0 +1,480 @@
|
|||||||
|
from bootstrap import bootstrap_paths
|
||||||
|
bootstrap_paths()
|
||||||
|
from functools import wraps
|
||||||
|
from flask import Flask, redirect, session, request, jsonify, render_template, send_from_directory, url_for
|
||||||
|
from flask_cors import CORS
|
||||||
|
from flask_socketio import SocketIO, join_room, emit, Namespace
|
||||||
|
import markdown
|
||||||
|
import os
|
||||||
|
import uuid
|
||||||
|
import shutil
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
from apps.auth.decorators import require_role
|
||||||
|
parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
|
||||||
|
sys.path.insert(0, parent_dir)
|
||||||
|
student_workspace_root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../study'))
|
||||||
|
current_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '.'))
|
||||||
|
sys.path.insert(0, current_dir)
|
||||||
|
from AlgoriAgent.projects.algoriAgent.agent_manager import AgentManager
|
||||||
|
|
||||||
|
|
||||||
|
import configparser
|
||||||
|
|
||||||
|
from db.user_list import UserList
|
||||||
|
from db.user import User, load_user_from_json, create_user_json
|
||||||
|
from db.course_list import CourseList
|
||||||
|
from db.course import Course, load_course_from_json
|
||||||
|
GLOBAL_CONFIG = configparser.ConfigParser()
|
||||||
|
GLOBAL_CONFIG.read('config.ini')
|
||||||
|
VSCODE_WEB_URL = GLOBAL_CONFIG['VSCODE_WEB']['url']
|
||||||
|
USER_DATA_DIR = GLOBAL_CONFIG['USER_DATA']['dir']
|
||||||
|
COURSE_DATA_DIR = GLOBAL_CONFIG['COURSE_DATA']['dir']
|
||||||
|
|
||||||
|
app = Flask(__name__)
|
||||||
|
socketio = SocketIO(app, cors_allowed_origins="*",ping_timeout=60, ping_interval=5)
|
||||||
|
# socketio = SocketIO(app, cors_allowed_origins="http://localhost:9888") # 设置跨域支持
|
||||||
|
import logging
|
||||||
|
app.secret_key = 'cakebaker'
|
||||||
|
app.logger.setLevel(logging.DEBUG)
|
||||||
|
# 配置 CORS
|
||||||
|
CORS(app, resources={r"/*": {"origins": VSCODE_WEB_URL},}, supports_credentials=True)
|
||||||
|
|
||||||
|
|
||||||
|
userid_recorder = {} # user_id&path -> session['user_id']
|
||||||
|
|
||||||
|
'''
|
||||||
|
Backboard
|
||||||
|
'''
|
||||||
|
from backboardManager import BackBoardManager, Backboard
|
||||||
|
|
||||||
|
backboard_manager = BackBoardManager()
|
||||||
|
uuid2username = {}
|
||||||
|
username2uuid = {}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# 定义命名空间:用于和 VSCode 插件交流
|
||||||
|
class VSCodeNamespace(Namespace):
|
||||||
|
def on_login(self,data):
|
||||||
|
print("VSCode client connected")
|
||||||
|
print(data)
|
||||||
|
dataconfig = data['config']
|
||||||
|
user_id = dataconfig.get('user_id')
|
||||||
|
path = dataconfig.get('path')
|
||||||
|
course_id = dataconfig.get('course_id')
|
||||||
|
lesson_id = dataconfig.get('chapter_id')
|
||||||
|
print(f"User {user_id} connected with path: {path}")
|
||||||
|
useruuid = username2uuid[user_id]
|
||||||
|
join_room(useruuid, namespace='/vscode')
|
||||||
|
if backboard_manager.get_backboard(useruuid) == None:
|
||||||
|
backboard_manager.add_backboard(useruuid,user_id, course_id, lesson_id, path)
|
||||||
|
|
||||||
|
|
||||||
|
def on_message(self, data):
|
||||||
|
print(f"Received from VSCode client: {data}")
|
||||||
|
dataconfig = data['config']
|
||||||
|
realtime_response(dataconfig, data)
|
||||||
|
# emit('response', {'message': 'Config data received and connection established'})
|
||||||
|
def on_disconnect(self, data):
|
||||||
|
print("VSCode client disconnected")
|
||||||
|
print("Disconnect reason:"+str(data))
|
||||||
|
|
||||||
|
|
||||||
|
def realtime_response(config, realtime_action):
|
||||||
|
user_id = config['user_id']
|
||||||
|
folder_path = config['path']
|
||||||
|
useruuid = username2uuid[user_id]
|
||||||
|
bb = backboard_manager.get_backboard(useruuid)
|
||||||
|
assert type(bb) == Backboard
|
||||||
|
|
||||||
|
bb.add_history(realtime_action)
|
||||||
|
|
||||||
|
if realtime_action['type'] == 'workspaceFolders':
|
||||||
|
bb.file_tree = realtime_action['fileTree']
|
||||||
|
|
||||||
|
if realtime_action['type'] == 'activeFile':
|
||||||
|
file_path = realtime_action['filePath']
|
||||||
|
assert type(file_path) == str
|
||||||
|
with open(f"{file_path}") as f:
|
||||||
|
bb.active_file_content = f.read()
|
||||||
|
|
||||||
|
if realtime_action['type'] == 'paste':
|
||||||
|
file_path = realtime_action['filePath']
|
||||||
|
assert type(file_path) == str
|
||||||
|
bb.pasted_file_path = file_path
|
||||||
|
bb.pasted_content = realtime_action['content']
|
||||||
|
bb.active_file_path = file_path
|
||||||
|
with open(f"{file_path}") as f:
|
||||||
|
bb.active_file_content = f.read()
|
||||||
|
|
||||||
|
|
||||||
|
if realtime_action['type'] == 'fileEdit':
|
||||||
|
file_path = realtime_action['filePath']
|
||||||
|
assert type(file_path) == str
|
||||||
|
bb.active_file_path = file_path
|
||||||
|
with open(f"{file_path}") as f:
|
||||||
|
bb.active_file_content = f.read()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
print("config"+str(config))
|
||||||
|
print("realtime_action"+str(realtime_action))
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
'''
|
||||||
|
Agent and Chat
|
||||||
|
'''
|
||||||
|
agent_manager = AgentManager(app = app, socketio = socketio)
|
||||||
|
user_threads = {}
|
||||||
|
import threading
|
||||||
|
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||||
|
|
||||||
|
# 初始化线程池
|
||||||
|
executor = ThreadPoolExecutor(max_workers=10)
|
||||||
|
class AgentNamespace(Namespace):
|
||||||
|
def on_login(self, data):
|
||||||
|
data = json.loads(data)
|
||||||
|
user = data['username']
|
||||||
|
course_id = data['course_id']
|
||||||
|
chapter_id = data['chapter_id']
|
||||||
|
user_uuid = username2uuid[user]
|
||||||
|
session['user_id'] = user_uuid
|
||||||
|
print(f'User connected with session user_id: {user_uuid}')
|
||||||
|
# 从markdown、markdown_prompts、score_prompts中各读取数据folder.md并进行new_agent
|
||||||
|
with open(f'books/markdown/{course_id}/{chapter_id}.md','r',encoding='UTF-8') as fmd,\
|
||||||
|
open(f'books/markdown_prompts/{course_id}/{chapter_id}.md','r',encoding='UTF-8')as fmdp,\
|
||||||
|
open(f'books/score_prompts/{course_id}/{chapter_id}.md','r',encoding='UTF-8') as fsp:
|
||||||
|
markdown = fmd.read()
|
||||||
|
markdown_prompts = fmdp.read()
|
||||||
|
score_prompts = fsp.read()
|
||||||
|
user_uuid, agent = agent_manager.new_agent(course_id, chapter_id, markdown, markdown_prompts, score_prompts, id=user_uuid,
|
||||||
|
root_path=f'../../study/{user}/{course_id}/{chapter_id}')
|
||||||
|
print(user_uuid)
|
||||||
|
join_room(user_uuid, namespace='/agent') # 将该用户加入以user_id为名的room
|
||||||
|
backboard_manager.add_backboard(user_uuid, user, course_id, chapter_id, root_path=f'../../study/{user}/{course_id}/{chapter_id}')
|
||||||
|
|
||||||
|
def on_language(self, language):
|
||||||
|
id = session.get('user_id')
|
||||||
|
agent_manager.change_language(id, language)
|
||||||
|
|
||||||
|
def on_message(self, data):
|
||||||
|
print(f"Message from client: {data}")
|
||||||
|
id = session.get('user_id')
|
||||||
|
if (type(data)==str):
|
||||||
|
data = json.loads(data)
|
||||||
|
print(id)
|
||||||
|
if data['type'] == 'text':
|
||||||
|
res = agent_manager.invoke(id, data['data'], backboard_manager.get_backboard(id).get_info_prompt())
|
||||||
|
print('=*='*20)
|
||||||
|
print(res.content)
|
||||||
|
reply = f"{res.content['speak']}"
|
||||||
|
with app.app_context():
|
||||||
|
emit('message',reply, room=id, namespace='/agent')
|
||||||
|
emit('request_function',res.content['function'], room=id, namespace='/agent')
|
||||||
|
|
||||||
|
if data['type'] == 'function':
|
||||||
|
agent_manager.function_call(id, data['data'])
|
||||||
|
|
||||||
|
def on_initiative(self,data):
|
||||||
|
print("User active function call")
|
||||||
|
user_id = session['user_id']
|
||||||
|
if data['name'] == 'sample_judge':
|
||||||
|
agent_manager.sample_judge(user_id, backboard_manager.get_backboard(user_id))
|
||||||
|
if data['name'] == 'judge':
|
||||||
|
agent_manager.judge(user_id, backboard_manager.get_backboard(user_id))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def on_disconnect(self,data):
|
||||||
|
print("VSCode client disconnected")
|
||||||
|
print("Disconnect reason:"+str(data))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
'''
|
||||||
|
Markdown to HTML
|
||||||
|
'''
|
||||||
|
# 配置文件路径
|
||||||
|
MARKDOWN_DIR = 'books/markdown' # 存放 markdown 文件的文件夹
|
||||||
|
STATIC_DIR = 'static' # 存放生成的 HTML 和图片资源的文件夹
|
||||||
|
IMAGE_DIR = 'image' # 图片资源相对于 markdown 的位置
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/<course_id>-<filename>-markdown', methods=['GET'])
|
||||||
|
def convert_md(course_id, filename):
|
||||||
|
md_file_path = os.path.join(MARKDOWN_DIR,course_id, f'{filename}.md')
|
||||||
|
|
||||||
|
if not os.path.exists(md_file_path):
|
||||||
|
return jsonify({'error': 'Markdown file not found'}), 404
|
||||||
|
|
||||||
|
# 读取 markdown 文件内容
|
||||||
|
with open(md_file_path, 'r', encoding='utf-8') as file:
|
||||||
|
md_content = file.read()
|
||||||
|
|
||||||
|
# 将 markdown 转换为 HTML
|
||||||
|
html_content = markdown.markdown(md_content)
|
||||||
|
# 插入 CSS 样式,限制图片最大宽度为 100%,高度自动调整
|
||||||
|
html_with_styles = f"""
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<style>
|
||||||
|
img {{
|
||||||
|
max-width: 100%;
|
||||||
|
height: auto;
|
||||||
|
}}
|
||||||
|
</style>
|
||||||
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.2.0/github-markdown.min.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
{html_content}
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
"""
|
||||||
|
# 保存 HTML 文件到 static 文件夹
|
||||||
|
html_output_path = os.path.join(STATIC_DIR, f'{filename}.html')
|
||||||
|
with open(html_output_path, 'w', encoding='utf-8') as html_file:
|
||||||
|
html_file.write(html_with_styles)
|
||||||
|
|
||||||
|
# 处理图片资源,将 image/xxx 文件夹拷贝到 static/image/xxx
|
||||||
|
image_source_dir = os.path.join(MARKDOWN_DIR,course_id, IMAGE_DIR, filename)
|
||||||
|
image_target_dir = os.path.join(STATIC_DIR, IMAGE_DIR, filename)
|
||||||
|
print(f"Copying image resources from {image_source_dir} to {image_target_dir}")
|
||||||
|
if os.path.exists(image_source_dir):
|
||||||
|
# 确保 static/image/xxx 目录存在
|
||||||
|
if not os.path.exists(image_target_dir):
|
||||||
|
os.makedirs(image_target_dir)
|
||||||
|
|
||||||
|
# 拷贝图片资源
|
||||||
|
for image_file in os.listdir(image_source_dir):
|
||||||
|
full_image_file_path = os.path.join(image_source_dir, image_file)
|
||||||
|
if os.path.isfile(full_image_file_path):
|
||||||
|
shutil.copy(full_image_file_path, image_target_dir)
|
||||||
|
|
||||||
|
return jsonify({'html_url': f'/static/{filename}.html'})
|
||||||
|
|
||||||
|
# 静态文件(HTML 和图片资源)的访问
|
||||||
|
@app.route('/static/<path:filename>')
|
||||||
|
def serve_static(filename):
|
||||||
|
return send_from_directory(STATIC_DIR, filename)
|
||||||
|
|
||||||
|
|
||||||
|
'''
|
||||||
|
Vscode
|
||||||
|
'''
|
||||||
|
@app.route('/desktop/<user_id>/<course_id>/<chapter_id>')
|
||||||
|
def desktop(user_id, course_id, chapter_id):
|
||||||
|
if 'user_id' not in session:
|
||||||
|
# return redirect(url_for('login'))
|
||||||
|
session['user_id'] = 'user_' + str(uuid.uuid4())
|
||||||
|
print("user "+ user_id + "uuid is"+ session['user_id'])
|
||||||
|
username2uuid[user_id] = session['user_id']
|
||||||
|
uuid2username[session['user_id']] = user_id
|
||||||
|
userid_recorder[user_id+'&'+course_id] = session['user_id']
|
||||||
|
|
||||||
|
# 在学习目录下创建一个名为 user_id_path 的文件夹
|
||||||
|
path_dir = os.path.join(student_workspace_root_path, user_id, course_id,chapter_id)
|
||||||
|
os.makedirs(path_dir, exist_ok=True)
|
||||||
|
# 在此文件夹内部创建一个.config文件,并写入 user_id=user_id\n path=path
|
||||||
|
config_path = os.path.join(path_dir, '.config')
|
||||||
|
if GLOBAL_CONFIG['VSCODE_WEB_PATH']['is_wsl']: # 如果是在 WSL 中运行,则将路径转换为 WSL 路径
|
||||||
|
path_dir = path_dir.replace('\\', '/')
|
||||||
|
path_dir = path_dir.replace(GLOBAL_CONFIG['VSCODE_WEB_PATH']['windows_path'] , GLOBAL_CONFIG['VSCODE_WEB_PATH']['wsl_path'])
|
||||||
|
with open(config_path, 'w', encoding='utf-8') as f:
|
||||||
|
tmpd = {'user_id': user_id, 'course_id': course_id, 'chapter_id': chapter_id, 'path': path_dir}
|
||||||
|
json.dump(tmpd, f)
|
||||||
|
print('---------------------')
|
||||||
|
print(config_path)
|
||||||
|
return render_template('desktop.html', vscode_web_url=VSCODE_WEB_URL, user_id=user_id, course_id=course_id, chapter_id=chapter_id, workspace_path=path_dir)
|
||||||
|
|
||||||
|
@app.route('/desktop_nouser/<course_id>/<chapter_id>')
|
||||||
|
def desktop_nouser(course_id, chapter_id):
|
||||||
|
if 'user_id' not in session:
|
||||||
|
return redirect(url_for('login'))
|
||||||
|
user_id = session['user_id']
|
||||||
|
username = uuid2username[user_id]
|
||||||
|
return redirect(url_for('desktop', user_id=username, course_id=course_id, chapter_id=chapter_id))
|
||||||
|
|
||||||
|
@app.route('/vscode_data', methods=['POST'])
|
||||||
|
def vscode_data():
|
||||||
|
data = request.json
|
||||||
|
config = data['config']
|
||||||
|
realtime_response(config,data)
|
||||||
|
print(f"Received data from VSCode: {data}")
|
||||||
|
return jsonify({"status": "success", "received": data})
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
'''
|
||||||
|
Login
|
||||||
|
|
||||||
|
'''
|
||||||
|
users_list = UserList()
|
||||||
|
course_list = CourseList()
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/register')
|
||||||
|
def register():
|
||||||
|
return render_template('register.html')
|
||||||
|
|
||||||
|
@app.route('/register_teacher')
|
||||||
|
def register_teacher():
|
||||||
|
return render_template('register_teacher.html')
|
||||||
|
|
||||||
|
@app.route('/register_teacher_post', methods=['POST'])
|
||||||
|
def register_teacher_post():
|
||||||
|
data = request.get_json()
|
||||||
|
username = data.get('username')
|
||||||
|
password = data.get('password')
|
||||||
|
if users_list.has_user(username) is not None:
|
||||||
|
users_list.add_user(username, password, teacher=True)
|
||||||
|
create_user_json(username, USER_DATA_DIR)
|
||||||
|
return jsonify({'success': True, 'message': '注册成功'})
|
||||||
|
else: return jsonify({'success': False, 'message': '用户已存在,请更换用户名'})
|
||||||
|
|
||||||
|
@app.route('/register_post', methods=['POST'])
|
||||||
|
def register_post():
|
||||||
|
data = request.get_json()
|
||||||
|
username = data.get('username')
|
||||||
|
password = data.get('password')
|
||||||
|
if users_list.has_user(username) is not None:
|
||||||
|
users_list.add_user(username, password)
|
||||||
|
create_user_json(username, USER_DATA_DIR)
|
||||||
|
return jsonify({'success': True, 'message': '注册成功'})
|
||||||
|
else: return jsonify({'success': False, 'message': '用户已存在,请更换用户名'})
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/login')
|
||||||
|
def login():
|
||||||
|
return render_template('login.html')
|
||||||
|
if 'user_id' not in session:
|
||||||
|
return render_template('login.html')
|
||||||
|
else:
|
||||||
|
return redirect(url_for('/'))
|
||||||
|
|
||||||
|
@app.route('/login_post', methods=['POST'])
|
||||||
|
def login_post():
|
||||||
|
# 获取请求的 JSON 数据
|
||||||
|
data = request.get_json()
|
||||||
|
|
||||||
|
username = data.get('username')
|
||||||
|
password = data.get('password')
|
||||||
|
|
||||||
|
pswd = users_list.get_user_pswd(username)
|
||||||
|
|
||||||
|
if pswd is None:
|
||||||
|
return jsonify({'success': False, 'message': '用户名或密码错误'})
|
||||||
|
if pswd != password:
|
||||||
|
return jsonify({'success': False, 'message': '用户名或密码错误'})
|
||||||
|
|
||||||
|
session['user_id'] = 'user_' + str(uuid.uuid4())
|
||||||
|
print("user "+ username + "uuid is"+ session['user_id'])
|
||||||
|
username2uuid[username] = session['user_id']
|
||||||
|
uuid2username[session['user_id']] = username
|
||||||
|
return jsonify({'success': True, 'message': '登录成功'})
|
||||||
|
|
||||||
|
@app.route('/login_teacher_post', methods=['POST'])
|
||||||
|
def login_teacher_post():
|
||||||
|
data = request.get_json()
|
||||||
|
username = data.get('username')
|
||||||
|
password = data.get('password')
|
||||||
|
pswd = users_list.get_user_pswd(username)
|
||||||
|
is_teacher = users_list.get_user_is_teacher(username)
|
||||||
|
if is_teacher is None or is_teacher == False:
|
||||||
|
return jsonify({'success': False, 'message': '用户名不存在或非教师账号'})
|
||||||
|
if pswd is None:
|
||||||
|
return jsonify({'success': False, 'message': '用户名或密码错误'})
|
||||||
|
if pswd != password:
|
||||||
|
return jsonify({'success': False, 'message': '用户名或密码错误'})
|
||||||
|
session['user_id'] = 'user_' + str(uuid.uuid4())
|
||||||
|
print("user "+ username + "uuid is"+ session['user_id'])
|
||||||
|
username2uuid[username] = session['user_id']
|
||||||
|
uuid2username[session['user_id']] = username
|
||||||
|
return jsonify({'success': True, 'message': '登录成功'})
|
||||||
|
|
||||||
|
@app.route('/teacherboard')
|
||||||
|
@require_role(roles="teacher")
|
||||||
|
def teacherboard():
|
||||||
|
return render_template('teacherboard.html')
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/logout')
|
||||||
|
def logout():
|
||||||
|
session.pop('user_id', None)
|
||||||
|
return redirect(url_for('login'))
|
||||||
|
|
||||||
|
@app.route('/get_session')
|
||||||
|
def get_session():
|
||||||
|
user_session = session.get('user_id', 'default_session')
|
||||||
|
return jsonify({"session": user_session})
|
||||||
|
|
||||||
|
|
||||||
|
'''
|
||||||
|
DashBoard
|
||||||
|
'''
|
||||||
|
user_id2UserClass = {}
|
||||||
|
@app.route('/dashboard')
|
||||||
|
@require_role
|
||||||
|
def dashboard():
|
||||||
|
user_id = session['user_id']
|
||||||
|
username = uuid2username[user_id]
|
||||||
|
if (user_id not in user_id2UserClass):
|
||||||
|
user_id2UserClass[user_id] = load_user_from_json(username, user_data_dir = USER_DATA_DIR)
|
||||||
|
user_course_data = []
|
||||||
|
for course_id in user_id2UserClass[user_id].select_course:
|
||||||
|
course_brief_info = course_list.get_course_brief_info(course_id, load_course_from_json(course_id, course_data_dir = COURSE_DATA_DIR))
|
||||||
|
user_course_data.append(course_brief_info)
|
||||||
|
return render_template('dashboard.html',user_data = user_id2UserClass[user_id].to_json_without_dialog(), user_course_data = json.dumps(user_course_data))
|
||||||
|
|
||||||
|
'''
|
||||||
|
Course
|
||||||
|
'''
|
||||||
|
|
||||||
|
@app.route('/course/<course_id>')
|
||||||
|
@require_role
|
||||||
|
def course(course_id):
|
||||||
|
c = load_course_from_json(course_id, course_data_dir = COURSE_DATA_DIR)
|
||||||
|
return render_template('course.html', course_id=course_id, course_data=c)
|
||||||
|
|
||||||
|
@app.route('/select_course', methods=['POST'])
|
||||||
|
@require_role
|
||||||
|
def select_course():
|
||||||
|
user = user_id2UserClass[session['user_id']]
|
||||||
|
data = request.get_json()
|
||||||
|
course_id = data.get('course_id')
|
||||||
|
if course_id:
|
||||||
|
user.select_new_course(course_id, load_course_from_json(course_id, COURSE_DATA_DIR))
|
||||||
|
return jsonify({'success': True, 'message': '课程选择成功'})
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
@require_role
|
||||||
|
def home_index():
|
||||||
|
selected_courses=[]
|
||||||
|
if ('user_id' in session):
|
||||||
|
if (session['user_id'] not in user_id2UserClass): return redirect(url_for('login'))
|
||||||
|
user = user_id2UserClass[session['user_id']]
|
||||||
|
for course_id in user.select_course:
|
||||||
|
selected_courses.append(course_id)
|
||||||
|
|
||||||
|
return render_template('index.html', courses_data = course_list, selected_courses =selected_courses)
|
||||||
|
|
||||||
|
# 一些app辅助函数,主要提供给Agent与数据库的交互能力
|
||||||
|
|
||||||
|
class MyFunction:
|
||||||
|
def save_chapter_memory(self, id, course_id, lesson_id, subchapter_title, mem_list, score, is_rebuttal):
|
||||||
|
print("-=-=-=-=-=-=-=-")
|
||||||
|
print(id, course_id, lesson_id, subchapter_title, mem_list, score, is_rebuttal)
|
||||||
|
username = uuid2username[id]
|
||||||
|
u = load_user_from_json(username, user_data_dir = USER_DATA_DIR)
|
||||||
|
u.save_chapter_memory(course_id, lesson_id, subchapter_title, mem_list, score, is_rebuttal)
|
||||||
|
|
||||||
|
app.my_function = MyFunction()
|
||||||
|
if __name__ == '__main__':
|
||||||
|
socketio.on_namespace(VSCodeNamespace('/vscode'))
|
||||||
|
socketio.on_namespace(AgentNamespace('/agent'))
|
||||||
|
socketio.run(app, host='0.0.0.0', port=5551, debug=False,allow_unsafe_werkzeug=True)
|
||||||
|
|
||||||
File diff suppressed because one or more lines are too long
@@ -60,7 +60,6 @@
|
|||||||
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 {
|
||||||
@@ -82,27 +81,6 @@
|
|||||||
.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; /* 行高 */
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 课程目录弹出框 */
|
/* 课程目录弹出框 */
|
||||||
@@ -181,14 +159,11 @@
|
|||||||
/* 浮窗内容 */
|
/* 浮窗内容 */
|
||||||
.modal-content {
|
.modal-content {
|
||||||
background-color: #fff;
|
background-color: #fff;
|
||||||
margin: 10% auto; /* 修改为10%以缩小顶部距离 */
|
margin: 15% auto;
|
||||||
padding: 20px;
|
padding: 20px;
|
||||||
border-radius: 10px;
|
border-radius: 10px;
|
||||||
width: 80%; /* 修改为80%以适应小屏幕 */
|
width: 40%;
|
||||||
max-width: 600px; /* 设置最大宽度 */
|
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
|
||||||
box-shadow: 0 4px 8px rgba(0, 0, 0, 0 1);
|
|
||||||
overflow-y: auto; /* 添加垂直滚动条 */
|
|
||||||
max-height: 80vh; /* 设置最大高度 */
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 按钮样式 */
|
/* 按钮样式 */
|
||||||
@@ -230,34 +205,7 @@ 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 {
|
||||||
@@ -485,20 +433,6 @@ 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;
|
||||||
|
|||||||
@@ -292,50 +292,13 @@ 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;
|
||||||
// 构建发送的数据
|
// 构建发送的数据
|
||||||
@@ -349,7 +312,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
|
||||||
|
|||||||
@@ -46,7 +46,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{% include 'footer-brief.html' %}
|
{% include 'foot.html' %}
|
||||||
</body>
|
</body>
|
||||||
<script>
|
<script>
|
||||||
var course_id = "{{course_id}}";
|
var course_id = "{{course_id}}";
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
</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">
|
||||||
@@ -80,7 +81,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{% include 'footer-brief.html' %}
|
{% include 'foot.html' %}
|
||||||
|
|
||||||
<script src="/static/js/dashboard.js"></script>
|
<script src="/static/js/dashboard.js"></script>
|
||||||
<script>
|
<script>
|
||||||
|
|||||||
@@ -1,11 +0,0 @@
|
|||||||
<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>
|
|
||||||
@@ -80,7 +80,7 @@
|
|||||||
</main>
|
</main>
|
||||||
|
|
||||||
|
|
||||||
{% include 'footer-brief.html' %}
|
{% include 'foot.html' %}
|
||||||
</body>
|
</body>
|
||||||
<script>
|
<script>
|
||||||
window.appData = {
|
window.appData = {
|
||||||
|
|||||||
@@ -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 materials %}
|
{% for course in courses %}
|
||||||
<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 'footer-brief.html' %}
|
{% include 'foot.html' %}
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
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
|
||||||
@@ -38,60 +37,24 @@ 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', 'PUT', 'DELETE'])
|
@bp.route('/materials/<material_id>', methods=['GET'])
|
||||||
@require_role(roles="teacher")
|
@require_role(roles="teacher")
|
||||||
def handle_material(material_id):
|
def get_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':
|
|
||||||
if material_id is None:
|
@bp.route('/materials/<material_id>', methods=['PUT'])
|
||||||
return jsonify({"message": "教材名称不能为空"}), 400
|
@require_role(roles="teacher")
|
||||||
material = load_material(material_id)
|
def update_existing_material(material_id):
|
||||||
print(material)
|
data = request.get_json()
|
||||||
return jsonify(material.model_dump()), 200
|
chapters = data.get('chapters')
|
||||||
|
if update_material(material_id, chapters):
|
||||||
elif request.method == 'PUT':
|
return jsonify({"message": "教材更新成功"}), 200
|
||||||
data = request.get_json()
|
return jsonify({"message": "教材未找到"}), 404
|
||||||
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")
|
||||||
|
|||||||
@@ -39,35 +39,56 @@ def read_and_forward_pty_output(fd=None, pid=None, room_id=None,namespace=None):
|
|||||||
"""
|
"""
|
||||||
max_read_bytes = 1024 * 20
|
max_read_bytes = 1024 * 20
|
||||||
timeout=0.1
|
timeout=0.1
|
||||||
while True:
|
try:
|
||||||
socketio.sleep(timeout)
|
while True:
|
||||||
timeout=min(timeout*2, 0.4)
|
socketio.sleep(timeout)
|
||||||
# using flask default web server, or uwsgi production web server
|
timeout=min(timeout*2, 0.4)
|
||||||
# when the child process is terminated, it will not disappear from linux process list
|
# using flask default web server, or uwsgi production web server
|
||||||
# and keep staying as a zombie process until the parent exits.
|
# when the child process is terminated, it will not disappear from linux process list
|
||||||
try:
|
# and keep staying as a zombie process until the parent exits.
|
||||||
child_process = psutil.Process(pid)
|
try:
|
||||||
except psutil.NoSuchProcess as err:
|
child_process = psutil.Process(pid)
|
||||||
return
|
except psutil.NoSuchProcess as err:
|
||||||
if child_process.status() not in ('running', 'sleeping'):
|
# Process already terminated, clean up any zombie
|
||||||
return
|
|
||||||
if fd:
|
|
||||||
timeout_sec = 0
|
|
||||||
(data_ready, _, _) = select.select([fd], [], [], timeout_sec)
|
|
||||||
if data_ready:
|
|
||||||
# output = os.read(fd, max_read_bytes).decode('ascii')
|
|
||||||
timeout=0.1
|
|
||||||
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
|
||||||
{}
|
if child_process.status() not in ('running', 'sleeping'):
|
||||||
***********************
|
# Process is terminated or in other state, clean up
|
||||||
""".format(err)
|
try:
|
||||||
# the key for different visitor to get different terminal (instead of mixing up)
|
child_process.wait(timeout=1)
|
||||||
# is to let the background task push pty response to each one's own (default) ROOM!
|
except Exception:
|
||||||
namespace.emit("pty_output", {"output": output}, room=room_id)
|
try:
|
||||||
|
os.waitpid(pid, os.WNOHANG)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return
|
||||||
|
if fd:
|
||||||
|
timeout_sec = 0
|
||||||
|
(data_ready, _, _) = select.select([fd], [], [], timeout_sec)
|
||||||
|
if data_ready:
|
||||||
|
# output = os.read(fd, max_read_bytes).decode('ascii')
|
||||||
|
timeout=0.1
|
||||||
|
try:
|
||||||
|
output = os.read(fd, max_read_bytes).decode()
|
||||||
|
except Exception as err:
|
||||||
|
output = """
|
||||||
|
***AQUI WEB TERM ERR***
|
||||||
|
{}
|
||||||
|
***********************
|
||||||
|
""".format(err)
|
||||||
|
# the key for different visitor to get different terminal (instead of mixing up)
|
||||||
|
# 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)
|
||||||
|
finally:
|
||||||
|
# Clean up file descriptor if it's open
|
||||||
|
if fd:
|
||||||
|
try:
|
||||||
|
os.close(fd)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
class VSCLikeNameSpace(Namespace):
|
class VSCLikeNameSpace(Namespace):
|
||||||
def on_connect(self):
|
def on_connect(self):
|
||||||
@@ -156,15 +177,40 @@ class VSCLikeNameSpace(Namespace):
|
|||||||
set_winsize(fd, data["rows"], data["cols"])
|
set_winsize(fd, data["rows"], data["cols"])
|
||||||
|
|
||||||
def on_disconnect(self):
|
def on_disconnect(self):
|
||||||
try:
|
child_pid = session.get('terminal_config', {}).get('child_pid')
|
||||||
child_process = psutil.Process(session.get('terminal_config', {}).get('child_pid'))
|
if child_pid:
|
||||||
except psutil.NoSuchProcess as err:
|
try:
|
||||||
disconnect()
|
child_process = psutil.Process(child_pid)
|
||||||
session['terminal_config'] = TERM_INIT_CONFIG
|
if child_process.status() in ('running', 'sleeping'):
|
||||||
return
|
# if visitor just close the browser tab then left alone the pty here
|
||||||
if child_process.status() in ('running', 'sleeping'):
|
# it should be terminated by the parent process after
|
||||||
# if visitor just close the browser tab then left alone the pty here
|
child_process.terminate()
|
||||||
# it should be terminated by the parent process after
|
# Wait for the process to terminate and collect its exit status
|
||||||
child_process.terminate()
|
child_process.wait(timeout=2)
|
||||||
current_app.logger.debug('user left the pty alone, terminated')
|
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
|
||||||
|
child_process.kill()
|
||||||
|
try:
|
||||||
|
child_process.wait(timeout=1)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
except Exception as err:
|
||||||
|
current_app.logger.error(f'Error terminating process: {err}')
|
||||||
|
finally:
|
||||||
|
# Close the file descriptor if it's open
|
||||||
|
fd = session.get('terminal_config', {}).get('fd')
|
||||||
|
if fd:
|
||||||
|
try:
|
||||||
|
os.close(fd)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
# Reset session config
|
||||||
|
session['terminal_config'] = TERM_INIT_CONFIG
|
||||||
current_app.logger.debug('Client disconnected')
|
current_app.logger.debug('Client disconnected')
|
||||||
@@ -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>
|
||||||
|
|||||||
Reference in New Issue
Block a user