-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.ts
More file actions
695 lines (644 loc) · 24.3 KB
/
main.ts
File metadata and controls
695 lines (644 loc) · 24.3 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
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
// src/main.ts
import { Plugin, TFile, Notice } from 'obsidian';
import { SupabaseService } from './services/SupabaseService';
import { OpenAIService } from './services/OpenAIService';
import { QueueService } from './services/QueueService';
import { FileTracker } from './utils/FileTracker';
import { ErrorHandler } from './utils/ErrorHandler';
import { NotificationManager } from './utils/NotificationManager';
import { MindMatrixSettingsTab } from './settings/SettingsTab';
import { SyncFileManager } from './services/SyncFileManager';
import { InitialSyncManager } from './services/InitialSyncManager';
import { MetadataExtractor } from './services/MetadataExtractor';
import { StatusManager, PluginStatus } from './services/StatusManager';
import { SyncDetectionManager } from './services/SyncDetectionManager';
import {
MindMatrixSettings,
DEFAULT_SETTINGS,
isVaultInitialized,
generateVaultId,
getAllExclusions,
SYSTEM_EXCLUSIONS
} from './settings/Settings';
import { ProcessingTask, TaskType, TaskStatus } from './models/ProcessingTask';
export default class MindMatrixPlugin extends Plugin {
settings: MindMatrixSettings;
private supabaseService: SupabaseService | null = null;
private openAIService: OpenAIService | null = null;
private queueService: QueueService | null = null;
private fileTracker: FileTracker | null = null;
private errorHandler: ErrorHandler | null = null;
private notificationManager: NotificationManager | null = null;
private isInitializing = false;
private syncManager: SyncFileManager | null = null;
private syncCheckInterval: NodeJS.Timeout | null = null;
private initializationTimeout: NodeJS.Timeout | null = null;
private syncCheckAttempts = 0;
private initialSyncManager: InitialSyncManager | null = null;
private metadataExtractor: MetadataExtractor | null = null;
private statusManager: StatusManager | null = null;
private syncDetectionManager: SyncDetectionManager | null = null;
async onload() {
console.log('Loading Mind Matrix Plugin...');
try {
// Initialize status manager first
this.statusManager = new StatusManager(this.addStatusBarItem());
this.statusManager.setStatus(PluginStatus.INITIALIZING, {
message: 'Loading Mind Matrix Plugin...'
});
// Load settings
await this.loadSettings();
// Initialize core services and vault if needed
await this.initializeCoreServices();
await this.initializeVaultIfNeeded();
// Initialize FileTracker early to capture events
this.fileTracker = new FileTracker(
this.app.vault,
this.errorHandler!,
this.settings.sync.syncFilePath
);
// Register event handlers immediately to capture all events
this.registerEventHandlers();
// Add settings tab
this.addSettingTab(new MindMatrixSettingsTab(this.app, this));
if (isVaultInitialized(this.settings)) {
this.statusManager.setStatus(PluginStatus.WAITING_FOR_SYNC, {
message: 'Waiting for Obsidian sync to settle...'
});
// Create and start sync detection with improved logging
this.syncDetectionManager = new SyncDetectionManager(
this,
this.statusManager,
this.onSyncQuietPeriodReached.bind(this)
);
this.syncDetectionManager.startMonitoring();
} else {
await this.completeInitialization();
}
} catch (error) {
console.error('Failed to initialize Mind Matrix Plugin:', error);
this.statusManager?.setStatus(PluginStatus.ERROR, {
message: 'Failed to initialize plugin. Check console for details.',
error: error as Error
});
}
}
private async onSyncQuietPeriodReached(): Promise<void> {
try {
// Stop monitoring as we've reached a quiet period
this.syncDetectionManager?.stopMonitoring();
// Check if the vault has already been synced
if (this.syncManager && this.supabaseService) {
const syncStatus = await this.syncManager.validateSyncState();
if (syncStatus.isValid) {
// Perform a quick integrity check with the database
const fileCount = await this.supabaseService.getFileCount();
if (fileCount > 0) {
console.log('[MindMatrix] Database contains files, skipping initial sync');
await this.completeInitialization();
return;
}
}
}
this.statusManager?.setStatus(PluginStatus.CHECKING_FILE, {
message: 'Initializing sync manager with updated sync file format...'
});
// Initialize sync manager
await this.initializeSyncManager();
// Start sync process
await this.startSyncProcess();
// Complete remaining initialization
await this.completeInitialization();
} catch (error) {
console.error('Error during quiet period initialization:', error);
this.statusManager?.setStatus(PluginStatus.ERROR, {
message: 'Failed to initialize after sync quiet period',
error: error as Error
});
}
}
private async completeInitialization(): Promise<void> {
try {
// Wait for services to be initialized
await this.initializeServices();
// Ensure FileTracker is initialized before registering event handlers
if (!this.fileTracker?.getInitializationStatus()) {
console.warn('[MindMatrix] FileTracker not initialized. Waiting for initialization...');
await new Promise<void>((resolve) => {
const checkInterval = setInterval(() => {
if (this.fileTracker?.getInitializationStatus()) {
clearInterval(checkInterval);
resolve();
}
}, 100);
// Timeout after 10 seconds
setTimeout(() => {
clearInterval(checkInterval);
resolve();
}, 10000);
});
}
// Register event handlers and commands
this.registerEventHandlers();
this.addCommands();
// Update status to ready
this.statusManager?.setStatus(PluginStatus.READY, {
message: 'Mind Matrix is ready'
});
} catch (error) {
console.error('Error completing initialization:', error);
this.statusManager?.setStatus(PluginStatus.ERROR, {
message: 'Failed to complete initialization',
error: error as Error
});
}
}
async onunload() {
console.log('Unloading Mind Matrix Plugin...');
// Stop sync detection and clear any intervals/timeouts
this.syncDetectionManager?.stopMonitoring();
if (this.initializationTimeout) clearTimeout(this.initializationTimeout);
if (this.syncCheckInterval) clearInterval(this.syncCheckInterval);
this.queueService?.stop();
this.notificationManager?.clear();
this.initialSyncManager?.stop();
}
private async startSyncProcess(): Promise<void> {
if (!this.syncManager) throw new Error('Sync manager not initialized');
try {
this.statusManager?.setStatus(PluginStatus.CHECKING_FILE, {
message: 'Checking sync file status with new structure...'
});
const syncStatus = await this.syncManager.validateSyncState();
if (!syncStatus.isValid) {
if (this.settings.sync.requireSync) {
this.statusManager?.setStatus(PluginStatus.ERROR, {
message: `Sync validation failed: ${syncStatus.error}`
});
throw new Error(`Sync validation failed: ${syncStatus.error}`);
} else {
console.warn(`Sync validation warning: ${syncStatus.error}`);
new Notice(`Sync warning: ${syncStatus.error}`);
}
}
this.statusManager?.setStatus(PluginStatus.INITIALIZING, {
message: 'Initializing services...'
});
await this.initializeServices();
// Start periodic sync checks
this.startPeriodicSyncChecks();
if (this.settings.initialSync.enableAutoInitialSync && this.initialSyncManager) {
this.statusManager?.setStatus(PluginStatus.INITIALIZING, {
message: 'Starting initial vault sync...'
});
await this.initialSyncManager.startSync();
}
this.statusManager?.setStatus(PluginStatus.READY, {
message: 'Sync process completed'
});
} catch (error) {
if (this.settings.sync.requireSync) {
this.statusManager?.setStatus(PluginStatus.ERROR, {
message: 'Sync process failed',
error: error as Error
});
throw error;
} else {
console.error('Sync process error:', error);
new Notice('Sync process error. Continuing with limited functionality.');
await this.initializeServices();
}
}
}
private async initializeSyncManager(): Promise<void> {
if (!this.errorHandler) throw new Error('Error handler must be initialized before sync manager');
if (!this.settings.vaultId) {
this.settings.vaultId = generateVaultId();
await this.saveSettings();
}
try {
this.syncManager = new SyncFileManager(
this.app.vault,
this.errorHandler,
this.settings.sync.syncFilePath,
this.settings.sync.backupInterval,
this.settings.vaultId,
this.settings.sync.deviceId,
this.settings.sync.deviceName,
this.manifest.version
);
await this.syncManager.initialize();
console.log('Sync manager initialized successfully with new sync file format');
} catch (error) {
console.error('Failed to initialize sync manager:', error);
if (this.settings.enableNotifications) new Notice('Failed to initialize sync system. Some features may be unavailable.');
throw error;
}
}
private async initializeCoreServices(): Promise<void> {
this.statusManager?.setStatus(PluginStatus.INITIALIZING, { message: 'Initializing core services...' });
// Initialize error handler
this.errorHandler = new ErrorHandler(this.settings?.debug ?? DEFAULT_SETTINGS.debug);
// Initialize notification manager
this.notificationManager = new NotificationManager(
this.addStatusBarItem(),
this.settings?.enableNotifications ?? true,
this.settings?.enableProgressBar ?? true
);
this.statusManager?.setStatus(PluginStatus.INITIALIZING, { message: 'Core services initialized' });
}
private async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
// Ensure exclusions have the expected structure
if (!this.settings.exclusions) this.settings.exclusions = { ...DEFAULT_SETTINGS.exclusions };
if (!this.settings.exclusions.excludedFolders) this.settings.exclusions.excludedFolders = [];
if (!this.settings.exclusions.excludedFileTypes) this.settings.exclusions.excludedFileTypes = [];
if (!this.settings.exclusions.excludedFilePrefixes) this.settings.exclusions.excludedFilePrefixes = [];
if (!this.settings.exclusions.excludedFiles) this.settings.exclusions.excludedFiles = [];
if (!this.settings.exclusions.systemExcludedFolders) this.settings.exclusions.systemExcludedFolders = [...SYSTEM_EXCLUSIONS.folders];
if (!this.settings.exclusions.systemExcludedFileTypes) this.settings.exclusions.systemExcludedFileTypes = [...SYSTEM_EXCLUSIONS.fileTypes];
if (!this.settings.exclusions.systemExcludedFilePrefixes) this.settings.exclusions.systemExcludedFilePrefixes = [...SYSTEM_EXCLUSIONS.filePrefixes];
if (!this.settings.exclusions.systemExcludedFiles) this.settings.exclusions.systemExcludedFiles = [...SYSTEM_EXCLUSIONS.files];
}
async saveSettings() {
await this.saveData(this.settings);
// Update service settings after saving
this.notificationManager?.updateSettings(this.settings.enableNotifications, this.settings.enableProgressBar);
this.errorHandler?.updateSettings(this.settings.debug);
if (isVaultInitialized(this.settings)) await this.initializeServices();
}
private startPeriodicSyncChecks(): void {
if (this.syncCheckInterval) clearInterval(this.syncCheckInterval);
this.syncCheckInterval = setInterval(async () => {
await this.performSyncCheck();
}, this.settings.sync.checkInterval);
}
private async performSyncCheck(): Promise<void> {
if (!this.syncManager) return;
try {
const syncStatus = await this.syncManager.validateSyncState();
if (!syncStatus.isValid) {
console.warn(`Sync check failed: ${syncStatus.error}`);
if (this.settings.enableNotifications) new Notice(`Sync issue detected: ${syncStatus.error}`);
const recovered = await this.syncManager.attemptRecovery();
if (!recovered && this.settings.sync.requireSync) await this.restartServices();
}
await this.syncManager.updateLastSync();
} catch (error) {
this.errorHandler?.handleError(error, { context: 'performSyncCheck', metadata: { timestamp: Date.now() } });
}
}
private async restartServices(): Promise<void> {
this.queueService?.stop();
if (this.syncCheckInterval) clearInterval(this.syncCheckInterval);
try {
await this.initializeSyncManager();
await this.startSyncProcess();
} catch (error) {
console.error('Failed to restart services:', error);
if (this.settings.enableNotifications) new Notice('Failed to restart services after sync error');
}
}
private async initializeVaultIfNeeded() {
if (this.isInitializing) return;
this.isInitializing = true;
try {
if (!isVaultInitialized(this.settings)) {
this.settings.vaultId = generateVaultId();
this.settings.lastKnownVaultName = this.app.vault.getName();
await this.saveSettings();
if (this.settings.enableNotifications) new Notice('Vault initialized with new ID');
} else if (this.settings.lastKnownVaultName !== this.app.vault.getName()) {
this.settings.lastKnownVaultName = this.app.vault.getName();
await this.saveSettings();
}
} finally {
this.isInitializing = false;
}
}
private async initializeServices(): Promise<void> {
console.log('[MindMatrix] Initializing services...', {
hasVault: !!this.app.vault,
hasErrorHandler: !!this.errorHandler
});
if (!this.errorHandler) {
throw new Error('Error handler must be initialized before services');
}
try {
// Initialize Supabase service first
this.supabaseService = await SupabaseService.getInstance(this.settings);
if (!this.supabaseService) {
throw new Error('Failed to initialize Supabase service');
}
console.log('[MindMatrix] Supabase service initialized.');
// Initialize OpenAI service
this.openAIService = new OpenAIService(this.settings.openai, this.errorHandler);
console.log('[MindMatrix] OpenAI service initialized.');
// Initialize QueueService
const notificationManager = this.notificationManager || new NotificationManager(
this.addStatusBarItem(),
this.settings.enableNotifications,
this.settings.enableProgressBar
);
this.queueService = new QueueService(
this.settings.queue.maxConcurrent,
this.settings.queue.retryAttempts,
this.supabaseService,
this.openAIService,
this.errorHandler,
notificationManager,
this.app.vault,
this.settings.chunking
);
await this.queueService.start();
console.log('[MindMatrix] Queue service initialized and started.');
// Initialize FileTracker
this.fileTracker = new FileTracker(
this.app.vault,
this.errorHandler,
this.settings.sync.syncFilePath,
this.supabaseService
);
await this.fileTracker.initialize(this.settings, this.supabaseService, this.queueService);
console.log('[MindMatrix] FileTracker initialized.');
// Initialize MetadataExtractor
this.metadataExtractor = new MetadataExtractor(this.app.vault, this.errorHandler);
console.log('[MindMatrix] MetadataExtractor initialized.');
// Initialize InitialSyncManager
if (!this.syncManager) {
throw new Error('SyncManager must be initialized before InitialSyncManager');
}
if (!this.queueService) {
throw new Error('QueueService must be initialized before InitialSyncManager');
}
if (!this.metadataExtractor) {
throw new Error('MetadataExtractor must be initialized before InitialSyncManager');
}
if (!this.errorHandler) {
throw new Error('ErrorHandler must be initialized before InitialSyncManager');
}
if (!this.notificationManager) {
throw new Error('NotificationManager must be initialized before InitialSyncManager');
}
this.initialSyncManager = new InitialSyncManager(
this.app.vault,
this.queueService,
this.syncManager,
this.metadataExtractor,
this.errorHandler,
this.notificationManager,
this.supabaseService,
{
batchSize: this.settings.initialSync.batchSize || 50,
maxConcurrentBatches: this.settings.initialSync.maxConcurrentBatches || 3,
enableAutoInitialSync: this.settings.initialSync.enableAutoInitialSync,
priorityRules: this.settings.initialSync.priorityRules || [],
syncFilePath: this.settings.sync.syncFilePath,
exclusions: {
excludedFolders: this.settings.exclusions.excludedFolders || [],
excludedFileTypes: this.settings.exclusions.excludedFileTypes || [],
excludedFilePrefixes: this.settings.exclusions.excludedFilePrefixes || [],
excludedFiles: this.settings.exclusions.excludedFiles || []
}
}
);
console.log('[MindMatrix] InitialSyncManager initialized.');
} catch (error) {
console.error('[MindMatrix] Error initializing services:', error);
this.errorHandler.handleError(error, { context: 'MindMatrixPlugin.initializeServices' });
throw error;
}
}
private checkRequiredConfigurations(): void {
if (!this.settings.openai.apiKey) {
new Notice('OpenAI API key is missing. AI features are disabled. Configure it in the settings.');
}
if (!this.settings.supabase.url || !this.settings.supabase.apiKey) {
new Notice('Supabase configuration is incomplete. Database features are disabled. Configure it in the settings.');
}
}
private registerEventHandlers() {
// Enhanced file event handlers with improved debouncing and logging
this.registerEvent(
this.app.vault.on('create', async (file) => {
if (!(file instanceof TFile)) return;
if (!(await this.ensureSyncFileExists())) {
new Notice('Failed to create sync file. Plugin functionality limited.');
return;
}
if (!this.shouldProcessFile(file)) return;
console.log(`File created: ${file.path}`);
await this.fileTracker?.handleCreate(file);
await this.queueFileProcessing(file, TaskType.CREATE);
})
);
this.registerEvent(
this.app.vault.on('modify', async (file) => {
if (!(file instanceof TFile)) return;
if (!(await this.ensureSyncFileExists())) {
new Notice('Failed to create sync file. Plugin functionality limited.');
return;
}
if (!this.shouldProcessFile(file)) return;
console.log(`File modified: ${file.path}`);
// Enhanced debouncing is handled in FileTracker.handleModify
await this.fileTracker?.handleModify(file);
await this.queueFileProcessing(file, TaskType.UPDATE);
})
);
this.registerEvent(
this.app.vault.on('delete', async (file) => {
if (!(file instanceof TFile)) return;
if (file.path === this.settings.sync.syncFilePath) {
console.log('Sync file was deleted, will recreate on next operation');
return;
}
if (!(await this.ensureSyncFileExists())) {
new Notice('Failed to create sync file. Plugin functionality limited.');
return;
}
if (!this.shouldProcessFile(file)) return;
console.log(`File deleted: ${file.path}`);
await this.fileTracker?.handleDelete(file);
await this.queueFileProcessing(file, TaskType.DELETE);
})
);
this.registerEvent(
this.app.vault.on('rename', async (file, oldPath) => {
if (!(file instanceof TFile)) return;
if (!(await this.ensureSyncFileExists())) {
new Notice('Failed to create sync file. Plugin functionality limited.');
return;
}
if (!this.shouldProcessFile(file)) return;
console.log(`File renamed from ${oldPath} to ${file.path}`);
await this.fileTracker?.handleRename(file, oldPath);
})
);
}
private shouldProcessFile(file: TFile): boolean {
if (!this.queueService || !isVaultInitialized(this.settings)) return false;
if (!this.settings.enableAutoSync) return false;
const allExclusions = getAllExclusions(this.settings);
const filePath = file.path;
const fileName = file.name;
if (filePath === this.settings.sync.syncFilePath || filePath === this.settings.sync.syncFilePath + '.backup') {
console.log(`Skipping sync file: ${filePath}`);
return false;
}
if (Array.isArray(allExclusions.excludedFiles) && allExclusions.excludedFiles.includes(fileName)) {
console.log('Skipping excluded file:', fileName);
return false;
}
if (Array.isArray(allExclusions.excludedFolders)) {
const isExcludedFolder = allExclusions.excludedFolders.some(folder => {
const normalizedFolder = folder.endsWith('/') ? folder : folder + '/';
return filePath.startsWith(normalizedFolder);
});
if (isExcludedFolder) {
console.log('Skipping file in excluded folder:', filePath);
return false;
}
}
if (Array.isArray(allExclusions.excludedFileTypes)) {
const isExcludedType = allExclusions.excludedFileTypes.some(ext => filePath.toLowerCase().endsWith(ext.toLowerCase()));
if (isExcludedType) {
console.log('Skipping excluded file type:', filePath);
return false;
}
}
if (Array.isArray(allExclusions.excludedFilePrefixes)) {
const isExcludedPrefix = allExclusions.excludedFilePrefixes.some(prefix => fileName.startsWith(prefix));
if (isExcludedPrefix) {
console.log('Skipping file with excluded prefix:', fileName);
return false;
}
}
return true;
}
private async ensureSyncFileExists(): Promise<boolean> {
if (!this.syncManager) {
console.error('Sync manager not initialized');
return false;
}
try {
const syncFile = this.app.vault.getAbstractFileByPath(this.settings.sync.syncFilePath);
if (!syncFile) {
console.log('Sync file missing, recreating...');
await this.syncManager.initialize();
new Notice('Recreated sync file');
return true;
}
return true;
} catch (error) {
console.error('Error ensuring sync file exists:', error);
return false;
}
}
private async queueFileProcessing(file: TFile, type: TaskType.CREATE | TaskType.UPDATE | TaskType.DELETE): Promise<void> {
try {
if (!this.queueService || !this.fileTracker) {
console.error('Required services not initialized:', { queueService: !!this.queueService, fileTracker: !!this.fileTracker });
return;
}
console.log('Queueing file processing:', { fileName: file.name, type, path: file.path });
const metadata = await this.fileTracker.createFileMetadata(file);
console.log('Created metadata:', metadata);
const task: ProcessingTask = {
id: file.path,
type: type,
priority: type === TaskType.DELETE ? 2 : 1,
maxRetries: this.settings.queue.retryAttempts,
retryCount: 0,
createdAt: Date.now(),
updatedAt: Date.now(),
status: TaskStatus.PENDING,
metadata,
data: {}
};
console.log('Created task:', task);
await this.queueService.addTask(task);
console.log('Task added to queue');
if (this.settings.enableNotifications) {
const action = type.toLowerCase();
new Notice(`Queued ${action} for processing: ${file.name}`);
}
} catch (error) {
console.error('Error in queueFileProcessing:', error);
this.errorHandler?.handleError(error, { context: 'queueFileProcessing', metadata: { filePath: file.path, type } });
if (this.settings.enableNotifications) {
new Notice(`Failed to queue ${file.name} for processing`);
}
}
}
private addCommands() {
this.addCommand({
id: 'force-sync-current-file',
name: 'Force sync current file',
checkCallback: (checking: boolean) => {
const file = this.app.workspace.getActiveFile();
if (file) {
if (!checking) {
this.queueFileProcessing(file, TaskType.UPDATE);
}
return true;
}
return false;
}
});
this.addCommand({
id: 'force-sync-all-files',
name: 'Force sync all files',
callback: async () => {
const files = this.app.vault.getMarkdownFiles();
for (const file of files) {
if (this.shouldProcessFile(file)) {
await this.queueFileProcessing(file, TaskType.UPDATE);
}
}
}
});
this.addCommand({
id: 'clear-sync-queue',
name: 'Clear sync queue',
callback: () => {
this.queueService?.clear();
if (this.settings.enableNotifications) {
new Notice('Sync queue cleared');
}
}
});
this.addCommand({
id: 'reset-file-tracker',
name: 'Reset file tracker cache',
callback: async () => {
this.fileTracker?.clearQueue();
if (this.fileTracker && this.settings && this.supabaseService && this.queueService) {
await this.fileTracker.initialize(this.settings, this.supabaseService, this.queueService);
}
if (this.settings.enableNotifications) {
new Notice('File tracker cache reset');
}
}
});
this.addCommand({
id: 'start-initial-sync',
name: 'Start initial vault sync',
callback: async () => {
if (this.initialSyncManager) {
await this.initialSyncManager.startSync();
} else {
new Notice('Initial sync manager not initialized');
}
}
});
this.addCommand({
id: 'stop-initial-sync',
name: 'Stop initial vault sync',
callback: () => {
this.initialSyncManager?.stop();
new Notice('Initial sync stopped');
}
});
}
}