fetch2gmail 1.0.8__tar.gz → 1.1.0__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.
Files changed (24) hide show
  1. {fetch2gmail-1.0.8/src/fetch2gmail.egg-info → fetch2gmail-1.1.0}/PKG-INFO +4 -1
  2. {fetch2gmail-1.0.8 → fetch2gmail-1.1.0}/README.md +3 -0
  3. {fetch2gmail-1.0.8 → fetch2gmail-1.1.0}/pyproject.toml +1 -1
  4. {fetch2gmail-1.0.8 → fetch2gmail-1.1.0/src/fetch2gmail.egg-info}/PKG-INFO +4 -1
  5. {fetch2gmail-1.0.8 → fetch2gmail-1.1.0}/src/fetcher/gmail_client.py +36 -2
  6. {fetch2gmail-1.0.8 → fetch2gmail-1.1.0}/src/fetcher/imap_client.py +32 -4
  7. {fetch2gmail-1.0.8 → fetch2gmail-1.1.0}/src/fetcher/run.py +194 -1
  8. {fetch2gmail-1.0.8 → fetch2gmail-1.1.0}/src/fetcher/web_ui.py +64 -1
  9. {fetch2gmail-1.0.8 → fetch2gmail-1.1.0}/LICENSE +0 -0
  10. {fetch2gmail-1.0.8 → fetch2gmail-1.1.0}/setup.cfg +0 -0
  11. {fetch2gmail-1.0.8 → fetch2gmail-1.1.0}/src/fetch2gmail.egg-info/SOURCES.txt +0 -0
  12. {fetch2gmail-1.0.8 → fetch2gmail-1.1.0}/src/fetch2gmail.egg-info/dependency_links.txt +0 -0
  13. {fetch2gmail-1.0.8 → fetch2gmail-1.1.0}/src/fetch2gmail.egg-info/entry_points.txt +0 -0
  14. {fetch2gmail-1.0.8 → fetch2gmail-1.1.0}/src/fetch2gmail.egg-info/requires.txt +0 -0
  15. {fetch2gmail-1.0.8 → fetch2gmail-1.1.0}/src/fetch2gmail.egg-info/top_level.txt +0 -0
  16. {fetch2gmail-1.0.8 → fetch2gmail-1.1.0}/src/fetcher/__init__.py +0 -0
  17. {fetch2gmail-1.0.8 → fetch2gmail-1.1.0}/src/fetcher/auth_server.py +0 -0
  18. {fetch2gmail-1.0.8 → fetch2gmail-1.1.0}/src/fetcher/auth_ui.py +0 -0
  19. {fetch2gmail-1.0.8 → fetch2gmail-1.1.0}/src/fetcher/cli.py +0 -0
  20. {fetch2gmail-1.0.8 → fetch2gmail-1.1.0}/src/fetcher/config.py +0 -0
  21. {fetch2gmail-1.0.8 → fetch2gmail-1.1.0}/src/fetcher/env_file.py +0 -0
  22. {fetch2gmail-1.0.8 → fetch2gmail-1.1.0}/src/fetcher/log_buffer.py +0 -0
  23. {fetch2gmail-1.0.8 → fetch2gmail-1.1.0}/src/fetcher/state.py +0 -0
  24. {fetch2gmail-1.0.8 → fetch2gmail-1.1.0}/src/fetcher/ui_auth.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fetch2gmail
3
- Version: 1.0.8
3
+ Version: 1.1.0
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
@@ -268,6 +268,7 @@ You’ll see messages like "Poller: next fetch in Xs", "Poller: running fetch no
268
268
 
269
269
  | Command | Purpose |
270
270
  |--------|---------|
271
+ | `fetch2gmail --version` | Show installed version. |
271
272
  | `fetch2gmail auth` | Get **token.json** on a machine with a browser (opens http://127.0.0.1:8765). |
272
273
  | `fetch2gmail set-ui-password` | Set UI username and password (hash in **.ui_auth**). |
273
274
  | `fetch2gmail install-service` | Generate systemd unit file (one service: web UI + background fetch). Use `--user`, `--dir`, and optionally `--output` or pipe to `sudo tee`. |
@@ -285,6 +286,8 @@ You’ll see messages like "Poller: next fetch in Xs", "Poller: running fetch no
285
286
 
286
287
  ### Updating
287
288
 
289
+ To check your installed version: **`fetch2gmail --version`**.
290
+
288
291
  If you installed with **pipx**, upgrade to the latest release with:
289
292
 
290
293
  ```bash
@@ -237,6 +237,7 @@ You’ll see messages like "Poller: next fetch in Xs", "Poller: running fetch no
237
237
 
238
238
  | Command | Purpose |
239
239
  |--------|---------|
240
+ | `fetch2gmail --version` | Show installed version. |
240
241
  | `fetch2gmail auth` | Get **token.json** on a machine with a browser (opens http://127.0.0.1:8765). |
241
242
  | `fetch2gmail set-ui-password` | Set UI username and password (hash in **.ui_auth**). |
242
243
  | `fetch2gmail install-service` | Generate systemd unit file (one service: web UI + background fetch). Use `--user`, `--dir`, and optionally `--output` or pipe to `sudo tee`. |
@@ -254,6 +255,8 @@ You’ll see messages like "Poller: next fetch in Xs", "Poller: running fetch no
254
255
 
255
256
  ### Updating
256
257
 
258
+ To check your installed version: **`fetch2gmail --version`**.
259
+
257
260
  If you installed with **pipx**, upgrade to the latest release with:
258
261
 
259
262
  ```bash
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "fetch2gmail"
7
- version = "1.0.8"
7
+ version = "1.1.0"
8
8
  description = "Self-hosted email fetcher: IMAP to Gmail API import with idempotent state tracking"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fetch2gmail
3
- Version: 1.0.8
3
+ Version: 1.1.0
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
@@ -268,6 +268,7 @@ You’ll see messages like "Poller: next fetch in Xs", "Poller: running fetch no
268
268
 
269
269
  | Command | Purpose |
270
270
  |--------|---------|
271
+ | `fetch2gmail --version` | Show installed version. |
271
272
  | `fetch2gmail auth` | Get **token.json** on a machine with a browser (opens http://127.0.0.1:8765). |
272
273
  | `fetch2gmail set-ui-password` | Set UI username and password (hash in **.ui_auth**). |
273
274
  | `fetch2gmail install-service` | Generate systemd unit file (one service: web UI + background fetch). Use `--user`, `--dir`, and optionally `--output` or pipe to `sudo tee`. |
@@ -285,6 +286,8 @@ You’ll see messages like "Poller: next fetch in Xs", "Poller: running fetch no
285
286
 
286
287
  ### Updating
287
288
 
289
+ To check your installed version: **`fetch2gmail --version`**.
290
+
288
291
  If you installed with **pipx**, upgrade to the latest release with:
289
292
 
290
293
  ```bash
@@ -94,23 +94,24 @@ def import_message(
94
94
  label_ids: list[str],
95
95
  inbox_label_id: str | None = None,
96
96
  unread_label_id: str | None = None,
97
+ mark_unread: bool = True,
97
98
  ) -> str:
98
99
  """
99
100
  Import a single message using users.messages.import.
100
101
  Preserves original headers and sets internalDate when possible.
102
+ If mark_unread is False (message was read on ISP), the message is imported as read.
101
103
  Returns Gmail message ID.
102
104
  """
103
105
  body = {"raw": base64.urlsafe_b64encode(raw).decode("ascii")}
104
106
  internal_date = _parse_date_from_raw(raw)
105
107
  if internal_date:
106
108
  body["internalDate"] = internal_date
107
- # Gmail API: imported messages do not appear in INBOX unless we pass labelIds. Include INBOX and UNREAD.
108
109
  inbox_id = inbox_label_id or get_inbox_label_id(service, user_id)
109
110
  unread_id = unread_label_id or get_unread_label_id(service, user_id)
110
111
  body["labelIds"] = list(label_ids) if label_ids else []
111
112
  if inbox_id not in body["labelIds"]:
112
113
  body["labelIds"].append(inbox_id)
113
- if unread_id not in body["labelIds"]:
114
+ if mark_unread and unread_id not in body["labelIds"]:
114
115
  body["labelIds"].append(unread_id)
115
116
 
116
117
  msg = _execute_with_backoff(
@@ -122,6 +123,39 @@ def import_message(
122
123
  return msg["id"]
123
124
 
124
125
 
126
+ def _parse_message_id_from_raw(raw: bytes) -> str | None:
127
+ """Extract Message-ID header from raw message. Returns None if missing."""
128
+ try:
129
+ msg = BytesParser(policy=policy.default).parsebytes(raw)
130
+ mid = msg.get("Message-ID")
131
+ return mid.strip() if mid else None
132
+ except Exception: # noqa: BLE001
133
+ return None
134
+
135
+
136
+ def gmail_has_message_with_id(
137
+ service: Any, user_id: str, rfc822_message_id: str
138
+ ) -> bool:
139
+ """
140
+ Return True if Gmail already has a message with the given RFC822 Message-ID
141
+ (checks the account, so we can skip re-importing). Used for copy-all deduplication.
142
+ """
143
+ if not rfc822_message_id or not rfc822_message_id.strip():
144
+ return False
145
+ # Gmail search: rfc822msgid:<value>. Value may contain angle brackets; keep as-is.
146
+ q = f"rfc822msgid:{rfc822_message_id.strip()}"
147
+ try:
148
+ resp = _execute_with_backoff(
149
+ lambda: service.users()
150
+ .messages()
151
+ .list(userId=user_id, q=q, maxResults=1)
152
+ .execute()
153
+ )
154
+ return bool(resp.get("messages"))
155
+ except Exception: # noqa: BLE001
156
+ return False
157
+
158
+
125
159
  def _execute_with_backoff(request_fn, max_retries: int = 5):
126
160
  """Execute Gmail API request with exponential backoff on 5xx and rate limits."""
127
161
  delay = 1.0
@@ -36,6 +36,18 @@ def _extract_rfc822(parts: list | None) -> bytes:
36
36
  return b""
37
37
 
38
38
 
39
+ def _extract_flags_seen(parts: list | None) -> bool:
40
+ """Extract FLAGS from IMAP FETCH response; return True if \\Seen is set."""
41
+ if not parts:
42
+ return False
43
+ first = parts[0]
44
+ if isinstance(first, tuple):
45
+ first = first[0] if first else b""
46
+ if isinstance(first, bytes):
47
+ return b"\\Seen" in first
48
+ return "\\Seen" in str(first)
49
+
50
+
39
51
  @dataclass
40
52
  class FetchedMessage:
41
53
  """A message fetched by UID with its raw bytes and hash for deduplication."""
@@ -44,11 +56,24 @@ class FetchedMessage:
44
56
  uid_validity: int
45
57
  raw: bytes
46
58
  message_hash: str
59
+ is_seen: bool = False
47
60
 
48
61
  @classmethod
49
- def from_raw(cls, uid: int, uid_validity: int, raw: bytes) -> "FetchedMessage":
62
+ def from_raw(
63
+ cls,
64
+ uid: int,
65
+ uid_validity: int,
66
+ raw: bytes,
67
+ is_seen: bool = False,
68
+ ) -> "FetchedMessage":
50
69
  h = hashlib.sha256(raw).hexdigest()
51
- return cls(uid=uid, uid_validity=uid_validity, raw=raw, message_hash=h)
70
+ return cls(
71
+ uid=uid,
72
+ uid_validity=uid_validity,
73
+ raw=raw,
74
+ message_hash=h,
75
+ is_seen=is_seen,
76
+ )
52
77
 
53
78
 
54
79
  def get_uid_validity(
@@ -129,11 +154,14 @@ def fetch_messages(
129
154
  def fetch_one() -> Iterator[FetchedMessage]:
130
155
  try:
131
156
  for uid in uids:
132
- _, parts = conn.uid("FETCH", str(uid), "(RFC822)")
157
+ _, parts = conn.uid("FETCH", str(uid), "(FLAGS RFC822)")
133
158
  raw = _extract_rfc822(parts)
134
159
  if not raw:
135
160
  continue
136
- yield FetchedMessage.from_raw(uid, uid_validity, raw)
161
+ is_seen = _extract_flags_seen(parts)
162
+ yield FetchedMessage.from_raw(
163
+ uid, uid_validity, raw, is_seen=is_seen
164
+ )
137
165
  finally:
138
166
  try:
139
167
  conn.logout()
@@ -10,7 +10,14 @@ import os
10
10
  from typing import Any
11
11
 
12
12
  from .config import load_config
13
- from .gmail_client import get_gmail_service, get_inbox_label_id, get_unread_label_id, import_message
13
+ from .gmail_client import (
14
+ _parse_message_id_from_raw,
15
+ get_gmail_service,
16
+ get_inbox_label_id,
17
+ get_unread_label_id,
18
+ gmail_has_message_with_id,
19
+ import_message,
20
+ )
14
21
  from .imap_client import delete_and_expunge, fetch_messages, get_uid_validity
15
22
  from .state import StateStore
16
23
 
@@ -153,6 +160,7 @@ def run_once(config_path: str | None = None, dry_run: bool = False) -> dict[str,
153
160
  label_ids=label_ids,
154
161
  inbox_label_id=inbox_label_id,
155
162
  unread_label_id=unread_label_id,
163
+ mark_unread=not msg.is_seen,
156
164
  )
157
165
  state.record_import(msg.message_hash, gmail_id, mailbox, uid_validity, msg.uid)
158
166
  state.set_last_processed_uid(mailbox, uid_validity, msg.uid)
@@ -192,6 +200,189 @@ def run_once(config_path: str | None = None, dry_run: bool = False) -> dict[str,
192
200
  }
193
201
 
194
202
 
203
+ def run_copy_all(
204
+ config_path: str | None = None,
205
+ delete_after_import: bool = False,
206
+ dry_run: bool = False,
207
+ ) -> dict[str, Any]:
208
+ """
209
+ Copy all messages from ISP mailbox to Gmail (not just UID > last_processed).
210
+ Preserves read/unread from IMAP \\Seen. Skips messages already in Gmail (by hash or Message-ID).
211
+ delete_after_import: if True, delete from ISP after successful import (or after skip when already in Gmail).
212
+ Returns same shape as run_once.
213
+ """
214
+ if config_path is None:
215
+ from .config import get_config_path
216
+ config_path = str(get_config_path())
217
+ cfg = load_config(config_path)
218
+ imap_cfg = cfg["imap"]
219
+ gmail_cfg = cfg["gmail"]
220
+ state_cfg = cfg.get("state", {})
221
+ db_path = state_cfg.get("db_path", "state.db")
222
+ mailbox = imap_cfg.get("mailbox", "INBOX")
223
+ use_label = gmail_cfg.get("use_label") if "use_label" in gmail_cfg else bool((gmail_cfg.get("label") or "").strip())
224
+ label_name = (gmail_cfg.get("label") or "ISP Mail").strip() if use_label else None
225
+
226
+ state = StateStore(db_path)
227
+ state.connect()
228
+
229
+ try:
230
+ uid_validity = get_uid_validity(
231
+ host=imap_cfg["host"],
232
+ port=int(imap_cfg.get("port", 993)),
233
+ username=imap_cfg["username"],
234
+ password=imap_cfg["password"],
235
+ mailbox=mailbox,
236
+ use_ssl=imap_cfg.get("use_ssl", True),
237
+ )
238
+ except Exception as e:
239
+ logger.exception("IMAP connect (UIDVALIDITY) failed: %s", e)
240
+ return {"error": str(e), "imported": 0, "skipped_duplicate": 0, "deleted": 0}
241
+
242
+ try:
243
+ uid_validity, messages_iter = fetch_messages(
244
+ host=imap_cfg["host"],
245
+ port=int(imap_cfg.get("port", 993)),
246
+ username=imap_cfg["username"],
247
+ password=imap_cfg["password"],
248
+ mailbox=mailbox,
249
+ use_ssl=imap_cfg.get("use_ssl", True),
250
+ last_processed_uid=None,
251
+ )
252
+ except Exception as e:
253
+ logger.exception("IMAP fetch failed: %s", e)
254
+ return {"error": str(e), "imported": 0, "skipped_duplicate": 0, "deleted": 0}
255
+
256
+ imported = 0
257
+ skipped_duplicate = 0
258
+ deleted = 0
259
+ service = None
260
+ label_id = None
261
+ inbox_label_id = None
262
+ unread_label_id = None
263
+
264
+ if not dry_run:
265
+ try:
266
+ service = get_gmail_service(
267
+ gmail_cfg["credentials_path"],
268
+ gmail_cfg["token_path"],
269
+ )
270
+ inbox_label_id = get_inbox_label_id(service, USER_ID)
271
+ unread_label_id = get_unread_label_id(service, USER_ID)
272
+ label_id = _ensure_label(service, label_name) if label_name else None
273
+ except Exception as e:
274
+ logger.exception("Gmail API init failed: %s", e)
275
+ return {"error": str(e), "imported": 0, "skipped_duplicate": 0, "deleted": 0}
276
+
277
+ for msg in messages_iter:
278
+ if state.seen_hash(msg.message_hash):
279
+ logger.debug("Copy-all: skipping duplicate (hash): uid=%s", msg.uid)
280
+ skipped_duplicate += 1
281
+ if not dry_run and delete_after_import:
282
+ try:
283
+ delete_and_expunge(
284
+ imap_cfg["host"],
285
+ int(imap_cfg.get("port", 993)),
286
+ imap_cfg["username"],
287
+ imap_cfg["password"],
288
+ mailbox,
289
+ msg.uid,
290
+ imap_cfg.get("use_ssl", True),
291
+ )
292
+ state.set_last_processed_uid(mailbox, uid_validity, msg.uid)
293
+ deleted += 1
294
+ except Exception as e:
295
+ logger.warning("Delete (duplicate) failed for uid=%s: %s", msg.uid, e)
296
+ continue
297
+
298
+ if not dry_run:
299
+ message_id_header = _parse_message_id_from_raw(msg.raw)
300
+ if message_id_header and gmail_has_message_with_id(
301
+ service, USER_ID, message_id_header
302
+ ):
303
+ logger.debug(
304
+ "Copy-all: skipping (already in Gmail by Message-ID): uid=%s",
305
+ msg.uid,
306
+ )
307
+ skipped_duplicate += 1
308
+ if delete_after_import:
309
+ try:
310
+ delete_and_expunge(
311
+ imap_cfg["host"],
312
+ int(imap_cfg.get("port", 993)),
313
+ imap_cfg["username"],
314
+ imap_cfg["password"],
315
+ mailbox,
316
+ msg.uid,
317
+ imap_cfg.get("use_ssl", True),
318
+ )
319
+ state.set_last_processed_uid(mailbox, uid_validity, msg.uid)
320
+ deleted += 1
321
+ except Exception as e:
322
+ logger.warning(
323
+ "Delete (already in Gmail) failed for uid=%s: %s",
324
+ msg.uid,
325
+ e,
326
+ )
327
+ continue
328
+
329
+ if dry_run:
330
+ logger.info(
331
+ "[DRY-RUN] Copy-all would import uid=%s (hash=%s)",
332
+ msg.uid,
333
+ msg.message_hash[:16],
334
+ )
335
+ imported += 1
336
+ continue
337
+
338
+ try:
339
+ label_ids = [label_id] if label_id else []
340
+ gmail_id = import_message(
341
+ service,
342
+ USER_ID,
343
+ msg.raw,
344
+ label_ids=label_ids,
345
+ inbox_label_id=inbox_label_id,
346
+ unread_label_id=unread_label_id,
347
+ mark_unread=not msg.is_seen,
348
+ )
349
+ state.record_import(msg.message_hash, gmail_id, mailbox, uid_validity, msg.uid)
350
+ state.set_last_processed_uid(mailbox, uid_validity, msg.uid)
351
+ imported += 1
352
+ logger.info("Copy-all imported uid=%s -> Gmail id=%s", msg.uid, gmail_id)
353
+ except Exception as e:
354
+ logger.exception("Gmail import failed for uid=%s: %s", msg.uid, e)
355
+ continue
356
+
357
+ if delete_after_import:
358
+ try:
359
+ delete_and_expunge(
360
+ imap_cfg["host"],
361
+ int(imap_cfg.get("port", 993)),
362
+ imap_cfg["username"],
363
+ imap_cfg["password"],
364
+ mailbox,
365
+ msg.uid,
366
+ imap_cfg.get("use_ssl", True),
367
+ )
368
+ deleted += 1
369
+ except Exception as e:
370
+ logger.exception(
371
+ "Delete failed for uid=%s (already in Gmail): %s", msg.uid, e
372
+ )
373
+ deleted += 1
374
+
375
+ last_fetch = state.get_last_fetch_time(mailbox, uid_validity)
376
+ state.close()
377
+ return {
378
+ "error": None,
379
+ "imported": imported,
380
+ "skipped_duplicate": skipped_duplicate,
381
+ "deleted": deleted,
382
+ "last_fetch_time": last_fetch,
383
+ }
384
+
385
+
195
386
  def setup_logging() -> None:
196
387
  """Configure logging to systemd journal (stdout) and structured format."""
197
388
  import sys
@@ -202,3 +393,5 @@ def setup_logging() -> None:
202
393
  datefmt="%Y-%m-%dT%H:%M:%S",
203
394
  stream=sys.stdout,
204
395
  )
396
+ # Suppress noisy googleapiclient message about file_cache and oauth2client
397
+ logging.getLogger("googleapiclient.discovery_cache").setLevel(logging.WARNING)
@@ -27,7 +27,7 @@ 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
29
29
  from .log_buffer import get_recent_logs, install_log_buffer
30
- from .run import run_once, setup_logging
30
+ from .run import run_once, run_copy_all, setup_logging
31
31
  from .ui_auth import create_ui_auth, load_ui_auth, verify_ui_auth
32
32
 
33
33
  logger = logging.getLogger(__name__)
@@ -626,6 +626,11 @@ def api_config_update(request: Request, update: ConfigUpdate) -> dict[str, str]:
626
626
  return {"status": "ok"}
627
627
 
628
628
 
629
+ class CopyAllBody(BaseModel):
630
+ """Body for copy-all: copy every message from ISP to Gmail (with optional delete after)."""
631
+ delete_after: bool = False
632
+
633
+
629
634
  @app.post("/api/fetch")
630
635
  def api_fetch(request: Request, dry_run: bool = False) -> dict[str, Any]:
631
636
  """Trigger one fetch cycle. Optionally dry_run."""
@@ -642,6 +647,26 @@ def api_fetch(request: Request, dry_run: bool = False) -> dict[str, Any]:
642
647
  raise HTTPException(status_code=400, detail=str(e))
643
648
 
644
649
 
650
+ @app.post("/api/fetch/copy-all")
651
+ def api_fetch_copy_all(request: Request, body: CopyAllBody) -> dict[str, Any]:
652
+ """Copy all emails from ISP mailbox to Gmail (not just new). Skips already in Gmail. Optionally delete from ISP after."""
653
+ if not _require_auth(request):
654
+ raise HTTPException(status_code=401, detail="Not authenticated")
655
+ setup_logging()
656
+ install_log_buffer()
657
+ try:
658
+ result = run_copy_all(
659
+ config_path=str(_get_config_path()),
660
+ delete_after_import=body.delete_after,
661
+ dry_run=False,
662
+ )
663
+ return result
664
+ except FileNotFoundError as e:
665
+ raise HTTPException(status_code=404, detail=str(e))
666
+ except ValueError as e:
667
+ raise HTTPException(status_code=400, detail=str(e))
668
+
669
+
645
670
  @app.get("/api/logs")
646
671
  def api_logs(request: Request, n: int = 100) -> dict[str, list[str]]:
647
672
  """Return recent log lines (no credentials)."""
@@ -752,6 +777,13 @@ _HTML_PAGE = """
752
777
  <p id="status">Loading...</p>
753
778
  <button type="button" id="btnFetch">Run fetch now</button>
754
779
  <button type="button" id="btnDryRun">Dry run (no import/delete)</button>
780
+ <div style="margin-top:1rem;">
781
+ <h3 style="font-size:1rem; margin-bottom:0.5rem;">Copy all emails from ISP to Gmail</h3>
782
+ <p class="hint" style="font-size:0.85rem; color:#666; margin:0.25rem 0;">Fetches every message in the mailbox (not just new). Read/unread is preserved. Skips messages already in Gmail.</p>
783
+ <label style="display:inline-block; margin-top:0.5rem;"><input type="checkbox" id="copy_all_delete_after"> Delete from ISP after copying</label>
784
+ <button type="button" id="btnCopyAll" style="margin-left:0.5rem;">Copy all now</button>
785
+ <p id="copyAllMsg" class="status" style="margin-top:0.5rem;"></p>
786
+ </div>
755
787
  </section>
756
788
 
757
789
  <section>
@@ -973,6 +1005,37 @@ _APP_JS = r"""
973
1005
  loadLogs();
974
1006
  });
975
1007
  };
1008
+ document.getElementById('btnCopyAll').onclick = function() {
1009
+ var msgEl = document.getElementById('copyAllMsg');
1010
+ var deleteAfter = document.getElementById('copy_all_delete_after').checked;
1011
+ msgEl.textContent = 'Copying all...';
1012
+ msgEl.className = 'status';
1013
+ document.getElementById('btnCopyAll').disabled = true;
1014
+ fetch('/api/fetch/copy-all', {
1015
+ method: 'POST',
1016
+ headers: { 'Content-Type': 'application/json' },
1017
+ body: JSON.stringify({ delete_after: deleteAfter })
1018
+ }).then(function(r) {
1019
+ if (r.status === 401) { location.href = '/'; return; }
1020
+ return r.json();
1021
+ }).then(function(j) {
1022
+ if (j.error) {
1023
+ msgEl.textContent = 'Error: ' + j.error;
1024
+ msgEl.className = 'error';
1025
+ } else {
1026
+ msgEl.textContent = 'Imported: ' + j.imported + ', Skipped (already in Gmail): ' + j.skipped_duplicate + ', Deleted from ISP: ' + j.deleted + '.';
1027
+ msgEl.className = 'ok';
1028
+ }
1029
+ loadStatus();
1030
+ loadLogs();
1031
+ }).catch(function(e) {
1032
+ msgEl.textContent = 'Error: ' + ((e.detail && e.detail.detail) ? e.detail.detail : e.message || 'request failed');
1033
+ msgEl.className = 'error';
1034
+ loadLogs();
1035
+ }).then(function() {
1036
+ document.getElementById('btnCopyAll').disabled = false;
1037
+ });
1038
+ };
976
1039
  document.getElementById('gmail_use_label').onchange = function() {
977
1040
  document.getElementById('gmail_label_row').style.display = this.checked ? 'block' : 'none';
978
1041
  };
File without changes
File without changes