sideora 0.0.1-alpha.0 → 0.1.0-alpha.2
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.
- package/LICENSE.md +9 -0
- package/README.md +57 -6
- package/assets/sounds/freesound_community-mail-40275.mp3 +0 -0
- package/assets/sounds/mixkit-clear-announce-tones-2861.wav +0 -0
- package/assets/sounds/mixkit-happy-bells-notification-937.wav +0 -0
- package/assets/sounds/mixkit-musical-alert-notification-2309.wav +0 -0
- package/assets/sounds/nice-chime.mp3 +0 -0
- package/bin/sideora.js +2430 -12
- package/extension/dist/assets/background.ts-NW8YqAlO.js +1 -0
- package/extension/dist/assets/fillCode-Ci8IkBvY.js +1 -0
- package/extension/dist/assets/index.html-DrrPha1M.js +2 -0
- package/extension/dist/assets/modulepreload-polyfill-DcjICKwh.js +1 -0
- package/extension/dist/assets/shell-82MNMljp.css +1 -0
- package/extension/dist/assets/shell-QYBN1bx1.js +1 -0
- package/extension/dist/icons/icon-128.png +0 -0
- package/extension/dist/icons/icon-16.png +0 -0
- package/extension/dist/icons/icon-32.png +0 -0
- package/extension/dist/icons/icon-48.png +0 -0
- package/extension/dist/manifest.json +40 -0
- package/extension/dist/service-worker-loader.js +1 -0
- package/extension/dist/src/newtab/index.html +14 -0
- package/extension/dist/src/panel/index.html +15 -0
- package/extension/dist-web/assets/abnfDiagram-WEYOIA3C-CoXOc872.js +1 -0
- package/extension/dist-web/assets/apple-touch-icon-DSgRQASq.png +0 -0
- package/extension/dist-web/assets/architecture-WOLXFQ4H-BkJ4AerO.js +1 -0
- package/extension/dist-web/assets/architectureDiagram-ZHVYKT53-aPkSDlxA.js +36 -0
- package/extension/dist-web/assets/blockDiagram-RJAE7QA3-CH1G4NBZ.js +140 -0
- package/extension/dist-web/assets/c4Diagram-XDPPPE54-Baum1zDu.js +38 -0
- package/extension/dist-web/assets/channel-PsQg-mnK.js +1 -0
- package/extension/dist-web/assets/chunk-2E7WHVMD-CKvLrWRa.js +88 -0
- package/extension/dist-web/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
- package/extension/dist-web/assets/chunk-4EMNKR2T-6fjnroCZ.js +1 -0
- package/extension/dist-web/assets/chunk-55XCU76K-Ygs3sNpi.js +1 -0
- package/extension/dist-web/assets/chunk-5VM5RSS4-ZNzvKenW.js +15 -0
- package/extension/dist-web/assets/chunk-7S6XSTFO-iX5xYzfP.js +2 -0
- package/extension/dist-web/assets/chunk-AQDTSKZB-D9zwhFI8.js +72 -0
- package/extension/dist-web/assets/chunk-DSNLSHJZ-siGS-4qu.js +129 -0
- package/extension/dist-web/assets/chunk-DUW6YSOI-Dgx8z5s3.js +1 -0
- package/extension/dist-web/assets/chunk-HAGFOTED-_3dtnWXn.js +62 -0
- package/extension/dist-web/assets/chunk-HNE4Q36P-BPzRHi72.js +1 -0
- package/extension/dist-web/assets/chunk-J5ZVWO5B-oDCd-gWO.js +1 -0
- package/extension/dist-web/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
- package/extension/dist-web/assets/chunk-NGNAAXSQ-DI_UYJZ4.js +136 -0
- package/extension/dist-web/assets/chunk-NQOKRVIF-AXbmOBjs.js +213 -0
- package/extension/dist-web/assets/chunk-UHW7PFBP-B3xrZ8sD.js +1 -0
- package/extension/dist-web/assets/chunk-VQ5W62QI-D_k7Pa6b.js +1 -0
- package/extension/dist-web/assets/chunk-WQQL4CDK-BBIrWwoZ.js +10 -0
- package/extension/dist-web/assets/chunk-XXDRQBXY-i7MKP1NY.js +1 -0
- package/extension/dist-web/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
- package/extension/dist-web/assets/chunk-YZO67HFG-Z7qp5QAI.js +1 -0
- package/extension/dist-web/assets/chunk-ZAUX2LTX-CSt3c0Rb.js +1 -0
- package/extension/dist-web/assets/chunk-ZCHMQSOR-g8XRABGK.js +2 -0
- package/extension/dist-web/assets/classDiagram-v2-4MYWR3UA-BL706wzc.js +217 -0
- package/extension/dist-web/assets/cose-bilkent-JH36ORCC-C6J2IoHg.js +1 -0
- package/extension/dist-web/assets/cynefin-EF2NZ3EQ-DLhQOiAy.js +1 -0
- package/extension/dist-web/assets/cynefinDiagram-WF24UDRP-Cv9Lx6_l.js +62 -0
- package/extension/dist-web/assets/cytoscape.esm-nTrd5EVq.js +321 -0
- package/extension/dist-web/assets/d3-scale-CElPUUud.js +1 -0
- package/extension/dist-web/assets/d3-selection-COWvaQNI.js +1 -0
- package/extension/dist-web/assets/dagre-NK4GIZVX-ngM-w2EC.js +4 -0
- package/extension/dist-web/assets/diagram-CBK3MWTC-kp8sayNG.js +24 -0
- package/extension/dist-web/assets/diagram-I5XIIV2D-BZ_Dgs6K.js +24 -0
- package/extension/dist-web/assets/diagram-ODIL2UCW-DWhUyArG.js +30 -0
- package/extension/dist-web/assets/diagram-PFBEJUXE-CBAdEK7l.js +3 -0
- package/extension/dist-web/assets/diagram-RJA3I4VV-kOdIr_3K.js +41 -0
- package/extension/dist-web/assets/diagram-TYUNFSNR-BrWGa0x5.js +200 -0
- package/extension/dist-web/assets/dist-DdXDFcej.js +1 -0
- package/extension/dist-web/assets/docx-preview-D1zbEiLy.js +20 -0
- package/extension/dist-web/assets/earth-Ce3xs8Cb.webp +0 -0
- package/extension/dist-web/assets/ebnfDiagram-V4P3TTPT-0r3weWmj.js +1 -0
- package/extension/dist-web/assets/elk-QONTBCTQ-D3oElRZ3.js +27 -0
- package/extension/dist-web/assets/erDiagram-KYQIGQAA-B9oU7_j_.js +99 -0
- package/extension/dist-web/assets/eventmodeling-K75KTNOO-CMKgc1nP.js +1 -0
- package/extension/dist-web/assets/favicon-D_X6tUVf.svg +5 -0
- package/extension/dist-web/assets/flowDiagram-IUGLLWBU-yRwks0Mw.js +1 -0
- package/extension/dist-web/assets/ganttDiagram-R7GPNTJY-cJqD1qwQ.js +292 -0
- package/extension/dist-web/assets/gitGraph-VSP46ZUC-CuBQqkbr.js +1 -0
- package/extension/dist-web/assets/gitGraphDiagram-PDYL7XHY-D7bHnQXC.js +106 -0
- package/extension/dist-web/assets/graphlib-DS17s2tU.js +1 -0
- package/extension/dist-web/assets/home-CV7-8Trs.js +1 -0
- package/extension/dist-web/assets/index-CQvw7Wy_.js +7 -0
- package/extension/dist-web/assets/index-CVKnZ21i.css +1 -0
- package/extension/dist-web/assets/info-OHQRW6UA-B8kyzV4O.js +1 -0
- package/extension/dist-web/assets/infoDiagram-MVDRKAX5-CEm6lezX.js +2 -0
- package/extension/dist-web/assets/ishikawaDiagram-HPEHV2GE-Ce3uv2wr.js +70 -0
- package/extension/dist-web/assets/journeyDiagram-BOSHW7O7-QgdahHCP.js +139 -0
- package/extension/dist-web/assets/jszip.min-3XXygzvy.js +2 -0
- package/extension/dist-web/assets/kanban-definition-FNSA4HC5-DPuTtWgR.js +89 -0
- package/extension/dist-web/assets/katex-MEuSR36T.js +257 -0
- package/extension/dist-web/assets/mermaid-parser.core-h7U7YGn_.js +7 -0
- package/extension/dist-web/assets/mermaid.core-DkGhophj.js +44 -0
- package/extension/dist-web/assets/mindmap-definition-6OY57UG3-D7VQxbda.js +98 -0
- package/extension/dist-web/assets/mount-CBzzf6KQ.js +195 -0
- package/extension/dist-web/assets/mount-DtvYnQXt.css +1 -0
- package/extension/dist-web/assets/officeparser.browser.slim-kEjhTrQ1.js +1989 -0
- package/extension/dist-web/assets/packet-JDAUHWVQ-oafHgw6X.js +1 -0
- package/extension/dist-web/assets/pegDiagram-ECIUJNBX-C3zo1naj.js +1 -0
- package/extension/dist-web/assets/peoria-B5TBlKDG.jpg +0 -0
- package/extension/dist-web/assets/peoria-thumb-CN8upAdZ.jpg +0 -0
- package/extension/dist-web/assets/pie-XZMESJXO-DXzeBQqF.js +1 -0
- package/extension/dist-web/assets/pieDiagram-GNMPY74T-S5NzPthl.js +39 -0
- package/extension/dist-web/assets/quadrantDiagram-D57K4MC3-C9glHQmk.js +7 -0
- package/extension/dist-web/assets/radar-ABXABTNO-CWTNqtbu.js +1 -0
- package/extension/dist-web/assets/railroad-I3PHUGI6-BTpD5_Bu.js +1 -0
- package/extension/dist-web/assets/railroad-abnf-LNEFI6M7-bWyxoXQG.js +1 -0
- package/extension/dist-web/assets/railroad-ebnf-DWYD2UWJ-ri5733DQ.js +1 -0
- package/extension/dist-web/assets/railroad-peg-JR7BVNR7-CmGfTubP.js +1 -0
- package/extension/dist-web/assets/railroadDiagram-Y72NRBL7-DTfe6Dh1.js +1 -0
- package/extension/dist-web/assets/requirementDiagram-EQYSW5RA-DQDzcS3L.js +84 -0
- package/extension/dist-web/assets/rolldown-runtime-COiEfhsA.js +1 -0
- package/extension/dist-web/assets/rough.esm-Dy-Kn_BL.js +1 -0
- package/extension/dist-web/assets/sankeyDiagram-SY24JHO5-DyMKWxdB.js +40 -0
- package/extension/dist-web/assets/sequenceDiagram-BLEHNHQU-dIkB1mCn.js +169 -0
- package/extension/dist-web/assets/sizeCapture-INFHLROL-3uHXrFqA.js +1 -0
- package/extension/dist-web/assets/stateDiagram-v2-A6IESKWZ-Bj_vxEVF.js +291 -0
- package/extension/dist-web/assets/swimlanes-B3ENRKFQ-BSkWEwHR.js +1 -0
- package/extension/dist-web/assets/swimlanesDiagram-AYQRV4AK-BTzSDlSM.js +8 -0
- package/extension/dist-web/assets/timeline-definition-JXYKGLGB-TwfWS0pw.js +120 -0
- package/extension/dist-web/assets/treeView-D4JQ5SDB-BzA_8YYb.js +1 -0
- package/extension/dist-web/assets/treemap-SAJKECNS-BI9d6--2.js +1 -0
- package/extension/dist-web/assets/usecaseDiagram-WPOLBNNX-BOVbAUPk.js +328 -0
- package/extension/dist-web/assets/vennDiagram-Q3Y3IDCW-X2kYAWaj.js +34 -0
- package/extension/dist-web/assets/wardley-7MLQ67FV-CItxqJ8G.js +1 -0
- package/extension/dist-web/assets/wardleyDiagram-IVAIDKWA-BnUXvKD_.js +78 -0
- package/extension/dist-web/assets/xychartDiagram-4URNHDU4-ysvBXvyE.js +7 -0
- package/extension/dist-web/icon-192.png +0 -0
- package/extension/dist-web/icon-512.png +0 -0
- package/extension/dist-web/index.html +25 -0
- package/extension/dist-web/manifest.webmanifest +14 -0
- package/package.json +64 -12
- package/plugin/.claude-plugin/icon.png +0 -0
- package/plugin/.claude-plugin/plugin.json +6 -0
- package/plugin/.mcp.json +8 -0
- package/plugin/README.md +72 -0
- package/plugin/mcp-launcher.mjs +48 -0
- package/src/account-probe.js +45 -0
- package/src/accounts.js +687 -0
- package/src/ai.js +269 -0
- package/src/assistant-runs.js +32 -0
- package/src/attached-mail.js +76 -0
- package/src/auth-gate.js +70 -0
- package/src/backup-cli.js +158 -0
- package/src/backup.js +329 -0
- package/src/bimi.js +233 -0
- package/src/bridge.js +101 -0
- package/src/calendar-alerts.js +56 -0
- package/src/chats.js +27 -0
- package/src/compose-editor.js +58 -0
- package/src/config.js +420 -0
- package/src/connections.d.ts +24 -0
- package/src/connections.js +37 -0
- package/src/core/agent.js +92 -0
- package/src/core/assistant.d.ts +13 -0
- package/src/core/assistant.js +790 -0
- package/src/core/chats.js +323 -0
- package/src/core/markdown.d.ts +8 -0
- package/src/core/markdown.js +239 -0
- package/src/core/notes.js +445 -0
- package/src/core/otp.js +152 -0
- package/src/core/rules.js +196 -0
- package/src/core/runs.d.ts +9 -0
- package/src/core/runs.js +211 -0
- package/src/core/thread.js +526 -0
- package/src/core/write.js +247 -0
- package/src/core-db.js +131 -0
- package/src/core.js +174 -0
- package/src/credentials.js +320 -0
- package/src/daemon.js +564 -0
- package/src/events.js +213 -0
- package/src/extension-id.d.ts +2 -0
- package/src/extension-id.js +5 -0
- package/src/file-lock.js +27 -0
- package/src/files-index.js +154 -0
- package/src/google-contacts.js +315 -0
- package/src/google-signin.js +306 -0
- package/src/host/assistant-html.js +44 -0
- package/src/host/chats-files.js +137 -0
- package/src/host/file-prep.js +122 -0
- package/src/host/notes-files.js +158 -0
- package/src/host/office-text.js +224 -0
- package/src/host/office-worker.js +8 -0
- package/src/host/rules-file.js +20 -0
- package/src/host/secrets-file.js +91 -0
- package/src/host/systemd.js +90 -0
- package/src/hub.js +245 -0
- package/src/identity.js +316 -0
- package/src/labels.js +5 -0
- package/src/mail-port.d.ts +79 -0
- package/src/mail-port.js +148 -0
- package/src/mcp-server.js +747 -0
- package/src/microsoft-app.js +20 -0
- package/src/microsoft-signin.js +194 -0
- package/src/migrate.js +327 -0
- package/src/notes-html.js +450 -0
- package/src/notes.js +19 -0
- package/src/notify.js +105 -0
- package/src/onepassword.js +223 -0
- package/src/op-registry.d.ts +14 -0
- package/src/op-registry.js +150 -0
- package/src/ops.js +1251 -0
- package/src/otp.js +6 -0
- package/src/panel-ops.js +273 -0
- package/src/pictures.js +735 -0
- package/src/postinstall.js +25 -0
- package/src/relay-passkey.js +122 -0
- package/src/relay-request.js +155 -0
- package/src/relay-seal.js +56 -0
- package/src/relay-settings.js +139 -0
- package/src/relay.js +876 -0
- package/src/render.js +82 -0
- package/src/rules-store.js +8 -0
- package/src/safe-fetch.js +215 -0
- package/src/sender-auth.js +270 -0
- package/src/site-match.js +77 -0
- package/src/tui-agenda.js +266 -0
- package/src/tui.js +670 -0
- package/src/vmc.js +376 -0
- package/src/wake.js +96 -0
- package/src/web-access.js +185 -0
- package/src/web-server.js +241 -0
- package/src/web-service.js +152 -0
package/src/daemon.js
ADDED
|
@@ -0,0 +1,564 @@
|
|
|
1
|
+
// The watch loop: poll every account's inbox, match rules, alert and wake
|
|
2
|
+
// agents. One poll ticker and one push stream (EWS streaming notifications
|
|
3
|
+
// or IMAP IDLE) per account; the interval stays as a safety net for both.
|
|
4
|
+
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { ruleMatches, accountOk, inQuietHours } from 'mailcore';
|
|
7
|
+
import { core, cache, withAuthRetry, isAuthError, createClient, splitId, idParts, keepConnections } from './core.js';
|
|
8
|
+
import { createAuthGate } from './auth-gate.js';
|
|
9
|
+
import { loadConfig, loadRulesDoc, loadState, saveState, ensureDirs, accountNames, DIGEST_DIR, calendarProvider, hasMail, credentialsOf, isOnePassword, passwordSource, childEnv } from './config.js';
|
|
10
|
+
import { startEventServer } from './events.js';
|
|
11
|
+
import { playSound, notifyMac } from './notify.js';
|
|
12
|
+
import { wakeAgent } from './wake.js';
|
|
13
|
+
import { startCalendarWatch } from './calendar-alerts.js';
|
|
14
|
+
import { pictures } from './pictures.js';
|
|
15
|
+
import { startHub } from './hub.js';
|
|
16
|
+
|
|
17
|
+
let bus = { emit: () => {} };
|
|
18
|
+
|
|
19
|
+
const MAX_ALERTS_PER_POLL = 3;
|
|
20
|
+
/** How long a check on a kept connection may take before the connection is given up for dead. */
|
|
21
|
+
const KEPT_DEADLINE_MS = 20_000;
|
|
22
|
+
/** And how long bringing the cache in step may take after it (differences are small; a server can still be slow). */
|
|
23
|
+
const STEP_DEADLINE_MS = 30_000;
|
|
24
|
+
const RECONCILE_MINUTES = 15;
|
|
25
|
+
/** IMAP: how often the cache is settled by a whole listing, on top of being kept in step by differences. */
|
|
26
|
+
const WHOLE_HOURS = 24;
|
|
27
|
+
|
|
28
|
+
export async function runDaemon() {
|
|
29
|
+
ensureDirs();
|
|
30
|
+
const config = loadConfig();
|
|
31
|
+
const names = accountNames(config);
|
|
32
|
+
// (no mail: the hub runs all the same: notes, chats, the assistant and the rest of what is not mail)
|
|
33
|
+
log(names.length ? `watching ${names.map((n) => `${n} (${config.accounts[n].provider}: ${describe(config.accounts[n])})`).join(', ')} every ${config.pollSeconds}s` : 'no mail account: the hub alone (sideora setup adds one)');
|
|
34
|
+
bus = startEventServer(log);
|
|
35
|
+
// the hub: the panel's ops answered here for the bridge (src/hub.js), so that one process writes what is kept
|
|
36
|
+
const { runOp } = await import('./panel-ops.js');
|
|
37
|
+
keepConnections(); // (as the bridge did: the IMAP connections a person's clicks use are kept between uses)
|
|
38
|
+
const hub = startHub({ run: (op, args, ctx) => runOp(op, args, undefined, ctx), log });
|
|
39
|
+
// leave no dead socket file behind (foreground Ctrl-C, launchd SIGTERM)
|
|
40
|
+
for (const sig of ['SIGINT', 'SIGTERM']) {
|
|
41
|
+
process.on(sig, () => { try { bus.close(); } catch {} try { hub.close(); } catch {} process.exit(0); });
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const cached = cache.cachedAccounts(config);
|
|
45
|
+
if (cached.length) {
|
|
46
|
+
try {
|
|
47
|
+
cache.openCache({ create: true });
|
|
48
|
+
const removed = cache.prune(config);
|
|
49
|
+
log(`cache: ${cached.join(', ')} → ${cache.CACHE_PATH}${removed ? ` (pruned ${removed} old rows)` : ''}`);
|
|
50
|
+
setInterval(() => { try { cache.prune(loadConfig()); } catch (e) { log('cache prune failed: ' + e.message); } }, 6 * 3600e3);
|
|
51
|
+
} catch (e) {
|
|
52
|
+
log('cache disabled: ' + e.message);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
for (const name of names) watchAccount(config, config.accounts[name]);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function describe(acct) {
|
|
60
|
+
if (acct.provider === 'imap') return acct.imap?.host;
|
|
61
|
+
if (acct.provider === 'jmap') { try { return new URL(acct.jmap?.session).hostname; } catch { return 'jmap'; } }
|
|
62
|
+
if (acct.provider === 'caldav') return acct.server || acct.service;
|
|
63
|
+
if (acct.provider === 'google') return 'calendar.google.com';
|
|
64
|
+
return acct.host;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function watchAccount(config, acct) {
|
|
68
|
+
const name = acct.name;
|
|
69
|
+
const mail = hasMail(acct);
|
|
70
|
+
let failures = 0;
|
|
71
|
+
let ticking = false;
|
|
72
|
+
let again = false; // a push arrived mid-poll: run once more right after
|
|
73
|
+
// a rejected sign-in pauses poll, push and calendar for this account (see auth-gate.js)
|
|
74
|
+
const authGate = createAuthGate(name, {
|
|
75
|
+
log,
|
|
76
|
+
hint: isOnePassword(credentialsOf(acct)) ? `Update the password in ${passwordSource(acct)}.` : credentialsOf(acct).source === 'env' ? `Update ${passwordSource(acct)}.` : credentialsOf(acct).source === 'microsoft' ? 'Sign in to Microsoft again (Settings, Accounts, add it again).' : 'Update the stored password (sideora setup).'
|
|
77
|
+
});
|
|
78
|
+
// IMAP: one signed-in connection is kept for the checks, instead of a sign-in for each (a second on Gmail,
|
|
79
|
+
// every time). When it fails for any reason (dropped, a sign-in gone stale), the check is done the usual way,
|
|
80
|
+
// which knows how to sign in again, and a new connection is kept from the next one on.
|
|
81
|
+
let kept = null;
|
|
82
|
+
let newFrom = null; // IMAP, when asking found new mail: the first message number that is new (only those are fetched)
|
|
83
|
+
// let go without waiting for the server's goodbye: a connection given up for dead would not answer it
|
|
84
|
+
const letGo = async () => { const c = kept; kept = null; c?.close().catch(() => {}); };
|
|
85
|
+
const usual = () => withAuthRetry((client) => poll(client, name), () => log(`[${name}] sign-in rejected — reading the password again (${passwordSource(acct)})…`), name);
|
|
86
|
+
const check = async () => {
|
|
87
|
+
if (acct.provider !== 'imap') return usual();
|
|
88
|
+
try {
|
|
89
|
+
if (!kept) { kept = await createClient(name); kept.backend.asWatcher?.(); }
|
|
90
|
+
kept.backend.lookAgain?.();
|
|
91
|
+
const from = newFrom;
|
|
92
|
+
newFrom = null;
|
|
93
|
+
// A kept connection can go dead without saying so (a server that stops answering and never hangs up), and a
|
|
94
|
+
// check on it would then wait for minutes with every other check queued behind it. So it has a deadline;
|
|
95
|
+
// past it the connection is let go, which ends whatever was waiting on it, and the check is done the usual way.
|
|
96
|
+
const within = async (work, ms) => {
|
|
97
|
+
work.catch(() => {}); // when the deadline wins, its own failure is expected
|
|
98
|
+
let alarm;
|
|
99
|
+
const late = new Promise((_, reject) => { alarm = setTimeout(() => reject(new Error(`no answer in ${ms / 1000}s`)), ms); });
|
|
100
|
+
try { return await Promise.race([work, late]); } finally { clearTimeout(alarm); }
|
|
101
|
+
};
|
|
102
|
+
const found = await within(poll(kept, name, { newFrom: from }), KEPT_DEADLINE_MS);
|
|
103
|
+
// The cache is then brought in step, on its own time: it is not what tells of new mail, and on a slow server
|
|
104
|
+
// it may take longer than a check may. When it does not finish, the connection is let go all the same (it is
|
|
105
|
+
// busy with an answer nobody waits for), and the next tries wait a while instead of failing at every check.
|
|
106
|
+
try {
|
|
107
|
+
await within(inStep(kept), STEP_DEADLINE_MS);
|
|
108
|
+
} catch (e) {
|
|
109
|
+
steppingPausedUntil = Date.now() + 10 * 60e3;
|
|
110
|
+
log(`[${name}] the cache was not brought in step (${e.message}): trying again in ten minutes`);
|
|
111
|
+
await letGo();
|
|
112
|
+
}
|
|
113
|
+
interrupted = false;
|
|
114
|
+
return found;
|
|
115
|
+
} catch (e) {
|
|
116
|
+
// said, whatever it was: a check that fails here and then passes the usual way would otherwise leave no trace
|
|
117
|
+
log(`[${name}] check on the kept connection failed (${e.message}): signing in again`);
|
|
118
|
+
await letGo();
|
|
119
|
+
return usual();
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
// IMAP: after each check the cache is brought in step with what changed on the server since the last one
|
|
123
|
+
// (read, flagged, gone), by asking for the difference; the sent folder the same way, at the old pace. The
|
|
124
|
+
// whole listing (reconcileCache, reconcileSent) is what there was before, and what there still is the first
|
|
125
|
+
// time, when a mailbox was rebuilt, and once a day in case a difference was ever missed.
|
|
126
|
+
let sentLookedAt = 0;
|
|
127
|
+
let allFlagsAt = 0;
|
|
128
|
+
let steppingPausedUntil = 0; // after a difference pass that did not finish in time: not at every check again
|
|
129
|
+
// Whole listings run on a connection of their own, one after the other, each folder asked for at most once at
|
|
130
|
+
// a time. A difference is never taken of a folder while its whole listing runs, nor a whole listing begun while
|
|
131
|
+
// a difference is being applied: two writers with two marks could leave the older one's view behind the newer mark.
|
|
132
|
+
const wholes = new Map(); // folder → its whole listing, in progress or waiting
|
|
133
|
+
let wholeQueue = Promise.resolve();
|
|
134
|
+
let stepping = Promise.resolve(); // the difference pass in progress, if any
|
|
135
|
+
const whole = (folder) => {
|
|
136
|
+
if (!wholes.has(folder)) {
|
|
137
|
+
const run = async () => {
|
|
138
|
+
try {
|
|
139
|
+
await stepping.catch(() => {});
|
|
140
|
+
// where the folder stands is taken first: what changes during the listing is then in the next difference
|
|
141
|
+
const stand = await withAuthRetry((client) => client.changesIn(folder, { mark: null }), null, name);
|
|
142
|
+
if (folder === 'inbox') await withAuthRetry((client) => reconcileCache(client, name), null, name);
|
|
143
|
+
else await withAuthRetry((client) => reconcileSent(client, name), null, name);
|
|
144
|
+
if (stand?.mark) { cache.setMeta(`sync:${name}:${folder}`, JSON.stringify(stand.mark)); cache.setMeta(`sync:${name}:${folder}:whole`, String(Date.now())); }
|
|
145
|
+
} catch (e) {
|
|
146
|
+
log(`[${name}] ${folder === 'inbox' ? 'cache reconcile' : 'sent threads'} failed: ${e.message}`);
|
|
147
|
+
} finally {
|
|
148
|
+
wholes.delete(folder);
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
const queued = wholeQueue.then(run);
|
|
152
|
+
wholeQueue = queued;
|
|
153
|
+
wholes.set(folder, queued);
|
|
154
|
+
}
|
|
155
|
+
return wholes.get(folder);
|
|
156
|
+
};
|
|
157
|
+
let stepInFlight = false;
|
|
158
|
+
let interrupted = false; // the pass in flight was cut short for new mail: not a failure
|
|
159
|
+
const inStep = (client) => { stepInFlight = true; stepping = step(client).finally(() => { stepInFlight = false; }); return stepping; };
|
|
160
|
+
const step = async (client) => {
|
|
161
|
+
if (acct.cache?.enabled === false || cache.openCache() === null) return;
|
|
162
|
+
if (Date.now() < steppingPausedUntil) return;
|
|
163
|
+
try {
|
|
164
|
+
// a server that keeps no change counter is asked for every flag of the cached span, at the old pace
|
|
165
|
+
const allFlags = Date.now() - allFlagsAt > RECONCILE_MINUTES * 60e3;
|
|
166
|
+
const r = wholes.has('inbox') ? null : await syncFolder(client, name, 'inbox', { allFlags });
|
|
167
|
+
if (r?.reset) whole('inbox');
|
|
168
|
+
else if (r) {
|
|
169
|
+
if (allFlags) allFlagsAt = Date.now();
|
|
170
|
+
// a mail the difference saw before a check did: the check will not take it for new, so its body is fetched here
|
|
171
|
+
if (r.items?.length && acct.cache?.bodies !== false) await cacheBodies(client, name, r.items);
|
|
172
|
+
if (r.read || r.flagged || r.gone || r.added) {
|
|
173
|
+
log(`[${name}] in step: ${[r.read && `${r.read} read state`, r.flagged && `${r.flagged} flag`, r.gone && `${r.gone} gone`, r.added && `${r.added} added`].filter(Boolean).join(', ')}`);
|
|
174
|
+
bus.emit('mailchanged', { account: name, read: r.read, flagged: r.flagged, gone: r.gone, added: r.added });
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (Date.now() - sentLookedAt > RECONCILE_MINUTES * 60e3 && !wholes.has('sent')) {
|
|
178
|
+
sentLookedAt = Date.now();
|
|
179
|
+
const sent = await syncFolder(client, name, 'sent').catch((e) => { if (!/no "sent" folder/.test(e.message)) throw e; return null; });
|
|
180
|
+
if (sent?.reset) whole('sent');
|
|
181
|
+
else if (sent && (sent.added || sent.gone)) log(`[${name}] sent threads: ${sent.added} added, ${sent.gone} gone`);
|
|
182
|
+
}
|
|
183
|
+
} catch (e) {
|
|
184
|
+
if (!interrupted) log(`[${name}] could not bring the cache in step: ${e.message}`); // the next check tries again; the daily listing settles what is left
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
const tick = async () => {
|
|
188
|
+
if (!mail || authGate.blocked()) return;
|
|
189
|
+
if (ticking) { again = true; return; }
|
|
190
|
+
ticking = true;
|
|
191
|
+
const began = Date.now();
|
|
192
|
+
try {
|
|
193
|
+
await check();
|
|
194
|
+
// a check is a sign-in, a listing and at most a few bodies: seconds. Longer is worth knowing about
|
|
195
|
+
if (Date.now() - began > 5000) log(`[${name}] a check took ${((Date.now() - began) / 1000).toFixed(1)}s`);
|
|
196
|
+
failures = 0;
|
|
197
|
+
authGate.ok();
|
|
198
|
+
} catch (e) {
|
|
199
|
+
failures++;
|
|
200
|
+
log(`[${name}] poll failed (${failures}): ${e.message}`);
|
|
201
|
+
if (isAuthError(e)) authGate.failed(e);
|
|
202
|
+
else if (failures === 3) notifyMac('Sideora ⚠️', `${name}: mail checks are failing: ` + e.message.slice(0, 120));
|
|
203
|
+
} finally {
|
|
204
|
+
ticking = false;
|
|
205
|
+
if (again) { again = false; setTimeout(tick, 250); }
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
if (mail) {
|
|
209
|
+
await tick();
|
|
210
|
+
setInterval(tick, Math.max(15, config.pollSeconds) * 1000);
|
|
211
|
+
// the poll only looks at the newest mail; this settles the rest of the cached span
|
|
212
|
+
const settle = async () => {
|
|
213
|
+
if (authGate.blocked()) return;
|
|
214
|
+
if (acct.provider === 'imap') {
|
|
215
|
+
// kept in step by differences (inStep): the whole listing only when there is no mark yet, or once a day
|
|
216
|
+
try {
|
|
217
|
+
if (acct.cache?.enabled === false || cache.openCache() === null) return;
|
|
218
|
+
for (const folder of ['inbox', 'sent']) {
|
|
219
|
+
const last = Number(cache.getMeta(`sync:${name}:${folder}:whole`)) || 0;
|
|
220
|
+
if (!cache.getMeta(`sync:${name}:${folder}`) || Date.now() - last > WHOLE_HOURS * 3600e3) await whole(folder);
|
|
221
|
+
}
|
|
222
|
+
} catch (e) {
|
|
223
|
+
log(`[${name}] cache reconcile failed: ${e.message}`); // a cache that cannot be opened is no reason for the daemon to stop
|
|
224
|
+
}
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
try { await withAuthRetry((client) => reconcileCache(client, name), null, name); } catch (e) { log(`[${name}] cache reconcile failed: ${e.message}`); }
|
|
228
|
+
try { await withAuthRetry((client) => reconcileSent(client, name), null, name); } catch (e) { log(`[${name}] sent threads not refreshed: ${e.message}`); }
|
|
229
|
+
};
|
|
230
|
+
setTimeout(settle, 5000);
|
|
231
|
+
setInterval(settle, RECONCILE_MINUTES * 60e3);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// Calendar: snapshot + reminders, refreshed on push (Exchange) or by polling
|
|
235
|
+
let calendar = null;
|
|
236
|
+
if (calendarProvider(acct) && acct.calendar && acct.calendar.watch !== false) {
|
|
237
|
+
try {
|
|
238
|
+
calendar = startCalendarWatch({ account: name, bus, log, authGate });
|
|
239
|
+
log(`[${name}] calendar watch on (reminders ${[].concat(acct.calendar.remindMinutes).join('/')} min before)`);
|
|
240
|
+
} catch (e) {
|
|
241
|
+
log(`[${name}] calendar watch not started: ${e.message}`);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// Push: the server tells us the instant mail arrives; each event triggers
|
|
246
|
+
// an immediate check.
|
|
247
|
+
if (!mail || acct.streaming === false) return;
|
|
248
|
+
try {
|
|
249
|
+
// (the password is the account's, as for a check; after a rejected sign-in the stream asks for it fresh)
|
|
250
|
+
const stream = await core.stream(name, {
|
|
251
|
+
// small delay lets the item settle. Said in the log: how soon after a mail's arrival the server told is the one
|
|
252
|
+
// thing no later line shows (see "ready … after arrival" in poll)
|
|
253
|
+
// (`how`: "told" by the server's push, or "asked", IMAP's own frequent look. What was asked for is there
|
|
254
|
+
// already; what the server tells of gets a moment to settle.)
|
|
255
|
+
onNewMail: (how = 'told', from = null) => {
|
|
256
|
+
log(`[${name}] [stream] new mail (${how})`);
|
|
257
|
+
if (from != null) newFrom = newFrom == null ? from : Math.min(newFrom, from);
|
|
258
|
+
// New mail does not wait behind the cache being brought in step: that pass is cut short (its connection is
|
|
259
|
+
// let go, which ends it at once; the difference is taken again at a later check) and the mail is looked for now.
|
|
260
|
+
if (stepInFlight && !interrupted) { interrupted = true; letGo(); }
|
|
261
|
+
setTimeout(tick, how === 'asked' ? 0 : 500);
|
|
262
|
+
},
|
|
263
|
+
onCalendarChange: calendar ? () => calendar.refresh() : undefined,
|
|
264
|
+
// live only (not queued): a client that shows drafts reloads them. One event per burst —
|
|
265
|
+
// a draft being typed elsewhere is saved every few seconds, each save several notifications.
|
|
266
|
+
onDraftsChange: burst(() => bus.emit('drafts', { account: name }), 1500),
|
|
267
|
+
authGate,
|
|
268
|
+
onState: (s) => {
|
|
269
|
+
const state = loadState();
|
|
270
|
+
const streams = { ...(state.streams || {}), [name]: { state: s, at: Date.now() } };
|
|
271
|
+
// keep the legacy single-account fields for `status`
|
|
272
|
+
saveState({ ...state, streams, streaming: summarize(streams), streamingAt: Date.now() });
|
|
273
|
+
bus.emit('stream', { account: name, state: s });
|
|
274
|
+
},
|
|
275
|
+
log: (m) => log(`[${name}] [stream] ` + m)
|
|
276
|
+
});
|
|
277
|
+
stream.start();
|
|
278
|
+
} catch (e) {
|
|
279
|
+
log(`[${name}] push stream not started: ${e.message} — polling only`);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** Collapse a burst of calls into one, `ms` after the last. */
|
|
284
|
+
function burst(fn, ms) {
|
|
285
|
+
let timer = null;
|
|
286
|
+
return () => { clearTimeout(timer); timer = setTimeout(fn, ms); };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function summarize(streams) {
|
|
290
|
+
const states = Object.values(streams).map((s) => s.state);
|
|
291
|
+
if (states.every((s) => s === 'connected')) return 'connected';
|
|
292
|
+
if (states.some((s) => s === 'reconnecting')) return 'reconnecting';
|
|
293
|
+
return 'off';
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* The poll refreshes only the newest mail, so older rows drift: a mail read,
|
|
298
|
+
* moved or deleted in another client stays unread, or stays at all, in the
|
|
299
|
+
* cache. This lists the whole cached span of the inbox and makes the cache
|
|
300
|
+
* match it.
|
|
301
|
+
*/
|
|
302
|
+
export async function reconcileCache(client, account, { dryRun = false } = {}) {
|
|
303
|
+
const acct = loadConfig().accounts[account];
|
|
304
|
+
if (acct?.cache?.enabled === false || cache.openCache() === null) return null;
|
|
305
|
+
const sinceIso = new Date(Date.now() - Number(acct.cache?.days || 30) * 86400e3).toISOString();
|
|
306
|
+
const items = [];
|
|
307
|
+
let complete = false;
|
|
308
|
+
for (let page = 0; page < 50; page++) {
|
|
309
|
+
const batch = await client.findInbox({ limit: 100, offset: page * 100, sinceIso });
|
|
310
|
+
// only an empty page is the end: a page can come back short (items that are not messages are skipped)
|
|
311
|
+
if (!batch.length) { complete = true; break; }
|
|
312
|
+
items.push(...batch);
|
|
313
|
+
}
|
|
314
|
+
// an inbox larger than what was listed: only the span actually listed is settled
|
|
315
|
+
const span = complete ? sinceIso : items.length ? items[items.length - 1].received : null;
|
|
316
|
+
if (!span) return null;
|
|
317
|
+
if (dryRun) return { listed: items.length, complete, span, items };
|
|
318
|
+
const r = cache.reconcile(account, items, span);
|
|
319
|
+
if (r.removed || r.added) log(`[${account}] cache reconciled: ${r.removed} no longer in the inbox, ${r.added} added`);
|
|
320
|
+
return r;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* IMAP: bring what the cache holds of a folder in step with the server, by the difference since the folder was
|
|
325
|
+
* last looked at (ImapClient.changesIn) instead of by listing it again. Inbox: read and flag state, messages that
|
|
326
|
+
* left, messages that came and the checks did not see (the daemon was not running). Sent: which thread each new
|
|
327
|
+
* message belongs to, and which are gone. Returns { read, flagged, gone, added }, { reset: true } when there is
|
|
328
|
+
* no difference to take (no mark yet, a mailbox rebuilt: the whole listing is due), or null where it does not apply.
|
|
329
|
+
*/
|
|
330
|
+
export async function syncFolder(client, account, folder, { allFlags = false } = {}) {
|
|
331
|
+
const key = `sync:${account}:${folder}`;
|
|
332
|
+
let mark = null;
|
|
333
|
+
try { mark = JSON.parse(cache.getMeta(key) || 'null'); } catch { mark = null; }
|
|
334
|
+
// what the cache holds of this folder, by message number (rows of an earlier generation of the mailbox are not its)
|
|
335
|
+
const held = new Map();
|
|
336
|
+
if (mark) {
|
|
337
|
+
for (const id of cache.idsOf(account, folder === 'sent' ? 'sent' : 'messages')) {
|
|
338
|
+
const p = idParts(splitId(id).rawId);
|
|
339
|
+
if (p && p.path === mark.path && p.validity === mark.validity) held.set(p.uid, id);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
// from the lowest message held, and never above where the folder stood: what came since is asked about too,
|
|
343
|
+
// even when the checks have cached the newest of it (and so raised the lowest number held)
|
|
344
|
+
const from = Math.min(held.size ? Math.min(...held.keys()) : Infinity, mark?.next ?? 1);
|
|
345
|
+
const r = await client.changesIn(folder, { mark, from, flags: folder === 'sent' ? false : allFlags ? 'all' : 'changed' });
|
|
346
|
+
if (!r) return null;
|
|
347
|
+
if (r.reset) return { reset: true };
|
|
348
|
+
const out = { read: 0, flagged: 0, gone: 0, added: 0 };
|
|
349
|
+
const addedItems = []; // inbox rows put in here, not by a check: their bodies are still to fetch (see inStep)
|
|
350
|
+
if (!r.same) {
|
|
351
|
+
const gone = r.uids ? [...held].filter(([uid]) => uid >= from && !r.uids.has(uid)).map(([, id]) => id) : [];
|
|
352
|
+
const done = cache.applyChanges({ flags: (r.flags || []).filter((f) => held.has(f.uid)), ...(folder === 'sent' ? { goneSent: gone } : { gone }) });
|
|
353
|
+
Object.assign(out, { read: done.read, flagged: done.flagged, gone: folder === 'sent' ? gone.length : done.gone });
|
|
354
|
+
// there and not held, numbered after the last look: came while nothing was looking. All of them, a couple of
|
|
355
|
+
// hundred at a time, before the mark moves on: what is skipped here would wait for the whole listing.
|
|
356
|
+
const fresh = r.uids ? [...r.uids].filter((uid) => uid >= mark.next && !held.has(uid)).sort((a, b) => b - a) : [];
|
|
357
|
+
const sinceIso = new Date(Date.now() - Number(loadConfig().accounts[account]?.cache?.days || 30) * 86400e3).toISOString();
|
|
358
|
+
for (let at = 0; at < fresh.length; at += 200) {
|
|
359
|
+
const items = await client.listByUids(folder, fresh.slice(at, at + 200));
|
|
360
|
+
if (folder === 'sent') out.added += cache.noteSent(account, items).added;
|
|
361
|
+
else {
|
|
362
|
+
const ids = new Set(cache.upsertItems(account, items.filter((i) => i.received >= sinceIso)));
|
|
363
|
+
out.added += ids.size;
|
|
364
|
+
addedItems.push(...items.filter((i) => ids.has(i.id)));
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
cache.setMeta(key, JSON.stringify(r.mark));
|
|
369
|
+
if (addedItems.length) Object.defineProperty(out, 'items', { value: addedItems, enumerable: false });
|
|
370
|
+
return out;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* Which thread each sent message of the cached span belongs to (see
|
|
375
|
+
* cache.noteSent): what lets a listing count a thread's messages, the ones
|
|
376
|
+
* you wrote included. Mail sent from another client shows up here at the next
|
|
377
|
+
* pass.
|
|
378
|
+
*/
|
|
379
|
+
export async function reconcileSent(client, account) {
|
|
380
|
+
const acct = loadConfig().accounts[account];
|
|
381
|
+
if (acct?.cache?.enabled === false || cache.openCache() === null) return null;
|
|
382
|
+
const sinceIso = new Date(Date.now() - Number(acct.cache?.days || 30) * 86400e3).toISOString();
|
|
383
|
+
const items = [];
|
|
384
|
+
let complete = false;
|
|
385
|
+
for (let page = 0; page < 20; page++) {
|
|
386
|
+
const batch = await client.findInbox({ folder: 'sent', limit: 100, offset: page * 100, sinceIso });
|
|
387
|
+
if (!batch.length) { complete = true; break; }
|
|
388
|
+
// a server without thread ids (plain IMAP): nothing here to keep, on this page or the next
|
|
389
|
+
if (!page && !batch.some((m) => m.conversationId)) return null;
|
|
390
|
+
items.push(...batch);
|
|
391
|
+
}
|
|
392
|
+
// more sent mail than was listed: only the span actually listed is settled
|
|
393
|
+
const span = complete ? sinceIso : items[items.length - 1].received;
|
|
394
|
+
const r = cache.noteSent(account, items, span);
|
|
395
|
+
if (r.added || r.removed) log(`[${account}] sent threads: ${r.added} added, ${r.removed} gone`);
|
|
396
|
+
return r;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* Look at an account's inbox and act on what is new. `newFrom` (IMAP): new mail is known to start at that message
|
|
401
|
+
* number, so only those messages are fetched, whole, instead of the newest page being listed again.
|
|
402
|
+
*/
|
|
403
|
+
async function poll(client, account, { newFrom = null } = {}) {
|
|
404
|
+
const acct = loadConfig().accounts[account];
|
|
405
|
+
const caching = acct?.cache?.enabled !== false && cache.openCache() !== null;
|
|
406
|
+
// first poll with a cache: backfill a deeper slice of headers
|
|
407
|
+
const backfill = caching && !(loadState().baselinedAccounts || {})[account];
|
|
408
|
+
const startedAt = Date.now();
|
|
409
|
+
// only what is new, where that is known; else the newest page, as ever
|
|
410
|
+
// (only on an account whose inbox is already known: the first look has to be the listing, which sets what counts as old)
|
|
411
|
+
const settled = !!(loadState().baselinedAccounts || {})[account];
|
|
412
|
+
const whole = newFrom != null && !backfill && settled ? await client.newSince(newFrom, { bodies: caching && acct.cache?.bodies !== false }) : null;
|
|
413
|
+
const items = whole ?? await client.findInbox({ limit: backfill ? 100 : 25 });
|
|
414
|
+
const listedAt = Date.now();
|
|
415
|
+
if (caching) {
|
|
416
|
+
try {
|
|
417
|
+
const seen = {};
|
|
418
|
+
const newIds = cache.upsertItems(account, items, seen);
|
|
419
|
+
// read or flagged in another mail client, among the mail just listed: a list on screen should follow
|
|
420
|
+
// (older mail is followed by the differences, on IMAP: see syncFolder)
|
|
421
|
+
if (seen.changed && !backfill) bus.emit('mailchanged', { account, changed: seen.changed });
|
|
422
|
+
// What the server lists is the inbox down to its oldest row: a cached row newer than that and not
|
|
423
|
+
// listed has left the inbox (archived or deleted here or in another client), and goes now rather
|
|
424
|
+
// than at the next full reconciliation. A second is left at the edge: mail of the same second as
|
|
425
|
+
// the last row listed may be the row after it.
|
|
426
|
+
const oldest = items.length ? Date.parse(items[items.length - 1].received) : NaN;
|
|
427
|
+
// (Exchange and JMAP list by date received, exactly; an IMAP listing is by arrival, which may not be the same order)
|
|
428
|
+
if ((acct.provider === 'ews' || acct.provider === 'jmap') && !backfill && !whole && !Number.isNaN(oldest)) {
|
|
429
|
+
const dropped = cache.dropUnlisted(account, items, new Date(oldest + 1000).toISOString());
|
|
430
|
+
if (dropped) { log(`[${account}] cache: ${dropped} no longer in the inbox`); bus.emit('mailchanged', { account, gone: dropped }); }
|
|
431
|
+
}
|
|
432
|
+
if (acct.cache.bodies !== false && !backfill) {
|
|
433
|
+
// fetched whole: the bodies are here already
|
|
434
|
+
if (whole) { for (const m of whole.filter((i) => newIds.includes(i.id) && i.body !== undefined)) { cache.upsertBody(account, m, { text: m.body, html: m.html ?? '' }); await noteSender(account, m); } }
|
|
435
|
+
else await cacheBodies(client, account, items.filter((i) => newIds.includes(i.id)));
|
|
436
|
+
}
|
|
437
|
+
// where the time went for mail that is new: what a listing shows only from now on
|
|
438
|
+
if (newIds.length && !backfill) {
|
|
439
|
+
const newest = Math.max(...items.filter((i) => newIds.includes(i.id)).map((i) => Date.parse(i.received)).filter(Number.isFinite));
|
|
440
|
+
log(`[${account}] ${newIds.length} new, ready ${Number.isFinite(newest) ? ((Date.now() - newest) / 1000).toFixed(1) + 's after arrival' : ''} (${whole ? 'fetched whole in' : 'listing'} ${listedAt - startedAt} ms${whole ? '' : `, bodies ${Date.now() - listedAt} ms`})`);
|
|
441
|
+
}
|
|
442
|
+
} catch (e) {
|
|
443
|
+
log(`[${account}] cache write failed: ${e.message}`);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
const state = loadState();
|
|
447
|
+
const seen = new Set(state.seenIds || []);
|
|
448
|
+
// ids are "<account>:<raw>" now; a pre-upgrade seen-set holds raw EWS ids
|
|
449
|
+
// for the default account — honour those too so nothing re-alerts.
|
|
450
|
+
const known = (id) => seen.has(id) || seen.has(id.slice(account.length + 1));
|
|
451
|
+
// A mail moved out of the inbox and back (an archive taken back, a restore from the trash) comes back
|
|
452
|
+
// under a new id. It is the same mail, by its Message-ID: not new, and not to be alerted about again.
|
|
453
|
+
const seenMail = new Set(state.seenMessageIds || []);
|
|
454
|
+
const fresh = items.filter((i) => i.id && !known(i.id) && !(i.messageId && seenMail.has(i.messageId)));
|
|
455
|
+
for (const i of items) { if (i.id) seen.add(i.id); if (i.messageId) seenMail.add(i.messageId); }
|
|
456
|
+
let ids = Array.from(seen);
|
|
457
|
+
if (ids.length > 4000) ids = ids.slice(ids.length - 4000);
|
|
458
|
+
let mailIds = Array.from(seenMail);
|
|
459
|
+
if (mailIds.length > 4000) mailIds = mailIds.slice(mailIds.length - 4000);
|
|
460
|
+
|
|
461
|
+
const baselined = { ...(state.baselinedAccounts || {}) };
|
|
462
|
+
const wasBaselined = baselined[account] || (account === 'default' && state.baselined);
|
|
463
|
+
baselined[account] = true;
|
|
464
|
+
saveState({ ...state, seenIds: ids, seenMessageIds: mailIds, baselined: true, baselinedAccounts: baselined, lastPollAt: Date.now() });
|
|
465
|
+
|
|
466
|
+
if (!wasBaselined) {
|
|
467
|
+
log(`[${account}] baseline set: ${items.length} items`);
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
if (fresh.length === 0) return;
|
|
471
|
+
|
|
472
|
+
const { rules, quietHours } = loadRulesDoc();
|
|
473
|
+
const quiet = inQuietHours(quietHours);
|
|
474
|
+
let alerts = 0;
|
|
475
|
+
let soundPlayed = false;
|
|
476
|
+
|
|
477
|
+
for (const item of fresh) {
|
|
478
|
+
if (item.isRead) continue;
|
|
479
|
+
const mail = {
|
|
480
|
+
id: item.id,
|
|
481
|
+
account,
|
|
482
|
+
from: item.fromName,
|
|
483
|
+
fromEmail: item.fromEmail,
|
|
484
|
+
subject: item.subject,
|
|
485
|
+
received: item.received
|
|
486
|
+
};
|
|
487
|
+
// rule.account (string or list) scopes a rule to specific accounts
|
|
488
|
+
const rule = rules.find((r) => accountOk(r, account) && ruleMatches(r, item));
|
|
489
|
+
bus.emit('newmail', { ...mail, rule: rule ? rule.name || 'rule' : null });
|
|
490
|
+
if (!rule) {
|
|
491
|
+
log(`[${account}] new mail (no rule): ${item.fromName} | ${item.subject}`);
|
|
492
|
+
continue;
|
|
493
|
+
}
|
|
494
|
+
log(`[${account}] MATCH [${rule.name || 'rule'}]: ${item.fromName} <${item.fromEmail}> | ${item.subject}`);
|
|
495
|
+
bus.emit('match', { rule: rule.name || 'rule', ...mail, quiet });
|
|
496
|
+
if (quiet) {
|
|
497
|
+
log(' (quiet hours — suppressed)');
|
|
498
|
+
continue;
|
|
499
|
+
}
|
|
500
|
+
if (!soundPlayed && rule.sound !== false) {
|
|
501
|
+
playSound(rule.sound || 'chime');
|
|
502
|
+
soundPlayed = true;
|
|
503
|
+
}
|
|
504
|
+
if (rule.notify !== false && alerts < MAX_ALERTS_PER_POLL) {
|
|
505
|
+
notifyMac(`📬 ${item.fromName || item.fromEmail}`, item.subject || '(no subject)');
|
|
506
|
+
alerts++;
|
|
507
|
+
}
|
|
508
|
+
if (rule.wake) {
|
|
509
|
+
const logFile = wakeAgent(loadConfig(), rule, item, DIGEST_DIR);
|
|
510
|
+
log(` woke agent → ${logFile}`);
|
|
511
|
+
bus.emit('wake', { rule: rule.name || 'rule', ...mail, log: logFile });
|
|
512
|
+
}
|
|
513
|
+
if (rule.webhook) {
|
|
514
|
+
fetch(rule.webhook, {
|
|
515
|
+
method: 'POST',
|
|
516
|
+
headers: { 'Content-Type': 'application/json' },
|
|
517
|
+
body: JSON.stringify({ event: 'match', rule: rule.name || 'rule', ...mail }),
|
|
518
|
+
signal: AbortSignal.timeout(10000)
|
|
519
|
+
}).catch((e) => log(` webhook failed: ${e.message}`));
|
|
520
|
+
}
|
|
521
|
+
if (rule.exec) {
|
|
522
|
+
spawn('/bin/sh', ['-c', rule.exec], {
|
|
523
|
+
detached: true,
|
|
524
|
+
stdio: 'ignore',
|
|
525
|
+
// no password of an account (credentials.env) nor a 1Password token goes to the rule's command
|
|
526
|
+
env: childEnv({
|
|
527
|
+
MAIL_RULE: rule.name || 'rule',
|
|
528
|
+
MAIL_ACCOUNT: account,
|
|
529
|
+
MAIL_FROM: item.fromName,
|
|
530
|
+
MAIL_FROM_EMAIL: item.fromEmail,
|
|
531
|
+
MAIL_SUBJECT: item.subject,
|
|
532
|
+
MAIL_ID: item.id
|
|
533
|
+
})
|
|
534
|
+
}).unref();
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// Fetch and store the text + HTML bodies of newly seen mail (two calls per
|
|
540
|
+
// mail; new-mail volume is low). Failures only cost the cached body.
|
|
541
|
+
async function cacheBodies(client, account, items) {
|
|
542
|
+
for (const item of items.slice(0, 10)) {
|
|
543
|
+
try {
|
|
544
|
+
const text = await client.getMessage(item.id, { bodyType: 'Text' });
|
|
545
|
+
let html = null;
|
|
546
|
+
try { html = await client.getMessage(item.id, { bodyType: 'HTML' }); } catch {}
|
|
547
|
+
cache.upsertBody(account, text, { text: text.body, html: html ? (html.bodyType === 'HTML' ? html.body : '') : null }); // '': no HTML in this mail; null: could not be asked
|
|
548
|
+
await noteSender(account, text);
|
|
549
|
+
} catch (e) {
|
|
550
|
+
log(`[${account}] body cache failed for ${item.subject}: ${e.message}`);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/** A new mail's DMARC verdict, kept for its sender's picture (pictures.js): from the headers it was fetched with, nothing asked. */
|
|
556
|
+
async function noteSender(account, msg) {
|
|
557
|
+
try { (await pictures()).noteMessage(account, msg); } catch { /* its picture waits for a lookup */ }
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
function log(msg) {
|
|
561
|
+
// one line per entry — multi-line errors (e.g. op CLI output) stay greppable
|
|
562
|
+
const flat = String(msg).replace(/\s*\n\s*/g, ' · ').slice(0, 500);
|
|
563
|
+
console.log(`[${new Date().toISOString()}] ${flat}`);
|
|
564
|
+
}
|