1
0
Fork 0
mirror of https://github.com/sussy-code/smov.git synced 2025-01-18 02:01:24 +01:00
smov/src/stores/bookmarks/BookmarkSyncer.tsx

79 lines
2 KiB
TypeScript
Raw Normal View History

2023-11-19 20:03:35 +01:00
import { useEffect } from "react";
import { addBookmark, removeBookmark } from "@/backend/accounts/bookmarks";
import { useBackendUrl } from "@/hooks/auth/useBackendUrl";
import { AccountWithToken, useAuthStore } from "@/stores/auth";
import { BookmarkUpdateItem, useBookmarkStore } from "@/stores/bookmarks";
const syncIntervalMs = 5 * 1000;
async function syncBookmarks(
items: BookmarkUpdateItem[],
finish: (id: string) => void,
url: string,
account: AccountWithToken | null
) {
for (const item of items) {
// complete it beforehand so it doesn't get handled while in progress
finish(item.id);
if (!account) return; // not logged in, dont sync to server
try {
if (item.action === "delete") {
await removeBookmark(url, account, item.tmdbId);
continue;
}
if (item.action === "add") {
await addBookmark(url, account, {
poster: item.poster,
title: item.title ?? "",
tmdbId: item.tmdbId,
type: item.type ?? "",
year: item.year ?? NaN,
});
continue;
}
} catch (err) {
console.error(
`Failed to sync bookmark: ${item.tmdbId} - ${item.action}`,
err
);
}
}
}
export function BookmarkSyncer() {
const clearUpdateQueue = useBookmarkStore((s) => s.clearUpdateQueue);
const removeUpdateItem = useBookmarkStore((s) => s.removeUpdateItem);
const url = useBackendUrl();
// when booting for the first time, clear update queue.
// we dont want to process persisted update items
useEffect(() => {
clearUpdateQueue();
}, [clearUpdateQueue]);
useEffect(() => {
const interval = setInterval(() => {
(async () => {
const state = useBookmarkStore.getState();
const user = useAuthStore.getState();
await syncBookmarks(
state.updateQueue,
removeUpdateItem,
url,
user.account
);
})();
}, syncIntervalMs);
return () => {
clearInterval(interval);
};
}, [removeUpdateItem, url]);
return null;
}