-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
266 lines (236 loc) · 10.4 KB
/
Copy pathdatabase.py
File metadata and controls
266 lines (236 loc) · 10.4 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
263
264
265
266
"""Module for database operations"""
import sqlite3
import json
from datetime import datetime
from typing import Optional, List, Dict, Any
from contextlib import contextmanager
import config
class Database:
def __init__(self, db_path: str = config.DB_PATH):
self.db_path = db_path
self.init_db()
@contextmanager
def get_connection(self):
"""Context manager for database connection"""
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
try:
yield conn
conn.commit()
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
def init_db(self):
"""Initialize database schema"""
with self.get_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS chats (
chat_id INTEGER PRIMARY KEY,
chat_type TEXT,
title TEXT,
username TEXT,
first_seen TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
message_id INTEGER,
chat_id INTEGER,
sender_id INTEGER,
sender_name TEXT,
text TEXT,
date TIMESTAMP,
media_type TEXT,
media_path TEXT,
is_edited BOOLEAN DEFAULT 0,
is_deleted BOOLEAN DEFAULT 0,
deleted_at TIMESTAMP,
reply_to_msg_id INTEGER,
raw_data TEXT,
FOREIGN KEY (chat_id) REFERENCES chats(chat_id),
UNIQUE(message_id, chat_id)
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS message_edits (
id INTEGER PRIMARY KEY AUTOINCREMENT,
message_id INTEGER,
chat_id INTEGER,
old_text TEXT,
new_text TEXT,
edited_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (message_id, chat_id) REFERENCES messages(message_id, chat_id)
)
''')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_messages_chat ON messages(chat_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_messages_date ON messages(date)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_messages_deleted ON messages(is_deleted)')
def save_chat(self, chat_id: int, chat_type: str, title: str, username: Optional[str] = None):
"""Save chat information"""
with self.get_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO chats (chat_id, chat_type, title, username, last_activity)
VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
ON CONFLICT(chat_id) DO UPDATE SET
title = excluded.title,
username = excluded.username,
last_activity = CURRENT_TIMESTAMP
''', (chat_id, chat_type, title, username))
def save_message(self, message_data: Dict[str, Any], mark_edited: bool = False) -> int:
"""Save message"""
with self.get_connection() as conn:
cursor = conn.cursor()
if mark_edited:
cursor.execute('''
INSERT INTO messages (
message_id, chat_id, sender_id, sender_name, text,
date, media_type, media_path, reply_to_msg_id, raw_data
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(message_id, chat_id) DO UPDATE SET
text = excluded.text,
media_type = excluded.media_type,
media_path = excluded.media_path,
is_edited = 1
''', (
message_data['message_id'],
message_data['chat_id'],
message_data['sender_id'],
message_data['sender_name'],
message_data['text'],
message_data['date'],
message_data.get('media_type'),
message_data.get('media_path'),
message_data.get('reply_to_msg_id'),
json.dumps(message_data.get('raw_data', {}))
))
else:
cursor.execute('''
INSERT INTO messages (
message_id, chat_id, sender_id, sender_name, text,
date, media_type, media_path, reply_to_msg_id, raw_data
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(message_id, chat_id) DO NOTHING
''', (
message_data['message_id'],
message_data['chat_id'],
message_data['sender_id'],
message_data['sender_name'],
message_data['text'],
message_data['date'],
message_data.get('media_type'),
message_data.get('media_path'),
message_data.get('reply_to_msg_id'),
json.dumps(message_data.get('raw_data', {}))
))
return cursor.lastrowid
def mark_message_deleted(self, message_id: int, chat_id: int):
"""Mark message as deleted"""
with self.get_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
UPDATE messages
SET is_deleted = 1, deleted_at = CURRENT_TIMESTAMP
WHERE message_id = ? AND chat_id = ?
''', (message_id, chat_id))
return cursor.rowcount > 0
def find_message_chat_id(self, message_id: int) -> Optional[int]:
"""Find chat_id by message_id"""
with self.get_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT chat_id FROM messages
WHERE message_id = ?
LIMIT 1
''', (message_id,))
result = cursor.fetchone()
return result[0] if result else None
def save_message_edit(self, message_id: int, chat_id: int, old_text: str, new_text: str):
"""Save message edit history"""
with self.get_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO message_edits (message_id, chat_id, old_text, new_text)
VALUES (?, ?, ?, ?)
''', (message_id, chat_id, old_text, new_text))
def get_chats(self, limit: int = 100) -> List[Dict]:
"""Get list of chats"""
with self.get_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT c.*, COUNT(m.id) as message_count
FROM chats c
LEFT JOIN messages m ON c.chat_id = m.chat_id
GROUP BY c.chat_id
ORDER BY c.last_activity DESC
LIMIT ?
''', (limit,))
return [dict(row) for row in cursor.fetchall()]
def get_messages(self, chat_id: int, limit: int = 100, offset: int = 0,
include_deleted: bool = True) -> List[Dict]:
"""Get messages from chat"""
with self.get_connection() as conn:
cursor = conn.cursor()
query = '''
SELECT * FROM messages
WHERE chat_id = ?
'''
params = [chat_id]
if not include_deleted:
query += ' AND is_deleted = 0'
query += ' ORDER BY date DESC LIMIT ? OFFSET ?'
params.extend([limit, offset])
cursor.execute(query, params)
return [dict(row) for row in cursor.fetchall()]
def search_messages(self, query: str, chat_id: Optional[int] = None,
limit: int = 100) -> List[Dict]:
"""Search messages by text"""
with self.get_connection() as conn:
cursor = conn.cursor()
sql = '''
SELECT m.*, c.title as chat_title
FROM messages m
JOIN chats c ON m.chat_id = c.chat_id
WHERE m.text LIKE ?
'''
params = [f'%{query}%']
if chat_id:
sql += ' AND m.chat_id = ?'
params.append(chat_id)
sql += ' ORDER BY m.date DESC LIMIT ?'
params.append(limit)
cursor.execute(sql, params)
return [dict(row) for row in cursor.fetchall()]
def get_message_edits(self, message_id: int, chat_id: int) -> List[Dict]:
"""Get message edit history"""
with self.get_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM message_edits
WHERE message_id = ? AND chat_id = ?
ORDER BY edited_at DESC
''', (message_id, chat_id))
return [dict(row) for row in cursor.fetchall()]
def get_stats(self) -> Dict[str, Any]:
"""Database statistics"""
with self.get_connection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT COUNT(*) FROM chats')
total_chats = cursor.fetchone()[0]
cursor.execute('SELECT COUNT(*) FROM messages')
total_messages = cursor.fetchone()[0]
cursor.execute('SELECT COUNT(*) FROM messages WHERE is_deleted = 1')
deleted_messages = cursor.fetchone()[0]
cursor.execute('SELECT COUNT(*) FROM messages WHERE is_edited = 1')
edited_messages = cursor.fetchone()[0]
return {
'total_chats': total_chats,
'total_messages': total_messages,
'deleted_messages': deleted_messages,
'edited_messages': edited_messages
}