-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
271 lines (228 loc) · 9.49 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
import { App, Plugin, TFile, Notice, Modal, Setting, PluginSettingTab } from 'obsidian';
interface FindOrphanedImagesSettings {
imageExtensions: string;
maxDeleteCount: number;
moveToTrash: boolean;
}
const DEFAULT_SETTINGS: FindOrphanedImagesSettings = {
imageExtensions: 'png, jpg, jpeg, gif, svg, bmp',
maxDeleteCount: -1,
moveToTrash: false, // <--- Default to false
};
export default class FindOrphanedImagesPlugin extends Plugin {
settings: FindOrphanedImagesSettings;
ribbonIconEl: HTMLElement | null = null;
async onload() {
console.log('Loading Find Orphaned Images Plugin');
await this.loadSettings();
this.addSettingTab(new FindOrphanedImagesSettingTab(this.app, this));
this.addCommand({
id: 'find-orphaned-images',
name: 'Find or delete orphaned images',
callback: () => this.showOptionsModal(),
});
// Add the ribbon icon
this.ribbonIconEl = this.addRibbonIcon('find-orphaned-images-icon', 'Find orphaned images', () => {
this.showOptionsModal();
});
}
showOptionsModal() {
const modal = new ImageOptionsModal(this.app, this);
modal.open();
}
async findUnlinkedImages(embedImages: boolean) {
const { vault, metadataCache } = this.app;
const imageExtensions = this.settings.imageExtensions.split(',').map(ext => ext.trim());
const allFiles = vault.getFiles();
const imageFiles = allFiles.filter(file => imageExtensions.includes(file.extension));
const unlinkedImages: string[] = [];
imageFiles.forEach(image => {
const imagePath = image.path;
let isLinked = false;
for (const [filePath, links] of Object.entries(metadataCache.resolvedLinks)) {
if (links[imagePath]) {
isLinked = true;
break;
}
}
if (!isLinked) {
unlinkedImages.push(imagePath);
}
});
if (unlinkedImages.length > 0) {
await this.createOrUpdateUnlinkedImagesNote(unlinkedImages, embedImages);
new Notice(`Found ${unlinkedImages.length} orphaned images. Note created or updated with details.`);
} else {
new Notice("All images are linked!");
}
}
async deleteFirstUnlinkedImage() {
const { vault, metadataCache } = this.app;
const imageExtensions = this.settings.imageExtensions.split(',').map(ext => ext.trim());
const allFiles = vault.getFiles();
const imageFiles = allFiles.filter(file => imageExtensions.includes(file.extension));
const unlinkedImages: string[] = [];
imageFiles.forEach(image => {
const imagePath = image.path;
let isLinked = false;
for (const [filePath, links] of Object.entries(metadataCache.resolvedLinks)) {
if (links[imagePath]) {
isLinked = true;
break;
}
}
if (!isLinked) {
unlinkedImages.push(imagePath);
}
});
let deleteCount = 0;
for (const imagePath of unlinkedImages) {
if (this.settings.maxDeleteCount !== -1 && deleteCount >= this.settings.maxDeleteCount) break;
try {
const fileToDelete = vault.getAbstractFileByPath(imagePath);
if (fileToDelete instanceof TFile) {
if (this.settings.moveToTrash) {
// Move to system trash (if supported)
await vault.trash(fileToDelete, true);
new Notice(`Moved orphaned image to trash: ${imagePath}`);
} else {
// Permanently delete
await vault.delete(fileToDelete);
new Notice(`Deleted orphaned image: ${imagePath}`);
}
deleteCount++;
}
} catch (error) {
console.error("Failed to delete the image:", error);
new Notice("Failed to delete the orphaned image.");
}
}
if (deleteCount === 0) {
new Notice("No orphaned images found to delete.");
}
}
async createOrUpdateUnlinkedImagesNote(unlinkedImages: string[], embedImages: boolean) {
const { vault } = this.app;
const noteContent = `# Orphaned Images\n\nThese images are not linked in any note:\n\n` +
unlinkedImages.map(imagePath => {
const encodedPath = this.encodeImagePath(imagePath);
return embedImages ? `- ![](${encodedPath})` : `- [${imagePath}](${encodedPath})`;
}).join('\n');
const noteName = "Orphaned Images Report.md";
const notePath = `${noteName}`;
try {
const existingFile = vault.getAbstractFileByPath(notePath);
if (existingFile instanceof TFile) {
await vault.modify(existingFile, noteContent);
} else {
await vault.create(notePath, noteContent);
}
new Notice(`Note "${noteName}" created or updated with orphaned images.`);
this.app.workspace.openLinkText(notePath, '', true);
} catch (error) {
console.error("Failed to create or update note:", error);
new Notice("Failed to create or update note with orphaned images.");
}
}
encodeImagePath(imagePath: string): string {
return imagePath.replace(/ /g, '%20');
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
onunload() {
console.log('Unloading Find Orphaned Images Plugin');
if (this.ribbonIconEl) {
this.ribbonIconEl.remove();
}
}
}
class ImageOptionsModal extends Modal {
plugin: FindOrphanedImagesPlugin;
constructor(app: App, plugin: FindOrphanedImagesPlugin) {
super(app);
this.plugin = plugin;
}
onOpen() {
const { contentEl } = this;
contentEl.createEl('h2', { text: 'Create a report or delete the images?' });
new Setting(contentEl)
.setName('Embed images')
.setDesc('Create a report with embedded images. This will display the images in the note.')
.addButton(button => button
.setButtonText('Create')
.setCta()
.onClick(() => {
this.plugin.findUnlinkedImages(true);
this.close();
}));
new Setting(contentEl)
.setName('Text links')
.setDesc('Create a report with text links to the images. This will not display the images in the note.')
.addButton(button => button
.setButtonText('Create')
.setCta()
.onClick(() => {
this.plugin.findUnlinkedImages(false);
this.close();
}));
new Setting(contentEl)
.setName('Delete orphaned images')
.setDesc('Delete the X images found in the vault. X is the max delete count, defined in the settings.')
.addButton(button => button
.setButtonText('Delete')
.setCta()
.onClick(() => {
this.plugin.deleteFirstUnlinkedImage();
this.close();
}));
}
onClose() {
const { contentEl } = this;
contentEl.empty();
}
}
class FindOrphanedImagesSettingTab extends PluginSettingTab {
plugin: FindOrphanedImagesPlugin;
constructor(app: App, plugin: FindOrphanedImagesPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
new Setting(containerEl)
.setName('Image extensions')
.setDesc('Comma-separated list of image extensions to look for.')
.addText(text => text
.setPlaceholder('Enter image extensions')
.setValue(this.plugin.settings.imageExtensions)
.onChange(async (value) => {
this.plugin.settings.imageExtensions = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Max delete count')
.setDesc('Maximum number of orphaned images to delete (-1 for no limit).')
.addText(text => text
.setPlaceholder('-1')
.setValue(this.plugin.settings.maxDeleteCount.toString())
.onChange(async (value) => {
this.plugin.settings.maxDeleteCount = parseInt(value, 10) || -1;
await this.plugin.saveSettings();
}));
// --- Add the "Move to Trash" toggle ---
new Setting(containerEl)
.setName('Move to Trash')
.setDesc('If enabled, orphaned images will be moved to the system trash instead of deleted.')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.moveToTrash)
.onChange(async (value) => {
this.plugin.settings.moveToTrash = value;
await this.plugin.saveSettings();
}));
}
}