-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathchat.py
More file actions
262 lines (220 loc) · 10 KB
/
chat.py
File metadata and controls
262 lines (220 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
from flask import Blueprint, request, jsonify
from models import db, User, ProjectGroup, GroupMessage, Task, SharedFile
from auth import token_required
chat_bp = Blueprint('chat', __name__)
@chat_bp.route('/rooms', methods=['GET'])
@token_required
def get_chat_rooms(current_user):
"""获取当前用户的聊天室列表"""
# 获取用户所在的所有项目组
groups = current_user.project_groups
chat_rooms = []
for group in groups:
# 获取最新的消息
last_message = GroupMessage.query.filter_by(group_id=group.id).order_by(GroupMessage.sent_at.desc()).first()
# 获取未读消息数 (需要 MessageReadStatus 模型支持)
# 此处为简化实现,未读消息数暂时为0
unread_count = 0
chat_rooms.append({
'id': group.id,
'name': group.name,
'lastMessage': last_message.content if last_message else None,
'lastMessageTimestamp': last_message.sent_at if last_message else None,
'unreadCount': unread_count
})
return jsonify(chat_rooms)
@chat_bp.route('/rooms/<room_id>/messages', methods=['GET'])
@token_required
def get_messages(current_user, room_id):
"""分页获取指定聊天室的历史消息"""
# 验证用户是否是该项目组成员
group = ProjectGroup.query.filter_by(id=room_id).first()
if not group or current_user not in group.members:
return jsonify({'message': 'Chat room not found or access denied'}), 404
# 分页参数
page = request.args.get('page', 1, type=int)
per_page = request.args.get('per_page', 20, type=int)
# 查询历史消息(排除已删除的消息)
messages = GroupMessage.query.filter_by(
group_id=room_id,
is_deleted=False
).order_by(GroupMessage.sent_at.desc())\
.paginate(page=page, per_page=per_page, error_out=False)
response = []
for msg in messages.items:
sender = User.query.get(msg.sender_id)
# 统一返回字段为下划线风格,类型为大写
updated_str = None
try:
# updated_time 可能为Unix时间戳,序列化为字符串时间
if getattr(msg, 'updated_time', None) is not None:
from datetime import datetime
if isinstance(msg.updated_time, (int, float)):
updated_str = datetime.utcfromtimestamp(int(msg.updated_time)).strftime('%Y-%m-%d %H:%M:%S')
else:
updated_str = str(msg.updated_time)
except Exception:
updated_str = None
message_dict = {
'id': msg.id,
'room_id': msg.group_id,
'sender_id': msg.sender_id,
'sender_name': sender.username if sender else 'Unknown',
'content': msg.content,
'message_type': (msg.message_type or 'text').upper(),
'file_url': msg.file_url,
'task_id': msg.task_id,
'created_at': msg.sent_at,
'updated_time': updated_str
}
# 为非文本类型提供 caption 字段,便于客户端统一展示附加文字
try:
if (msg.message_type or 'text') in ['image', 'video', 'audio', 'file', 'task'] and (msg.content or '').strip():
message_dict['caption'] = msg.content
except Exception:
pass
# 添加回复消息ID(如果存在)
if msg.reply_to_id:
message_dict['reply_to_id'] = msg.reply_to_id
# 添加文件URL(如果是文件类型消息)
# file_url 已在主字段返回
# 添加任务信息(如果是任务类型消息)
if msg.task_id:
task = Task.query.filter_by(id=msg.task_id, is_deleted=False).first()
if task:
message_dict['task'] = task.to_dict()
response.append(message_dict)
return jsonify({
'messages': response,
'page': messages.page,
'pages': messages.pages,
'total': messages.total
})
@chat_bp.route('/rooms/<room_id>/messages', methods=['POST'])
@token_required
def send_message(current_user, room_id):
"""向指定聊天室发送消息(支持多种消息类型)"""
data = request.get_json()
if not data:
return jsonify({'success': False, 'message': 'Invalid request body'}), 400
# 验证用户是否是该项目组成员
group = ProjectGroup.query.filter_by(id=room_id).first()
if not group or current_user not in group.members:
return jsonify({'success': False, 'message': 'Chat room not found or access denied'}), 404
# 获取消息类型,默认为text
# 兼容客户端字段命名:messageType 或 message_type
message_type = data.get('messageType', data.get('message_type', 'text'))
if message_type not in ['text', 'image', 'video', 'audio', 'file', 'task']:
return jsonify({'success': False, 'message': 'Invalid message type'}), 400
content = data.get('content', '')
# 兼容客户端字段命名:fileUrl 或 file_url
file_url = data.get('fileUrl', data.get('file_url'))
task_id = data.get('taskId', data.get('task_id'))
reply_to_id = data.get('replyToId', data.get('reply_to_id')) # 支持回复消息功能
# 验证文件URL(如果是文件类型消息)
if message_type in ['image', 'video', 'audio', 'file']:
if not file_url:
return jsonify({'success': False, 'message': f'File URL or File ID is required for {message_type} message'}), 400
# 从file_url中提取文件ID(可能是完整URL或文件ID)
file_id = file_url
if '/' in file_url:
# 如果是URL,尝试提取文件ID(假设是/files/{fileId}格式)
parts = file_url.split('/')
file_id = parts[-1] if parts else file_url
# 验证文件存在且有权限访问
file = SharedFile.query.filter_by(id=file_id, is_deleted=False).first()
if not file:
return jsonify({'success': False, 'message': 'File not found'}), 404
# 检查权限
if file.user_id != current_user.id:
if file.group_id != room_id:
return jsonify({'success': False, 'message': 'Permission denied: File does not belong to this group'}), 403
# 验证任务ID(如果是任务类型消息)
if message_type == 'task':
if not task_id:
return jsonify({'success': False, 'message': 'Task ID is required for task message'}), 400
task = Task.query.filter_by(id=task_id, is_deleted=False).first()
if not task:
return jsonify({'success': False, 'message': 'Task not found'}), 404
# 验证任务权限:任务所有者或项目组成员
if task.user_id != current_user.id:
if task.project_id != room_id:
return jsonify({'success': False, 'message': 'Permission denied: Task does not belong to this group'}), 403
# 验证回复消息ID(如果提供)
if reply_to_id:
reply_message = GroupMessage.query.filter_by(id=reply_to_id, group_id=room_id, is_deleted=False).first()
if not reply_message:
return jsonify({'success': False, 'message': 'Reply message not found'}), 404
# 创建新消息
new_message = GroupMessage(
group_id=room_id,
sender_id=current_user.id,
content=content,
message_type=message_type,
file_url=file_url,
task_id=task_id,
reply_to_id=reply_to_id
)
db.session.add(new_message)
db.session.commit()
# 构造完整的消息对象用于返回和WebSocket广播
sender = User.query.get(new_message.sender_id)
# 统一返回字段为下划线风格,类型为大写
from datetime import datetime
updated_str = None
try:
if getattr(new_message, 'updated_time', None) is not None:
if isinstance(new_message.updated_time, (int, float)):
updated_str = datetime.utcfromtimestamp(int(new_message.updated_time)).strftime('%Y-%m-%d %H:%M:%S')
else:
updated_str = str(new_message.updated_time)
except Exception:
updated_str = None
message_data = {
'id': new_message.id,
'room_id': new_message.group_id,
'sender_id': new_message.sender_id,
'sender_name': sender.username if sender else 'Unknown',
'message_type': (new_message.message_type or 'text').upper(),
'content': new_message.content,
'created_at': new_message.sent_at,
'updated_time': updated_str
}
# 为非文本类型提供 caption 字段,便于客户端统一展示附加文字
try:
if (new_message.message_type or 'text') in ['image', 'video', 'audio', 'file', 'task'] and (new_message.content or '').strip():
message_data['caption'] = new_message.content
except Exception:
pass
# 添加回复消息ID
if new_message.reply_to_id:
message_data['reply_to_id'] = new_message.reply_to_id
# 添加文件URL
if new_message.file_url:
message_data['file_url'] = new_message.file_url
# 添加任务信息
if new_message.task_id:
task = Task.query.filter_by(id=new_message.task_id, is_deleted=False).first()
if task:
message_data['task'] = task.to_dict()
message_data['task_id'] = new_message.task_id
# 通过WebSocket广播新消息
try:
from utils.websocket_manager import ws_manager
ws_manager.broadcast_to_room(
str(room_id),
{
"type": "new_message",
"payload": message_data
}
)
except Exception as e:
print(f"WS Broadcast error: {e}")
# 保留 SocketIO 代码作为备份或向后兼容 (如果需要)
try:
from app import socketio
if socketio:
socketio.emit('new_message', {'type': 'new_message', 'payload': message_data}, room=str(room_id))
except (ImportError, AttributeError):
pass
return jsonify(message_data), 201