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