2022-03-30 15:52:48 +05:00
|
|
|
import { checkIsUserPremium, CHECK_IDS, EVENTS } from "../../common";
|
|
|
|
|
|
|
|
|
|
export class AutoSync {
|
|
|
|
|
/**
|
|
|
|
|
*
|
|
|
|
|
* @param {import("../index").default} db
|
|
|
|
|
* @param {number} interval
|
|
|
|
|
*/
|
|
|
|
|
constructor(db, interval) {
|
|
|
|
|
this.db = db;
|
|
|
|
|
this.interval = interval;
|
|
|
|
|
this.timeout = null;
|
2022-03-30 20:45:16 +05:00
|
|
|
this.isAutoSyncing = false;
|
2022-03-30 15:52:48 +05:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async start() {
|
|
|
|
|
if (!(await checkIsUserPremium(CHECK_IDS.databaseSync))) return;
|
2022-03-30 20:45:16 +05:00
|
|
|
if (this.isAutoSyncing) return;
|
2022-03-30 15:52:48 +05:00
|
|
|
|
2022-03-30 20:45:16 +05:00
|
|
|
this.isAutoSyncing = true;
|
2022-03-30 15:52:48 +05:00
|
|
|
this.databaseUpdatedEvent = this.db.eventManager.subscribeSingle(
|
|
|
|
|
EVENTS.databaseUpdated,
|
|
|
|
|
this.schedule.bind(this)
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
stop() {
|
2022-03-30 20:45:16 +05:00
|
|
|
this.isAutoSyncing = false;
|
2022-03-30 15:52:48 +05:00
|
|
|
clearTimeout(this.timeout);
|
|
|
|
|
if (this.databaseUpdatedEvent) this.databaseUpdatedEvent.unsubscribe();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @private
|
|
|
|
|
*/
|
2022-03-30 20:45:16 +05:00
|
|
|
schedule(id, item) {
|
2022-03-31 14:32:24 +05:00
|
|
|
if (item && (item.remote || item.localOnly || item.failed)) return;
|
2022-03-30 20:45:16 +05:00
|
|
|
|
|
|
|
|
clearTimeout(this.timeout);
|
2022-03-30 15:52:48 +05:00
|
|
|
this.timeout = setTimeout(() => {
|
2022-03-30 20:45:16 +05:00
|
|
|
console.log("SYNC REQUESTED by", id);
|
2022-03-30 15:52:48 +05:00
|
|
|
this.db.eventManager.publish(EVENTS.databaseSyncRequested, false, false);
|
|
|
|
|
}, this.interval);
|
|
|
|
|
}
|
|
|
|
|
}
|