ZHIWEI666 commited on
Commit
0b38188
·
verified ·
1 Parent(s): af39c17

Upload router_messages.py

Browse files
Files changed (1) hide show
  1. router_messages.py +161 -105
router_messages.py CHANGED
@@ -1,106 +1,162 @@
1
- # router_messages.py
2
- from fastapi import APIRouter
3
- import time
4
- import uuid
5
- import 数据库连接 as db
6
- from notifications import add_notification
7
- from models import PrivateMessage
8
-
9
- router = APIRouter()
10
-
11
- @router.post("/api/messages/private")
12
- async def send_private_message(msg: PrivateMessage):
13
- chats_db = db.load_data("chats.json", default_data={})
14
- conv_id = f"{min(msg.sender, msg.receiver)}_{max(msg.sender, msg.receiver)}"
15
- if conv_id not in chats_db: chats_db[conv_id] = []
16
-
17
- chat_msg = {"id": f"chat_{int(time.time())}_{uuid.uuid4().hex[:6]}", "sender": msg.sender, "receiver": msg.receiver, "content": msg.content, "created_at": int(time.time()), "is_read": False}
18
- chats_db[conv_id].append(chat_msg)
19
- db.save_data("chats.json", chats_db)
20
-
21
- add_notification(msg.receiver, {"type": "private", "from_user": msg.sender, "content": msg.content})
22
- return {"status": "success"}
23
-
24
- @router.get("/api/chats/{account}")
25
- async def get_chat_list(account: str):
26
- chats_db = db.load_data("chats.json", default_data={})
27
- users_db = db.load_data("users.json", default_data={})
28
- chat_list = []
29
- now = int(time.time())
30
- seven_days = 7 * 24 * 3600
31
-
32
- for conv_id, msgs in chats_db.items():
33
- accs = conv_id.split("_")
34
- if account in accs and msgs:
35
- # 列表中只统计有效消息
36
- valid_msgs = [m for m in msgs if not m.get("is_read") or (now - m.get("created_at", 0) < seven_days)]
37
- if valid_msgs:
38
- target = accs[0] if accs[1] == account else accs[1]
39
- target_info = users_db.get(target, {})
40
- chat_list.append({
41
- "target_account": target, "target_name": target_info.get("name", target),
42
- "last_message": valid_msgs[-1]["content"], "last_time": valid_msgs[-1]["created_at"],
43
- "unread": sum(1 for m in valid_msgs if m["receiver"] == account and not m.get("is_read"))
44
- })
45
- chat_list.sort(key=lambda x: x["last_time"], reverse=True)
46
- return {"status": "success", "data": chat_list}
47
-
48
- @router.get("/api/chats/{account}/{target}")
49
- async def get_chat_history(account: str, target: str):
50
- chats_db = db.load_data("chats.json", default_data={})
51
- conv_id = f"{min(account, target)}_{max(account, target)}"
52
- msgs = chats_db.get(conv_id, [])
53
-
54
- now = int(time.time())
55
- seven_days = 7 * 24 * 3600
56
- valid_msgs = []
57
- modified = False
58
-
59
- for m in msgs:
60
- # 【核心策略】:未读的永远保留,已读的超过 7 天直接抛弃
61
- if not m.get("is_read") or (now - m.get("created_at", 0) < seven_days):
62
- valid_msgs.append(m)
63
- else:
64
- modified = True
65
-
66
- # 本次访问即为已读
67
- if m["receiver"] == account and not m.get("is_read"):
68
- m["is_read"] = True
69
- modified = True
70
-
71
- if modified or len(valid_msgs) != len(msgs):
72
- chats_db[conv_id] = valid_msgs
73
- db.save_data("chats.json", chats_db)
74
-
75
- return {"status": "success", "data": valid_msgs}
76
-
77
- @router.get("/api/messages/{account}")
78
- async def get_messages(account: str):
79
- msgs_db = db.load_data("messages.json", default_data={})
80
- user_msgs = msgs_db.get(account, [])
81
-
82
- now = int(time.time())
83
- seven_days = 7 * 24 * 3600
84
- valid = []
85
- modified = False
86
-
87
- for m in user_msgs:
88
- if not m.get("is_read") or (now - m.get("created_at", 0) < seven_days):
89
- valid.append(m)
90
- else:
91
- modified = True
92
-
93
- if modified:
94
- msgs_db[account] = valid
95
- db.save_data("messages.json", msgs_db)
96
-
97
- return {"status": "success", "data": valid, "unread_count": sum(1 for m in valid if not m.get("is_read"))}
98
-
99
- @router.post("/api/messages/{account}/read")
100
- async def mark_messages_read(account: str):
101
- msgs_db = db.load_data("messages.json", default_data={})
102
- user_msgs = msgs_db.get(account, [])
103
- for m in user_msgs: m["is_read"] = True
104
- msgs_db[account] = user_msgs
105
- db.save_data("messages.json", msgs_db)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  return {"status": "success"}
 
1
+ # router_messages.py
2
+ from fastapi import APIRouter, HTTPException
3
+ from pydantic import BaseModel
4
+ import time
5
+ import uuid
6
+ import 数据库连接 as db
7
+ from notifications import add_notification
8
+ from models import PrivateMessage
9
+
10
+ router = APIRouter()
11
+
12
+ # === 用于接收系统公告的请求体模型 ===
13
+ class SystemAnnouncement(BaseModel):
14
+ admin_account: str
15
+ content: str
16
+
17
+ # === 发布系统公告接口 (仅限管理员) ===
18
+ @router.post("/api/system/announcement")
19
+ async def publish_announcement(ann: SystemAnnouncement):
20
+ if ann.admin_account != "666666":
21
+ raise HTTPException(status_code=403, detail="无权发布系统公告")
22
+
23
+ announcements_db = db.load_data("announcements.json", default_data=[])
24
+
25
+ new_ann = {
26
+ "id": f"sys_{int(time.time())}_{uuid.uuid4().hex[:6]}",
27
+ "type": "system",
28
+ "from_user": "666666",
29
+ "from_name": "官方团队",
30
+ "from_avatar": "https://via.placeholder.com/150/FF9800/FFFFFF?text=Sys",
31
+ "content": ann.content,
32
+ "created_at": int(time.time())
33
+ }
34
+
35
+ announcements_db.append(new_ann)
36
+ db.save_data("announcements.json", announcements_db)
37
+
38
+ return {"status": "success", "data": new_ann}
39
+
40
+ @router.post("/api/messages/private")
41
+ async def send_private_message(msg: PrivateMessage):
42
+ chats_db = db.load_data("chats.json", default_data={})
43
+ conv_id = f"{min(msg.sender, msg.receiver)}_{max(msg.sender, msg.receiver)}"
44
+ if conv_id not in chats_db: chats_db[conv_id] = []
45
+
46
+ chat_msg = {"id": f"chat_{int(time.time())}_{uuid.uuid4().hex[:6]}", "sender": msg.sender, "receiver": msg.receiver, "content": msg.content, "created_at": int(time.time()), "is_read": False}
47
+ chats_db[conv_id].append(chat_msg)
48
+ db.save_data("chats.json", chats_db)
49
+
50
+ add_notification(msg.receiver, {"type": "private", "from_user": msg.sender, "content": msg.content})
51
+ return {"status": "success"}
52
+
53
+ @router.get("/api/chats/{account}")
54
+ async def get_chat_list(account: str):
55
+ chats_db = db.load_data("chats.json", default_data={})
56
+ users_db = db.load_data("users.json", default_data={})
57
+
58
+ chat_list = []
59
+ for conv_id, msgs in chats_db.items():
60
+ if account in conv_id:
61
+ participants = conv_id.split("_")
62
+ target_account = participants[0] if participants[1] == account else participants[1]
63
+ if not msgs: continue
64
+
65
+ last_msg = sorted(msgs, key=lambda x: x.get("created_at", 0))[-1]
66
+ unread_count = sum(1 for m in msgs if m["receiver"] == account and not m.get("is_read"))
67
+
68
+ target_user = users_db.get(target_account, {})
69
+ chat_list.append({
70
+ "target_account": target_account,
71
+ "target_name": target_user.get("name", target_account),
72
+ "target_avatar": target_user.get("avatarDataUrl", "https://via.placeholder.com/150"),
73
+ "last_message": last_msg["content"],
74
+ "last_time": last_msg["created_at"],
75
+ "unread_count": unread_count
76
+ })
77
+
78
+ chat_list.sort(key=lambda x: x["last_time"], reverse=True)
79
+ return {"status": "success", "data": chat_list}
80
+
81
+ @router.get("/api/chats/{account}/{target_account}")
82
+ async def get_chat_history(account: str, target_account: str):
83
+ chats_db = db.load_data("chats.json", default_data={})
84
+ conv_id = f"{min(account, target_account)}_{max(account, target_account)}"
85
+ msgs = chats_db.get(conv_id, [])
86
+
87
+ now = int(time.time())
88
+ seven_days = 7 * 24 * 3600
89
+ valid_msgs = []
90
+ modified = False
91
+
92
+ for m in msgs:
93
+ if now - m.get("created_at", 0) < seven_days:
94
+ valid_msgs.append(m)
95
+ else:
96
+ modified = True
97
+
98
+ if m["receiver"] == account and not m.get("is_read"):
99
+ m["is_read"] = True
100
+ modified = True
101
+
102
+ if modified or len(valid_msgs) != len(msgs):
103
+ chats_db[conv_id] = valid_msgs
104
+ db.save_data("chats.json", chats_db)
105
+
106
+ return {"status": "success", "data": valid_msgs}
107
+
108
+ @router.get("/api/messages/{account}")
109
+ async def get_messages(account: str):
110
+ msgs_db = db.load_data("messages.json", default_data={})
111
+ user_msgs = msgs_db.get(account, [])
112
+
113
+ # --- 系统公告懒加载注入 ---
114
+ announcements_db = db.load_data("announcements.json", default_data=[])
115
+ user_msg_ids = {m.get("id") for m in user_msgs}
116
+
117
+ injected = False
118
+ for ann in announcements_db:
119
+ if ann.get("id") not in user_msg_ids:
120
+ new_sys_msg = dict(ann)
121
+ new_sys_msg["is_read"] = False
122
+ new_sys_msg["receiver"] = account
123
+ user_msgs.append(new_sys_msg)
124
+ injected = True
125
+
126
+ if injected:
127
+ user_msgs.sort(key=lambda x: x.get("created_at", 0), reverse=True)
128
+ # --------------------------
129
+
130
+ now = int(time.time())
131
+ seven_days = 7 * 24 * 3600
132
+ valid = []
133
+ modified = injected
134
+
135
+ for m in user_msgs:
136
+ if not m.get("is_read") or (now - m.get("created_at", 0) < seven_days):
137
+ valid.append(m)
138
+ else:
139
+ modified = True
140
+
141
+ if modified:
142
+ msgs_db[account] = valid
143
+ db.save_data("messages.json", msgs_db)
144
+
145
+ return {"status": "success", "data": valid, "unread_count": sum(1 for m in valid if not m.get("is_read"))}
146
+
147
+ @router.post("/api/messages/{account}/read")
148
+ async def mark_messages_read(account: str):
149
+ msgs_db = db.load_data("messages.json", default_data={})
150
+ user_msgs = msgs_db.get(account, [])
151
+ modified = False
152
+
153
+ for m in user_msgs:
154
+ if not m.get("is_read"):
155
+ m["is_read"] = True
156
+ modified = True
157
+
158
+ if modified:
159
+ msgs_db[account] = user_msgs
160
+ db.save_data("messages.json", msgs_db)
161
+
162
  return {"status": "success"}