-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
713 lines (602 loc) · 21.3 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
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting, TFile } from 'obsidian';
import * as yaml from 'js-yaml';
import moment from "moment"; // A namespace-style import cannot be called or constructed, and will cause a failure at runtime.
import * as dbQueries from "./db-queries";
import { ExportData } from "./export-data";
import { ExportWizardModal } from "./export-wizard";
import { CustomNotice } from "./custom-notice";
import * as fs from "fs";
import * as path from "path";
const SERVICE_NAME_ENCRYPTION = "LabBookExpLogSettings";
interface LabBookExpLogSettings {
dbUser: string;
dbPassword: string;
dbServer: string;
dbName: string;
dbEncrypt: boolean;
dbTrustServerCertificate: boolean;
inputDateFormat: string;
inputTimeFormat: string;
}
const DEFAULT_SETTINGS: LabBookExpLogSettings = {
dbUser: '',
dbPassword: '',
dbServer: 'localhost',
dbName: 'ExpLog',
dbEncrypt: false,
dbTrustServerCertificate: true,
inputDateFormat: "YYYY-MM-DD",
inputTimeFormat: "HH:mm"
}
function catchLabBookExpLogPluginErrors(target: any, propertyKey: string, descriptor: PropertyDescriptor): void {
const originalMethod = descriptor.value;
descriptor.value = async function (...args: any[]) {
try {
await originalMethod.apply(this, args);
} catch (error) {
console.error(`Error in ${propertyKey}:`, error);
new Notice(`An error occurred: ${error.message}`);
}
};
}
export default class LabBookExpLogPlugin extends Plugin {
_settings: LabBookExpLogSettings;
_dbConfig: dbQueries.DBConfig;
_keytar: typeof import("keytar") | null = null;
public async onload() {
// Resolve the plugin root directory
const vaultBasePath = (this.app.vault.adapter as any).basePath;
const pluginRoot = path.join(vaultBasePath, ".obsidian/plugins/labbook-explog-fmi");
const keytarPath = path.join(pluginRoot, "node_modules/keytar/build/Release/keytar.node");
console.log("Vault Base Path:", vaultBasePath);
console.log("Plugin Root:", pluginRoot);
console.log("Keytar Path:", keytarPath);
// Load keytar first (used below when loading settings)
if (fs.existsSync(keytarPath)) {
try {
this._keytar = require(keytarPath);
console.log("Keytar loaded successfully:", this._keytar);
} catch (error) {
console.error("Failed to load keytar:", error);
this._keytar = null;
}
} else {
console.error("Keytar.node file not found at:", keytarPath);
}
await this.loadSettings();
await this.updateDBConfig();
this.addRibbonIcon("table", "Add ExpLog Table", async () => {
await this.createExpLogTable();
}).addClass("my-addtable-icon");
this.addRibbonIcon("database", "Export ExpLog Database", async () => {
await this.exportExpLogData();
}).addClass("my-exportdatabase-icon");
this.addSettingTab(new LabBookSettingTab(this.app, this));
}
public onunload() {
}
private async savePassword(username: string, password: string): Promise<void> {
await this._keytar!.setPassword(SERVICE_NAME_ENCRYPTION, username, password);
}
private async getPassword(username: string): Promise<string | null> {
return await this._keytar!.getPassword(SERVICE_NAME_ENCRYPTION, username);
}
@catchLabBookExpLogPluginErrors
private async loadSettings() {
this._settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
if (this._keytar && this._settings.dbUser) {
const password = await this.getPassword(this._settings.dbUser);
if (password) {
this._settings.dbPassword = password!;
}
}
}
@catchLabBookExpLogPluginErrors
public async saveSettings() {
const password = this._settings.dbPassword;
if (this._keytar && password) {
if (this._settings.dbUser) {
// Persist password with keytar for specific user
await this.savePassword(this._settings.dbUser, password);
}
else {
new CustomNotice("Database Password has not been saved!\nIt is only persisted together with the Database User.", "warning-notice");
}
this._settings.dbPassword = ""; // Reset (only persisted by keytar)
}
await this.saveData(this._settings);
if (this._keytar && password) {
// Keep password in memory only
this._settings.dbPassword = password;
}
await this.updateDBConfig();
}
private async updateDBConfig() {
this._dbConfig = {
user: this._settings.dbUser || "",
password: this._settings.dbPassword || "",
server: this._settings.dbServer || "",
database: this._settings.dbName || "",
encrypt: this._settings.dbEncrypt ?? true,
trustServerCertificate: this._settings.dbTrustServerCertificate ?? true,
};
// Optional: Validate the configuration
if (!this._dbConfig.user || !this._dbConfig.password || !this._dbConfig.server) {
new Notice("DB Config is incomplete. Ensure all required settings are provided.");
}
}
@catchLabBookExpLogPluginErrors
private async createExpLogTable() {
const file = this.app.workspace.getActiveFile();
if (!file) {
new Notice("No active file to insert the table.");
return;
}
// Check/get AnimalID from metadata
const metadata = this.app.metadataCache.getFileCache(file);
if (!metadata?.frontmatter?.AnimalID) {
const modal = new QueryAnimalModal(this.app, this._dbConfig, this);
const animalID = await modal.openWithPromise();
if (animalID) {
await this.updateYamlMetadata(file, { AnimalID: animalID });
} else {
new Notice("No animal selected.");
return;
}
}
// Define table headers
const headers = this.getExpLogTableHeaders();
const fileContent = await this.app.vault.read(file);
// Check if any matching table already exists
if (this.matchingTableExist(fileContent, headers)) {
new Notice("A table with matching headers already exists in this file.");
return;
}
// Create and insert the table
const newTable = this.generateTableWithHeaders(headers);
await this.insertTableIntoFile(file, fileContent, newTable);
}
@catchLabBookExpLogPluginErrors
private async exportExpLogData() {
try {
const file = this.app.workspace.getActiveFile();
if (!file) {
new CustomNotice("No active file to export data.", "warning-notice");
return;
}
// Check/get AnimalID from metadata
let animalID: string | null = null;
const metadata = this.app.metadataCache.getFileCache(file);
if (!metadata?.frontmatter?.AnimalID) {
const modal = new QueryAnimalModal(this.app, this._dbConfig, this);
animalID = await modal.openWithPromise();
if (animalID) {
await this.updateYamlMetadata(file, { AnimalID: animalID });
} else {
new CustomNotice("No animal selected.", "warning-notice");
return;
}
}
else {
animalID = metadata.frontmatter.AnimalID as string;
}
if (!animalID) {
new CustomNotice("No AnimalID found in properties.", "warning-notice");
return;
}
const animalExists = await dbQueries.existsAnimal(this._dbConfig, animalID);
if (!animalExists) {
new CustomNotice("Animal not found in database.", "warning-notice");
return;
}
// Some initial validations
const exportData = await this.extractExpLogData();
if (!exportData || exportData.length === 0) {
new CustomNotice("No data to be exported.", "warning-notice");
return;
}
const hasInvalidData = exportData.some(p => p.isInvalid());
if (hasInvalidData) {
const invalidRows: string[] = [];
for (let i = 0; i < exportData.length; i++) {
const data = exportData[i];
if (data.isInvalid()) {
invalidRows.push(data.position.toString());
}
}
const invalidRowsOutput = invalidRows.join(", ");
new CustomNotice(`There is invalid data!\n\nPlease make sure to provide correct data for Date, Time, StackID, ExpID and SiteID. Empty rows are skipped by default.\n\nRows: ${invalidRowsOutput}`, "warning-notice");
return;
}
const hasIncompleteData = exportData.some(p => !p.isComplete());
if (hasIncompleteData) {
const incompleteRows: string[] = [];
for (let i = 0; i < exportData.length; i++) {
const data = exportData[i];
if (!data.isComplete()) {
incompleteRows.push(data.position.toString());
}
}
const incompleteRowsOutput = incompleteRows.join(", ");
new CustomNotice(`There is incomplete data!\n\nPlease make sure to provide Date, Time, StackID, ExpID and SiteID. Empty rows are skipped by default.\n\nRows: ${incompleteRowsOutput}`, "warning-notice");
return;
}
const actualExportData = exportData.filter(p => !p.isEmpty());
if (!actualExportData || actualExportData.length === 0) {
new CustomNotice("No data to be exported.", "warning-notice");
return;
}
console.log(`Actual ExportData: ${actualExportData}`);
const exportModal = new ExportWizardModal(this.app, this._dbConfig, animalID, actualExportData);
const errorResult = await exportModal.openWithPromise();
if (!errorResult) {
new CustomNotice(`Data for '${animalID}' has been exported successfully.`, "success-notice");
}
else {
new CustomNotice(`Sorry, data for '${animalID}' has not been exported.`, "warning-notice");
new CustomNotice(errorResult, "error-notice", 10000);
}
}
catch (err) {
console.error("Failed to export:", err);
new CustomNotice(err.message, "error-notice");
}
}
private async updateYamlMetadata(file: TFile, newMetadata: Record<string, any>): Promise<void> {
const content = await this.app.vault.read(file);
// Extract existing YAML front matter
const frontMatterRegex = /^---\n([\s\S]*?)\n---/;
const match = frontMatterRegex.exec(content);
const existingMetadata = match ? await this.parseYaml(match[1]) : {};
// Merge new metadata with existing metadata
const updatedMetadata = { ...existingMetadata, ...newMetadata };
const updatedYaml = `---\n${await this.stringifyYaml(updatedMetadata)}\n---`;
// Replace or prepend YAML front matter
const updatedContent = match
? content.replace(frontMatterRegex, updatedYaml)
: `${updatedYaml}\n\n${content}`;
await this.app.vault.modify(file, updatedContent);
}
private async parseYaml(content: string): Promise<Record<string, any>> {
try {
return yaml.load(content) as Record<string, any>;
} catch (err) {
console.error("Failed to parse YAML:", err);
return {};
}
}
private async stringifyYaml(data: Record<string, any>): Promise<string> {
try {
return yaml.dump(data);
} catch (err) {
console.error("Failed to stringify YAML:", err);
return "";
}
}
private matchingTableExist(content: string, headers: string[]): boolean {
const headerRegex = new RegExp(
`\\|\\s*${headers.join("\\s*\\|\\s*")}\\s*\\|`
);
return headerRegex.test(content);
}
private getExpLogTableHeaders(): string[] {
return ["Date", "Time", "StackID", "ExpID", "SiteID", "Comment"];
}
private generateTableWithHeaders(headers: string[]): string {
const headerRow = `| ${headers.join(" | ")} |`;
const separatorRow = `| ${headers.map(() => "---").join(" | ")} |`;
// Generate a blank row below the headers
const blankRow = `| ${headers.map(() => " ").join(" | ")} |`;
return `${headerRow}\n${separatorRow}\n${blankRow}`;
}
private async insertTableIntoFile(file: TFile, content: string, table: string) {
const updatedContent = `${content}\n\n${table}`;
await this.app.vault.modify(file, updatedContent);
}
private async extractExpLogData(): Promise<ExportData[]> {
const file = this.app.workspace.getActiveFile();
if (!file) {
new Notice("No active file.");
return[];
}
const headers = this.getExpLogTableHeaders();
const fileContent = await this.app.vault.read(file);
let spinner = null;
try {
// Configure spinner
const mainElement = this.app.workspace.containerEl;
spinner = this.showSpinner(mainElement);
const tableData = await this.extractTableData(fileContent, headers);
if (tableData && tableData.length > 0) {
const dateFormat = this._settings.inputDateFormat + " " + this._settings.inputTimeFormat;
let exportDataArray: ExportData[] = [];
let position = 1;
tableData.forEach(row => {
let data = new ExportData(position);
position++;
data.origStringLogDate = row["Date"];
data.origStringLogTime = row["Time"];
data.origStringStackID = row["StackID"];
data.origStringExpID = row["ExpID"];
data.origStringSiteID = row["SiteID"];
data.comment = row["Comment"];
if (data.origStringLogDate && data.origStringLogTime) {
var dateInput = data.origStringLogDate + " " + data.origStringLogTime;
const dateParsed = moment(dateInput, dateFormat, true); // 'true' ensures strict parsing
if (dateParsed.isValid()) {
data.logDateTime = dateParsed.toDate();
}
}
if (data.origStringStackID) {
const num = parseInt(data.origStringStackID, 10);
if (!isNaN(num)) {
data.stackID = num;
}
}
if (data.origStringExpID) {
const num = parseInt(data.origStringExpID, 10);
if (!isNaN(num)) {
data.expID = num;
}
}
if (data.origStringSiteID) {
const num = parseInt(data.origStringSiteID, 10);
if (!isNaN(num)) {
data.siteID = num;
}
}
if (!data.isEmpty()) {
exportDataArray.push(data);
}
});
return exportDataArray;
}
}
finally {
// Reset spinner
if (spinner) {
this.hideSpinner(spinner);
}
}
return[];
}
private async extractTableData(content: string, headers: string[]): Promise<{ [key: string]: string }[]> {
// Create a regex to match the table headers
const headerRegex = new RegExp(
`^\\|\\s*${headers.join("\\s*\\|\\s*")}\\s*(\\|.*)?\\|\\s*$`,
"m"
);
// Find the header row in the content
const headerMatch = content.match(headerRegex);
if (!headerMatch) {
return []; // No matching header found
}
// Find the position of the matching header
const headerLine = headerMatch.index!;
const tableContent = content.substring(headerLine);
// Split the table into lines
const lines = tableContent.split("\n");
// Verify the second line is the separator (e.g., | --- | --- |)
const separatorRegex = new RegExp(
`^\\|\\s*${headers.map(() => "-+").join("\\s*\\|\\s*")}\\s*(\\|.*)?\\|\\s*$`
);
if (!separatorRegex.test(lines[1])) {
return []; // No valid table separator found
}
// Extract rows below the header and separator
const dataRows: { [key: string]: string }[] = [];
for (let i = 2; i < lines.length; i++) {
const row = lines[i].trim();
if (!row || !row.startsWith("|") || !row.endsWith("|")) {
break; // Stop when no more valid table rows are found
}
// Split the row into cells
const cells = row.split("|").map((cell) => cell.trim());
// Ensure that there are at least as many cells as the number of headers
if (cells.length - 2 < headers.length) {
continue;
}
// Map only the cells corresponding to the headers
const rowData: { [key: string]: string } = {};
headers.forEach((header, index) => {
rowData[header] = cells[index + 1] || ""; // Use an empty string if the cell is missing
});
dataRows.push(rowData);
}
return dataRows;
}
showSpinner(containerEl: HTMLElement): HTMLElement {
const spinner = containerEl.createDiv({ cls: "loading-spinner" });
return spinner;
}
hideSpinner(spinner: HTMLElement) {
spinner.remove();
}
}
class QueryAnimalModal extends Modal {
_plugin: LabBookExpLogPlugin;
_dbConfig: dbQueries.DBConfig
private _resolvePromise: (value: string | null) => void; // Function to resolve the Promise
private _result: string | null = null; // To store the result
private _animalDropdown: any; // Used for referencing by the other dropdown (PI)
constructor(app: App, dbConfig: dbQueries.DBConfig, plugin: LabBookExpLogPlugin) {
super(app);
this._dbConfig = dbConfig;
this._plugin = plugin;
}
// Method to open the modal and return a Promise
openWithPromise(): Promise<string | null> {
return new Promise((resolve) => {
this._resolvePromise = resolve; // Store the resolve function
this.open();
});
}
onOpen() {
const { contentEl } = this;
const modalContainer = contentEl.parentElement;
if (modalContainer) {
modalContainer.addClass("my-queryanimal-modal");
}
contentEl.createEl('h2', { text: 'Search Animal' });
new Setting(contentEl)
.setName("PI")
//.setDesc("Choose a PI from the list")
.addDropdown(async (dropdown) => {
dropdown.addOption("", "Please select");
try {
// Fetch the list of PIs
const piList = await dbQueries.queryPIs(this._dbConfig);
// Populate the dropdown with PIs
if (piList) {
piList.forEach((pi) => {
dropdown.addOption(pi, pi);
});
}
} catch (err) {
console.error("Failed to load PIs:", err);
dropdown.addOption("error", "Error loading PIs");
new CustomNotice(err.message, "error-notice");
}
// Handle dropdown value change
dropdown.onChange(async (value) => {
if (value) {
console.log(`Selected PI: ${value}`);
const animalIDList = await dbQueries.queryAnimals(this._dbConfig, value);
// Reset and populate the second dropdown
this._animalDropdown.selectEl.innerHTML = ""; // Clear previous options
this._animalDropdown.addOption("", "Please select");
animalIDList.forEach((animalID) => {
this._animalDropdown.addOption(animalID, animalID);
});
} else {
console.log("No PI selected.");
// Reset the second dropdown
this._animalDropdown.selectEl.innerHTML = ""; // Clear all options
this._animalDropdown.addOption("", "Please select");
}
});
});
new Setting(contentEl)
.setName("Animal")
.addDropdown(async (dropdown) => {
dropdown.addOption("", "Please select");
this._animalDropdown = dropdown; // Assign for easy reference
// Handle dropdown value change
dropdown.onChange(async (value) => {
if (value) {
console.log(`Selected Animal: ${value}`);
this._result = value;
} else {
console.log("No Animal selected.");
this._result = null;
}
});
});
new Setting(contentEl)
.addButton(button => {
button
.setButtonText('Select')
.setCta()
.onClick(async () => {
// Check if this.result` is set
if (!this._result) {
new Notice("Please select an animal before proceeding, or cancel by closing this window.");
return; // Prevent closing the modal
}
this.close();
});
});
}
onClose() {
const { contentEl } = this;
contentEl.empty(); // Clean up modal
this._resolvePromise(this._result); // Resolve the Promise with the result
}
}
class LabBookSettingTab extends PluginSettingTab {
_plugin: LabBookExpLogPlugin;
constructor(app: App, plugin: LabBookExpLogPlugin) {
super(app, plugin);
this._plugin = plugin;
}
display(): void {
const {containerEl} = this;
containerEl.empty();
containerEl.createEl('h2', { text: 'Database Settings' });
new Setting(containerEl)
.setName('Database Server')
.addText(text => text
.setPlaceholder('localhost')
.setValue(this._plugin._settings.dbServer)
.onChange(async (value) => {
this._plugin._settings.dbServer = value;
await this._plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Database Name')
.addText(text => text
.setPlaceholder('ExpLog')
.setValue(this._plugin._settings.dbName)
.onChange(async (value) => {
this._plugin._settings.dbName = value;
await this._plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Database User')
.addText(text => text
.setPlaceholder('dbuser')
.setValue(this._plugin._settings.dbUser)
.onChange(async (value) => {
this._plugin._settings.dbUser = value;
await this._plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Database Password')
.addText(text => {
text
.setPlaceholder('password')
.setValue(this._plugin._settings.dbPassword)
.onChange(async (value) => {
this._plugin._settings.dbPassword = value;
await this._plugin.saveSettings();
});
// Set the input type to 'password' to mask the input
text.inputEl.setAttribute('type', 'password');
});
new Setting(containerEl)
.setName('Encrypt')
.addToggle(text => text
.setValue(this._plugin._settings.dbEncrypt)
.onChange(async (value) => {
this._plugin._settings.dbEncrypt = value;
await this._plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Trust Server Certificate')
.addToggle(text => text
.setValue(this._plugin._settings.dbTrustServerCertificate)
.onChange(async (value) => {
this._plugin._settings.dbTrustServerCertificate = value;
await this._plugin.saveSettings();
}));
containerEl.createEl('h2', { text: 'Other Settings' });
new Setting(containerEl)
.setName('Input Date Format')
.addText(text => text
.setPlaceholder('YYYY-MM-DD')
.setValue(this._plugin._settings.inputDateFormat)
.onChange(async (value) => {
this._plugin._settings.inputDateFormat = value;
await this._plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Input Time Format')
.addText(text => text
.setPlaceholder('HH:mm')
.setValue(this._plugin._settings.inputTimeFormat)
.onChange(async (value) => {
this._plugin._settings.inputTimeFormat = value;
await this._plugin.saveSettings();
}));
}
}