Files
SmartChat/app.py
lychang d10ec1f911 init
2025-11-01 02:40:17 +08:00

605 lines
17 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from flask import Flask, render_template, jsonify, request
import sqlite3
import json
from datetime import datetime
import os
app = Flask(__name__)
# 数据库文件路径
DB_PATH = 'data.sqlite'
def get_db_connection():
"""获取数据库连接"""
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
return conn
@app.route('/')
def index():
"""主页面 - 聊天界面"""
return render_template('index.html')
@app.route('/api/messages_by_ids', methods=['POST'])
def get_messages_by_ids():
"""根据消息ID列表获取消息内容"""
try:
data = request.get_json()
message_ids = data.get('message_ids', [])
if not message_ids:
return jsonify({
'success': True,
'messages': []
})
conn = get_db_connection()
cursor = conn.cursor()
# 构建IN查询的占位符
placeholders = ','.join(['?'] * len(message_ids))
query = f"SELECT id, content, type,sender,receiver,datetime(substr(time,0,11), 'unixepoch','localtime') as formatted_time FROM message WHERE id IN ({placeholders}) order by time"
cursor.execute(query, message_ids)
messages_data = cursor.fetchall()
messages = [dict(msg) for msg in messages_data]
conn.close()
return jsonify({
'success': True,
'messages': messages
})
except Exception as e:
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/messages')
def get_messages():
"""获取消息列表API"""
try:
conn = get_db_connection()
cursor = conn.cursor()
# 获取查询参数
limit = request.args.get('limit', 100, type=int)
offset = request.args.get('offset', 0, type=int)
group_id = request.args.get('group_id', type=str)
# 构建查询条件
query = '''
SELECT m.*, u.name as sender_name, g.name as group_name
FROM message m
LEFT JOIN user u ON m.sender = u.id
LEFT JOIN "group" g ON m.receiver = g.id
where m.type NOT IN ('disagree', 'agree', 'webapp', 'link') \
'''
params = []
if group_id:
query += ' AND g.id = ?'
params.append(group_id)
query += ' ORDER BY m.time ASC LIMIT ? OFFSET ?'
params.extend([limit, offset])
# 查询消息数据
cursor.execute(query, params)
messages = cursor.fetchall()
# 格式化消息数据
formatted_messages = []
for msg in messages:
message_data = dict(msg)
# 处理时间戳
if message_data['time']:
try:
timestamp = int(message_data['time'][:-3])
message_data['formatted_time'] = datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
except:
message_data['formatted_time'] = '未知时间'
# 处理消息内容
content = message_data['content']
if message_data['type'] == 'text':
message_data['display_content'] = content
elif message_data['type'] in ['image', 'file', 'video', 'voice']:
message_data['display_content'] = f'[{message_data["type"]}] {content}'
elif message_data['type'] == 'mixed':
try:
mixed_content = json.loads(content)
display_parts = []
for item in mixed_content:
msg_type, item_content = item
if msg_type == 'text':
display_parts.append(item_content)
else:
display_parts.append(f'[{msg_type}]')
message_data['display_content'] = ' '.join(display_parts)
except:
message_data['display_content'] = '[混合消息]'
elif message_data['type'] == 'chatrecord':
try:
chatrecord_data = json.loads(content)
if 'chatrecord' in chatrecord_data and 'title' in chatrecord_data['chatrecord']:
message_data['display_content'] = f'[聊天记录] {chatrecord_data["chatrecord"]["title"]}'
message_data['chatrecord_data'] = chatrecord_data # 保存完整数据供前端使用
else:
message_data['display_content'] = '[聊天记录]'
except:
message_data['display_content'] = '[聊天记录]'
else:
message_data['display_content'] = f'[{message_data["type"]}] {content}'
formatted_messages.append(message_data)
conn.close()
return jsonify({
'success': True,
'messages': formatted_messages,
'total': len(formatted_messages)
})
except Exception as e:
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/users')
def get_users():
"""获取用户列表API"""
try:
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('SELECT * FROM user ORDER BY name')
users = cursor.fetchall()
user_list = [dict(user) for user in users]
conn.close()
return jsonify({
'success': True,
'users': user_list
})
except Exception as e:
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/groups')
def get_groups():
"""获取群组列表API"""
try:
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('SELECT * FROM "group" ORDER BY id')
groups = cursor.fetchall()
group_list = [dict(group) for group in groups]
conn.close()
return jsonify({
'success': True,
'groups': group_list
})
except Exception as e:
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/group_messages')
def get_group_messages():
"""获取按群组分组的消息统计API"""
try:
conn = get_db_connection()
cursor = conn.cursor()
# 获取每个群组的消息统计
cursor.execute('''
SELECT g.id as group_id,
g.name as group_name,
COUNT(m.id) as message_count,
MAX(m.time) as latest_message_time,
COUNT(DISTINCT m.sender) as member_count
FROM "group" g
LEFT JOIN message m ON g.id = m.receiver
WHERE m.toType = 1
GROUP BY g.id, g.name
ORDER BY latest_message_time DESC
''')
groups = cursor.fetchall()
group_list = []
for group in groups:
group_data = dict(group)
# 处理最新消息时间
if group_data['latest_message_time']:
try:
timestamp = int(group_data['latest_message_time'][:-3])
group_data['latest_message_time_formatted'] = datetime.fromtimestamp(timestamp).strftime(
'%Y-%m-%d %H:%M:%S')
except Exception as e:
print(f"时间转换错误: {e}")
group_data['latest_message_time_formatted'] = '未知时间'
else:
group_data['latest_message_time_formatted'] = '暂无消息'
group_list.append(group_data)
conn.close()
return jsonify({
'success': True,
'groups': group_list
})
except Exception as e:
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/statistics')
def get_statistics():
"""获取统计信息API"""
try:
conn = get_db_connection()
cursor = conn.cursor()
# 获取用户数量
cursor.execute('SELECT COUNT(*) as count FROM user')
user_count = cursor.fetchone()['count']
# 获取群组数量
cursor.execute('SELECT COUNT(*) as count FROM "group"')
group_count = cursor.fetchone()['count']
# 获取消息数量
cursor.execute('SELECT COUNT(*) as count FROM message')
message_count = cursor.fetchone()['count']
# 获取文件数量
cursor.execute('SELECT COUNT(*) as count FROM file')
file_count = cursor.fetchone()['count']
# 获取最新消息时间
cursor.execute('SELECT MAX(time) as latest_time FROM message')
latest_time_result = cursor.fetchone()
latest_time = latest_time_result['latest_time'] if latest_time_result['latest_time'] else None
if latest_time:
try:
latest_time_formatted = datetime.fromtimestamp(int(latest_time)).strftime('%Y-%m-%d %H:%M:%S')
except:
latest_time_formatted = '未知时间'
else:
latest_time_formatted = '暂无消息'
conn.close()
return jsonify({
'success': True,
'statistics': {
'user_count': user_count,
'group_count': group_count,
'message_count': message_count,
'file_count': file_count,
'latest_message_time': latest_time_formatted
}
})
except Exception as e:
return jsonify({
'success': False,
'error': str(e)
}), 500
def init_qa_table():
"""初始化qa表"""
try:
conn = get_db_connection()
cursor = conn.cursor()
# 检查qa表是否存在,如果不存在则创建
cursor.execute("""
CREATE TABLE IF NOT EXISTS qa (
id INTEGER PRIMARY KEY AUTOINCREMENT,
groupId TEXT,
question JSON DEFAULT '[]' NOT NULL,
answer JSON DEFAULT '[]' NOT NULL
)
""")
conn.commit()
conn.close()
print("qa表初始化完成")
except Exception as e:
print(f"初始化qa表时出错: {e}")
@app.route('/qa')
def qa_page():
"""问答管理页面"""
return render_template('qa.html')
@app.route('/api/qa')
def get_qa_list():
"""获取QA列表API"""
try:
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('SELECT * FROM qa ORDER BY id DESC')
qa_list = cursor.fetchall()
result = []
for qa in qa_list:
qa_data = dict(qa)
# 解析JSON字段
try:
qa_data['question_list'] = json.loads(qa_data['question'])
qa_data['answer_list'] = json.loads(qa_data['answer'])
except:
qa_data['question_list'] = []
qa_data['answer_list'] = []
result.append(qa_data)
conn.close()
return jsonify({
'success': True,
'qa_list': result
})
except Exception as e:
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/qa/<int:qa_id>')
def get_qa_detail(qa_id):
"""获取单个QA详情API"""
try:
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('SELECT * FROM qa WHERE id = ?', (qa_id,))
qa = cursor.fetchone()
if not qa:
return jsonify({
'success': False,
'error': 'QA记录不存在'
}), 404
qa_data = dict(qa)
# 解析JSON字段
try:
qa_data['question_list'] = json.loads(qa_data['question'])
qa_data['answer_list'] = json.loads(qa_data['answer'])
except:
qa_data['question_list'] = []
qa_data['answer_list'] = []
conn.close()
return jsonify({
'success': True,
'qa': qa_data
})
except Exception as e:
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/qa', methods=['POST'])
def create_qa():
"""创建QA记录API"""
try:
data = request.get_json()
group_id = data.get('groupId', '')
question_ids = data.get('question', [])
answer_ids = data.get('answer', [])
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
INSERT INTO qa (groupId, question, answer)
VALUES (?, ?, ?)
''', (group_id, json.dumps(question_ids), json.dumps(answer_ids)))
conn.commit()
qa_id = cursor.lastrowid
conn.close()
return jsonify({
'success': True,
'id': qa_id,
'message': 'QA记录创建成功'
})
except Exception as e:
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/qa/<int:qa_id>', methods=['PUT'])
def update_qa(qa_id):
"""更新QA记录API"""
try:
data = request.get_json()
group_id = data.get('groupId', '')
question_ids = data.get('question', [])
answer_ids = data.get('answer', [])
conn = get_db_connection()
cursor = conn.cursor()
# 检查记录是否存在
cursor.execute('SELECT id FROM qa WHERE id = ?', (qa_id,))
if not cursor.fetchone():
return jsonify({
'success': False,
'error': 'QA记录不存在'
}), 404
cursor.execute('''
UPDATE qa
SET groupId = ?, question = ?, answer = ?
WHERE id = ?
''', (group_id, json.dumps(question_ids), json.dumps(answer_ids), qa_id))
conn.commit()
conn.close()
return jsonify({
'success': True,
'message': 'QA记录更新成功'
})
except Exception as e:
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/qa/<int:qa_id>', methods=['DELETE'])
def delete_qa(qa_id):
"""删除QA记录API"""
try:
conn = get_db_connection()
cursor = conn.cursor()
# 检查记录是否存在
cursor.execute('SELECT id FROM qa WHERE id = ?', (qa_id,))
if not cursor.fetchone():
return jsonify({
'success': False,
'error': 'QA记录不存在'
}), 404
cursor.execute('DELETE FROM qa WHERE id = ?', (qa_id,))
conn.commit()
conn.close()
return jsonify({
'success': True,
'message': 'QA记录删除成功'
})
except Exception as e:
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/search_messages')
def search_messages():
"""搜索消息API"""
try:
keyword = request.args.get('keyword', '')
limit = request.args.get('limit', 50, type=int)
group_id = request.args.get('groupId', '')
if not keyword:
return jsonify({
'success': True,
'messages': []
})
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
SELECT id, content, type, time, sender, receiver
FROM message
WHERE content LIKE ?
AND type NOT IN ('disagree', 'agree', 'webapp', 'link')
ORDER BY time DESC
LIMIT ?
''', (f'%{keyword}%', limit))
messages = cursor.fetchall()
result = []
for msg in messages:
message_data = dict(msg)
# 处理时间戳
if message_data['time']:
try:
timestamp = int(message_data['time'][:-3])
message_data['formatted_time'] = datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
except:
message_data['formatted_time'] = '未知时间'
result.append(message_data)
conn.close()
return jsonify({
'success': True,
'messages': result
})
except Exception as e:
return jsonify({
'success': False,
'error': str(e)
}), 500
if __name__ == '__main__':
# 检查数据库文件是否存在
if not os.path.exists(DB_PATH):
print(f"错误: 数据库文件 {DB_PATH} 不存在")
print("请确保data.sqlite文件在当前目录下")
else:
# 初始化qa表
init_qa_table()
print("启动聊天网页服务...")
print("访问地址: http://127.0.0.1:5000")
print("问答页面: http://127.0.0.1:5000/qa")
app.run(debug=True, host='127.0.0.1', port=5000)