-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdatabase.py
More file actions
382 lines (335 loc) · 15.2 KB
/
database.py
File metadata and controls
382 lines (335 loc) · 15.2 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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
#!/usr/bin/env python3
import sqlite3
import logging
import time
from pathlib import Path
from typing import Optional, Dict, Any
from contextlib import contextmanager
logger = logging.getLogger(__name__)
PERMANENT_TTL = 9999999999
def calculate_time_remaining(ttl: int, current_time: int) -> Dict[str, Any]:
"""
Calculate time remaining for a secret with smart formatting
Returns object with time remaining and formatted display string
"""
if ttl == PERMANENT_TTL:
return {
"value": -1,
"display": "Permanent",
"type": "permanent"
}
seconds_remaining = max(0, ttl - current_time)
hours_remaining = seconds_remaining // (60 * 60)
days_remaining = seconds_remaining // (24 * 60 * 60)
if seconds_remaining == 0:
return {
"value": 0,
"display": "Expired",
"type": "expired"
}
if days_remaining >= 1:
return {
"value": days_remaining,
"display": f"{days_remaining} day{'s' if days_remaining != 1 else ''}",
"type": "days"
}
elif hours_remaining >= 1:
return {
"value": hours_remaining,
"display": f"{hours_remaining} hour{'s' if hours_remaining != 1 else ''}",
"type": "hours"
}
else:
minutes_remaining = max(1, seconds_remaining // 60)
return {
"value": minutes_remaining,
"display": f"{minutes_remaining} minute{'s' if minutes_remaining != 1 else ''}",
"type": "minutes"
}
class DatabaseManager:
"""SQLite database manager for Inigma messages"""
def __init__(self, db_path: str = "data/inigma.db"):
self.db_path = Path(db_path)
# Создаем папку data если её нет
self.db_path.parent.mkdir(exist_ok=True)
self.init_database()
def init_database(self):
"""Initialize database with required tables"""
with self.get_connection() as conn:
cursor = conn.cursor()
# Create messages table
cursor.execute("""
CREATE TABLE IF NOT EXISTS messages (
id TEXT PRIMARY KEY,
ttl INTEGER NOT NULL,
uid TEXT NOT NULL DEFAULT '',
encrypted_message TEXT NOT NULL,
iv TEXT NOT NULL,
salt TEXT NOT NULL,
custom_name TEXT DEFAULT '',
creator_uid TEXT DEFAULT '',
created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
)
""")
# Create indexes for efficient queries
# Single-column indexes
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_messages_uid ON messages(uid)
""")
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_messages_creator_uid ON messages(creator_uid)
""")
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_messages_ttl ON messages(ttl)
""")
# Composite indexes for better performance
# Optimizes list_user_secrets query
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_messages_uid_ttl_created
ON messages(uid, ttl, created_at DESC)
""")
# Optimizes list_pending_secrets query
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_messages_creator_uid_ttl
ON messages(creator_uid, uid, ttl)
""")
# Optimizes cleanup_expired_messages query
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_messages_ttl_created_cleanup
ON messages(ttl, created_at)
""")
conn.commit()
logger.info(f"Database initialized at {self.db_path}")
@contextmanager
def get_connection(self):
"""Get database connection with proper error handling"""
conn = None
try:
conn = sqlite3.connect(self.db_path)
conn.execute('PRAGMA journal_mode=WAL')
conn.execute('PRAGMA busy_timeout=5000')
conn.row_factory = sqlite3.Row # Enable dict-like access
yield conn
except Exception as e:
if conn:
conn.rollback()
logger.error(f"Database error: {e}")
raise
finally:
if conn:
conn.close()
def store_message(self, message_id: str, data: Dict[str, Any]) -> bool:
"""Store message data in database"""
try:
with self.get_connection() as conn:
cursor = conn.cursor()
cursor.execute("""
INSERT INTO messages
(id, ttl, uid, encrypted_message, iv, salt, custom_name, creator_uid)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""", (
message_id,
data['ttl'],
data.get('uid', ''),
data['encrypted_message'],
data['iv'],
data['salt'],
data.get('custom_name', ''),
data.get('creator_uid', '')
))
conn.commit()
logger.debug(f"Message {message_id} stored successfully")
return True
except Exception as e:
logger.error(f"Error storing message {message_id}: {e}")
return False
def retrieve_message(self, message_id: str) -> Optional[Dict[str, Any]]:
"""Retrieve message data from database"""
try:
with self.get_connection() as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT * FROM messages WHERE id = ?
""", (message_id,))
row = cursor.fetchone()
if row:
return dict(row)
return None
except Exception as e:
logger.error(f"Error retrieving message {message_id}: {e}")
return None
def update_message_owner(self, message_id: str, uid: str, encrypted_message: str,
iv: str, salt: str) -> Dict[str, Any]:
"""Update message owner and content. Returns structured result matching Workers."""
try:
with self.get_connection() as conn:
cursor = conn.cursor()
cursor.execute("""
UPDATE messages
SET uid = ?, encrypted_message = ?, iv = ?, salt = ?
WHERE id = ? AND uid = ''
""", (uid, encrypted_message, iv, salt, message_id))
conn.commit()
if cursor.rowcount > 0:
logger.debug(f"Message {message_id} owner updated successfully")
return {"ok": True}
# Distinguish: not found vs already owned
cursor.execute("SELECT uid FROM messages WHERE id = ?", (message_id,))
row = cursor.fetchone()
if row is None:
return {"ok": False, "error": "not_found"}
return {"ok": False, "error": "already_owned"}
except Exception as e:
logger.error(f"Error updating message owner {message_id}: {e}")
return {"ok": False, "error": "db_error"}
def update_custom_name(self, message_id: str, uid: str, custom_name: str) -> bool:
"""Update custom name for a message"""
try:
with self.get_connection() as conn:
cursor = conn.cursor()
cursor.execute("""
UPDATE messages
SET custom_name = ?
WHERE id = ? AND uid = ?
""", (custom_name, message_id, uid))
conn.commit()
if cursor.rowcount > 0:
logger.debug(f"Custom name updated for message {message_id}")
return True
else:
logger.warning(f"Message {message_id} not found or access denied")
return False
except Exception as e:
logger.error(f"Error updating custom name for {message_id}: {e}")
return False
def delete_message(self, message_id: str, uid: str) -> Dict[str, Any]:
"""Delete a message (only if user owns it or created it). Returns structured result."""
try:
with self.get_connection() as conn:
cursor = conn.cursor()
# Delete if user owns it or created it (for pending messages)
cursor.execute("""
DELETE FROM messages
WHERE id = ? AND (uid = ? OR (uid = '' AND creator_uid = ?))
""", (message_id, uid, uid))
conn.commit()
if cursor.rowcount > 0:
logger.debug(f"Message {message_id} deleted successfully")
return {"ok": True}
else:
logger.warning(f"Message {message_id} not found or access denied")
return {"ok": False, "error": "not_found"}
except Exception as e:
logger.error(f"Error deleting message {message_id}: {e}")
return {"ok": False, "error": "db_error"}
def list_user_secrets(self, uid: str, page: int = 1, per_page: int = 10) -> Dict[str, Any]:
"""List user's owned secrets with pagination"""
try:
current_time = int(time.time())
offset = (page - 1) * per_page
logger.debug(f"Listing secrets for uid: {uid}, current_time: {current_time}")
with self.get_connection() as conn:
cursor = conn.cursor()
# Debug: Check all messages for this uid
cursor.execute("SELECT id, uid, ttl FROM messages WHERE uid = ?", (uid,))
all_user_messages = cursor.fetchall()
logger.debug(f"All messages for uid {uid}: {all_user_messages}")
# Get total count
cursor.execute("""
SELECT COUNT(*) FROM messages
WHERE uid = ? AND (ttl > ? OR ttl = ?)
""", (uid, current_time, PERMANENT_TTL))
total = cursor.fetchone()[0]
logger.debug(f"Total count for uid {uid}: {total}")
# Get paginated results
cursor.execute("""
SELECT id, custom_name, ttl, created_at
FROM messages
WHERE uid = ? AND (ttl > ? OR ttl = ?)
ORDER BY created_at DESC
LIMIT ? OFFSET ?
""", (uid, current_time, PERMANENT_TTL, per_page, offset))
secrets = []
for row in cursor.fetchall():
row = dict(row)
# Calculate time remaining with smart formatting
time_remaining = calculate_time_remaining(row['ttl'], current_time)
secrets.append({
"id": row['id'],
"custom_name": row['custom_name'] or "",
"days_remaining": time_remaining["value"],
"time_remaining_display": time_remaining["display"],
"time_remaining_type": time_remaining["type"]
})
logger.debug(f"Found {len(secrets)} secrets for uid {uid}")
return {
"secrets": secrets,
"page": page,
"per_page": per_page,
"total": total,
"has_more": (offset + per_page) < total
}
except Exception as e:
logger.error(f"Error listing user secrets: {e}")
return {"secrets": [], "page": page, "per_page": per_page, "total": 0, "has_more": False}
def list_pending_secrets(self, creator_uid: str, page: int = 1, per_page: int = 10) -> Dict[str, Any]:
"""List user's pending (unclaimed) secrets with pagination"""
try:
current_time = int(time.time())
offset = (page - 1) * per_page
with self.get_connection() as conn:
cursor = conn.cursor()
# Get total count
cursor.execute("""
SELECT COUNT(*) FROM messages
WHERE creator_uid = ? AND uid = '' AND (ttl > ? OR ttl = ?)
""", (creator_uid, current_time, PERMANENT_TTL))
total = cursor.fetchone()[0]
# Get paginated results
cursor.execute("""
SELECT id, custom_name, ttl, created_at
FROM messages
WHERE creator_uid = ? AND uid = '' AND (ttl > ? OR ttl = ?)
ORDER BY created_at DESC
LIMIT ? OFFSET ?
""", (creator_uid, current_time, PERMANENT_TTL, per_page, offset))
secrets = []
for row in cursor.fetchall():
row = dict(row)
# Calculate time remaining with smart formatting
time_remaining = calculate_time_remaining(row['ttl'], current_time)
secrets.append({
"id": row['id'],
"custom_name": row['custom_name'] or "",
"days_remaining": time_remaining["value"],
"time_remaining_display": time_remaining["display"],
"time_remaining_type": time_remaining["type"]
})
return {
"secrets": secrets,
"page": page,
"per_page": per_page,
"total": total,
"has_more": (offset + per_page) < total
}
except Exception as e:
logger.error(f"Error listing pending secrets: {e}")
return {"secrets": [], "page": page, "per_page": per_page, "total": 0, "has_more": False}
def cleanup_expired_messages(self, cleanup_days: int = 50) -> int:
"""Remove expired messages and messages older than cleanup_days"""
try:
current_time = int(time.time())
cutoff_time = current_time - (cleanup_days * 24 * 60 * 60)
with self.get_connection() as conn:
cursor = conn.cursor()
cursor.execute("""
DELETE FROM messages
WHERE (ttl < ? AND ttl != ?) OR created_at < ?
""", (current_time, PERMANENT_TTL, cutoff_time))
deleted_count = cursor.rowcount
conn.commit()
logger.info(f"Cleanup completed. Deleted {deleted_count} expired messages")
return deleted_count
except Exception as e:
logger.error(f"Error during cleanup: {e}")
return 0