understanding commited on
Commit
ad6ca7e
·
verified ·
1 Parent(s): 5b5c90e

Update db_utils.py

Browse files
Files changed (1) hide show
  1. db_utils.py +76 -4
db_utils.py CHANGED
@@ -1,8 +1,9 @@
1
  # db_utils.py
 
2
  import aiosqlite
3
  import logging
4
- from datetime import datetime, timezone
5
- from typing import Optional
6
 
7
  from config import DATABASE_NAME
8
 
@@ -10,8 +11,19 @@ logger = logging.getLogger("db_utils")
10
 
11
  # --- Initialization ---
12
  async def initialize_database():
13
- """Sets up all necessary tables in the database."""
14
  async with aiosqlite.connect(DATABASE_NAME) as db:
 
 
 
 
 
 
 
 
 
 
 
15
  await db.execute("""
16
  CREATE TABLE IF NOT EXISTS users (
17
  user_id INTEGER PRIMARY KEY,
@@ -21,12 +33,55 @@ async def initialize_database():
21
  is_active INTEGER DEFAULT 1
22
  )
23
  """)
 
24
  await db.commit()
25
  logger.info(f"All tables initialized in database '{DATABASE_NAME}'.")
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  # --- User Tracking Functions ---
28
  async def add_or_update_user_db(user_id: int, username: Optional[str], first_name: Optional[str]):
29
- """Add new user or update existing user's info and activity."""
30
  async with aiosqlite.connect(DATABASE_NAME) as db:
31
  await db.execute(
32
  """
@@ -40,4 +95,21 @@ async def add_or_update_user_db(user_id: int, username: Optional[str], first_nam
40
  """,
41
  (user_id, username, first_name, datetime.now(timezone.utc))
42
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  await db.commit()
 
1
  # db_utils.py
2
+
3
  import aiosqlite
4
  import logging
5
+ from datetime import datetime, timezone, timedelta
6
+ from typing import Optional, Dict, List
7
 
8
  from config import DATABASE_NAME
9
 
 
11
 
12
  # --- Initialization ---
13
  async def initialize_database():
14
+ """Sets up all necessary tables."""
15
  async with aiosqlite.connect(DATABASE_NAME) as db:
16
+ await db.execute("""
17
+ CREATE TABLE IF NOT EXISTS terabox_cache (
18
+ short_id TEXT PRIMARY KEY,
19
+ telegram_file_id TEXT NOT NULL,
20
+ filename TEXT NOT NULL,
21
+ media_type TEXT NOT NULL,
22
+ file_size INTEGER,
23
+ cached_at TIMESTAMP NOT NULL
24
+ )
25
+ """)
26
+
27
  await db.execute("""
28
  CREATE TABLE IF NOT EXISTS users (
29
  user_id INTEGER PRIMARY KEY,
 
33
  is_active INTEGER DEFAULT 1
34
  )
35
  """)
36
+
37
  await db.commit()
38
  logger.info(f"All tables initialized in database '{DATABASE_NAME}'.")
39
 
40
+ # --- Cache Functions ---
41
+ async def get_cached_file(short_id: str) -> Optional[Dict]:
42
+ """Retrieve cached file if available and not expired."""
43
+ async with aiosqlite.connect(DATABASE_NAME) as db:
44
+ expiry_time = datetime.now(timezone.utc) - timedelta(days=7)
45
+ async with db.execute(
46
+ """
47
+ SELECT telegram_file_id, filename, media_type, file_size
48
+ FROM terabox_cache
49
+ WHERE short_id = ? AND cached_at > ?
50
+ """,
51
+ (short_id, expiry_time)
52
+ ) as cursor:
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
+ }
61
+ return None
62
+
63
+ async def add_to_cache(short_id: str, telegram_file_id: str, filename: str, media_type: str, file_size: int):
64
+ """Insert or update cached file info."""
65
+ async with aiosqlite.connect(DATABASE_NAME) as db:
66
+ await db.execute(
67
+ """
68
+ INSERT OR REPLACE INTO terabox_cache
69
+ VALUES (?, ?, ?, ?, ?, ?)
70
+ """,
71
+ (
72
+ short_id,
73
+ telegram_file_id,
74
+ filename,
75
+ media_type,
76
+ file_size,
77
+ datetime.now(timezone.utc)
78
+ )
79
+ )
80
+ await db.commit()
81
+
82
  # --- User Tracking Functions ---
83
  async def add_or_update_user_db(user_id: int, username: Optional[str], first_name: Optional[str]):
84
+ """Add new user or update existing user's info."""
85
  async with aiosqlite.connect(DATABASE_NAME) as db:
86
  await db.execute(
87
  """
 
95
  """,
96
  (user_id, username, first_name, datetime.now(timezone.utc))
97
  )
98
+ await db.commit()
99
+
100
+ async def get_all_active_user_ids_db() -> List[int]:
101
+ """Retrieve IDs of all active users."""
102
+ async with aiosqlite.connect(DATABASE_NAME) as db:
103
+ async with db.execute(
104
+ "SELECT user_id FROM users WHERE is_active = 1"
105
+ ) as cursor:
106
+ return [row[0] for row in await cursor.fetchall()]
107
+
108
+ async def mark_user_inactive_db(user_id: int):
109
+ """Mark user as inactive."""
110
+ async with aiosqlite.connect(DATABASE_NAME) as db:
111
+ await db.execute(
112
+ "UPDATE users SET is_active = 0 WHERE user_id = ?",
113
+ (user_id,)
114
+ )
115
  await db.commit()