-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.ts
More file actions
293 lines (246 loc) · 8.87 KB
/
main.ts
File metadata and controls
293 lines (246 loc) · 8.87 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
import { Plugin, Modal, TFile, App, PluginSettingTab, Setting, Platform } from 'obsidian';
interface ObsifetchSettings {
customLogo: string;
}
interface CustomCSS {
theme?: string;
}
interface ObsidianApp extends App {
customCss: CustomCSS;
plugins: {
manifests: Record<string, any>;
};
internalPlugins: {
plugins: Record<string, any>;
};
}
const DEFAULT_SETTINGS: ObsifetchSettings = {
customLogo: ''
}
const getUsername = (): string => {
try {
return require("os").userInfo().username;
} catch {
return "user";
}
};
class ObsifetchModal extends Modal {
private logo: string;
private vaultInfo: string;
private systemInfo: string;
constructor(app: App, logo: string, vaultInfo: string, systemInfo: string) {
super(app);
this.logo = logo;
this.vaultInfo = vaultInfo;
this.systemInfo = systemInfo;
}
onOpen() {
const {contentEl} = this;
contentEl.addClass('obsifetch-modal');
contentEl.createEl('div', {
text: '> obsifetch',
cls: 'obsifetch-title'
});
const container = contentEl.createDiv({cls: 'obsifetch-container'});
const logoSection = container.createDiv({cls: 'logo-section'});
logoSection.createEl('pre', {text: this.logo});
const infoSection = container.createDiv({cls: 'info-section'});
const vaultName = this.app.vault.getName();
infoSection.createEl('div', {
text: `${getUsername()}@${vaultName.toLowerCase()}`,
cls: 'vault-header'
});
infoSection.createEl('hr', {
cls: 'vault-separator'
});
const preElement = infoSection.createEl('pre');
this.vaultInfo.toLowerCase().split('\n').forEach(line => {
const [label, value] = line.split(': ');
const lineDiv = preElement.createDiv();
lineDiv.createSpan({text: label + ': ', cls: 'stat-label'});
lineDiv.createSpan({text: value, cls: 'stat-value'});
});
this.systemInfo.toLowerCase().split('\n').forEach(line => {
const [label, value] = line.split(': ');
const lineDiv = preElement.createDiv();
lineDiv.createSpan({text: label + ': ', cls: 'stat-label'});
lineDiv.createSpan({text: value, cls: 'stat-value'});
});
const colorSquares = preElement.createSpan({cls: 'color-squares'});
for (let i = 0; i < 8; i++) {
colorSquares.createSpan();
}
}
onClose() {
const {contentEl} = this;
contentEl.empty();
}
}
class ObsifetchSettingTab extends PluginSettingTab {
plugin: ObsifetchPlugin;
constructor(app: App, plugin: ObsifetchPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const {containerEl} = this;
containerEl.empty();
new Setting(containerEl)
.setName('Custom art')
.setDesc('Display your own ASCII art. Delete the content to reset to default.')
.addTextArea(text => text
.setPlaceholder('Paste ASCII art here...')
.setValue(this.plugin.settings.customLogo)
.onChange(async (value) => {
this.plugin.settings.customLogo = value;
await this.plugin.saveSettings();
}));
}
}
export default class ObsifetchPlugin extends Plugin {
settings: ObsifetchSettings;
private ribbonIcon: HTMLElement;
private defaultLogo = ` ;++
;;+++X;
:;;;;;XXXX
:::::XXXXXX
::..::XXXXXX
$+ .Xxx+++
$$$X .:++++++
X$$$$X$&&$X+;;;+
;XXXXX$&$$$$$$;;.
XXXX$$$$$XXXX
XX$$XXXXXXX
;XXXX `;
async onload() {
await this.loadSettings();
this.addSettingTab(new ObsifetchSettingTab(this.app, this));
console.log('loading obsifetch');
this.addCommand({
id: 'show',
name: 'Show',
callback: () => this.displayObsifetch()
});
this.ribbonIcon = this.addRibbonIcon(
'terminal-square',
'obsifetch',
(evt: MouseEvent) => {
this.displayObsifetch();
}
);
}
private async getVaultStats() {
const activeTheme = (this.app as ObsidianApp).customCss?.theme || 'default';
const manifests = (this.app as ObsidianApp).plugins?.manifests || {};
const communityPluginCount = Object.keys(manifests).length;
const corePluginCount = Object.keys((this.app as ObsidianApp).internalPlugins?.plugins || {}).length;
const allFiles = this.app.vault.getAllLoadedFiles()
.filter((file): file is TFile => file instanceof TFile);
const markdownFiles = allFiles
.filter(file => file.extension === 'md');
const attachments = allFiles
.filter(file => file.extension !== 'md');
const resolvedLinks = this.app.metadataCache.resolvedLinks;
const linkedFiles = new Set<string>();
let internalLinkCount = 0;
Object.values(resolvedLinks).forEach(links => {
Object.keys(links).forEach(path => {
linkedFiles.add(path);
internalLinkCount += links[path];
});
});
const orphanedFiles = markdownFiles.filter(file =>
!linkedFiles.has(file.path)
).length;
const totalSize = await this.calculateTotalSize(allFiles);
const attachmentSize = await this.calculateTotalSize(attachments);
const markdownSize = await this.calculateTotalSize(markdownFiles);
const attachmentPercentage = ((attachments.length / allFiles.length) * 100).toFixed(1);
return {
totalFiles: allFiles.length,
totalMarkdown: markdownFiles.length,
totalAttachments: attachments.length,
orphanedFiles,
internalLinkCount,
attachmentPercentage: `${attachmentPercentage}%`,
totalPlugins: communityPluginCount + corePluginCount,
communityPlugins: communityPluginCount,
corePlugins: corePluginCount,
theme: activeTheme,
version: this.manifest.version,
totalSize: this.formatSize(totalSize),
markdownSize: this.formatSize(markdownSize),
attachmentSize: this.formatSize(attachmentSize)
};
}
private async calculateTotalSize(files: TFile[]): Promise<number> {
let total = 0;
for (const file of files) {
try {
const stat = await this.app.vault.adapter.stat(file.path);
if (stat) {
total += stat.size;
}
} catch (e) {
console.warn(`Failed to get size for file: ${file.path}`);
}
}
return total;
}
private formatSize(bytes: number): string {
const units = ['B', 'KB', 'MB', 'GB'];
let size = bytes;
let unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex++;
}
return `${size.toFixed(1)} ${units[unitIndex]}`;
}
private getSystemInfo(): string {
const isDarkTheme = document.body.classList.contains('theme-dark');
let os = 'unknown';
if (Platform.isLinux) {
os = 'linux';
} else if (Platform.isMacOS) {
os = 'macos';
} else if (Platform.isWin) {
os = 'windows';
}
return [
`appearance: ${isDarkTheme ? 'dark' : 'light'}`,
`os: ${os}`
].join('\n').trimEnd();
}
private async displayObsifetch() {
const stats = await this.getVaultStats();
const info = this.getSystemInfo();
const logo = this.settings.customLogo || this.defaultLogo;
const vaultInfoLines = [
`obsifetch: v${this.manifest.version}`,
`total files: ${stats.totalFiles} (${stats.totalSize})`,
`markdown files: ${stats.totalMarkdown} (${stats.markdownSize})`,
`attachments: ${stats.totalAttachments} (${stats.attachmentSize})`,
`orphan files: ${stats.orphanedFiles}`,
`internal links: ${stats.internalLinkCount}`,
`core plugins: ${stats.corePlugins}`,
`community plugins: ${stats.communityPlugins}`,
`theme: ${stats.theme}`
].join('\n').trimEnd();
new ObsifetchModal(
this.app,
logo,
vaultInfoLines,
info
).open();
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
onunload() {
console.log('unloading obsifetch');
}
}