xref: /MusicFree/src/core/config.ts (revision 3d4d06d97c4d26f92447d0589edfb5b2cfaed4d5)
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            rate: number;
78        };
79    };
80}
81
82type FilterType<T, R = never> = T extends Record<string | number, any>
83    ? {
84          [P in keyof T]: T[P] extends ExceptionType ? R : T[P];
85      }
86    : never;
87
88type KeyPaths<
89    T extends object,
90    Root extends boolean = true,
91    R = FilterType<T, ''>,
92    K extends keyof R = keyof R,
93> = K extends string | number
94    ?
95          | (Root extends true ? `${K}` : `.${K}`)
96          | (R[K] extends Record<string | number, any>
97                ? `${Root extends true ? `${K}` : `.${K}`}${KeyPaths<
98                      R[K],
99                      false
100                  >}`
101                : never)
102    : never;
103
104type KeyPathValue<T extends object, K extends string> = T extends Record<
105    string | number,
106    any
107>
108    ? K extends `${infer S}.${infer R}`
109        ? KeyPathValue<T[S], R>
110        : T[K]
111    : never;
112
113type KeyPathsObj<
114    T extends object,
115    K extends string = KeyPaths<T>,
116> = T extends Record<string | number, any>
117    ? {
118          [R in K]: KeyPathValue<T, R>;
119      }
120    : never;
121
122type DeepPartial<T> = {
123    [K in keyof T]?: T[K] extends Record<string | number, any>
124        ? T[K] extends ExceptionType
125            ? T[K]
126            : DeepPartial<T[K]>
127        : T[K];
128};
129
130export type IConfigPaths = KeyPaths<IConfig>;
131type PartialConfig = DeepPartial<IConfig> | null;
132type IConfigPathsObj = KeyPathsObj<DeepPartial<IConfig>, IConfigPaths>;
133
134let config: PartialConfig = null;
135/** 初始化config */
136async function setup() {
137    config = (await getStorage('local-config')) ?? {};
138    // await checkValidPath(['setting.theme.background']);
139    notify();
140}
141
142/** 设置config */
143async function setConfig<T extends IConfigPaths>(
144    key: T,
145    value: IConfigPathsObj[T],
146    shouldNotify = true,
147) {
148    if (config === null) {
149        return;
150    }
151    const keys = key.split('.');
152
153    const result = produce(config, draft => {
154        draft[keys[0] as keyof IConfig] = draft[keys[0] as keyof IConfig] ?? {};
155        let conf: any = draft[keys[0] as keyof IConfig];
156        for (let i = 1; i < keys.length - 1; ++i) {
157            if (!conf?.[keys[i]]) {
158                conf[keys[i]] = {};
159            }
160            conf = conf[keys[i]];
161        }
162        conf[keys[keys.length - 1]] = value;
163        return draft;
164    });
165
166    setStorage('local-config', result);
167    config = result;
168    if (shouldNotify) {
169        notify();
170    }
171}
172
173// todo: 获取兜底
174/** 获取config */
175function getConfig(): PartialConfig;
176function getConfig<T extends IConfigPaths>(key: T): IConfigPathsObj[T];
177function getConfig(key?: string) {
178    let result: any = config;
179    if (key && config) {
180        result = getPathValue(config, key);
181    }
182
183    return result;
184}
185
186/** 通过path获取值 */
187function getPathValue(obj: Record<string, any>, path: string) {
188    const keys = path.split('.');
189    let tmp = obj;
190    for (let i = 0; i < keys.length; ++i) {
191        tmp = tmp?.[keys[i]];
192    }
193    return tmp;
194}
195
196/** 同步hook */
197const notifyCbs = new Set<() => void>();
198function notify() {
199    notifyCbs.forEach(_ => _?.());
200}
201
202/** hook */
203function useConfig(): PartialConfig;
204function useConfig<T extends IConfigPaths>(key: T): IConfigPathsObj[T];
205function useConfig(key?: string) {
206    const [_cfg, _setCfg] = useState<PartialConfig>(config);
207    function setCfg() {
208        _setCfg(config);
209    }
210    useEffect(() => {
211        notifyCbs.add(setCfg);
212        return () => {
213            notifyCbs.delete(setCfg);
214        };
215    }, []);
216
217    if (key) {
218        return _cfg ? getPathValue(_cfg, key) : undefined;
219    } else {
220        return _cfg;
221    }
222}
223
224const Config = {
225    get: getConfig,
226    set: setConfig,
227    useConfig,
228    setup,
229};
230
231export default Config;
232