fetch2gmail 1.1.5__tar.gz → 1.1.7__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {fetch2gmail-1.1.5/src/fetch2gmail.egg-info → fetch2gmail-1.1.7}/PKG-INFO +10 -3
- {fetch2gmail-1.1.5 → fetch2gmail-1.1.7}/README.md +9 -2
- {fetch2gmail-1.1.5 → fetch2gmail-1.1.7}/pyproject.toml +1 -1
- {fetch2gmail-1.1.5 → fetch2gmail-1.1.7/src/fetch2gmail.egg-info}/PKG-INFO +10 -3
- {fetch2gmail-1.1.5 → fetch2gmail-1.1.7}/src/fetcher/auth_server.py +3 -2
- {fetch2gmail-1.1.5 → fetch2gmail-1.1.7}/src/fetcher/cli.py +21 -5
- {fetch2gmail-1.1.5 → fetch2gmail-1.1.7}/src/fetcher/config.py +15 -0
- {fetch2gmail-1.1.5 → fetch2gmail-1.1.7}/src/fetcher/run.py +191 -122
- {fetch2gmail-1.1.5 → fetch2gmail-1.1.7}/src/fetcher/web_ui.py +411 -36
- {fetch2gmail-1.1.5 → fetch2gmail-1.1.7}/LICENSE +0 -0
- {fetch2gmail-1.1.5 → fetch2gmail-1.1.7}/setup.cfg +0 -0
- {fetch2gmail-1.1.5 → fetch2gmail-1.1.7}/src/fetch2gmail.egg-info/SOURCES.txt +0 -0
- {fetch2gmail-1.1.5 → fetch2gmail-1.1.7}/src/fetch2gmail.egg-info/dependency_links.txt +0 -0
- {fetch2gmail-1.1.5 → fetch2gmail-1.1.7}/src/fetch2gmail.egg-info/entry_points.txt +0 -0
- {fetch2gmail-1.1.5 → fetch2gmail-1.1.7}/src/fetch2gmail.egg-info/requires.txt +0 -0
- {fetch2gmail-1.1.5 → fetch2gmail-1.1.7}/src/fetch2gmail.egg-info/top_level.txt +0 -0
- {fetch2gmail-1.1.5 → fetch2gmail-1.1.7}/src/fetcher/__init__.py +0 -0
- {fetch2gmail-1.1.5 → fetch2gmail-1.1.7}/src/fetcher/auth_ui.py +0 -0
- {fetch2gmail-1.1.5 → fetch2gmail-1.1.7}/src/fetcher/env_file.py +0 -0
- {fetch2gmail-1.1.5 → fetch2gmail-1.1.7}/src/fetcher/gmail_client.py +0 -0
- {fetch2gmail-1.1.5 → fetch2gmail-1.1.7}/src/fetcher/imap_client.py +0 -0
- {fetch2gmail-1.1.5 → fetch2gmail-1.1.7}/src/fetcher/log_buffer.py +0 -0
- {fetch2gmail-1.1.5 → fetch2gmail-1.1.7}/src/fetcher/state.py +0 -0
- {fetch2gmail-1.1.5 → fetch2gmail-1.1.7}/src/fetcher/ui_auth.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: fetch2gmail
|
|
3
|
-
Version: 1.1.
|
|
3
|
+
Version: 1.1.7
|
|
4
4
|
Summary: Self-hosted email fetcher: IMAP to Gmail API import with idempotent state tracking
|
|
5
5
|
Author: Fetch2Gmail Contributors
|
|
6
6
|
License-Expression: MIT
|
|
@@ -237,11 +237,18 @@ One instance = one IMAP mailbox → one Gmail account. To run **multiple account
|
|
|
237
237
|
```bash
|
|
238
238
|
fetch2gmail install-service --user YOUR_USER --dir /opt/fetch2gmail2 -o /tmp/fetch2gmail2.service
|
|
239
239
|
```
|
|
240
|
-
Edit `/tmp/fetch2gmail2.service`: in **ExecStart**, add **`--port 8766`** so this instance uses port 8766 (the first stays on 8765). Set **WorkingDirectory** and **Environment=FETCH2GMAIL_CONFIG** to the second directory (e.g. `/opt/fetch2gmail2`, `/opt/fetch2gmail2/config.json`).
|
|
241
240
|
|
|
242
|
-
3. Install
|
|
241
|
+
3. Install the second unit under a different name so both can run, **then edit its ExecStart to add a port**:
|
|
243
242
|
```bash
|
|
244
243
|
sudo mv /tmp/fetch2gmail2.service /etc/systemd/system/fetch2gmail2.service
|
|
244
|
+
sudo nano /etc/systemd/system/fetch2gmail2.service
|
|
245
|
+
```
|
|
246
|
+
In the editor, find the `ExecStart=` line and make sure it includes a port flag, for example:
|
|
247
|
+
```
|
|
248
|
+
ExecStart=/home/YOUR_USER/.local/pipx/venvs/fetch2gmail/bin/fetch2gmail serve --host 0.0.0.0 --port 8766
|
|
249
|
+
```
|
|
250
|
+
Also set **WorkingDirectory** and **Environment=FETCH2GMAIL_CONFIG** to the second directory (e.g. `/opt/fetch2gmail2`, `/opt/fetch2gmail2/config.json`). Then reload and enable:
|
|
251
|
+
```bash
|
|
245
252
|
sudo systemctl daemon-reload
|
|
246
253
|
sudo systemctl enable fetch2gmail2
|
|
247
254
|
sudo systemctl start fetch2gmail2
|
|
@@ -206,11 +206,18 @@ One instance = one IMAP mailbox → one Gmail account. To run **multiple account
|
|
|
206
206
|
```bash
|
|
207
207
|
fetch2gmail install-service --user YOUR_USER --dir /opt/fetch2gmail2 -o /tmp/fetch2gmail2.service
|
|
208
208
|
```
|
|
209
|
-
Edit `/tmp/fetch2gmail2.service`: in **ExecStart**, add **`--port 8766`** so this instance uses port 8766 (the first stays on 8765). Set **WorkingDirectory** and **Environment=FETCH2GMAIL_CONFIG** to the second directory (e.g. `/opt/fetch2gmail2`, `/opt/fetch2gmail2/config.json`).
|
|
210
209
|
|
|
211
|
-
3. Install
|
|
210
|
+
3. Install the second unit under a different name so both can run, **then edit its ExecStart to add a port**:
|
|
212
211
|
```bash
|
|
213
212
|
sudo mv /tmp/fetch2gmail2.service /etc/systemd/system/fetch2gmail2.service
|
|
213
|
+
sudo nano /etc/systemd/system/fetch2gmail2.service
|
|
214
|
+
```
|
|
215
|
+
In the editor, find the `ExecStart=` line and make sure it includes a port flag, for example:
|
|
216
|
+
```
|
|
217
|
+
ExecStart=/home/YOUR_USER/.local/pipx/venvs/fetch2gmail/bin/fetch2gmail serve --host 0.0.0.0 --port 8766
|
|
218
|
+
```
|
|
219
|
+
Also set **WorkingDirectory** and **Environment=FETCH2GMAIL_CONFIG** to the second directory (e.g. `/opt/fetch2gmail2`, `/opt/fetch2gmail2/config.json`). Then reload and enable:
|
|
220
|
+
```bash
|
|
214
221
|
sudo systemctl daemon-reload
|
|
215
222
|
sudo systemctl enable fetch2gmail2
|
|
216
223
|
sudo systemctl start fetch2gmail2
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: fetch2gmail
|
|
3
|
-
Version: 1.1.
|
|
3
|
+
Version: 1.1.7
|
|
4
4
|
Summary: Self-hosted email fetcher: IMAP to Gmail API import with idempotent state tracking
|
|
5
5
|
Author: Fetch2Gmail Contributors
|
|
6
6
|
License-Expression: MIT
|
|
@@ -237,11 +237,18 @@ One instance = one IMAP mailbox → one Gmail account. To run **multiple account
|
|
|
237
237
|
```bash
|
|
238
238
|
fetch2gmail install-service --user YOUR_USER --dir /opt/fetch2gmail2 -o /tmp/fetch2gmail2.service
|
|
239
239
|
```
|
|
240
|
-
Edit `/tmp/fetch2gmail2.service`: in **ExecStart**, add **`--port 8766`** so this instance uses port 8766 (the first stays on 8765). Set **WorkingDirectory** and **Environment=FETCH2GMAIL_CONFIG** to the second directory (e.g. `/opt/fetch2gmail2`, `/opt/fetch2gmail2/config.json`).
|
|
241
240
|
|
|
242
|
-
3. Install
|
|
241
|
+
3. Install the second unit under a different name so both can run, **then edit its ExecStart to add a port**:
|
|
243
242
|
```bash
|
|
244
243
|
sudo mv /tmp/fetch2gmail2.service /etc/systemd/system/fetch2gmail2.service
|
|
244
|
+
sudo nano /etc/systemd/system/fetch2gmail2.service
|
|
245
|
+
```
|
|
246
|
+
In the editor, find the `ExecStart=` line and make sure it includes a port flag, for example:
|
|
247
|
+
```
|
|
248
|
+
ExecStart=/home/YOUR_USER/.local/pipx/venvs/fetch2gmail/bin/fetch2gmail serve --host 0.0.0.0 --port 8766
|
|
249
|
+
```
|
|
250
|
+
Also set **WorkingDirectory** and **Environment=FETCH2GMAIL_CONFIG** to the second directory (e.g. `/opt/fetch2gmail2`, `/opt/fetch2gmail2/config.json`). Then reload and enable:
|
|
251
|
+
```bash
|
|
245
252
|
sudo systemctl daemon-reload
|
|
246
253
|
sudo systemctl enable fetch2gmail2
|
|
247
254
|
sudo systemctl start fetch2gmail2
|
|
@@ -97,12 +97,13 @@ def _auth_callback(
|
|
|
97
97
|
|
|
98
98
|
cred_abs = cred_path.resolve()
|
|
99
99
|
tok_abs = token_path.resolve()
|
|
100
|
+
tok_name = tok_abs.name
|
|
100
101
|
html = f"""<!DOCTYPE html><html><head><meta charset="utf-8"><title>Token saved</title></head><body>
|
|
101
102
|
<h2>Token saved</h2>
|
|
102
|
-
<p><strong>
|
|
103
|
+
<p><strong>{tok_name}</strong> has been saved. Copy these two files to your Odroid (or other headless device):</p>
|
|
103
104
|
<ul>
|
|
104
105
|
<li><strong>credentials.json</strong> (from GCP)</li>
|
|
105
|
-
<li><strong>
|
|
106
|
+
<li><strong>{tok_name}</strong> (just saved at <code>{tok_abs}</code>)</li>
|
|
106
107
|
</ul>
|
|
107
108
|
<p>On the headless server (e.g. Debian, Odroid, Raspberry Pi), put both files in the <strong>data directory</strong> where Fetch2Gmail runs — the same folder as <code>config.json</code>, e.g. <code>/opt/fetch2gmail</code> or <code>/home/odroid/fetch2gmail</code>. See the README for setup.</p>
|
|
108
109
|
<p>You can close this window and stop the server (Ctrl+C).</p>
|
|
@@ -235,7 +235,21 @@ def _cmd_auth(args: argparse.Namespace) -> None:
|
|
|
235
235
|
from .auth_server import app
|
|
236
236
|
|
|
237
237
|
cred_path = Path(args.credentials).resolve()
|
|
238
|
-
|
|
238
|
+
# If the user did not override --token (still default "token.json"), automatically pick
|
|
239
|
+
# token.json, token2.json, token3.json, ... in the current directory, so additional
|
|
240
|
+
# accounts are easy to add without manually specifying --token.
|
|
241
|
+
if args.token == "token.json":
|
|
242
|
+
base_dir = Path.cwd()
|
|
243
|
+
idx = 0
|
|
244
|
+
while True:
|
|
245
|
+
name = "token.json" if idx == 0 else f"token{idx + 1}.json"
|
|
246
|
+
candidate = base_dir / name
|
|
247
|
+
if not candidate.exists():
|
|
248
|
+
token_path = candidate
|
|
249
|
+
break
|
|
250
|
+
idx += 1
|
|
251
|
+
else:
|
|
252
|
+
token_path = Path(args.token).resolve()
|
|
239
253
|
if not cred_path.exists():
|
|
240
254
|
print(f"Credentials file not found: {cred_path}", file=sys.stderr)
|
|
241
255
|
print("Download credentials.json from Google Cloud (OAuth client, Web application).", file=sys.stderr)
|
|
@@ -252,8 +266,9 @@ def _cmd_auth(args: argparse.Namespace) -> None:
|
|
|
252
266
|
webbrowser.open(url)
|
|
253
267
|
|
|
254
268
|
threading.Thread(target=open_browser, daemon=True).start()
|
|
255
|
-
|
|
256
|
-
print("
|
|
269
|
+
token_name = token_path.name
|
|
270
|
+
print(f"Opening {url} in your browser. Sign in with Google; {token_name} will be saved to {token_path}")
|
|
271
|
+
print(f"Then copy credentials.json and {token_name} to your Odroid. Press Ctrl+C when done.")
|
|
257
272
|
import uvicorn
|
|
258
273
|
uvicorn.run(app, host="127.0.0.1", port=args.port, log_level="warning")
|
|
259
274
|
|
|
@@ -270,7 +285,8 @@ def _write_default_config(dest: Path) -> None:
|
|
|
270
285
|
"use_ssl": True,
|
|
271
286
|
"delete_after_import": True,
|
|
272
287
|
},
|
|
273
|
-
|
|
288
|
+
# Canonical: gmail_accounts (multi-account). Single-account setups will have one entry.
|
|
289
|
+
"gmail_accounts": [{"use_label": False, "label": "ISP Mail", "credentials_path": "credentials.json", "token_path": "token.json"}],
|
|
274
290
|
"state": {"db_path": "state.db"},
|
|
275
291
|
"ui": {"host": "127.0.0.1", "port": 8765},
|
|
276
292
|
"poll_interval_minutes": 5,
|
|
@@ -302,7 +318,7 @@ def config_wizard_interactive() -> None:
|
|
|
302
318
|
"use_ssl": True,
|
|
303
319
|
"delete_after_import": True,
|
|
304
320
|
},
|
|
305
|
-
"
|
|
321
|
+
"gmail_accounts": [{"use_label": bool(label), "label": label or "ISP Mail", "credentials_path": cred_path, "token_path": token_path}],
|
|
306
322
|
"state": {"db_path": db_path},
|
|
307
323
|
"ui": {"host": "127.0.0.1", "port": 8765},
|
|
308
324
|
"poll_interval_minutes": 5,
|
|
@@ -51,3 +51,18 @@ def get_config_path() -> Path:
|
|
|
51
51
|
if env:
|
|
52
52
|
return Path(env)
|
|
53
53
|
return Path.cwd() / "config.json"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def get_gmail_accounts(cfg: dict[str, Any]) -> list[dict[str, Any]]:
|
|
57
|
+
"""
|
|
58
|
+
Return list of Gmail account configs for import.
|
|
59
|
+
Supports multi-account: use "gmail_accounts" (array) or legacy "gmail" (single object).
|
|
60
|
+
If both present, "gmail_accounts" wins. Each entry has credentials_path, token_path, label, use_label.
|
|
61
|
+
"""
|
|
62
|
+
accounts = cfg.get("gmail_accounts")
|
|
63
|
+
if isinstance(accounts, list) and len(accounts) > 0:
|
|
64
|
+
return accounts
|
|
65
|
+
gmail = cfg.get("gmail")
|
|
66
|
+
if gmail and isinstance(gmail, dict):
|
|
67
|
+
return [gmail]
|
|
68
|
+
return []
|
|
@@ -3,13 +3,15 @@ Main fetch run: IMAP -> Gmail import -> state update -> delete from ISP.
|
|
|
3
3
|
|
|
4
4
|
Idempotency: UID + message SHA256 hash. On UIDVALIDITY change, hashes prevent duplicates.
|
|
5
5
|
Only delete from ISP after Gmail confirms import. Dry-run skips Gmail and delete.
|
|
6
|
+
Supports multiple Gmail accounts: import to all in one run; delete from ISP only if all imports succeed.
|
|
6
7
|
"""
|
|
7
8
|
|
|
8
9
|
import logging
|
|
9
10
|
import os
|
|
11
|
+
from pathlib import Path
|
|
10
12
|
from typing import Any
|
|
11
13
|
|
|
12
|
-
from .config import load_config
|
|
14
|
+
from .config import get_gmail_accounts, load_config
|
|
13
15
|
from .gmail_client import (
|
|
14
16
|
SkipMessageError,
|
|
15
17
|
_parse_message_id_from_raw,
|
|
@@ -40,6 +42,32 @@ def _ensure_label(service: Any, label_name: str) -> str:
|
|
|
40
42
|
return created["id"]
|
|
41
43
|
|
|
42
44
|
|
|
45
|
+
def _build_gmail_contexts(
|
|
46
|
+
gmail_accounts: list[dict[str, Any]],
|
|
47
|
+
config_dir: Path,
|
|
48
|
+
) -> list[tuple[Any, str | None, str, str]]:
|
|
49
|
+
"""
|
|
50
|
+
Build list of (service, label_id, inbox_label_id, unread_label_id) for each account.
|
|
51
|
+
Paths in account dicts are resolved relative to config_dir.
|
|
52
|
+
"""
|
|
53
|
+
contexts = []
|
|
54
|
+
for acct in gmail_accounts:
|
|
55
|
+
cred_path = Path(acct.get("credentials_path", "credentials.json"))
|
|
56
|
+
token_path = Path(acct.get("token_path", "token.json"))
|
|
57
|
+
if not cred_path.is_absolute():
|
|
58
|
+
cred_path = config_dir / cred_path
|
|
59
|
+
if not token_path.is_absolute():
|
|
60
|
+
token_path = config_dir / token_path
|
|
61
|
+
use_label = acct.get("use_label") if "use_label" in acct else bool((acct.get("label") or "").strip())
|
|
62
|
+
label_name = (acct.get("label") or "ISP Mail").strip() if use_label else None
|
|
63
|
+
service = get_gmail_service(cred_path, token_path)
|
|
64
|
+
inbox_label_id = get_inbox_label_id(service, USER_ID)
|
|
65
|
+
unread_label_id = get_unread_label_id(service, USER_ID)
|
|
66
|
+
label_id = _ensure_label(service, label_name) if label_name else None
|
|
67
|
+
contexts.append((service, label_id, inbox_label_id, unread_label_id))
|
|
68
|
+
return contexts
|
|
69
|
+
|
|
70
|
+
|
|
43
71
|
def run_once(config_path: str | None = None, dry_run: bool = False) -> dict[str, Any]:
|
|
44
72
|
"""
|
|
45
73
|
Run one fetch cycle: fetch NEW mail only (UID > last_processed), import to Gmail, update state, delete from ISP.
|
|
@@ -52,16 +80,20 @@ def run_once(config_path: str | None = None, dry_run: bool = False) -> dict[str,
|
|
|
52
80
|
from .config import get_config_path
|
|
53
81
|
config_path = str(get_config_path())
|
|
54
82
|
cfg = load_config(config_path)
|
|
83
|
+
config_dir = Path(config_path).resolve().parent
|
|
55
84
|
imap_cfg = cfg["imap"]
|
|
56
|
-
|
|
85
|
+
gmail_accounts = get_gmail_accounts(cfg)
|
|
86
|
+
if not gmail_accounts:
|
|
87
|
+
return {"error": "No Gmail account configured (add 'gmail' or 'gmail_accounts' in config)", "imported": 0, "skipped_duplicate": 0, "deleted": 0}
|
|
57
88
|
state_cfg = cfg.get("state", {})
|
|
58
|
-
|
|
89
|
+
raw_db_path = state_cfg.get("db_path", "state.db")
|
|
90
|
+
db_path = Path(raw_db_path)
|
|
91
|
+
if not db_path.is_absolute():
|
|
92
|
+
db_path = config_dir / db_path
|
|
59
93
|
mailbox = imap_cfg.get("mailbox", "INBOX")
|
|
60
94
|
delete_after_import = imap_cfg.get("delete_after_import", True)
|
|
61
|
-
use_label = gmail_cfg.get("use_label") if "use_label" in gmail_cfg else bool((gmail_cfg.get("label") or "").strip())
|
|
62
|
-
label_name = (gmail_cfg.get("label") or "ISP Mail").strip() if use_label else None
|
|
63
95
|
|
|
64
|
-
state = StateStore(db_path)
|
|
96
|
+
state = StateStore(str(db_path))
|
|
65
97
|
state.connect()
|
|
66
98
|
|
|
67
99
|
try:
|
|
@@ -95,22 +127,11 @@ def run_once(config_path: str | None = None, dry_run: bool = False) -> dict[str,
|
|
|
95
127
|
imported = 0
|
|
96
128
|
skipped_duplicate = 0
|
|
97
129
|
deleted = 0
|
|
98
|
-
|
|
99
|
-
label_id = None
|
|
100
|
-
inbox_label_id = None
|
|
101
|
-
unread_label_id = None
|
|
130
|
+
gmail_contexts: list[tuple[Any, str | None, str, str]] = []
|
|
102
131
|
|
|
103
132
|
if not dry_run:
|
|
104
133
|
try:
|
|
105
|
-
|
|
106
|
-
gmail_cfg["credentials_path"],
|
|
107
|
-
gmail_cfg["token_path"],
|
|
108
|
-
)
|
|
109
|
-
inbox_label_id = get_inbox_label_id(service, USER_ID)
|
|
110
|
-
unread_label_id = get_unread_label_id(service, USER_ID)
|
|
111
|
-
label_id = _ensure_label(service, label_name) if label_name else None
|
|
112
|
-
if label_name and not label_id:
|
|
113
|
-
label_id = _ensure_label(service, label_name)
|
|
134
|
+
gmail_contexts = _build_gmail_contexts(gmail_accounts, config_dir)
|
|
114
135
|
except Exception as e:
|
|
115
136
|
logger.exception("Gmail API init failed: %s", e)
|
|
116
137
|
return {"error": str(e), "imported": 0, "skipped_duplicate": 0, "deleted": 0}
|
|
@@ -119,18 +140,6 @@ def run_once(config_path: str | None = None, dry_run: bool = False) -> dict[str,
|
|
|
119
140
|
if state.seen_hash(msg.message_hash):
|
|
120
141
|
logger.debug("Skipping duplicate (hash): uid=%s", msg.uid)
|
|
121
142
|
skipped_duplicate += 1
|
|
122
|
-
# Still advance last_processed_uid after we would have deleted (see below)
|
|
123
|
-
# Actually no: we don't delete duplicates from ISP. So we don't update last_uid for skipped.
|
|
124
|
-
# So we'll see them again next run. To avoid re-checking forever, we could record "seen UID" without
|
|
125
|
-
# Gmail ID - but then we'd want to delete from ISP too for duplicates. Per spec: "If a UID changes or
|
|
126
|
-
# server resets UIDVALIDITY, use the hash to prevent duplicates." So we skip import but do we delete?
|
|
127
|
-
# Spec says "Only delete from ISP after Gmail confirms successful import." So we don't delete if we
|
|
128
|
-
# skipped (no Gmail import). So the message stays on ISP. We could still advance last_processed_uid
|
|
129
|
-
# so we don't keep re-fetching it - but then we'd never delete it. So the right behavior is: skip
|
|
130
|
-
# import, do NOT delete, do NOT advance last_uid - so next run we'll see it again and skip again.
|
|
131
|
-
# That's wasteful. Alternative: when we skip by hash, we still delete from ISP (we know it's already
|
|
132
|
-
# in Gmail from a previous run). That way we advance and delete. I'll do that: if seen_hash, delete
|
|
133
|
-
# from ISP and advance last_uid, so we don't re-process.
|
|
134
143
|
if not dry_run and delete_after_import:
|
|
135
144
|
try:
|
|
136
145
|
delete_and_expunge(
|
|
@@ -153,31 +162,57 @@ def run_once(config_path: str | None = None, dry_run: bool = False) -> dict[str,
|
|
|
153
162
|
imported += 1
|
|
154
163
|
continue
|
|
155
164
|
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
165
|
+
# Import to all Gmail accounts. Record state when at least one import succeeds; only
|
|
166
|
+
# delete from ISP when *all* imports succeed. This avoids duplicate imports when a
|
|
167
|
+
# subset of accounts succeeded but others failed.
|
|
168
|
+
first_gmail_id: str | None = None
|
|
169
|
+
all_succeeded = True
|
|
170
|
+
any_imported = False
|
|
171
|
+
skip_entire_message = False
|
|
172
|
+
for idx, (service, label_id, inbox_label_id, unread_label_id) in enumerate(gmail_contexts):
|
|
173
|
+
try:
|
|
174
|
+
label_ids = [label_id] if label_id else []
|
|
175
|
+
gmail_id = import_message(
|
|
176
|
+
service,
|
|
177
|
+
USER_ID,
|
|
178
|
+
msg.raw,
|
|
179
|
+
label_ids=label_ids,
|
|
180
|
+
inbox_label_id=inbox_label_id,
|
|
181
|
+
unread_label_id=unread_label_id,
|
|
182
|
+
mark_unread=True,
|
|
183
|
+
)
|
|
184
|
+
any_imported = True
|
|
185
|
+
if first_gmail_id is None:
|
|
186
|
+
first_gmail_id = gmail_id
|
|
187
|
+
logger.info("Imported uid=%s -> Gmail account %s id=%s", msg.uid, idx + 1, gmail_id)
|
|
188
|
+
except SkipMessageError as e:
|
|
189
|
+
logger.warning("Skipping uid=%s (no From/Sender/Reply-To): %s", msg.uid, e)
|
|
190
|
+
# Message is structurally invalid for Gmail (missing From/Sender/Reply-To). Treat it
|
|
191
|
+
# as permanently unimportable for *all* accounts: do not record a partial success,
|
|
192
|
+
# but do advance last_processed_uid so we don't get stuck retrying this UID forever.
|
|
193
|
+
skip_entire_message = True
|
|
194
|
+
all_succeeded = False
|
|
195
|
+
break
|
|
196
|
+
except Exception as e:
|
|
197
|
+
logger.exception("Gmail import failed for uid=%s account %s: %s", msg.uid, idx + 1, e)
|
|
198
|
+
all_succeeded = False
|
|
199
|
+
break
|
|
200
|
+
|
|
201
|
+
if skip_entire_message:
|
|
169
202
|
state.set_last_processed_uid(mailbox, uid_validity, msg.uid)
|
|
170
|
-
|
|
171
|
-
logger.info("Imported uid=%s -> Gmail id=%s", msg.uid, gmail_id)
|
|
172
|
-
except SkipMessageError as e:
|
|
173
|
-
logger.warning("Skipping uid=%s (no From/Sender/Reply-To): %s", msg.uid, e)
|
|
203
|
+
# Do not record_import and do not delete from ISP; the message remains only on ISP.
|
|
174
204
|
continue
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
#
|
|
205
|
+
|
|
206
|
+
if not any_imported or first_gmail_id is None:
|
|
207
|
+
# No successful import this run; do not record state or delete from ISP.
|
|
208
|
+
# Next run will retry for all accounts.
|
|
178
209
|
continue
|
|
179
210
|
|
|
180
|
-
|
|
211
|
+
state.record_import(msg.message_hash, first_gmail_id, mailbox, uid_validity, msg.uid)
|
|
212
|
+
state.set_last_processed_uid(mailbox, uid_validity, msg.uid)
|
|
213
|
+
imported += 1
|
|
214
|
+
|
|
215
|
+
if delete_after_import and all_succeeded:
|
|
181
216
|
try:
|
|
182
217
|
delete_and_expunge(
|
|
183
218
|
imap_cfg["host"],
|
|
@@ -190,10 +225,8 @@ def run_once(config_path: str | None = None, dry_run: bool = False) -> dict[str,
|
|
|
190
225
|
)
|
|
191
226
|
deleted += 1
|
|
192
227
|
except Exception as e:
|
|
228
|
+
# Count only successful deletions; failures are logged but not included.
|
|
193
229
|
logger.exception("Delete failed for uid=%s (already in Gmail): %s", msg.uid, e)
|
|
194
|
-
# State already updated; next run won't re-import (hash recorded). We can retry delete later
|
|
195
|
-
# by scanning ISP and matching hashes - not implemented; manual cleanup or re-run delete-only.
|
|
196
|
-
deleted += 1 # count as "handled"
|
|
197
230
|
|
|
198
231
|
last_fetch = state.get_last_fetch_time(mailbox, uid_validity)
|
|
199
232
|
state.close()
|
|
@@ -215,21 +248,26 @@ def run_copy_all(
|
|
|
215
248
|
Copy all messages from ISP mailbox to Gmail (not just UID > last_processed).
|
|
216
249
|
Preserves read/unread from IMAP \\Seen. Skips messages already in Gmail (by hash or Message-ID).
|
|
217
250
|
delete_after_import: if True, delete from ISP after successful import (or after skip when already in Gmail).
|
|
251
|
+
Supports multiple Gmail accounts: import to all; delete from ISP only if all imports succeed.
|
|
218
252
|
Returns same shape as run_once.
|
|
219
253
|
"""
|
|
220
254
|
if config_path is None:
|
|
221
255
|
from .config import get_config_path
|
|
222
256
|
config_path = str(get_config_path())
|
|
223
257
|
cfg = load_config(config_path)
|
|
258
|
+
config_dir = Path(config_path).resolve().parent
|
|
224
259
|
imap_cfg = cfg["imap"]
|
|
225
|
-
|
|
260
|
+
gmail_accounts = get_gmail_accounts(cfg)
|
|
261
|
+
if not gmail_accounts:
|
|
262
|
+
return {"error": "No Gmail account configured (add 'gmail' or 'gmail_accounts' in config)", "imported": 0, "skipped_duplicate": 0, "deleted": 0}
|
|
226
263
|
state_cfg = cfg.get("state", {})
|
|
227
|
-
|
|
264
|
+
raw_db_path = state_cfg.get("db_path", "state.db")
|
|
265
|
+
db_path = Path(raw_db_path)
|
|
266
|
+
if not db_path.is_absolute():
|
|
267
|
+
db_path = config_dir / db_path
|
|
228
268
|
mailbox = imap_cfg.get("mailbox", "INBOX")
|
|
229
|
-
use_label = gmail_cfg.get("use_label") if "use_label" in gmail_cfg else bool((gmail_cfg.get("label") or "").strip())
|
|
230
|
-
label_name = (gmail_cfg.get("label") or "ISP Mail").strip() if use_label else None
|
|
231
269
|
|
|
232
|
-
state = StateStore(db_path)
|
|
270
|
+
state = StateStore(str(db_path))
|
|
233
271
|
state.connect()
|
|
234
272
|
|
|
235
273
|
try:
|
|
@@ -262,26 +300,24 @@ def run_copy_all(
|
|
|
262
300
|
imported = 0
|
|
263
301
|
skipped_duplicate = 0
|
|
264
302
|
deleted = 0
|
|
265
|
-
|
|
266
|
-
label_id = None
|
|
267
|
-
inbox_label_id = None
|
|
268
|
-
unread_label_id = None
|
|
303
|
+
gmail_contexts: list[tuple[Any, str | None, str, str]] = []
|
|
269
304
|
|
|
270
305
|
if not dry_run:
|
|
271
306
|
try:
|
|
272
|
-
|
|
273
|
-
gmail_cfg["credentials_path"],
|
|
274
|
-
gmail_cfg["token_path"],
|
|
275
|
-
)
|
|
276
|
-
inbox_label_id = get_inbox_label_id(service, USER_ID)
|
|
277
|
-
unread_label_id = get_unread_label_id(service, USER_ID)
|
|
278
|
-
label_id = _ensure_label(service, label_name) if label_name else None
|
|
307
|
+
gmail_contexts = _build_gmail_contexts(gmail_accounts, config_dir)
|
|
279
308
|
except Exception as e:
|
|
280
309
|
logger.exception("Gmail API init failed: %s", e)
|
|
281
310
|
return {"error": str(e), "imported": 0, "skipped_duplicate": 0, "deleted": 0}
|
|
282
311
|
|
|
283
312
|
for msg in messages_iter:
|
|
284
|
-
|
|
313
|
+
# Copy-all is also used as a "repair" tool. With multiple Gmail accounts, we must not
|
|
314
|
+
# skip a message just because one account already has it; we should import to the missing
|
|
315
|
+
# accounts. Therefore:
|
|
316
|
+
# - For single-account setups, we keep the existing hash-based dedupe fast-path.
|
|
317
|
+
# - For multi-account setups, we rely on per-account Message-ID checks when available.
|
|
318
|
+
# IMPORTANT: use gmail_accounts length here (not gmail_contexts) so behavior is correct
|
|
319
|
+
# even in dry-run, where gmail_contexts is intentionally empty.
|
|
320
|
+
if len(gmail_accounts) <= 1 and state.seen_hash(msg.message_hash):
|
|
285
321
|
logger.debug("Copy-all: skipping duplicate (hash): uid=%s", msg.uid)
|
|
286
322
|
skipped_duplicate += 1
|
|
287
323
|
if not dry_run and delete_after_import:
|
|
@@ -301,37 +337,6 @@ def run_copy_all(
|
|
|
301
337
|
logger.warning("Delete (duplicate) failed for uid=%s: %s", msg.uid, e)
|
|
302
338
|
continue
|
|
303
339
|
|
|
304
|
-
if not dry_run:
|
|
305
|
-
message_id_header = _parse_message_id_from_raw(msg.raw)
|
|
306
|
-
if message_id_header and gmail_has_message_with_id(
|
|
307
|
-
service, USER_ID, message_id_header
|
|
308
|
-
):
|
|
309
|
-
logger.debug(
|
|
310
|
-
"Copy-all: skipping (already in Gmail by Message-ID): uid=%s",
|
|
311
|
-
msg.uid,
|
|
312
|
-
)
|
|
313
|
-
skipped_duplicate += 1
|
|
314
|
-
if delete_after_import:
|
|
315
|
-
try:
|
|
316
|
-
delete_and_expunge(
|
|
317
|
-
imap_cfg["host"],
|
|
318
|
-
int(imap_cfg.get("port", 993)),
|
|
319
|
-
imap_cfg["username"],
|
|
320
|
-
imap_cfg["password"],
|
|
321
|
-
mailbox,
|
|
322
|
-
msg.uid,
|
|
323
|
-
imap_cfg.get("use_ssl", True),
|
|
324
|
-
)
|
|
325
|
-
state.set_last_processed_uid(mailbox, uid_validity, msg.uid)
|
|
326
|
-
deleted += 1
|
|
327
|
-
except Exception as e:
|
|
328
|
-
logger.warning(
|
|
329
|
-
"Delete (already in Gmail) failed for uid=%s: %s",
|
|
330
|
-
msg.uid,
|
|
331
|
-
e,
|
|
332
|
-
)
|
|
333
|
-
continue
|
|
334
|
-
|
|
335
340
|
if dry_run:
|
|
336
341
|
logger.info(
|
|
337
342
|
"[DRY-RUN] Copy-all would import uid=%s (hash=%s)",
|
|
@@ -341,29 +346,93 @@ def run_copy_all(
|
|
|
341
346
|
imported += 1
|
|
342
347
|
continue
|
|
343
348
|
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
349
|
+
message_id_header = None
|
|
350
|
+
if not dry_run:
|
|
351
|
+
message_id_header = _parse_message_id_from_raw(msg.raw)
|
|
352
|
+
|
|
353
|
+
first_gmail_id: str | None = None
|
|
354
|
+
all_succeeded = True
|
|
355
|
+
any_imported = False
|
|
356
|
+
all_already_had = True
|
|
357
|
+
|
|
358
|
+
for idx, (service, label_id, inbox_label_id, unread_label_id) in enumerate(gmail_contexts):
|
|
359
|
+
try:
|
|
360
|
+
already_here = False
|
|
361
|
+
if message_id_header:
|
|
362
|
+
already_here = gmail_has_message_with_id(service, USER_ID, message_id_header)
|
|
363
|
+
if already_here:
|
|
364
|
+
logger.debug("Copy-all: uid=%s already in Gmail account %s (Message-ID)", msg.uid, idx + 1)
|
|
365
|
+
else:
|
|
366
|
+
all_already_had = False
|
|
367
|
+
label_ids = [label_id] if label_id else []
|
|
368
|
+
gmail_id = import_message(
|
|
369
|
+
service,
|
|
370
|
+
USER_ID,
|
|
371
|
+
msg.raw,
|
|
372
|
+
label_ids=label_ids,
|
|
373
|
+
inbox_label_id=inbox_label_id,
|
|
374
|
+
unread_label_id=unread_label_id,
|
|
375
|
+
mark_unread=not msg.is_seen,
|
|
376
|
+
)
|
|
377
|
+
any_imported = True
|
|
378
|
+
if first_gmail_id is None:
|
|
379
|
+
first_gmail_id = gmail_id
|
|
380
|
+
logger.info(
|
|
381
|
+
"Copy-all imported uid=%s -> Gmail account %s id=%s",
|
|
382
|
+
msg.uid,
|
|
383
|
+
idx + 1,
|
|
384
|
+
gmail_id,
|
|
385
|
+
)
|
|
386
|
+
except SkipMessageError as e:
|
|
387
|
+
logger.warning("Skipping uid=%s (no From/Sender/Reply-To): %s", msg.uid, e)
|
|
388
|
+
all_succeeded = False
|
|
389
|
+
break
|
|
390
|
+
except Exception as e:
|
|
391
|
+
logger.exception("Gmail import failed for uid=%s account %s: %s", msg.uid, idx + 1, e)
|
|
392
|
+
all_succeeded = False
|
|
393
|
+
break
|
|
394
|
+
|
|
395
|
+
if not all_succeeded:
|
|
396
|
+
continue
|
|
397
|
+
|
|
398
|
+
if all_already_had and message_id_header:
|
|
399
|
+
skipped_duplicate += 1
|
|
400
|
+
# Even when every Gmail account already has the message, we still consider it "handled"
|
|
401
|
+
# for copy-all bookkeeping so we don't re-process it on subsequent copy-all runs.
|
|
402
|
+
state.record_import(
|
|
403
|
+
msg.message_hash,
|
|
404
|
+
"already-present",
|
|
405
|
+
mailbox,
|
|
406
|
+
uid_validity,
|
|
407
|
+
msg.uid,
|
|
355
408
|
)
|
|
356
|
-
state.record_import(msg.message_hash, gmail_id, mailbox, uid_validity, msg.uid)
|
|
357
409
|
state.set_last_processed_uid(mailbox, uid_validity, msg.uid)
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
410
|
+
if delete_after_import:
|
|
411
|
+
try:
|
|
412
|
+
delete_and_expunge(
|
|
413
|
+
imap_cfg["host"],
|
|
414
|
+
int(imap_cfg.get("port", 993)),
|
|
415
|
+
imap_cfg["username"],
|
|
416
|
+
imap_cfg["password"],
|
|
417
|
+
mailbox,
|
|
418
|
+
msg.uid,
|
|
419
|
+
imap_cfg.get("use_ssl", True),
|
|
420
|
+
)
|
|
421
|
+
deleted += 1
|
|
422
|
+
except Exception as e:
|
|
423
|
+
logger.warning("Delete (already in Gmail) failed for uid=%s: %s", msg.uid, e)
|
|
362
424
|
continue
|
|
363
|
-
|
|
364
|
-
|
|
425
|
+
|
|
426
|
+
if not any_imported and first_gmail_id is None:
|
|
427
|
+
# No Message-ID to check, and no import happened (shouldn't occur); be safe.
|
|
365
428
|
continue
|
|
366
429
|
|
|
430
|
+
# Consider the message handled when every account either already had it (by Message-ID)
|
|
431
|
+
# or we successfully imported it. Record a single hash marker for copy-all bookkeeping.
|
|
432
|
+
state.record_import(msg.message_hash, first_gmail_id or "already-present", mailbox, uid_validity, msg.uid)
|
|
433
|
+
state.set_last_processed_uid(mailbox, uid_validity, msg.uid)
|
|
434
|
+
imported += 1
|
|
435
|
+
|
|
367
436
|
if delete_after_import:
|
|
368
437
|
try:
|
|
369
438
|
delete_and_expunge(
|
|
@@ -377,10 +446,10 @@ def run_copy_all(
|
|
|
377
446
|
)
|
|
378
447
|
deleted += 1
|
|
379
448
|
except Exception as e:
|
|
449
|
+
# Only count successful deletions; failures are logged but not included.
|
|
380
450
|
logger.exception(
|
|
381
451
|
"Delete failed for uid=%s (already in Gmail): %s", msg.uid, e
|
|
382
452
|
)
|
|
383
|
-
deleted += 1
|
|
384
453
|
|
|
385
454
|
last_fetch = state.get_last_fetch_time(mailbox, uid_validity)
|
|
386
455
|
state.close()
|
|
@@ -22,7 +22,7 @@ from pydantic import BaseModel
|
|
|
22
22
|
|
|
23
23
|
import imaplib
|
|
24
24
|
|
|
25
|
-
from .config import get_config_path, load_config
|
|
25
|
+
from .config import get_config_path, get_gmail_accounts, load_config
|
|
26
26
|
from .env_file import set_encrypted_env
|
|
27
27
|
from .gmail_client import get_gmail_service
|
|
28
28
|
from .imap_client import get_uid_validity
|
|
@@ -175,16 +175,22 @@ def _config_exists() -> bool:
|
|
|
175
175
|
|
|
176
176
|
|
|
177
177
|
def _token_exists() -> bool:
|
|
178
|
-
"""True when config exists and
|
|
178
|
+
"""True when config exists and every Gmail account has its token file."""
|
|
179
179
|
cfg_dir = _config_dir_safe()
|
|
180
180
|
if not cfg_dir or not _config_exists():
|
|
181
181
|
return False
|
|
182
182
|
try:
|
|
183
183
|
cfg = load_config(_get_config_path(), resolve_password=False)
|
|
184
|
-
|
|
185
|
-
if not
|
|
186
|
-
|
|
187
|
-
|
|
184
|
+
accounts = get_gmail_accounts(cfg)
|
|
185
|
+
if not accounts:
|
|
186
|
+
return False
|
|
187
|
+
for acct in accounts:
|
|
188
|
+
token_path = Path(acct.get("token_path", "token.json"))
|
|
189
|
+
if not token_path.is_absolute():
|
|
190
|
+
token_path = cfg_dir / token_path
|
|
191
|
+
if not token_path.exists():
|
|
192
|
+
return False
|
|
193
|
+
return True
|
|
188
194
|
except Exception:
|
|
189
195
|
return False
|
|
190
196
|
|
|
@@ -230,6 +236,13 @@ class GmailConfigSafe(BaseModel):
|
|
|
230
236
|
token_path: str
|
|
231
237
|
|
|
232
238
|
|
|
239
|
+
class GmailAccountSafe(BaseModel):
|
|
240
|
+
use_label: bool
|
|
241
|
+
label: str
|
|
242
|
+
credentials_path: str
|
|
243
|
+
token_path: str
|
|
244
|
+
|
|
245
|
+
|
|
233
246
|
class UIConfigSafe(BaseModel):
|
|
234
247
|
host: str
|
|
235
248
|
port: int
|
|
@@ -238,6 +251,7 @@ class UIConfigSafe(BaseModel):
|
|
|
238
251
|
class ConfigResponse(BaseModel):
|
|
239
252
|
imap: ImapConfigSafe
|
|
240
253
|
gmail: GmailConfigSafe
|
|
254
|
+
gmail_accounts: list[GmailAccountSafe] = []
|
|
241
255
|
ui: UIConfigSafe
|
|
242
256
|
poll_interval_minutes: int
|
|
243
257
|
state_db_path: str
|
|
@@ -336,27 +350,20 @@ def index(request: Request) -> str:
|
|
|
336
350
|
|
|
337
351
|
|
|
338
352
|
def _gmail_connected() -> bool:
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
return False
|
|
342
|
-
try:
|
|
343
|
-
cfg = load_config(path, resolve_password=False)
|
|
344
|
-
token_path = (cfg.get("gmail") or {}).get("token_path", "token.json")
|
|
345
|
-
tp = Path(token_path)
|
|
346
|
-
if not tp.is_absolute():
|
|
347
|
-
tp = _config_dir() / token_path
|
|
348
|
-
return tp.exists()
|
|
349
|
-
except Exception:
|
|
350
|
-
return False
|
|
353
|
+
"""True when all configured Gmail accounts have token files (and can be used for fetch)."""
|
|
354
|
+
return _token_exists()
|
|
351
355
|
|
|
352
356
|
|
|
353
357
|
def _gmail_email() -> str | None:
|
|
354
|
-
"""Return the Gmail address for the
|
|
358
|
+
"""Return the Gmail address for the first account, or None if not connected or error."""
|
|
355
359
|
if not _gmail_connected():
|
|
356
360
|
return None
|
|
357
361
|
try:
|
|
358
362
|
cfg = load_config(_get_config_path(), resolve_password=False)
|
|
359
|
-
|
|
363
|
+
accounts = get_gmail_accounts(cfg)
|
|
364
|
+
if not accounts:
|
|
365
|
+
return None
|
|
366
|
+
gmail = accounts[0]
|
|
360
367
|
cred_path = Path(gmail.get("credentials_path", "credentials.json"))
|
|
361
368
|
token_path = Path(gmail.get("token_path", "token.json"))
|
|
362
369
|
if not cred_path.is_absolute():
|
|
@@ -439,6 +446,14 @@ def _default_config_response() -> ConfigResponse:
|
|
|
439
446
|
credentials_path="credentials.json",
|
|
440
447
|
token_path="token.json",
|
|
441
448
|
),
|
|
449
|
+
gmail_accounts=[
|
|
450
|
+
GmailAccountSafe(
|
|
451
|
+
use_label=False,
|
|
452
|
+
label="ISP Mail",
|
|
453
|
+
credentials_path="credentials.json",
|
|
454
|
+
token_path="token.json",
|
|
455
|
+
)
|
|
456
|
+
],
|
|
442
457
|
ui=UIConfigSafe(host="127.0.0.1", port=8765),
|
|
443
458
|
poll_interval_minutes=5,
|
|
444
459
|
state_db_path="state.db",
|
|
@@ -463,11 +478,22 @@ def api_config(request: Request) -> ConfigResponse:
|
|
|
463
478
|
except ValueError as e:
|
|
464
479
|
raise HTTPException(status_code=400, detail=str(e))
|
|
465
480
|
imap = cfg.get("imap") or {}
|
|
466
|
-
|
|
481
|
+
gmail_accounts = get_gmail_accounts(cfg)
|
|
482
|
+
gmail = gmail_accounts[0] if gmail_accounts else {}
|
|
467
483
|
ui = cfg.get("ui") or {}
|
|
468
484
|
state = cfg.get("state") or {}
|
|
469
485
|
cred_path = gmail.get("credentials_path", "credentials.json")
|
|
470
486
|
token_path = gmail.get("token_path", "token.json")
|
|
487
|
+
gmail_accounts_safe: list[GmailAccountSafe] = []
|
|
488
|
+
for acct in gmail_accounts:
|
|
489
|
+
gmail_accounts_safe.append(
|
|
490
|
+
GmailAccountSafe(
|
|
491
|
+
use_label=acct.get("use_label") if "use_label" in acct else bool((acct.get("label") or "").strip()),
|
|
492
|
+
label=acct.get("label", "ISP Mail"),
|
|
493
|
+
credentials_path=acct.get("credentials_path", "credentials.json"),
|
|
494
|
+
token_path=acct.get("token_path", "token.json"),
|
|
495
|
+
)
|
|
496
|
+
)
|
|
471
497
|
return ConfigResponse(
|
|
472
498
|
imap=ImapConfigSafe(
|
|
473
499
|
host=imap.get("host", ""),
|
|
@@ -483,6 +509,7 @@ def api_config(request: Request) -> ConfigResponse:
|
|
|
483
509
|
credentials_path=cred_path,
|
|
484
510
|
token_path=token_path,
|
|
485
511
|
),
|
|
512
|
+
gmail_accounts=gmail_accounts_safe,
|
|
486
513
|
ui=UIConfigSafe(
|
|
487
514
|
host=ui.get("host", "127.0.0.1"),
|
|
488
515
|
port=int(ui.get("port", 8765)),
|
|
@@ -507,6 +534,7 @@ class ConfigUpdate(BaseModel):
|
|
|
507
534
|
delete_after_import: bool | None = None
|
|
508
535
|
gmail_use_label: bool | None = None
|
|
509
536
|
gmail_label: str | None = None
|
|
537
|
+
gmail_accounts: list[GmailAccountSafe] | None = None
|
|
510
538
|
poll_interval_minutes: int | None = None
|
|
511
539
|
state_db_path: str | None = None
|
|
512
540
|
|
|
@@ -557,12 +585,15 @@ def api_setup(request: Request, body: SetupBody) -> dict[str, str]:
|
|
|
557
585
|
"use_ssl": body.imap_use_ssl,
|
|
558
586
|
"delete_after_import": body.delete_after_import,
|
|
559
587
|
},
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
588
|
+
# Canonical: gmail_accounts. Keep legacy readers working via get_gmail_accounts().
|
|
589
|
+
"gmail_accounts": [
|
|
590
|
+
{
|
|
591
|
+
"use_label": body.gmail_use_label,
|
|
592
|
+
"label": body.gmail_label,
|
|
593
|
+
"credentials_path": body.credentials_path,
|
|
594
|
+
"token_path": body.token_path,
|
|
595
|
+
}
|
|
596
|
+
],
|
|
566
597
|
"state": {"db_path": body.state_db_path},
|
|
567
598
|
"ui": {"host": "127.0.0.1", "port": 8765},
|
|
568
599
|
"poll_interval_minutes": 5,
|
|
@@ -620,10 +651,35 @@ def api_config_update(request: Request, update: ConfigUpdate) -> dict[str, str]:
|
|
|
620
651
|
imap["use_ssl"] = update.imap_use_ssl
|
|
621
652
|
if update.delete_after_import is not None:
|
|
622
653
|
cfg.setdefault("imap", {})["delete_after_import"] = update.delete_after_import
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
cfg
|
|
654
|
+
# Gmail accounts
|
|
655
|
+
if update.gmail_accounts is not None:
|
|
656
|
+
# Replace full list from UI (canonical).
|
|
657
|
+
cfg["gmail_accounts"] = [
|
|
658
|
+
{
|
|
659
|
+
"use_label": a.use_label,
|
|
660
|
+
"label": a.label,
|
|
661
|
+
"credentials_path": a.credentials_path,
|
|
662
|
+
"token_path": a.token_path,
|
|
663
|
+
}
|
|
664
|
+
for a in update.gmail_accounts
|
|
665
|
+
]
|
|
666
|
+
# Do not keep legacy 'gmail' when explicitly using gmail_accounts.
|
|
667
|
+
if "gmail" in cfg:
|
|
668
|
+
cfg.pop("gmail", None)
|
|
669
|
+
else:
|
|
670
|
+
# Back-compat: UI may still send gmail_use_label/gmail_label for the first account.
|
|
671
|
+
if update.gmail_use_label is not None or update.gmail_label is not None:
|
|
672
|
+
existing = get_gmail_accounts(cfg)
|
|
673
|
+
if not existing:
|
|
674
|
+
existing = [{"credentials_path": "credentials.json", "token_path": "token.json"}]
|
|
675
|
+
first = dict(existing[0])
|
|
676
|
+
if update.gmail_use_label is not None:
|
|
677
|
+
first["use_label"] = update.gmail_use_label
|
|
678
|
+
if update.gmail_label is not None:
|
|
679
|
+
first["label"] = update.gmail_label
|
|
680
|
+
rest = existing[1:]
|
|
681
|
+
cfg["gmail_accounts"] = [first, *rest]
|
|
682
|
+
cfg.pop("gmail", None)
|
|
627
683
|
if update.poll_interval_minutes is not None:
|
|
628
684
|
cfg["poll_interval_minutes"] = update.poll_interval_minutes
|
|
629
685
|
if update.state_db_path is not None:
|
|
@@ -633,6 +689,94 @@ def api_config_update(request: Request, update: ConfigUpdate) -> dict[str, str]:
|
|
|
633
689
|
return {"status": "ok"}
|
|
634
690
|
|
|
635
691
|
|
|
692
|
+
class DiscoveredToken(BaseModel):
|
|
693
|
+
token_path: str
|
|
694
|
+
email: str | None = None
|
|
695
|
+
in_use: bool = False
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
@app.get("/api/gmail/discover-tokens", response_model=list[DiscoveredToken])
|
|
699
|
+
def api_gmail_discover_tokens(request: Request) -> list[DiscoveredToken]:
|
|
700
|
+
"""List token*.json files in config dir and (best-effort) associated Gmail email."""
|
|
701
|
+
if not _require_auth(request):
|
|
702
|
+
raise HTTPException(status_code=401, detail="Not authenticated")
|
|
703
|
+
cfg_dir = _config_dir_safe()
|
|
704
|
+
if not cfg_dir:
|
|
705
|
+
return []
|
|
706
|
+
# tokens in directory
|
|
707
|
+
token_files = sorted([p.name for p in Path(cfg_dir).glob("token*.json") if p.is_file()])
|
|
708
|
+
in_use: set[str] = set()
|
|
709
|
+
try:
|
|
710
|
+
if _config_exists():
|
|
711
|
+
cfg = load_config(_get_config_path(), resolve_password=False)
|
|
712
|
+
for a in get_gmail_accounts(cfg):
|
|
713
|
+
# Normalize for comparison against filenames in this directory. Config may store
|
|
714
|
+
# relative paths ("token2.json") or absolute paths ("/.../token2.json").
|
|
715
|
+
tp = Path(str(a.get("token_path", "token.json")))
|
|
716
|
+
in_use.add(tp.name)
|
|
717
|
+
except Exception:
|
|
718
|
+
pass
|
|
719
|
+
out: list[DiscoveredToken] = []
|
|
720
|
+
# Resolve email addresses best-effort (credentials required)
|
|
721
|
+
cred_path = Path(cfg_dir) / "credentials.json"
|
|
722
|
+
for fname in token_files:
|
|
723
|
+
tok_path = Path(cfg_dir) / fname
|
|
724
|
+
email = None
|
|
725
|
+
try:
|
|
726
|
+
if cred_path.exists() and tok_path.exists():
|
|
727
|
+
service = get_gmail_service(cred_path, tok_path)
|
|
728
|
+
profile = service.users().getProfile(userId="me").execute()
|
|
729
|
+
email = profile.get("emailAddress")
|
|
730
|
+
except Exception:
|
|
731
|
+
email = None
|
|
732
|
+
out.append(DiscoveredToken(token_path=fname, email=email, in_use=(fname in in_use)))
|
|
733
|
+
return out
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
class DeleteGmailAccountBody(BaseModel):
|
|
737
|
+
index: int
|
|
738
|
+
|
|
739
|
+
|
|
740
|
+
@app.delete("/api/gmail/accounts")
|
|
741
|
+
def api_delete_gmail_account(request: Request, body: DeleteGmailAccountBody) -> dict[str, str]:
|
|
742
|
+
"""Delete a secondary Gmail account entry and delete its token file (safety: index must be > 0)."""
|
|
743
|
+
if not _require_auth(request):
|
|
744
|
+
raise HTTPException(status_code=401, detail="Not authenticated")
|
|
745
|
+
if body.index <= 0:
|
|
746
|
+
raise HTTPException(status_code=400, detail="Cannot delete the primary Gmail account from the UI.")
|
|
747
|
+
path = _get_config_path()
|
|
748
|
+
if not path.exists():
|
|
749
|
+
raise HTTPException(status_code=404, detail="config.json not found")
|
|
750
|
+
with open(path, encoding="utf-8") as f:
|
|
751
|
+
cfg = json.load(f)
|
|
752
|
+
accounts = get_gmail_accounts(cfg)
|
|
753
|
+
if body.index >= len(accounts):
|
|
754
|
+
raise HTTPException(status_code=400, detail="Invalid account index")
|
|
755
|
+
token_path = str(accounts[body.index].get("token_path", "")).strip()
|
|
756
|
+
# Remove from config
|
|
757
|
+
new_accounts = [accounts[i] for i in range(len(accounts)) if i != body.index]
|
|
758
|
+
cfg["gmail_accounts"] = new_accounts
|
|
759
|
+
cfg.pop("gmail", None)
|
|
760
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
761
|
+
json.dump(cfg, f, indent=2)
|
|
762
|
+
try:
|
|
763
|
+
# Delete token file (only if inside config dir and named token*.json)
|
|
764
|
+
cfg_dir = _config_dir()
|
|
765
|
+
tp = Path(token_path)
|
|
766
|
+
if not tp.is_absolute():
|
|
767
|
+
tp = cfg_dir / tp
|
|
768
|
+
tp = tp.resolve()
|
|
769
|
+
if tp.parent != cfg_dir.resolve():
|
|
770
|
+
return {"status": "ok", "message": "Account removed. Token file was not deleted (outside config dir)."}
|
|
771
|
+
if not tp.name.startswith("token") or not tp.name.endswith(".json"):
|
|
772
|
+
return {"status": "ok", "message": "Account removed. Token file was not deleted (unexpected filename)."}
|
|
773
|
+
if tp.exists():
|
|
774
|
+
tp.unlink()
|
|
775
|
+
return {"status": "ok", "message": f"Account removed. Deleted {tp.name}."}
|
|
776
|
+
except Exception:
|
|
777
|
+
return {"status": "ok", "message": "Account removed. Token file deletion failed (check permissions)."}
|
|
778
|
+
|
|
779
|
+
|
|
636
780
|
class CopyAllBody(BaseModel):
|
|
637
781
|
"""Body for copy-all: copy every message from ISP to Gmail (with optional delete after)."""
|
|
638
782
|
delete_after: bool = False
|
|
@@ -692,9 +836,13 @@ def api_status(request: Request) -> dict[str, Any]:
|
|
|
692
836
|
cfg = load_config(_get_config_path(), resolve_password=False)
|
|
693
837
|
from .state import StateStore
|
|
694
838
|
state_cfg = cfg.get("state", {})
|
|
695
|
-
|
|
839
|
+
raw_db_path = state_cfg.get("db_path", "state.db")
|
|
840
|
+
from pathlib import Path as _PathForStatus
|
|
841
|
+
db_path = _PathForStatus(raw_db_path)
|
|
842
|
+
if not db_path.is_absolute():
|
|
843
|
+
db_path = _PathForStatus(_get_config_path()).resolve().parent / db_path
|
|
696
844
|
mailbox = (cfg.get("imap") or {}).get("mailbox", "INBOX")
|
|
697
|
-
state = StateStore(db_path)
|
|
845
|
+
state = StateStore(str(db_path))
|
|
698
846
|
state.connect()
|
|
699
847
|
row = state.get_last_fetch_time_any(mailbox)
|
|
700
848
|
state.close()
|
|
@@ -800,7 +948,24 @@ _HTML_PAGE = """
|
|
|
800
948
|
<h2>Gmail</h2>
|
|
801
949
|
<p id="gmailStatus"></p>
|
|
802
950
|
<p id="gmailEmail" class="status" style="font-size:0.9rem"></p>
|
|
803
|
-
<
|
|
951
|
+
<div id="gmailAccounts"></div>
|
|
952
|
+
<button type="button" id="btnAddGmailAccount">Add Gmail account</button>
|
|
953
|
+
<div id="addGmailAccountPanel" style="display:none; margin-top:0.75rem; padding:0.75rem; background:#f7f7f7; border:1px solid #e6e6e6;">
|
|
954
|
+
<div style="display:flex; gap:0.5rem; align-items:center; flex-wrap:wrap;">
|
|
955
|
+
<label style="margin:0; flex: 1 1 320px;">
|
|
956
|
+
Token to add
|
|
957
|
+
<select id="addGmailTokenSelect" style="width:100%; padding:0.4rem; margin-top:0.25rem;"></select>
|
|
958
|
+
</label>
|
|
959
|
+
<div style="display:flex; gap:0.5rem; align-items:flex-end; padding-top:1.35rem;">
|
|
960
|
+
<button type="button" id="btnConfirmAddGmailAccount">Add</button>
|
|
961
|
+
<button type="button" id="btnCancelAddGmailAccount">Cancel</button>
|
|
962
|
+
</div>
|
|
963
|
+
</div>
|
|
964
|
+
<p id="addGmailAccountMsg" class="status" style="margin-top:0.5rem;"></p>
|
|
965
|
+
</div>
|
|
966
|
+
<p class="hint" style="font-size:0.85rem; color:#666; margin-top:0.5rem;">
|
|
967
|
+
Tokens are created with <code>fetch2gmail auth</code> (CLI). To add a second account, run it again with a different token filename (e.g. <code>--token token2.json</code>).
|
|
968
|
+
</p>
|
|
804
969
|
</section>
|
|
805
970
|
|
|
806
971
|
<section id="changePasswordSection" style="display:none">
|
|
@@ -851,6 +1016,7 @@ _APP_JS = r"""
|
|
|
851
1016
|
(function() {
|
|
852
1017
|
const api = function(path) { return fetch(path).then(function(r) { if (r.status === 401) { location.href = '/'; throw new Error('Unauthorized'); } return r.ok ? r.json() : r.json().then(function(j) { return Promise.reject(j); }); }); };
|
|
853
1018
|
const put = function(path, body) { return fetch(path, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).then(function(r) { if (r.status === 401) { location.href = '/'; throw new Error('Unauthorized'); } return r.ok ? r.json() : r.json().then(function(j) { return Promise.reject(j); }); }); };
|
|
1019
|
+
const del = function(path, body) { return fetch(path, { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).then(function(r) { if (r.status === 401) { location.href = '/'; throw new Error('Unauthorized'); } return r.ok ? r.json() : r.json().then(function(j) { return Promise.reject(j); }); }); };
|
|
854
1020
|
|
|
855
1021
|
fetch('/api/setup/status').then(function(r) { return r.json(); }).then(function(st) {
|
|
856
1022
|
if (!st.credentials_exist) {
|
|
@@ -869,6 +1035,100 @@ _APP_JS = r"""
|
|
|
869
1035
|
if (params.get('error') === 'no_credentials') document.getElementById('subtitle').innerHTML = '<span class="error">Put credentials.json in the app folder and run fetch2gmail auth for token.json.</span>';
|
|
870
1036
|
|
|
871
1037
|
function hideLoading() { var el = document.getElementById('loadingMsg'); if (el) el.style.display = 'none'; }
|
|
1038
|
+
function ensureGmailAccounts(c) {
|
|
1039
|
+
if (c.gmail_accounts && c.gmail_accounts.length) return c.gmail_accounts;
|
|
1040
|
+
// Back-compat: synthesize from single c.gmail
|
|
1041
|
+
if (c.gmail) return [c.gmail];
|
|
1042
|
+
return [];
|
|
1043
|
+
}
|
|
1044
|
+
function renderGmailAccounts(c) {
|
|
1045
|
+
var wrap = document.getElementById('gmailAccounts');
|
|
1046
|
+
if (!wrap) return;
|
|
1047
|
+
var accounts = ensureGmailAccounts(c);
|
|
1048
|
+
if (!accounts.length) {
|
|
1049
|
+
wrap.innerHTML = '<p class=\"error\">No Gmail accounts configured.</p>';
|
|
1050
|
+
return;
|
|
1051
|
+
}
|
|
1052
|
+
// Enrich with Gmail email addresses by looking at token*.json files.
|
|
1053
|
+
api('/api/gmail/discover-tokens').then(function(tokens) {
|
|
1054
|
+
var emailByToken = {};
|
|
1055
|
+
if (Array.isArray(tokens)) {
|
|
1056
|
+
for (var i = 0; i < tokens.length; i++) {
|
|
1057
|
+
var t = tokens[i];
|
|
1058
|
+
if (t && t.token_path) emailByToken[t.token_path] = t.email || '';
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
var html = '<div style=\"margin-top:0.5rem;\">';
|
|
1062
|
+
html += '<table style=\"width:100%; border-collapse:collapse;\">';
|
|
1063
|
+
html += '<tr><th style=\"text-align:left; font-weight:600; padding:4px 0;\">Account</th><th style=\"text-align:left; font-weight:600; padding:4px 0;\">Token</th><th style=\"text-align:left; font-weight:600; padding:4px 0;\">Gmail account</th><th></th></tr>';
|
|
1064
|
+
for (var j = 0; j < accounts.length; j++) {
|
|
1065
|
+
var a = accounts[j];
|
|
1066
|
+
var token = (a.token_path || '').replace(/</g,'<').replace(/>/g,'>');
|
|
1067
|
+
var email = emailByToken[a.token_path || ''] || '';
|
|
1068
|
+
var emailDisplay = email ? email.replace(/</g,'<').replace(/>/g,'>') : '(unknown)';
|
|
1069
|
+
html += '<tr style=\"border-top:1px solid #eee;\">';
|
|
1070
|
+
html += '<td style=\"padding:6px 0;\">#' + (j + 1) + (j === 0 ? ' (primary)' : '') + '</td>';
|
|
1071
|
+
html += '<td style=\"padding:6px 0;\"><code>' + token + '</code></td>';
|
|
1072
|
+
html += '<td style=\"padding:6px 0; white-space:nowrap;\">' + emailDisplay + '</td>';
|
|
1073
|
+
html += '<td style=\"padding:6px 0; text-align:right;\">' + (j === 0 ? '' : '<button type=\"button\" data-gdel=\"' + j + '\">Delete</button>') + '</td>';
|
|
1074
|
+
html += '</tr>';
|
|
1075
|
+
}
|
|
1076
|
+
html += '</table>';
|
|
1077
|
+
html += '<p class=\"hint\" style=\"font-size:0.85rem; color:#666; margin:0.5rem 0 0;\">Deleting a secondary account also deletes its token file (e.g. <code>token2.json</code>).</p>';
|
|
1078
|
+
html += '</div>';
|
|
1079
|
+
wrap.innerHTML = html;
|
|
1080
|
+
// Wire delete buttons
|
|
1081
|
+
var btns = wrap.querySelectorAll('button[data-gdel]');
|
|
1082
|
+
for (var k = 0; k < btns.length; k++) {
|
|
1083
|
+
btns[k].onclick = function(ev) {
|
|
1084
|
+
var idx = parseInt(ev.target.getAttribute('data-gdel'), 10);
|
|
1085
|
+
if (!confirm('Delete Gmail account #' + (idx + 1) + '?\\n\\nThis will remove it from config and delete its token file.')) return;
|
|
1086
|
+
del('/api/gmail/accounts', { index: idx }).then(function(r) {
|
|
1087
|
+
document.getElementById('status').textContent = r.message || 'Account deleted.';
|
|
1088
|
+
document.getElementById('status').className = 'status';
|
|
1089
|
+
return loadConfig().then(function(cc) { if (cc) { renderGmailAccounts(cc); } });
|
|
1090
|
+
}).catch(function(e) {
|
|
1091
|
+
document.getElementById('status').textContent = 'Error: ' + (typeof e.detail === 'string' ? e.detail : (e.detail && e.detail.detail) || e.message || 'Delete failed');
|
|
1092
|
+
document.getElementById('status').className = 'error';
|
|
1093
|
+
});
|
|
1094
|
+
};
|
|
1095
|
+
}
|
|
1096
|
+
}).catch(function() {
|
|
1097
|
+
// Fallback: render without email info if discover-tokens fails.
|
|
1098
|
+
var html = '<div style=\"margin-top:0.5rem;\">';
|
|
1099
|
+
html += '<table style=\"width:100%; border-collapse:collapse;\">';
|
|
1100
|
+
html += '<tr><th style=\"text-align:left; font-weight:600; padding:4px 0;\">Account</th><th style=\"text-align:left; font-weight:600; padding:4px 0;\">Token</th><th></th></tr>';
|
|
1101
|
+
for (var j = 0; j < accounts.length; j++) {
|
|
1102
|
+
var a = accounts[j];
|
|
1103
|
+
var token = (a.token_path || '').replace(/</g,'<').replace(/>/g,'>');
|
|
1104
|
+
html += '<tr style=\"border-top:1px solid #eee;\">';
|
|
1105
|
+
html += '<td style=\"padding:6px 0;\">#' + (j + 1) + (j === 0 ? ' (primary)' : '') + '</td>';
|
|
1106
|
+
html += '<td style=\"padding:6px 0;\"><code>' + token + '</code></td>';
|
|
1107
|
+
html += '<td style=\"padding:6px 0; text-align:right;\">' + (j === 0 ? '' : '<button type=\"button\" data-gdel=\"' + j + '\">Delete</button>') + '</td>';
|
|
1108
|
+
html += '</tr>';
|
|
1109
|
+
}
|
|
1110
|
+
html += '</table>';
|
|
1111
|
+
html += '<p class=\"hint\" style=\"font-size:0.85rem; color:#666; margin:0.5rem 0 0;\">Deleting a secondary account also deletes its token file (e.g. <code>token2.json</code>).</p>';
|
|
1112
|
+
html += '</div>';
|
|
1113
|
+
wrap.innerHTML = html;
|
|
1114
|
+
// Wire delete buttons in fallback as well.
|
|
1115
|
+
var btns = wrap.querySelectorAll('button[data-gdel]');
|
|
1116
|
+
for (var k = 0; k < btns.length; k++) {
|
|
1117
|
+
btns[k].onclick = function(ev) {
|
|
1118
|
+
var idx = parseInt(ev.target.getAttribute('data-gdel'), 10);
|
|
1119
|
+
if (!confirm('Delete Gmail account #' + (idx + 1) + '?\\n\\nThis will remove it from config and delete its token file.')) return;
|
|
1120
|
+
del('/api/gmail/accounts', { index: idx }).then(function(r) {
|
|
1121
|
+
document.getElementById('status').textContent = r.message || 'Account deleted.';
|
|
1122
|
+
document.getElementById('status').className = 'status';
|
|
1123
|
+
return loadConfig().then(function(cc) { if (cc) { renderGmailAccounts(cc); } });
|
|
1124
|
+
}).catch(function(e) {
|
|
1125
|
+
document.getElementById('status').textContent = 'Error: ' + (typeof e.detail === 'string' ? e.detail : (e.detail && e.detail.detail) || e.message || 'Delete failed');
|
|
1126
|
+
document.getElementById('status').className = 'error';
|
|
1127
|
+
});
|
|
1128
|
+
};
|
|
1129
|
+
}
|
|
1130
|
+
});
|
|
1131
|
+
}
|
|
872
1132
|
function loadConfig() {
|
|
873
1133
|
return api('/api/config').then(function(c) {
|
|
874
1134
|
hideLoading();
|
|
@@ -903,8 +1163,23 @@ _APP_JS = r"""
|
|
|
903
1163
|
document.getElementById('gmailStatus').innerHTML = c.gmail_connected ? '<span class="ok">Gmail connected</span>' : '<span class="error">Not connected (add token.json from fetch2gmail auth)</span>';
|
|
904
1164
|
document.getElementById('gmailEmail').textContent = '';
|
|
905
1165
|
if (c.gmail_connected) {
|
|
906
|
-
api('/api/gmail/
|
|
1166
|
+
api('/api/gmail/discover-tokens').then(function(tokens) {
|
|
1167
|
+
if (!Array.isArray(tokens) || !tokens.length) return;
|
|
1168
|
+
var emails = [];
|
|
1169
|
+
for (var i = 0; i < tokens.length; i++) {
|
|
1170
|
+
if (tokens[i].email) emails.push(tokens[i].email);
|
|
1171
|
+
}
|
|
1172
|
+
if (!emails.length) return;
|
|
1173
|
+
var uniq = [];
|
|
1174
|
+
var seen = {};
|
|
1175
|
+
for (var j = 0; j < emails.length; j++) {
|
|
1176
|
+
var e = emails[j];
|
|
1177
|
+
if (!seen[e]) { seen[e] = true; uniq.push(e); }
|
|
1178
|
+
}
|
|
1179
|
+
document.getElementById('gmailEmail').textContent = 'Connected as ' + uniq.join(', ');
|
|
1180
|
+
}).catch(function() {});
|
|
907
1181
|
}
|
|
1182
|
+
renderGmailAccounts(c);
|
|
908
1183
|
return c;
|
|
909
1184
|
}).catch(function(e) {
|
|
910
1185
|
hideLoading();
|
|
@@ -1053,6 +1328,12 @@ _APP_JS = r"""
|
|
|
1053
1328
|
document.getElementById('gmail_label_row').style.display = this.checked ? 'block' : 'none';
|
|
1054
1329
|
};
|
|
1055
1330
|
document.getElementById('btnSave').onclick = function() {
|
|
1331
|
+
// Read current accounts from UI (labels only editable here).
|
|
1332
|
+
var currentAccounts = null;
|
|
1333
|
+
try {
|
|
1334
|
+
// use last loaded config from DOM if present
|
|
1335
|
+
// We'll rebuild from /api/config right before save to avoid stale token list
|
|
1336
|
+
} catch (e) {}
|
|
1056
1337
|
var body = {
|
|
1057
1338
|
imap_host: document.getElementById('imap_host').value,
|
|
1058
1339
|
imap_port: parseInt(document.getElementById('imap_port').value, 10),
|
|
@@ -1067,7 +1348,22 @@ _APP_JS = r"""
|
|
|
1067
1348
|
};
|
|
1068
1349
|
var pw = document.getElementById('imap_password').value;
|
|
1069
1350
|
if (pw) body.imap_password = pw;
|
|
1070
|
-
|
|
1351
|
+
// Merge updated settings into gmail_accounts and save canonical list.
|
|
1352
|
+
api('/api/config').then(function(c) {
|
|
1353
|
+
var accounts = ensureGmailAccounts(c);
|
|
1354
|
+
var useLabel = document.getElementById('gmail_use_label').checked;
|
|
1355
|
+
var globalLabel = document.getElementById('gmail_label').value || 'ISP Mail';
|
|
1356
|
+
// Apply global label toggle to all accounts; apply global label NAME only to primary
|
|
1357
|
+
// account so per-account labels (e.g. email-based) are not overwritten.
|
|
1358
|
+
for (var k = 0; k < accounts.length; k++) {
|
|
1359
|
+
accounts[k].use_label = useLabel;
|
|
1360
|
+
if (k === 0) {
|
|
1361
|
+
accounts[k].label = globalLabel;
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
body.gmail_accounts = accounts;
|
|
1365
|
+
return put('/api/config', body);
|
|
1366
|
+
}).then(function() {
|
|
1071
1367
|
document.getElementById('status').textContent = 'Config saved.';
|
|
1072
1368
|
document.getElementById('status').className = 'status';
|
|
1073
1369
|
if (pw) document.getElementById('imap_password').value = '';
|
|
@@ -1107,6 +1403,85 @@ _APP_JS = r"""
|
|
|
1107
1403
|
msg.className = 'error';
|
|
1108
1404
|
});
|
|
1109
1405
|
};
|
|
1406
|
+
|
|
1407
|
+
var addBtn = document.getElementById('btnAddGmailAccount');
|
|
1408
|
+
if (addBtn) {
|
|
1409
|
+
addBtn.onclick = function() {
|
|
1410
|
+
var panel = document.getElementById('addGmailAccountPanel');
|
|
1411
|
+
var sel = document.getElementById('addGmailTokenSelect');
|
|
1412
|
+
var msg = document.getElementById('addGmailAccountMsg');
|
|
1413
|
+
var btnOk = document.getElementById('btnConfirmAddGmailAccount');
|
|
1414
|
+
var btnCancel = document.getElementById('btnCancelAddGmailAccount');
|
|
1415
|
+
if (!panel || !sel || !msg || !btnOk || !btnCancel) return;
|
|
1416
|
+
msg.textContent = 'Loading tokens...';
|
|
1417
|
+
msg.className = 'status';
|
|
1418
|
+
panel.style.display = 'block';
|
|
1419
|
+
sel.innerHTML = '';
|
|
1420
|
+
btnOk.disabled = true;
|
|
1421
|
+
|
|
1422
|
+
function closePanel() {
|
|
1423
|
+
panel.style.display = 'none';
|
|
1424
|
+
msg.textContent = '';
|
|
1425
|
+
sel.innerHTML = '';
|
|
1426
|
+
}
|
|
1427
|
+
btnCancel.onclick = closePanel;
|
|
1428
|
+
|
|
1429
|
+
api('/api/gmail/discover-tokens').then(function(tokens) {
|
|
1430
|
+
var available = tokens.filter(function(t) { return !t.in_use && t.token_path; });
|
|
1431
|
+
if (!available.length) {
|
|
1432
|
+
msg.textContent = 'No unused token*.json files found in the app folder. Run: fetch2gmail auth --token token2.json';
|
|
1433
|
+
msg.className = 'error';
|
|
1434
|
+
btnOk.disabled = true;
|
|
1435
|
+
return;
|
|
1436
|
+
}
|
|
1437
|
+
for (var i = 0; i < available.length; i++) {
|
|
1438
|
+
var t = available[i];
|
|
1439
|
+
var opt = document.createElement('option');
|
|
1440
|
+
opt.value = t.token_path;
|
|
1441
|
+
opt.textContent = t.token_path + (t.email ? (' (' + t.email + ')') : '');
|
|
1442
|
+
sel.appendChild(opt);
|
|
1443
|
+
}
|
|
1444
|
+
msg.textContent = 'Select a token and click Add.';
|
|
1445
|
+
msg.className = 'status';
|
|
1446
|
+
btnOk.disabled = false;
|
|
1447
|
+
|
|
1448
|
+
btnOk.onclick = function() {
|
|
1449
|
+
var chosen = sel.value;
|
|
1450
|
+
if (!chosen) return;
|
|
1451
|
+
btnOk.disabled = true;
|
|
1452
|
+
msg.textContent = 'Adding account...';
|
|
1453
|
+
msg.className = 'status';
|
|
1454
|
+
var chosenEmail = '';
|
|
1455
|
+
for (var i = 0; i < available.length; i++) {
|
|
1456
|
+
if (available[i].token_path === chosen) { chosenEmail = available[i].email || ''; break; }
|
|
1457
|
+
}
|
|
1458
|
+
api('/api/config').then(function(c) {
|
|
1459
|
+
var accounts = ensureGmailAccounts(c);
|
|
1460
|
+
accounts.push({
|
|
1461
|
+
use_label: document.getElementById('gmail_use_label').checked,
|
|
1462
|
+
// Default label for new accounts: Gmail email if known; otherwise fall back to global label or ISP Mail.
|
|
1463
|
+
label: (chosenEmail || document.getElementById('gmail_label').value || 'ISP Mail'),
|
|
1464
|
+
credentials_path: (accounts[0] && accounts[0].credentials_path) ? accounts[0].credentials_path : 'credentials.json',
|
|
1465
|
+
token_path: chosen
|
|
1466
|
+
});
|
|
1467
|
+
return put('/api/config', { gmail_accounts: accounts });
|
|
1468
|
+
}).then(function() {
|
|
1469
|
+
msg.textContent = 'Account added.';
|
|
1470
|
+
msg.className = 'ok';
|
|
1471
|
+
setTimeout(function() { closePanel(); loadConfig(); }, 600);
|
|
1472
|
+
}).catch(function(e) {
|
|
1473
|
+
msg.textContent = 'Error: ' + (typeof e.detail === 'string' ? e.detail : (e.detail && e.detail.detail) || e.message || 'Failed');
|
|
1474
|
+
msg.className = 'error';
|
|
1475
|
+
btnOk.disabled = false;
|
|
1476
|
+
});
|
|
1477
|
+
};
|
|
1478
|
+
}).catch(function() {
|
|
1479
|
+
msg.textContent = 'Could not discover tokens.';
|
|
1480
|
+
msg.className = 'error';
|
|
1481
|
+
btnOk.disabled = true;
|
|
1482
|
+
});
|
|
1483
|
+
};
|
|
1484
|
+
}
|
|
1110
1485
|
})();
|
|
1111
1486
|
"""
|
|
1112
1487
|
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|