-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathtools.py
More file actions
185 lines (155 loc) · 6.95 KB
/
tools.py
File metadata and controls
185 lines (155 loc) · 6.95 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
import json, time
class Tools:
def __init__(self):
pass
def generate_profile(
self, id=1, phone=70000000000, avatarUrl=None,
photoId=None, updateTime=0,
firstName="Test", lastName="Account", options=[],
description=None, accountStatus=0, profileOptions=[],
includeProfileOptions=True, username=None, type="ONEME"
):
contact = {
"id": id,
"updateTime": updateTime,
"phone": phone,
"names": [
{
"name": firstName,
"firstName": firstName,
"lastName": lastName,
"type": "ONEME"
}
],
"options": options,
"accountStatus": accountStatus
}
if avatarUrl:
contact["photoId"] = photoId
contact["baseUrl"] = avatarUrl
contact["baseRawUrl"] = avatarUrl
if description:
contact["description"] = description
if username:
contact["link"] = "https://max.ru/" + username
if includeProfileOptions == True:
return {
"contact": contact,
"profileOptions": profileOptions
}
else:
return contact
def generate_chat(self, id, owner, type, participants, lastMessage, lastEventTime):
"""Генерация чата"""
# Генерируем список участников
result_participants = {
str(participant): 0 for participant in participants
}
result = None
# Генерируем нужный список в зависимости от типа чата
if type == "DIALOG":
result = {
"id": id,
"type": type,
"status": "ACTIVE",
"owner": owner,
"participants": result_participants,
"lastMessage": lastMessage,
"lastEventTime": lastEventTime,
"lastDelayedUpdateTime": 0,
"lastFireDelayedErrorTime": 0,
"created": 1,
"joinTime": 1,
"modified": lastEventTime
}
# Возвращаем
return result
async def generate_chats(self, chatIds, db_pool, senderId):
"""Генерирует чаты для отдачи клиенту"""
# Готовый список с чатами
chats = []
# Формируем список чатов
for chatId in chatIds:
async with db_pool.acquire() as db_connection:
async with db_connection.cursor() as cursor:
# Получаем чат по id
await cursor.execute("SELECT * FROM `chats` WHERE id = %s", (chatId,))
row = await cursor.fetchone()
if row:
# Получаем последнее сообщение из чата
message, messageTime = await self.get_last_message(
chatId, db_pool
)
# Формируем список участников
participants = {
str(participant): 0 for participant in row.get("participants")
}
# Выносим результат в лист
chats.append(
self.generate_chat(
row.get("id"),
row.get("owner"),
row.get("type"),
participants,
message,
messageTime
)
)
# Получаем последнее сообщение из избранного
message, messageTime = await self.get_last_message(
senderId, db_pool
)
# ID избранного
chatId = senderId ^ senderId
# Хардкодим в лист чатов избранное
chats.append(
self.generate_chat(
chatId,
senderId,
"DIALOG",
[senderId],
message,
messageTime
)
)
return chats
async def insert_message(self, chatId, senderId, text, attaches, elements, cid, type, db_pool):
"""Добавление сообщения в историю"""
async with db_pool.acquire() as db_connection:
async with db_connection.cursor() as cursor:
# Получаем id последнего сообщения в чате
await cursor.execute("SELECT id FROM `messages` WHERE chat_id = %s ORDER BY time DESC LIMIT 1", (chatId,))
row = await cursor.fetchone() or {}
last_message_id = row.get("id") or 0 # последнее id сообщения в чате
# Вносим новое сообщение в таблицу
await cursor.execute(
"INSERT INTO `messages` (chat_id, sender, time, text, attaches, cid, elements, type) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
(chatId, senderId, int(time.time() * 1000), text, json.dumps(attaches), cid, json.dumps(elements), type)
)
message_id = cursor.lastrowid # id сообщения
# Возвращаем айдишки
return int(message_id), int(last_message_id)
async def get_last_message(self, chatId, db_pool):
"""Получение последнего сообщения в чате"""
async with db_pool.acquire() as db_connection:
async with db_connection.cursor() as cursor:
# Получаем id последнего сообщения в чате
await cursor.execute("SELECT * FROM `messages` WHERE chat_id = %s ORDER BY time DESC LIMIT 1", (chatId,))
row = await cursor.fetchone()
# Если нет результатов - возвращаем None
if not row:
return None, None
# Собираем сообщение
message = {
"id": row.get("id"),
"time": int(row.get("time")),
"type": row.get("type"),
"sender": row.get("sender"),
"cid": int(row.get("cid")),
"text": row.get("text"),
"attaches": json.loads(row.get("attaches")),
"elements": json.loads(row.get("elements")),
"reactionInfo": {}
}
# Возвращаем
return message, int(row.get("time"))