Spaces:
Sleeping
Sleeping
Update db_utils.py
Browse files- db_utils.py +130 -40
db_utils.py
CHANGED
|
@@ -1,71 +1,161 @@
|
|
| 1 |
# db_utils.py
|
| 2 |
-
|
| 3 |
import aiosqlite
|
| 4 |
-
import os
|
| 5 |
import logging
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
|
| 8 |
-
os.makedirs("data", exist_ok=True)
|
| 9 |
|
| 10 |
logger = logging.getLogger(__name__)
|
| 11 |
|
| 12 |
-
# ---
|
| 13 |
async def initialize_database():
|
|
|
|
| 14 |
async with aiosqlite.connect(DATABASE_NAME) as db:
|
| 15 |
await db.execute("""
|
| 16 |
-
CREATE TABLE IF NOT EXISTS
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
| 20 |
)
|
| 21 |
""")
|
| 22 |
|
| 23 |
await db.execute("""
|
| 24 |
-
CREATE TABLE IF NOT EXISTS
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
size INTEGER
|
| 30 |
)
|
| 31 |
""")
|
| 32 |
-
await db.commit()
|
| 33 |
-
logger.info(f"All tables initialized in database '{DATABASE_NAME}'.")
|
| 34 |
|
| 35 |
-
# --- Add/update user ---
|
| 36 |
-
async def add_or_update_user_db(user_id: int, username: str, first_name: str):
|
| 37 |
-
async with aiosqlite.connect(DATABASE_NAME) as db:
|
| 38 |
await db.execute("""
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
| 45 |
await db.commit()
|
|
|
|
| 46 |
|
| 47 |
-
# --- Cache
|
| 48 |
-
async def get_cached_file(short_id: str):
|
|
|
|
| 49 |
async with aiosqlite.connect(DATABASE_NAME) as db:
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
row = await cursor.fetchone()
|
| 54 |
if row:
|
| 55 |
return {
|
| 56 |
"file_id": row[0],
|
| 57 |
"filename": row[1],
|
| 58 |
"type": row[2],
|
| 59 |
-
"size": row[3]
|
| 60 |
-
"short_id": short_id
|
| 61 |
}
|
| 62 |
-
|
| 63 |
|
| 64 |
-
|
| 65 |
-
|
| 66 |
async with aiosqlite.connect(DATABASE_NAME) as db:
|
| 67 |
-
await db.execute(
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
await db.commit()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# db_utils.py
|
|
|
|
| 2 |
import aiosqlite
|
|
|
|
| 3 |
import logging
|
| 4 |
+
from datetime import datetime, timezone, timedelta
|
| 5 |
+
from typing import Optional, Dict, List
|
| 6 |
|
| 7 |
+
from config import DATABASE_NAME
|
|
|
|
| 8 |
|
| 9 |
logger = logging.getLogger(__name__)
|
| 10 |
|
| 11 |
+
# --- Initialization ---
|
| 12 |
async def initialize_database():
|
| 13 |
+
"""Sets up all necessary tables in the single database file."""
|
| 14 |
async with aiosqlite.connect(DATABASE_NAME) as db:
|
| 15 |
await db.execute("""
|
| 16 |
+
CREATE TABLE IF NOT EXISTS terabox_cache (
|
| 17 |
+
short_id TEXT PRIMARY KEY,
|
| 18 |
+
telegram_file_id TEXT NOT NULL,
|
| 19 |
+
filename TEXT NOT NULL,
|
| 20 |
+
media_type TEXT NOT NULL,
|
| 21 |
+
file_size INTEGER,
|
| 22 |
+
cached_at TIMESTAMP NOT NULL
|
| 23 |
)
|
| 24 |
""")
|
| 25 |
|
| 26 |
await db.execute("""
|
| 27 |
+
CREATE TABLE IF NOT EXISTS user_scheduled_deletions (
|
| 28 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 29 |
+
chat_id INTEGER NOT NULL,
|
| 30 |
+
message_id INTEGER NOT NULL,
|
| 31 |
+
delete_at TIMESTAMP NOT NULL
|
|
|
|
| 32 |
)
|
| 33 |
""")
|
|
|
|
|
|
|
| 34 |
|
|
|
|
|
|
|
|
|
|
| 35 |
await db.execute("""
|
| 36 |
+
CREATE TABLE IF NOT EXISTS users (
|
| 37 |
+
user_id INTEGER PRIMARY KEY,
|
| 38 |
+
username TEXT,
|
| 39 |
+
first_name TEXT,
|
| 40 |
+
last_seen TIMESTAMP NOT NULL,
|
| 41 |
+
is_active INTEGER DEFAULT 1
|
| 42 |
+
)
|
| 43 |
+
""")
|
| 44 |
+
|
| 45 |
await db.commit()
|
| 46 |
+
logger.info(f"All tables initialized in database '{DATABASE_NAME}'.")
|
| 47 |
|
| 48 |
+
# --- Cache Functions ---
|
| 49 |
+
async def get_cached_file(short_id: str) -> Optional[Dict]:
|
| 50 |
+
"""Retrieve cached file details if not expired."""
|
| 51 |
async with aiosqlite.connect(DATABASE_NAME) as db:
|
| 52 |
+
expiry_time = datetime.now(timezone.utc) - timedelta(days=7)
|
| 53 |
+
async with db.execute(
|
| 54 |
+
"""
|
| 55 |
+
SELECT telegram_file_id, filename, media_type, file_size
|
| 56 |
+
FROM terabox_cache
|
| 57 |
+
WHERE short_id = ? AND cached_at > ?
|
| 58 |
+
""",
|
| 59 |
+
(short_id, expiry_time)
|
| 60 |
+
) as cursor:
|
| 61 |
row = await cursor.fetchone()
|
| 62 |
if row:
|
| 63 |
return {
|
| 64 |
"file_id": row[0],
|
| 65 |
"filename": row[1],
|
| 66 |
"type": row[2],
|
| 67 |
+
"size": row[3]
|
|
|
|
| 68 |
}
|
| 69 |
+
return None
|
| 70 |
|
| 71 |
+
async def add_to_cache(short_id: str, telegram_file_id: str, filename: str, media_type: str, file_size: int):
|
| 72 |
+
"""Insert or update cached file info."""
|
| 73 |
async with aiosqlite.connect(DATABASE_NAME) as db:
|
| 74 |
+
await db.execute(
|
| 75 |
+
"""
|
| 76 |
+
INSERT OR REPLACE INTO terabox_cache
|
| 77 |
+
VALUES (?, ?, ?, ?, ?, ?)
|
| 78 |
+
""",
|
| 79 |
+
(
|
| 80 |
+
short_id,
|
| 81 |
+
telegram_file_id,
|
| 82 |
+
filename,
|
| 83 |
+
media_type,
|
| 84 |
+
file_size,
|
| 85 |
+
datetime.now(timezone.utc)
|
| 86 |
+
)
|
| 87 |
+
)
|
| 88 |
await db.commit()
|
| 89 |
+
|
| 90 |
+
# --- User Scheduled Deletion Functions ---
|
| 91 |
+
async def add_user_scheduled_deletion(chat_id: int, message_id: int, delete_at: datetime):
|
| 92 |
+
"""Schedule message deletion."""
|
| 93 |
+
async with aiosqlite.connect(DATABASE_NAME) as db:
|
| 94 |
+
await db.execute(
|
| 95 |
+
"""
|
| 96 |
+
INSERT INTO user_scheduled_deletions (chat_id, message_id, delete_at)
|
| 97 |
+
VALUES (?, ?, ?)
|
| 98 |
+
""",
|
| 99 |
+
(chat_id, message_id, delete_at)
|
| 100 |
+
)
|
| 101 |
+
await db.commit()
|
| 102 |
+
|
| 103 |
+
async def get_due_user_deletions() -> List[Dict]:
|
| 104 |
+
"""Fetch deletions that are due."""
|
| 105 |
+
async with aiosqlite.connect(DATABASE_NAME) as db:
|
| 106 |
+
async with db.execute(
|
| 107 |
+
"""
|
| 108 |
+
SELECT id, chat_id, message_id
|
| 109 |
+
FROM user_scheduled_deletions
|
| 110 |
+
WHERE delete_at <= ?
|
| 111 |
+
""",
|
| 112 |
+
(datetime.now(timezone.utc),)
|
| 113 |
+
) as cursor:
|
| 114 |
+
return [
|
| 115 |
+
{"id": row[0], "chat_id": row[1], "message_id": row[2]}
|
| 116 |
+
for row in await cursor.fetchall()
|
| 117 |
+
]
|
| 118 |
+
|
| 119 |
+
async def remove_user_scheduled_deletion(entry_id: int):
|
| 120 |
+
"""Remove scheduled deletion entry."""
|
| 121 |
+
async with aiosqlite.connect(DATABASE_NAME) as db:
|
| 122 |
+
await db.execute(
|
| 123 |
+
"DELETE FROM user_scheduled_deletions WHERE id = ?",
|
| 124 |
+
(entry_id,)
|
| 125 |
+
)
|
| 126 |
+
await db.commit()
|
| 127 |
+
|
| 128 |
+
# --- User Tracking Functions ---
|
| 129 |
+
async def add_or_update_user_db(user_id: int, username: Optional[str], first_name: Optional[str]):
|
| 130 |
+
"""Add new user or update existing user's info and activity."""
|
| 131 |
+
async with aiosqlite.connect(DATABASE_NAME) as db:
|
| 132 |
+
await db.execute(
|
| 133 |
+
"""
|
| 134 |
+
INSERT INTO users (user_id, username, first_name, last_seen, is_active)
|
| 135 |
+
VALUES (?, ?, ?, ?, 1)
|
| 136 |
+
ON CONFLICT(user_id) DO UPDATE SET
|
| 137 |
+
username=excluded.username,
|
| 138 |
+
first_name=excluded.first_name,
|
| 139 |
+
last_seen=excluded.last_seen,
|
| 140 |
+
is_active=1
|
| 141 |
+
""",
|
| 142 |
+
(user_id, username, first_name, datetime.now(timezone.utc))
|
| 143 |
+
)
|
| 144 |
+
await db.commit()
|
| 145 |
+
|
| 146 |
+
async def get_all_active_user_ids_db() -> List[int]:
|
| 147 |
+
"""Retrieve IDs of all active users."""
|
| 148 |
+
async with aiosqlite.connect(DATABASE_NAME) as db:
|
| 149 |
+
async with db.execute(
|
| 150 |
+
"SELECT user_id FROM users WHERE is_active = 1"
|
| 151 |
+
) as cursor:
|
| 152 |
+
return [row[0] for row in await cursor.fetchall()]
|
| 153 |
+
|
| 154 |
+
async def mark_user_inactive_db(user_id: int):
|
| 155 |
+
"""Mark user as inactive."""
|
| 156 |
+
async with aiosqlite.connect(DATABASE_NAME) as db:
|
| 157 |
+
await db.execute(
|
| 158 |
+
"UPDATE users SET is_active = 0 WHERE user_id = ?",
|
| 159 |
+
(user_id,)
|
| 160 |
+
)
|
| 161 |
+
await db.commit()
|