Repository navigation
Expand file tree
/
Copy pathdatabase.py
More file actions
305 lines (259 loc) · 9.83 KB
/
Copy pathdatabase.py
File metadata and controls
305 lines (259 loc) · 9.83 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
import sqlite3
from datetime import datetime
from typing import Optional, List, Tuple, Dict
import config
class Database:
def __init__(self, db_path: str = None):
self.db_path = db_path or config.DATABASE_PATH
self.init_db()
def init_db(self):
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS accounts
(
id
INTEGER
PRIMARY
KEY
AUTOINCREMENT,
email
TEXT
NOT
NULL,
password
TEXT
NOT
NULL,
status
TEXT
DEFAULT
'pending',
refresh_token
TEXT,
created_at
TEXT
DEFAULT
CURRENT_TIMESTAMP,
processed_at
TEXT,
skip_verification
INTEGER
DEFAULT
0,
error_message
TEXT
)
""")
conn.commit()
conn.close()
def add_account(self, email: str, password: str):
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(
"INSERT INTO accounts (email, password) VALUES (?, ?)",
(email, password)
)
conn.commit()
account_id = cursor.lastrowid
conn.close()
return account_id
def update_or_add_account(self, email: str, password: str):
"""如果邮箱存在则更新密码并重置状态,否则新增"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# 检查邮箱是否存在
cursor.execute("SELECT id FROM accounts WHERE email = ?", (email,))
result = cursor.fetchone()
if result:
# 邮箱存在,更新密码并重置状态
account_id = result[0]
cursor.execute("""
UPDATE accounts
SET password = ?,
status = 'pending',
refresh_token = NULL,
processed_at = NULL
WHERE email = ?
""", (password, email))
conn.commit()
conn.close()
return account_id, True # True表示是更新
else:
# 邮箱不存在,新增
cursor.execute(
"INSERT INTO accounts (email, password) VALUES (?, ?)",
(email, password)
)
conn.commit()
account_id = cursor.lastrowid
conn.close()
return account_id, False # False表示是新增
def get_pending_account(self) -> Optional[Tuple[int, str, str]]:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(
"SELECT id, email, password FROM accounts WHERE status = 'pending' AND skip_verification = 0 LIMIT 1"
)
result = cursor.fetchone()
conn.close()
return result
def update_account_status(self, account_id: int, status: str, refresh_token: Optional[str] = None):
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(
"UPDATE accounts SET status = ?, refresh_token = ?, processed_at = ? WHERE id = ?",
(status, refresh_token, datetime.now().isoformat(), account_id)
)
conn.commit()
conn.close()
def cleanup_processed_accounts(self) -> int:
"""删除所有已处理的账号,只保留pending状态"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# 删除非pending状态的记录
cursor.execute("DELETE FROM accounts WHERE status != 'pending'")
deleted_count = cursor.rowcount
conn.commit()
conn.close()
return deleted_count
def get_pending_count(self) -> int:
"""获取待处理账号数量"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM accounts WHERE status = 'pending' AND skip_verification = 0")
count = cursor.fetchone()[0]
conn.close()
return count
def mark_skip_verification_and_error(self, account_id: int, error_message: Optional[str] = None):
"""标记账号跳过验证码处理并设置为错误状态
Args:
account_id: 账号ID
error_message: 错误信息(可选)
"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(
"UPDATE accounts SET skip_verification = 1, status = ?, processed_at = ?, error_message = ? WHERE id = ?",
("error", datetime.now().isoformat(), error_message, account_id)
)
conn.commit()
conn.close()
def batch_reset_accounts_by_emails(self, emails: List[str]) -> int:
"""批量重置账号状态(根据邮箱列表,只更新未标记跳过验证码的账号)
Args:
emails: 邮箱列表
Returns:
更新的记录数
"""
if not emails:
return 0
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# 使用IN子句批量更新,只更新 skip_verification = 0 的账号
placeholders = ','.join(['?' for _ in emails])
cursor.execute(f"""
UPDATE accounts
SET status = 'pending',
refresh_token = NULL,
processed_at = NULL
WHERE email IN ({placeholders}) AND skip_verification = 0
""", emails)
updated_count = cursor.rowcount
conn.commit()
conn.close()
return updated_count
def batch_reset_accounts_by_patterns(self, patterns: List[str]) -> int:
"""根据邮箱或邮箱后缀批量重置账号状态
支持两种模式:
1. 完整邮箱匹配:如 'user@example.com'
2. 域名后缀匹配:如 'example.com' 会匹配所有 @example.com 的邮箱
Args:
patterns: 邮箱或域名后缀列表
Returns:
更新的记录数
"""
if not patterns:
return 0
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# 构建WHERE条件
conditions = []
params = []
for pattern in patterns:
if '@' in pattern:
# 完整邮箱匹配
conditions.append("email = ?")
params.append(pattern)
else:
# 域名后缀匹配
conditions.append("email LIKE ?")
params.append(f"%@{pattern}")
if not conditions:
conn.close()
return 0
# 构建SQL查询
where_clause = "(" + " OR ".join(conditions) + ") AND skip_verification = 0"
cursor.execute(f"""
UPDATE accounts
SET status = 'pending',
refresh_token = NULL,
processed_at = NULL
WHERE {where_clause}
""", params)
updated_count = cursor.rowcount
conn.commit()
conn.close()
return updated_count
def query_accounts(self, search: Optional[str] = None, page: int = 1, page_size: int = 20) -> Dict:
"""查询邮箱信息(支持分页和搜索)
Args:
search: 搜索关键词(匹配邮箱)
page: 页码(从1开始)
page_size: 每页数量
Returns:
包含accounts列表和total总数的字典
"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# 构建查询条件
where_clause = ""
params = []
if search:
where_clause = "WHERE email LIKE ?"
params.append(f"%{search}%")
# 查询总数
count_query = f"SELECT COUNT(*) FROM accounts {where_clause}"
cursor.execute(count_query, params)
total = cursor.fetchone()[0]
# 查询分页数据
offset = (page - 1) * page_size
query = f"""
SELECT id, email, password, status, created_at, processed_at, skip_verification, error_message
FROM accounts
{where_clause}
ORDER BY CASE WHEN processed_at IS NULL THEN 1 ELSE 0 END, processed_at ASC, id ASC
LIMIT ? OFFSET ?
"""
cursor.execute(query, params + [page_size, offset])
rows = cursor.fetchall()
accounts = []
for row in rows:
accounts.append({
"id": row[0],
"email": row[1],
"password": row[2],
"status": row[3],
"created_at": row[4],
"processed_at": row[5],
"skip_verification": bool(row[6]),
"error_message": row[7]
})
conn.close()
return {
"accounts": accounts,
"total": total,
"page": page,
"page_size": page_size,
"total_pages": (total + page_size - 1) // page_size
}