-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
683 lines (673 loc) · 21.8 KB
/
main.js
File metadata and controls
683 lines (673 loc) · 21.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/main.ts
var main_exports = {};
__export(main_exports, {
default: () => RiverPlugin
});
module.exports = __toCommonJS(main_exports);
var import_obsidian3 = require("obsidian");
// src/settings.ts
var import_obsidian = require("obsidian");
var DEFAULT_SETTINGS = {
apiUrl: "https://river-email.fly.dev",
smsApiUrl: "https://river-sms.fly.dev",
syncApiUrl: "https://river-dev-sync.fly.dev",
userId: "",
token: "",
syncOnStartup: true,
syncInterval: 5,
// 5 minutes
inboxFolder: "Inbox/",
tagPrefix: "river/",
addFrontmatter: true,
dateFormat: "YYYY-MM-DD"
};
var RiverSettingTab = class extends import_obsidian.PluginSettingTab {
constructor(app, plugin) {
super(app, plugin);
this.pollingInterval = null;
this.plugin = plugin;
}
display() {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl("h2", { text: "River Sync Settings" });
this.displayConnectionStatus(containerEl);
containerEl.createEl("h3", { text: "Sync Configuration" });
new import_obsidian.Setting(containerEl).setName("Sync on startup").setDesc("Automatically sync notes when Obsidian opens").addToggle(
(toggle) => toggle.setValue(this.plugin.settings.syncOnStartup).onChange(async (value) => {
this.plugin.settings.syncOnStartup = value;
await this.plugin.saveSettings();
})
);
new import_obsidian.Setting(containerEl).setName("Sync interval").setDesc("Minutes between automatic syncs (0 = manual only)").addText(
(text) => text.setPlaceholder("5").setValue(String(this.plugin.settings.syncInterval)).onChange(async (value) => {
const interval = parseInt(value);
if (!isNaN(interval) && interval >= 0) {
this.plugin.settings.syncInterval = interval;
await this.plugin.saveSettings();
}
})
);
containerEl.createEl("h3", { text: "Note Organization" });
new import_obsidian.Setting(containerEl).setName("Inbox folder").setDesc("Folder path for synced notes (e.g., Inbox/ or Daily/)").addText(
(text) => text.setPlaceholder("Inbox/").setValue(this.plugin.settings.inboxFolder).onChange(async (value) => {
this.plugin.settings.inboxFolder = value;
await this.plugin.saveSettings();
})
);
new import_obsidian.Setting(containerEl).setName("Tag prefix").setDesc("Prefix for auto-generated tags (e.g., river/)").addText(
(text) => text.setPlaceholder("river/").setValue(this.plugin.settings.tagPrefix).onChange(async (value) => {
this.plugin.settings.tagPrefix = value;
await this.plugin.saveSettings();
})
);
new import_obsidian.Setting(containerEl).setName("Add frontmatter").setDesc("Add metadata properties to synced notes (received date, topics)").addToggle(
(toggle) => toggle.setValue(this.plugin.settings.addFrontmatter).onChange(async (value) => {
this.plugin.settings.addFrontmatter = value;
await this.plugin.saveSettings();
})
);
new import_obsidian.Setting(containerEl).setName("Date format").setDesc("Date format for note filenames (using moment.js)").addText(
(text) => text.setPlaceholder("YYYY-MM-DD").setValue(this.plugin.settings.dateFormat).onChange(async (value) => {
this.plugin.settings.dateFormat = value;
await this.plugin.saveSettings();
})
);
}
displayConnectionStatus(containerEl) {
const section = containerEl.createDiv({ cls: "river-connection-section" });
section.createEl("h3", { text: "Connection" });
const isConnected = this.plugin.settings.userId && this.plugin.settings.token;
if (isConnected) {
const statusDiv = section.createDiv({ cls: "river-status-connected" });
statusDiv.createEl("p", {
text: "\u2705 Connected to River"
});
new import_obsidian.Setting(section).setName("Disconnect").setDesc("Clear your River credentials and disconnect").addButton(
(button) => button.setButtonText("Disconnect").setCta().onClick(async () => {
this.plugin.settings.userId = "";
this.plugin.settings.token = "";
await this.plugin.saveSettings();
this.display();
})
);
} else {
const statusDiv = section.createDiv({ cls: "river-status-disconnected" });
statusDiv.createEl("p", {
text: "\u26A0\uFE0F Not connected to River"
});
new import_obsidian.Setting(section).setName("Connect to River").setDesc("Authorize this plugin to access your River account").addButton(
(button) => button.setButtonText("Connect").setCta().onClick(async () => {
await this.initiateOAuthFlow();
})
);
}
}
async initiateOAuthFlow() {
try {
const response = await fetch(
`${this.plugin.settings.syncApiUrl}/api/oauth/session`,
{
method: "POST",
headers: {
"Content-Type": "application/json"
}
}
);
if (!response.ok) {
throw new Error("Failed to create OAuth session");
}
const data = await response.json();
if (!data.success) {
throw new Error(data.error || "Failed to create OAuth session");
}
window.open(data.authUrl, "_blank");
this.startPolling(data.sessionId);
} catch (error) {
console.error("OAuth flow error:", error);
const errorDiv = document.createElement("div");
errorDiv.className = "river-error";
errorDiv.textContent = `Failed to connect: ${error.message}`;
this.containerEl.insertBefore(errorDiv, this.containerEl.firstChild);
}
}
startPolling(sessionId) {
let attempts = 0;
const maxAttempts = 90;
this.pollingInterval = window.setInterval(async () => {
attempts++;
if (attempts > maxAttempts) {
this.stopPolling();
console.log("OAuth session expired");
return;
}
try {
const response = await fetch(
`${this.plugin.settings.syncApiUrl}/api/oauth/session/${sessionId}`
);
if (!response.ok) {
throw new Error("Failed to check session status");
}
const data = await response.json();
if (data.state === "authorized") {
this.plugin.settings.userId = data.userId;
this.plugin.settings.token = data.token;
this.plugin.settings.apiUrl = data.emailApiUrl;
this.plugin.settings.smsApiUrl = data.smsApiUrl;
await this.plugin.saveSettings();
this.stopPolling();
this.display();
const successDiv = document.createElement("div");
successDiv.className = "river-success";
successDiv.textContent = "\u2705 Successfully connected to River!";
this.containerEl.insertBefore(
successDiv,
this.containerEl.firstChild
);
setTimeout(() => {
successDiv.remove();
}, 3e3);
} else if (data.state === "expired") {
this.stopPolling();
console.log("OAuth session expired");
}
} catch (error) {
console.error("Polling error:", error);
}
}, 2e3);
}
stopPolling() {
if (this.pollingInterval !== null) {
window.clearInterval(this.pollingInterval);
this.pollingInterval = null;
}
}
hide() {
this.stopPolling();
}
};
// src/riverClient.ts
var RiverClient = class {
constructor(apiUrl, userId, smsApiUrl) {
this.apiUrl = apiUrl.replace(/\/$/, "");
this.smsApiUrl = (smsApiUrl || "https://river-sms.fly.dev").replace(
/\/$/,
""
);
this.userId = userId;
}
/**
* Fetch pending emails from River staging API
*/
async getPendingEmails() {
if (!this.userId) {
throw new Error("User ID not configured");
}
const url = `${this.apiUrl}/api/staging/${this.userId}/pending`;
console.log(`River: Fetching pending emails from ${url}`);
const response = await fetch(url);
if (!response.ok) {
throw new Error(
`Failed to fetch pending emails: ${response.status} ${response.statusText}`
);
}
const data = await response.json();
if (!data.success) {
throw new Error("API returned success=false");
}
console.log(`River: Found ${data.count} pending emails`);
const emails = data.emails.map((email) => ({
...email,
source: "email"
}));
const smsMessages = await this.getPendingSms();
const allMessages = [...emails, ...smsMessages];
console.log(
`River: Total pending messages: ${allMessages.length} (${emails.length} emails, ${smsMessages.length} SMS)`
);
return allMessages;
}
/**
* Fetch pending SMS messages from River SMS service
*/
async getPendingSms() {
if (!this.userId) {
throw new Error("User ID not configured");
}
try {
const url = `${this.smsApiUrl}/api/sms/staging/pending?userId=${this.userId}`;
console.log(`River: Fetching pending SMS from ${url}`);
const response = await fetch(url);
if (!response.ok) {
console.warn(
`River: Failed to fetch SMS (${response.status}), continuing with emails only`
);
return [];
}
const data = await response.json();
if (!data.messages || !Array.isArray(data.messages)) {
console.warn("River: Invalid SMS response format");
return [];
}
console.log(`River: Found ${data.messages.length} pending SMS`);
return data.messages.map((sms) => {
const receivedDate = new Date(sms.received_at);
return {
id: String(sms.id),
subject: sms.ai_summary || "SMS Note",
content: sms.ai_enhanced_content || sms.body,
urls: sms.detected_urls || [],
topics: sms.suggested_topics || [],
receivedAt: receivedDate.getTime(),
contentType: sms.content_type || "note",
eventDetails: sms.event_details ? JSON.parse(sms.event_details) : null,
source: "sms",
from: sms.from_phone
};
});
} catch (error) {
console.warn(
"River: Failed to fetch SMS, continuing with emails only:",
error
);
return [];
}
}
/**
* Mark an email or SMS as synced to Obsidian
*/
async markAsSynced(messageId, metadata, source = "email") {
if (source === "sms") {
const url2 = `${this.smsApiUrl}/api/sms/staging/${messageId}/synced`;
console.log(`River: Marking SMS ${messageId} as synced`);
const response2 = await fetch(url2, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ obsidianMetadata: metadata })
});
if (!response2.ok) {
throw new Error(
`Failed to mark SMS as synced: ${response2.status} ${response2.statusText}`
);
}
return;
}
const url = `${this.apiUrl}/api/staging/${messageId}/mark-synced`;
console.log(`River: Marking email ${messageId} as synced`);
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ obsidianMetadata: metadata })
});
if (!response.ok) {
throw new Error(
`Failed to mark email as synced: ${response.status} ${response.statusText}`
);
}
const data = await response.json();
if (!data.success) {
throw new Error("Failed to mark email as synced");
}
}
/**
* Test the connection to the River API
*/
async testConnection() {
try {
const url = `${this.apiUrl}/health`;
const response = await fetch(url);
return response.ok;
} catch (error) {
console.error("River: Connection test failed:", error);
return false;
}
}
};
// src/noteCreator.ts
var import_obsidian2 = require("obsidian");
var NoteCreator = class {
constructor(app, settings) {
this.app = app;
this.settings = settings;
}
/**
* Create a markdown note from a pending email
*/
async createNote(email) {
const filename = this.generateFilename(email);
const filepath = this.settings.inboxFolder + filename;
const content = this.generateContent(email);
await this.ensureFolderExists(this.settings.inboxFolder);
const existingFile = this.app.vault.getAbstractFileByPath(filepath);
if (existingFile instanceof import_obsidian2.TFile) {
console.log(`River: File already exists, updating: ${filepath}`);
await this.app.vault.modify(existingFile, content);
return existingFile;
}
console.log(`River: Creating note: ${filepath}`);
const file = await this.app.vault.create(filepath, content);
return file;
}
/**
* Generate filename for the note
*/
generateFilename(email) {
const date = (0, import_obsidian2.moment)(email.receivedAt).format("MM-DD-YYYY");
const sanitizedSubject = this.sanitizeFilename(email.subject);
const fullFilename = `${date} - ${sanitizedSubject}`;
return this.sanitizeFilename(fullFilename) + ".md";
}
/**
* Sanitize filename by removing invalid characters
* Ensures filename is filesystem-safe across all platforms
*/
sanitizeFilename(filename) {
return filename.replace(/[\\/:*?"<>|]/g, "").replace(/\s+/g, " ").replace(/^\.+/, "").trim().substring(0, 200);
}
/**
* Generate markdown content for the note
*/
generateContent(email) {
let content = "";
if (this.settings.addFrontmatter) {
content += this.generateFrontmatter(email);
content += "\n";
}
content += `# ${email.subject}
`;
content += `${email.content}
`;
if (email.urls && email.urls.length > 0) {
content += `
## Links
`;
email.urls.forEach((url) => {
content += `- ${url}
`;
});
}
if (email.topics && email.topics.length > 0) {
content += `
---
`;
const tags = email.topics.map(
(topic) => `#${this.settings.tagPrefix}${this.sanitizeTag(topic)}`
);
content += tags.join(" ");
}
return content;
}
/**
* Generate YAML frontmatter
*/
generateFrontmatter(email) {
var _a, _b;
let frontmatter = "---\n";
frontmatter += `received: ${(0, import_obsidian2.moment)(email.receivedAt).format("MM/DD/YYYY hh:mm A")}
`;
if (email.topics && email.topics.length > 0) {
frontmatter += `topics:
`;
email.topics.forEach((topic) => {
frontmatter += ` - ${topic}
`;
});
}
if ((_a = email.eventDetails) == null ? void 0 : _a.date) {
frontmatter += `event_date: ${email.eventDetails.date}
`;
}
if ((_b = email.eventDetails) == null ? void 0 : _b.time) {
frontmatter += `event_time: ${email.eventDetails.time}
`;
}
frontmatter += "---\n";
return frontmatter;
}
/**
* Get emoji for content type
*/
getTypeEmoji(contentType) {
switch (contentType) {
case "note":
return "\u{1F4DD}";
case "event":
return "\u{1F4C5}";
case "task":
return "\u2705";
case "mixed":
return "\u{1F500}";
default:
return "\u{1F4C4}";
}
}
/**
* Sanitize tag by removing special characters
*/
sanitizeTag(tag) {
return tag.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
}
/**
* Ensure folder exists, create if not
*/
async ensureFolderExists(folderPath) {
const folder = folderPath.replace(/\/$/, "");
if (!folder)
return;
const exists = this.app.vault.getAbstractFileByPath(folder);
if (!exists) {
console.log(`River: Creating folder: ${folder}`);
await this.app.vault.createFolder(folder);
}
}
};
// src/syncService.ts
var SyncService = class {
constructor(app, client, settings) {
this.app = app;
this.client = client;
this.settings = settings;
this.noteCreator = new NoteCreator(app, settings);
}
/**
* Sync all pending notes from River
* Returns the number of notes synced
*/
async syncPendingNotes() {
console.log("River: Starting sync...");
const emails = await this.client.getPendingEmails();
if (emails.length === 0) {
console.log("River: No pending emails to sync");
return 0;
}
console.log(`River: Syncing ${emails.length} emails...`);
let syncedCount = 0;
const errors = [];
for (const email of emails) {
try {
await this.syncEmail(email);
syncedCount++;
} catch (error) {
console.error(`River: Failed to sync email ${email.id}:`, error);
errors.push(`${email.subject}: ${error.message}`);
}
}
if (errors.length > 0) {
console.warn(`River: ${errors.length} emails failed to sync:`, errors);
}
console.log(
`River: Sync complete. Synced ${syncedCount}/${emails.length} emails`
);
return syncedCount;
}
/**
* Sync a single email
*/
async syncEmail(email) {
console.log(`River: Syncing email: ${email.subject}`);
const file = await this.noteCreator.createNote(email);
const metadata = {
notePath: file.path,
tags: email.topics.map((topic) => `${this.settings.tagPrefix}${topic}`),
frontmatter: {
river_id: email.id,
type: email.contentType,
received: email.receivedAt
}
};
await this.client.markAsSynced(email.id, metadata, email.source || "email");
console.log(`River: Successfully synced: ${email.subject} -> ${file.path}`);
}
/**
* Update the note creator when settings change
*/
updateSettings(settings) {
this.settings = settings;
this.noteCreator = new NoteCreator(this.app, settings);
}
/**
* Update the client reference (called when credentials change)
*/
updateClient(client) {
this.client = client;
}
};
// src/main.ts
var RiverPlugin = class extends import_obsidian3.Plugin {
constructor() {
super(...arguments);
this.syncInterval = null;
}
async onload() {
console.log("Loading River Sync plugin");
await this.loadSettings();
this.client = new RiverClient(
this.settings.apiUrl,
this.settings.userId,
this.settings.smsApiUrl
);
this.syncService = new SyncService(this.app, this.client, this.settings);
this.addRibbonIcon("sync", "Sync River notes", async () => {
await this.syncNotes();
});
this.addCommand({
id: "sync-river-notes",
name: "Sync notes from River",
callback: async () => {
await this.syncNotes();
}
});
this.addCommand({
id: "test-river-connection",
name: "Test River connection",
callback: async () => {
await this.testConnection();
}
});
this.addSettingTab(new RiverSettingTab(this.app, this));
if (this.settings.syncOnStartup) {
setTimeout(() => {
this.syncNotes();
}, 2e3);
}
if (this.settings.syncInterval > 0) {
this.startPeriodicSync();
}
}
async onunload() {
console.log("Unloading River Sync plugin");
this.stopPeriodicSync();
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
this.client = new RiverClient(
this.settings.apiUrl,
this.settings.userId,
this.settings.smsApiUrl
);
this.syncService.updateSettings(this.settings);
this.syncService.updateClient(this.client);
this.stopPeriodicSync();
if (this.settings.syncInterval > 0) {
this.startPeriodicSync();
}
}
async syncNotes() {
if (!this.settings.userId || !this.settings.token) {
new import_obsidian3.Notice("\u26A0\uFE0F Please connect to River in settings first");
return;
}
try {
new import_obsidian3.Notice("\u{1F504} Syncing notes from River...");
const count = await this.syncService.syncPendingNotes();
if (count > 0) {
new import_obsidian3.Notice(
`\u2705 Synced ${count} note${count !== 1 ? "s" : ""} from River`
);
} else {
new import_obsidian3.Notice("\u2713 No new notes to sync");
}
} catch (error) {
console.error("River sync failed:", error);
new import_obsidian3.Notice(`\u274C Sync failed: ${error.message}`);
}
}
async testConnection() {
new import_obsidian3.Notice("\u{1F50D} Testing River connection...");
try {
const isConnected = await this.client.testConnection();
if (isConnected) {
new import_obsidian3.Notice("\u2705 Connected to River successfully!");
} else {
new import_obsidian3.Notice("\u274C Failed to connect to River. Check your API URL.");
}
} catch (error) {
console.error("River connection test failed:", error);
new import_obsidian3.Notice(`\u274C Connection test failed: ${error.message}`);
}
}
startPeriodicSync() {
const intervalMs = this.settings.syncInterval * 60 * 1e3;
console.log(
`River: Starting periodic sync every ${this.settings.syncInterval} minutes`
);
this.syncInterval = window.setInterval(() => {
this.syncNotes();
}, intervalMs);
}
stopPeriodicSync() {
if (this.syncInterval !== null) {
console.log("River: Stopping periodic sync");
window.clearInterval(this.syncInterval);
this.syncInterval = null;
}
}
};