-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
179 lines (166 loc) · 6.85 KB
/
db.py
File metadata and controls
179 lines (166 loc) · 6.85 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
import os
import sqlite3
from typing import Dict, List, Optional, Tuple
class Database:
"""Simple SQLite wrapper for caching emails and codes locally."""
def __init__(self, db_path: Optional[str] = None) -> None:
self.db_path = db_path or os.path.join(os.path.dirname(__file__), 'emails.db')
self._connection = sqlite3.connect(self.db_path, check_same_thread=False)
self._connection.row_factory = sqlite3.Row
self._ensure_schema()
def _ensure_schema(self) -> None:
cursor = self._connection.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS accounts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
host TEXT
);
"""
)
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS emails (
id INTEGER PRIMARY KEY AUTOINCREMENT,
account_username TEXT NOT NULL,
message_uid TEXT,
message_id TEXT,
subject TEXT,
sender TEXT,
recipient TEXT,
date TEXT,
body_snippet TEXT,
code TEXT,
is_unread INTEGER DEFAULT 1,
created_at TEXT DEFAULT (datetime('now')),
UNIQUE(account_username, message_uid)
);
"""
)
try:
cursor.execute("ALTER TABLE emails ADD COLUMN body_full TEXT")
except sqlite3.OperationalError:
pass
cursor.execute("CREATE INDEX IF NOT EXISTS idx_emails_account_date ON emails(account_username, date DESC);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_emails_code ON emails(code);")
self._connection.commit()
def upsert_account(self, username: str, host: Optional[str]) -> None:
cursor = self._connection.cursor()
cursor.execute(
"""
INSERT INTO accounts (username, host)
VALUES (?, ?)
ON CONFLICT(username) DO UPDATE SET host=excluded.host
""",
(username, host),
)
self._connection.commit()
def insert_email(self, email_record: Dict[str, Optional[str]]) -> bool:
"""Insert new email if not exists; update existing otherwise.
Returns True only when a NEW row is inserted (used to gate UI 'new_email' signal).
"""
cursor = self._connection.cursor()
# First, attempt insert-or-ignore using UID as unique key
cursor.execute(
"""
INSERT OR IGNORE INTO emails (
account_username, message_uid, message_id, subject, sender, recipient, date,
body_snippet, code, is_unread, body_full
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
email_record.get('account_username'),
email_record.get('message_uid'),
email_record.get('message_id'),
email_record.get('subject'),
email_record.get('sender'),
email_record.get('recipient'),
email_record.get('date'),
email_record.get('body_snippet'),
email_record.get('code'),
1 if email_record.get('is_unread', True) else 0,
email_record.get('body_full'),
),
)
inserted = cursor.rowcount == 1
if not inserted:
# On conflict, update key fields but do not flip code if new is None
cursor.execute(
"""
UPDATE emails
SET subject=?, sender=?, recipient=?, date=?, body_snippet=?, body_full=?,
code=COALESCE(?, code), is_unread=?
WHERE account_username=? AND message_uid=?
""",
(
email_record.get('subject'),
email_record.get('sender'),
email_record.get('recipient'),
email_record.get('date'),
email_record.get('body_snippet'),
email_record.get('body_full'),
email_record.get('code'),
1 if email_record.get('is_unread', True) else 0,
email_record.get('account_username'),
email_record.get('message_uid'),
),
)
self._connection.commit()
return inserted
def mark_email_read(self, account_username: str, message_uid: Optional[str], message_id: Optional[str]) -> None:
cursor = self._connection.cursor()
if message_uid:
cursor.execute(
"UPDATE emails SET is_unread=0 WHERE account_username=? AND message_uid=?",
(account_username, message_uid),
)
elif message_id:
cursor.execute(
"UPDATE emails SET is_unread=0 WHERE account_username=? AND message_id=?",
(account_username, message_id),
)
self._connection.commit()
def mark_all_read(self, account_username: Optional[str] = None) -> None:
cursor = self._connection.cursor()
if account_username:
cursor.execute("UPDATE emails SET is_unread=0 WHERE account_username=?", (account_username,))
else:
cursor.execute("UPDATE emails SET is_unread=0")
self._connection.commit()
def fetch_recent_emails(self, limit: int = 200, account_username: Optional[str] = None) -> List[Dict[str, str]]:
cursor = self._connection.cursor()
if account_username:
cursor.execute(
"""
SELECT account_username, message_uid, message_id, subject, sender, recipient, date, body_snippet, code, is_unread, created_at, body_full
FROM emails
WHERE account_username = ?
ORDER BY datetime(date) DESC, id DESC
LIMIT ?
""",
(account_username, limit),
)
else:
cursor.execute(
"""
SELECT account_username, message_uid, message_id, subject, sender, recipient, date, body_snippet, code, is_unread, created_at, body_full
FROM emails
ORDER BY datetime(date) DESC, id DESC
LIMIT ?
""",
(limit,),
)
rows = cursor.fetchall()
return [dict(row) for row in rows]
def fetch_accounts(self) -> List[Tuple[str, Optional[str]]]:
cursor = self._connection.cursor()
cursor.execute("SELECT username, host FROM accounts ORDER BY username ASC")
rows = cursor.fetchall()
return [(row[0], row[1]) for row in rows]
def close(self) -> None:
try:
self._connection.close()
except Exception:
pass
__all__ = ["Database"]