|
|
@@ -1,3 +1,4 @@
|
|
|
+import { Q } from '@nozbe/watermelondb';
|
|
|
import { database } from 'src/watermelondb';
|
|
|
import Chat from 'src/watermelondb/models/Chat';
|
|
|
|
|
|
@@ -29,21 +30,29 @@ export async function upsertChats(chats: ServerChat[]) {
|
|
|
if (!chats?.length) return;
|
|
|
|
|
|
const chatCollection = database.get<Chat>('chats');
|
|
|
- const existingChats = await chatCollection.query().fetch();
|
|
|
+ const seen = new Set<string>();
|
|
|
+
|
|
|
+ const makeKey = (c: ServerChat) => (c.uid ? `u:${c.uid}` : `g:${c.group_chat_token}`);
|
|
|
|
|
|
await database.write(async () => {
|
|
|
const batch: any[] = [];
|
|
|
|
|
|
for (const c of chats) {
|
|
|
- const existing = existingChats.find(
|
|
|
- (ec) =>
|
|
|
- (ec.chatUid && ec.chatUid === c.uid) ||
|
|
|
- (ec.groupChatToken && ec.groupChatToken === c.group_chat_token)
|
|
|
- );
|
|
|
+ const key = makeKey(c);
|
|
|
+
|
|
|
+ if (seen.has(key)) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
|
|
|
- if (existing) {
|
|
|
+ seen.add(key);
|
|
|
+
|
|
|
+ const existingNow = await chatCollection
|
|
|
+ .query(c.uid ? Q.where('chat_uid', c.uid) : Q.where('group_chat_token', c.group_chat_token))
|
|
|
+ .fetch();
|
|
|
+
|
|
|
+ if (existingNow.length) {
|
|
|
batch.push(
|
|
|
- existing.prepareUpdate((rec) => {
|
|
|
+ existingNow[0].prepareUpdate((rec) => {
|
|
|
rec.name = c.name;
|
|
|
rec.avatar = c.avatar ?? null;
|
|
|
rec.short = c.short;
|
|
|
@@ -102,3 +111,47 @@ export async function upsertChats(chats: ServerChat[]) {
|
|
|
console.log('upsertChats complete');
|
|
|
});
|
|
|
}
|
|
|
+
|
|
|
+export async function dedupeChats() {
|
|
|
+ const chatCollection = database.get<Chat>('chats');
|
|
|
+ const chats = await chatCollection.query().fetch();
|
|
|
+
|
|
|
+ const map = new Map<string, Chat[]>();
|
|
|
+
|
|
|
+ for (const c of chats) {
|
|
|
+ const key = c.chatUid
|
|
|
+ ? `dm:${c.chatUid}`
|
|
|
+ : c.groupChatToken
|
|
|
+ ? `group:${c.groupChatToken}`
|
|
|
+ : null;
|
|
|
+
|
|
|
+ if (!key) continue;
|
|
|
+
|
|
|
+ if (!map.has(key)) map.set(key, []);
|
|
|
+ map.get(key)!.push(c);
|
|
|
+ }
|
|
|
+
|
|
|
+ await database.write(async () => {
|
|
|
+ for (const [, list] of map) {
|
|
|
+ if (list.length <= 1) continue;
|
|
|
+
|
|
|
+ list.sort((a, b) => {
|
|
|
+ if (a.isDirty && !b.isDirty) return -1;
|
|
|
+ if (!a.isDirty && b.isDirty) return 1;
|
|
|
+ return b.updated - a.updated;
|
|
|
+ });
|
|
|
+
|
|
|
+ const [, ...duplicates] = list;
|
|
|
+
|
|
|
+ for (const d of duplicates) {
|
|
|
+ await d.destroyPermanently();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ });
|
|
|
+}
|
|
|
+
|
|
|
+export async function clearLocalDatabaseOnLogout() {
|
|
|
+ await database.write(async () => {
|
|
|
+ await database.unsafeResetDatabase();
|
|
|
+ });
|
|
|
+}
|