#!/usr/bin/env python3 # -*- coding: utf-8 -*- """修复定时任务并添加执行日志功能""" def add_schedule_logs_table(database_content): """在database.py中添加定时任务执行日志表""" # 在init_database函数中添加表创建代码 insert_position = ''' print(" ✓ 创建 user_schedules 表 (用户定时任务)")''' new_table_code = ''' print(" ✓ 创建 user_schedules 表 (用户定时任务)") # 定时任务执行日志表 cursor.execute(\''' CREATE TABLE IF NOT EXISTS schedule_execution_logs ( id INTEGER PRIMARY KEY AUTOINCREMENT, schedule_id INTEGER NOT NULL, user_id INTEGER NOT NULL, schedule_name TEXT, execute_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, total_accounts INTEGER DEFAULT 0, success_accounts INTEGER DEFAULT 0, failed_accounts INTEGER DEFAULT 0, total_items INTEGER DEFAULT 0, total_attachments INTEGER DEFAULT 0, total_screenshots INTEGER DEFAULT 0, duration_seconds INTEGER DEFAULT 0, status TEXT DEFAULT 'running', error_message TEXT, FOREIGN KEY (schedule_id) REFERENCES user_schedules (id) ON DELETE CASCADE, FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE ) \''') print(" ✓ 创建 schedule_execution_logs 表 (定时任务执行日志)")''' if insert_position in database_content: database_content = database_content.replace(insert_position, new_table_code) print("✓ 已添加schedule_execution_logs表创建代码") else: print("❌ 未找到插入位置") return database_content # 添加数据库操作函数 functions_code = ''' # ==================== 定时任务执行日志 ==================== def create_schedule_execution_log(schedule_id, user_id, schedule_name): """创建定时任务执行日志""" with db_pool.get_db() as conn: cursor = conn.cursor() cst_tz = pytz.timezone("Asia/Shanghai") execute_time = datetime.now(cst_tz).strftime("%Y-%m-%d %H:%M:%S") cursor.execute(\''' INSERT INTO schedule_execution_logs ( schedule_id, user_id, schedule_name, execute_time, status ) VALUES (?, ?, ?, ?, 'running') \''', (schedule_id, user_id, schedule_name, execute_time)) conn.commit() return cursor.lastrowid def update_schedule_execution_log(log_id, **kwargs): """更新定时任务执行日志""" with db_pool.get_db() as conn: cursor = conn.cursor() updates = [] params = [] allowed_fields = ['total_accounts', 'success_accounts', 'failed_accounts', 'total_items', 'total_attachments', 'total_screenshots', 'duration_seconds', 'status', 'error_message'] for field in allowed_fields: if field in kwargs: updates.append(f'{field} = ?') params.append(kwargs[field]) if not updates: return False params.append(log_id) sql = f"UPDATE schedule_execution_logs SET {', '.join(updates)} WHERE id = ?" cursor.execute(sql, params) conn.commit() return cursor.rowcount > 0 def get_schedule_execution_logs(schedule_id, limit=10): """获取定时任务执行日志""" with db_pool.get_db() as conn: cursor = conn.cursor() cursor.execute(\''' SELECT * FROM schedule_execution_logs WHERE schedule_id = ? ORDER BY execute_time DESC LIMIT ? \''', (schedule_id, limit)) return [dict(row) for row in cursor.fetchall()] def get_user_all_schedule_logs(user_id, limit=50): """获取用户所有定时任务的执行日志""" with db_pool.get_db() as conn: cursor = conn.cursor() cursor.execute(\''' SELECT * FROM schedule_execution_logs WHERE user_id = ? ORDER BY execute_time DESC LIMIT ? \''', (user_id, limit)) return [dict(row) for row in cursor.fetchall()] ''' # 在文件末尾添加这些函数 database_content += functions_code print("✓ 已添加定时任务日志操作函数") return database_content def add_schedule_log_tracking(app_content): """在app.py中添加定时任务执行日志记录""" # 修改check_user_schedules函数,添加日志记录 old_code = ''' print(f"[用户定时任务] 用户 {schedule_config.get('user_username', user_id)} 的任务 '{schedule_config.get('name', '')}' 开始执行") started_count = 0 for account_id in account_ids:''' new_code = ''' print(f"[用户定时任务] 用户 {schedule_config.get('user_username', user_id)} 的任务 '{schedule_config.get('name', '')}' 开始执行") # 创建执行日志 import time as time_mod execution_start_time = time_mod.time() log_id = database.create_schedule_execution_log( schedule_id=schedule_id, user_id=user_id, schedule_name=schedule_config.get('name', '未命名任务') ) started_count = 0 for account_id in account_ids:''' if old_code in app_content: app_content = app_content.replace(old_code, new_code) print("✓ 已添加执行日志创建代码") else: print("⚠ 未找到执行日志创建位置") # 添加日志更新代码(在任务执行完成后) old_code2 = ''' # 更新最后执行时间 database.update_schedule_last_run(schedule_id) print(f"[用户定时任务] 已启动 {started_count} 个账号")''' new_code2 = ''' # 更新最后执行时间 database.update_schedule_last_run(schedule_id) # 更新执行日志 execution_duration = int(time_mod.time() - execution_start_time) database.update_schedule_execution_log( log_id, total_accounts=len(account_ids), success_accounts=started_count, failed_accounts=len(account_ids) - started_count, duration_seconds=execution_duration, status='completed' ) print(f"[用户定时任务] 已启动 {started_count} 个账号")''' if old_code2 in app_content: app_content = app_content.replace(old_code2, new_code2) print("✓ 已添加执行日志更新代码") else: print("⚠ 未找到执行日志更新位置") # 添加日志查询API api_code = ''' # ==================== 定时任务执行日志API ==================== @app.route('/api/schedules//logs', methods=['GET']) @login_required def get_schedule_logs_api(schedule_id): """获取定时任务执行日志""" schedule = database.get_schedule_by_id(schedule_id) if not schedule: return jsonify({"error": "定时任务不存在"}), 404 if schedule['user_id'] != current_user.id: return jsonify({"error": "无权访问"}), 403 limit = request.args.get('limit', 10, type=int) logs = database.get_schedule_execution_logs(schedule_id, limit) return jsonify(logs) ''' # 在批量操作API之前插入 insert_marker = '# ==================== 批量操作API ====================' if insert_marker in app_content: app_content = app_content.replace(insert_marker, api_code + insert_marker) print("✓ 已添加日志查询API") else: print("⚠ 未找到API插入位置") return app_content def add_frontend_log_button(html_content): """在前端添加日志按钮""" # 修改定时任务卡片,添加日志按钮 old_html = ''' '' + '' +''' new_html = ''' '' + '' + '' +''' if old_html in html_content: html_content = html_content.replace(old_html, new_html) print("✓ 已添加日志按钮HTML") else: print("⚠ 未找到日志按钮插入位置") # 添加日志弹窗HTML modal_html = '''