-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
351 lines (302 loc) · 13.5 KB
/
Copy pathdatabase.py
File metadata and controls
351 lines (302 loc) · 13.5 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
"""
database.py — All SQLite operations for the bot.
Uses aiosqlite for non-blocking async I/O compatible with python-telegram-bot v20.
"""
import aiosqlite
import logging
from datetime import datetime, timedelta
from typing import Optional, List, Dict, Any
logger = logging.getLogger(__name__)
DB_PATH = "dropsvipbot.db"
# ══════════════════════════════════════════════════════════════════════════════
# Schema
# ══════════════════════════════════════════════════════════════════════════════
SCHEMA = """
CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
username TEXT,
first_name TEXT,
last_name TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_banned INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS subscriptions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
sub_type TEXT NOT NULL, -- 'paid' | 'free'
start_date TIMESTAMP NOT NULL,
end_date TIMESTAMP NOT NULL,
is_active INTEGER DEFAULT 1,
FOREIGN KEY (user_id) REFERENCES users(user_id)
);
CREATE TABLE IF NOT EXISTS payments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
method TEXT NOT NULL, -- 'stripe' | 'crypto' | 'stars' | 'paypal'
amount REAL,
currency TEXT,
status TEXT DEFAULT 'pending', -- 'pending' | 'approved' | 'rejected'
proof TEXT, -- TXID, screenshot file_id, Stripe session id, etc.
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(user_id)
);
CREATE TABLE IF NOT EXISTS share_submissions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
platform TEXT NOT NULL, -- 'twitter' | 'discord' | 'telegram' | 'reddit' | 'instagram'
proof TEXT NOT NULL, -- URL or Telegram file_id
proof_type TEXT NOT NULL, -- 'url' | 'photo'
status TEXT DEFAULT 'pending', -- 'pending' | 'approved' | 'rejected'
submitted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(user_id)
);
"""
# ══════════════════════════════════════════════════════════════════════════════
# Init
# ══════════════════════════════════════════════════════════════════════════════
async def init_db() -> None:
"""Create all tables on first run."""
async with aiosqlite.connect(DB_PATH) as db:
await db.executescript(SCHEMA)
await db.commit()
logger.info("Database initialised at %s", DB_PATH)
# ══════════════════════════════════════════════════════════════════════════════
# Users
# ══════════════════════════════════════════════════════════════════════════════
async def upsert_user(
user_id: int,
username: Optional[str],
first_name: str,
last_name: Optional[str],
) -> None:
"""Insert or update a user record."""
async with aiosqlite.connect(DB_PATH) as db:
await db.execute(
"""
INSERT INTO users (user_id, username, first_name, last_name)
VALUES (?, ?, ?, ?)
ON CONFLICT(user_id) DO UPDATE SET
username = excluded.username,
first_name = excluded.first_name,
last_name = excluded.last_name
""",
(user_id, username, first_name, last_name),
)
await db.commit()
async def get_user(user_id: int) -> Optional[Dict[str, Any]]:
async with aiosqlite.connect(DB_PATH) as db:
db.row_factory = aiosqlite.Row
async with db.execute(
"SELECT * FROM users WHERE user_id = ?", (user_id,)
) as cur:
row = await cur.fetchone()
return dict(row) if row else None
async def get_all_active_subscriber_ids() -> List[int]:
"""Return user_ids with a currently active subscription."""
now = datetime.utcnow().isoformat()
async with aiosqlite.connect(DB_PATH) as db:
async with db.execute(
"""
SELECT DISTINCT user_id FROM subscriptions
WHERE is_active = 1 AND end_date > ?
""",
(now,),
) as cur:
rows = await cur.fetchall()
return [r[0] for r in rows]
# ══════════════════════════════════════════════════════════════════════════════
# Subscriptions
# ══════════════════════════════════════════════════════════════════════════════
async def add_subscription(
user_id: int,
sub_type: str,
months: int,
) -> None:
"""Grant a subscription starting now for `months` months."""
start = datetime.utcnow()
# Add months by advancing the month field, rolling over year as needed
month = start.month - 1 + months
year = start.year + month // 12
month = month % 12 + 1
end = start.replace(year=year, month=month)
async with aiosqlite.connect(DB_PATH) as db:
# Deactivate any existing active subscriptions first
await db.execute(
"UPDATE subscriptions SET is_active = 0 WHERE user_id = ? AND is_active = 1",
(user_id,),
)
await db.execute(
"""
INSERT INTO subscriptions (user_id, sub_type, start_date, end_date)
VALUES (?, ?, ?, ?)
""",
(user_id, sub_type, start.isoformat(), end.isoformat()),
)
await db.commit()
logger.info("Subscription granted: user=%s type=%s until=%s", user_id, sub_type, end)
async def has_active_subscription(user_id: int) -> bool:
now = datetime.utcnow().isoformat()
async with aiosqlite.connect(DB_PATH) as db:
async with db.execute(
"""
SELECT id FROM subscriptions
WHERE user_id = ? AND is_active = 1 AND end_date > ?
LIMIT 1
""",
(user_id, now),
) as cur:
return (await cur.fetchone()) is not None
async def get_subscription_expiry(user_id: int) -> Optional[str]:
now = datetime.utcnow().isoformat()
async with aiosqlite.connect(DB_PATH) as db:
async with db.execute(
"""
SELECT end_date FROM subscriptions
WHERE user_id = ? AND is_active = 1 AND end_date > ?
ORDER BY end_date DESC LIMIT 1
""",
(user_id, now),
) as cur:
row = await cur.fetchone()
return row[0] if row else None
# ══════════════════════════════════════════════════════════════════════════════
# Payments
# ══════════════════════════════════════════════════════════════════════════════
async def create_payment(
user_id: int,
method: str,
amount: float,
currency: str,
proof: Optional[str] = None,
) -> int:
"""Insert a pending payment and return its id."""
async with aiosqlite.connect(DB_PATH) as db:
cur = await db.execute(
"""
INSERT INTO payments (user_id, method, amount, currency, proof)
VALUES (?, ?, ?, ?, ?)
""",
(user_id, method, amount, currency, proof),
)
await db.commit()
return cur.lastrowid
async def update_payment_proof(payment_id: int, proof: str) -> None:
async with aiosqlite.connect(DB_PATH) as db:
await db.execute(
"UPDATE payments SET proof = ? WHERE id = ?",
(proof, payment_id),
)
await db.commit()
async def update_payment_status(payment_id: int, status: str) -> Optional[int]:
"""Update payment status and return user_id for notification."""
async with aiosqlite.connect(DB_PATH) as db:
await db.execute(
"UPDATE payments SET status = ? WHERE id = ?",
(status, payment_id),
)
await db.commit()
async with db.execute(
"SELECT user_id FROM payments WHERE id = ?", (payment_id,)
) as cur:
row = await cur.fetchone()
return row[0] if row else None
async def get_pending_payment_by_user(user_id: int) -> Optional[Dict[str, Any]]:
"""Get the most recent pending payment for a user."""
async with aiosqlite.connect(DB_PATH) as db:
db.row_factory = aiosqlite.Row
async with db.execute(
"""
SELECT * FROM payments
WHERE user_id = ? AND status = 'pending'
ORDER BY created_at DESC LIMIT 1
""",
(user_id,),
) as cur:
row = await cur.fetchone()
return dict(row) if row else None
async def approve_payment_by_user(user_id: int) -> bool:
"""Approve the most recent pending payment for a user. Returns True if found."""
async with aiosqlite.connect(DB_PATH) as db:
async with db.execute(
"""
SELECT id FROM payments
WHERE user_id = ? AND status = 'pending'
ORDER BY created_at DESC LIMIT 1
""",
(user_id,),
) as cur:
row = await cur.fetchone()
if not row:
return False
await db.execute(
"UPDATE payments SET status = 'approved' WHERE id = ?", (row[0],)
)
await db.commit()
return True
# ══════════════════════════════════════════════════════════════════════════════
# Share submissions
# ══════════════════════════════════════════════════════════════════════════════
async def create_share_submission(
user_id: int,
platform: str,
proof: str,
proof_type: str,
) -> int:
"""Insert a pending share submission and return its id."""
async with aiosqlite.connect(DB_PATH) as db:
cur = await db.execute(
"""
INSERT INTO share_submissions (user_id, platform, proof, proof_type)
VALUES (?, ?, ?, ?)
""",
(user_id, platform, proof, proof_type),
)
await db.commit()
return cur.lastrowid
async def get_approved_share_count(user_id: int) -> int:
"""Count how many share submissions have been approved for this user."""
async with aiosqlite.connect(DB_PATH) as db:
async with db.execute(
"""
SELECT COUNT(*) FROM share_submissions
WHERE user_id = ? AND status = 'approved'
""",
(user_id,),
) as cur:
row = await cur.fetchone()
return row[0] if row else 0
async def get_pending_share_submission(submission_id: int) -> Optional[Dict[str, Any]]:
async with aiosqlite.connect(DB_PATH) as db:
db.row_factory = aiosqlite.Row
async with db.execute(
"SELECT * FROM share_submissions WHERE id = ?", (submission_id,)
) as cur:
row = await cur.fetchone()
return dict(row) if row else None
async def update_share_status(submission_id: int, status: str) -> Optional[int]:
"""Update submission status and return user_id."""
async with aiosqlite.connect(DB_PATH) as db:
await db.execute(
"UPDATE share_submissions SET status = ? WHERE id = ?",
(status, submission_id),
)
await db.commit()
async with db.execute(
"SELECT user_id FROM share_submissions WHERE id = ?", (submission_id,)
) as cur:
row = await cur.fetchone()
return row[0] if row else None
async def get_pending_shares_for_user(user_id: int) -> List[Dict[str, Any]]:
"""Get all pending share submissions for a user."""
async with aiosqlite.connect(DB_PATH) as db:
db.row_factory = aiosqlite.Row
async with db.execute(
"""
SELECT * FROM share_submissions
WHERE user_id = ? AND status = 'pending'
ORDER BY submitted_at ASC
""",
(user_id,),
) as cur:
rows = await cur.fetchall()
return [dict(r) for r in rows]