One-click backups for AT Protocol
1import { Agent } from "@atproto/api";
2import { BackupAgent } from "./backup";
3import { settingsManager } from "./settings";
4
5export class AutoBackupScheduler {
6 private agent: Agent;
7 private intervalId: NodeJS.Timeout | null = null;
8 private isRunning = false;
9
10 constructor(agent: Agent) {
11 this.agent = agent;
12 }
13
14 start(): void {
15 if (this.isRunning) return;
16
17 this.isRunning = true;
18 // Check every hour if a backup is needed
19 this.intervalId = setInterval(() => {
20 this.checkAndPerformBackup();
21 }, 60 * 60 * 1000); // 1 hour
22
23 // Also check immediately when starting
24 this.checkAndPerformBackup();
25 }
26
27 stop(): void {
28 if (this.intervalId) {
29 clearInterval(this.intervalId);
30 this.intervalId = null;
31 }
32 this.isRunning = false;
33 }
34
35 private async checkAndPerformBackup(): Promise<void> {
36 try {
37 const shouldBackup = await this.shouldPerformBackup();
38
39 if (shouldBackup) {
40 console.log("Automatic backup due, starting backup...");
41 await this.performBackup();
42 }
43 } catch (error) {
44 console.error("Error in automatic backup check:", error);
45 }
46 }
47
48 private async shouldPerformBackup(): Promise<boolean> {
49 try {
50 const lastBackupDate = await settingsManager.getLastBackupDate();
51 const frequency = await settingsManager.getBackupFrequency();
52
53 if (!lastBackupDate) {
54 // No previous backup, so we should do one
55 return true;
56 }
57
58 const lastBackup = new Date(lastBackupDate);
59 const now = new Date();
60 const timeDiff = now.getTime() - lastBackup.getTime();
61
62 if (frequency === "daily") {
63 // Check if 24 hours have passed
64 const oneDay = 24 * 60 * 60 * 1000;
65 return timeDiff >= oneDay;
66 } else if (frequency === "weekly") {
67 // Check if 7 days have passed
68 const oneWeek = 7 * 24 * 60 * 60 * 1000;
69 return timeDiff >= oneWeek;
70 }
71
72 return false;
73 } catch (error) {
74 console.error("Error checking if backup is due:", error);
75 return false;
76 }
77 }
78
79 private async performBackup(): Promise<void> {
80 try {
81 const manager = new BackupAgent(this.agent);
82 await manager.startBackup();
83
84 // Update the last backup date
85 await settingsManager.setLastBackupDate(new Date().toISOString());
86
87 console.log("Automatic backup completed successfully");
88 } catch (error) {
89 console.error("Automatic backup failed:", error);
90 }
91 }
92}