generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
514 lines (454 loc) · 17.5 KB
/
main.ts
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
import { App, MarkdownView, Notice, Plugin, PluginSettingTab, Setting, requestUrl } from 'obsidian';
import { promises as fs } from 'fs'; // Import fs module
interface XenQuotesSettings {
mySetting: string;
showRibbonIcon: boolean;
enableImageQuote: boolean;
imageDirectory: string;
saveImagesLocally: boolean;
enableOnThisDay: boolean;
selectedCentury: number;
selectedDecade: number;
allCenturies: boolean;
allDecades: boolean;
}
const DEFAULT_SETTINGS: XenQuotesSettings = {
mySetting: 'random',
showRibbonIcon: true,
enableImageQuote: false,
imageDirectory: './images',
saveImagesLocally: false,
enableOnThisDay: false,
selectedCentury: 21,
selectedDecade: 0,
allCenturies: false,
allDecades: false,
}
const cleanText = (text: string) => {
return text.replace(/–/g, '-')
.replace(/\s+/g, ' ')
.trim(); // Remove extra spaces and trim
};
// Helper function to get century from year
const getCentury = (year: number): number => Math.ceil(year / 100);
// Helper function to get decade from year
const getDecade = (year: number): number => Math.floor((year % 100) / 10);
// Helper function to filter events by year
const filterEventsByYear = (events: any[], century: number | null = null, decade: number | null = null): any[] => {
return events.filter(event => {
const yearMatch = event.text.match(/\b\d{4}\b/);
if (!yearMatch) return false;
const year = parseInt(yearMatch[0]);
const eventCentury = getCentury(year);
const eventDecade = getDecade(year);
if (century && decade) {
return eventCentury === century && eventDecade === decade;
} else if (century) {
return eventCentury === century;
} else if (decade) {
return eventDecade === decade;
}
return true;
});
};
// Function to format the date
const formatDate = (dateString: string): string => {
const date = new Date(dateString);
const options: Intl.DateTimeFormatOptions = { month: 'long', day: 'numeric', year: 'numeric' };
return date.toLocaleDateString('en-US', options).replace(/\s+/g, ' ');
};
export default class XenQuotes extends Plugin {
settings: XenQuotesSettings;
ribbonIconEl: HTMLElement | null = null;
async onload() {
await this.loadSettings();
// Add ribbon icon
if (this.settings.showRibbonIcon) {
this.ribbonIconEl = this.addRibbonIcon('dice', 'XenQuotes Plugin', async (evt: MouseEvent) => {
console.log('Ribbon icon clicked');
const activeLeaf = this.app.workspace.getActiveViewOfType(MarkdownView);
if (!activeLeaf) {
console.error('No active Markdown editor found.');
new Notice('No active note to insert quote into.');
return;
}
if (this.settings.enableImageQuote) {
await this.fetchRandomImageQuote(activeLeaf);
} else if (this.settings.enableOnThisDay) {
await this.fetchOnThisDayQuote(activeLeaf);
} else {
await this.fetchAndInsertQuote(activeLeaf);
}
});
if (this.ribbonIconEl) {
this.ribbonIconEl.addClass('xenquotes-ribbon-class');
}
}
// Add command
this.addCommand({
id: 'fetch-quote-of-the-day',
name: 'Fetch Quote of the Day',
callback: async () => {
const activeLeaf = this.app.workspace.getActiveViewOfType(MarkdownView);
if (!activeLeaf) {
new Notice("No active note to insert quote into.");
return;
}
if (this.settings.enableImageQuote) {
await this.fetchRandomImageQuote(activeLeaf);
} else if (this.settings.enableOnThisDay) {
await this.fetchOnThisDayQuote(activeLeaf);
} else {
await this.fetchAndInsertQuote(activeLeaf);
}
}
});
// Add settings tab
this.addSettingTab(new XenQuotesSettingTab(this.app, this));
}
async fetchAndInsertQuote(view: MarkdownView) {
try {
console.log('Fetching quote...');
const response = await requestUrl({ url: "https://zenquotes.io/api/random" });
console.log('Response received:', response.status);
if (response.status === 200) {
const quoteData = JSON.parse(response.text);
if (quoteData && quoteData.length > 0) {
const quote = quoteData[0];
const quoteText = `>[!quote]+ Quote of the Day:\n>\n> ${quote.q}\n>\n> — <cite>${quote.a}</cite> \u270D\uFE0F\n---`;
view.editor.replaceRange(quoteText, view.editor.getCursor());
new Notice("Daily Quote inserted successfully!");
} else {
new Notice("No quote available today.");
}
} else {
new Notice(`Failed to fetch quote. Status: ${response.status}`);
}
} catch (error) {
console.error("Error fetching quote:", error);
new Notice("An error occurred while fetching the quote.");
}
}
async fetchRandomImageQuote(view: MarkdownView) {
try {
const response = await requestUrl({
url: "https://zenquotes.io/api/image",
method: "GET"
});
// Log all available properties
console.log("Response properties:", Object.keys(response));
console.log("Full response:", response);
if (response.status === 200) {
if (this.settings.saveImagesLocally) {
// Get the vault's base path and create an absolute path for the images directory
const basePath = this.app.vault.adapter.getBasePath();
const imageDir = `${basePath}/${this.settings.imageDirectory}`;
const imagePath = `${imageDir}/random-image.jpg`;
// Create the directory if it doesn't exist
try {
await fs.mkdir(imageDir, { recursive: true });
} catch (err) {
console.log("Directory already exists or creation failed:", err);
}
// Try to write the binary data
try {
if (response.arrayBuffer) {
await fs.writeFile(imagePath, Buffer.from(response.arrayBuffer));
// Use a relative path for the markdown link
const relativePath = `${this.settings.imageDirectory}/random-image.jpg`;
const quote = ""; // Placeholder for the quote
const quoteText = `## Daily Image\n\n![Random Image](${relativePath})\n\n ${quote}`;
view.editor.replaceRange(quoteText, view.editor.getCursor());
new Notice("Random image and quote inserted successfully!");
} else {
throw new Error("No binary data available in response");
}
} catch (error) {
console.error("Error saving image:", error);
new Notice("Failed to save the image.");
}
} else {
const quote = ""; // Placeholder for the quote
const quoteText = `## Daily Image & Quote\n\n![Random Image](${response.url})\n\n> ${quote}`;
view.editor.replaceRange(quoteText, view.editor.getCursor());
new Notice("Random image and quote inserted successfully!");
}
} else {
new Notice("Failed to fetch random image and quote.");
}
} catch (error) {
console.error("Error fetching random image and quote:", error);
new Notice("An error occurred while fetching the random image and quote.");
}
}
async fetchOnThisDayQuote(view: MarkdownView) {
const today = new Date();
const month = today.getMonth() + 1; // Months are zero-based
const day = today.getDate();
const century = this.settings.selectedCentury;
const decade = this.settings.selectedDecade;
const url = `https://today.zenquotes.io/api/${month}/${day}`;
console.log("Calling URL:", url);
try {
const response = await requestUrl({ url, method: "GET" });
console.log("API Response Status:", response.status);
if (response.status === 200 && response.json) {
const apiData = response.json;
if (apiData.data) {
let { Events = [], Births = [], Deaths = [] } = apiData.data;
// Apply filters based on settings
if (this.settings.allCenturies && this.settings.allDecades) {
// No filtering needed, show all events
} else if (this.settings.allCenturies) {
// Filter only by decade
Events = filterEventsByYear(Events, null, decade);
Births = filterEventsByYear(Births, null, decade);
Deaths = filterEventsByYear(Deaths, null, decade);
} else if (this.settings.allDecades) {
// Filter only by century
Events = filterEventsByYear(Events, century, null);
Births = filterEventsByYear(Births, century, null);
Deaths = filterEventsByYear(Deaths, century, null);
} else if (century && decade) {
// Filter by both century and decade
Events = filterEventsByYear(Events, century, decade);
Births = filterEventsByYear(Births, century, decade);
Deaths = filterEventsByYear(Deaths, century, decade);
}
console.log("API Response Data:", apiData);
let currentYear = today.getFullYear(); // Get the current year
let output = `## On This Day ${formatDate(`${month}/${day}/${currentYear}`)}\n\n`;
if (Events && Events.length) {
output += "### Events:\n";
Events.forEach(event => {
output += `- [${cleanText(event.text)}](https://wikipedia.org/wiki/${cleanText(event.text)})\n`;
});
}
if (Births && Births.length) {
output += "\n### Births:\n";
Births.forEach(birth => {
output += `- [${cleanText(birth.text)}](https://wikipedia.org/wiki/${cleanText(birth.text)})\n`;
});
}
if (Deaths && Deaths.length) {
output += "\n### Deaths:\n";
Deaths.forEach(death => {
output += `- [${cleanText(death.text)}](https://wikipedia.org/wiki/${cleanText(death.text)})\n`;
});
}
if (!Events.length && !Births.length && !Deaths.length) {
output += "No events found for the selected time period.\n";
}
view.editor.replaceRange(output, view.editor.getCursor());
new Notice("On This Day information inserted successfully!");
} else {
console.error("Unexpected data structure:", apiData);
new Notice("Received unexpected data structure from API.");
}
} else {
new Notice(`Failed to fetch On This Day information. Status: ${response.status}`);
}
} catch (error) {
console.error("Error fetching On This Day information:", error);
new Notice("An error occurred while fetching the On This Day information.");
}
}
onunload() {
if (this.ribbonIconEl) {
this.ribbonIconEl.remove();
}
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
//@PluginSettingTab
class XenQuotesSettingTab extends PluginSettingTab {
plugin: XenQuotes;
constructor(app: App, plugin: XenQuotes) {
super(app, plugin);
this.plugin = plugin;
}
display(container: HTMLElement) {
const {containerEl} = this;
containerEl.empty();
const announcementEl = containerEl.createDiv('announcement');
announcementEl.addClass('announcement');
const messageEl = announcementEl.createEl('p');
messageEl.empty();
messageEl.createSpan({
text: 'This plugin is currently limited to fetching random or daily quotes, historical onthisday data and images. You can also fetch quotes from specific authors! ' +
'However, this feature requires a subscription to the ZenQuotes API. If you\'d like to help make this feature available to everyone, and support further development such as formatting the quote & tags, ' +
'please consider supporting the project by:'
});
const bulletList = messageEl.createEl('ul');
const links = [
{
text: '⭐ Starring our repository on ',
link: 'https://github.com/ubuntpunk/obsidian-xenquotes',
linkText: 'GitHub'
},
{
text: '💝 Funding development and unlocking features for the entire community via ',
link: 'https://buymeacoffee.com/ubuntupunk',
linkText: 'buymeacoffee.com'
},
{
text: '🤝 Joining our ',
link: 'https://github.com/ubuntupunk/obsidian-xenquotes/discussions',
linkText: 'community discussions on GitHub'
}
];
links.forEach(({ text, link, linkText }) => {
const li = bulletList.createEl('li');
li.createSpan({ text });
li.createEl('a', { text: linkText, href: link });
});
new Setting(containerEl)
.setName('Quote Mode')
.setDesc('Choose how you want to fetch quotes')
.addDropdown(dropdown => dropdown
.addOption('random', 'Random Quote')
.addOption('today', 'Quote of the Day')
.addOption('author', 'By Author (Coming Soon)')
.addOption('on-this-day', 'On This Day Quote')
.setValue(this.plugin.settings.mySetting)
.onChange(async (value) => {
this.plugin.settings.mySetting = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Show Ribbon Icon')
.setDesc('Toggle the visibility of the ribbon icon')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.showRibbonIcon)
.onChange(async (value) => {
this.plugin.settings.showRibbonIcon = value;
await this.plugin.saveSettings();
if (value) {
if (!this.plugin.ribbonIconEl) {
this.plugin.ribbonIconEl = this.plugin.addRibbonIcon('dice', 'XenQuotes Plugin', async (evt: MouseEvent) => {
console.log('Ribbon icon clicked');
const activeLeaf = this.plugin.app.workspace.getActiveViewOfType(MarkdownView);
if (!activeLeaf) {
console.error('No active Markdown editor found.');
new Notice('No active note to insert quote into.');
return;
}
if (this.plugin.settings.enableImageQuote) {
await this.plugin.fetchRandomImageQuote(activeLeaf);
} else if (this.plugin.settings.enableOnThisDay) {
await this.plugin.fetchOnThisDayQuote(activeLeaf);
} else {
await this.plugin.fetchAndInsertQuote(activeLeaf);
}
});
this.plugin.ribbonIconEl.addClass('xenquotes-ribbon-class');
}
} else {
if (this.plugin.ribbonIconEl) {
this.plugin.ribbonIconEl.remove();
this.plugin.ribbonIconEl = null;
}
}
}));
new Setting(containerEl)
.setName('Enable Random Image and Quote')
.setDesc('Toggle to fetch a random image along with the quote.')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.enableImageQuote)
.onChange(async (value) => {
this.plugin.settings.enableImageQuote = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Image Directory')
.setDesc('Directory to save images locally')
.addText(text => text
.setPlaceholder('./images')
.setValue(this.plugin.settings.imageDirectory)
.onChange(async (value) => {
this.plugin.settings.imageDirectory = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Save Images Locally')
.setDesc('Toggle to save images locally')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.saveImagesLocally)
.onChange(async (value) => {
this.plugin.settings.saveImagesLocally = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Enable On This Day Quotes')
.setDesc('Fetch quotes from historical data based on the current date.')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.enableOnThisDay)
.onChange(async (value) => {
this.plugin.settings.enableOnThisDay = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Custom Decade')
.setDesc('Enter a custom decade (0-9)')
.addText(text => text
.setPlaceholder('Enter decade')
.setValue(this.plugin.settings.selectedDecade.toString())
.onChange(async (value) => {
const decadeValue = parseInt(value);
if (!isNaN(decadeValue) && decadeValue >= 0 && decadeValue <= 9) {
this.plugin.settings.selectedDecade = decadeValue;
await this.plugin.saveSettings();
}
}));
new Setting(containerEl)
.setName('Custom Century')
.setDesc('Enter the century for On This Day quotes (e.g., 21 for 21st century)')
.addText(text => text
.setPlaceholder('Enter century')
.setValue(this.plugin.settings.selectedCentury.toString())
.onChange(async (value) => {
const centuryValue = parseInt(value);
if (!isNaN(centuryValue) && centuryValue > 0) {
this.plugin.settings.selectedCentury = centuryValue;
await this.plugin.saveSettings();
}
}));
new Setting(containerEl)
.setName('All Centuries')
.setDesc('Fetch quotes from all centuries')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.allCenturies)
.onChange(async (value) => {
this.plugin.settings.allCenturies = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('All Decades')
.setDesc('Fetch quotes from all decades')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.allDecades)
.onChange(async (value) => {
this.plugin.settings.allDecades = value;
await this.plugin.saveSettings();
}));
const attribution = containerEl.createEl('div', { cls: 'xenquotes-attribution' });
attribution.createSpan({ text: 'Inspiration quotes, images & historical data provided by ' });
attribution.createEl('a', {
text: 'ZenQuotes API',
href: 'https://zenquotes.io/',
attr: { target: '_blank' }
});
attribution.createSpan({ text: ' • Developed by ' });
attribution.createEl('a', {
text: 'ubuntupunk',
href: 'https://github.com/ubuntupunk',
attr: { target: '_blank' }
});
containerEl.appendChild(attribution);
}
}