generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 6
/
methods.ts
520 lines (478 loc) · 14.7 KB
/
methods.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
import type BridgePlugin from './main';
import {
App,
CachedMetadata,
EmbedCache,
FileSystemAdapter,
FrontMatterCache,
getAllTags,
getLinkpath,
LinkCache,
Notice,
parseFrontMatterAliases,
TAbstractFile,
TFile,
TFolder,
} from 'obsidian';
import type {
backlinks,
extendedFrontMatterCache,
extendedMetadataCache,
file,
folder,
links,
Metadata,
tagCache,
tagNumber,
} from './interfaces';
import { writeFileSync } from 'fs';
//@ts-expect-error, there is no export, but this is how the esbuild inline plugin works
import Worker from './workers/metadata.worker';
import { getAllExceptMd } from './utils';
function getAll(allFiles: TAbstractFile[]) {
const folders: folder[] = [];
const files: file[] = [];
for (const TAFile of allFiles) {
if (TAFile instanceof TFolder) {
folders.push({ name: TAFile.name, relativePath: TAFile.path });
} else if (TAFile instanceof TFile) {
files.push({
name: TAFile.name,
basename: TAFile.basename,
relativePath: TAFile.path,
});
}
}
return { folders, files };
}
export default class Methods {
app: App;
plugin: BridgePlugin;
constructor(plugin: BridgePlugin, app: App) {
this.plugin = plugin;
this.app = app;
}
// https://github.com/tillahoffmann/obsidian-jupyter/blob/e1e28db25fd74cd16844b37d0fe2eda9c3f2b1ee/main.ts#L175
getAbsolutePath(fileName: string): string {
let basePath;
// base path
if (this.app.vault.adapter instanceof FileSystemAdapter) {
basePath = this.app.vault.adapter.getBasePath();
} else {
throw new Error('Cannot determine base path.');
}
// relative path
const relativePath = `${this.app.vault.configDir}/plugins/metadata-extractor/${fileName}`;
// absolute path
return `${basePath}/${relativePath}`;
}
/**
*
* @param currentCache - the object from Obsidian that contains all the metadata for the current file
* @returns - lower cased tags, duplicates are removed, stripped the #
*/
getUniqueTags(currentCache: CachedMetadata): string[] {
let currentTags: string[] = [];
const tags = getAllTags(currentCache);
if (tags) {
currentTags = tags;
}
currentTags = currentTags.map((tag) => tag.slice(1).toLowerCase());
// remove duplicate tags in file
currentTags = Array.from(new Set(currentTags));
return currentTags;
}
writeAllExceptMd(fileName: string) {
let path = this.plugin.settings.allExceptMdPath;
// only change path not to be the plugin folder if the user entered a custom path
if (!this.plugin.settings.allExceptMdPath) {
path = this.getAbsolutePath(fileName);
}
const allFiles = this.app.vault.getAllLoadedFiles();
const { folders, files } = getAll(allFiles);
const foldersAndFiles = getAllExceptMd(folders, files);
writeFileSync(path, JSON.stringify(foldersAndFiles, null, 2));
if (this.plugin.settings.consoleLog) {
console.log(
'Metadata Extractor plugin: wrote the allExceptMd JSON file'
);
}
}
writeCanvases(fileName: string) {
let path = this.plugin.settings.canvasPath;
// only change path not to be the plugin folder if the user entered a custom path
if (!this.plugin.settings.canvasPath) {
path = this.getAbsolutePath(fileName);
}
const allFiles = this.app.vault.getAllLoadedFiles();
const files: file[] = [];
for (const TAFile of allFiles) {
if (TAFile instanceof TFile) {
if (TAFile.extension === 'canvas') {
files.push({
name: TAFile.name,
basename: TAFile.basename,
relativePath: TAFile.path,
});
}
}
}
writeFileSync(path, JSON.stringify(files, null, 2));
if (this.plugin.settings.consoleLog) {
console.log(
'Metadata Extractor plugin: wrote the canvas JSON file'
);
}
}
createCleanFrontmatter(
frontmatter: FrontMatterCache
): extendedFrontMatterCache {
const newFrontmatter = Object.assign({}, frontmatter);
if (newFrontmatter.aliases) {
delete newFrontmatter.aliases;
}
if (newFrontmatter.tags) {
delete newFrontmatter.tags;
}
return newFrontmatter as extendedFrontMatterCache;
}
/**
*
* @param fileName - the filename for the file
* If another path is set (tagPath) in the settings, then it will use that path
*/
writeTagsToJSON(fileName: string): void {
// if there are no tags in the vault, exit
const tags = (
this.app.metadataCache as extendedMetadataCache
).getTags();
if (Object.keys(tags).length === 0) {
const error = 'There are no tags in your vault.';
if (this.plugin.settings.consoleLog) {
console.log(error);
return;
} else {
return;
}
}
let path = this.plugin.settings.tagPath;
// only set the path to the plugin folder if no other path is specified
if (!this.plugin.settings.tagPath) {
path = this.getAbsolutePath(fileName);
}
const tagsCache: tagCache[] = [];
for (const tfile of this.app.vault.getMarkdownFiles()) {
let currentCache!: CachedMetadata;
const cache = this.app.metadataCache.getFileCache(tfile);
if (cache) {
currentCache = cache;
}
const relativePath: string = tfile.path;
//let displayName: string = this.app.metadataCache.fileToLinktext(tfile, tfile.path, false);
const currentTags: string[] = this.getUniqueTags(currentCache);
if (currentTags.length !== 0) {
tagsCache.push({
name: relativePath,
tags: currentTags,
});
}
}
// own version of this.app.metadataCache.getTags()
// it doesn't include subtags if there is only one tag/subtag/subsubtag
// (Obsidian would return tag, tag/subtag, tag/subtag/subtag for .getTags())
const allTagsFromCache: string[][] = tagsCache.map((element) => {
return element.tags;
});
const reducedAllTagsFromCache = allTagsFromCache.reduce(
(acc, tagArray) => {
return acc.concat(tagArray.map((tag) => tag.toLowerCase()));
}
);
const uniqueAllTagsFromCache = Array.from(
new Set(reducedAllTagsFromCache)
);
//private method
const numberOfNotesWithTag = (
this.app.metadataCache as extendedMetadataCache
).getTags();
// Obsidian doesn't consistently lower case the tags (it's a feature, it shows the most used version)
// used to get a tag count; cleaning up is necessary for matching to own cleaned up version
const tagsWithCount: tagNumber = {};
for (const [key, value] of Object.entries(numberOfNotesWithTag)) {
const newKey: string = key.slice(1).toLowerCase();
tagsWithCount[newKey] = value as number;
}
// what will be written to disk
const tagToFile: {
tag: string;
tagCount: number;
relativePaths: string[] | string;
}[] = [];
for (const tag of uniqueAllTagsFromCache) {
const fileNameArray: string[] = [];
// see which files contain the current tag
for (const file of tagsCache) {
if (file.tags.contains(tag)) {
fileNameArray.push(file.name);
}
}
const numberOfNotes: number = tagsWithCount[tag];
tagToFile.push({
tag: tag,
tagCount: numberOfNotes,
relativePaths: fileNameArray,
});
}
writeFileSync(path, JSON.stringify(tagToFile, null, 2));
if (this.plugin.settings.consoleLog) {
console.log(
'Metadata Extractor plugin: wrote the tagToFile JSON file'
);
}
}
writeCacheToJSON(fileName: string) {
let path = this.plugin.settings.metadataPath;
// only set the path to the plugin folder if no other path is specified
if (!this.plugin.settings.metadataPath) {
path = this.getAbsolutePath(fileName);
}
let metadataCache: Metadata[] = [];
for (const tfile of this.app.vault.getMarkdownFiles()) {
const displayName = tfile.basename;
const relativeFilePath: string = tfile.path;
let currentCache!: CachedMetadata;
const cache = this.app.metadataCache.getFileCache(tfile);
if (cache) {
currentCache = cache;
} else {
if (this.plugin.settings.consoleLog) {
console.log(`No cache for file: ${tfile.path}`);
}
continue;
}
let currentAliases: string[];
const currentHeadings: { heading: string; level: number }[] = [];
//@ts-expect-error, object needs to be initialized, but values will only be known later
const metaObj: Metadata = {};
metaObj.fileName = displayName;
metaObj.relativePath = relativeFilePath;
const currentTags = this.getUniqueTags(currentCache);
if (currentTags) {
if (currentTags.length > 0) {
metaObj.tags = currentTags;
}
}
if (currentCache.frontmatter) {
metaObj.frontmatter = this.createCleanFrontmatter(
currentCache.frontmatter
);
//@ts-expect-error, could return null so can't be assigned to current aliases,
// check for null is done later
currentAliases = parseFrontMatterAliases(
currentCache.frontmatter
);
if (currentAliases) {
if (currentAliases.length > 0) {
metaObj.aliases = currentAliases;
}
}
}
if (currentCache.headings) {
currentCache.headings.forEach((headings) => {
currentHeadings.push({
heading: headings.heading,
level: headings.level,
});
});
metaObj.headings = currentHeadings;
}
const linkMetaObj = calculateLinks(
currentCache,
metaObj,
relativeFilePath,
displayName,
this.app,
tfile
);
Object.assign(metaObj, linkMetaObj);
if (Object.keys(metaObj).length > 0) {
metadataCache.push(metaObj);
}
}
//backlinks
const backlinkObj: backlinks[] = [];
const worker = Worker();
worker.postMessage([metadataCache, backlinkObj]);
worker.onerror = (event: any) => {
new Notice('Something went wrong with the backlinks calculation.');
};
worker.onmessage = (event: any) => {
metadataCache = event.data;
writeFileSync(path, JSON.stringify(metadataCache, null, 2));
if (this.plugin.settings.consoleLog) {
console.log(
'Metadata Extractor plugin: wrote the metadata JSON file'
);
}
// writeFileSync(path + 'cache.json', JSON.stringify(Object.entries(this.app.vault.getMarkdownFiles())))
worker.terminate();
};
}
setWritingSchedule(
tagFileName: string,
metadataFileName: string,
allExceptMdFileName: string,
canvasFileName: string
) {
if (this.plugin.settings.writingFrequency !== '0') {
const intervalInMinutes = parseInt(
this.plugin.settings.writingFrequency
);
const milliseconds = intervalInMinutes * 60000;
// schedule for tagsToJSON
window.clearInterval(this.plugin.intervalId1);
this.plugin.intervalId1 = undefined;
this.plugin.intervalId1 = window.setInterval(
() => this.writeTagsToJSON(tagFileName),
milliseconds
);
// API function to cancel interval when plugin unloads
this.plugin.registerInterval(this.plugin.intervalId1);
// schedule for metadataCache to JSON
window.clearInterval(this.plugin.intervalId2);
this.plugin.intervalId2 = undefined;
this.plugin.intervalId2 = window.setInterval(
() => this.writeCacheToJSON(metadataFileName),
milliseconds
);
// API function to cancel interval when plugin unloads
this.plugin.registerInterval(this.plugin.intervalId2);
// schedule for allExceptMd to JSON
window.clearInterval(this.plugin.intervalId3);
this.plugin.intervalId3 = undefined;
this.plugin.intervalId3 = window.setInterval(
() => this.writeAllExceptMd(allExceptMdFileName),
milliseconds
);
// API function to cancel interval when plugin unloads
this.plugin.registerInterval(this.plugin.intervalId3);
// schedule for canvas to JSON
window.clearInterval(this.plugin.intervalId4);
this.plugin.intervalId4 = undefined;
this.plugin.intervalId4 = window.setInterval(
() => this.writeCanvases(canvasFileName),
milliseconds
);
// API function to cancel interval when plugin unloads
this.plugin.registerInterval(this.plugin.intervalId4);
} else if (this.plugin.settings.writingFrequency === '0') {
window.clearInterval(this.plugin.intervalId1);
window.clearInterval(this.plugin.intervalId2);
window.clearInterval(this.plugin.intervalId3);
window.clearInterval(this.plugin.intervalId4);
}
}
}
function calculateLinks(
currentCache: CachedMetadata,
metaObj: Metadata,
relativeFilePath: string,
displayName: string,
app: App,
tfile: TFile
): Metadata {
const currentLinks: links[] = [];
let bothLinks: LinkCache[] & EmbedCache[] = [];
linksAndOrEmbeds();
function linksAndOrEmbeds(): void {
let onlyLinks: LinkCache[] = [];
let onlyEmbeds: EmbedCache[] = [];
if (currentCache.links) {
onlyLinks = currentCache.links;
}
if (currentCache.embeds) {
onlyEmbeds = currentCache.embeds.filter((embed) => {
const link = embed.link;
const rawLink = getLinkpath(link);
const dest = app.metadataCache.getFirstLinkpathDest(
rawLink,
tfile.path
);
if (dest) {
return embed;
}
});
}
bothLinks = onlyLinks.concat(onlyEmbeds);
getLinksAndEmbeds();
}
function getLinksAndEmbeds() {
for (const links of bothLinks) {
let fullLink = links.link;
let aliasText = '';
//@ts-expect-error, must be initialized for adding keys, but
// TS interface requires certain keys, which will be added later
const currentLinkObject: links = {};
if (typeof links.displayText !== 'undefined') {
aliasText = links.displayText;
}
// calculate relative path before truncating it
const relPath = app.metadataCache.getFirstLinkpathDest(
getLinkpath(fullLink),
tfile.path
);
if (relPath) {
// only include md links
if (relPath.path.slice(-3).toLowerCase() !== '.md') {
continue;
}
}
// account for relative links
if (fullLink.includes('/')) {
//@ts-expect-error, it only takes the last element if it includes a slash
fullLink = fullLink.split('/').last();
}
if (!fullLink.includes('#')) {
currentLinkObject.link = fullLink;
// account for alias
if (aliasText !== fullLink) {
currentLinkObject.displayText = aliasText;
}
// account for uncreated files
if (relPath) {
currentLinkObject.relativePath = relPath.path;
}
}
// heading/block ref and maybe an alias, but not to the same file
else if (fullLink.includes('#') && fullLink.charAt(0) !== '#') {
const alias = aliasText;
const cleanLink = getLinkpath(fullLink);
currentLinkObject.link = fullLink;
currentLinkObject.cleanLink = cleanLink;
// it has an alias
if (!aliasText.includes('#') || !aliasText.includes('>')) {
currentLinkObject.displayText = alias;
}
// account for uncreated files
if (relPath) {
currentLinkObject.relativePath = relPath.path;
}
}
// heading/block ref to same file and maybe alias
else if (fullLink.charAt(0) === '#') {
currentLinkObject.link = fullLink;
currentLinkObject.relativePath = relativeFilePath;
currentLinkObject.cleanLink = displayName;
// account for alias
if (fullLink !== aliasText) {
currentLinkObject.displayText = aliasText;
}
}
currentLinks.push(currentLinkObject);
}
if (currentLinks.length > 0) {
metaObj.links = currentLinks;
}
}
return metaObj;
}