import { create } from 'zustand'; import type { GiteaConfig } from './schema'; import { queryLogin } from '@/modules/query'; import { toast } from 'sonner'; type GiteaConfigState = { config: GiteaConfig; setConfig: (config: Partial) => void; resetConfig: () => void; saveToRemote: () => Promise; loadFromRemote: () => Promise; checkConfig: (opts?: { isUser?: boolean, reload?: boolean }) => Promise; }; const DEFAULT_CONFIG: GiteaConfig = { GITEA_TOKEN: '', GITEA_URL: 'https://git.xiongxiao.me', }; const loadInitialConfig = (): GiteaConfig => { try { const token = localStorage.getItem('GITEA_TOKEN') || ''; const url = localStorage.getItem('GITEA_URL') || DEFAULT_CONFIG.GITEA_URL; return { GITEA_TOKEN: token, GITEA_URL: url, }; } catch { // Ignore parse errors } return DEFAULT_CONFIG; }; const saveConfig = (config: GiteaConfig) => { try { localStorage.setItem('GITEA_TOKEN', config.GITEA_TOKEN); localStorage.setItem('GITEA_URL', config.GITEA_URL); } catch (error) { console.error('Failed to save config:', error); } }; export const useGiteaConfigStore = create()((set, get) => ({ config: loadInitialConfig(), setConfig: (newConfig) => set((state) => { const updatedConfig = { ...state.config, ...newConfig }; saveConfig(updatedConfig); return { config: updatedConfig }; }), resetConfig: () => { saveConfig(DEFAULT_CONFIG); return set({ config: DEFAULT_CONFIG }); }, saveToRemote: async () => { const _config = get().config; const res = await queryLogin.post({ path: 'config', key: 'update', data: { key: 'gitea_config.json', data: _config, } }); if (res.code === 200) { toast.success('保存到远端成功') } else { toast.error('保存到远端失败') } }, loadFromRemote: async () => { const setConfig = (config: GiteaConfig) => set({ config }); const res = await queryLogin.post({ path: 'config', key: 'get', data: { key: 'gitea_config.json', } }) if (res.code === 404) { toast.error('远端配置不存在') return false; } if (res.code === 200) { const config = res.data?.data as GiteaConfig; setConfig(config); toast.success('获取远端配置成功') return true; } return false; }, checkConfig: async (opts?: { isUser?: boolean, reload?: boolean }) => { const { GITEA_TOKEN } = get().config; if (!GITEA_TOKEN && opts?.isUser) { const res = await get().loadFromRemote(); if (opts?.reload && res) { location.reload(); } return res; } return false } }));