xref: /MusicFree/src/entry/bootstrap.ts (revision 6780f402e1a699cde3293b13d6bc38231824d37a)
1import MusicQueue from '@/common/musicQueue';
2import MusicSheet from '@/common/musicSheetManager';
3import {check, PERMISSIONS, request} from 'react-native-permissions';
4import TrackPlayer, {Capability} from 'react-native-track-player';
5import {pluginManager} from '../common/pluginManager';
6import 'react-native-get-random-values';
7import {Platform, ToastAndroid} from 'react-native';
8import {loadConfig} from '@/common/localConfigManager';
9import RNBootSplash from 'react-native-bootsplash';
10import RNFS, {exists, mkdir} from 'react-native-fs';
11import DownloadManager from '@/common/downloadManager';
12import pathConst from '@/constants/pathConst';
13
14/** app加载前执行 */
15export default async function () {
16  // 检查权限
17  const [readStoragePermission, writeStoragePermission] = await Promise.all([
18    check(PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE),
19    check(PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE),
20  ]);
21  if (
22    !(
23      readStoragePermission === 'granted' &&
24      writeStoragePermission === 'granted'
25    )
26  ) {
27    await request(PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE);
28    await request(PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE);
29  }
30
31  /** 初始化路径 */
32  await setupFolder();
33  // 加载配置
34  await loadConfig();
35  // 加载插件
36
37  Promise.all([
38    await pluginManager.setupPlugins(),
39    await TrackPlayer.setupPlayer(),
40  ]);
41  await TrackPlayer.updateOptions({
42    progressUpdateEventInterval: 2,
43    stopWithApp: false,
44    alwaysPauseOnInterruption: true,
45    capabilities: [
46      Capability.Play,
47      Capability.Pause,
48      Capability.SkipToNext,
49      Capability.SkipToPrevious,
50    ],
51    compactCapabilities: [
52      Capability.Play,
53      Capability.Pause,
54      Capability.SkipToNext,
55      Capability.SkipToPrevious,
56    ],
57    notificationCapabilities: [
58      Capability.Play,
59      Capability.Pause,
60      Capability.SkipToNext,
61      Capability.SkipToPrevious,
62    ],
63  });
64  await MusicQueue.setupMusicQueue();
65  await MusicSheet.setupMusicSheet();
66  await DownloadManager.setupDownload();
67
68  ErrorUtils.setGlobalHandler(error =>
69    ToastAndroid.show(`error: ${error?.message}`, ToastAndroid.LONG),
70  );
71  // 隐藏开屏动画
72  RNBootSplash.hide({fade: true});
73}
74
75async function checkAndCreate(path: string) {
76  const filePath = path;
77  if (!(await exists(filePath))) {
78    await mkdir(filePath);
79  }
80}
81/** 初始化 */
82async function setupFolder() {
83  await Promise.all([
84    checkAndCreate(pathConst.dataPath),
85    checkAndCreate(pathConst.storagePath),
86    checkAndCreate(pathConst.pluginPath)
87  ]);
88}
89