-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
551 lines (467 loc) · 18.2 KB
/
Copy pathmain.js
File metadata and controls
551 lines (467 loc) · 18.2 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
/**
* Current Block
* @returns {object} - An object representing the block the plug-in is triggered in.
*/
async function getCurrentBlock() {
let currentBlock = await logseq.App.getCurrentBlock();
if (currentBlock) {
currentBlockId = currentBlock.uuid; // Store the block ID (UUID) in the variable
console.log("Current block ID:", currentBlockId);
} else {
console.log("No block is currently selected.");
}
return currentBlock;
}
/**
* @param {object} block - An object representing the block the plug-in is triggered in.
* @returns - An object representing the page that hosts the provided block object.
*/
async function getCurrentPage(block) {
const page = await logseq.Editor.getPage(block.page.id);
if (page) {
currentPageName = page.name;
console.log("Page name:", currentPageName);
if (page.journal) {
console.log("This is a journal page. Date:", page.journal["date"]);
} else {
console.log("This is not a journal page.");
}
} else {
console.log("No page is currently open.");
}
return page;
}
/**
* @param {string} journalDay - The date of the Journal Page.
* @returns {Date} - The date converted from the provided string.
*/
function journalDayToDate(journalDay) {
const y = Math.floor(journalDay / 10000);
const m = Math.floor((journalDay % 10000) / 100) - 1;
const d = journalDay % 100;
return new Date(y, m, d);
}
/**
* Format a date string to YYYY-MM-DD format for the API
* @param {Date} date - The date to format
* @returns {string} - Formatted date string
*/
function formatDateForAPI(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
/**
* Format datetime string using a custom format pattern
* @param {string} timeString - Time string from Outlook (already in Eastern time)
* @returns {string} - Formatted datetime string according to user configuration
*/
function formatTime(timeString) {
// Parse the time string manually to avoid timezone conversion
const date = new Date(timeString);
// Extract components directly from the date object
// Use UTC methods to avoid any local timezone adjustments
const utcDate = new Date(date.getTime() + (date.getTimezoneOffset() * 60000));
// Get the format pattern from settings
const formatPattern = logseq.settings?.timeFormat || "h:mm a";
// Extract date components
const year = utcDate.getFullYear();
const month = utcDate.getMonth();
const day = utcDate.getDate();
const hours24 = utcDate.getHours();
const hours12 = hours24 % 12 || 12;
const minutes = utcDate.getMinutes();
const seconds = utcDate.getSeconds();
const ampm = hours24 >= 12 ? 'PM' : 'AM';
const ampmLower = ampm.toLowerCase();
// Month names
const monthNames = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
];
const monthNamesShort = [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
];
// Day names
const dayNames = [
'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
];
const dayNamesShort = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
// Format tokens and their replacements
const formatTokens = {
// Year
'YYYY': String(year),
'YY': String(year).slice(-2),
// Month
'MMMM': monthNames[month],
'MMM': monthNamesShort[month],
'MM': String(month + 1).padStart(2, '0'),
'M': String(month + 1),
// Day of month
'DD': String(day).padStart(2, '0'),
'D': String(day),
// Day of week
'dddd': dayNames[utcDate.getDay()],
'ddd': dayNamesShort[utcDate.getDay()],
// Hour (24-hour)
'HH': String(hours24).padStart(2, '0'),
'H': String(hours24),
// Hour (12-hour)
'hh': String(hours12).padStart(2, '0'),
'h': String(hours12),
// Minutes
'mm': String(minutes).padStart(2, '0'),
'm': String(minutes),
// Seconds
'ss': String(seconds).padStart(2, '0'),
's': String(seconds),
// AM/PM
'A': ampm,
'a': ampmLower
};
// --- START OF FIX ---
// Create a single regex that matches any of the tokens, longest first.
const sortedTokens = Object.keys(formatTokens).sort((a, b) => b.length - a.length);
const regex = new RegExp(sortedTokens.join('|'), 'g');
// Use the .replace() method with a replacer function.
// This finds all tokens in one pass and replaces them with their corresponding values.
return formatPattern.replace(regex, (match) => formatTokens[match]);
// --- END OF FIX ---
}
/**
* Calculate duration between two times as a time quantity
* @param {string} startTime - Start time string (already in Eastern time)
* @param {string} endTime - End time string (already in Eastern time)
* @returns {string} - Duration in format "HH:MM:SS"
*/
function calculateDuration(startTime, endTime) {
const start = new Date(startTime);
const end = new Date(endTime);
// Calculate difference in milliseconds
const diffMs = end.getTime() - start.getTime();
// Convert to hours, minutes, seconds
const totalSeconds = Math.floor(diffMs / 1000);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
// Format as HH:MM:SS
return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
}
/**
* Create meeting links for an event
* @param {Array} meetingLinks - Array of meeting link URLs
* @returns {string} - Markdown links string
*/
function createMeetingLinks(meetingLinks) {
if (!meetingLinks || meetingLinks.length === 0) {
return "";
}
let linksHtml = "";
meetingLinks.forEach((link, index) => {
// Use "Join Meeting" for all links, with numbering for multiple links
let linkText = meetingLinks.length > 1 ? `Join Meeting ${index + 1}` : "Join Meeting";
// Create the markdown link
linksHtml += `[${linkText}](${link})`;
// Add space between multiple links
if (index < meetingLinks.length - 1) {
linksHtml += " ";
}
});
return " " + linksHtml; // Add leading space to separate from subject/emoji
}
/**
* Format event subject based on bracket settings and add recurring emoji and meeting links
* @param {string} subject - The event subject
* @param {boolean} isRecurring - Whether the event is recurring
* @param {Array} meetingLinks - Array of meeting link URLs
* @returns {string} - Formatted subject with brackets, recurring emoji, and meeting links
*/
function formatEventSubject(subject, isRecurring = false, meetingLinks = []) {
const bracketSetting = logseq.settings?.bracketEvents || "none";
let formattedSubject = subject;
// First apply brackets based on setting
switch (bracketSetting) {
case "all":
formattedSubject = `[[${subject}]]`;
break;
case "recurring":
formattedSubject = isRecurring ? `[[${subject}]]` : subject;
break;
case "none":
default:
formattedSubject = subject;
break;
}
// Then add recurring emoji outside the brackets if it's a recurring event
if (isRecurring) {
formattedSubject = `${formattedSubject} 🔃`;
}
// Finally add meeting links after subject and emoji
const meetingLinks_formatted = createMeetingLinks(meetingLinks);
formattedSubject = `${formattedSubject}${meetingLinks_formatted}`;
return formattedSubject;
}
/**
* Format event description by truncating if needed
* @param {string} description - The event description
* @returns {string} - Formatted/truncated description
*/
function formatDescription(description) {
if (!description) return "";
const maxLength = logseq.settings?.descriptionMaxLength || 0;
if (maxLength > 0 && description.length > maxLength) {
return description.substring(0, maxLength).trim() + "...";
}
return description.trim();
}
/**
* Format event block content based on user template and handle child blocks
* @param {object} event - The event object from API
* @returns {object} - Object with mainContent and childBlocks array
*/
function formatEventContent(event) {
const template = logseq.settings?.outputFormat ||
"{subject}\\nevent-time:: {time}\\nevent-duration:: {duration}\\nattendees:: {attendees}";
const includeEmpty = logseq.settings?.includeEmptyFields || false;
// Format the event subject with brackets, emoji, and meeting links
const formattedSubject = formatEventSubject(event.subject, event.isRecurring, event.meetingLinks);
// Prepare all possible variables
const variables = {
subject: formattedSubject,
time: formatTime(event.start),
duration: calculateDuration(event.start, event.end),
attendees: formatAttendees(event.attendees),
location: event.location || "",
description: formatDescription(event.description || "")
};
// Replace variables in template
let content = template;
// Handle each variable replacement
Object.keys(variables).forEach(key => {
const value = variables[key];
const placeholder = `{${key}}`;
if (content.includes(placeholder)) {
if (!includeEmpty && !value) {
// Remove the entire line if the field is empty and includeEmpty is false
const lines = content.split('\\n');
content = lines.filter(line => {
if (line.includes(placeholder)) {
// Only remove lines that are just property assignments (contain ::)
return line.includes('::') ? false : true;
}
return true;
}).join('\\n');
} else {
// Replace the placeholder with the value
content = content.replace(new RegExp(`\\{${key}\\}`, 'g'), value);
}
}
});
// Convert \\n to actual newlines
content = content.replace(/\\n/g, '\n');
// Split content by ---CHILD--- delimiter to separate main content from child blocks
const parts = content.split('---CHILD---');
const mainContent = parts[0].trim();
const childBlocks = parts.slice(1).map(block => block.trim()).filter(block => block.length > 0);
return {
mainContent,
childBlocks
};
}
/**
* @param {Array} attendees - Array of attendee names
* @returns {string} - Comma-separated list with each name in square brackets if the confiuration is selected
*/
function formatAttendees(attendees) {
if (!attendees || attendees.length === 0) {
return "";
}
// Get the user's configured name to exclude
const excludeName = logseq.settings?.excludeUserName || "";
// Get the bracketing setting
const bracketSetting = logseq.settings?.bracketAttendees || "all";
// Filter out the user's name if configured
const filteredAttendees = excludeName
? attendees.filter(name => name !== excludeName)
: attendees;
// Format names based on bracket setting
return filteredAttendees
.map(name => bracketSetting === "all" ? `[[${name}]]` : name)
.join(", ");
}
/**
* Fetch events from the Outlook API
* @param {string} dateString - Date in YYYY-MM-DD format
* @returns {Promise<Array>} - Array of events or empty array if error
*/
async function fetchEventsFromAPI(dateString) {
try {
// Get the configured API URL, default to localhost:5000
const apiUrl = logseq.settings?.apiUrl || 'http://localhost:5000';
const meetingBaseUrls = logseq.settings?.meetingBaseUrls || '';
// Build the URL with meeting URLs parameter if configured
let url = `${apiUrl}/events/${dateString}`;
if (meetingBaseUrls.trim()) {
url += `?meeting_urls=${encodeURIComponent(meetingBaseUrls)}`;
}
const response = await fetch(url);
if (!response.ok) {
console.error(`API request failed: ${response.status} ${response.statusText}`);
return [];
}
const data = await response.json();
if (data.success) {
console.log(`Found ${data.events.length} events for ${dateString}`);
return data.events;
} else {
console.error('API returned error:', data.error);
return [];
}
} catch (error) {
console.error('Error fetching events from API:', error);
return [];
}
}
// Insert the day's list of events from the local Outlook calendar.
async function getEvents(e) {
console.log('=== getEvents function called ===');
console.log('Trigger block UUID:', e.uuid);
try {
const currentBlock = await getCurrentBlock();
const currentPage = await getCurrentPage(currentBlock);
if (!currentPage?.journalDay) {
console.log("Not on a journal page");
logseq.Editor.insertBlock(e.uuid, `Error: This command only works on journal pages`, {before: true});
return;
}
const pageDate = journalDayToDate(currentPage.journalDay);
const apiDateString = formatDateForAPI(pageDate);
console.log("Fetching events for date:", apiDateString);
// Fetch events from API
const events = await fetchEventsFromAPI(apiDateString);
if (events.length === 0) {
logseq.Editor.insertBlock(e.uuid, `No events found for ${apiDateString}`, {before: true});
return;
}
console.log(`Processing ${events.length} events`);
// Sort events by start time (earliest to latest)
const sortedEvents = events.sort((a, b) => {
const startTimeA = new Date(a.start);
const startTimeB = new Date(b.start);
return startTimeA - startTimeB; // This gives us earliest to latest
});
console.log('Events sorted by start time');
// Insert in reverse order with before: true to get chronological order
for (let i = 0; i < sortedEvents.length; i++) {
const event = sortedEvents[i];
console.log(`Processing event ${i + 1}:`, event.subject);
// Format the complete event block content using the user's template
const eventData = formatEventContent(event);
// Insert the main event block
const insertedBlock = await logseq.Editor.insertBlock(
e.uuid,
eventData.mainContent,
{ sibling: true, before: true }
);
console.log('Event block inserted, UUID:', insertedBlock?.uuid);
// Insert any child blocks
if (eventData.childBlocks.length > 0 && insertedBlock?.uuid) {
for (const childContent of eventData.childBlocks) {
const childBlock = await logseq.Editor.insertBlock(
insertedBlock.uuid,
childContent,
{ sibling: false } // Insert as child, not sibling
);
console.log('Child block inserted, UUID:', childBlock?.uuid);
}
}
console.log(`Inserted event: ${event.subject}`);
}
console.log('=== getEvents function completed ===');
} catch (error) {
console.error('Error in getEvents:', error);
logseq.Editor.insertBlock(e.uuid, `Error fetching events: ${error.message}`, {before: true});
}
}
// The main app
const main = async () => {
console.log('Get Outlook Events Plugin Loaded');
// Register plugin settings
logseq.useSettingsSchema([
{
key: "excludeUserName",
type: "string",
default: "",
title: "Excluded User Name",
description: "Enter your name as it is returned by Outlook to exclude it from attendees lists (e.g., 'Simpson, Homer' or 'Diana Prince')"
},
{
key: "apiUrl",
type: "string",
default: "http://localhost:5000",
title: "API URL",
description: "The URL of the Outlook Events API service"
},
{
key: "bracketEvents",
type: "enum",
default: "none",
title: "Add Double Brackets to Event Titles",
description: "Choose when to add [[double brackets]] around event subjects to create Logseq page links\n\nOptions:\n- all: Add brackets to all event titles\n- recurring: Only add brackets to recurring events\n- none: No brackets (default)",
enumChoices: ["all", "recurring", "none"],
enumPicker: "select"
},
{
key: "bracketAttendees",
type: "enum",
default: "all",
title: "Add Double Brackets to Attendee Names",
description: "Choose whether to add [[double brackets]] around attendee names to create Logseq page links",
enumChoices: ["all", "none"],
enumPicker: "select"
},
{
key: "timeFormat",
type: "string",
default: "h:mm a",
title: "Date & Time Format",
description: "Define the format for event times using tokens.\n\nAvailable Tokens:\n- Year: YYYY (2025), YY (25)\n- Month: MMMM (September), MMM (Sep), MM (09), M (9)\n- Day: DD (15), D (15), dddd (Monday), ddd (Mon)\n- Hour: HH (09), H (9), hh (09), h (9)\n- Minute: mm (05), m (5)\n- Second: ss (03), s (3)\n- AM/PM: A (AM), a (am)\n\nExamples:\n- h:mm a → 9:30 AM\n- HH:mm → 09:30\n- ddd, MMM D, h:mm a → Mon, Sep 15, 9:30 AM"
},
{
key: "meetingBaseUrls",
type: "string",
default: "https://teams.microsoft.com,https://zoom.us,https://meet.google.com",
title: "Meeting Base URLs",
description: "Comma-separated list of base URLs to look for meeting links (e.g., 'https://teams.microsoft.com,https://zoom.us,https://meet.google.com')"
},
{
key: "outputFormat",
type: "string",
inputAs: "textarea",
default: "{subject}\\nevent-time:: {time}\\nevent-duration:: {duration}\\nattendees:: {attendees}",
title: "Output Format Template",
description: "Customize the format of event blocks. Available variables:\n\n{subject}, {time}, {duration}, {attendees}, {location}, {description}\n\nAdd ---CHILD--- to start a new child blocks."
},
{
key: "includeEmptyFields",
type: "boolean",
default: false,
title: "Include Empty Fields",
description: "Whether to include fields in the output even when they are empty (e.g., show 'location::' even if no location is set)"
},
{
key: "descriptionMaxLength",
type: "number",
default: 200,
title: "Description Max Length",
description: "Maximum number of characters to include from event descriptions (0 = no limit)"
}
]);
logseq.Editor.registerSlashCommand('Get Events', async (e) => {
const executionBlock = await logseq.App.getCurrentBlock();
getEvents(e, executionBlock);
});
}
logseq.ready(main).catch(console.error);