xref: /MusicFree/src/core/config.ts (revision e5a0c4d718dd8de014c792b182a6f4128092b88f)
1// import {Quality} from '@/constants/commonConst';
2import {CustomizedColors} from '@/hooks/useColors';
3import {getStorage, setStorage} from '@/utils/storage';
4import produce from 'immer';
5import {useEffect, useState} from 'react';
6
7type ExceptionType = IMusic.IMusicItem | IMusic.IMusicItem[] | IMusic.IQuality;
8interface IConfig {
9    setting: {
10        basic: {
11            autoPlayWhenAppStart: boolean;
12            /** 使用移动网络播放 */
13            useCelluarNetworkPlay: boolean;
14            /** 使用移动网络下载 */
15            useCelluarNetworkDownload: boolean;
16            /** 最大同时下载 */
17            maxDownload: number | string;
18            /** 播放歌曲行为 */
19            clickMusicInSearch: '播放歌曲' | '播放歌曲并替换播放列表';
20            /** 点击专辑单曲 */
21            clickMusicInAlbum: '播放专辑' | '播放单曲';
22            /** 下载文件夹 */
23            downloadPath: string;
24            /** 同时播放 */
25            notInterrupt: boolean;
26            /** 打断时 */
27            tempRemoteDuck: '暂停' | '降低音量';
28            /** 播放错误时自动停止 */
29            autoStopWhenError: boolean;
30            /** 插件缓存策略 todo */
31            pluginCacheControl: string;
32            /** 最大音乐缓存 */
33            maxCacheSize: number;
34            /** 默认播放音质 */
35            defaultPlayQuality: IMusic.IQualityKey;
36            /** 音质顺序 */
37            playQualityOrder: 'asc' | 'desc';
38            /** 默认下载音质 */
39            defaultDownloadQuality: IMusic.IQualityKey;
40            /** 下载音质顺序 */
41            downloadQualityOrder: 'asc' | 'desc';
42            /** 歌曲详情页 */
43            musicDetailDefault: 'album' | 'lyric';
44            /** 歌曲详情页常亮 */
45            musicDetailAwake: boolean;
46            debug: {
47                errorLog: boolean;
48                traceLog: boolean;
49                devLog: boolean;
50            };
51            /** 最大历史记录条目 */
52            maxHistoryLen: number;
53            /** 启动时自动更新插件 */
54            autoUpdatePlugin: boolean;
55            // 不检查插件版本号
56            notCheckPluginVersion: boolean;
57            /** 关联歌词方式 */
58            associateLyricType: 'input' | 'search';
59        };
60        /** 歌词 */
61        lyric: {
62            showStatusBarLyric: boolean;
63            topPercent: number;
64            leftPercent: number;
65            align: number;
66            color: string;
67            backgroundColor: string;
68            widthPercent: number;
69            fontSize: number;
70        };
71
72        /** 主题 */
73        theme: {
74            background: string;
75            backgroundOpacity: number;
76            backgroundBlur: number;
77            colors: CustomizedColors;
78            followSystem: boolean;
79            selectedTheme: string;
80        };
81
82        plugin: {
83            subscribeUrl: string;
84        };
85    };
86    status: {
87        music: {
88            /** 当前的音乐 */
89            track: IMusic.IMusicItem;
90            /** 进度 */
91            progress: number;
92            /** 模式 */
93            repeatMode: string;
94            /** 列表 */
95            musicQueue: IMusic.IMusicItem[];
96            /** 速度 */
97            rate: number;
98        };
99        app: {
100            /** 跳过特定版本 */
101            skipVersion: string;
102        };
103    };
104}
105
106type FilterType<T, R = never> = T extends Record<string | number, any>
107    ? {
108          [P in keyof T]: T[P] extends ExceptionType ? R : T[P];
109      }
110    : never;
111
112type KeyPaths<
113    T extends object,
114    Root extends boolean = true,
115    R = FilterType<T, ''>,
116    K extends keyof R = keyof R,
117> = K extends string | number
118    ?
119          | (Root extends true ? `${K}` : `.${K}`)
120          | (R[K] extends Record<string | number, any>
121                ? `${Root extends true ? `${K}` : `.${K}`}${KeyPaths<
122                      R[K],
123                      false
124                  >}`
125                : never)
126    : never;
127
128type KeyPathValue<T extends object, K extends string> = T extends Record<
129    string | number,
130    any
131>
132    ? K extends `${infer S}.${infer R}`
133        ? KeyPathValue<T[S], R>
134        : T[K]
135    : never;
136
137type KeyPathsObj<
138    T extends object,
139    K extends string = KeyPaths<T>,
140> = T extends Record<string | number, any>
141    ? {
142          [R in K]: KeyPathValue<T, R>;
143      }
144    : never;
145
146type DeepPartial<T> = {
147    [K in keyof T]?: T[K] extends Record<string | number, any>
148        ? T[K] extends ExceptionType
149            ? T[K]
150            : DeepPartial<T[K]>
151        : T[K];
152};
153
154export type IConfigPaths = KeyPaths<IConfig>;
155type PartialConfig = DeepPartial<IConfig> | null;
156type IConfigPathsObj = KeyPathsObj<DeepPartial<IConfig>, IConfigPaths>;
157
158let config: PartialConfig = null;
159/** 初始化config */
160async function setup() {
161    config = (await getStorage('local-config')) ?? {};
162    // await checkValidPath(['setting.theme.background']);
163    notify();
164}
165
166/** 设置config */
167async function setConfig<T extends IConfigPaths>(
168    key: T,
169    value: IConfigPathsObj[T],
170    shouldNotify = true,
171) {
172    if (config === null) {
173        return;
174    }
175    const keys = key.split('.');
176
177    const result = produce(config, draft => {
178        draft[keys[0] as keyof IConfig] = draft[keys[0] as keyof IConfig] ?? {};
179        let conf: any = draft[keys[0] as keyof IConfig];
180        for (let i = 1; i < keys.length - 1; ++i) {
181            if (!conf?.[keys[i]]) {
182                conf[keys[i]] = {};
183            }
184            conf = conf[keys[i]];
185        }
186        conf[keys[keys.length - 1]] = value;
187        return draft;
188    });
189
190    setStorage('local-config', result);
191    config = result;
192    if (shouldNotify) {
193        notify();
194    }
195}
196
197// todo: 获取兜底
198/** 获取config */
199function getConfig(): PartialConfig;
200function getConfig<T extends IConfigPaths>(key: T): IConfigPathsObj[T];
201function getConfig(key?: string) {
202    let result: any = config;
203    if (key && config) {
204        result = getPathValue(config, key);
205    }
206
207    return result;
208}
209
210/** 通过path获取值 */
211function getPathValue(obj: Record<string, any>, path: string) {
212    const keys = path.split('.');
213    let tmp = obj;
214    for (let i = 0; i < keys.length; ++i) {
215        tmp = tmp?.[keys[i]];
216    }
217    return tmp;
218}
219
220/** 同步hook */
221const notifyCbs = new Set<() => void>();
222function notify() {
223    notifyCbs.forEach(_ => _?.());
224}
225
226/** hook */
227function useConfig(): PartialConfig;
228function useConfig<T extends IConfigPaths>(key: T): IConfigPathsObj[T];
229function useConfig(key?: string) {
230    // TODO: 应该有性能损失
231    const [_cfg, _setCfg] = useState<PartialConfig>(config);
232    function setCfg() {
233        _setCfg(config);
234    }
235    useEffect(() => {
236        notifyCbs.add(setCfg);
237        return () => {
238            notifyCbs.delete(setCfg);
239        };
240    }, []);
241
242    if (key) {
243        return _cfg ? getPathValue(_cfg, key) : undefined;
244    } else {
245        return _cfg;
246    }
247}
248
249const Config = {
250    get: getConfig,
251    set: setConfig,
252    useConfig,
253    setup,
254};
255
256export default Config;
257