diff --git a/packages/core/api/index.js b/packages/core/api/index.js index 1a019c95b..f738b42e0 100644 --- a/packages/core/api/index.js +++ b/packages/core/api/index.js @@ -96,8 +96,6 @@ class Database { await this.migrations.migrate(); this.monographs.init(); - - await this.syncer.cleanup(); } async connectSSE() { @@ -114,7 +112,8 @@ class Database { headers: { Authorization: `Bearer ${token}` }, }); - this.evtSource.onopen = function () { + this.evtSource.onopen = async () => { + await this.syncer.cleanup(); console.log("SSE: opened channel successfully!"); }; diff --git a/packages/core/api/sync/index.js b/packages/core/api/sync/index.js index 53d4ba8fd..9b267e57a 100644 --- a/packages/core/api/sync/index.js +++ b/packages/core/api/sync/index.js @@ -145,6 +145,8 @@ export default class Sync { { collection: "content", ids: contentIds }, token ); - } catch (e) {} + } catch (e) { + console.error(e); + } } } diff --git a/packages/core/collections/content.js b/packages/core/collections/content.js index 6698e16a3..4be7986e0 100644 --- a/packages/core/collections/content.js +++ b/packages/core/collections/content.js @@ -57,14 +57,18 @@ export default class Content extends Collection { } async cleanup() { - const allContent = await this.all(); + const indices = this._collection.indexer.indices; + await this._db.notes.init(); + const notes = this._db.notes._collection.getRaw(); let ids = []; - for (let content of allContent) { - const { noteId } = content; - const note = this._db.notes._collection.getItem(noteId); - if (!note || note.contentId !== content.id) { - ids.push(content.id); - await this._collection.deleteItem(content.id); + for (let contentId of indices) { + const noteIndex = notes.findIndex((note) => note.contentId === contentId); + const isOrphaned = noteIndex === -1; + if (isOrphaned) { + ids.push(contentId); + await this._collection.deleteItem(contentId); + } else if (notes[noteIndex].localOnly) { + ids.push(contentId); } } return ids;