import { message } from '@tauri-apps/plugin-dialog'; import { platform } from '@tauri-apps/plugin-os'; import { relaunch } from '@tauri-apps/plugin-process'; import Database from '@tauri-apps/plugin-sql'; import { check } from '@tauri-apps/plugin-updater'; import Markdown from 'markdown-to-jsx'; import { PropsWithChildren, createContext, useContext, useEffect, useState } from 'react'; import { LumeStorage } from '@libs/storage/instance'; import { LoaderIcon } from '@shared/icons'; import { QUOTES } from '@stores/constants'; interface StorageContext { db: LumeStorage; } const StorageContext = createContext({ db: undefined, }); const StorageInstance = () => { const [db, setDB] = useState(undefined); const [isNewVersion, setIsNewVersion] = useState(false); const initLumeStorage = async () => { try { const sqlite = await Database.load('sqlite:lume_v2.db'); const platformName = await platform(); const lumeStorage = new LumeStorage(sqlite, platformName); if (!lumeStorage.account) await lumeStorage.getActiveAccount(); const settings = await lumeStorage.getAllSettings(); let autoUpdater = false; if (settings) { settings.forEach((item) => { if (item.key === 'outbox') lumeStorage.settings.outbox = !!parseInt(item.value); if (item.key === 'media') lumeStorage.settings.media = !!parseInt(item.value); if (item.key === 'hashtag') lumeStorage.settings.hashtag = !!parseInt(item.value); if (item.key === 'autoupdate') { if (parseInt(item.value)) autoUpdater = true; } }); } if (autoUpdater) { // check update const update = await check(); // install new version if (update) { setIsNewVersion(true); await update.downloadAndInstall(); await relaunch(); } } setDB(lumeStorage); } catch (e) { await message(`Cannot initialize database: ${e}`, { title: 'Lume', type: 'error', }); } }; useEffect(() => { if (!db) initLumeStorage(); }, []); return { db, isNewVersion }; }; const StorageProvider = ({ children }: PropsWithChildren) => { const { db, isNewVersion } = StorageInstance(); if (!db) return (
TIP:
{QUOTES[Math.floor(Math.random() * QUOTES.length)]}

{isNewVersion ? 'Found a new version, updating...' : 'Starting...'}

); return {children}; }; const useStorage = () => { const context = useContext(StorageContext); if (context === undefined) { throw new Error('Storage not found'); } return context; }; export { StorageProvider, useStorage };