Repository: maotoumao/MusicFree Branch: master Commit: 42fdbd67955e Files: 371 Total size: 1.3 MB Directory structure: gitextract_hqly39f3/ ├── .bundle/ │ └── config ├── .commitlintrc.json ├── .eslintignore ├── .eslintrc.js ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report_zh.yaml │ │ ├── config.yml │ │ └── feature_request_zh.yaml │ └── workflows/ │ └── build-beta.yml ├── .gitignore ├── .husky/ │ ├── commit-msg │ └── pre-commit ├── .prettierrc.js ├── .watchmanconfig ├── Gemfile ├── LICENSE ├── android/ │ ├── app/ │ │ ├── build.gradle │ │ ├── debug.keystore │ │ ├── proguard-rules.pro │ │ └── src/ │ │ ├── debug/ │ │ │ └── AndroidManifest.xml │ │ └── main/ │ │ ├── AndroidManifest.xml │ │ ├── java/ │ │ │ └── fun/ │ │ │ └── upup/ │ │ │ └── musicfree/ │ │ │ ├── MainActivity.kt │ │ │ ├── MainApplication.kt │ │ │ ├── lyricUtil/ │ │ │ │ ├── LyricUtilModule.kt │ │ │ │ ├── LyricUtilPackage.kt │ │ │ │ └── LyricView.kt │ │ │ ├── mp3Util/ │ │ │ │ ├── Mp3UtilModule.kt │ │ │ │ └── Mp3UtilPackage.kt │ │ │ └── utils/ │ │ │ ├── UtilsModule.kt │ │ │ └── UtilsPackage.kt │ │ └── res/ │ │ ├── drawable/ │ │ │ ├── rn_edit_text_material.xml │ │ │ └── splashscreen.xml │ │ ├── mipmap-anydpi-v26/ │ │ │ ├── ic_launcher.xml │ │ │ └── ic_launcher_round.xml │ │ └── values/ │ │ ├── colors.xml │ │ ├── ic_launcher_background.xml │ │ ├── strings.xml │ │ └── styles.xml │ ├── build.gradle │ ├── gradle/ │ │ └── wrapper/ │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties │ ├── gradle.properties │ ├── gradlew │ ├── gradlew.bat │ └── settings.gradle ├── app.json ├── babel.config.js ├── changelog.md ├── generator/ │ └── generate-assets.mjs ├── index.js ├── ios/ │ ├── .xcode.env │ ├── MusicFree/ │ │ ├── AppDelegate.h │ │ ├── AppDelegate.mm │ │ ├── Images.xcassets/ │ │ │ ├── AppIcon.appiconset/ │ │ │ │ └── Contents.json │ │ │ └── Contents.json │ │ ├── Info.plist │ │ ├── LaunchScreen.storyboard │ │ ├── PrivacyInfo.xcprivacy │ │ └── main.m │ ├── MusicFree.xcodeproj/ │ │ ├── project.pbxproj │ │ └── xcshareddata/ │ │ └── xcschemes/ │ │ └── MusicFreeNew.xcscheme │ ├── MusicFreeTests/ │ │ ├── Info.plist │ │ └── MusicFreeNewTests.m │ └── Podfile ├── jest.config.js ├── metro.config.js ├── package.json ├── readme-en.md ├── readme.md ├── release/ │ └── version.json ├── src/ │ ├── components/ │ │ ├── base/ │ │ │ ├── SortableFlatList.tsx │ │ │ ├── appBar.tsx │ │ │ ├── button.tsx │ │ │ ├── checkbox.tsx │ │ │ ├── chip.tsx │ │ │ ├── colorBlock.tsx │ │ │ ├── divider.tsx │ │ │ ├── empty.tsx │ │ │ ├── fab.tsx │ │ │ ├── fastImage.tsx │ │ │ ├── horizontalSafeAreaView.tsx │ │ │ ├── icon.tsx │ │ │ ├── iconButton.tsx │ │ │ ├── iconTextButton.tsx │ │ │ ├── image.tsx │ │ │ ├── imageBtn.tsx │ │ │ ├── input.tsx │ │ │ ├── linkText.tsx │ │ │ ├── listEmpty.tsx │ │ │ ├── listFooter.tsx │ │ │ ├── listItem.tsx │ │ │ ├── loading.tsx │ │ │ ├── noPlugin.tsx │ │ │ ├── pageBackground.tsx │ │ │ ├── paragraph.tsx │ │ │ ├── playAllBar.tsx │ │ │ ├── portal.tsx │ │ │ ├── statusBar.tsx │ │ │ ├── switch.tsx │ │ │ ├── tag.tsx │ │ │ ├── textButton.tsx │ │ │ ├── themeText.tsx │ │ │ ├── tip.tsx │ │ │ ├── toast.tsx │ │ │ ├── typeTag.tsx │ │ │ └── verticalSafeAreaView.tsx │ │ ├── debug/ │ │ │ └── index.tsx │ │ ├── dialogs/ │ │ │ ├── components/ │ │ │ │ ├── base/ │ │ │ │ │ └── index.tsx │ │ │ │ ├── checkStorage.tsx │ │ │ │ ├── downloadDialog.tsx │ │ │ │ ├── editSheetDetail.tsx │ │ │ │ ├── index.ts │ │ │ │ ├── loadingDialog.tsx │ │ │ │ ├── markdownDialog.tsx │ │ │ │ ├── radioDialog.tsx │ │ │ │ ├── setScheduleCloseTimeDialog.tsx │ │ │ │ ├── simpleDialog.tsx │ │ │ │ └── subscribePluginDialog.tsx │ │ │ ├── index.tsx │ │ │ └── useDialog.ts │ │ ├── errorBoundary/ │ │ │ └── index.tsx │ │ ├── mediaItem/ │ │ │ ├── LyricItem.tsx │ │ │ ├── albumItem.tsx │ │ │ ├── musicItem.tsx │ │ │ ├── sheetItem.tsx │ │ │ ├── titleAndTag.tsx │ │ │ └── topListItem.tsx │ │ ├── musicBar/ │ │ │ ├── index.tsx │ │ │ └── musicInfo.tsx │ │ ├── musicList/ │ │ │ └── index.tsx │ │ ├── musicSheetPage/ │ │ │ ├── components/ │ │ │ │ ├── header.tsx │ │ │ │ ├── navBar.tsx │ │ │ │ └── sheetMusicList.tsx │ │ │ └── index.tsx │ │ └── panels/ │ │ ├── base/ │ │ │ ├── panelBase.tsx │ │ │ ├── panelFullscreen.tsx │ │ │ └── panelHeader.tsx │ │ ├── index.tsx │ │ ├── types/ │ │ │ ├── addToMusicSheet.tsx │ │ │ ├── associateLrc.tsx │ │ │ ├── colorPicker.tsx │ │ │ ├── createMusicSheet.tsx │ │ │ ├── editMusicSheetInfo.tsx │ │ │ ├── imageViewer.tsx │ │ │ ├── importMusicSheet.tsx │ │ │ ├── index.ts │ │ │ ├── musicComment/ │ │ │ │ ├── comment.tsx │ │ │ │ ├── index.tsx │ │ │ │ └── useComments.ts │ │ │ ├── musicItemLyricOptions.tsx │ │ │ ├── musicItemOptions.tsx │ │ │ ├── musicQuality.tsx │ │ │ ├── playList/ │ │ │ │ ├── body.tsx │ │ │ │ ├── header.tsx │ │ │ │ └── index.tsx │ │ │ ├── playRate.tsx │ │ │ ├── searchLrc/ │ │ │ │ ├── LyricList.tsx │ │ │ │ ├── index.tsx │ │ │ │ ├── searchResultStore.ts │ │ │ │ └── useSearchLrc.ts │ │ │ ├── setFontSize.tsx │ │ │ ├── setLyricOffset.tsx │ │ │ ├── setUserVariables.tsx │ │ │ ├── sheetTags.tsx │ │ │ ├── simpleInput.tsx │ │ │ ├── simpleSelect.tsx │ │ │ └── timingClose.tsx │ │ └── usePanel.ts │ ├── constants/ │ │ ├── assetsConst.ts │ │ ├── commonConst.ts │ │ ├── globalStyle.ts │ │ ├── pathConst.ts │ │ ├── repeatModeConst.ts │ │ └── uiConst.ts │ ├── core/ │ │ ├── appConfig.ts │ │ ├── appMeta.ts │ │ ├── backup.ts │ │ ├── downloader.ts │ │ ├── i18n/ │ │ │ ├── index.ts │ │ │ └── languages/ │ │ │ ├── en-us.json │ │ │ ├── zh-cn.json │ │ │ └── zh-tw.json │ │ ├── localMusicSheet.ts │ │ ├── lyricManager.ts │ │ ├── mediaCache.ts │ │ ├── musicHistory.ts │ │ ├── musicSheet/ │ │ │ ├── index.ts │ │ │ ├── migrate.ts │ │ │ ├── sortedMusicList.ts │ │ │ └── storage.ts │ │ ├── pluginManager/ │ │ │ ├── index.ts │ │ │ ├── meta.ts │ │ │ └── plugin.ts │ │ ├── router/ │ │ │ ├── index.ts │ │ │ └── routes.tsx │ │ ├── theme.ts │ │ └── trackPlayer/ │ │ └── index.ts │ ├── core.defination/ │ │ └── trackPlayer/ │ │ └── index.ts │ ├── entry/ │ │ ├── bootstrap/ │ │ │ ├── BootstrapComponent.tsx │ │ │ ├── bootstrap.atom.ts │ │ │ └── bootstrap.ts │ │ └── index.tsx │ ├── hooks/ │ │ ├── useCheckUpdate.ts │ │ ├── useColors.ts │ │ ├── useDelayFalsy.ts │ │ ├── useHardwareBack.ts │ │ ├── useLogRerender.ts │ │ ├── useMounted.ts │ │ ├── useOnceEffect.ts │ │ ├── useOrientation.ts │ │ ├── usePrimaryColor.ts │ │ ├── useRerender.ts │ │ └── useTextColor.ts │ ├── lib/ │ │ └── react-native-vdebug/ │ │ ├── index.js │ │ └── src/ │ │ ├── event.js │ │ ├── hoc.js │ │ ├── log.js │ │ ├── network.js │ │ ├── storage.js │ │ └── tool.js │ ├── native/ │ │ ├── lyricUtil/ │ │ │ └── index.ts │ │ ├── mp3Util/ │ │ │ └── index.ts │ │ └── utils/ │ │ └── index.ts │ ├── pages/ │ │ ├── albumDetail/ │ │ │ ├── hooks/ │ │ │ │ └── useAlbumMusicList.ts │ │ │ └── index.tsx │ │ ├── artistDetail/ │ │ │ ├── components/ │ │ │ │ ├── body.tsx │ │ │ │ ├── content/ │ │ │ │ │ ├── albumContentItem.tsx │ │ │ │ │ ├── index.ts │ │ │ │ │ └── musicContentItem.tsx │ │ │ │ ├── header.tsx │ │ │ │ └── resultList.tsx │ │ │ ├── hooks/ │ │ │ │ └── useQuery.ts │ │ │ ├── index.tsx │ │ │ └── store/ │ │ │ └── atoms.ts │ │ ├── downloading/ │ │ │ ├── downloadingList.tsx │ │ │ └── index.tsx │ │ ├── fileSelector/ │ │ │ ├── fileItem.tsx │ │ │ └── index.tsx │ │ ├── history/ │ │ │ └── index.tsx │ │ ├── home/ │ │ │ ├── components/ │ │ │ │ ├── ActionButton.tsx │ │ │ │ ├── drawer/ │ │ │ │ │ └── index.tsx │ │ │ │ ├── homeBody/ │ │ │ │ │ ├── index.tsx │ │ │ │ │ ├── operations.tsx │ │ │ │ │ └── sheets.tsx │ │ │ │ ├── homeBodyHorizontal/ │ │ │ │ │ ├── index.tsx │ │ │ │ │ └── operations.tsx │ │ │ │ └── navBar.tsx │ │ │ └── index.tsx │ │ ├── localMusic/ │ │ │ ├── index.tsx │ │ │ └── mainPage/ │ │ │ ├── index.tsx │ │ │ └── localMusicList.tsx │ │ ├── musicDetail/ │ │ │ ├── components/ │ │ │ │ ├── background.tsx │ │ │ │ ├── bottom/ │ │ │ │ │ ├── index.tsx │ │ │ │ │ ├── playControl.tsx │ │ │ │ │ └── seekBar.tsx │ │ │ │ ├── content/ │ │ │ │ │ ├── albumCover/ │ │ │ │ │ │ ├── index.tsx │ │ │ │ │ │ └── operations.tsx │ │ │ │ │ ├── heartIcon/ │ │ │ │ │ │ └── index.tsx │ │ │ │ │ ├── index.tsx │ │ │ │ │ └── lyric/ │ │ │ │ │ ├── draggingTime.tsx │ │ │ │ │ ├── index.tsx │ │ │ │ │ ├── lyricItem.tsx │ │ │ │ │ └── lyricOperations.tsx │ │ │ │ └── navBar.tsx │ │ │ └── index.tsx │ │ ├── musicListEditor/ │ │ │ ├── components/ │ │ │ │ ├── body.tsx │ │ │ │ ├── bottom.tsx │ │ │ │ └── musicList.tsx │ │ │ ├── index.tsx │ │ │ └── store/ │ │ │ └── atom.ts │ │ ├── permissions/ │ │ │ └── index.tsx │ │ ├── pluginSheetDetail/ │ │ │ ├── hooks/ │ │ │ │ └── usePluginSheetMusicList.ts │ │ │ └── index.tsx │ │ ├── recommendSheets/ │ │ │ ├── components/ │ │ │ │ └── body/ │ │ │ │ ├── index.tsx │ │ │ │ ├── sheetBody.tsx │ │ │ │ └── sheetList.tsx │ │ │ ├── hooks/ │ │ │ │ ├── useRecommendListTags.ts │ │ │ │ └── useRecommendSheets.ts │ │ │ └── index.tsx │ │ ├── searchMusicList/ │ │ │ ├── index.tsx │ │ │ └── searchResult.tsx │ │ ├── searchPage/ │ │ │ ├── common/ │ │ │ │ └── historySearch.ts │ │ │ ├── components/ │ │ │ │ ├── historyPanel.tsx │ │ │ │ ├── navBar.tsx │ │ │ │ └── resultPanel/ │ │ │ │ ├── index.tsx │ │ │ │ ├── resultSubPanel.tsx │ │ │ │ ├── resultWrapper.tsx │ │ │ │ └── results/ │ │ │ │ ├── albumResultItem.tsx │ │ │ │ ├── artistResultItem.tsx │ │ │ │ ├── defaultResults.tsx │ │ │ │ ├── index.ts │ │ │ │ ├── musicResultItem.tsx │ │ │ │ └── musicSheetResultItem.tsx │ │ │ ├── hooks/ │ │ │ │ └── useSearch.ts │ │ │ ├── index.tsx │ │ │ └── store/ │ │ │ └── atoms.ts │ │ ├── setCustomTheme/ │ │ │ ├── body.tsx │ │ │ └── index.tsx │ │ ├── setting/ │ │ │ ├── index.tsx │ │ │ └── settingTypes/ │ │ │ ├── aboutSetting.tsx │ │ │ ├── backupSetting.tsx │ │ │ ├── basicSetting.tsx │ │ │ ├── index.ts │ │ │ ├── pluginSetting/ │ │ │ │ ├── components/ │ │ │ │ │ └── pluginItem.tsx │ │ │ │ ├── index.tsx │ │ │ │ └── views/ │ │ │ │ ├── pluginList.tsx │ │ │ │ ├── pluginSort.tsx │ │ │ │ └── pluginSubscribe.tsx │ │ │ └── themeSetting/ │ │ │ ├── background.tsx │ │ │ ├── index.tsx │ │ │ ├── logoCard.tsx │ │ │ ├── mode.tsx │ │ │ └── themeCard.tsx │ │ ├── sheetDetail/ │ │ │ ├── components/ │ │ │ │ ├── header.tsx │ │ │ │ ├── navBar.tsx │ │ │ │ └── sheetMusicList.tsx │ │ │ └── index.tsx │ │ ├── topList/ │ │ │ ├── components/ │ │ │ │ ├── boardPanel.tsx │ │ │ │ ├── boardPanelWrapper.tsx │ │ │ │ └── topListBody.tsx │ │ │ ├── hooks/ │ │ │ │ └── useGetTopList.ts │ │ │ ├── index.tsx │ │ │ └── store/ │ │ │ └── atoms.ts │ │ └── topListDetail/ │ │ ├── hooks/ │ │ │ └── useTopListDetail.ts │ │ └── index.tsx │ ├── service/ │ │ └── index.ts │ ├── types/ │ │ ├── album.d.ts │ │ ├── artist.d.ts │ │ ├── common.d.ts │ │ ├── core/ │ │ │ ├── config.d.ts │ │ │ ├── i18n/ │ │ │ │ └── index.d.ts │ │ │ ├── musicHistory.d.ts │ │ │ ├── pluginManager/ │ │ │ │ └── index.d.ts │ │ │ └── trackPlayer/ │ │ │ └── index.d.ts │ │ ├── declarations.d.ts │ │ ├── infra.d.ts │ │ ├── lyric.d.ts │ │ ├── media.d.ts │ │ ├── music.d.ts │ │ ├── musicSheet.d.ts │ │ ├── musicSheetGroup.d.ts │ │ └── plugin.d.ts │ └── utils/ │ ├── base64.ts │ ├── checkUpdate.ts │ ├── colorUtil.ts │ ├── delay.ts │ ├── eventBus.ts │ ├── fileUtils.ts │ ├── getOrCreateMMKV.ts │ ├── getUrlExt.ts │ ├── htmlUtil.ts │ ├── jsonUtil.ts │ ├── log.ts │ ├── lrcParser.ts │ ├── mediaExtra.ts │ ├── mediaIndexMap.ts │ ├── mediaUtils.ts │ ├── minDistance.ts │ ├── network.ts │ ├── notImplementedFunction.ts │ ├── openUrl.ts │ ├── perfLogger.ts │ ├── persistStatus.ts │ ├── qualities.ts │ ├── rpx.ts │ ├── scheduleClose.ts │ ├── stateMapper.ts │ ├── storage.ts │ ├── timeformat.ts │ ├── toast.ts │ └── trackUtils.ts └── tsconfig.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .bundle/config ================================================ BUNDLE_PATH: "vendor/bundle" BUNDLE_FORCE_RUBY_PLATFORM: 1 ================================================ FILE: .commitlintrc.json ================================================ { "extends": ["@commitlint/config-conventional"], "rules": { "type-enum": [ 2, "always", [ "ci", "chore", "docs", "feat", "fix", "perf", "refactor", "revert", "style" ] ] } } ================================================ FILE: .eslintignore ================================================ src/lib/* ================================================ FILE: .eslintrc.js ================================================ module.exports = { root: true, extends: ['@react-native', 'prettier'], overrides: [ { files: ['*.ts', '*.tsx'], rules: { '@typescript-eslint/no-shadow': 'warn', 'no-shadow': 'off', 'no-undef': 'off', 'react-hooks/exhaustive-deps': 'warn', '@typescript-eslint/object-curly-spacing': ['error', 'always'], "quotes": ["warn", "double"], "object-curly-spacing": ["error", "always"], "indent": ["error", 4], "semi": ["error", "always"], "comma-dangle": ["error", "always-multiline"], "brace-style": ["error", "1tbs"], }, }, ], }; ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report_zh.yaml ================================================ --- name: 反馈问题 description: 问题反馈模板 labels: ["bug"] body: - type: markdown attributes: value: "## 不要在此仓库提和具体插件有关的问题!!!" - type: checkboxes attributes: label: 提问题之前,请先确认 description: "请勾选以下确认项" options: - label: "已经阅读过Q&A (https://musicfree.catcat.work/qa/mobile.html)" required: true - label: "要提出的问题与插件功能无关(类似某个插件搜索结果不全、ip被封禁等请找对应插件作者,在此仓库下提具体插件的问题将会被直接关闭)" required: true - label: "不与其他已有issue重复" required: true - type: textarea id: system_info attributes: label: 系统信息 description: "请填写以下系统信息" placeholder: | 软件版本: 系统版本: 设备型号: validations: required: true - type: textarea id: problem_description attributes: label: 问题描述 description: "请详细描述问题现象及预期正确行为" placeholder: "例如:当执行XX操作时,出现XX现象,预期应该XX..." validations: required: true - type: textarea id: reproduction_steps attributes: label: 复现步骤 description: "请按顺序描述复现步骤" placeholder: | 1. 打开应用 2. 点击XX按钮 3. ... validations: required: true - type: textarea id: screenshots_logs attributes: label: 截图 & 日志 description: "请粘贴截图链接或错误日志(可拖放文件直接上传截图)" placeholder: "错误日志示例:\n[2023-01-01 12:00] ERROR: xxxx" validations: required: false ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ blank_issues_enabled: false contact_links: - name: 讨论区 url: https://github.com/maotoumao/MusicFree/discussions about: 在这里讨论或寻求帮助 ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request_zh.yaml ================================================ --- name: 提交新需求 description: 新功能需求模板 labels: ["feature"] body: - type: checkboxes attributes: label: 提需求之前,请先确认 description: "请检查以下确认项" options: - label: "已经阅读过Q&A (https://musicfree.catcat.work/qa/mobile.html)" required: true - label: "新需求不是仅仅满足个人口味的需求" required: true - label: "新需求不与其他已有issue重复" required: true - label: "我可以在代码、测试上提供帮助" required: false - type: textarea id: feature_description attributes: label: 需求描述 description: "请详细说明需求背景、使用场景和预期效果" placeholder: | 例如: - 当前存在的痛点是什么? - 希望如何解决这个问题? - 预期的使用体验是怎样的? validations: required: true - type: textarea id: attachments attributes: label: 附件信息(可选) description: "可拖放上传示意图/设计稿" placeholder: "设计稿说明或云文档链接..." validations: required: false ================================================ FILE: .github/workflows/build-beta.yml ================================================ name: Beta 构建 on: push: branches: [dev] paths: ['package.json'] workflow_dispatch: inputs: force_build: description: '强制构建 Beta 版本' required: false default: 'false' type: boolean jobs: check-version: if: github.actor == 'maotoumao' || github.event_name == 'push' runs-on: ubuntu-latest outputs: should_build: ${{ steps.version_check.outputs.should_build }} version: ${{ steps.version_check.outputs.version }} steps: - name: Checkout uses: actions/checkout@v4 - name: Check version format id: version_check run: | VERSION=$(node -p "require('./package.json').version") echo "Current version: $VERSION" # 检查版本是否符合 -beta.xx 格式 if [[ $VERSION =~ -beta\.[0-9]{1,2}$ ]]; then echo "✅ Version matches beta format: $VERSION" echo "should_build=true" >> $GITHUB_OUTPUT echo "version=$VERSION" >> $GITHUB_OUTPUT elif [[ "${{ github.event_name }}" == "workflow_dispatch" && "${{ inputs.force_build }}" == "true" ]]; then echo "🔧 Force build triggered by workflow_dispatch" echo "should_build=true" >> $GITHUB_OUTPUT echo "version=$VERSION" >> $GITHUB_OUTPUT else echo "❌ Version does not match beta format or not forced: $VERSION" echo "should_build=false" >> $GITHUB_OUTPUT fi build-beta: needs: check-version if: needs.check-version.outputs.should_build == 'true' runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4 - name: Setup Java uses: actions/setup-java@v4 with: java-version: '17' distribution: 'temurin' cache: 'gradle' - name: Setup Node.js uses: actions/setup-node@v4 with: node-version: 20 cache: 'npm' - name: Cache React Native dependencies uses: actions/cache@v4 with: path: | node_modules ~/.gradle/caches ~/.gradle/wrapper android/.gradle key: ${{ runner.os }}-rn-${{ hashFiles('package-lock.json', 'android/gradle/wrapper/gradle-wrapper.properties') }} restore-keys: | ${{ runner.os }}-rn- - name: Install Dependencies run: npm ci --prefer-offline --no-audit - name: Setup Keystore (if secrets available) if: ${{ secrets.RELEASE_KEYSTORE_BASE64 != '' }} run: | echo "${{ secrets.RELEASE_KEYSTORE_BASE64 }}" | base64 -d > android/app/release.keystore cat > android/keystore.properties << 'EOF' RELEASE_STORE_FILE=release.keystore RELEASE_STORE_PASSWORD=${{ secrets.RELEASE_STORE_PASSWORD }} RELEASE_KEY_ALIAS=${{ secrets.RELEASE_KEY_ALIAS }} RELEASE_KEY_PASSWORD=${{ secrets.RELEASE_KEY_PASSWORD }} EOF chmod 600 android/keystore.properties android/app/release.keystore - name: Make gradlew executable run: chmod +x android/gradlew - name: Build Beta APK run: | cd android ./gradlew assembleRelease --parallel --build-cache --configure-on-demand - name: List generated APKs run: | echo "📱 Generated APK files:" find android/app/build/outputs/apk/release -name "*.apk" -exec ls -lh {} \; - name: Upload Beta APKs uses: actions/upload-artifact@v4 with: name: beta-apks-${{ needs.check-version.outputs.version }} path: android/app/build/outputs/apk/release/*.apk retention-days: 30 - name: Build Summary run: | echo "🎉 Beta build completed successfully!" echo "📦 Version: ${{ needs.check-version.outputs.version }}" echo "🚀 Triggered by: ${{ github.event_name }}" echo "👤 Actor: ${{ github.actor }}" ================================================ FILE: .gitignore ================================================ # OSX # .DS_Store # Xcode # build/ *.pbxuser !default.pbxuser *.mode1v3 !default.mode1v3 *.mode2v3 !default.mode2v3 *.perspectivev3 !default.perspectivev3 xcuserdata *.xccheckout *.moved-aside DerivedData *.hmap *.ipa *.xcuserstate **/.xcode.env.local # Android/IntelliJ # build/ .idea .gradle local.properties *.iml *.hprof .cxx/ *.keystore !debug.keystore # node.js # node_modules/ npm-debug.log yarn-error.log # fastlane # # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the # screenshots whenever they are needed. # For more information about the recommended setup visit: # https://docs.fastlane.tools/best-practices/source-control/ **/fastlane/report.xml **/fastlane/Preview.html **/fastlane/screenshots **/fastlane/test_output # Bundle artifact *.jsbundle # Ruby / CocoaPods **/Pods/ /vendor/bundle/ # Temporary files created by Metro to check the health of the file watcher .metro-health-check* # testing /coverage # Yarn .yarn/* !.yarn/patches !.yarn/plugins !.yarn/releases !.yarn/sdks !.yarn/versions keystore.properties .VSCodeCounter/ .vscode/ tmp/ scripts/ *.log # Expo .expo dist/ web-build/ ================================================ FILE: .husky/commit-msg ================================================ npm run commit-lint ================================================ FILE: .husky/pre-commit ================================================ npm run lint-staged ================================================ FILE: .prettierrc.js ================================================ module.exports = { arrowParens: 'avoid', bracketSameLine: true, bracketSpacing: false, singleQuote: true, trailingComma: 'all', tabWidth: 4, useTabs: false, endOfLine: "auto" }; ================================================ FILE: .watchmanconfig ================================================ {} ================================================ FILE: Gemfile ================================================ source 'https://rubygems.org' # You may use http://rbenv.org/ or https://rvm.io/ to install and use this version ruby ">= 2.6.10" # Exclude problematic versions of cocoapods and activesupport that causes build failures. gem 'cocoapods', '>= 1.13', '!= 1.15.0', '!= 1.15.1' gem 'activesupport', '>= 6.1.7.5', '!= 7.1.0' gem 'xcodeproj', '< 1.26.0' ================================================ FILE: LICENSE ================================================ GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . ================================================ FILE: android/app/build.gradle ================================================ apply plugin: "com.android.application" apply plugin: "org.jetbrains.kotlin.android" apply plugin: "com.facebook.react" import com.android.build.OutputFile import groovy.json.JsonSlurper /** * This is the configuration block to customize your React Native Android app. * By default you don't need to apply any configuration, just uncomment the lines you need. */ react { /* Folders */ // The root of your project, i.e. where "package.json" lives. Default is '../..' // root = file("../../") // The folder where the react-native NPM package is. Default is ../../node_modules/react-native // reactNativeDir = file("../../node_modules/react-native") // The folder where the react-native Codegen package is. Default is ../../node_modules/@react-native/codegen // codegenDir = file("../../node_modules/@react-native/codegen") // The cli.js file which is the React Native CLI entrypoint. Default is ../../node_modules/react-native/cli.js // cliFile = file("../../node_modules/react-native/cli.js") /* Variants */ // The list of variants to that are debuggable. For those we're going to // skip the bundling of the JS bundle and the assets. By default is just 'debug'. // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants. // debuggableVariants = ["liteDebug", "prodDebug"] /* Bundling */ // A list containing the node command and its flags. Default is just 'node'. // nodeExecutableAndArgs = ["node"] // // The command to run when bundling. By default is 'bundle' // bundleCommand = "ram-bundle" // // The path to the CLI configuration file. Default is empty. // bundleConfig = file(../rn-cli.config.js) // // The name of the generated asset file containing your JS bundle // bundleAssetName = "MyApplication.android.bundle" // // The entry file for bundle generation. Default is 'index.android.js' or 'index.js' // entryFile = file("../js/MyApplication.android.js") // // A list of extra flags to pass to the 'bundle' commands. // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle // extraPackagerArgs = [] /* Hermes Commands */ // The hermes compiler command to run. By default it is 'hermesc' // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc" // // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map" // hermesFlags = ["-O", "-output-source-map"] /* Autolinking */ autolinkLibrariesWithApp() // // Added by install-expo-modules entryFile = file(["node", "-e", "require('expo/scripts/resolveAppEntry')", rootDir.getAbsoluteFile().getParentFile().getAbsolutePath(), "android", "absolute"].execute(null, rootDir).text.trim()) cliFile = new File(["node", "--print", "require.resolve('@expo/cli')"].execute(null, rootDir).text.trim()) bundleCommand = "export:embed" // // Added by install-expo-modules entryFile = file(["node", "-e", "require('expo/scripts/resolveAppEntry')", rootDir.getAbsoluteFile().getParentFile().getAbsolutePath(), "android", "absolute"].execute(null, rootDir).text.trim()) cliFile = new File(["node", "--print", "require.resolve('@expo/cli')"].execute(null, rootDir).text.trim()) bundleCommand = "export:embed" } /** * Set this to true to Run Proguard on Release builds to minify the Java bytecode. */ def enableProguardInReleaseBuilds = false /** * The preferred build flavor of JavaScriptCore (JSC) * * For example, to use the international variant, you can use: * `def jscFlavor = 'org.webkit:android-jsc-intl:+'` * * The international variant includes ICU i18n library and necessary data * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that * give correct results when using with locales other than en-US. Note that * this variant is about 6MiB larger per architecture than default. */ def jscFlavor = 'org.webkit:android-jsc:+' // !! Add lines def keystoreProperties = new Properties() def keystorePropertiesFile = rootProject.file('keystore.properties') if (keystorePropertiesFile.exists()) { keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) } static def getVersion() { def inputFile = new File("../package.json") def packageJson = new JsonSlurper().parseText(inputFile.text) return packageJson["version"] } // static def versionStringToCode(String version) { // def parts = version.split('\\.') // def versionCode = 0 // def multiplier = 1000000 // // parts.each { part -> // versionCode += part.toInteger() * multiplier // multiplier /= 1000 // } // // return versionCode.intValue() // } def appVersion = getVersion() def appVersionCode = 400011 android { ndkVersion rootProject.ext.ndkVersion buildToolsVersion rootProject.ext.buildToolsVersion compileSdk rootProject.ext.compileSdkVersion namespace "fun.upup.musicfree" defaultConfig { applicationId "fun.upup.musicfree" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode appVersionCode versionName appVersion } signingConfigs { debug { storeFile file('debug.keystore') storePassword 'android' keyAlias 'androiddebugkey' keyPassword 'android' } // !! Add lines release { storeFile file(keystoreProperties['RELEASE_STORE_FILE']) storePassword keystoreProperties['RELEASE_STORE_PASSWORD'] keyAlias keystoreProperties['RELEASE_KEY_ALIAS'] keyPassword keystoreProperties['RELEASE_KEY_PASSWORD'] } } splits { abi { reset() enable true universalApk true include "armeabi-v7a", "arm64-v8a", "x86", "x86_64" } } buildTypes { debug { signingConfig signingConfigs.debug } release { // Caution! In production, you need to generate your own keystore file. // see https://reactnative.dev/docs/signed-apk-android. signingConfig signingConfigs.release minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" } } } dependencies { // The version of react-native is set by the React Native Gradle Plugin implementation("com.facebook.react:react-android") if (hermesEnabled.toBoolean()) { implementation("com.facebook.react:hermes-android") } else { implementation jscFlavor } // !! Add lines implementation project(':react-native-fs') implementation 'com.facebook.fresco:animated-gif:2.5.0' // https://mvnrepository.com/artifact/net.jthink/jaudiotagger implementation 'net.jthink:jaudiotagger:2.2.5' implementation 'androidx.core:core-splashscreen:1.0.0' } ================================================ FILE: android/app/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: ================================================ FILE: android/app/src/debug/AndroidManifest.xml ================================================ ================================================ FILE: android/app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: android/app/src/main/java/fun/upup/musicfree/MainActivity.kt ================================================ package `fun`.upup.musicfree import expo.modules.ReactActivityDelegateWrapper import expo.modules.splashscreen.SplashScreenManager import com.facebook.react.ReactActivity import com.facebook.react.ReactActivityDelegate import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled import com.facebook.react.defaults.DefaultReactActivityDelegate import android.os.Bundle class MainActivity : ReactActivity() { /** * Returns the name of the main component registered from JavaScript. This is used to schedule * rendering of the component. */ override fun getMainComponentName(): String = "MusicFree" /** * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate] * which allows you to enable New Architecture with a single boolean flags [fabricEnabled] */ override fun createReactActivityDelegate(): ReactActivityDelegate = ReactActivityDelegateWrapper(this, BuildConfig.IS_NEW_ARCHITECTURE_ENABLED, DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)) // https://reactnavigation.org/docs/getting-started/#installing-dependencies-into-a-bare-react-native-project override fun onCreate(savedInstanceState: Bundle?) { SplashScreenManager.registerOnActivity(this) super.onCreate(null); } } ================================================ FILE: android/app/src/main/java/fun/upup/musicfree/MainApplication.kt ================================================ package `fun`.upup.musicfree import android.content.res.Configuration import expo.modules.ApplicationLifecycleDispatcher import expo.modules.ReactNativeHostWrapper import android.app.Application import com.facebook.react.PackageList import com.facebook.react.ReactApplication import com.facebook.react.ReactHost import com.facebook.react.ReactNativeHost import com.facebook.react.ReactPackage import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost import com.facebook.react.defaults.DefaultReactNativeHost import com.facebook.react.soloader.OpenSourceMergedSoMapping import com.facebook.soloader.SoLoader import `fun`.upup.musicfree.lyricUtil.LyricUtilPackage import `fun`.upup.musicfree.mp3Util.Mp3UtilPackage import `fun`.upup.musicfree.utils.UtilsPackage class MainApplication : Application(), ReactApplication { override val reactNativeHost: ReactNativeHost = ReactNativeHostWrapper(this, object : DefaultReactNativeHost(this) { override fun getPackages(): List = PackageList(this).packages.apply { // Packages that cannot be autolinked yet can be added manually here, for example: // add(MyReactNativePackage()) add(UtilsPackage()) add(Mp3UtilPackage()) add(LyricUtilPackage()) } override fun getJSMainModuleName(): String = "index" override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED }) override val reactHost: ReactHost get() = ReactNativeHostWrapper.createReactHost(applicationContext, reactNativeHost) override fun onCreate() { super.onCreate() SoLoader.init(this, OpenSourceMergedSoMapping) if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) { // If you opted-in for the New Architecture, we load the native entry point for this app. load() } ApplicationLifecycleDispatcher.onApplicationCreate(this) } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) ApplicationLifecycleDispatcher.onConfigurationChanged(this, newConfig) } } ================================================ FILE: android/app/src/main/java/fun/upup/musicfree/lyricUtil/LyricUtilModule.kt ================================================ package `fun`.upup.musicfree.lyricUtil import android.app.Activity import android.content.Intent import android.net.Uri import android.os.Build import android.provider.Settings import android.util.Log import androidx.annotation.RequiresApi import com.facebook.react.bridge.* import java.util.* class LyricUtilModule(private val reactContext: ReactApplicationContext): ReactContextBaseJavaModule(reactContext) { override fun getName() = "LyricUtil" private var lyricView: LyricView? = null @ReactMethod fun checkSystemAlertPermission(promise: Promise) { try { promise.resolve(Settings.canDrawOverlays(reactContext)) } catch (e: Exception) { promise.reject("Error", e.message) } } @ReactMethod fun requestSystemAlertPermission(promise: Promise) { try { val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION).apply { data = Uri.parse("package:" + reactContext.packageName) } currentActivity?.startActivity(intent) promise.resolve(true) } catch (e: Exception) { promise.reject("Error", e.message) } } @ReactMethod fun showStatusBarLyric(initLyric: String?, options: ReadableMap?, promise: Promise) { try { UiThreadUtil.runOnUiThread { if (lyricView == null) { lyricView = LyricView(reactContext) } val mapOptions = mutableMapOf().apply { if (options == null) { return@apply } if (options.hasKey("topPercent")) { put("topPercent", options.getDouble("topPercent")) } if (options.hasKey("leftPercent")) { put("leftPercent", options.getDouble("leftPercent")) } if (options.hasKey("align")) { put("align", options.getInt("align")) } if (options.hasKey("color")) { options.getString("color")?.let { put("color", it) } } if (options.hasKey("backgroundColor")) { options.getString("backgroundColor")?.let { put("backgroundColor", it) } } if (options.hasKey("widthPercent")) { put("widthPercent", options.getDouble("widthPercent")) } if (options.hasKey("fontSize")) { put("fontSize", options.getDouble("fontSize")) } } try { lyricView?.showLyricWindow(initLyric, mapOptions) promise.resolve(true) } catch (e: Exception) { promise.reject("Exception", e.message) } } } catch (e: Exception) { promise.reject("Exception", e.message) } } @ReactMethod fun hideStatusBarLyric(promise: Promise) { try { UiThreadUtil.runOnUiThread { lyricView?.hideLyricWindow() } promise.resolve(true) } catch (e: Exception) { promise.reject("Exception", e.message) } } @ReactMethod fun setStatusBarLyricText(lyric: String, promise: Promise) { try { UiThreadUtil.runOnUiThread { lyricView?.setText(lyric) } promise.resolve(true) } catch (e: Exception) { promise.reject("Exception", e.message) } } @ReactMethod fun setStatusBarLyricAlign(alignment: Int, promise: Promise) { try { UiThreadUtil.runOnUiThread { lyricView?.setAlign(alignment) } promise.resolve(true) } catch (e: Exception) { promise.reject("Exception", e.message) } } @ReactMethod fun setStatusBarLyricTop(pct: Double, promise: Promise) { try { UiThreadUtil.runOnUiThread { lyricView?.setTopPercent(pct) } promise.resolve(true) } catch (e: Exception) { promise.reject("Exception", e.message) } } @ReactMethod fun setStatusBarLyricLeft(pct: Double, promise: Promise) { try { UiThreadUtil.runOnUiThread { lyricView?.setLeftPercent(pct) } promise.resolve(true) } catch (e: Exception) { promise.reject("Exception", e.message) } } @ReactMethod fun setStatusBarLyricWidth(pct: Double, promise: Promise) { try { UiThreadUtil.runOnUiThread { lyricView?.setWidth(pct) } promise.resolve(true) } catch (e: Exception) { promise.reject("Exception", e.message) } } @ReactMethod fun setStatusBarLyricFontSize(fontSize: Float, promise: Promise) { try { UiThreadUtil.runOnUiThread { lyricView?.setFontSize(fontSize) } promise.resolve(true) } catch (e: Exception) { promise.reject("Exception", e.message) } } @ReactMethod fun setStatusBarColors(textColor: String?, backgroundColor: String?, promise: Promise) { try { UiThreadUtil.runOnUiThread { lyricView?.setColors(textColor, backgroundColor) } promise.resolve(true) } catch (e: Exception) { promise.reject("Exception", e.message) } } } ================================================ FILE: android/app/src/main/java/fun/upup/musicfree/lyricUtil/LyricUtilPackage.kt ================================================ package `fun`.upup.musicfree.lyricUtil import android.view.View import com.facebook.react.ReactPackage import com.facebook.react.bridge.NativeModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.uimanager.ReactShadowNode import com.facebook.react.uimanager.ViewManager class LyricUtilPackage : ReactPackage { override fun createViewManagers( reactContext: ReactApplicationContext ): MutableList>> = mutableListOf() override fun createNativeModules( reactContext: ReactApplicationContext ): MutableList = listOf(LyricUtilModule(reactContext)).toMutableList() } ================================================ FILE: android/app/src/main/java/fun/upup/musicfree/lyricUtil/LyricView.kt ================================================ package `fun`.upup.musicfree.lyricUtil import android.app.Activity import android.content.Context import android.graphics.Color import android.graphics.PixelFormat import android.graphics.drawable.ColorDrawable import android.hardware.SensorManager import android.os.Build import android.util.DisplayMetrics import android.util.Log import android.view.Gravity import android.view.MotionEvent import android.view.OrientationEventListener import android.view.View import android.view.WindowManager import android.widget.TextView import com.facebook.react.bridge.ReactContext class LyricView(private val reactContext: ReactContext) : Activity(), View.OnTouchListener { private var windowManager: WindowManager? = null private var orientationEventListener: OrientationEventListener? = null private var layoutParams: WindowManager.LayoutParams? = null private var tv: TextView? = null // 窗口信息 private var windowWidth = 0.0 private var windowHeight = 0.0 private var widthPercent = 0.0 private var leftPercent = 0.0 private var topPercent = 0.0 override fun onTouch(view: View, motionEvent: MotionEvent): Boolean { Log.d("touch", "Desktop Touch") return false } // 展示歌词窗口 fun showLyricWindow(initText: String?, options: Map) { try { if (windowManager == null) { windowManager = reactContext.getSystemService(WINDOW_SERVICE) as WindowManager layoutParams = WindowManager.LayoutParams() val outMetrics = DisplayMetrics() windowManager?.defaultDisplay?.getMetrics(outMetrics) windowWidth = outMetrics.widthPixels.toDouble() windowHeight = outMetrics.heightPixels.toDouble() layoutParams?.type = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) WindowManager.LayoutParams.TYPE_SYSTEM_ALERT else WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY /* * topPercent: number; * leftPercent: number; * align: number; * color: string; * backgroundColor: string; * widthPercent: number; * fontSize: number; */ val topPercent = options["topPercent"] val leftPercent = options["leftPercent"] val align = options["align"] val color = options["color"] val backgroundColor = options["backgroundColor"] val widthPercent = options["widthPercent"] val fontSize = options["fontSize"] this.widthPercent = widthPercent?.toString()?.toDouble() ?: 0.5 layoutParams?.width = (this.widthPercent * windowWidth).toInt() layoutParams?.height = WindowManager.LayoutParams.WRAP_CONTENT layoutParams?.gravity = Gravity.TOP or Gravity.START this.leftPercent = leftPercent?.toString()?.toDouble() ?: 0.5 layoutParams?.x = (this.leftPercent * (windowWidth - layoutParams!!.width)).toInt() layoutParams?.y = 0 layoutParams?.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE layoutParams?.format = PixelFormat.TRANSPARENT tv = TextView(reactContext).apply { text = initText ?: "" textSize = fontSize?.toString()?.toFloat() ?: 14f setBackgroundColor(Color.parseColor(rgba2argb(backgroundColor?.toString() ?: "#84888153"))) setTextColor(Color.parseColor(rgba2argb(color?.toString() ?: "#FFE9D2"))) setPadding(12, 6, 12, 6) gravity = align?.toString()?.toInt() ?: Gravity.CENTER } windowManager?.addView(tv, layoutParams) topPercent?.toString()?.toDouble()?.let { setTopPercent(it) } listenOrientationChange() } } catch (e: Exception) { hideLyricWindow() throw e } } private fun listenOrientationChange() { if (windowManager == null) return if (orientationEventListener == null) { orientationEventListener = object : OrientationEventListener(reactContext, SensorManager.SENSOR_DELAY_NORMAL) { override fun onOrientationChanged(orientation: Int) { if (windowManager != null) { val outMetrics = DisplayMetrics() windowManager?.defaultDisplay?.getMetrics(outMetrics) windowWidth = outMetrics.widthPixels.toDouble() windowHeight = outMetrics.heightPixels.toDouble() layoutParams?.width = (widthPercent * windowWidth).toInt() layoutParams?.x = (leftPercent * (windowWidth - layoutParams!!.width)).toInt() layoutParams?.y = (topPercent * (windowHeight - tv!!.height)).toInt() windowManager?.updateViewLayout(tv, layoutParams) } } } } if (orientationEventListener?.canDetectOrientation() == true) { orientationEventListener?.enable() } } private fun unlistenOrientationChange() { orientationEventListener?.disable() } private fun rgba2argb(color: String): String { return if (color.length == 9) { color[0] + color.substring(7, 9) + color.substring(1, 7) } else { color } } // 隐藏歌词窗口 fun hideLyricWindow() { if (windowManager != null) { tv?.let { try { windowManager?.removeView(it) } catch (e: Exception) { // Handle exception } tv = null } windowManager = null layoutParams = null unlistenOrientationChange() } } // 设置歌词内容 fun setText(text: String) { tv?.text = text } fun setAlign(gravity: Int) { tv?.gravity = gravity } fun setTopPercent(pct: Double) { var percent = pct.coerceIn(0.0, 1.0) tv?.let { layoutParams?.y = (percent * (windowHeight - it.height)).toInt() windowManager?.updateViewLayout(it, layoutParams) } this.topPercent = percent } fun setLeftPercent(pct: Double) { var percent = pct.coerceIn(0.0, 1.0) tv?.let { layoutParams?.x = (percent * (windowWidth - layoutParams!!.width)).toInt() windowManager?.updateViewLayout(it, layoutParams) } this.leftPercent = percent } fun setColors(textColor: String?, backgroundColor: String?) { tv?.let { textColor?.let { color -> it.setTextColor(Color.parseColor(rgba2argb(color))) } backgroundColor?.let { color -> it.background = ColorDrawable(Color.parseColor(rgba2argb(color))) } } } fun setWidth(pct: Double) { var percent = pct.coerceIn(0.3, 1.0) tv?.let { val width = (percent * windowWidth).toInt() val originalWidth = layoutParams?.width ?: 0 layoutParams?.x = if (width <= originalWidth) { layoutParams!!.x + (originalWidth - width) / 2 } else { layoutParams!!.x - (width - originalWidth) / 2 }.coerceAtLeast(0).coerceAtMost((windowWidth - width).toInt()) layoutParams?.width = width windowManager?.updateViewLayout(it, layoutParams) } this.widthPercent = percent } fun setFontSize(fontSize: Float) { tv?.textSize = fontSize } } ================================================ FILE: android/app/src/main/java/fun/upup/musicfree/mp3Util/Mp3UtilModule.kt ================================================ package `fun`.upup.musicfree.mp3Util import android.graphics.Bitmap import android.graphics.BitmapFactory import android.media.MediaMetadataRetriever import android.net.Uri import com.facebook.react.bridge.* import org.jaudiotagger.audio.AudioFileIO import org.jaudiotagger.tag.FieldKey import java.io.File import java.io.FileOutputStream import java.io.IOException class Mp3UtilModule(private val reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) { override fun getName() = "Mp3Util" private fun isContentUri(uri: Uri?): Boolean { return uri?.scheme?.equals("content", ignoreCase = true) == true } @ReactMethod fun getBasicMeta(filePath: String, promise: Promise) { try { val uri = Uri.parse(filePath) val mmr = MediaMetadataRetriever() if (isContentUri(uri)) { mmr.setDataSource(reactApplicationContext, uri) } else { mmr.setDataSource(filePath) } val properties = Arguments.createMap().apply { putString("duration", mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)) putString("bitrate", mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE)) putString("artist", mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST)) putString("author", mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_AUTHOR)) putString("album", mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM)) putString("title", mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE)) putString("date", mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DATE)) putString("year", mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_YEAR)) } promise.resolve(properties) } catch (e: Exception) { promise.reject("Exception", e.message) } } @ReactMethod fun getMediaMeta(filePaths: ReadableArray, promise: Promise) { val metas = Arguments.createArray() val mmr = MediaMetadataRetriever() for (i in 0 until filePaths.size()) { try { val filePath = filePaths.getString(i) val uri = Uri.parse(filePath) if (isContentUri(uri)) { mmr.setDataSource(reactApplicationContext, uri) } else { mmr.setDataSource(filePath) } val properties = Arguments.createMap().apply { putString("duration", mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)) putString("bitrate", mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE)) putString("artist", mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST)) putString("author", mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_AUTHOR)) putString("album", mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM)) putString("title", mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE)) putString("date", mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DATE)) putString("year", mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_YEAR)) } metas.pushMap(properties) } catch (e: Exception) { metas.pushNull() } } try { mmr.release() } catch (ignored: Exception) { } promise.resolve(metas) } @ReactMethod fun getMediaCoverImg(filePath: String, promise: Promise) { try { val file = File(filePath) if (!file.exists()) { promise.reject("File not exist", "File not exist") return } val pathHashCode = file.hashCode() if (pathHashCode == 0) { promise.resolve(null) return } val cacheDir = reactContext.cacheDir val coverFile = File(cacheDir, "image_manager_disk_cache/$pathHashCode.jpg") if (coverFile.exists()) { promise.resolve(coverFile.toURI().toString()) return } val mmr = MediaMetadataRetriever() mmr.setDataSource(filePath) val coverImg = mmr.embeddedPicture if (coverImg != null) { val bitmap = BitmapFactory.decodeByteArray(coverImg, 0, coverImg.size) FileOutputStream(coverFile).use { outputStream -> bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream) outputStream.flush() } promise.resolve(coverFile.toURI().toString()) } else { promise.resolve(null) } mmr.release() } catch (ignored: Exception) { promise.reject("Error", "Got error") } } @ReactMethod fun getLyric(filePath: String, promise: Promise) { try { val file = File(filePath) if (file.exists()) { val audioFile = AudioFileIO.read(file) val tag = audioFile.tag val lrc = tag.getFirst(FieldKey.LYRICS) promise.resolve(lrc) } else { throw IOException("File not found") } } catch (e: Exception) { promise.reject("Error", e.message) } } @ReactMethod fun setMediaTag(filePath: String, meta: ReadableMap, promise: Promise) { try { val file = File(filePath) if (file.exists()) { val audioFile = AudioFileIO.read(file) val tag = audioFile.tag meta.getString("title")?.let { tag.setField(FieldKey.TITLE, it) } meta.getString("artist")?.let { tag.setField(FieldKey.ARTIST, it) } meta.getString("album")?.let { tag.setField(FieldKey.ALBUM, it) } meta.getString("lyric")?.let { tag.setField(FieldKey.LYRICS, it) } meta.getString("comment")?.let { tag.setField(FieldKey.COMMENT, it) } audioFile.commit() promise.resolve(true) } else { promise.reject("Error", "File Not Exist") } } catch (e: Exception) { promise.reject("Error", e.message) } } @ReactMethod fun getMediaTag(filePath: String, promise: Promise) { try { val file = File(filePath) if (file.exists()) { val audioFile = AudioFileIO.read(file) val tag = audioFile.tag val properties = Arguments.createMap().apply { putString("title", tag.getFirst(FieldKey.TITLE)) putString("artist", tag.getFirst(FieldKey.ARTIST)) putString("album", tag.getFirst(FieldKey.ALBUM)) putString("lyric", tag.getFirst(FieldKey.LYRICS)) putString("comment", tag.getFirst(FieldKey.COMMENT)) } promise.resolve(properties) } else { promise.reject("Error", "File Not Found") } } catch (e: Exception) { promise.reject("Error", e.message) } } } ================================================ FILE: android/app/src/main/java/fun/upup/musicfree/mp3Util/Mp3UtilPackage.kt ================================================ package `fun`.upup.musicfree.mp3Util import android.view.View import com.facebook.react.ReactPackage import com.facebook.react.bridge.NativeModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.uimanager.ReactShadowNode import com.facebook.react.uimanager.ViewManager class Mp3UtilPackage : ReactPackage { override fun createViewManagers( reactContext: ReactApplicationContext ): MutableList>> = mutableListOf() override fun createNativeModules( reactContext: ReactApplicationContext ): MutableList = listOf(Mp3UtilModule(reactContext)).toMutableList() } ================================================ FILE: android/app/src/main/java/fun/upup/musicfree/utils/UtilsModule.kt ================================================ package `fun`.upup.musicfree.utils; // replace your-apps-package-name with your app’s package name import android.Manifest import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Environment import android.provider.Settings import android.util.DisplayMetrics import android.view.WindowInsets import android.view.WindowManager import androidx.core.content.ContextCompat import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.Promise import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactContextBaseJavaModule import com.facebook.react.bridge.ReactMethod import com.facebook.react.bridge.WritableMap import kotlin.system.exitProcess class UtilsModule(context: ReactApplicationContext) : ReactContextBaseJavaModule(context) { private val reactContext: ReactApplicationContext = context; override fun getName() = "NativeUtils" @ReactMethod fun exitApp() { val activity = reactContext.currentActivity activity?.finishAndRemoveTask() android.os.Process.killProcess(android.os.Process.myPid()) exitProcess(0) } @ReactMethod fun checkStoragePermission(promise: Promise) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { promise.resolve(Environment.isExternalStorageManager()) } else { val readPermission = ContextCompat.checkSelfPermission(reactContext, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED val writePermission = ContextCompat.checkSelfPermission(reactContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED promise.resolve(readPermission && writePermission) } } @ReactMethod fun requestStoragePermission() { val intent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION).apply { data = Uri.parse("package:${reactContext.packageName}") } } else { Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply { data = Uri.parse("package:${reactContext.packageName}") } } reactContext.currentActivity?.startActivity(intent) } @ReactMethod(isBlockingSynchronousMethod = true) fun getWindowDimensions(): WritableMap { val windowManager = reactApplicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager val displayMetrics: DisplayMetrics = reactApplicationContext.resources.displayMetrics val density = displayMetrics.density return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { // Android 11 (API 30) 及以上使用新 API val windowMetrics = windowManager.currentWindowMetrics val insets = windowMetrics.windowInsets.getInsetsIgnoringVisibility(WindowInsets.Type.systemBars()) val bounds = windowMetrics.bounds val totalWidthPx = bounds.width() val totalHeightPx = bounds.height() val leftInsetPx = insets.left val rightInsetPx = insets.right val topInsetPx = insets.top val bottomInsetPx = insets.bottom val usableWidthPx = totalWidthPx - leftInsetPx - rightInsetPx val usableHeightPx = totalHeightPx - topInsetPx - bottomInsetPx val usableWidthDp = usableWidthPx / density val usableHeightDp = usableHeightPx / density Arguments.createMap().apply { putDouble("width", usableWidthDp.toDouble()) putDouble("height", usableHeightDp.toDouble()) } } else { // Android 10 及以下使用旧 API val display = windowManager.defaultDisplay val realSize = android.graphics.Point() display.getRealSize(realSize) // 获取状态栏和导航栏高度 val resources = reactApplicationContext.resources var statusBarHeight = 0 var navigationBarHeight = 0 // 状态栏高度 val statusBarResourceId = resources.getIdentifier("status_bar_height", "dimen", "android") if (statusBarResourceId > 0) { statusBarHeight = resources.getDimensionPixelSize(statusBarResourceId) } // 导航栏高度 val navigationBarResourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android") if (navigationBarResourceId > 0) { navigationBarHeight = resources.getDimensionPixelSize(navigationBarResourceId) } val usableWidthPx = realSize.x val usableHeightPx = realSize.y - statusBarHeight - navigationBarHeight val usableWidthDp = usableWidthPx / density val usableHeightDp = usableHeightPx / density Arguments.createMap().apply { putDouble("width", usableWidthDp.toDouble()) putDouble("height", usableHeightDp.toDouble()) } } } } ================================================ FILE: android/app/src/main/java/fun/upup/musicfree/utils/UtilsPackage.kt ================================================ package `fun`.upup.musicfree.utils import android.view.View import com.facebook.react.ReactPackage import com.facebook.react.bridge.NativeModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.uimanager.ReactShadowNode import com.facebook.react.uimanager.ViewManager class UtilsPackage : ReactPackage { override fun createViewManagers( reactContext: ReactApplicationContext ): MutableList>> = mutableListOf() override fun createNativeModules( reactContext: ReactApplicationContext ): MutableList = listOf(UtilsModule(reactContext)).toMutableList() } ================================================ FILE: android/app/src/main/res/drawable/rn_edit_text_material.xml ================================================ ================================================ FILE: android/app/src/main/res/drawable/splashscreen.xml ================================================ ================================================ FILE: android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml ================================================ ================================================ FILE: android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml ================================================ ================================================ FILE: android/app/src/main/res/values/colors.xml ================================================ #27282C ================================================ FILE: android/app/src/main/res/values/ic_launcher_background.xml ================================================ #27282C ================================================ FILE: android/app/src/main/res/values/strings.xml ================================================ MusicFree true musicfree_temporary_channel musicfree_temporary_channel MusicFree ================================================ FILE: android/app/src/main/res/values/styles.xml ================================================ ================================================ FILE: android/build.gradle ================================================ buildscript { ext { buildToolsVersion = "35.0.0" minSdkVersion = 24 compileSdkVersion = 35 targetSdkVersion = 30 ndkVersion = "26.1.10909125" kotlinVersion = "1.9.24" } repositories { maven { url 'https://maven.aliyun.com/repository/central'} maven { url 'https://maven.aliyun.com/repository/public' } maven { url 'https://maven.aliyun.com/repository/gradle-plugin' } google() mavenCentral() maven { url 'https://jitpack.io' } } dependencies { classpath("com.android.tools.build:gradle") classpath("com.facebook.react:react-native-gradle-plugin") classpath("org.jetbrains.kotlin:kotlin-gradle-plugin") } } apply plugin: "com.facebook.react.rootproject" ================================================ FILE: android/gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists # distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip distributionUrl=https\://mirrors.cloud.tencent.com/gradle/gradle-8.10.2-all.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists ================================================ FILE: android/gradle.properties ================================================ # Project-wide Gradle settings. # IDE (e.g. Android Studio) users: # Gradle settings configured through the IDE *will override* # any settings specified in this file. # For more details on how to configure your build environment visit # http://www.gradle.org/docs/current/userguide/build_environment.html # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. # Default value: -Xmx512m -XX:MaxMetaspaceSize=256m org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # org.gradle.parallel=true # AndroidX package structure to make it clearer which packages are bundled with the # Android operating system, and which are packaged with your app's APK # https://developer.android.com/topic/libraries/support-library/androidx-rn android.useAndroidX=true # Use this property to specify which architecture you want to build. # You can also override it from the CLI using # ./gradlew -PreactNativeArchitectures=x86_64 reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64 # Use this property to enable support to the new architecture. # This will allow you to use TurboModules and the Fabric render in # your application. You should enable this flag either if you want # to write custom TurboModules/Fabric components OR use libraries that # are providing them. newArchEnabled=false # Use this property to enable or disable the Hermes JS engine. # If set to false, you will be using JSC instead. hermesEnabled=true ================================================ FILE: android/gradlew ================================================ #!/bin/sh # # Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # SPDX-License-Identifier: Apache-2.0 # ############################################################################## # # Gradle start up script for POSIX generated by Gradle. # # Important for running: # # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is # noncompliant, but you have some other compliant shell such as ksh or # bash, then to run this script, type that shell name before the whole # command line, like: # # ksh Gradle # # Busybox and similar reduced shells will NOT work, because this script # requires all of these POSIX shell features: # * functions; # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», # «${var#prefix}», «${var%suffix}», and «$( cmd )»; # * compound commands having a testable exit status, especially «case»; # * various built-in commands including «command», «set», and «ulimit». # # Important for patching: # # (2) This script targets any POSIX shell, so it avoids extensions provided # by Bash, Ksh, etc; in particular arrays are avoided. # # The "traditional" practice of packing multiple parameters into a # space-separated string is a well documented source of bugs and security # problems, so this is (mostly) avoided, by progressively accumulating # options in "$@", and eventually passing that to Java. # # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; # see the in-line comments for details. # # There are tweaks for specific operating systems such as AIX, CygWin, # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. # ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link app_path=$0 # Need this for daisy-chained symlinks. while APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path [ -h "$app_path" ] do ls=$( ls -ld "$app_path" ) link=${ls#*' -> '} case $link in #( /*) app_path=$link ;; #( *) app_path=$APP_HOME$link ;; esac done # This is normally unused # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s ' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum warn () { echo "$*" } >&2 die () { echo echo "$*" echo exit 1 } >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "$( uname )" in #( CYGWIN* ) cygwin=true ;; #( Darwin* ) darwin=true ;; #( MSYS* | MINGW* ) msys=true ;; #( NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD=$JAVA_HOME/jre/sh/java else JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD=java if ! command -v java >/dev/null 2>&1 then die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi fi # Increase the maximum file descriptors if we can. if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac fi # Collect all arguments for the java command, stacking in reverse order: # * args from the command line # * the main class name # * -classpath # * -D...appname settings # * --module-path (only if needed) # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java if "$cygwin" || "$msys" ; then APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) JAVACMD=$( cygpath --unix "$JAVACMD" ) # Now convert the arguments - kludge to limit ourselves to /bin/sh for arg do if case $arg in #( -*) false ;; # don't mess with options #( /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath [ -e "$t" ] ;; #( *) false ;; esac then arg=$( cygpath --path --ignore --mixed "$arg" ) fi # Roll the args list around exactly as many times as the number of # args, so each arg winds up back in the position where it started, but # possibly modified. # # NB: a `for` loop captures its iteration list before it begins, so # changing the positional parameters here affects neither the number of # iterations, nor the values presented in `arg`. shift # remove old arg set -- "$@" "$arg" # push replacement arg done fi # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Collect all arguments for the java command: # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, # and any embedded shellness will be escaped. # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be # treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ -classpath "$CLASSPATH" \ org.gradle.wrapper.GradleWrapperMain \ "$@" # Stop when "xargs" is not available. if ! command -v xargs >/dev/null 2>&1 then die "xargs is not available" fi # Use "xargs" to parse quoted args. # # With -n1 it outputs one arg per line, with the quotes and backslashes removed. # # In Bash we could simply go: # # readarray ARGS < <( xargs -n1 <<<"$var" ) && # set -- "${ARGS[@]}" "$@" # # but POSIX shell has neither arrays nor command substitution, so instead we # post-process each arg (as a line of input to sed) to backslash-escape any # character that might be a shell metacharacter, then use eval to reverse # that process (while maintaining the separation between arguments), and wrap # the whole thing up as a single "set" statement. # # This will of course break if any of these variables contains a newline or # an unmatched quote. # eval "set -- $( printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | xargs -n1 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | tr '\n' ' ' )" '"$@"' exec "$JAVACMD" "$@" ================================================ FILE: android/gradlew.bat ================================================ @rem @rem Copyright 2015 the original author or authors. @rem @rem Licensed under the Apache License, Version 2.0 (the "License"); @rem you may not use this file except in compliance with the License. @rem You may obtain a copy of the License at @rem @rem https://www.apache.org/licenses/LICENSE-2.0 @rem @rem Unless required by applicable law or agreed to in writing, software @rem distributed under the License is distributed on an "AS IS" BASIS, @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem @rem SPDX-License-Identifier: Apache-2.0 @rem @if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%"=="" set DIRNAME=. @rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Resolve any "." and ".." in APP_HOME to make it shorter. for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute echo. 1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 echo. 1>&2 echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo location of your Java installation. 1>&2 goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute echo. 1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 echo. 1>&2 echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo location of your Java installation. 1>&2 goto fail :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! set EXIT_CODE=%ERRORLEVEL% if %EXIT_CODE% equ 0 set EXIT_CODE=1 if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: android/settings.gradle ================================================ pluginManagement { includeBuild("../node_modules/@react-native/gradle-plugin") } plugins { id("com.facebook.react.settings") } extensions.configure(com.facebook.react.ReactSettingsExtension){ ex -> def command = [ 'node', '--no-warnings', '--eval', 'require(require.resolve(\'expo-modules-autolinking\', { paths: [require.resolve(\'expo/package.json\')] }))(process.argv.slice(1))', 'react-native-config', '--json', '--platform', 'android' ].toList() ex.autolinkLibrariesFromCommand(command) } rootProject.name = 'MusicFree' include ':app' includeBuild('../node_modules/@react-native/gradle-plugin') apply from: new File(["node", "--print", "require.resolve('expo/package.json')"].execute(null, rootDir).text.trim(), "../scripts/autolinking.gradle") useExpoModules() ================================================ FILE: app.json ================================================ { "name": "MusicFree", "displayName": "MusicFree" } ================================================ FILE: babel.config.js ================================================ module.exports = { presets: ['babel-preset-expo'], plugins: [ [ 'module-resolver', { root: ['./'], alias: { '^@/(.+)': './src/\\1', 'webdav': "webdav/dist/react-native" }, }, ], 'react-native-reanimated/plugin', ], env: { production: { plugins: ['transform-remove-console'], }, }, }; ================================================ FILE: changelog.md ================================================ `2025.10.9 v0.6.2` 1. 【优化】优化了软件启动速度 `2025.8.3 v0.6.1` 1. 修复进入软件时播放进度丢失的问题 2. 修复某些情况下无法添加到歌单的问题 `2025.7.24 v0.6.0` 一大波优化和问题修复~ 1. 【功能】优化了倒计时功能,支持倒计时结束后,歌曲播放完成后再退出应用 2. 【功能】支持多语言 3. 【功能】新增音源重定向功能 4. 【功能】自定义主题中,选择颜色弹窗支持直接输入颜色代码 5. 【功能】新增配置,音频被暂时打断时可调节降低音量的幅度(感谢@eastcukt) 6. 【功能】本地歌单中,高亮正在播放的歌曲 7. 【功能】本地歌单中,新增定位按钮,点击定位按钮可跳转到正在播放的音乐 8. 【优化】略微调大了歌词页的播放按钮 9. 【优化】首页-推荐歌单支持左右滑动 10. 【优化】优化播放器的稳定性,减少出现闪退/播放自动暂停的情况 11. 【修复】修复了一批样式bug 12. 【修复】修复了点击更新订阅插件后,插件页始终展示加载中的问题 13. 【修复】修复部分情况下歌词页高亮混乱的问题 14. 【插件】插件获取评论支持分页(需要插件配合) 15. 【插件】修复移动端axios库中读取的cookie和桌面版不一致的问题 16. 【插件】插件新增description字段,可嵌入markdown格式的插件说明 17. 【其他】重构了核心部分代码逻辑,后续维护起来成本会小一些 `2025.4.4 v0.5.1` 1. 【修复】修复插件开关点击无效的问题 2. 【修复】修复开屏图片消失的问题 3. 【优化】增加新建歌单名称的长度限制 4. 【优化】优化插件安装失败的提示样式 `2025.2.9 v0.5.0` 1. 【升级】升级ReactNative到0.76.5(注意:升级后只支持安卓7.0及以上设备,低于此版本的设备请不要升级) 2. 【修复】修复了运行应用一段时间后容易闪退的问题 3. 【修复】修复了插件网络请求无法传递cookie的问题 4. 【修复】新增了设置本地歌单封面的功能(在0.4版本暂时下线了) 5. 【修复】修复了部分情况下,播放本地音乐提示 “当前非Wifi环境” 的问题 6. 【优化】优化了一些代码逻辑 `2024.11.10 v0.4.4` 【修复】修复了部分系统上弹窗、浮层等无法出现,或动画表现异常的问题 `2024.10.27 v0.4.3` 【修复】修复了部分系统上文字显示不全的问题 `2024.9.18 v0.4.2` 1. 【修复】修复本地音乐无法播放的问题 `2024.9.8 v0.4.1` 安装包上传到了飞书云文档,浏览器打开链接后有个下载说明,可以根据这个指引安装apk 1. 【修复】修复桌面歌词无法开启的问题 2. 【修复】修复了修改桌面歌词颜色会导致闪退的问题 3. 【修复】回滚了本地音乐部分读取文件的逻辑 4. 【修复】修复了点击【编辑歌单信息】按钮无效的问题 `2024.9.1 v0.4.0` 本次更新修改了歌单的存储机制,建议谨慎更新 安装包上传到了飞书云文档,浏览器打开链接后有个下载说明,可以根据这个指引安装apk 1. 【升级】ReactNative升级到0.74.4 2. 【功能】换了个logo和开屏页 3. 【功能】播放列表的歌曲限制从1500首调整到10000首 4. 【功能】重写了歌曲排序机制 5. 【功能】插件新增评论区功能(需要插件实现getMusicComments方法) 6. 【优化】调整部分样式,优化删除歌曲时的性能 7. 【修复】修复歌词翻译错位的问题 8. 【修复】修复部分情况下无法复制作者/专辑的问题 9. 【修复】修复在歌单详情页删除歌单会导致白屏的问题 10. 【修复】修复搜索框在部分情况下自动触发搜索的问题 11. 【修复】修复右上角菜单位置跳变的问题 12. 【修复】修复在预览专辑封面时触发返回不会关闭预览弹窗的问题 13. 【修复】下载文件时转移文件中的保留字符(感谢@GuGuMur) 14. 【其他】分架构打包,更新开源协议为 AGPL 3.0 `2024.3.31 v0.3.0` 本次更新优化了存储方式,更新到此版本后,歌单会自动转化为新的存储方式;安装新版本后再回退到老版本会导致歌单清空,虽然测试下来没啥问题,但是请谨慎升级Orz 备用链接:https://pan.baidu.com/s/1HmbHlh3vTcSyVXcOs-7kTA?pwd=saku 提取码: saku 1. 【功能】历史播放记录支持批量编辑 2. 【功能】歌单内支持按照加入时间排序 3. 【功能】新增设置“本地歌单添加歌曲顺序”,在歌单内添加歌曲时可以加到歌单开头 4. 【功能】首页新建歌单旁边新增“导入歌单”按钮,点击时会自动寻找具有导入歌单功能的插件,并拉起导入浮层 5. 【功能】设置项中新增“自动换源”功能,当插件失效/无法获取播放链接时,会自动尝试更换其他源的同名歌曲 6. 【优化】尝试优化了软件启动时间,应该有点作用 7. 【优化】更新了存储方式,现在单个歌单可以存储大于10000首歌曲; 8. 【优化】调整未开启“允许使用移动网络播放”开关时的样式表现 9. 【优化】优化了设置页的样式 10. 【优化】微调歌词详情页的布局 11. 【修复】修复打开弹窗时,点击返回按钮不关闭弹窗的问题 12. 【修复】修复启动软件时播放模式错误的问题 13. 【修复】修复搜索结果页特定情况下白屏的问题 `2024.1.21 v0.2.0` 1. 【功能】支持 Webdav 备份 & 播放 2. 【功能】插件支持显示作者 3. 【功能】插件榜单详情支持分页 4. 【功能】首页&歌词页样式改版:新增歌词进度调整、歌词大小调整、歌词翻译、自动搜索歌词 5. 【功能】新增收藏歌单功能 6. 【功能】侧边栏新增“权限管理”设置 7. 【功能】音乐播放栏支持左右滑动切歌(可能会闪一下,后续修掉) 8. 【功能】新增 “通知栏显示关闭按钮” 设置 9. 【优化】重构播放、数据存储逻辑 10. 【优化】统一浮层、toast样式 11. 【优化】去除插件URL必须以.js结尾的限制 12. 【修复】修改无限列表到底不触发onEndReached的问题 (感谢 @282931) 13. 【修复】修复标题栏背景色透明度不生效的问题 14. 【修复】修复播放记录退出后被清空的问题 15. 【修复】修复部分情况下深色模式异常的问题 16. 【其他】这次安装包备用链接发到百度网盘了:https://pan.baidu.com/s/1H360C0MqejKXS67XwMqgPw?pwd=6666 提取码6666 `2023.11.24 v0.1.2-alpha.0` 1. 【功能】新增桌面歌词功能,可在设置页开启(开启之前需要去手机设置授予悬浮窗权限) 2. 【功能】可以使用 MusicFree 打开本地 .js 或 .mp3 文件;其中 .js 文件会被当作插件安装; .mp3 文件会直接播放 3. 【功能】新增插件设置:打开软件时自动更新插件、安装插件时不校验版本 4. 【功能】新增播放设置:打开软件时自动播放歌曲 5. 【功能】插件页新增开关,可以控制是否在榜单、热门歌单、搜索结果中展示对应插件的结果 6. 【功能】插件协议新增 “用户变量” ,可以在插件中获取 APP 输入的配置(可以由此实现自建音乐源的插件/webdav源插件,但是还没写) 7. 【优化】下载单曲支持选择音质 8. 【优化】新增“关联歌词方式”设置,如果设置为“输入歌曲ID”,则会恢复老版本关联歌词,即输入ID关联歌词 9. 【优化】侧边栏新增“返回桌面”按钮 10. 【修复】修复榜单、推荐歌单、搜索歌词页白屏闪退的问题 (感谢 @282931) 11. 【修复】修复自定义背景模糊度和透明度无法设置为 0 的问题 (感谢 @282931) 12. 【修复】修复浅色主题状态栏表现错误的问题 13. 【修复】修复歌单批量编辑无法删除的问题 14. 【修复】修复无法恢复桌面版导出的歌单的问题 `2023.10.15 v0.1.1-alpha.0` 1. 【功能】音源支持m3u8 (桌面版下个版本支持m3u8) 2. 【功能】增加歌曲详情页屏幕常亮的设置 3. 【功能】重构主题相关功能,增加「跟随系统深色设置」选项;调整大部分样式,移除第三方UI库 4. 【功能】插件页增加「插件批量更新」的功能 5. 【功能】取消原「歌词关联」的逻辑,修改为拉起「歌词搜索」浮层 6. 【优化】增加了一些无障碍属性 7. 【修复】修复部分场景下无法保存歌单的问题 8. 【修复】修复部分场景下重启之后无法播放歌曲的问题 9. 【插件】部分插件更新,侧边栏更新插件即可 `2023.8.13 v0.1.0-alpha.10` 1. 【功能】当前音乐无歌词时可以在歌词页搜索歌词 2. 【优化】调整右上角弹出气泡的位置 3. 【优化】增加打开歌曲详情页时的默认表现设置 4. 【优化】修复进入歌词页时候显示跳变的问题 5. 【插件】插件协议更新,更新后可以配置某插件不出现在特定的搜索结果页下 6. 【插件】部分插件更新,侧边栏更新插件即可 `2023.6.26 v0.1.0-alpha.9` 1. 【功能】新增搜索歌单功能 2. 【功能】新增播放记录功能 3. 【优化】加了一些无障碍适配 4. 【插件】部分插件更新,侧边栏更新插件即可 `2023.6.4 v0.1.0-alpha.8` 1. 【功能】新增“推荐歌单”功能,需要配合支持该功能的插件使用 2. 【功能】导入本地文件时增加“全选”按钮 3. 【优化】修改“保存专辑封面”时的提示文案 4. 【修复】修复当目标歌曲在播放列表内时,添加到下一首播放无效的问题 5. 【插件】部分插件更新,侧边栏更新插件即可 `2023.5.21 v0.1.0-alpha.7` 1. 【功能】歌单页新增“播放全部”按钮 2. 【功能】歌曲播放页中,长按专辑封面可保存到本地 3. 【功能】歌单页新增“歌单排序”功能 4. 【插件】b站插件作者页API变动,侧边栏更新插件即可 `2023.5.3 v0.1.0-alpha.6` 小小拖更一下~ 1. 【功能】歌单内搜索时支持英文大小写模糊搜索 2. 【修复】修复首次进入时歌曲可能无法正常播放的问题 `2023.3.26 v0.1.0-alpha.5` 1. 【功能】更新弹窗新增“跳过此版本”的复选框 2. 【功能】侧边栏-基本设置-开发选项中新增“查看错误日志”的选项,点击会弹出错误日志的弹窗 3. 【修复】修复输入框被软键盘遮挡的问题 4. 【优化】优化了定时关闭的样式 5. 【文档】文档中更新了插件的制作教程。文档地址:http://musicfree.upup.fun `2023.3.19 v0.1.0-alpha.4` 1. 【功能】适配横屏设备 2. 【功能】新建歌单时添加默认歌单名;从专辑/榜单批量添加到新歌单时,默认以专辑名/榜单名为新歌单名 3. 【修复】修复设备有虚拟按键时,浮层会被遮挡的问题 4. 【修复】修复拖拽歌词时部分情况下时间异常的问题 5. 【修复】调整下载失败时的提示文案 6. 【插件】部分插件有更新,可以从侧边栏更新 `2023.2.26 v0.1.0-alpha.3` 1. 【功能】专辑列表支持分页,需要配合插件更新; 2. 【优化】去掉了全面屏手机界面下方的小白条; 3. 【优化】调整拖拽歌词时标识线的对齐范围;调整歌词拖到最底端时的逻辑; 4. 【优化】调整下载歌曲时的文件名; 5. 【优化】导入歌曲时的提示文案增加滚动; 6. 【修复】修复特殊情况下歌曲中断后可能恢复到错误状态的问题(未验证); 7. 【插件】个别插件有更新,可以去侧边栏更新订阅。 `2023.2.13 v0.1.0-alpha.2` 1. 【功能】备份&恢复:可以把本地的歌单和插件备份到一个json文件中,也可以从本地文件或网络上恢复插件和歌单。 2. 【修复】修复部分情况下后台播放切换歌曲时暂停的问题 3. 【修复】修复部分场景无法下载的问题 4. 【修复】修复部分场景无法删除本地文件的问题 5. 【优化】简单优化了下歌单列表 6. 【调试】调试面板现在可以打印出插件中的console语句 `2023.1.27 v0.1.0-alpha.1` 1. !!!【功能】插件更新,升级到新版本之后原有插件完全不兼容;更新后卸载原有插件,然后更新订阅即可(具体看公众号示例) 2. 【功能】新增功能“倍速播放” 3. 【功能】重写了插件订阅的逻辑,现在应该会更合理一点点 4. 【功能】删除本地文件之前增加二次确认提醒 5. 【功能】增加了一些无关紧要的分享 6. 【样式】换了个logo,丑的更直白一些 7. 【样式】调整了一些样式(如播放页的模糊和透明度、歌词样式等) 8. 【样式】专辑描述文字默认6行,点击可以展开或折叠 9. 【修复】修复部分情况下无法下载的问题 10. 【插件】大量插件有更新,更新到此版本后更新订阅即可 `2023.1.8 v0.0.1-alpha.13` 1. 【功能】主页入口增加“榜单” 2. 【功能】歌单页新增“编辑歌单信息”,可以修改歌单名称和歌单封面 3. 【修复】修复了一个会导致播放音乐时拖拽排序卡顿的问题,做了一些其他优化 4. 【插件】部分插件有更新,可以在侧边栏更新 `2022.12.25 v0.0.1-alpha.12` 1. 【功能】增加“单击搜索结果中单曲tab”时的行为配置 2. 【功能】增加调试配置及调试面板,可用于查看插件的错误信息 3. 【修复】修复部分情况下本地音乐中断时无法继续播放的问题 4. 【修复】尝试修复扫描本地音乐,音乐文件太多时可能卡死的问题 `2022.12.11 v0.0.1-alpha.11` 1. 【功能】完善音质功能 2. 【功能】更新下载功能,支持根据音质下载文件;修复一些小问题 3. 【功能】新增播放时被打断的设置,可设置为暂停或者暂时降低音量 4. 【优化】调整侧边栏样式,侧边栏新增“定时关闭”功能 5. 【优化】本地音乐读取歌词时,会自动读取同目录下的同名lrc文件作为歌词 6. 【修复】修复安装插件时误弹安装失败提示的问题 7. 【修复】修复部分情况下本地文件删除失败的问题 8. 【修复】修复本地音乐在通知栏不显示音乐标题的问题 9. 【插件】示例插件仓库中migu有更新(支持音质),需要可自行更新 `2022.12.4 v0.0.1-alpha.10` 1. 【功能】支持自定义下载路径 2. 【功能】支持插件排序(也就是搜索结果的排序) 3. 【功能】增加音质相关的配置 4. 【优化】弹窗、浮层的性能优化,页面嵌套较深时卡顿的情况应该会好一点 5. 【优化】拖拽排序,比上个版本手感应该会好一点 6. 【修复】修复在歌词页清空播放列表时白屏的问题 `2022.11.20 v0.0.1-alpha.9` 1. 【功能】本地音乐读取内嵌歌词 2. 【功能】批量编辑页新增了凑合能用的拖拽排序 3. 【功能】歌曲详情浮层新增凑合能用的定时关闭 4. 【功能】添加到歌单时可以新建歌单 5. 【功能】本地音乐扫描支持外置sd卡;支持导入aac格式 6. 【优化】优化播放列表浮层拉起时的锚定 7. 【修复】修复更新弹窗无法滚动的问题 8. 【修复】修复安卓12状态栏概率不沉浸的问题 9. 【修复】修复安卓12、13播一首就停的问题 10. 【插件】示例插件有更新,可以删掉原有插件重新导入 `2022.11.13 v0.0.1-alpha.8` 1. 【功能】侧边栏插件设置新增“订阅插件”功能,订阅之后直接点击“更新插件”即可更新,不需要清空重装了 2. 【功能】本地音乐读取内置封面 3. 【功能】本地音乐歌单支持批量删除(不删除源文件) 4. 【优化】重写导入本地音乐的逻辑,支持多选文件夹;修复部分机型重启应用时本地音乐消失的问题(可能需要删除后重新导入);支持导入flac,wav,wav,m4a,ogg等格式 5. 【优化】重写播放列表浮层,拉起时会锚定到当前正在播放的歌曲 6. 【优化】调整部分逻辑,可能会减少音频卡顿时卡死的情况 7. 【修复】修复歌曲详情页进度条不连续的问题 8. 【修复】修复某些情况下无法关联歌词的问题 9. 【修复】修复正在播放的歌曲无歌词时,进入歌词页白屏的问题 10. 【插件】示例插件有更新,可以删掉原有插件重新导入 `2022.10.30 v0.0.1-alpha.7` 1. 新增功能:历史记录一键清空 2. 新增功能:歌手页、本地歌单页支持批量编辑 3. 修复移动网络下无法播放本地音乐的问题 4. 样式优化&修复:toast提示显示异常、侧边栏样式优化、歌单内序号显示不全、【关于】页无法滑动 5. 之前使用的拖拽排序组件在列表较大时有很严重的性能问题,会导致卡顿甚至白屏,因此批量编辑页暂时去掉了拖拽排序,后续会重新加上 `2022.10.22 v0.0.1-alpha.6` 1. 重要!! v0.0.1-alpha.5以前的版本无法通过app正常更新,请在gitee/github发布页下载最新版本(v0.0.1-alpha.6),或QQ群自取; 2. 导入本地音乐时,如果未识别本地音乐文件,则会使用文件名作为音乐名; 3. 自建歌单、专辑详情页增加批量选择功能,可点击右上角查看(歌曲较多时可能有点卡,后续优化);使用方式:选中歌曲可进行下一首播放/加入歌单/下载/删除,长按拖动进行排序;删除/排序后点击保存按钮方可生效 4. 调整歌单内歌曲编号字体大小; `2022.10.16 v0.0.1-alpha.5` 1. 新增功能:导入本地音乐文件 2. 从网络源安装的插件可在插件页直接更新 3. 调整下载逻辑 `2022.10.06 v0.0.1-alpha.4` 1. 修复专辑详情页没有loading的问题 2. 为插件新增Cookie管理器 3. 优化播放页的显示 4. 新增一键卸载全部插件的功能 `2022.10.04 v0.0.1-alpha.3` 1. 修复设置页无法滚动的问题 2. 修复播放结束时可能暂停的问题 `2022.10.03 v0.0.1-alpha.2` 1. 插件协议更新,需要重新安装插件 2. 支持批量导入插件 3. 新增清空播放列表功能 4. 优化搜索结果面板和播放专辑逻辑 `2022.10.02` 测试版本出现啦!撒花 ================================================ FILE: generator/generate-assets.mjs ================================================ import fs from 'fs/promises'; import path from 'path'; import * as url from "node:url"; function toCamelCase(str) { // 将下划线和中划线统一替换为空格 let camelCaseStr = str.replace(/[-_]/g, ' '); // 将每个单词的首字母大写,其余字母小写 camelCaseStr = camelCaseStr.split(' ').map(word => { return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); }).join(''); return camelCaseStr; } // 读取所有的icon const basePath = path.resolve(url.fileURLToPath(import.meta.url), '../../src/assets/icons') // 读取所有的svg const icons = await fs.readdir(basePath) const assets = icons.map(it => ({ componentName: toCamelCase(it.slice(0, -path.extname(it).length)) + "Icon", filePath: `@/assets/icons/${it}`, name: it.slice(0, -path.extname(it).length) })) let scriptTemplate = `// This file is generated by generate-assets.mjs. DO NOT MODIFY. import {SvgProps} from 'react-native-svg'; ${assets.map(asset => `import ${asset.componentName} from '${asset.filePath}';`).join('\n')} export type IIconName = ${assets.map(asset => `'${asset.name}'`).join(' | ')}; interface IProps extends SvgProps { /** 图标名称 */ name: IIconName; /** 图标大小 */ size?: number; } const iconMap = { ${assets.map(asset => ` '${asset.name}': ${asset.componentName}`).join(',\n')} } as const; export default function Icon(props: IProps) { const {name, size} = props; const newProps = { ...props, width: props.width ?? size, height: props.width ?? size } as SvgProps; const Component = iconMap[name]; return ; } ` const targetPath = path.resolve(url.fileURLToPath(import.meta.url), '../../src/components/base/icon.tsx'); await fs.writeFile(targetPath, scriptTemplate, 'utf8'); console.log(`Generate Succeed. ${assets.length} assets.`) ================================================ FILE: index.js ================================================ /** * @format */ import {AppRegistry} from 'react-native'; import {name as appName} from './app.json'; import TrackPlayer from 'react-native-track-player'; import Pages from '@/entry'; AppRegistry.registerComponent(appName, () => Pages); TrackPlayer.registerPlaybackService(() => require('./src/service/index')); ================================================ FILE: ios/.xcode.env ================================================ # This `.xcode.env` file is versioned and is used to source the environment # used when running script phases inside Xcode. # To customize your local environment, you can create an `.xcode.env.local` # file that is not versioned. # NODE_BINARY variable contains the PATH to the node executable. # # Customize the NODE_BINARY variable here. # For example, to use nvm with brew, add the following line # . "$(brew --prefix nvm)/nvm.sh" --no-use export NODE_BINARY=$(command -v node) ================================================ FILE: ios/MusicFree/AppDelegate.h ================================================ #import #import #import @interface AppDelegate : EXAppDelegateWrapper @end ================================================ FILE: ios/MusicFree/AppDelegate.mm ================================================ #import "AppDelegate.h" #import @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.moduleName = @"MusicFree"; // You can add your custom initial props in the dictionary below. // They will be passed down to the ViewController used by React Native. self.initialProps = @{}; return [super application:application didFinishLaunchingWithOptions:launchOptions]; } - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge { return [self bundleURL]; } - (NSURL *)bundleURL { #if DEBUG return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@".expo/.virtual-metro-entry"]; #else return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; #endif } @end ================================================ FILE: ios/MusicFree/Images.xcassets/AppIcon.appiconset/Contents.json ================================================ { "images" : [ { "idiom" : "iphone", "scale" : "2x", "size" : "20x20" }, { "idiom" : "iphone", "scale" : "3x", "size" : "20x20" }, { "idiom" : "iphone", "scale" : "2x", "size" : "29x29" }, { "idiom" : "iphone", "scale" : "3x", "size" : "29x29" }, { "idiom" : "iphone", "scale" : "2x", "size" : "40x40" }, { "idiom" : "iphone", "scale" : "3x", "size" : "40x40" }, { "idiom" : "iphone", "scale" : "2x", "size" : "60x60" }, { "idiom" : "iphone", "scale" : "3x", "size" : "60x60" }, { "idiom" : "ios-marketing", "scale" : "1x", "size" : "1024x1024" } ], "info" : { "author" : "xcode", "version" : 1 } } ================================================ FILE: ios/MusicFree/Images.xcassets/Contents.json ================================================ { "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: ios/MusicFree/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleDisplayName MusicFree CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType APPL CFBundleShortVersionString $(MARKETING_VERSION) CFBundleSignature ???? CFBundleVersion $(CURRENT_PROJECT_VERSION) LSRequiresIPhoneOS NSAppTransportSecurity NSAllowsArbitraryLoads NSAllowsLocalNetworking NSLocationWhenInUseUsageDescription UILaunchStoryboardName LaunchScreen UIRequiredDeviceCapabilities arm64 UISupportedInterfaceOrientations UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIViewControllerBasedStatusBarAppearance ================================================ FILE: ios/MusicFree/LaunchScreen.storyboard ================================================ ================================================ FILE: ios/MusicFree/PrivacyInfo.xcprivacy ================================================ NSPrivacyAccessedAPITypes NSPrivacyAccessedAPIType NSPrivacyAccessedAPICategoryFileTimestamp NSPrivacyAccessedAPITypeReasons C617.1 NSPrivacyAccessedAPIType NSPrivacyAccessedAPICategoryUserDefaults NSPrivacyAccessedAPITypeReasons CA92.1 NSPrivacyAccessedAPIType NSPrivacyAccessedAPICategorySystemBootTime NSPrivacyAccessedAPITypeReasons 35F9.1 NSPrivacyCollectedDataTypes NSPrivacyTracking ================================================ FILE: ios/MusicFree/main.m ================================================ #import #import "AppDelegate.h" int main(int argc, char *argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } } ================================================ FILE: ios/MusicFree.xcodeproj/project.pbxproj ================================================ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 54; objects = { /* Begin PBXBuildFile section */ 00E356F31AD99517003FC87E /* MusicFreeTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 00E356F21AD99517003FC87E /* MusicFreeTests.m */; }; 0C80B921A6F3F58F76C31292 /* libPods-MusicFree.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5DCACB8F33CDC322A6C60F78 /* libPods-MusicFree.a */; }; 13B07FBC1A68108700A75B9A /* AppDelegate.mm in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB01A68108700A75B9A /* AppDelegate.mm */; }; 13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; }; 13B07FC11A68108700A75B9A /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB71A68108700A75B9A /* main.m */; }; 7699B88040F8A987B510C191 /* libPods-MusicFree-MusicFreeTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 19F6CBCC0A4E27FBF8BF4A61 /* libPods-MusicFree-MusicFreeTests.a */; }; 81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ 00E356F41AD99517003FC87E /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 83CBB9F71A601CBA00E9B192; proxyType = 1; remoteGlobalIDString = 13B07F861A680F5B00A75B9A; remoteInfo = MusicFree; }; /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ 00E356EE1AD99517003FC87E /* MusicFreeTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = MusicFreeTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 00E356F11AD99517003FC87E /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 00E356F21AD99517003FC87E /* MusicFreeTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MusicFreeTests.m; sourceTree = ""; }; 13B07F961A680F5B00A75B9A /* MusicFree.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = MusicFree.app; sourceTree = BUILT_PRODUCTS_DIR; }; 13B07FAF1A68108700A75B9A /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AppDelegate.h; path = MusicFree/AppDelegate.h; sourceTree = ""; }; 13B07FB01A68108700A75B9A /* AppDelegate.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = AppDelegate.mm; path = MusicFree/AppDelegate.mm; sourceTree = ""; }; 13B07FB51A68108700A75B9A /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = MusicFree/Images.xcassets; sourceTree = ""; }; 13B07FB61A68108700A75B9A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = MusicFree/Info.plist; sourceTree = ""; }; 13B07FB71A68108700A75B9A /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = main.m; path = MusicFree/main.m; sourceTree = ""; }; 13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = PrivacyInfo.xcprivacy; path = MusicFree/PrivacyInfo.xcprivacy; sourceTree = ""; }; 19F6CBCC0A4E27FBF8BF4A61 /* libPods-MusicFree-MusicFreeTests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-MusicFree-MusicFreeTests.a"; sourceTree = BUILT_PRODUCTS_DIR; }; 3B4392A12AC88292D35C810B /* Pods-MusicFree.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-MusicFree.debug.xcconfig"; path = "Target Support Files/Pods-MusicFree/Pods-MusicFree.debug.xcconfig"; sourceTree = ""; }; 5709B34CF0A7D63546082F79 /* Pods-MusicFree.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-MusicFree.release.xcconfig"; path = "Target Support Files/Pods-MusicFree/Pods-MusicFree.release.xcconfig"; sourceTree = ""; }; 5B7EB9410499542E8C5724F5 /* Pods-MusicFree-MusicFreeTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-MusicFree-MusicFreeTests.debug.xcconfig"; path = "Target Support Files/Pods-MusicFree-MusicFreeTests/Pods-MusicFree-MusicFreeTests.debug.xcconfig"; sourceTree = ""; }; 5DCACB8F33CDC322A6C60F78 /* libPods-MusicFree.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-MusicFree.a"; sourceTree = BUILT_PRODUCTS_DIR; }; 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = LaunchScreen.storyboard; path = MusicFree/LaunchScreen.storyboard; sourceTree = ""; }; 89C6BE57DB24E9ADA2F236DE /* Pods-MusicFree-MusicFreeTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-MusicFree-MusicFreeTests.release.xcconfig"; path = "Target Support Files/Pods-MusicFree-MusicFreeTests/Pods-MusicFree-MusicFreeTests.release.xcconfig"; sourceTree = ""; }; ED297162215061F000B7C4FE /* JavaScriptCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = JavaScriptCore.framework; path = System/Library/Frameworks/JavaScriptCore.framework; sourceTree = SDKROOT; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 00E356EB1AD99517003FC87E /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 7699B88040F8A987B510C191 /* libPods-MusicFree-MusicFreeTests.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; 13B07F8C1A680F5B00A75B9A /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 0C80B921A6F3F58F76C31292 /* libPods-MusicFree.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 00E356EF1AD99517003FC87E /* MusicFreeTests */ = { isa = PBXGroup; children = ( 00E356F21AD99517003FC87E /* MusicFreeTests.m */, 00E356F01AD99517003FC87E /* Supporting Files */, ); path = MusicFreeTests; sourceTree = ""; }; 00E356F01AD99517003FC87E /* Supporting Files */ = { isa = PBXGroup; children = ( 00E356F11AD99517003FC87E /* Info.plist */, ); name = "Supporting Files"; sourceTree = ""; }; 13B07FAE1A68108700A75B9A /* MusicFree */ = { isa = PBXGroup; children = ( 13B07FAF1A68108700A75B9A /* AppDelegate.h */, 13B07FB01A68108700A75B9A /* AppDelegate.mm */, 13B07FB51A68108700A75B9A /* Images.xcassets */, 13B07FB61A68108700A75B9A /* Info.plist */, 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */, 13B07FB71A68108700A75B9A /* main.m */, 13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */, ); name = MusicFree; sourceTree = ""; }; 2D16E6871FA4F8E400B85C8A /* Frameworks */ = { isa = PBXGroup; children = ( ED297162215061F000B7C4FE /* JavaScriptCore.framework */, 5DCACB8F33CDC322A6C60F78 /* libPods-MusicFree.a */, 19F6CBCC0A4E27FBF8BF4A61 /* libPods-MusicFree-MusicFreeTests.a */, ); name = Frameworks; sourceTree = ""; }; 832341AE1AAA6A7D00B99B32 /* Libraries */ = { isa = PBXGroup; children = ( ); name = Libraries; sourceTree = ""; }; 83CBB9F61A601CBA00E9B192 /* PBXGroup */ = { isa = PBXGroup; children = ( 13B07FAE1A68108700A75B9A /* MusicFree */, 832341AE1AAA6A7D00B99B32 /* Libraries */, 00E356EF1AD99517003FC87E /* MusicFreeTests */, 83CBBA001A601CBA00E9B192 /* Products */, 2D16E6871FA4F8E400B85C8A /* Frameworks */, BBD78D7AC51CEA395F1C20DB /* Pods */, ); indentWidth = 2; sourceTree = ""; tabWidth = 2; usesTabs = 0; }; 83CBBA001A601CBA00E9B192 /* Products */ = { isa = PBXGroup; children = ( 13B07F961A680F5B00A75B9A /* MusicFree.app */, 00E356EE1AD99517003FC87E /* MusicFreeTests.xctest */, ); name = Products; sourceTree = ""; }; BBD78D7AC51CEA395F1C20DB /* Pods */ = { isa = PBXGroup; children = ( 3B4392A12AC88292D35C810B /* Pods-MusicFree.debug.xcconfig */, 5709B34CF0A7D63546082F79 /* Pods-MusicFree.release.xcconfig */, 5B7EB9410499542E8C5724F5 /* Pods-MusicFree-MusicFreeTests.debug.xcconfig */, 89C6BE57DB24E9ADA2F236DE /* Pods-MusicFree-MusicFreeTests.release.xcconfig */, ); path = Pods; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 00E356ED1AD99517003FC87E /* MusicFreeTests */ = { isa = PBXNativeTarget; buildConfigurationList = 00E357021AD99517003FC87E /* Build configuration list for PBXNativeTarget "MusicFreeTests" */; buildPhases = ( A55EABD7B0C7F3A422A6CC61 /* [CP] Check Pods Manifest.lock */, 00E356EA1AD99517003FC87E /* Sources */, 00E356EB1AD99517003FC87E /* Frameworks */, 00E356EC1AD99517003FC87E /* Resources */, C59DA0FBD6956966B86A3779 /* [CP] Embed Pods Frameworks */, F6A41C54EA430FDDC6A6ED99 /* [CP] Copy Pods Resources */, ); buildRules = ( ); dependencies = ( 00E356F51AD99517003FC87E /* PBXTargetDependency */, ); name = MusicFreeTests; productName = MusicFreeTests; productReference = 00E356EE1AD99517003FC87E /* MusicFreeTests.xctest */; productType = "com.apple.product-type.bundle.unit-test"; }; 13B07F861A680F5B00A75B9A /* MusicFree */ = { isa = PBXNativeTarget; buildConfigurationList = 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "MusicFree" */; buildPhases = ( C38B50BA6285516D6DCD4F65 /* [CP] Check Pods Manifest.lock */, 13B07F871A680F5B00A75B9A /* Sources */, 13B07F8C1A680F5B00A75B9A /* Frameworks */, 13B07F8E1A680F5B00A75B9A /* Resources */, 00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */, 00EEFC60759A1932668264C0 /* [CP] Embed Pods Frameworks */, E235C05ADACE081382539298 /* [CP] Copy Pods Resources */, ); buildRules = ( ); dependencies = ( ); name = MusicFree; productName = MusicFree; productReference = 13B07F961A680F5B00A75B9A /* MusicFree.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 83CBB9F71A601CBA00E9B192 = { isa = PBXProject; attributes = { LastUpgradeCheck = 1210; TargetAttributes = { 00E356ED1AD99517003FC87E = { CreatedOnToolsVersion = 6.2; TestTargetID = 13B07F861A680F5B00A75B9A /* MusicFree */; }; 13B07F861A680F5B00A75B9A = { LastSwiftMigration = 1120; }; }; }; buildConfigurationList = 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "MusicFree" */; compatibilityVersion = "Xcode 12.0"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); mainGroup = 83CBB9F61A601CBA00E9B192 /* PBXGroup */; productRefGroup = 83CBBA001A601CBA00E9B192 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( 13B07F861A680F5B00A75B9A /* MusicFree */, 00E356ED1AD99517003FC87E /* MusicFreeTests */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ 00E356EC1AD99517003FC87E /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; 13B07F8E1A680F5B00A75B9A /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( 81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */, 13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ 00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( "$(SRCROOT)/.xcode.env.local", "$(SRCROOT)/.xcode.env", ); name = "Bundle React Native code and images"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "if [[ -f \"$PODS_ROOT/../.xcode.env\" ]]; then\n source \"$PODS_ROOT/../.xcode.env\"\nfi\nif [[ -f \"$PODS_ROOT/../.xcode.env.local\" ]]; then\n source \"$PODS_ROOT/../.xcode.env.local\"\nfi\n\n# The project root by default is one level up from the ios directory\nexport PROJECT_ROOT=\"$PROJECT_DIR\"/..\n\nif [[ \"$CONFIGURATION\" = *Debug* ]]; then\n export SKIP_BUNDLING=1\nfi\nif [[ -z \"$ENTRY_FILE\" ]]; then\n # Set the entry JS file using the bundler's entry resolution.\n export ENTRY_FILE=\"$(\"$NODE_BINARY\" -e \"require('expo/scripts/resolveAppEntry')\" \"$PROJECT_ROOT\" ios absolute | tail -n 1)\"\nfi\n\nif [[ -z \"$CLI_PATH\" ]]; then\n # Use Expo CLI\n export CLI_PATH=\"$(\"$NODE_BINARY\" --print \"require.resolve('@expo/cli')\")\"\nfi\nif [[ -z \"$BUNDLE_COMMAND\" ]]; then\n # Default Expo CLI command for bundling\n export BUNDLE_COMMAND=\"export:embed\"\nfi\n\n`\"$NODE_BINARY\" --print \"require('path').dirname(require.resolve('react-native/package.json')) + '/scripts/react-native-xcode.sh'\"`\n"; }; 00EEFC60759A1932668264C0 /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-MusicFree/Pods-MusicFree-frameworks-${CONFIGURATION}-input-files.xcfilelist", ); name = "[CP] Embed Pods Frameworks"; outputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-MusicFree/Pods-MusicFree-frameworks-${CONFIGURATION}-output-files.xcfilelist", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-MusicFree/Pods-MusicFree-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; A55EABD7B0C7F3A422A6CC61 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( ); inputPaths = ( "${PODS_PODFILE_DIR_PATH}/Podfile.lock", "${PODS_ROOT}/Manifest.lock", ); name = "[CP] Check Pods Manifest.lock"; outputFileListPaths = ( ); outputPaths = ( "$(DERIVED_FILE_DIR)/Pods-MusicFree-MusicFreeTests-checkManifestLockResult.txt", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; showEnvVarsInLog = 0; }; C38B50BA6285516D6DCD4F65 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( ); inputPaths = ( "${PODS_PODFILE_DIR_PATH}/Podfile.lock", "${PODS_ROOT}/Manifest.lock", ); name = "[CP] Check Pods Manifest.lock"; outputFileListPaths = ( ); outputPaths = ( "$(DERIVED_FILE_DIR)/Pods-MusicFree-checkManifestLockResult.txt", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; showEnvVarsInLog = 0; }; C59DA0FBD6956966B86A3779 /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-MusicFree-MusicFreeTests/Pods-MusicFree-MusicFreeTests-frameworks-${CONFIGURATION}-input-files.xcfilelist", ); name = "[CP] Embed Pods Frameworks"; outputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-MusicFree-MusicFreeTests/Pods-MusicFree-MusicFreeTests-frameworks-${CONFIGURATION}-output-files.xcfilelist", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-MusicFree-MusicFreeTests/Pods-MusicFree-MusicFreeTests-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; E235C05ADACE081382539298 /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-MusicFree/Pods-MusicFree-resources-${CONFIGURATION}-input-files.xcfilelist", ); name = "[CP] Copy Pods Resources"; outputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-MusicFree/Pods-MusicFree-resources-${CONFIGURATION}-output-files.xcfilelist", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-MusicFree/Pods-MusicFree-resources.sh\"\n"; showEnvVarsInLog = 0; }; F6A41C54EA430FDDC6A6ED99 /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-MusicFree-MusicFreeTests/Pods-MusicFree-MusicFreeTests-resources-${CONFIGURATION}-input-files.xcfilelist", ); name = "[CP] Copy Pods Resources"; outputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-MusicFree-MusicFreeTests/Pods-MusicFree-MusicFreeTests-resources-${CONFIGURATION}-output-files.xcfilelist", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-MusicFree-MusicFreeTests/Pods-MusicFree-MusicFreeTests-resources.sh\"\n"; showEnvVarsInLog = 0; }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ 00E356EA1AD99517003FC87E /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 00E356F31AD99517003FC87E /* MusicFreeTests.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; 13B07F871A680F5B00A75B9A /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 13B07FBC1A68108700A75B9A /* AppDelegate.mm in Sources */, 13B07FC11A68108700A75B9A /* main.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ 00E356F51AD99517003FC87E /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 13B07F861A680F5B00A75B9A /* MusicFree */; targetProxy = 00E356F41AD99517003FC87E /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */ 00E356F61AD99517003FC87E /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 5B7EB9410499542E8C5724F5 /* Pods-MusicFree-MusicFreeTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); INFOPLIST_FILE = MusicFreeTests/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 15.1; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", "@loader_path/Frameworks", ); OTHER_LDFLAGS = ( "-ObjC", "-lc++", "$(inherited)", ); PRODUCT_BUNDLE_IDENTIFIER = "org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/MusicFree.app/MusicFree"; SWIFT_VERSION = 5.0; }; name = Debug; }; 00E356F71AD99517003FC87E /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 89C6BE57DB24E9ADA2F236DE /* Pods-MusicFree-MusicFreeTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; COPY_PHASE_STRIP = NO; INFOPLIST_FILE = MusicFreeTests/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 15.1; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", "@loader_path/Frameworks", ); OTHER_LDFLAGS = ( "-ObjC", "-lc++", "$(inherited)", ); PRODUCT_BUNDLE_IDENTIFIER = "org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/MusicFree.app/MusicFree"; SWIFT_VERSION = 5.0; }; name = Release; }; 13B07F941A680F5B00A75B9A /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 3B4392A12AC88292D35C810B /* Pods-MusicFree.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CURRENT_PROJECT_VERSION = 1; ENABLE_BITCODE = NO; INFOPLIST_FILE = MusicFree/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 15.1; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); MARKETING_VERSION = 1.0; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", "-lc++", ); PRODUCT_BUNDLE_IDENTIFIER = "org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = MusicFree; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 5.0; VERSIONING_SYSTEM = "apple-generic"; }; name = Debug; }; 13B07F951A680F5B00A75B9A /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 5709B34CF0A7D63546082F79 /* Pods-MusicFree.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CURRENT_PROJECT_VERSION = 1; INFOPLIST_FILE = MusicFree/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 15.1; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); MARKETING_VERSION = 1.0; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", "-lc++", ); PRODUCT_BUNDLE_IDENTIFIER = "org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = MusicFree; SWIFT_VERSION = 5.0; VERSIONING_SYSTEM = "apple-generic"; }; name = Release; }; 83CBBA201A601CBA00E9B192 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_CXX_LANGUAGE_STANDARD = "c++20"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; "EXCLUDED_ARCHS[sdk=iphonesimulator*]" = ""; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 15.1; LD_RUNPATH_SEARCH_PATHS = ( /usr/lib/swift, "$(inherited)", ); LIBRARY_SEARCH_PATHS = ( "\"$(SDKROOT)/usr/lib/swift\"", "\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\"", "\"$(inherited)\"", ); MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; OTHER_CPLUSPLUSFLAGS = ( "$(OTHER_CFLAGS)", "-DFOLLY_NO_CONFIG", "-DFOLLY_MOBILE=1", "-DFOLLY_USE_LIBCPP=1", "-DFOLLY_CFG_NO_COROUTINES=1", "-DFOLLY_HAVE_CLOCK_GETTIME=1", ); SDKROOT = iphoneos; SWIFT_VERSION = 5.0; }; name = Debug; }; 83CBBA211A601CBA00E9B192 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_CXX_LANGUAGE_STANDARD = "c++20"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = YES; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; "EXCLUDED_ARCHS[sdk=iphonesimulator*]" = ""; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 15.1; LD_RUNPATH_SEARCH_PATHS = ( /usr/lib/swift, "$(inherited)", ); LIBRARY_SEARCH_PATHS = ( "\"$(SDKROOT)/usr/lib/swift\"", "\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\"", "\"$(inherited)\"", ); MTL_ENABLE_DEBUG_INFO = NO; OTHER_CPLUSPLUSFLAGS = ( "$(OTHER_CFLAGS)", "-DFOLLY_NO_CONFIG", "-DFOLLY_MOBILE=1", "-DFOLLY_USE_LIBCPP=1", "-DFOLLY_CFG_NO_COROUTINES=1", "-DFOLLY_HAVE_CLOCK_GETTIME=1", ); SDKROOT = iphoneos; VALIDATE_PRODUCT = YES; SWIFT_VERSION = 5.0; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 00E357021AD99517003FC87E /* Build configuration list for PBXNativeTarget "MusicFreeTests" */ = { isa = XCConfigurationList; buildConfigurations = ( 00E356F61AD99517003FC87E /* Debug */, 00E356F71AD99517003FC87E /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "MusicFree" */ = { isa = XCConfigurationList; buildConfigurations = ( 13B07F941A680F5B00A75B9A /* Debug */, 13B07F951A680F5B00A75B9A /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "MusicFree" */ = { isa = XCConfigurationList; buildConfigurations = ( 83CBBA201A601CBA00E9B192 /* Debug */, 83CBBA211A601CBA00E9B192 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 83CBB9F71A601CBA00E9B192; } ================================================ FILE: ios/MusicFree.xcodeproj/xcshareddata/xcschemes/MusicFreeNew.xcscheme ================================================ ================================================ FILE: ios/MusicFreeTests/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType BNDL CFBundleShortVersionString 1.0 CFBundleSignature ???? CFBundleVersion 1 ================================================ FILE: ios/MusicFreeTests/MusicFreeNewTests.m ================================================ #import #import #import #import #define TIMEOUT_SECONDS 600 #define TEXT_TO_LOOK_FOR @"Welcome to React" @interface MusicFreeTests : XCTestCase @end @implementation MusicFreeTests - (BOOL)findSubviewInView:(UIView *)view matching:(BOOL (^)(UIView *view))test { if (test(view)) { return YES; } for (UIView *subview in [view subviews]) { if ([self findSubviewInView:subview matching:test]) { return YES; } } return NO; } - (void)testRendersWelcomeScreen { UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController]; NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS]; BOOL foundElement = NO; __block NSString *redboxError = nil; #ifdef DEBUG RCTSetLogFunction( ^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) { if (level >= RCTLogLevelError) { redboxError = message; } }); #endif while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) { [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; foundElement = [self findSubviewInView:vc.view matching:^BOOL(UIView *view) { if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) { return YES; } return NO; }]; } #ifdef DEBUG RCTSetLogFunction(RCTDefaultLogFunction); #endif XCTAssertNil(redboxError, @"RedBox error: %@", redboxError); XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS); } @end ================================================ FILE: ios/Podfile ================================================ require File.join(File.dirname(`node --print "require.resolve('expo/package.json')"`), "scripts/autolinking") # Resolve react_native_pods.rb with node to allow for hoisting require Pod::Executable.execute_command('node', ['-p', 'require.resolve( "react-native/scripts/react_native_pods.rb", {paths: [process.argv[1]]}, )', __dir__]).strip platform :ios, min_ios_version_supported prepare_react_native_project! linkage = ENV['USE_FRAMEWORKS'] if linkage != nil Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green use_frameworks! :linkage => linkage.to_sym end target 'MusicFree' do use_expo_modules! post_integrate do |installer| begin expo_patch_react_imports!(installer) rescue => e Pod::UI.warn e end end if ENV['EXPO_USE_COMMUNITY_AUTOLINKING'] == '1' config_command = ['node', '-e', "process.argv=['', '', 'config'];require('@react-native-community/cli').run()"]; else config_command = [ 'node', '--no-warnings', '--eval', 'require(require.resolve(\'expo-modules-autolinking\', { paths: [require.resolve(\'expo/package.json\')] }))(process.argv.slice(1))', 'react-native-config', '--json', '--platform', 'ios' ] end config = use_native_modules!(config_command) use_react_native!( :path => config[:reactNativePath], # An absolute path to your application root. :app_path => "#{Pod::Config.instance.installation_root}/.." ) target 'MusicFreeTests' do inherit! :complete # Pods for testing end post_install do |installer| # https://github.com/facebook/react-native/blob/main/packages/react-native/scripts/react_native_pods.rb#L197-L202 react_native_post_install( installer, config[:reactNativePath], :mac_catalyst_enabled => false, # :ccache_enabled => true ) end end ================================================ FILE: jest.config.js ================================================ module.exports = { preset: 'react-native', }; ================================================ FILE: metro.config.js ================================================ const {getDefaultConfig} = require('expo/metro-config'); const {mergeConfig} = require('@react-native/metro-config'); /** * Reference: https://github.com/software-mansion/react-native-svg/blob/main/USAGE.md */ const defaultConfig = getDefaultConfig(__dirname); const {assetExts, sourceExts} = defaultConfig.resolver; /** * Metro configuration * https://reactnative.dev/docs/metro * * @type {import('metro-config').MetroConfig} */ const config = { transformer: { babelTransformerPath: require.resolve('react-native-svg-transformer'), }, resolver: { assetExts: assetExts.filter(ext => ext !== 'svg'), sourceExts: [...sourceExts, 'svg'], }, }; module.exports = mergeConfig(getDefaultConfig(__dirname), config); ================================================ FILE: package.json ================================================ { "name": "MusicFree", "version": "0.6.2", "private": true, "license": "AGPL", "author": { "name": "猫头猫", "email": "lhx_xjtu@163.com" }, "scripts": { "android": "react-native run-android", "ios": "react-native run-ios", "lint": "eslint . --ext .js,.jsx,.ts,.tsx src --fix", "start": "react-native start", "clean": "cd ./android && ./gradlew clean", "test": "jest", "commit-lint": "commitlint --edit", "lint-staged": "lint-staged", "connect-mumu": "adb kill-server & adb connect localhost:7555", "build-android": "cd .\\android\\ && .\\gradlew assembleRelease", "generate-assets": "node ./generator/generate-assets.mjs", "prepare": "husky" }, "dependencies": { "@react-native-async-storage/async-storage": "1.23.1", "@react-native-clipboard/clipboard": "^1.15.0", "@react-native-community/netinfo": "11.4.1", "@react-native-community/slider": "~4.5.6", "@react-native-masked-view/masked-view": "0.3.2", "@react-navigation/drawer": "^6.7.2", "@react-navigation/native": "^6.1.18", "@react-navigation/native-stack": "^6.11.0", "@shopify/flash-list": "1.7.1", "axios": "1.7.4", "big-integer": "^1.6.52", "cheerio": "^1.0.0-rc.12", "color": "^4.2.3", "compare-versions": "^6.1.1", "crypto-js": "^4.2.0", "dayjs": "^1.11.12", "deepmerge": "^4.3.1", "eventemitter3": "^5.0.1", "expo": "^52.0.0", "expo-document-picker": "~13.0.1", "expo-file-system": "~18.0.6", "expo-keep-awake": "~14.0.1", "expo-splash-screen": "~0.29.18", "he": "^1.2.0", "immer": "^10.1.1", "jotai": "^2.9.1", "lodash.shuffle": "^4.2.0", "marked": "^15.0.12", "nanoid": "5.0.8", "object-path": "^0.11.8", "p-queue": "^8.0.1", "path-browserify": "^1.0.1", "qs": "^6.13.0", "react": "18.3.1", "react-native": "0.76.5", "react-native-background-timer": "^2.4.1", "react-native-circular-progress-indicator": "^4.4.2", "react-native-device-info": "^14.0.4", "react-native-fast-image": "^8.6.3", "react-native-fs": "^2.20.0", "react-native-gesture-handler": "~2.25.0", "react-native-get-random-values": "^1.11.0", "react-native-image-colors": "^2.4.0", "react-native-image-picker": "^7.1.2", "react-native-linear-gradient": "^2.8.3", "react-native-logs": "^5.1.0", "react-native-mmkv": "^2.12.2", "react-native-pager-view": "6.5.1", "react-native-permissions": "^4.1.5", "react-native-reanimated": "^3.17.5", "react-native-safe-area-context": "~5.4.0", "react-native-screens": "~4.4.0", "react-native-share": "^10.2.1", "react-native-svg": "^15.11.2", "react-native-tab-view": "^3.5.2", "react-native-track-player": "^4.1.1", "react-native-url-polyfill": "^2.0.0", "react-native-webview": "^13.13.5", "recyclerlistview": "^4.2.1", "webdav": "^5.7.0" }, "devDependencies": { "@babel/core": "^7.25.2", "@babel/preset-env": "^7.25.3", "@babel/runtime": "^7.25.0", "@commitlint/cli": "^19.3.0", "@commitlint/config-conventional": "^19.2.2", "@react-native-community/cli": "15.0.1", "@react-native-community/cli-platform-android": "15.0.1", "@react-native-community/cli-platform-ios": "15.0.1", "@react-native/babel-preset": "0.76.5", "@react-native/eslint-config": "0.76.5", "@react-native/metro-config": "0.76.5", "@react-native/typescript-config": "0.76.5", "@types/color": "^3.0.6", "@types/crypto-js": "^4.2.2", "@types/he": "^1.2.3", "@types/lodash.shuffle": "^4.2.9", "@types/object-path": "^0.11.4", "@types/path-browserify": "^1.0.2", "@types/qs": "^6.9.15", "@types/react": "~18.3.12", "@types/react-native-background-timer": "^2.0.2", "@types/react-test-renderer": "^18.0.0", "babel-jest": "^29.6.3", "babel-plugin-module-resolver": "^5.0.2", "babel-plugin-transform-remove-console": "^6.9.4", "eslint": "^8.19.0", "eslint-config-prettier": "^9.1.0", "husky": "^9.1.4", "jest": "^29.6.3", "lint-staged": "^15.2.7", "prettier": "2.8.8", "react-native-svg-transformer": "^1.5.0", "react-test-renderer": "18.3.1", "typescript": "^5.3.3" }, "engines": { "node": ">=18" }, "lint-staged": { "src/**/*.{ts,tsx}": [ "npm run lint", "git add ." ] }, "repository": { "type": "git", "url": "git+https://github.com/maotoumao/MusicFree.git" } } ================================================ FILE: readme-en.md ================================================ # MusicFree [中文](./readme.md) | **English** ![GitHub Repo stars](https://img.shields.io/github/stars/maotoumao/MusicFree) ![GitHub forks](https://img.shields.io/github/forks/maotoumao/MusicFree) ![star](https://gitcode.com/maotoumao/MusicFree/star/badge.svg) ![GitHub License](https://img.shields.io/github/license/maotoumao/MusicFree) ![GitHub Downloads (all assets, all releases)](https://img.shields.io/github/downloads/maotoumao/MusicFree/total) ![GitHub Issues or Pull Requests](https://img.shields.io/github/issues/maotoumao/MusicFree) ![GitHub package.json version](https://img.shields.io/github/package-json/v/maotoumao/MusicFree) maotoumao%2FMusicFree | Trendshift --- ## Introduction A plugin-based, customizable, ad-free music player that currently supports Android and Harmony OS only. > **Desktop version is here: ** If you need to stay updated on future developments, you can follow the WeChat official account below; if you have questions, you can leave feedback directly in the issue section or the official account. ![WeChat Official Account](./src/assets/imgs/wechat_channel.jpg) For software download methods, plugin usage instructions, and plugin development documentation, please visit . > [!NOTE] > - If you see paid/ad-free/cracked versions on other platforms, they are all fake. This is an open source project to begin with. **Please report paid versions directly when encountered**; > - The software is primarily for personal use, shared to hopefully help those in need; it's a hobby project that will be maintained as much as possible, but daily development time is limited (about half an hour), and it's expected to remain in unstable testing versions for a long time with irregular update frequency. Please use with caution; > - Third-party plugins and the data they generate are not related to this software. Please use legally and compliantly, and delete any copyright data that may be generated in a timely manner. > - **Please do not promote with VIP/cracked version as a gimmick**. The example repository is based on public internet API wrappers and **filters out all VIP, preview, and paid songs**. The example repository will **not provide plugins with cracking functionality** in the future; > - Information about this software **will only be actively published in Git repositories and the WeChat official account "一只猫头猫"**. If you wish to write articles introducing this software, feel free to do so, but please **describe truthfully, and please blur the plugin sources when involving the example repository**. Don't add unreal features to the software (although I wish it had them); in case of conflicting descriptions, this repository shall prevail. ## Project Usage Agreement: This project is open sourced under the AGPL 3.0 license. Please comply with the open source license when using this project. In addition, please ensure you understand the following additional notes when using the code: 1. For packaging and redistribution, **please retain the code source**: https://github.com/maotoumao/MusicFree 2. Please do not use for commercial purposes; use the code legally and compliantly; 3. If the open source license changes, it will be updated in this GitHub repository without separate notice. > [!CAUTION] > ### 👎 Hall of Shame > 👎 MusicFree apps on Xiaomi/Huawei/Vivo app stores are not related to this software. **They are adware that misappropriates this software's name and logo**. Please be cautious to avoid being deceived. > > 👎 速悦音乐 is based on secondary development of this software, with changes only including built-in plugins, UI modifications, and traffic diversion. **It has not complied with this project's open source license and refuses to communicate**. ## Features - **Plugin-based**: This software is just a player and **does not integrate** any music sources from any platform. All search, playback, playlist import and other functions are entirely based on **plugins**. This means that **as long as music sources can be searched on the internet, as long as there are corresponding plugins, you can use this software for search, playback and other functions**. For detailed plugin information, please see the Plugin section. - **Plugin-supported features**: Search (music, albums, artists), playback, view albums, view artist details, import singles, import playlists, get lyrics, etc. - **Customizable and ad-free**: This software provides light and dark modes; supports custom backgrounds; this software is open sourced under the AGPL license and ~~one star for a deal~~ will remain free. - **Privacy**: All data is stored locally, this software will not collect any of your personal information. - **Lyrics association**: You can associate the lyrics of two songs, for example, associate song A's lyrics to song B. After association, both songs A and B will display song B's lyrics. You can also associate multiple songs' lyrics, like A->B->C, so that songs A, B, and C will all display C's lyrics. ## Plugins ### Plugin Introduction A plugin is essentially a CommonJS module that satisfies the plugin protocol. The plugin defines basic functions such as search (music, albums, artists), playback, view albums, artist details, import playlists, get lyrics, etc. Plugin developers only need to focus on input and output logic, while pagination, caching, etc. are all handled by MusicFree. This software completes all player functions through plugins. This decoupled design also allows this software to focus on being a feature-complete player. I must say, small and beautiful. Plugin development documentation can be found [here](https://musicfree.catcat.work/plugin/introduction.html) Please note: - If you are using third-party downloaded plugins, please identify the security of the plugins yourself (basically check that there are no strange network requests; self-written ones are the safest, *don't install things from unknown sources*) to prevent malicious code damage. This software is not responsible for possible losses caused by third-party malicious plugins. - Plugins may generate certain copyright data unrelated to this software during use. Plugins and any data generated by plugins are not related to this software. Please consider carefully and delete data in a timely manner. This software does not advocate nor will it provide any cracking behavior. You can build your own offline music repository for use. ### Plugin Usage After downloading the app, you just need to install plugins in the sidebar Settings - Plugin Settings. Supports installing local plugins and installing plugins from the network (supports parsing .js files and .json description files; several example plugins have been written: [link to this repository](https://github.com/maotoumao/MusicFreePlugins), though functionality may not be very complete); You can directly click "Install plugin from network", then enter and click confirm to install. For detailed usage instructions with images, please refer to the WeChat official account: [MusicFree Plugin Usage Guide](https://mp.weixin.qq.com/s?__biz=MzkxOTM5MDI4MA==&mid=2247483875&idx=1&sn=aedf8bb909540634d927de7fd2b4b8b1&chksm=c1a390c4f6d419d233908bb781d418c6b9fd2ca82e9e93291e7c93b8ead3c50ca5ae39668212#rd), or the website: https://musicfree.catcat.work/usage/mobile/install-plugin.html ## Download Please go to the release page: [Link](https://github.com/maotoumao/MusicFree/releases) (if you can't open it, you can replace github with gitee). You can also reply "Musicfree" on the WeChat official account. ## Q&A For common issues encountered during use, see here: [MusicFree Usage Q&A](https://musicfree.catcat.work/qa/common.html) For technical exchange/building interesting things together/technical chats, welcome to join the QQ group: [683467814](https://jq.qq.com/?_wv=1027&k=upVpi2k3)~ (Not a Q&A group) For casual chat, you can go to [QQ Channel](https://pd.qq.com/s/cyxnf0jj1)~ ## WIP If you have new requirements that need discussion, you can leave a message on the WeChat official account backend/submit an issue/or start a topic in discussions. ## Support This Project If you like this project, or hope I can continue maintaining it, you can support me through any of the following ways ;) 1. Star this project and share it with people around you; 2. Follow the WeChat official account 👇 or Bilibili [不想睡觉猫头猫](https://space.bilibili.com/12866223) for the latest information; 3. Follow maotoumao's [XiaoHongShu](https://www.xiaohongshu.com/user/profile/5ce6085200000000050213a6?xhsshare=CopyLink&appuid=5ce6085200000000050213a6&apptime=1714394544) or [X](https://twitter.com/upupfun). Although I might not update software-related information there, it's still support~ ![WeChat Official Account](./src/assets/imgs/wechat_channel.jpg) Thanks to the following friends for their recommendations, very surprising and delightful ~~~ Recommendation from **果核剥壳**~ Recommendation from **小棉袄**~ ## ChangeLog [Click here](./changelog.md) --- This project is for learning and reference only, open sourced under the AGPL3.0 license; please use this project reasonably in compliance with laws and regulations, prohibited for commercial use. ## App Screenshots **The following screenshots are UI examples only. The software does not provide any music sources internally and does not represent actual performance as shown below.** #### Main Interface Main Interface #### Sidebar - Sidebar Sidebar - Basic Settings Basic Settings - Theme Settings Theme Settings #### Music Related - Playlist Page Playlist Page - Search in Playlist Search in Playlist - Player Page Player Page - Lyrics Page Lyrics Page #### Search Related - Artist Information Artist Information
The following are UI from early versions of the software #### Main Interface Main Interface #### Sidebar - Basic Settings Basic Settings - Theme Settings Theme Settings #### Music Related - Playlist Page Playlist Page - Search in Playlist Search in Playlist - Player Page Player Page - Lyrics Page Lyrics Page #### Search Related - Artist Information Artist Information
================================================ FILE: readme.md ================================================ # MusicFree **中文** | [English](./readme-en.md) ![GitHub Repo stars](https://img.shields.io/github/stars/maotoumao/MusicFree) ![GitHub forks](https://img.shields.io/github/forks/maotoumao/MusicFree) ![star](https://gitcode.com/maotoumao/MusicFree/star/badge.svg) ![GitHub License](https://img.shields.io/github/license/maotoumao/MusicFree) ![GitHub Downloads (all assets, all releases)](https://img.shields.io/github/downloads/maotoumao/MusicFree/total) ![GitHub Issues or Pull Requests](https://img.shields.io/github/issues/maotoumao/MusicFree) ![GitHub package.json version](https://img.shields.io/github/package-json/v/maotoumao/MusicFree) maotoumao%2FMusicFree | Trendshift ## 简介 一个插件化、定制化、无广告的免费音乐播放器,目前只支持 Android 和 Harmony OS。 > **桌面版来啦:** 如果需要了解后续进展可以关注公众号↓;如果有问题可以在 issue 区或者公众号直接留言反馈。 ![微信公众号](./src/assets/imgs/wechat_channel.jpg) 软件下载方式、插件使用说明、插件开发文档可去站点 [https://musicfree.catcat.work](https://musicfree.catcat.work) 查看。 > [!NOTE] > - 如果你在其他的平台看到收费版/无广告版/破解版,都是假的,本来就是开源项目,**遇到收费版请直接举报**; > - 软件首先是自用,顺带分享出来希望可以帮助到有需要的人;是业余作品,会尽量保持维护,不过每天能写的时间有限(半小时左右),目测会有很长一段时间处于不稳定测试版本,且更新频率不定,请谨慎使用; > - 软件的第三方插件、及其所产生的数据与本软件无关,请合理合法使用,可能产生的版权数据请及时删除。 > - **请不要以 VIP/破解版为噱头进行宣传**,示例仓库基于互联网公开接口封装,并**过滤掉所有 VIP、试听、付费歌曲**,且示例仓库以后也**不会提供具备破解功能的插件**; > - 本软件的相关信息**只会主动投放在 Git 仓库以及公众号“一只猫头猫”中**,如果希望写文章介绍本软件请自便,但还烦请**如实陈述,涉及到示例仓库请给插件源打个码**,不要给软件增加一些不实的功能(尽管我也想有);描述冲突的地方以本仓库为准。 ## 项目使用约定: 本项目基于 AGPL 3.0 协议开源,使用此项目时请遵守开源协议。 除此外,希望你在使用代码时已经了解以下额外说明: 1. 打包、二次分发 **请保留代码出处**:https://github.com/maotoumao/MusicFree 2. 请不要用于商业用途,合法合规使用代码; 3. 如果开源协议变更,将在此 Github 仓库更新,不另行通知。 > [!CAUTION] > ### 👎 Hall of Shame > 👎 小米/华为/vivo等应用市场的 MusicFree 和本软件无关,**是套用本软件名称和 Logo 的广告软件**。 > > 👎 速悦音乐基于本软件二次开发,改动点仅仅是内置插件、修改一些 UI 以及引流,**并未遵守本项目的开源协议,且拒绝沟通**。 --- ## 特性 - 插件化:本软件仅仅是一个播放器,本身**并不集成**任何平台的任何音源,所有的搜索、播放、歌单导入等功能全部基于**插件**。这也就意味着,**只要可以在互联网上搜索到的音源,只要有对应的插件,你都可以使用本软件进行搜索、播放等功能**。关于插件的详细说明请看插件一节。 - 插件支持的功能:搜索(音乐、专辑、作者)、播放、查看专辑、查看作者详细信息、导入单曲、导入歌单、获取歌词等。 - 定制化、无广告:本软件提供了浅色、深色模式;支持自定义背景;本软件基于 AGPL 协议开源,~~一个 star 做交易~~ 将会保持免费。 - 隐私:所有的数据都存储在本地,本软件不会收集你的任何个人信息。 - 歌词关联:你可以把两首歌的歌词关联起来,比如将歌曲 A 的歌词关联到歌曲 B,关联后 A、B 两首歌都将显示歌曲 B 的歌词。你也可以关联多首歌的歌词,如 A->B->C,这样 A、B、C 三首歌都将显示 C 的歌词。 ## 插件 ### 插件简介 插件本质上是一个满足插件协议的 commonjs 模块。插件中定义了搜索(音乐、专辑、作者)、播放、查看专辑、作者详细信息、导入歌单、获取歌词等基本函数,插件的开发者只需要关心输入输出逻辑,至于分页、缓存等全都交给 MusicFree 控制即可。本软件通过插件来完成播放器的所有功能,这样解耦的设计也可以使得本软件可以专注于做一个功能完善的播放器,我直呼小而美。 插件开发文档可以参考 [这里](https://musicfree.catcat.work/plugin/introduction.html) 需要注意的是: - 如果你是使用第三方下载的插件,那么请自行鉴别插件的安全性(基本上看下没有奇怪的网络请求什么的就好了;自己写的最安全,*不要安装来路不明的东西*),防止恶意代码破坏。因为第三方恶意插件导致的可能的损失与本软件无关。 - 插件使用过程中可能会产生某些和本软件无关的版权数据,插件、以及插件产生的任何数据与本软件无关,请使用者自行斟酌,及时删除数据,本软件不提倡也不会提供任何破解行为,你可以搭建自己的离线音乐仓库使用。 ### 插件使用 下载 app 之后,只需要在侧边栏设置-插件设置中安装插件即可。支持安装本地插件和从网络安装插件(支持解析.js 文件和.json 描述文件;已经写了几个示意的插件:[指路这个仓库](https://github.com/maotoumao/MusicFreePlugins),不过可能功能不是很完善); 你可以直接点击从网络安装插件,然后输入 ,点击确认即可安装。 图文版详细使用说明可以参考公众号:[MusicFree 插件使用指南](https://mp.weixin.qq.com/s?__biz=MzkxOTM5MDI4MA==&mid=2247483875&idx=1&sn=aedf8bb909540634d927de7fd2b4b8b1&chksm=c1a390c4f6d419d233908bb781d418c6b9fd2ca82e9e93291e7c93b8ead3c50ca5ae39668212#rd),或者站点: https://musicfree.catcat.work/usage/mobile/install-plugin.html ## 下载地址 请转到发布页查看:[指路](https://github.com/maotoumao/MusicFree/releases) (如果打不开可以把 github 换成 gitcode),公众号回复 Musicfree 也可以。 ## Q&A 使用时遇到的常见问题可以看这里:[MusicFree 使用 Q&A](https://musicfree.catcat.work/qa/common.html) 技术交流/一起写点有意思的东西/技术向的闲聊欢迎加群:[683467814](https://jq.qq.com/?_wv=1027&k=upVpi2k3)~ (不是答疑群) 闲聊可以到 [QQ 频道](https://pd.qq.com/s/cyxnf0jj1)~ ## WIP 如果有需要讨论的新需求,可以在公众号后台留言/提issue/或者去discussion开个话题。 ## 支持这个项目 如果你喜欢这个项目,或者希望我可以持续维护下去,你可以通过以下任何一种方式支持我;) 1. Star 这个项目,分享给你身边的人; 2. 关注公众号👇或 b 站 [不想睡觉猫头猫](https://space.bilibili.com/12866223) 获取最新信息; 3. 关注猫头猫的 [小红书](https://www.xiaohongshu.com/user/profile/5ce6085200000000050213a6?xhsshare=CopyLink&appuid=5ce6085200000000050213a6&apptime=1714394544),虽然可能不会在这里更新软件相关的信息,但也算支持啦~ ![微信公众号](./src/assets/imgs/wechat_channel.jpg) 感谢以下小伙伴的推荐,很意外也很惊喜 ~~~ 来自**果核剥壳**的安利~ 来自**小棉袄**的安利~ ## ChangeLog [点击这里](./changelog.md) --- 本项目仅供学习参考使用,基于 AGPL3.0 协议开源;请在符合法律法规的情况下合理使用本项目,禁止用于商业目的使用。 ## 应用截图 **以下截图仅为 UI 样例,软件内部不提供任何音源,不代表实际使用时表现如下图。** #### 主界面 主界面 #### 侧边栏 - 侧边栏 侧边栏 - 基础设置 基础设置 - 主题设置 主题设置 #### 音乐相关 - 歌单页 歌单页 - 歌单内检索 歌单内检索 - 播放页 播放页 - 歌词页 歌词页 #### 搜索相关 - 作者信息 作者信息
以下是软件早期版本的 UI #### 主界面 主界面 #### 侧边栏 - 基础设置 基础设置 - 主题设置 主题设置 #### 音乐相关 - 歌单页 歌单页 - 歌单内检索 歌单内检索 - 播放页 播放页 - 歌词页 歌词页 #### 搜索相关 - 作者信息 作者信息
================================================ FILE: release/version.json ================================================ {"version":"0.6.2","changeLog":[ "【优化】优化了软件启动速度 (需要在【侧边栏-基本设置-插件】中打开【启用插件懒加载】开关)" ],"download":["https://r0rvr854dd1.feishu.cn/drive/folder/KLqKfWOA3lx8MKdo8xNcYpR8n7t"]} ================================================ FILE: src/components/base/SortableFlatList.tsx ================================================ /** * 支持长按拖拽排序的flatlist,右边加个固定的按钮,拖拽排序。 * 考虑到方便实现+节省性能,整个app内的拖拽排序都遵守以下实现。 * 点击会出现 */ import globalStyle from "@/constants/globalStyle"; import { iconSizeConst } from "@/constants/uiConst"; import useTextColor from "@/hooks/useTextColor"; import rpx from "@/utils/rpx"; import { FlashList } from "@shopify/flash-list"; import React, { ForwardedRef, forwardRef, memo, useEffect, useMemo, useRef, useState, } from "react"; import { LayoutRectangle, Pressable, StyleSheet, View } from "react-native"; import { runOnJS, useDerivedValue, useSharedValue, } from "react-native-reanimated"; import Icon from "@/components/base/icon.tsx"; const defaultZIndex = 10; interface ISortableFlatListProps { data: T[]; renderItem: (props: { item: T; index: number }) => JSX.Element; // 高度 itemHeight: number; itemJustifyContent?: | "flex-start" | "flex-end" | "center" | "space-between" | "space-around" | "space-evenly"; // 滚动list距离顶部的距离, 这里写的不好 marginTop: number; /** 拖拽时的背景色 */ activeBackgroundColor?: string; /** 交换结束 */ onSortEnd?: (newData: T[]) => void; } export default function SortableFlatList( props: ISortableFlatListProps, ) { const { data, renderItem, itemHeight, itemJustifyContent, marginTop, activeBackgroundColor, onSortEnd, } = props; // 不要干扰原始数据 const [_data, _setData] = useState([...(data ?? [])]); // 是否禁止滚动 const [scrollEnabled, setScrollEnabled] = useState(true); // 是否处在激活状态, -1表示无,其他表示当前激活的下标 const activeRef = useRef(-1); const [activeItem, setActiveItem] = useState(null); const layoutRef = useRef(); // listref const listRef = useRef | null>(null); // fakeref const fakeItemRef = useRef(null); // contentoffset const contentOffsetYRef = useRef(-1); const targetOffsetYRef = useRef(0); const direction = useSharedValue(0); useEffect(() => { _setData([...(data ?? [])]); }, [data]); const initDragPageY = useRef(0); const initDragLocationY = useRef(0); const offsetRef = useRef(0); //#region 滚动 const scrollingRef = useRef(false); // 列表整体的高度 const listContentHeight = useMemo( () => itemHeight * data.length, [data, itemHeight], ); function scrollToTarget(forceScroll = false) { // 未选中 if (activeRef.current === -1) { scrollingRef.current = false; return; } // 滚动中就不滚了 / if (scrollingRef.current && !forceScroll) { scrollingRef.current = true; return; } // 方向是0 if (direction.value === 0) { scrollingRef.current = false; return; } const nextTarget = Math.sign(direction.value) * Math.max(Math.abs(direction.value), 0.3) * 300 + contentOffsetYRef.current; // 当前到极限了 if ( (contentOffsetYRef.current <= 2 && nextTarget < contentOffsetYRef.current) || (contentOffsetYRef.current >= listContentHeight - (layoutRef.current?.height ?? 0) - 2 && nextTarget > contentOffsetYRef.current) ) { scrollingRef.current = false; return; } scrollingRef.current = true; // 超出区域 targetOffsetYRef.current = Math.min( Math.max(0, nextTarget), listContentHeight - (layoutRef.current?.height ?? 0), ); listRef.current?.scrollToOffset({ animated: true, offset: targetOffsetYRef.current, }); } useDerivedValue(() => { // 正在滚动 if (scrollingRef.current) { return; } else if (direction.value !== 0) { // 开始滚动 runOnJS(scrollToTarget)(); } }, []); //#endregion return ( {/* 纯展示 */} (fakeItemRef.current = _)} backgroundColor={activeBackgroundColor} renderItem={renderItem} itemHeight={itemHeight} item={activeItem} itemJustifyContent={itemJustifyContent} /> { listRef.current = _; }} onLayout={evt => { layoutRef.current = evt.nativeEvent.layout; }} data={_data} estimatedItemSize={itemHeight} scrollEventThrottle={16} onTouchStart={e => { if (activeRef.current !== -1) { // 相对于整个页面顶部的距离 initDragPageY.current = e.nativeEvent.pageY; initDragLocationY.current = e.nativeEvent.locationY; } }} onTouchMove={e => { if (activeRef.current !== -1) { offsetRef.current = e.nativeEvent.pageY - (marginTop ?? layoutRef.current?.y ?? 0) - itemHeight / 2; if (offsetRef.current < 0) { offsetRef.current = 0; } else if ( offsetRef.current > (layoutRef.current?.height ?? 0) - itemHeight ) { offsetRef.current = (layoutRef.current?.height ?? 0) - itemHeight; } fakeItemRef.current!.setNativeProps({ top: offsetRef.current, opacity: 1, zIndex: 100, }); // 如果超出范围,停止 if (offsetRef.current < itemHeight * 2) { // 上滑 direction.value = offsetRef.current / itemHeight / 2 - 1; } else if ( offsetRef.current > (layoutRef.current?.height ?? 0) - 3 * itemHeight ) { // 下滑 direction.value = (offsetRef.current - (layoutRef.current?.height ?? 0) + 3 * itemHeight) / itemHeight / 2; } else { // 不滑动 direction.value = 0; } } }} onTouchEnd={e => { if (activeRef.current !== -1) { // 计算最终的位置,触发onSortEnd let index = activeRef.current; if (contentOffsetYRef.current !== -1) { index = Math.round( (contentOffsetYRef.current + offsetRef.current) / itemHeight, ); } else { // 拖动的距离 index = activeRef.current + Math.round( (e.nativeEvent.pageY - initDragPageY.current + initDragLocationY.current) / itemHeight, ); } index = Math.min(data.length, Math.max(index, 0)); // from: activeRef.current to: index if (activeRef.current !== index) { let nData = _data .slice(0, activeRef.current) .concat(_data.slice(activeRef.current + 1)); nData.splice(index, 0, activeItem as T); onSortEnd?.(nData); // 测试用,正式时移除掉 // _setData(nData); } } scrollingRef.current = false; activeRef.current = -1; setScrollEnabled(true); setActiveItem(null); fakeItemRef.current!.setNativeProps({ top: 0, opacity: 0, zIndex: -1, }); }} onTouchCancel={() => { // todo: 滑动很快的时候会触发取消,native的flatlist就这样 activeRef.current = -1; scrollingRef.current = false; setScrollEnabled(true); setActiveItem(null); fakeItemRef.current!.setNativeProps({ top: 0, opacity: 0, zIndex: -1, }); contentOffsetYRef.current = -1; }} onScroll={e => { contentOffsetYRef.current = e.nativeEvent.contentOffset.y; if ( activeRef.current !== -1 && Math.abs( contentOffsetYRef.current - targetOffsetYRef.current, ) < 2 ) { scrollToTarget(true); } }} renderItem={({ item, index }) => { return ( ); }} /> ); } interface ISortableFlatListItemProps { item: T; index: number; // 高度 itemHeight: number; itemJustifyContent?: | "flex-start" | "flex-end" | "center" | "space-between" | "space-around" | "space-evenly"; setScrollEnabled: (scrollEnabled: boolean) => void; renderItem: (props: { item: T; index: number }) => JSX.Element; setActiveItem: (item: T | null) => void; activeRef: React.MutableRefObject; } function _SortableFlatListItem(props: ISortableFlatListItemProps) { const { itemHeight, setScrollEnabled, renderItem, setActiveItem, itemJustifyContent, item, index, activeRef, } = props; // 省一点性能,height是顺着传下来的,放ref就好了 const styleRef = useRef( StyleSheet.create({ viewWrapper: { height: itemHeight, width: "100%", flexDirection: "row", justifyContent: itemJustifyContent ?? "flex-end", zIndex: defaultZIndex, }, btn: { height: itemHeight, justifyContent: "center", alignItems: "center", position: "absolute", top: 0, right: 0, width: rpx(100), textAlignVertical: "center", }, }), ); const textColor = useTextColor(); return ( {renderItem({ item, index })} { if (activeRef.current !== -1) { return; } /** 使用ref避免其它组件重新渲染; 由于事件冒泡,这里会先触发 */ activeRef.current = index; /** 锁定滚动 */ setScrollEnabled(false); setActiveItem(item); }} style={styleRef.current.btn}> ); } const SortableFlatListItem = memo( _SortableFlatListItem, (prev, curr) => prev.index === curr.index && prev.item === curr.item, ); const FakeFlatListItem = forwardRef(function ( props: Pick< ISortableFlatListItemProps, "itemHeight" | "renderItem" | "item" | "itemJustifyContent" > & { backgroundColor?: string; }, ref: ForwardedRef, ) { const { itemHeight, renderItem, item, backgroundColor, itemJustifyContent } = props; const styleRef = useRef( StyleSheet.create({ viewWrapper: { height: itemHeight, width: "100%", flexDirection: "row", justifyContent: itemJustifyContent ?? "flex-end", zIndex: defaultZIndex, }, btn: { height: itemHeight, paddingHorizontal: rpx(28), justifyContent: "center", alignItems: "center", position: "absolute", top: 0, right: 0, width: rpx(100), textAlignVertical: "center", }, }), ); const textColor = useTextColor(); return ( {item ? renderItem({ item, index: -1 }) : null} ); }); const style = StyleSheet.create({ activeItemDefault: { opacity: 0, zIndex: -1, position: "absolute", top: 0, left: 0, }, }); ================================================ FILE: src/components/base/appBar.tsx ================================================ import React, { ReactNode, useEffect, useState } from "react"; import { LayoutRectangle, StatusBar as OriginalStatusBar, StyleProp, StyleSheet, TouchableWithoutFeedback, View, ViewStyle, } from "react-native"; import rpx from "@/utils/rpx"; import useColors from "@/hooks/useColors"; import StatusBar from "./statusBar"; import color from "color"; import IconButton from "./iconButton"; import globalStyle from "@/constants/globalStyle"; import ThemeText from "./themeText"; import { useNavigation } from "@react-navigation/native"; import Animated, { Easing, useAnimatedStyle, useSharedValue, withTiming, } from "react-native-reanimated"; import Portal from "./portal"; import ListItem from "./listItem"; import { IIconName } from "@/components/base/icon.tsx"; interface IAppBarProps { titleTextOpacity?: number; withStatusBar?: boolean; color?: string; actions?: Array<{ icon: IIconName; onPress?: () => void; }>; menu?: Array<{ icon: IIconName; title: string; show?: boolean; onPress?: () => void; }>; menuWithStatusBar?: boolean; children?: string | ReactNode; containerStyle?: StyleProp; contentStyle?: StyleProp; actionComponent?: ReactNode; onBackPress?: () => void; } const ANIMATION_EASING: Animated.EasingFunction = Easing.out(Easing.exp); const ANIMATION_DURATION = 500; const timingConfig = { duration: ANIMATION_DURATION, easing: ANIMATION_EASING, }; export default function AppBar(props: IAppBarProps) { const { titleTextOpacity = 1, withStatusBar, color: _color, actions = [], menu = [], menuWithStatusBar = true, containerStyle, contentStyle, children, actionComponent, onBackPress, } = props; const colors = useColors(); const navigation = useNavigation(); const bgColor = color(colors.appBar ?? colors.primary).toString(); const contentColor = _color ?? colors.appBarText; const [showMenu, setShowMenu] = useState(false); const [menuIconLayout, setMenuIconLayout] = useState(null); const scaleRate = useSharedValue(0); useEffect(() => { if (showMenu) { scaleRate.value = withTiming(1, timingConfig); } else { scaleRate.value = withTiming(0, timingConfig); } }, [showMenu]); const transformStyle = useAnimatedStyle(() => { return { opacity: scaleRate.value, }; }); return ( <> {withStatusBar ? : null} { navigation.goBack(); }) } /> {typeof children === "string" ? ( {children} ) : ( children )} {actions.map((action, index) => ( ))} {actionComponent ?? null} {menu?.length ? ( { setMenuIconLayout(evt.nativeEvent.layout); }} color={contentColor} style={[globalStyle.notShrink, styles.rightButton]} onPress={() => { setShowMenu(true); }} /> ) : null} {showMenu ? ( { setShowMenu(false); }}> ) : null} <> {menu.map(it => it.show !== false ? ( { setShowMenu(false); // async setTimeout(() => { it.onPress?.(); }, 20); }}> ) : null, )} ); } const styles = StyleSheet.create({ container: { width: "100%", zIndex: 10000, height: rpx(88), flexDirection: "row", alignItems: "center", paddingHorizontal: rpx(24), }, content: { flexDirection: "row", flexBasis: 0, alignItems: "center", paddingHorizontal: rpx(24), }, rightButton: { marginLeft: rpx(28), }, blocker: { position: "absolute", bottom: 0, left: 0, width: "100%", height: "100%", zIndex: 10010, }, bubbleCorner: { position: "absolute", borderColor: "transparent", borderWidth: rpx(10), zIndex: 10012, transformOrigin: "right top", opacity: 0, }, menu: { width: rpx(340), maxHeight: rpx(600), borderRadius: rpx(8), zIndex: 10011, position: "absolute", opacity: 0, shadowOffset: { width: 0, height: 2, }, shadowOpacity: 0.23, shadowRadius: 2.62, elevation: 4, }, }); ================================================ FILE: src/components/base/button.tsx ================================================ import { GestureResponderEvent, StyleProp, StyleSheet, TouchableOpacity, ViewStyle, } from "react-native"; import useColors from "@/hooks/useColors.ts"; import ThemeText from "@/components/base/themeText.tsx"; import React from "react"; import rpx from "@/utils/rpx.ts"; export function Button(props: { type?: "normal" | "primary"; text: string; style?: StyleProp; onPress?: (evt: GestureResponderEvent) => void; }) { const { type = "normal", text, style, onPress } = props; const colors = useColors(); return ( {text} ); } const styles = StyleSheet.create({ bottomBtn: { borderRadius: rpx(8), flexShrink: 0, justifyContent: "center", alignItems: "center", height: rpx(72), }, }); ================================================ FILE: src/components/base/checkbox.tsx ================================================ import React from "react"; import { StyleProp, StyleSheet, View, ViewProps } from "react-native"; import rpx from "@/utils/rpx"; import useColors from "@/hooks/useColors"; import { TouchableOpacity } from "react-native-gesture-handler"; import Icon from "@/components/base/icon.tsx"; interface ICheckboxProps { checked?: boolean; onPress?: () => void; style?: StyleProp; } const slop = rpx(24); export default function Checkbox(props: ICheckboxProps) { const { checked, onPress, style } = props; const colors = useColors(); const innerNode = ( {checked ? ( ) : null} ); return onPress ? ( {innerNode} ) : ( innerNode ); } const styles = StyleSheet.create({ container: { width: rpx(36), height: rpx(36), borderRadius: rpx(2), borderWidth: rpx(1), alignItems: "center", justifyContent: "center", }, }); ================================================ FILE: src/components/base/chip.tsx ================================================ import React, { ReactNode } from "react"; import { Pressable, StyleProp, StyleSheet, ViewStyle } from "react-native"; import rpx from "@/utils/rpx"; import ThemeText from "./themeText"; import useColors from "@/hooks/useColors"; import IconButton from "./iconButton"; interface IChipProps { containerStyle?: StyleProp; children?: ReactNode; onPress?: () => void; onClose?: () => void; } export default function Chip(props: IChipProps) { const { containerStyle, children, onPress, onClose } = props; const colors = useColors(); return ( {typeof children === "string" ? ( {children} ) : ( children )} ); } const styles = StyleSheet.create({ container: { height: rpx(56), paddingHorizontal: rpx(18), borderRadius: rpx(28), flexDirection: "row", alignItems: "center", justifyContent: "center", }, icon: { marginLeft: rpx(8), }, }); ================================================ FILE: src/components/base/colorBlock.tsx ================================================ import React from "react"; import { Image, StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import { ImgAsset } from "@/constants/assetsConst"; interface IColorBlockProps { color: string; } export default function ColorBlock(props: IColorBlockProps) { const { color } = props; return ( ); } const styles = StyleSheet.create({ showBar: { width: rpx(76), height: rpx(50), borderWidth: 1, borderStyle: "solid", borderColor: "#ccc", }, showBarContent: { width: "100%", height: "100%", position: "absolute", left: 0, top: 0, }, transparentBg: { position: "absolute", zIndex: -1, width: "100%", height: "100%", left: 0, top: 0, }, }); ================================================ FILE: src/components/base/divider.tsx ================================================ import React from "react"; import { StyleProp, StyleSheet, View, ViewStyle } from "react-native"; import useColors from "@/hooks/useColors"; interface IDividerProps { vertical?: boolean; style?: StyleProp; } export default function Divider(props: IDividerProps) { const { vertical, style } = props; const colors = useColors(); return ( ); } const css = StyleSheet.create({ divider: { width: "100%", height: 1, }, dividerVertical: { height: "100%", width: 1, }, }); ================================================ FILE: src/components/base/empty.tsx ================================================ import React from "react"; import { StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import ThemeText from "./themeText"; import { useI18N } from "@/core/i18n"; interface IEmptyProps { content?: string; } export default function Empty(props: IEmptyProps) { const { t } = useI18N(); return ( {props?.content ?? t("common.emptyList")} ); } const style = StyleSheet.create({ wrapper: { width: "100%", flex: 1, minHeight: rpx(300), justifyContent: "center", alignItems: "center", }, }); ================================================ FILE: src/components/base/fab.tsx ================================================ import React from "react"; import { Pressable, StyleSheet } from "react-native"; import rpx from "@/utils/rpx"; import useColors from "@/hooks/useColors"; import { iconSizeConst } from "@/constants/uiConst"; import Icon, { IIconName } from "@/components/base/icon.tsx"; interface IFabProps { icon?: IIconName; onPress?: () => void; } export default function Fab(props: IFabProps) { const { icon, onPress } = props; const colors = useColors(); return ( {icon ? ( ) : null} ); } const styles = StyleSheet.create({ container: { width: rpx(108), height: rpx(108), borderRadius: rpx(54), position: "absolute", zIndex: 10010, right: rpx(36), bottom: rpx(72), justifyContent: "center", alignItems: "center", shadowOffset: { width: 0, height: 5, }, shadowOpacity: 0.34, shadowRadius: 6.27, elevation: 10, }, }); ================================================ FILE: src/components/base/fastImage.tsx ================================================ import React, { useEffect, useState } from "react"; import { ImageRequireSource } from "react-native"; import FastImage, { FastImageProps } from "react-native-fast-image"; interface IFastImageProps { style: FastImageProps["style"]; defaultSource?: FastImageProps["defaultSource"]; placeholderSource?: ImageRequireSource; source?: FastImageProps["source"] | string; } export default function (props: IFastImageProps) { const { style, placeholderSource, defaultSource, source } = props ?? {}; const [isError, setIsError] = useState(false); let realSource: FastImageProps["source"]; if (typeof source === "string") { realSource = { uri: source }; if (source.length === 0) { realSource = placeholderSource; } } else if (source){ realSource = source; } else { realSource = placeholderSource; } useEffect(() => { setIsError(false); }, [source]); return ( { setIsError(true); console.error("Image load error:", realSource); }} defaultSource={defaultSource} /> ); } ================================================ FILE: src/components/base/horizontalSafeAreaView.tsx ================================================ import React from "react"; import { StyleProp, ViewStyle } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; interface IHorizontalSafeAreaViewProps { mode?: "margin" | "padding"; children: JSX.Element | JSX.Element[]; style?: StyleProp; } export default function HorizontalSafeAreaView( props: IHorizontalSafeAreaViewProps, ) { const { children, style, mode } = props; return ( {children} ); } ================================================ FILE: src/components/base/icon.tsx ================================================ // This file is generated by generate-assets.mjs. DO NOT MODIFY. import { SvgProps } from "react-native-svg"; import AlarmOutlineIcon from "@/assets/icons/alarm-outline.svg"; import AlbumOutlineIcon from "@/assets/icons/album-outline.svg"; import ArchiveBoxXMarkIcon from "@/assets/icons/archive-box-x-mark.svg"; import ArrowDownTrayIcon from "@/assets/icons/arrow-down-tray.svg"; import ArrowLeftIcon from "@/assets/icons/arrow-left.svg"; import ArrowLongLeftIcon from "@/assets/icons/arrow-long-left.svg"; import ArrowPathIcon from "@/assets/icons/arrow-path.svg"; import ArrowRightEndOnRectangleIcon from "@/assets/icons/arrow-right-end-on-rectangle.svg"; import ArrowUpTrayIcon from "@/assets/icons/arrow-up-tray.svg"; import ArrowUturnLeftIcon from "@/assets/icons/arrow-uturn-left.svg"; import ArrowsLeftRightIcon from "@/assets/icons/arrows-left-right.svg"; import Bars3Icon from "@/assets/icons/bars-3.svg"; import BookmarkSquareIcon from "@/assets/icons/bookmark-square.svg"; import ChatBubbleOvalLeftEllipsisIcon from "@/assets/icons/chat-bubble-oval-left-ellipsis.svg"; import CheckCircleOutlineIcon from "@/assets/icons/check-circle-outline.svg"; import CheckCircleIcon from "@/assets/icons/check-circle.svg"; import CheckIcon from "@/assets/icons/check.svg"; import CircleStackIcon from "@/assets/icons/circle-stack.svg"; import ClockOutlineIcon from "@/assets/icons/clock-outline.svg"; import CodeBracketSquareIcon from "@/assets/icons/code-bracket-square.svg"; import Cog8ToothIcon from "@/assets/icons/cog-8-tooth.svg"; import CrossHairIcon from "@/assets/icons/crosshair.svg"; import DocumentOutlineIcon from "@/assets/icons/document-outline.svg"; import EllipsisVerticalIcon from "@/assets/icons/ellipsis-vertical.svg"; import ExclamationCircleIcon from "@/assets/icons/exclamation-circle.svg"; import FireOutlineIcon from "@/assets/icons/fire-outline.svg"; import FireIcon from "@/assets/icons/fire.svg"; import FolderMusicOutlineIcon from "@/assets/icons/folder-music-outline.svg"; import FolderOutlineIcon from "@/assets/icons/folder-outline.svg"; import FolderPlusIcon from "@/assets/icons/folder-plus.svg"; import FontSizeIcon from "@/assets/icons/font-size.svg"; import HandThumbUpIcon from "@/assets/icons/hand-thumb-up.svg"; import HeartOutlineIcon from "@/assets/icons/heart-outline.svg"; import HeartIcon from "@/assets/icons/heart.svg"; import HomeOutlineIcon from "@/assets/icons/home-outline.svg"; import IdentificationIcon from "@/assets/icons/identification.svg"; import InboxArrowDownIcon from "@/assets/icons/inbox-arrow-down.svg"; import InformationCircleIcon from "@/assets/icons/information-circle.svg"; import JavascriptIcon from "@/assets/icons/javascript.svg"; import LanguageIcon from "@/assets/icons/language.svg"; import LinkSlashIcon from "@/assets/icons/link-slash.svg"; import LinkIcon from "@/assets/icons/link.svg"; import LyricIcon from "@/assets/icons/lyric.svg"; import MagnifyingGlassIcon from "@/assets/icons/magnifying-glass.svg"; import MinusIcon from "@/assets/icons/minus.svg"; import MotionPlayIcon from "@/assets/icons/motion-play.svg"; import MusicalNoteIcon from "@/assets/icons/musical-note.svg"; import PauseCircleOutlineIcon from "@/assets/icons/pause-circle-outline.svg"; import PauseIcon from "@/assets/icons/pause.svg"; import PencilOutlineIcon from "@/assets/icons/pencil-outline.svg"; import PencilSquareIcon from "@/assets/icons/pencil-square.svg"; import PlayCircleOutlineIcon from "@/assets/icons/play-circle-outline.svg"; import PlayCircleIcon from "@/assets/icons/play-circle.svg"; import PlayIcon from "@/assets/icons/play.svg"; import PlaylistIcon from "@/assets/icons/playlist.svg"; import PlusIcon from "@/assets/icons/plus.svg"; import PowerOutlineIcon from "@/assets/icons/power-outline.svg"; import QuestionMarkCircleIcon from "@/assets/icons/question-mark-circle.svg"; import RepeatSong1Icon from "@/assets/icons/repeat-song-1.svg"; import RepeatSongIcon from "@/assets/icons/repeat-song.svg"; import ShareIcon from "@/assets/icons/share.svg"; import ShieldKeyholeOutlineIcon from "@/assets/icons/shield-keyhole-outline.svg"; import ShuffleIcon from "@/assets/icons/shuffle.svg"; import SkipLeftIcon from "@/assets/icons/skip-left.svg"; import SkipRightIcon from "@/assets/icons/skip-right.svg"; import SortOutlineIcon from "@/assets/icons/sort-outline.svg"; import StrategyIcon from "@/assets/icons/strategy.svg"; import TShirtOutlineIcon from "@/assets/icons/t-shirt-outline.svg"; import TranslationIcon from "@/assets/icons/translation.svg"; import TrashOutlineIcon from "@/assets/icons/trash-outline.svg"; import TrophyIcon from "@/assets/icons/trophy.svg"; import UserIcon from "@/assets/icons/user.svg"; import XMarkIcon from "@/assets/icons/x-mark.svg"; export type IIconName = | "alarm-outline" | "album-outline" | "archive-box-x-mark" | "arrow-down-tray" | "arrow-left" | "arrow-long-left" | "arrow-path" | "arrow-right-end-on-rectangle" | "arrow-up-tray" | "arrow-uturn-left" | "arrows-left-right" | "bars-3" | "bookmark-square" | "chat-bubble-oval-left-ellipsis" | "check-circle-outline" | "check-circle" | "check" | "circle-stack" | "clock-outline" | "code-bracket-square" | "cog-8-tooth" | "crosshair" | "document-outline" | "ellipsis-vertical" | "exclamation-circle" | "fire-outline" | "fire" | "folder-music-outline" | "folder-outline" | "folder-plus" | "font-size" | "hand-thumb-up" | "heart-outline" | "heart" | "home-outline" | "identification" | "inbox-arrow-down" | "information-circle" | "javascript" | "language" | "link-slash" | "link" | "lyric" | "magnifying-glass" | "minus" | "motion-play" | "musical-note" | "pause-circle-outline" | "pause" | "pencil-outline" | "pencil-square" | "play-circle-outline" | "play-circle" | "play" | "playlist" | "plus" | "power-outline" | "question-mark-circle" | "repeat-song-1" | "repeat-song" | "share" | "shield-keyhole-outline" | "shuffle" | "skip-left" | "skip-right" | "sort-outline" | "strategy" | "t-shirt-outline" | "translation" | "trash-outline" | "trophy" | "user" | "x-mark"; interface IProps extends SvgProps { /** 图标名称 */ name: IIconName; /** 图标大小 */ size?: number; } const iconMap = { "alarm-outline": AlarmOutlineIcon, "album-outline": AlbumOutlineIcon, "archive-box-x-mark": ArchiveBoxXMarkIcon, "arrow-down-tray": ArrowDownTrayIcon, "arrow-left": ArrowLeftIcon, "arrow-long-left": ArrowLongLeftIcon, "arrow-path": ArrowPathIcon, "arrow-right-end-on-rectangle": ArrowRightEndOnRectangleIcon, "arrow-up-tray": ArrowUpTrayIcon, "arrow-uturn-left": ArrowUturnLeftIcon, "arrows-left-right": ArrowsLeftRightIcon, "bars-3": Bars3Icon, "bookmark-square": BookmarkSquareIcon, "chat-bubble-oval-left-ellipsis": ChatBubbleOvalLeftEllipsisIcon, "check-circle-outline": CheckCircleOutlineIcon, "check-circle": CheckCircleIcon, check: CheckIcon, "circle-stack": CircleStackIcon, "clock-outline": ClockOutlineIcon, "code-bracket-square": CodeBracketSquareIcon, "cog-8-tooth": Cog8ToothIcon, crosshair: CrossHairIcon, "document-outline": DocumentOutlineIcon, "ellipsis-vertical": EllipsisVerticalIcon, "exclamation-circle": ExclamationCircleIcon, "fire-outline": FireOutlineIcon, fire: FireIcon, "folder-music-outline": FolderMusicOutlineIcon, "folder-outline": FolderOutlineIcon, "folder-plus": FolderPlusIcon, "font-size": FontSizeIcon, "hand-thumb-up": HandThumbUpIcon, "heart-outline": HeartOutlineIcon, heart: HeartIcon, "home-outline": HomeOutlineIcon, identification: IdentificationIcon, "inbox-arrow-down": InboxArrowDownIcon, "information-circle": InformationCircleIcon, javascript: JavascriptIcon, "link-slash": LinkSlashIcon, link: LinkIcon, language: LanguageIcon, lyric: LyricIcon, "magnifying-glass": MagnifyingGlassIcon, minus: MinusIcon, "motion-play": MotionPlayIcon, "musical-note": MusicalNoteIcon, "pause-circle-outline": PauseCircleOutlineIcon, pause: PauseIcon, "pencil-outline": PencilOutlineIcon, "pencil-square": PencilSquareIcon, "play-circle-outline": PlayCircleOutlineIcon, "play-circle": PlayCircleIcon, play: PlayIcon, playlist: PlaylistIcon, plus: PlusIcon, "power-outline": PowerOutlineIcon, "question-mark-circle": QuestionMarkCircleIcon, "repeat-song-1": RepeatSong1Icon, "repeat-song": RepeatSongIcon, share: ShareIcon, "shield-keyhole-outline": ShieldKeyholeOutlineIcon, shuffle: ShuffleIcon, "skip-left": SkipLeftIcon, "skip-right": SkipRightIcon, "sort-outline": SortOutlineIcon, strategy: StrategyIcon, "t-shirt-outline": TShirtOutlineIcon, translation: TranslationIcon, "trash-outline": TrashOutlineIcon, trophy: TrophyIcon, user: UserIcon, "x-mark": XMarkIcon, } as const; export default function Icon(props: IProps) { const { name, size } = props; const newProps = { ...props, width: props.width ?? size, height: props.width ?? size, } as SvgProps; const Component = iconMap[name]; return ; } ================================================ FILE: src/components/base/iconButton.tsx ================================================ import React from "react"; import { ColorKey, colorMap, iconSizeConst } from "@/constants/uiConst"; import { TapGestureHandler } from "react-native-gesture-handler"; import { StyleSheet, View } from "react-native"; import useColors from "@/hooks/useColors"; import { SvgProps } from "react-native-svg"; import Icon, { IIconName } from "@/components/base/icon.tsx"; interface IIconButtonProps extends SvgProps { name: IIconName; style?: SvgProps["style"]; sizeType?: keyof typeof iconSizeConst; fontColor?: ColorKey; color?: string; onPress?: () => void; accessibilityLabel?: string; } export function IconButtonWithGesture(props: IIconButtonProps) { const { name, sizeType: size = "normal", fontColor = "normal", onPress, style, accessibilityLabel, } = props; const colors = useColors(); const textSize = iconSizeConst[size]; const color = colors[colorMap[fontColor]]; return ( ); } export default function IconButton(props: IIconButtonProps) { const { sizeType = "normal", fontColor = "normal", style, color } = props; const colors = useColors(); const size = iconSizeConst[sizeType]; return ( ); } const styles = StyleSheet.create({ textCenter: { height: "100%", textAlignVertical: "center", }, }); ================================================ FILE: src/components/base/iconTextButton.tsx ================================================ import React from "react"; import { StyleProp, StyleSheet, ViewStyle } from "react-native"; import rpx from "@/utils/rpx"; import ThemeText from "./themeText"; import { iconSizeConst } from "@/constants/uiConst"; import useColors from "@/hooks/useColors"; import { TouchableOpacity } from "react-native-gesture-handler"; import Icon, { IIconName } from "@/components/base/icon.tsx"; interface IProps { icon: IIconName; onPress?: () => void; containerStyle?: StyleProp; children?: string; } export default function (props: IProps) { const { icon, children, onPress, containerStyle } = props; const colors = useColors(); return ( {children} ); } const style = StyleSheet.create({ container: { flexDirection: "row", alignItems: "center", paddingHorizontal: rpx(16), paddingVertical: rpx(8), }, text: { marginLeft: rpx(8), }, }); ================================================ FILE: src/components/base/image.tsx ================================================ import React from "react"; import { Image, ImageProps } from "react-native"; interface IImageProps extends ImageProps { uri?: string | null; emptySrc?: any; } export default function (props: Omit) { const { uri, emptySrc } = props; const source = typeof uri === "string" ? { uri, } : emptySrc; return ; } ================================================ FILE: src/components/base/imageBtn.tsx ================================================ import React from "react"; import { StyleProp, StyleSheet, TouchableOpacity, ViewStyle } from "react-native"; import rpx from "@/utils/rpx"; import Image from "./image"; import { ImgAsset } from "@/constants/assetsConst"; import ThemeText from "./themeText"; interface IImageBtnProps { uri?: string; title?: string; onPress?: () => void; style?: StyleProp; } export default function ImageBtn(props: IImageBtnProps) { const { onPress, uri, title, style: _style } = props ?? {}; return ( {title ?? ""} ); } const style = StyleSheet.create({ wrapper: { width: rpx(210), height: rpx(290), flexGrow: 0, flexShrink: 0, }, image: { width: rpx(210), height: rpx(210), borderRadius: rpx(12), marginBottom: rpx(16), }, }); ================================================ FILE: src/components/base/input.tsx ================================================ import useColors from "@/hooks/useColors"; import rpx from "@/utils/rpx"; import Color from "color"; import React from "react"; import { StyleSheet, TextInput, TextInputProps } from "react-native"; interface IInputProps extends TextInputProps { fontColor?: string; hasHorizontalPadding?: boolean; } export default function Input(props: IInputProps) { const { fontColor, hasHorizontalPadding = true } = props; const colors = useColors(); const currentColor = fontColor ?? colors.text; const defaultStyle = { color: currentColor, }; return ( ); } const styles = StyleSheet.create({ container: { paddingVertical: 0, paddingHorizontal: rpx(24), }, containerWithoutPadding: { padding: 0, }, }); ================================================ FILE: src/components/base/linkText.tsx ================================================ import React, { useState } from "react"; import { GestureResponderEvent, StyleSheet, TextProps } from "react-native"; import { fontSizeConst, fontWeightConst } from "@/constants/uiConst"; import openUrl from "@/utils/openUrl"; import ThemeText from "./themeText"; import Color from "color"; type ILinkTextProps = TextProps & { fontSize?: keyof typeof fontSizeConst; fontWeight?: keyof typeof fontWeightConst; linkTo?: string; onPress?: (event: GestureResponderEvent) => void; }; export default function LinkText(props: ILinkTextProps) { const [isPressed, setIsPressed] = useState(false); return ( { setIsPressed(true); }} onPress={evt => { if (props.onPress) { props.onPress(evt); } else { props?.linkTo && openUrl(props.linkTo); } }} onPressOut={() => { setIsPressed(false); }}> {props.children} ); } const style = StyleSheet.create({ linkText: { color: "#66ccff", textDecorationLine: "underline", }, pressed: { color: Color("#66ccff").alpha(0.4).toString(), }, }); ================================================ FILE: src/components/base/listEmpty.tsx ================================================ import { RequestStateCode } from "@/constants/commonConst"; import { fontSizeConst } from "@/constants/uiConst"; import useColors from "@/hooks/useColors"; import rpx from "@/utils/rpx"; import React from "react"; import { ActivityIndicator, StyleSheet, TouchableOpacity, View } from "react-native"; import ThemeText from "./themeText"; import { useI18N } from "@/core/i18n"; interface IEmptyProps { state: RequestStateCode onRetry?: () => void; } export default function ListEmpty(props: IEmptyProps) { const { state, onRetry } = props; const colors = useColors(); const { t } = useI18N(); if (state === RequestStateCode.FINISHED || state === RequestStateCode.PARTLY_DONE) { return {t("common.emptyList")} ; } else if (state === RequestStateCode.PENDING_FIRST_PAGE) { return {t("common.loading")} ; } else if (state === RequestStateCode.ERROR) { return {t("common.error")} {t("common.clickToRetry")} ; } } const style = StyleSheet.create({ wrapper: { width: "100%", flex: 1, minHeight: rpx(540), justifyContent: "center", alignItems: "center", gap: rpx(36), }, retryButton: { paddingVertical: rpx(24), paddingHorizontal: rpx(48), borderRadius: rpx(36), backgroundColor: "rgba(128, 128, 128, 0.2)", }, }); ================================================ FILE: src/components/base/listFooter.tsx ================================================ import React from "react"; import { ActivityIndicator, StyleSheet, Text, View } from "react-native"; import rpx from "@/utils/rpx"; import { fontSizeConst } from "@/constants/uiConst"; import ThemeText from "./themeText"; import useColors from "@/hooks/useColors"; import { RequestStateCode } from "@/constants/commonConst"; import { Pressable } from "react-native-gesture-handler"; import { useI18N } from "@/core/i18n"; interface IProps { state: RequestStateCode; onRetry?: () => void; } export default function ListFooter(props: IProps) { const { state } = props; const colors = useColors(); const { t } = useI18N(); if (state === RequestStateCode.ERROR) { return {t("common.failToLoad")}{" "}{t("common.clickToRetry")} ; } else if (state === RequestStateCode.PENDING_REST_PAGE || state === RequestStateCode.PARTLY_DONE) { return {t("common.loading")} ; } else if (state === RequestStateCode.FINISHED) { return {t("common.listReachEnd")} ; } // PENDING_FIRST_PAGE, IDLE return null; } const style = StyleSheet.create({ wrapper: { width: "100%", height: rpx(120), justifyContent: "center", alignItems: "center", flexDirection: "row", columnGap: rpx(24), }, underline: { textDecorationLine: "underline", textDecorationStyle: "solid", }, }); ================================================ FILE: src/components/base/listItem.tsx ================================================ import React, { ReactNode } from "react"; import { StyleProp, StyleSheet, TextProps, TextStyle, TouchableHighlight, TouchableOpacity, View, ViewStyle, } from "react-native"; import rpx from "@/utils/rpx"; import useColors, { CustomizedColors } from "@/hooks/useColors"; import ThemeText from "./themeText"; import { fontSizeConst, fontWeightConst, iconSizeConst, } from "@/constants/uiConst"; import FastImage from "./fastImage"; import { ImageStyle } from "react-native-fast-image"; import Icon, { IIconName } from "@/components/base/icon.tsx"; interface IListItemProps { // 是否有左右边距 withHorizontalPadding?: boolean; // 左边距 leftPadding?: number; // 右边距 rightPadding?: number; // height: style?: StyleProp; // 高度类型 heightType?: "big" | "small" | "smallest" | "normal" | "none"; children?: ReactNode; onPress?: () => void; onLongPress?: () => void; } const defaultPadding = rpx(24); const defaultActionWidth = rpx(80); const Size = { big: rpx(120), normal: rpx(108), small: rpx(96), smallest: rpx(72), none: undefined, }; function ListItem(props: IListItemProps) { const { withHorizontalPadding, leftPadding = defaultPadding, rightPadding = defaultPadding, style, heightType = "normal", children, onPress, onLongPress, } = props; const defaultStyle: StyleProp = { paddingLeft: withHorizontalPadding ? leftPadding : 0, paddingRight: withHorizontalPadding ? rightPadding : 0, height: Size[heightType], }; const colors = useColors(); return ( {children} ); } interface IListItemTextProps { children?: number | string; fontSize?: keyof typeof fontSizeConst; fontColor?: keyof CustomizedColors; fontWeight?: keyof typeof fontWeightConst; width?: number; position?: "left" | "right" | "none"; fixedWidth?: boolean; containerStyle?: StyleProp; contentStyle?: StyleProp; contentProps?: TextProps; } function ListItemText(props: IListItemTextProps) { const { children, fontSize, fontWeight, fontColor, position = "left", fixedWidth, width, containerStyle, contentStyle, contentProps = {}, } = props; const defaultStyle: StyleProp = { marginRight: position === "left" ? defaultPadding : 0, marginLeft: position === "right" ? defaultPadding : 0, width: fixedWidth ? width ?? defaultActionWidth : undefined, flexBasis: fixedWidth ? width ?? defaultActionWidth : undefined, }; return ( {children} ); } interface IListItemIconProps { icon: IIconName; iconSize?: number; width?: number; position?: "left" | "right" | "none"; fixedWidth?: boolean; containerStyle?: StyleProp; contentStyle?: StyleProp; onPress?: () => void; color?: string; } function ListItemIcon(props: IListItemIconProps) { const { icon, iconSize = iconSizeConst.normal, position = "left", fixedWidth, width, containerStyle, contentStyle, onPress, color, } = props; const colors = useColors(); const defaultStyle: StyleProp = { marginRight: position === "left" ? defaultPadding : 0, marginLeft: position === "right" ? defaultPadding : 0, width: fixedWidth ? width ?? defaultActionWidth : undefined, flexBasis: fixedWidth ? width ?? defaultActionWidth : undefined, }; const innerContent = ( ); return onPress ? ( {innerContent} ) : ( innerContent ); } interface IListItemImageProps { uri?: string; fallbackImg?: number; imageSize?: number; width?: number; position?: "left" | "right"; fixedWidth?: boolean; containerStyle?: StyleProp; contentStyle?: StyleProp; maskIcon?: IIconName | null; } function ListItemImage(props: IListItemImageProps) { const { uri, fallbackImg, position = "left", fixedWidth, width, containerStyle, contentStyle, maskIcon, } = props; const defaultStyle: StyleProp = { marginRight: position === "left" ? defaultPadding : 0, marginLeft: position === "right" ? defaultPadding : 0, width: fixedWidth ? width ?? defaultActionWidth : undefined, flexBasis: fixedWidth ? width ?? defaultActionWidth : undefined, }; return ( {maskIcon ? ( ) : null} ); } interface IContentProps { title?: ReactNode; children?: ReactNode; description?: ReactNode; containerStyle?: StyleProp; } function Content(props: IContentProps) { const { children, title = children, description = null, containerStyle, } = props; let realTitle; let realDescription; if (typeof title === "string" || typeof title === "number") { realTitle = {title}; } else { realTitle = title; } if (typeof description === "string" || typeof description === "number") { realDescription = ( {description} ); } else { realDescription = description; } return ( {realTitle} {realDescription} ); } export function ListItemHeader(props: { children?: ReactNode }) { const { children } = props; return ( {typeof children === "string" ? ( {children} ) : ( children )} ); } const styles = StyleSheet.create({ /** listitem */ container: { width: "100%", flexDirection: "row", alignItems: "center", }, /** left */ actionBase: { height: "100%", flexShrink: 0, flexGrow: 0, flexBasis: 0, flexDirection: "row", justifyContent: "center", alignItems: "center", }, leftImage: { width: rpx(80), height: rpx(80), borderRadius: rpx(16), }, imageMask: { position: "absolute", alignItems: "center", justifyContent: "center", backgroundColor: "#00000022", }, itemContentContainer: { flex: 1, height: "100%", justifyContent: "center", }, contentDesc: { marginTop: rpx(16), }, listItemHeader: { marginTop: rpx(20), }, }); ListItem.Size = Size; ListItem.ListItemIcon = ListItemIcon; ListItem.ListItemImage = ListItemImage; ListItem.ListItemText = ListItemText; ListItem.Content = Content; export default ListItem; ================================================ FILE: src/components/base/loading.tsx ================================================ import React from "react"; import { ActivityIndicator, StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import ThemeText from "./themeText"; import useColors from "@/hooks/useColors"; import { useI18N } from "@/core/i18n"; interface ILoadingProps { text?: string; showText?: boolean; height?: number; color?: string; } export default function Loading(props: ILoadingProps) { const { showText = true, height, text, color } = props; const colors = useColors(); const { t } = useI18N(); return ( {showText ? ( {text ?? t("common.loading")} ) : null} ); } const style = StyleSheet.create({ wrapper: { width: "100%", flex: 1, justifyContent: "center", alignItems: "center", }, text: { marginTop: rpx(48), }, }); ================================================ FILE: src/components/base/noPlugin.tsx ================================================ import React from "react"; import { StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import ThemeText from "@/components/base/themeText"; import { useI18N } from "@/core/i18n"; interface IProps { notSupportType?: string; } export default function NoPlugin(props: IProps) { const { t } = useI18N(); return ( {props.notSupportType ? t("noPlugin.titleWithType", { type: props.notSupportType, }) : t("noPlugin.title")} {t("noPlugin.description")} ); } const style = StyleSheet.create({ wrapper: { width: rpx(750), flex: 1, alignItems: "center", justifyContent: "center", }, mt: { marginTop: rpx(24), }, }); ================================================ FILE: src/components/base/pageBackground.tsx ================================================ import React, { memo } from "react"; import { StyleSheet, View } from "react-native"; import Image from "./image"; import useColors from "@/hooks/useColors"; import Theme from "@/core/theme"; function PageBackground() { const theme = Theme.useTheme(); const background = Theme.useBackground(); const colors = useColors(); return ( <> {!theme.id.startsWith("p-") && background?.url ? ( ) : null} ); } export default memo(PageBackground, () => true); const style = StyleSheet.create({ wrapper: { position: "absolute", top: 0, left: 0, right: 0, bottom: 0, width: "100%", height: "100%", }, }); ================================================ FILE: src/components/base/paragraph.tsx ================================================ import React from "react"; import { StyleSheet, TextProps } from "react-native"; import ThemeText from "./themeText"; import { fontSizeConst } from "@/constants/uiConst"; interface IParagraphProps extends TextProps {} export default function Paragraph(props: IParagraphProps) { return ; } const styles = StyleSheet.create({ container: { fontSize: fontSizeConst.content, lineHeight: fontSizeConst.content * 1.8, marginVertical: 2, letterSpacing: 0.25, }, }); ================================================ FILE: src/components/base/playAllBar.tsx ================================================ import React from "react"; import { Pressable, StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import { iconSizeConst } from "@/constants/uiConst"; import { ROUTE_PATH, useNavigate } from "@/core/router"; import ThemeText from "./themeText"; import useColors from "@/hooks/useColors"; import { showPanel } from "../panels/usePanel"; import IconButton from "./iconButton"; import TrackPlayer from "@/core/trackPlayer"; import Toast from "@/utils/toast"; import Icon from "@/components/base/icon.tsx"; import MusicSheet, { useSheetIsStarred } from "@/core/musicSheet"; import { MusicRepeatMode } from "@/constants/repeatModeConst"; import { useI18N } from "@/core/i18n"; interface IProps { musicList: IMusic.IMusicItem[] | null; canStar?: boolean; musicSheet?: IMusic.IMusicSheetItem | null; } export default function (props: IProps) { const { musicList, canStar, musicSheet } = props; const sheetName = musicSheet?.title; const sheetId = musicSheet?.id; const colors = useColors(); const navigate = useNavigate(); const { t } = useI18N(); const starred = useSheetIsStarred(musicSheet); return ( { if (musicList) { let defaultPlayMusic = musicList[0]; if ( TrackPlayer.repeatMode === MusicRepeatMode.SHUFFLE ) { defaultPlayMusic = musicList[ Math.floor(Math.random() * musicList.length) ]; } TrackPlayer.playWithReplacePlayList( defaultPlayMusic, musicList, ); } }}> {t("playAllBar.title")} {canStar && musicSheet ? ( { if (!starred) { MusicSheet.starMusicSheet(musicSheet); Toast.success(t("toast.hasStarred")); } else { MusicSheet.unstarMusicSheet(musicSheet); Toast.success(t("toast.hasUnstarred")); } }} /> ) : null} { showPanel("AddToMusicSheet", { musicItem: musicList ?? [], newSheetDefaultName: sheetName, }); }} /> { navigate(ROUTE_PATH.MUSIC_LIST_EDITOR, { musicList: musicList, musicSheet: { title: sheetName, id: sheetId, }, }); }} /> ); } const style = StyleSheet.create({ /** playall */ topWrapper: { height: rpx(84), paddingHorizontal: rpx(24), flexDirection: "row", alignItems: "center", }, playAll: { flex: 1, flexDirection: "row", alignItems: "center", }, playAllIcon: { marginRight: rpx(12), }, optionButton: { marginLeft: rpx(36), }, }); ================================================ FILE: src/components/base/portal.tsx ================================================ import React, { ReactNode, useEffect, useRef } from "react"; import { StyleSheet, View } from "react-native"; import { atom, useAtomValue, useSetAtom } from "jotai"; interface IPortalNode { key: string | null; children: ReactNode; } const portalsAtom = atom([]); interface IPortalProps { children: ReactNode; } export default function Portal(props: IPortalProps) { const { children } = props; const keyRef = useRef(null); const setPortalsAtoms = useSetAtom(portalsAtom); useEffect(() => { if (!keyRef.current) { // mount keyRef.current = Math.random().toString().slice(2); // console.log("MOUNT!", keyRef.current); setPortalsAtoms(portals => [ ...portals, { key: keyRef.current, children }, ]); } else { // update // console.log("UPDATE!", keyRef.current); setPortalsAtoms(portals => portals.map(it => it.key === keyRef.current ? { ...it, children } : it, ), ); } }, [children]); useEffect(() => { return () => { if (keyRef.current) { // console.log("UNMOUNT!", keyRef.current); setPortalsAtoms(portals => portals.filter(it => it.key !== keyRef.current), ); } }; }, []); return null; } const styles = StyleSheet.create({ portalContainer: { zIndex: 20000, }, }); const composedStyle = [StyleSheet.absoluteFill, styles.portalContainer]; export function PortalHost() { const portals = useAtomValue(portalsAtom); return ( <> {portals.map(({ key, children }) => ( {children} ))} ); } ================================================ FILE: src/components/base/statusBar.tsx ================================================ import React from "react"; import { StatusBar, StatusBarProps, View } from "react-native"; import useColors from "@/hooks/useColors"; interface IStatusBarProps extends StatusBarProps {} export default function (props: IStatusBarProps) { const colors = useColors(); const { backgroundColor, barStyle } = props; return ( <> ); } ================================================ FILE: src/components/base/switch.tsx ================================================ import React, { useEffect } from "react"; import { StyleSheet, SwitchProps, TouchableWithoutFeedback, View, } from "react-native"; import useColors from "@/hooks/useColors"; import rpx from "@/utils/rpx"; import Animated, { useAnimatedStyle, useSharedValue, withTiming, } from "react-native-reanimated"; import { timingConfig } from "@/constants/commonConst"; interface ISwitchProps extends SwitchProps {} const fixedWidth = rpx(40); export default function ThemeSwitch(props: ISwitchProps) { const { value, onValueChange } = props; const colors = useColors(); const sharedValue = useSharedValue(value ? 1 : 0); useEffect(() => { sharedValue.value = value ? 1 : 0; }, [value]); const thumbStyle = useAnimatedStyle(() => { return { transform: [ { translateX: withTiming( sharedValue.value * fixedWidth, timingConfig.animationNormal, ), }, ], }; }); return ( { onValueChange?.(!value); }}> ); } const styles = StyleSheet.create({ container: { width: rpx(80), height: rpx(40), borderRadius: rpx(40), justifyContent: "center", }, thumb: { width: rpx(34), height: rpx(34), borderRadius: rpx(17), backgroundColor: "white", left: rpx(3), }, }); ================================================ FILE: src/components/base/tag.tsx ================================================ import React from "react"; import { StyleProp, StyleSheet, TextStyle, View, ViewStyle } from "react-native"; import rpx from "@/utils/rpx"; import ThemeText from "./themeText"; import useColors from "@/hooks/useColors"; interface ITagProps { tagName: string; containerStyle?: StyleProp; style?: StyleProp; } export default function Tag(props: ITagProps) { const colors = useColors(); return ( {props.tagName} ); } const styles = StyleSheet.create({ tag: { height: rpx(32), marginLeft: rpx(12), paddingHorizontal: rpx(12), borderRadius: rpx(24), justifyContent: "center", alignItems: "center", flexShrink: 0, borderWidth: 1, borderStyle: "solid", }, tagText: { textAlignVertical: "center", }, }); ================================================ FILE: src/components/base/textButton.tsx ================================================ import React from "react"; import { Pressable } from "react-native"; import ThemeText from "./themeText"; import rpx from "@/utils/rpx"; import { CustomizedColors } from "@/hooks/useColors"; interface IButtonProps { withHorizontalPadding?: boolean; style?: any; hitSlop?: number; children: string; fontColor?: keyof CustomizedColors; onPress?: () => void; } export default function (props: IButtonProps) { const { children, onPress, fontColor, hitSlop, withHorizontalPadding } = props; return ( {children} ); } ================================================ FILE: src/components/base/themeText.tsx ================================================ import React from "react"; import { Text, TextProps } from "react-native"; import { fontSizeConst, fontWeightConst } from "@/constants/uiConst"; import useColors, { CustomizedColors } from "@/hooks/useColors"; type IThemeTextProps = TextProps & { color?: string; fontColor?: keyof CustomizedColors; fontSize?: keyof typeof fontSizeConst; fontWeight?: keyof typeof fontWeightConst; opacity?: number; }; export default function ThemeText(props: IThemeTextProps) { const colors = useColors(); const { style, color, children, fontSize = "content", fontColor = "text", fontWeight = "regular", opacity, } = props; const themeStyle = { color: color ?? colors[fontColor], fontSize: fontSizeConst[fontSize], fontWeight: fontWeightConst[fontWeight], includeFontPadding: false, opacity, }; const _style = Array.isArray(style) ? [themeStyle, ...style] : [themeStyle, style]; return ( {children} ); } ================================================ FILE: src/components/base/tip.tsx ================================================ import React, { ReactNode, useCallback, useEffect, useRef, useState } from "react"; import { View, StyleSheet, LayoutRectangle, Text } from "react-native"; import { Gesture, GestureDetector } from "react-native-gesture-handler"; import Animated, { useSharedValue, useAnimatedStyle, withTiming, runOnJS, } from "react-native-reanimated"; import Portal from "./portal"; import rpx from "@/utils/rpx"; import useColors from "@/hooks/useColors"; import { timingConfig } from "@/constants/commonConst"; type TipPosition = "top" | "bottom" | "left" | "right"; interface ITipProps { children: ReactNode; content: string; position?: TipPosition; autoHideDuration?: number; // 自动消失时间,单位毫秒,0表示不自动消失 backgroundColor?: string; textColor?: string; triangleSize?: number; } interface ITipPortalProps { content: string; position: TipPosition; childRect: LayoutRectangle; backgroundColor: string; textColor: string; triangleSize: number; visible: boolean; onHide: () => void; autoHideDuration: number; } // 计算tip的位置和三角形位置 const calculateTipPosition = ( childRect: LayoutRectangle, tipWidth: number, tipHeight: number, position: TipPosition, triangleSize: number ) => { const margin = rpx(12); let tipLeft = 0; let tipTop = 0; let triangleLeft = 0; let triangleTop = 0; let triangleRotation = 0; switch (position) { case "top": tipLeft = childRect.x + childRect.width / 2 - tipWidth / 2; tipTop = childRect.y - tipHeight - margin - triangleSize; triangleLeft = tipWidth / 2 - triangleSize / 2; triangleTop = tipHeight; triangleRotation = 180; // 指向下方 break; case "bottom": tipLeft = childRect.x + childRect.width / 2 - tipWidth / 2; tipTop = childRect.y + childRect.height + margin + triangleSize; triangleLeft = tipWidth / 2 - triangleSize / 2; triangleTop = -triangleSize; triangleRotation = 0; // 指向上方 break; case "left": tipLeft = childRect.x - tipWidth - margin - triangleSize; tipTop = childRect.y + childRect.height / 2 - tipHeight / 2; triangleLeft = tipWidth; triangleTop = tipHeight / 2 - triangleSize / 2; triangleRotation = 90; // 指向右方 break; case "right": tipLeft = childRect.x + childRect.width + margin + triangleSize; tipTop = childRect.y + childRect.height / 2 - tipHeight / 2; triangleLeft = -triangleSize; triangleTop = tipHeight / 2 - triangleSize / 2; triangleRotation = -90; // 指向左方 break; } return { tipLeft, tipTop, triangleLeft, triangleTop, triangleRotation, }; }; // 三角形组件 const Triangle = ({ size, color, style }: { size: number; color: string; style?: any }) => ( ); // Tip内容Portal组件 const TipPortal = ({ content, position, childRect, backgroundColor, textColor, triangleSize, visible, onHide, autoHideDuration, }: ITipPortalProps) => { const opacity = useSharedValue(0); const scale = useSharedValue(0.8); const [tipDimensions, setTipDimensions] = useState({ width: 0, height: 0 }); const [shouldRender, setShouldRender] = useState(visible); useEffect(() => { if (visible) { setShouldRender(true); // 显示动画 opacity.value = withTiming(1, timingConfig.animationNormal); scale.value = withTiming(1, timingConfig.animationNormal); // 自动隐藏 if (autoHideDuration > 0) { const hideTimer = setTimeout(() => { // 开始隐藏动画 opacity.value = withTiming(0, timingConfig.animationNormal, (finished) => { if (finished) { runOnJS(onHide)(); } }); scale.value = withTiming(0.8, timingConfig.animationNormal); }, autoHideDuration); return () => clearTimeout(hideTimer); } } else { // 隐藏动画 opacity.value = withTiming(0, timingConfig.animationNormal, (finished) => { if (finished) { runOnJS(setShouldRender)(false); } }); scale.value = withTiming(0.8, timingConfig.animationNormal); } }, [visible, autoHideDuration, onHide, opacity, scale]); const animatedStyle = useAnimatedStyle(() => { return { opacity: opacity.value, transform: [{ scale: scale.value }], }; }); const handleLayout = useCallback((event: any) => { const { width, height } = event.nativeEvent.layout; setTipDimensions({ width, height }); }, []); // 如果不需要渲染,直接返回null if (!shouldRender) { return null; } if (tipDimensions.width === 0 || tipDimensions.height === 0) { // 测量阶段,先渲染不可见的tip来获取尺寸 return ( {content} ); } const { tipLeft, tipTop, triangleLeft, triangleTop, triangleRotation } = calculateTipPosition( childRect, tipDimensions.width, tipDimensions.height, position, triangleSize ); return ( {content} ); }; export default function Tip({ children, content, position = "top", autoHideDuration = 3000, backgroundColor, textColor, triangleSize = rpx(12), }: ITipProps) { const colors = useColors(); const [visible, setVisible] = useState(false); const [childRect, setChildRect] = useState(null); const childRef = useRef(null); const finalBackgroundColor = backgroundColor || colors.notification; const finalTextColor = textColor || colors.text; const handlePress = useCallback(() => { if (!childRef.current) return; childRef.current.measure((x, y, width, height, pageX, pageY) => { setChildRect({ x: pageX, y: pageY, width, height, }); setVisible(true); }); }, []); const handleHide = useCallback(() => { setVisible(false); }, []); const tap = Gesture.Tap().onStart(() => { runOnJS(handlePress)(); }); return ( <> {children} {visible && childRect && ( )} ); } const styles = StyleSheet.create({ tipContainer: { position: "absolute", backgroundColor: "rgba(0, 0, 0, 0.8)", paddingHorizontal: rpx(16), paddingVertical: rpx(8), borderRadius: rpx(8), maxWidth: rpx(300), zIndex: 9999, }, measurementContainer: { opacity: 0, position: "absolute", top: -1000, }, tipText: { fontSize: rpx(24), lineHeight: rpx(32), textAlign: "center", }, triangle: { position: "absolute", }, }); ================================================ FILE: src/components/base/toast.tsx ================================================ import { timingConfig } from "@/constants/commonConst"; import { fontSizeConst } from "@/constants/uiConst"; import useColors from "@/hooks/useColors"; import rpx from "@/utils/rpx"; import { GlobalState } from "@/utils/stateMapper"; import { nanoid } from "nanoid"; import React, { useCallback, useEffect } from "react"; import { Pressable, StyleSheet, Text, View } from "react-native"; import { Directions, Gesture, GestureDetector, } from "react-native-gesture-handler"; import Animated, { cancelAnimation, runOnJS, useAnimatedStyle, useSharedValue, withDelay, withTiming, } from "react-native-reanimated"; import Icon from "@/components/base/icon.tsx"; export interface IToastConfig { /** 类型 */ type: "success" | "warn"; /** 消息内容 */ message?: string; /** 行动点 */ actionText?: string; /** 行动点按钮行为 */ onActionClick?: () => void; /** 展示时间 */ duration?: number; } type IToastConfigInner = IToastConfig & { id: string; }; const toastQueue: IToastConfigInner[] = []; const fixedTop = rpx(250); const activeToastStore = new GlobalState(null); const typeConfig = { success: { name: "check-circle", color: "#457236", }, warn: { name: "exclamation-circle", color: "#de7622", }, } as const; export function ToastBaseComponent() { const activeToast = activeToastStore.useValue(); const colors = useColors(); const toastAnim = useSharedValue(0); const setNextToast = useCallback(() => { activeToastStore.setValue(toastQueue.shift() || null); }, []); useEffect(() => { if (activeToast) { toastAnim.value = withTiming(1, timingConfig.animationSlow, () => { toastAnim.value = withDelay( activeToast.duration || 1200, withTiming(0, timingConfig.animationSlow, finished => { if (finished) { runOnJS(setNextToast)(); } }), ); }); } }, [activeToast]); function removeCurrentToast() { if (toastAnim.value === 1) { cancelAnimation(toastAnim); toastAnim.value = withTiming( 0, timingConfig.animationSlow, finished => { if (finished) { runOnJS(setNextToast)(); } }, ); } } const flingGesture = Gesture.Fling() .direction(Directions.UP) .onEnd(() => { removeCurrentToast(); }) .runOnJS(true); const toastAnimStyle = useAnimatedStyle(() => { return { transform: [ { translateY: (toastAnim.value - 1) * fixedTop, }, ], opacity: toastAnim.value, }; }); return activeToast ? ( {activeToast.message} {activeToast.actionText && activeToast.onActionClick ? ( {activeToast.actionText} ) : null} ) : null; } const styles = StyleSheet.create({ container: { position: "absolute", top: rpx(128), width: "100%", alignItems: "center", height: rpx(100), zIndex: 20000, }, contentContainer: { width: rpx(688), height: "100%", borderRadius: rpx(12), backgroundColor: "blue", flexDirection: "row", alignItems: "center", paddingHorizontal: rpx(24), shadowOffset: { width: 0, height: 2, }, shadowOpacity: 0.2, shadowRadius: 1.41, elevation: 2, }, text: { fontSize: fontSizeConst.content, includeFontPadding: false, flex: 1, marginLeft: rpx(24), }, actionText: { fontSize: fontSizeConst.content, includeFontPadding: false, color: "white", }, actionTextContainer: { marginLeft: rpx(24), width: rpx(120), paddingHorizontal: rpx(12), flexDirection: "row", alignItems: "center", justifyContent: "center", borderRadius: rpx(30), height: rpx(58), }, }); export function showToast(config: IToastConfig) { const id = nanoid(); const _config = { ...config, id, }; const activeToast = activeToastStore.getValue(); if (!activeToast) { activeToastStore.setValue(_config); } else { toastQueue.push(_config); } return id; } ================================================ FILE: src/components/base/typeTag.tsx ================================================ import React from "react"; import { ColorValue, StyleProp, StyleSheet, TouchableOpacity, View, ViewStyle, } from "react-native"; import rpx from "@/utils/rpx"; import ThemeText from "@/components/base/themeText"; import useColors from "@/hooks/useColors"; interface ITypeTagProps { title: string; selected?: boolean; onPress?: () => void; backgroundColor?: ColorValue; style?: StyleProp; } export default function TypeTag(props: ITypeTagProps) { const { title, onPress, selected = false, // backgroundColor, style: _style, } = props; const colors = useColors(); return ( {title} ); } const style = StyleSheet.create({ wrapper: { flexGrow: 0, paddingHorizontal: rpx(18), paddingVertical: rpx(12), borderRadius: rpx(36), marginHorizontal: rpx(16), borderWidth: 1, borderStyle: "solid", }, }); ================================================ FILE: src/components/base/verticalSafeAreaView.tsx ================================================ import React from "react"; import { StyleProp, ViewStyle } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; interface IVerticalSafeAreaViewProps { mode?: "margin" | "padding"; children: JSX.Element | JSX.Element[]; style?: StyleProp; } export default function VerticalSafeAreaView( props: IVerticalSafeAreaViewProps, ) { const { children, style, mode } = props; return ( {children} ); } ================================================ FILE: src/components/debug/index.tsx ================================================ import React from "react"; import { StyleSheet, View } from "react-native"; import VDebug from "@/lib/react-native-vdebug"; import { useAppConfig } from "@/core/appConfig"; export default function Debug() { const showDebug = useAppConfig("debug.devLog"); return showDebug ? ( ) : null; } const style = StyleSheet.create({ wrapper: { position: "absolute", top: 0, left: 0, right: 0, bottom: 0, width: "100%", height: "100%", zIndex: 999, }, }); ================================================ FILE: src/components/dialogs/components/base/index.tsx ================================================ import React, { ReactNode, useEffect, useMemo, useRef } from "react"; import { BackHandler, NativeEventSubscription, StyleProp, StyleSheet, TouchableOpacity, TouchableWithoutFeedback, View, ViewStyle, } from "react-native"; import rpx, { vh, vw } from "@/utils/rpx"; import Animated, { useAnimatedStyle, useSharedValue, withTiming, } from "react-native-reanimated"; import { timingConfig } from "@/constants/commonConst"; import useColors from "@/hooks/useColors"; import ThemeText from "@/components/base/themeText"; import Divider from "@/components/base/divider"; import { fontSizeConst } from "@/constants/uiConst"; import { ScrollView } from "react-native-gesture-handler"; import useOrientation from "@/hooks/useOrientation.ts"; interface IDialogProps { onDismiss?: () => void; children?: ReactNode; } function Dialog(props: IDialogProps) { const { children, onDismiss } = props; const sharedShowValue = useSharedValue(0); const colors = useColors(); const backHandlerRef = useRef(); const orientation = useOrientation(); // 对话框宽度 const dialogContainerStyle: ViewStyle = orientation === "vertical" ? { width: vw(100) - rpx(72), } : { width: "80%", }; useEffect(() => { sharedShowValue.value = 1; if (backHandlerRef.current) { backHandlerRef.current?.remove(); backHandlerRef.current = undefined; } backHandlerRef.current = BackHandler.addEventListener( "hardwareBackPress", () => { onDismiss?.(); return true; }, ); return () => { sharedShowValue.value = 0; if (backHandlerRef.current) { backHandlerRef.current?.remove(); backHandlerRef.current = undefined; } }; }, []); const containerStyle = useAnimatedStyle(() => { return { opacity: withTiming( sharedShowValue.value, timingConfig.animationFast, ), }; }); const scaleAnimationStyle = useAnimatedStyle(() => { return { transform: [ { scale: withTiming( 0.9 + sharedShowValue.value * 0.1, timingConfig.animationFast, ), }, ], }; }); return ( {children} ); } interface IDialogTitleProps { children?: ReactNode; withDivider?: boolean; stringContent?: boolean; containerStyle?: StyleProp; } function Title(props: IDialogTitleProps) { const { children, withDivider, stringContent, containerStyle } = props; return ( <> {typeof children === "string" || stringContent ? ( {children} ) : ( children )} {withDivider ? : null} ); } interface IDialogContentProps { children?: ReactNode; style?: StyleProp; needScroll?: boolean; } function Content(props: IDialogContentProps) { const { children, style, needScroll } = props; const content = typeof children === "string" ? ( {children} ) : ( children ); return ( {needScroll ? {content} : content} ); } interface IDialogActionsProps { children?: ReactNode; actions?: Array<{ title: string; type?: "normal" | "primary"; show?: boolean; onPress?: () => void; }>; style?: StyleProp; } function Actions(props: IDialogActionsProps) { const { children, style, actions } = props; const validActions = useMemo( () => actions?.filter(it => it.show !== false), [actions], ); const _children = validActions?.length ? ( <> {validActions.map((it, index) => it.show === false ? null : ( ), )} ) : ( children ); return ( {typeof children === "string" ? ( {children} ) : ( _children )} ); } function BottomButton(props: { type?: "normal" | "primary"; text: string; style?: StyleProp; onPress?: () => void; }) { const { type = "normal", text, style, onPress } = props; const colors = useColors(); return ( {text} ); } const styles = StyleSheet.create({ bottomBtn: { borderRadius: rpx(8), flex: 1, flexShrink: 0, justifyContent: "center", alignItems: "center", height: rpx(72), }, backContainer: { position: "absolute", zIndex: 16299, width: "100%", height: "100%", left: 0, top: 0, alignItems: "center", justifyContent: "center", }, container: { zIndex: 16300, position: "absolute", width: "100%", height: "100%", left: 0, top: 0, backgroundColor: "rgba(0, 0, 0, 0.5)", }, dialogContainer: { position: "absolute", width: "80%", zIndex: 16310, borderRadius: rpx(16), backgroundColor: "red", shadowOffset: { width: 0, height: 2, }, shadowOpacity: 0.5, shadowRadius: 4, elevation: 5, }, defaultFontStyle: { lineHeight: fontSizeConst.content * 1.5, }, /**** title */ titleContainer: { height: rpx(88), width: "100%", alignItems: "center", justifyContent: "center", flexDirection: "row", paddingHorizontal: rpx(24), }, /** content */ contentContainer: { width: "100%", paddingHorizontal: rpx(24), paddingVertical: rpx(36), }, /** actions */ actionsContainer: { width: "100%", height: rpx(88), flexDirection: "row", alignItems: "center", justifyContent: "flex-end", paddingHorizontal: rpx(24), marginBottom: rpx(12), flexWrap: "nowrap", }, actionButton: { marginLeft: rpx(24), }, }); Dialog.Title = Title; Dialog.Content = Content; Dialog.Actions = Actions; export default Dialog; ================================================ FILE: src/components/dialogs/components/checkStorage.tsx ================================================ import React, { useState } from "react"; import ThemeText from "@/components/base/themeText"; import { StyleSheet, View } from "react-native"; import rpx, { vh } from "@/utils/rpx"; import { ScrollView, TouchableOpacity } from "react-native-gesture-handler"; import { hideDialog } from "../useDialog"; import Checkbox from "@/components/base/checkbox"; import Dialog from "./base"; import PersistStatus from "@/utils/persistStatus"; import NativeUtils from "@/native/utils"; import { useI18N } from "@/core/i18n"; export default function CheckStorage() { const [skipState, setSkipState] = useState(false); const { t } = useI18N(); const onCancel = () => { if (skipState) { PersistStatus.set("app.skipBootstrapStorageDialog", true); } hideDialog(); }; return ( {t("dialog.checkStorage.title")} {t("dialog.checkStorage.content.0")} {t("dialog.checkStorage.content.1")} {t("dialog.checkStorage.content.2")} {t("dialog.checkStorage.content.3")} { setSkipState(state => !state); }}> {t("dialog.checkStorage.button.doNotShowAgain")} { NativeUtils.requestStoragePermission(); hideDialog(); }, }, ]} /> ); } const styles = StyleSheet.create({ item: { marginBottom: rpx(20), lineHeight: rpx(36), }, scrollView: { maxHeight: vh(40), paddingHorizontal: rpx(26), }, checkBox: { marginHorizontal: rpx(24), marginVertical: rpx(36), }, checkboxGroup: { flexDirection: "row", alignItems: "center", }, checkboxHint: { marginLeft: rpx(12), }, }); ================================================ FILE: src/components/dialogs/components/downloadDialog.tsx ================================================ import React, { useState } from "react"; import ThemeText from "@/components/base/themeText"; import { StyleSheet, View } from "react-native"; import rpx, { vh } from "@/utils/rpx"; import openUrl from "@/utils/openUrl"; import Clipboard from "@react-native-clipboard/clipboard"; import { ScrollView, TouchableOpacity } from "react-native-gesture-handler"; import { hideDialog } from "../useDialog"; import Checkbox from "@/components/base/checkbox"; import Button from "@/components/base/textButton.tsx"; import Dialog from "./base"; import PersistStatus from "@/utils/persistStatus"; import { useI18N } from "@/core/i18n"; interface IDownloadDialogProps { version: string; content: string[]; fromUrl: string; backUrl?: string; } export default function DownloadDialog(props: IDownloadDialogProps) { const { content, fromUrl, backUrl, version } = props; const [skipState, setSkipState] = useState(false); const { t } = useI18N(); return ( { if (skipState) { PersistStatus.set("app.skipVersion", version); } hideDialog(); }}> {t("dialog.downloadDialog.title", { version: version, })} {content?.map?.(_ => ( {_} ))} { setSkipState(state => !state); }}> {t("dialog.downloadDialog.skipThisVersion")} {backUrl && ( )} ); } const style = StyleSheet.create({ item: { marginBottom: rpx(20), lineHeight: rpx(36), }, content: { flex: 1, maxHeight: vh(50), }, scrollView: { maxHeight: vh(40), paddingHorizontal: rpx(26), }, dialogActions: { marginTop: rpx(24), height: rpx(120), marginBottom: rpx(12), flexDirection: "column", alignItems: "flex-start", justifyContent: "space-between", }, checkboxGroup: { flexDirection: "row", alignItems: "center", }, buttonGroup: { flexDirection: "row", alignItems: "center", width: "100%", justifyContent: "flex-end", }, checkboxHint: { marginLeft: rpx(12), }, button: { paddingLeft: rpx(28), paddingVertical: rpx(14), marginLeft: rpx(16), alignItems: "flex-end", }, }); ================================================ FILE: src/components/dialogs/components/editSheetDetail.tsx ================================================ import React, { useState } from "react"; import useColors from "@/hooks/useColors"; import rpx from "@/utils/rpx"; import { StyleSheet, TouchableOpacity, View } from "react-native"; import ThemeText from "@/components/base/themeText"; import { ImgAsset } from "@/constants/assetsConst"; import { launchImageLibrary } from "react-native-image-picker"; import pathConst from "@/constants/pathConst"; import Image from "@/components/base/image"; import { addFileScheme, addRandomHash } from "@/utils/fileUtils"; import Toast from "@/utils/toast"; import { hideDialog } from "../useDialog"; import Dialog from "./base"; import Input from "@/components/base/input"; import { fontSizeConst } from "@/constants/uiConst"; import { copyAsync, deleteAsync, getInfoAsync } from "expo-file-system"; import MusicSheet from "@/core/musicSheet"; import { useI18N } from "@/core/i18n"; interface IEditSheetDetailProps { musicSheet: IMusic.IMusicSheetItem; } export default function EditSheetDetailDialog(props: IEditSheetDetailProps) { const { musicSheet } = props; const colors = useColors(); const [coverImg, setCoverImg] = useState(musicSheet?.coverImg); const [title, setTitle] = useState(musicSheet?.title); const { t } = useI18N(); // onCover const onChangeCoverPress = async () => { try { const result = await launchImageLibrary({ mediaType: "photo", }); const uri = result.assets?.[0].uri; if (!uri) { return; } console.log(uri); setCoverImg(uri); } catch (e) { console.log(e); } }; function onTitleChange(_: string) { setTitle(_); } async function onConfirm() { // 判断是否相同 if (coverImg === musicSheet?.coverImg && title === musicSheet?.title) { hideDialog(); return; } let newCoverImg = coverImg; if (coverImg && coverImg !== musicSheet?.coverImg) { newCoverImg = addFileScheme( `${pathConst.dataPath}sheet${musicSheet.id}${coverImg.substring( coverImg.lastIndexOf("."), )}`, ); try { if ((await getInfoAsync(newCoverImg)).exists) { await deleteAsync(newCoverImg, { idempotent: true, // 报错时不抛异常 }); } await copyAsync({ from: coverImg, to: newCoverImg, }); } catch (e) { console.log(e); } } let _title = title; if (!_title?.length) { _title = musicSheet.title; } // 更新歌单信息 MusicSheet.updateMusicSheetBase(musicSheet.id, { coverImg: newCoverImg ? addRandomHash(newCoverImg) : undefined, title: _title, }).then(() => { Toast.success("更新歌单信息成功~"); }); hideDialog(); } return ( {t("common.cover")} { setCoverImg(undefined); }}> {t("dialog.editSheetDetail.sheetName")} ); } const style = StyleSheet.create({ row: { marginTop: rpx(28), height: rpx(120), flexDirection: "row", justifyContent: "space-between", alignItems: "center", paddingBottom: rpx(12), }, coverImg: { width: rpx(100), height: rpx(100), borderRadius: rpx(28), }, }); ================================================ FILE: src/components/dialogs/components/index.ts ================================================ import CheckStorage from "@/components/dialogs/components/checkStorage.tsx"; import DownloadDialog from "./downloadDialog"; import EditSheetDetailDialog from "./editSheetDetail"; import LoadingDialog from "./loadingDialog"; import MarkdownDialog from "./markdownDialog"; import RadioDialog from "./radioDialog"; import SimpleDialog from "./simpleDialog"; import SubscribePluginDialog from "./subscribePluginDialog"; import SetScheduleCloseTimeDialog from "./setScheduleCloseTimeDialog"; const dialogs = { SimpleDialog, RadioDialog, DownloadDialog, SubscribePluginDialog, LoadingDialog, EditSheetDetailDialog, CheckStorage, MarkdownDialog, SetScheduleCloseTimeDialog, }; export default dialogs; export type IDialogType = typeof dialogs; export type IDialogKey = keyof IDialogType; ================================================ FILE: src/components/dialogs/components/loadingDialog.tsx ================================================ import React, { useEffect } from "react"; import Loading from "@/components/base/loading"; import rpx from "@/utils/rpx"; import { StyleSheet } from "react-native"; import { hideDialog } from "../useDialog"; import Dialog from "./base"; import { useI18N } from "@/core/i18n"; interface ILoadingDialogProps { promise?: Promise; task?: () => Promise; title: string; loadingText?: string; onResolve?: (data: T, hideDialog: () => void) => void; onReject?: (reason: any, hideDialog: () => void) => void; onCancel?: (hideDialog: () => void) => void; } export default function LoadingDialog(props: ILoadingDialogProps) { const { title, loadingText, onResolve, onReject, promise, task, onCancel } = props; const { t } = useI18N(); useEffect(() => { const _promise = promise || task?.(); _promise ?.then(data => { onResolve?.(data, hideDialog); }) .catch(e => { onReject?.(e, hideDialog); }); }, []); return ( {title} ); } const style = StyleSheet.create({ content: { height: rpx(280), }, cancelBtn: { marginRight: rpx(12), marginBottom: rpx(4), }, }); ================================================ FILE: src/components/dialogs/components/markdownDialog.tsx ================================================ import React, { useEffect, useRef, useState } from "react"; import { hideDialog } from "../useDialog"; import Dialog from "./base"; import i18n, { useI18N } from "@/core/i18n"; import { WebView } from "react-native-webview"; import rpx, { vh } from "@/utils/rpx"; import { StyleSheet } from "react-native"; import { Marked } from "marked"; import Loading from "@/components/base/loading"; import { useOnMounted } from "@/hooks/useMounted"; import useColors from "@/hooks/useColors"; import { sanitizeHtml } from "@/utils/htmlUtil"; import Toast from "@/utils/toast"; import openUrl from "@/utils/openUrl"; interface IMarkdownDialogProps { title: string; markdownContent: string; okText?: string; } export default function MarkdownDialog(props: IMarkdownDialogProps) { const { title, markdownContent, okText } = props; const markedRef = useRef(new Marked()); const [loading, setLoading] = useState(true); const [htmlContent, setHtmlContent] = useState(""); const { onMounted } = useOnMounted(); const { t } = useI18N(); const colors = useColors(); useEffect(() => { const md = markedRef.current; md.parse(markdownContent, { async: true, }).then(html => { if (onMounted()) { setHtmlContent(` ${title} ${sanitizeHtml(html)} `); setLoading(false); } }).catch(() => { if (onMounted()) { setHtmlContent(markdownContent); setLoading(false); } }); }, [markdownContent, onMounted, colors]); const actions = [ { title: okText ?? t("dialog.errorLogKnow"), type: "primary", onPress() { hideDialog(); }, }, ] as any; return ( {title} {loading ? : { if (event.url.startsWith("http") || event.url.startsWith("https")) { Toast.warn(i18n.t("dialog.markdownDialog.openExternalLink"), { type: "warn", duration: 3000, actionText: i18n.t("common.open"), onActionClick() { openUrl(event.url); }, }); } return false; }} />} ); } const styles = StyleSheet.create({ webView: { flex: 1, width: "100%", height: "100%", backgroundColor: "transparent", }, dialogContent: { paddingVertical: 0, paddingHorizontal: 0, paddingBottom: rpx(8), }, }); ================================================ FILE: src/components/dialogs/components/radioDialog.tsx ================================================ import React, { useEffect, useMemo, useRef } from "react"; import { FlatList } from "react-native-gesture-handler"; import { hideDialog } from "../useDialog"; import Dialog from "./base"; import ListItem from "@/components/base/listItem"; import useOrientation from "@/hooks/useOrientation"; import rpx, { vmax, vmin } from "@/utils/rpx"; import Icon, { IIconName } from "@/components/base/icon.tsx"; import useColors from "@/hooks/useColors.ts"; import ThemeText from "@/components/base/themeText"; import Tip from "@/components/base/tip"; import { iconSizeConst } from "@/constants/uiConst"; interface IKV { label: string; value: T; icon?: IIconName; } interface IRadioDialogProps { title: string; tip?: string; content: Array>; defaultSelected?: T; onOk?: (value: T) => void; } function isObject(v: string | number | IKV): v is IKV { return !(typeof v === "string" || typeof v === "number"); } export default function RadioDialog(props: IRadioDialogProps) { const { title, content, onOk, defaultSelected, tip } = props; const orientation = useOrientation(); const colors = useColors(); const ref = useRef(null); const defaultSelectedIndex = useMemo(() => { return content.findIndex(item => { if (isObject(item)) { return item.value === defaultSelected; } return item === defaultSelected; }); }, [content, defaultSelected]); useEffect(() => { if (ref.current && (defaultSelectedIndex - 3) >= 0) { ref.current.scrollToIndex({ index: defaultSelectedIndex - 3, animated: false, }); } }, []); return ( <> {title} {tip ? : null} ({ length: ListItem.Size.normal, offset: ListItem.Size.normal * index, index, })} renderItem={({ item }) => { const isConfig = isObject(item); return ( { if (isConfig) { onOk?.(item.value); } else { onOk?.(item); } hideDialog(); }} heightType="small"> {isConfig && item.icon ? ( ) : null} {defaultSelected !== undefined && defaultSelected === (isConfig ? item.value : item) ? ( ) : null} ); }} /> ); } ================================================ FILE: src/components/dialogs/components/setScheduleCloseTimeDialog.tsx ================================================ import React, { useState } from "react"; import rpx from "@/utils/rpx"; import { StyleSheet, View } from "react-native"; import ThemeText from "@/components/base/themeText"; import { hideDialog } from "../useDialog"; import Dialog from "./base"; import Input from "@/components/base/input"; import useColors from "@/hooks/useColors"; import { useI18N } from "@/core/i18n"; import PersistStatus from "@/utils/persistStatus"; interface ISetScheduleCloseTimeDialogProps { onOk?: (minutes: number) => void; } export default function SetScheduleCloseTimeDialog( props: ISetScheduleCloseTimeDialogProps, ) { const { onOk } = props; const [timeInput, setTimeInput] = useState(""); const colors = useColors(); const { t } = useI18N(); // Get last custom time as placeholder const lastCustomTime = PersistStatus.get("app.scheduleCloseTime"); const placeholder = lastCustomTime ? String(lastCustomTime) : ""; const handleConfirm = () => { let minutes = 0; if (timeInput.trim()) { minutes = parseInt(timeInput.trim(), 10); } else if (placeholder) { minutes = parseInt(placeholder, 10); } // Validate input if (isNaN(minutes) || minutes <= 0 || minutes > 1440) { return; } // Save to persistent storage PersistStatus.set("app.scheduleCloseTime", minutes); onOk?.(minutes); hideDialog(); }; const inputStyles = { backgroundColor: colors.card, borderColor: colors.divider, color: colors.text, }; const containerStyles = { backgroundColor: colors.backdrop, }; return ( {t("dialog.setScheduleCloseTime.title")} { // Only allow numbers const numericText = text.replace(/[^0-9]/g, ""); // Limit to 4 digits (max 1440 minutes = 24 hours) if (numericText.length <= 4) { setTimeInput(numericText); } }} placeholder={placeholder || t("dialog.setScheduleCloseTime.placeholder")} placeholderTextColor={colors.textSecondary} keyboardType="numeric" maxLength={4} /> {t("dialog.setScheduleCloseTime.unit")} {t("dialog.setScheduleCloseTime.hint")} ); } const style = StyleSheet.create({ dialogContent: { paddingHorizontal: rpx(24), paddingVertical: rpx(20), borderRadius: rpx(12), }, inputSection: { marginBottom: rpx(8), }, inputRow: { flexDirection: "row", alignItems: "center", marginBottom: rpx(16), }, inputContainer: { flex: 1, borderWidth: rpx(2), borderRadius: rpx(8), paddingHorizontal: rpx(16), paddingVertical: rpx(4), minHeight: rpx(72), justifyContent: "center", shadowOffset: { width: 0, height: rpx(2), }, shadowOpacity: 0.1, shadowRadius: rpx(4), elevation: 2, }, textInput: { fontSize: rpx(28), includeFontPadding: false, paddingVertical: rpx(12), borderWidth: 0, backgroundColor: "transparent", textAlign: "center", }, unitContainer: { marginLeft: rpx(16), paddingHorizontal: rpx(8), }, unitText: { fontSize: rpx(28), fontWeight: "500", }, hintContainer: { paddingHorizontal: rpx(4), }, hintText: { lineHeight: rpx(32), textAlign: "center", }, }); ================================================ FILE: src/components/dialogs/components/simpleDialog.tsx ================================================ import React from "react"; import { hideDialog } from "../useDialog"; import Dialog from "./base"; import { useI18N } from "@/core/i18n"; interface ISimpleDialogProps { title: string; content: string | JSX.Element; okText?: string; cancelText?: string; onOk?: () => void; } export default function SimpleDialog(props: ISimpleDialogProps) { const { title, content, onOk, okText, cancelText } = props; const { t } = useI18N(); const actions = onOk ? [ { title: cancelText ?? t("common.cancel"), type: "normal", onPress: hideDialog, }, { title: okText ?? t("common.confirm"), type: "primary", onPress() { onOk?.(); hideDialog(); }, }, ] : ([ { title: okText ?? t("dialog.errorLogKnow"), type: "primary", onPress() { hideDialog(); }, }, ] as any); return ( {title} {content} ); } ================================================ FILE: src/components/dialogs/components/subscribePluginDialog.tsx ================================================ import React, { useState } from "react"; import rpx from "@/utils/rpx"; import { StyleSheet, View } from "react-native"; import ThemeText from "@/components/base/themeText"; import { hideDialog } from "../useDialog"; import Dialog from "./base"; import Input from "@/components/base/input"; import useColors from "@/hooks/useColors"; import { useI18N } from "@/core/i18n"; interface ISubscribeItem { name: string; url: string; } interface ISubscribePluginDialogProps { subscribeItem?: ISubscribeItem; onSubmit: ( subscribeItem: ISubscribeItem, hideDialog: () => void, editingIndex?: number, ) => void; editingIndex?: number; onDelete?: (editingIndex: number, hideDialog: () => void) => void; } export default function SubscribePluginDialog( props: ISubscribePluginDialogProps, ) { const { subscribeItem, onSubmit, editingIndex, onDelete } = props; const [name, setName] = useState(subscribeItem?.name ?? ""); const [url, setUrl] = useState(subscribeItem?.url ?? ""); const colors = useColors(); const { t } = useI18N(); const inputStyles = { backgroundColor: colors.card, borderColor: colors.divider, color: colors.text, }; const containerStyles = { backgroundColor: colors.backdrop, }; return ( {t("dialog.subscriptionPluginDialog.title")} {t("common.name")} { setName(text); }} placeholder={t("common.name")} placeholderTextColor={colors.textSecondary} /> URL { setUrl(text); }} /> ); } const style = StyleSheet.create({ dialogContent: { paddingHorizontal: rpx(24), paddingVertical: rpx(16), borderRadius: rpx(12), }, inputSection: { marginBottom: rpx(24), }, labelContainer: { marginBottom: rpx(8), }, label: { fontSize: rpx(28), fontWeight: "500", opacity: 0.9, }, inputContainer: { borderWidth: rpx(2), borderRadius: rpx(8), paddingHorizontal: rpx(16), paddingVertical: rpx(4), minHeight: rpx(72), justifyContent: "center", shadowOffset: { width: 0, height: rpx(2), }, shadowOpacity: 0.1, shadowRadius: rpx(4), elevation: 2, }, textInput: { fontSize: rpx(28), includeFontPadding: false, paddingVertical: rpx(12), borderWidth: 0, backgroundColor: "transparent", }, headerWrapper: { flexDirection: "row", alignItems: "center", height: rpx(92), }, }); ================================================ FILE: src/components/dialogs/index.tsx ================================================ import React from "react"; import components from "./components"; import { dialogInfoStore } from "./useDialog"; export default function () { const dialogInfoState = dialogInfoStore.useValue(); const Component = dialogInfoState.name ? components[dialogInfoState.name] : null; return ( Component ? ( ) : null ); } ================================================ FILE: src/components/dialogs/useDialog.ts ================================================ import { GlobalState } from "@/utils/stateMapper"; import { useCallback } from "react"; import { IDialogKey, IDialogType } from "./components"; interface IDialogInfo { name: IDialogKey | null; payload: any; } export const dialogInfoStore = new GlobalState({ name: null, payload: null, }); export function showDialog( name: T, payload?: Parameters[0], ) { dialogInfoStore.setValue({ name, payload, }); } export function hideDialog() { dialogInfoStore.setValue({ name: null, payload: null, }); } export default function useDialog() { const showDialog = useCallback( ( name: T, payload?: Parameters[0], ) => { dialogInfoStore.setValue({ name, payload, }); }, [], ); const hideDialog = useCallback(() => { dialogInfoStore.setValue({ name: null, payload: null, }); }, []); return { showDialog, hideDialog }; } export function getCurrentDialog() { return dialogInfoStore.getValue(); } ================================================ FILE: src/components/errorBoundary/index.tsx ================================================ import React, { Component, ReactNode, useEffect, useState } from "react"; import { View, Text, StyleSheet, ScrollView, Image, Platform } from "react-native"; import DeviceInfo from "react-native-device-info"; import useColors from "@/hooks/useColors"; import rpx from "@/utils/rpx"; import LinkText from "@/components/base/linkText"; import { ImgAsset } from "@/constants/assetsConst"; import ThemeText from "@/components/base/themeText"; interface DeviceInfoProps { colors: any; } function DeviceInfoSection({ colors }: DeviceInfoProps) { const [deviceInfo, setDeviceInfo] = useState({ appVersion: "获取中...", buildNumber: "获取中...", systemName: Platform.OS, systemVersion: "获取中...", deviceModel: "获取中...", deviceBrand: "获取中...", }); useEffect(() => { const getDeviceInfo = async () => { try { const [ appVersion, buildNumber, systemVersion, deviceModel, brand, ] = await Promise.all([ DeviceInfo.getVersion(), DeviceInfo.getBuildNumber(), DeviceInfo.getSystemVersion(), DeviceInfo.getModel(), DeviceInfo.getBrand(), ]); setDeviceInfo({ appVersion, buildNumber, systemName: Platform.OS, systemVersion, deviceModel, deviceBrand: brand, }); } catch (error) { console.warn("获取设备信息失败:", error); } }; getDeviceInfo(); }, []); const systemDisplayName = Platform.OS === "ios" ? "iOS" : "Android"; return ( 📱 设备信息 应用版本: {deviceInfo.appVersion} ({deviceInfo.buildNumber}) 系统版本: {systemDisplayName} {deviceInfo.systemVersion} 设备型号: {deviceInfo.deviceBrand} {deviceInfo.deviceModel} ); } interface ErrorBoundaryProps { children: ReactNode; } interface ErrorBoundaryState { hasError: boolean; error: Error | null; errorInfo: any; } class ErrorBoundary extends Component { constructor(props: ErrorBoundaryProps) { super(props); this.state = { hasError: false, error: null, errorInfo: null, }; } static getDerivedStateFromError(error: Error): Partial { return { hasError: true, error, }; } componentDidCatch(error: Error, errorInfo: any) { this.setState({ error, errorInfo, }); // 这里可以添加错误日志上报 console.error("ErrorBoundary caught an error:", error, errorInfo); } render() { if (this.state.hasError) { return ; } return this.props.children; } } interface ErrorFallbackProps { error: Error | null; errorInfo: any; } function ErrorFallback({ error, errorInfo }: ErrorFallbackProps) { const colors = useColors(); return ( {/* 错误标题 */} 🙈 哎呀,程序崩了... {/* 设备信息 */} {/* 错误详情 */} 🐛 错误详情 {error?.message || "未知错误"} {error?.stack && ( {error.stack} )} {/* 组件堆栈信息 */} {errorInfo?.componentStack && ( 📍 组件堆栈 {errorInfo.componentStack} )} {/* 反馈建议 */} 💌 请帮忙反馈一下这个问题吧 {/* GitHub Issue */} 📝 GitHub Issues (推荐): https://github.com/maotoumao/MusicFree/issues 点击链接或复制粘贴到浏览器打开 {/* 微信公众号 */} 💬 微信公众号【一只猫头猫】: 扫描二维码关注公众号反馈 ); } const styles = StyleSheet.create({ container: { flex: 1, }, scrollView: { flex: 1, }, scrollContent: { padding: rpx(32), paddingBottom: rpx(60), }, header: { alignItems: "center", marginBottom: rpx(48), paddingTop: rpx(40), }, title: { textAlign: "center", marginBottom: rpx(16), }, subtitle: { textAlign: "center", lineHeight: rpx(40), }, deviceInfoBox: { borderRadius: rpx(16), borderWidth: rpx(2), padding: rpx(24), marginBottom: rpx(24), }, deviceInfoTitle: { marginBottom: rpx(16), }, deviceInfoList: { gap: rpx(12), }, deviceInfoRow: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", }, deviceInfoLabel: { fontSize: rpx(28), flex: 1, }, deviceInfoValue: { fontSize: rpx(28), flex: 2, textAlign: "right", fontWeight: "500", }, errorBox: { borderRadius: rpx(16), borderWidth: rpx(2), padding: rpx(24), marginBottom: rpx(24), }, errorTitle: { marginBottom: rpx(16), }, errorText: { lineHeight: rpx(36), marginBottom: rpx(16), }, stackContainer: { maxHeight: rpx(300), borderRadius: rpx(8), backgroundColor: "rgba(0, 0, 0, 0.05)", padding: rpx(16), }, stackText: { fontSize: rpx(24), fontFamily: "monospace", lineHeight: rpx(32), }, feedbackSection: { marginBottom: rpx(48), }, feedbackTitle: { marginBottom: rpx(24), textAlign: "center", }, feedbackOptions: { gap: rpx(24), }, feedbackItem: { borderRadius: rpx(16), borderWidth: rpx(2), padding: rpx(24), }, feedbackLabel: { marginBottom: rpx(16), }, feedbackHint: { marginTop: rpx(12), fontStyle: "italic", }, link: { lineHeight: rpx(36), }, qrCodeContainer: { alignItems: "center", gap: rpx(16), }, qrCode: { width: rpx(300), height: rpx(300), borderRadius: rpx(12), }, qrCodeHint: { textAlign: "center", }, bottomTip: { alignItems: "center", paddingVertical: rpx(24), }, tipText: { textAlign: "center", fontStyle: "italic", }, }); export default ErrorBoundary; ================================================ FILE: src/components/mediaItem/LyricItem.tsx ================================================ import React from "react"; import ListItem from "@/components/base/listItem"; import { ImgAsset } from "@/constants/assetsConst"; import TitleAndTag from "./titleAndTag"; interface IAlbumResultsProps { lyricItem: ILyric.ILyricItem; onPress?: (musicItem: ILyric.ILyricItem) => void; } export default function LyricItem(props: IAlbumResultsProps) { const { lyricItem, onPress } = props; return ( { onPress?.(lyricItem); }}> } /> ); } ================================================ FILE: src/components/mediaItem/albumItem.tsx ================================================ import React from "react"; import { ROUTE_PATH, useNavigate } from "@/core/router"; import ListItem from "@/components/base/listItem"; import { ImgAsset } from "@/constants/assetsConst"; import TitleAndTag from "./titleAndTag"; interface IAlbumResultsProps { albumItem: IAlbum.IAlbumItem; } export default function AlbumItem(props: IAlbumResultsProps) { const { albumItem } = props; const navigate = useNavigate(); return ( { navigate(ROUTE_PATH.ALBUM_DETAIL, { albumItem, }); }}> } description={`${albumItem.artist ?? ""} ${ albumItem.date ?? "" }`} /> // { // navigate(ROUTE_PATH.ALBUM_DETAIL, { // albumItem, // }); // }} // /> ); } ================================================ FILE: src/components/mediaItem/musicItem.tsx ================================================ import React from "react"; import { StyleProp, StyleSheet, View, ViewStyle } from "react-native"; import rpx from "@/utils/rpx"; import ListItem from "../base/listItem"; import LocalMusicSheet from "@/core/localMusicSheet"; import { showPanel } from "../panels/usePanel"; import TitleAndTag from "./titleAndTag"; import ThemeText from "../base/themeText"; import TrackPlayer from "@/core/trackPlayer"; import Icon from "@/components/base/icon.tsx"; interface IMusicItemProps { index?: string | number; showMoreIcon?: boolean; musicItem: IMusic.IMusicItem; musicSheet?: IMusic.IMusicSheetItem; onItemPress?: (musicItem: IMusic.IMusicItem) => void; onItemLongPress?: () => void; itemPaddingRight?: number; left?: () => JSX.Element; containerStyle?: StyleProp; highlight?: boolean } export default function MusicItem(props: IMusicItemProps) { const { musicItem, index, onItemPress, onItemLongPress, musicSheet, itemPaddingRight, showMoreIcon = true, left: Left, containerStyle, highlight = false, } = props; return ( { if (onItemPress) { onItemPress(musicItem); } else { TrackPlayer.play(musicItem); } }}> {Left ? : null} {index !== undefined ? ( {index} ) : null} } description={ {LocalMusicSheet.isLocalMusic(musicItem) && ( )} {musicItem.artist} {musicItem.album ? ` - ${musicItem.album}` : ""} } /> {showMoreIcon ? ( { showPanel("MusicItemOptions", { musicItem, musicSheet, }); }} /> ) : null} ); } const styles = StyleSheet.create({ icon: { marginRight: rpx(6), }, descContainer: { flexDirection: "row", marginTop: rpx(16), }, indexText: { fontStyle: "italic", textAlign: "center", padding: rpx(2), }, }); ================================================ FILE: src/components/mediaItem/sheetItem.tsx ================================================ import React from "react"; import { StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import { ROUTE_PATH, useNavigate } from "@/core/router"; import ImageBtn from "../base/imageBtn"; interface ISheetItemProps { pluginHash: string; sheetInfo: IMusic.IMusicSheetItemBase; } const marginBottom = rpx(16); export default function SheetItem(props: ISheetItemProps) { const { sheetInfo, pluginHash } = props ?? {}; const navigate = useNavigate(); return ( { navigate(ROUTE_PATH.PLUGIN_SHEET_DETAIL, { pluginHash, sheetInfo, }); }} /> ); } const style = StyleSheet.create({ imageWrapper: { width: "100%", justifyContent: "center", alignItems: "center", }, }); ================================================ FILE: src/components/mediaItem/titleAndTag.tsx ================================================ import React from "react"; import { StyleSheet, View } from "react-native"; import ThemeText from "../base/themeText"; import Tag from "../base/tag"; import { CustomizedColors } from "@/hooks/useColors"; interface ITitleAndTagProps { title: string; titleFontColor?: keyof CustomizedColors tag?: string; } export default function TitleAndTag(props: ITitleAndTagProps) { const { title, tag, titleFontColor } = props; return ( {title} {tag ? : null} ); } const styles = StyleSheet.create({ container: { flexDirection: "row", alignItems: "center", justifyContent: "space-between", }, title: { flex: 1, }, }); ================================================ FILE: src/components/mediaItem/topListItem.tsx ================================================ import React from "react"; // import {ROUTE_PATH, useNavigate} from '@/entry/router'; import ListItem from "@/components/base/listItem"; import { ImgAsset } from "@/constants/assetsConst"; import { ROUTE_PATH, useNavigate } from "@/core/router"; interface ITopListResultsProps { pluginHash: string; topListItem: IMusic.IMusicSheetItemBase; } export default function TopListItem(props: ITopListResultsProps) { const { pluginHash, topListItem } = props; const navigate = useNavigate(); return ( { navigate(ROUTE_PATH.TOP_LIST_DETAIL, { pluginHash: pluginHash, topList: topListItem, }); }}> ); } ================================================ FILE: src/components/musicBar/index.tsx ================================================ import React, { memo, useEffect, useState } from "react"; import { Keyboard, StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import { CircularProgressBase } from "react-native-circular-progress-indicator"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { showPanel } from "../panels/usePanel"; import useColors from "@/hooks/useColors"; import IconButton from "../base/iconButton"; import TrackPlayer, { useCurrentMusic, useMusicState, useProgress } from "@/core/trackPlayer"; import { musicIsPaused } from "@/utils/trackUtils"; import MusicInfo from "./musicInfo"; import Icon from "@/components/base/icon.tsx"; function CircularPlayBtn() { const progress = useProgress(); const musicState = useMusicState(); const colors = useColors(); const isPaused = musicIsPaused(musicState); return ( { if (isPaused) { await TrackPlayer.play(); } else { await TrackPlayer.pause(); } }} /> ); } function MusicBar() { const musicItem = useCurrentMusic(); const [showKeyboard, setKeyboardStatus] = useState(false); const colors = useColors(); const safeAreaInsets = useSafeAreaInsets(); useEffect(() => { const showSubscription = Keyboard.addListener("keyboardDidShow", () => { setKeyboardStatus(true); }); const hideSubscription = Keyboard.addListener("keyboardDidHide", () => { setKeyboardStatus(false); }); return () => { showSubscription.remove(); hideSubscription.remove(); }; }, []); return ( <> {musicItem && !showKeyboard && ( { // navigate(ROUTE_PATH.MUSIC_DETAIL); // }} > { showPanel("PlayList"); }} color={colors.musicBarText} style={[style.actionIcon]} /> )} ); } export default memo(MusicBar, () => true); const style = StyleSheet.create({ wrapper: { width: "100%", height: rpx(132), flexDirection: "row", alignItems: "center", paddingRight: rpx(24), }, actionGroup: { width: rpx(200), justifyContent: "flex-end", flexDirection: "row", alignItems: "center", }, actionIcon: { marginLeft: rpx(36), }, }); ================================================ FILE: src/components/musicBar/musicInfo.tsx ================================================ import React, { memo, useLayoutEffect, useMemo } from "react"; import { StyleSheet, Text, View } from "react-native"; import rpx from "@/utils/rpx"; import FastImage from "../base/fastImage"; import { ImgAsset } from "@/constants/assetsConst"; import Color from "color"; import ThemeText from "../base/themeText"; import useColors from "@/hooks/useColors"; import { ROUTE_PATH, useNavigate } from "@/core/router"; import { Gesture, GestureDetector } from "react-native-gesture-handler"; import TrackPlayer, { usePlayList } from "@/core/trackPlayer"; import Animated, { SharedValue, runOnJS, useAnimatedStyle, useSharedValue, withTiming, } from "react-native-reanimated"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { timingConfig } from "@/constants/commonConst"; interface IBarMusicItemProps { musicItem: IMusic.IMusicItem | null; activeIndex: number; // 当前展示的是0/1/2 transformSharedValue: SharedValue; } function _BarMusicItem(props: IBarMusicItemProps) { const { musicItem, activeIndex, transformSharedValue } = props; const colors = useColors(); const safeAreaInsets = useSafeAreaInsets(); const animatedStyles = useAnimatedStyle(() => { return { left: `${(transformSharedValue.value + activeIndex) * 100}%`, }; }, [activeIndex]); if (!musicItem) { return null; } return ( {musicItem?.title} {musicItem?.artist && ( {" "} -{musicItem.artist} )} ); } const BarMusicItem = memo( _BarMusicItem, (prev, curr) => prev.musicItem === curr.musicItem && prev.activeIndex === curr.activeIndex, ); const styles = StyleSheet.create({ container: { flexDirection: "row", width: "100%", alignItems: "center", position: "absolute", }, textWrapper: { flexGrow: 1, flexShrink: 1, }, artworkImg: { width: rpx(96), height: rpx(96), borderRadius: rpx(48), marginRight: rpx(24), }, }); interface IMusicInfoProps { musicItem: IMusic.IMusicItem | null; paddingLeft?: number; } function skipMusicItem(direction: number) { if (direction === -1) { TrackPlayer.skipToNext(); } else if (direction === 1) { TrackPlayer.skipToPrevious(); } } export default function MusicInfo(props: IMusicInfoProps) { const { musicItem } = props; const navigate = useNavigate(); const playLists = usePlayList(); const siblingMusicItems = useMemo(() => { if (!musicItem) { return { prev: null, next: null, }; } return { prev: TrackPlayer.previousMusic, next: TrackPlayer.nextMusic, }; }, [musicItem, playLists]); // +- 1 const transformSharedValue = useSharedValue(0); const musicItemWidthValue = useSharedValue(0); const tapGesture = Gesture.Tap() .onStart(() => { navigate(ROUTE_PATH.MUSIC_DETAIL); }) .runOnJS(true); useLayoutEffect(() => { transformSharedValue.value = 0; }, [musicItem]); const panGesture = Gesture.Pan() .minPointers(1) .maxPointers(1) .onUpdate(e => { if (musicItemWidthValue.value) { transformSharedValue.value = e.translationX / musicItemWidthValue.value; } }) .onEnd((e, success) => { if (!success) { // 还原到原始位置 transformSharedValue.value = withTiming( 0, timingConfig.animationFast, ); } else { // fling const deltaX = e.translationX; const vX = e.velocityX; let skip = 0; if (musicItemWidthValue.value) { const rate = deltaX / musicItemWidthValue.value; if (Math.abs(rate) > 0.3) { // 先判断距离 skip = vX > 0 ? 1 : -1; transformSharedValue.value = withTiming( skip, timingConfig.animationFast, () => { runOnJS(skipMusicItem)(skip); }, ); } else if (Math.abs(vX) > 1500) { // 再判断速度 skip = vX > 0 ? 1 : -1; transformSharedValue.value = skip; runOnJS(skipMusicItem)(skip); } else { transformSharedValue.value = withTiming( 0, timingConfig.animationFast, ); } } else { transformSharedValue.value = 0; } } }); const gesture = Gesture.Race(panGesture, tapGesture); return ( { musicItemWidthValue.value = e.nativeEvent.layout.width; }}> ); } const musicInfoStyles = StyleSheet.create({ infoContainer: { flex: 1, height: "100%", alignItems: "center", flexDirection: "row", overflow: "hidden", }, }); ================================================ FILE: src/components/musicList/index.tsx ================================================ import { RequestStateCode } from "@/constants/commonConst"; import TrackPlayer from "@/core/trackPlayer"; import rpx from "@/utils/rpx"; import { FlashList } from "@shopify/flash-list"; import React, { useRef, useCallback, useState, useEffect } from "react"; import { FlatListProps, Pressable, StyleSheet, View } from "react-native"; import ListEmpty from "../base/listEmpty"; import ListFooter from "../base/listFooter"; import MusicItem from "../mediaItem/musicItem"; import { isSameMediaItem } from "@/utils/mediaUtils"; import Icon from "../base/icon"; import { iconSizeConst } from "@/constants/uiConst"; import useColors from "@/hooks/useColors"; interface IMusicListProps { /** 顶部 */ Header?: FlatListProps["ListHeaderComponent"]; /** 音乐列表 */ musicList?: IMusic.IMusicItem[]; /** 所在歌单 */ musicSheet?: IMusic.IMusicSheetItem; /** 是否展示序号 */ showIndex?: boolean; /** 点击 */ onItemPress?: ( musicItem: IMusic.IMusicItem, musicList?: IMusic.IMusicItem[], ) => void; // 状态 state: RequestStateCode; /** 高亮的音乐 */ highlightMusicItem?: IMusic.IMusicItem | null; onRetry?: () => void; onLoadMore?: () => void; } const ITEM_HEIGHT = rpx(120); /** 音乐列表 */ export default function MusicList(props: IMusicListProps) { const { Header, musicList, musicSheet, showIndex, onItemPress, state, onRetry, onLoadMore, highlightMusicItem, } = props; const colors = useColors(); const flashListRef = useRef>(null); const [showBadge, setShowBadge] = useState(false); const hideTimeoutRef = useRef(); // 查找高亮项的索引 const highlightIndex = React.useMemo(() => { if (!highlightMusicItem || !musicList) return -1; return musicList.findIndex(item => isSameMediaItem(item, highlightMusicItem)); }, [highlightMusicItem, musicList]); // 处理滚动开始 const handleScrollBegin = useCallback(() => { if (highlightIndex !== -1) { if (hideTimeoutRef.current) { clearTimeout(hideTimeoutRef.current); } setShowBadge(true); } }, [highlightIndex]); // 处理滚动结束 const handleScrollEnd = useCallback(() => { if (hideTimeoutRef.current) { clearTimeout(hideTimeoutRef.current); } // 5秒后直接隐藏 hideTimeoutRef.current = setTimeout(() => { setShowBadge(false); }, 5000); }, []); // 滚动到高亮项 const scrollToHighlight = useCallback(() => { if (highlightIndex !== -1 && flashListRef.current) { flashListRef.current.scrollToIndex({ index: highlightIndex, animated: false, viewPosition: 0, }); // 立即隐藏角标 setShowBadge(false); if (hideTimeoutRef.current) { clearTimeout(hideTimeoutRef.current); } } }, [highlightIndex]); // 清理定时器 useEffect(() => { return () => { if (hideTimeoutRef.current) { clearTimeout(hideTimeoutRef.current); } }; }, []); return ( } ListFooterComponent={ musicList?.length ? : null } extraData={highlightMusicItem} data={musicList ?? []} estimatedItemSize={ITEM_HEIGHT} onScrollBeginDrag={handleScrollBegin} onScrollEndDrag={handleScrollEnd} onMomentumScrollEnd={handleScrollEnd} renderItem={({ index, item: musicItem }) => { return ( { if (onItemPress) { onItemPress(musicItem, musicList); } else { TrackPlayer.playWithReplacePlayList( musicItem, musicList ?? [musicItem], ); } }} musicSheet={musicSheet} highlight={isSameMediaItem(musicItem, highlightMusicItem)} /> ); }} onEndReached={() => { if (state === RequestStateCode.IDLE || state === RequestStateCode.PARTLY_DONE) { onLoadMore?.(); } }} onEndReachedThreshold={0.1} /> {showBadge && ( )} ); } const styles = StyleSheet.create({ container: { flex: 1, }, badge: { position: "absolute", bottom: rpx(80), right: rpx(84), zIndex: 1000, }, badgeButton: { width: rpx(64), height: rpx(64), borderRadius: rpx(32), justifyContent: "center", alignItems: "center", shadowColor: "#000", shadowOffset: { width: 0, height: 2, }, shadowOpacity: 0.25, shadowRadius: 3.84, elevation: 5, }, }); ================================================ FILE: src/components/musicSheetPage/components/header.tsx ================================================ import React, { useState } from "react"; import { Pressable, StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import ThemeText from "@/components/base/themeText"; import { ImgAsset } from "@/constants/assetsConst"; import FastImage from "@/components/base/fastImage"; import PlayAllBar from "@/components/base/playAllBar"; import useColors from "@/hooks/useColors"; interface IHeaderProps { musicSheet: IMusic.IMusicSheetItem | null; musicList: IMusic.IMusicItem[] | null; canStar?: boolean; } export default function Header(props: IHeaderProps) { const { musicSheet, musicList, canStar } = props; const colors = useColors(); const [maxLines, setMaxLines] = useState(6); const toggleShowMore = () => { if (maxLines) { setMaxLines(undefined); } else { setMaxLines(6); } }; return ( {musicSheet?.title} 共 {musicSheet?.worksNum ?? (musicList ? musicList.length ?? 0 : "-")} 首{" "} {musicSheet?.description ? ( { // console.log(evt.nativeEvent.layout); // }} > {musicSheet.description} ) : null} ); } const style = StyleSheet.create({ wrapper: { width: "100%", padding: rpx(24), justifyContent: "center", alignItems: "flex-start", }, content: { flex: 1, flexDirection: "row", justifyContent: "flex-start", alignItems: "center", }, coverImg: { width: rpx(210), height: rpx(210), borderRadius: rpx(24), }, details: { flex: 1, height: rpx(140), paddingHorizontal: rpx(36), justifyContent: "space-between", }, divider: { marginVertical: rpx(18), }, albumDesc: { width: "100%", marginTop: rpx(28), }, }); ================================================ FILE: src/components/musicSheetPage/components/navBar.tsx ================================================ import React from "react"; import { ROUTE_PATH, useNavigate } from "@/core/router"; import AppBar from "@/components/base/appBar"; interface INavBarProps { navTitle: string; musicList: IMusic.IMusicItem[] | null; } export default function (props: INavBarProps) { const navigate = useNavigate(); const { navTitle, musicList = [] } = props; return ( {navTitle} ); } ================================================ FILE: src/components/musicSheetPage/components/sheetMusicList.tsx ================================================ import React from "react"; import { View } from "react-native"; import Loading from "@/components/base/loading"; import Header from "./header"; import MusicList from "@/components/musicList"; import Config from "@/core/appConfig"; import globalStyle from "@/constants/globalStyle"; import HorizontalSafeAreaView from "@/components/base/horizontalSafeAreaView.tsx"; import TrackPlayer from "@/core/trackPlayer"; import { RequestStateCode } from "@/constants/commonConst"; interface IMusicListProps { sheetInfo: IMusic.IMusicSheetItem | null; musicList?: IMusic.IMusicItem[] | null; // 是否可收藏 canStar?: boolean; // 状态 state: RequestStateCode; onRetry?: () => void; onLoadMore?: () => void; } export default function SheetMusicList(props: IMusicListProps) { const { sheetInfo, musicList, canStar, state, onRetry, onLoadMore } = props; return ( {!musicList ? ( ) : ( } onLoadMore={onLoadMore} onRetry={onRetry} state={state} musicList={musicList} onItemPress={(musicItem, currentMusicList) => { if ( Config.getConfig( "basic.clickMusicInAlbum", ) === "playMusic" ) { TrackPlayer.play(musicItem); } else { TrackPlayer.playWithReplacePlayList( musicItem, currentMusicList ?? [musicItem], ); } }} /> )} ); } ================================================ FILE: src/components/musicSheetPage/index.tsx ================================================ import React from "react"; import NavBar from "./components/navBar"; import MusicBar from "@/components/musicBar"; import SheetMusicList from "./components/sheetMusicList"; import StatusBar from "@/components/base/statusBar"; import globalStyle from "@/constants/globalStyle"; import VerticalSafeAreaView from "../base/verticalSafeAreaView"; import { RequestStateCode } from "@/constants/commonConst"; interface IMusicSheetPageProps { navTitle: string; sheetInfo: ICommon.WithMusicList | null; musicList?: IMusic.IMusicItem[] | null; // 是否可收藏 canStar?: boolean; // 状态 state: RequestStateCode; onRetry?: () => void; onLoadMore?: () => void; } export default function MusicSheetPage(props: IMusicSheetPageProps) { const { navTitle, sheetInfo, musicList, canStar, onLoadMore, onRetry, state } = props; return ( ); } ================================================ FILE: src/components/panels/base/panelBase.tsx ================================================ import useColors from "@/hooks/useColors"; import useOrientation from "@/hooks/useOrientation"; import rpx, { vh } from "@/utils/rpx"; import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { BackHandler, DeviceEventEmitter, KeyboardAvoidingView, NativeEventSubscription, Pressable, StyleSheet, } from "react-native"; import Animated, { Easing, EasingFunction, runOnJS, useAnimatedReaction, useAnimatedStyle, useSharedValue, withTiming, } from "react-native-reanimated"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { panelInfoStore } from "../usePanel"; import NativeUtils from "@/native/utils"; const ANIMATION_EASING: EasingFunction = Easing.out(Easing.exp); const ANIMATION_DURATION = 250; const timingConfig = { duration: ANIMATION_DURATION, easing: ANIMATION_EASING, }; interface IPanelBaseProps { keyboardAvoidBehavior?: "height" | "padding" | "position" | "none"; height?: number; // 定位方式 positionMethod?: "top" | "bottom"; renderBody: (loading: boolean) => JSX.Element; } export default function (props: IPanelBaseProps) { const { height = vh(60), renderBody, keyboardAvoidBehavior, positionMethod = "bottom", } = props; const snapPoint = useSharedValue(0); const colors = useColors(); const [loading, setLoading] = useState(true); // 是否处于弹出状态 const timerRef = useRef(); const safeAreaInsets = useSafeAreaInsets(); const orientation = useOrientation(); const useAnimatedBase = useMemo( () => (orientation === "horizontal" ? rpx(750) : height), [orientation], ); const backHandlerRef = useRef(); const hideCallbackRef = useRef([]); useEffect(() => { snapPoint.value = withTiming(1, timingConfig); timerRef.current = setTimeout(() => { if (loading) { // 兜底 setLoading(false); } }, 400); if (backHandlerRef.current) { backHandlerRef.current.remove(); backHandlerRef.current = undefined; } backHandlerRef.current = BackHandler.addEventListener( "hardwareBackPress", () => { snapPoint.value = withTiming(0, timingConfig); return true; }, ); const listenerSubscription = DeviceEventEmitter.addListener( "hidePanel", (callback?: () => void) => { if (callback) { hideCallbackRef.current.push(callback); } snapPoint.value = withTiming(0, timingConfig); }, ); return () => { if (timerRef.current) { clearTimeout(timerRef.current); timerRef.current = null; } if (backHandlerRef.current) { backHandlerRef.current?.remove(); backHandlerRef.current = undefined; } listenerSubscription.remove(); }; }, []); const maskAnimated = useAnimatedStyle(() => { return { opacity: snapPoint.value * 0.5, }; }); const panelAnimated = useAnimatedStyle(() => { return { transform: [ orientation === "vertical" ? { translateY: (1 - snapPoint.value) * useAnimatedBase, } : { translateX: (1 - snapPoint.value) * useAnimatedBase, }, ], }; }, [orientation]); const mountPanel = useCallback(() => { setLoading(false); }, []); const unmountPanel = useCallback(() => { panelInfoStore.setValue({ name: null, payload: null, }); hideCallbackRef.current.forEach(cb => cb?.()); }, []); useAnimatedReaction( () => snapPoint.value, (result, prevResult) => { if ( ((prevResult !== null && result > prevResult) || prevResult === null) && result > 0.8 ) { runOnJS(mountPanel)(); } if (prevResult && result < prevResult && result === 0) { runOnJS(unmountPanel)(); } }, [], ); const panelBody = ( {renderBody(loading)} ); return ( <> { snapPoint.value = withTiming(0, timingConfig); }}> {keyboardAvoidBehavior === "none" ? ( panelBody ) : ( {panelBody} )} ); } const style = StyleSheet.create({ maskWrapper: { position: "absolute", width: "100%", height: "100%", top: 0, left: 0, right: 0, bottom: 0, zIndex: 15000, }, mask: { backgroundColor: "#000", opacity: 0.5, }, wrapper: { position: "absolute", width: rpx(750), right: 0, borderTopLeftRadius: rpx(28), borderTopRightRadius: rpx(28), zIndex: 15010, }, kbContainer: { zIndex: 15010, }, }); ================================================ FILE: src/components/panels/base/panelFullscreen.tsx ================================================ import React, { useCallback, useEffect, useMemo, useRef } from "react"; import { BackHandler, DeviceEventEmitter, NativeEventSubscription, Pressable, StyleSheet, ViewStyle, } from "react-native"; import Animated, { Easing, EasingFunction, runOnJS, useAnimatedReaction, useAnimatedStyle, useSharedValue, withTiming, } from "react-native-reanimated"; import useColors from "@/hooks/useColors"; import { panelInfoStore } from "../usePanel"; import { vh } from "@/utils/rpx.ts"; import useOrientation from "@/hooks/useOrientation.ts"; const ANIMATION_EASING: EasingFunction = Easing.out(Easing.exp); const ANIMATION_DURATION = 250; const timingConfig = { duration: ANIMATION_DURATION, easing: ANIMATION_EASING, }; interface IPanelFullScreenProps { // 有遮罩 hasMask?: boolean; // 内容 children?: React.ReactNode; // 内容区样式 containerStyle?: ViewStyle; animationType?: "SlideToTop" | "Scale"; } export default function (props: IPanelFullScreenProps) { const { hasMask, containerStyle, children, animationType = "SlideToTop", } = props; const snapPoint = useSharedValue(0); const colors = useColors(); const backHandlerRef = useRef(); const hideCallbackRef = useRef([]); const orientation = useOrientation(); const windowHeight = useMemo(() => vh(100), [orientation]); useEffect(() => { snapPoint.value = 1; if (backHandlerRef.current) { backHandlerRef.current?.remove(); backHandlerRef.current = undefined; } backHandlerRef.current = BackHandler.addEventListener( "hardwareBackPress", () => { snapPoint.value = 0; return true; }, ); const listenerSubscription = DeviceEventEmitter.addListener( "hidePanel", (callback?: () => void) => { if (callback) { hideCallbackRef.current.push(callback); } snapPoint.value = 0; }, ); return () => { if (backHandlerRef.current) { backHandlerRef.current?.remove(); backHandlerRef.current = undefined; } listenerSubscription.remove(); }; }, []); const maskAnimated = useAnimatedStyle(() => { return { opacity: withTiming(snapPoint.value * 0.5, timingConfig), }; }); const panelAnimated = useAnimatedStyle(() => { if (animationType === "SlideToTop") { return { transform: [ { translateY: withTiming( (1 - snapPoint.value) * windowHeight, timingConfig, ), }, ], }; } else { return { transform: [ { scale: withTiming( 0.3 + snapPoint.value * 0.7, timingConfig, ), }, ], opacity: withTiming(snapPoint.value, timingConfig), }; } }); const unmountPanel = useCallback(() => { panelInfoStore.setValue({ name: null, payload: null, }); hideCallbackRef.current.forEach(cb => cb?.()); }, []); useAnimatedReaction( () => snapPoint.value, (result, prevResult) => { if (prevResult && result < prevResult && result === 0) { runOnJS(unmountPanel)(); } }, [], ); return ( <> {hasMask ? ( { snapPoint.value = withTiming(0, timingConfig); }}> ) : null} {children} ); } const style = StyleSheet.create({ maskWrapper: { position: "absolute", width: "100%", height: "100%", top: 0, left: 0, right: 0, bottom: 0, zIndex: 15000, }, mask: { backgroundColor: "#000", opacity: 0.5, }, wrapper: { position: "absolute", width: "100%", height: "100%", bottom: 0, right: 0, zIndex: 15010, flexDirection: "column", }, kbContainer: { zIndex: 15010, }, }); ================================================ FILE: src/components/panels/base/panelHeader.tsx ================================================ import React from "react"; import { StyleProp, StyleSheet, View, ViewStyle } from "react-native"; import rpx from "@/utils/rpx"; import { TouchableOpacity } from "react-native-gesture-handler"; import ThemeText from "@/components/base/themeText"; import Divider from "@/components/base/divider"; import i18n from "@/core/i18n"; interface IPanelHeaderProps { title: string; cancelText?: string; okText?: string; onCancel?: () => void; onOk?: () => void; hideButtons?: boolean; hideDivider?: boolean; style?: StyleProp; } export default function PanelHeader(props: IPanelHeaderProps) { const { title, cancelText, okText, onOk, onCancel, hideButtons, hideDivider, style, } = props; return ( <> {hideButtons ? null : ( {cancelText || i18n.t("common.cancel")} )} {title} {hideButtons ? null : ( {okText || i18n.t("common.confirm")} )} {hideDivider ? null : } ); } const styles = StyleSheet.create({ header: { width: "100%", flexDirection: "row", alignItems: "center", paddingHorizontal: rpx(24), height: rpx(100), }, button: { width: rpx(120), height: "100%", justifyContent: "center", }, rightButton: { alignItems: "flex-end", }, title: { flex: 1, textAlign: "center", }, }); ================================================ FILE: src/components/panels/index.tsx ================================================ import React from "react"; import panels from "./types"; import { panelInfoStore } from "./usePanel"; function Panels() { const panelInfoState = panelInfoStore.useValue(); const Component = panelInfoState.name ? panels[panelInfoState.name] : null; return Component ? : null; } export default React.memo(Panels, () => true); ================================================ FILE: src/components/panels/types/addToMusicSheet.tsx ================================================ import React from "react"; import { StyleSheet, View } from "react-native"; import rpx, { vmax } from "@/utils/rpx"; import ListItem from "@/components/base/listItem"; import { ImgAsset } from "@/constants/assetsConst"; import Toast from "@/utils/toast"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import PanelBase from "../base/panelBase"; import { FlatList } from "react-native-gesture-handler"; import { hidePanel, showPanel } from "../usePanel"; import PanelHeader from "../base/panelHeader"; import MusicSheet, { useSheetsBase } from "@/core/musicSheet"; import { useI18N } from "@/core/i18n"; interface IAddToMusicSheetProps { musicItem: IMusic.IMusicItem | IMusic.IMusicItem[]; // 如果是新建歌单,可以传入一个默认的名称 newSheetDefaultName?: string; } export default function AddToMusicSheet(props: IAddToMusicSheetProps) { const sheets = useSheetsBase(); const { musicItem = [], newSheetDefaultName } = props ?? {}; const safeAreaInsets = useSafeAreaInsets(); const { t } = useI18N(); return ( ( <> sheet.id} style={{ marginBottom: safeAreaInsets.bottom, }} ListHeaderComponent={ { showPanel("CreateMusicSheet", { defaultName: newSheetDefaultName, async onSheetCreated(sheetId) { try { await MusicSheet.addMusic( sheetId, musicItem, ); Toast.success( t("panel.addToMusicSheet.toast.success"), ); } catch { Toast.warn( t("panel.addToMusicSheet.toast.fail"), ); } }, onCancel() { showPanel("AddToMusicSheet", { musicItem: musicItem, newSheetDefaultName, }); }, }); }}> } renderItem={({ item: sheet }) => ( { try { await MusicSheet.addMusic( sheet.id, musicItem, ); hidePanel(); Toast.success(t("panel.addToMusicSheet.toast.success")); } catch { Toast.warn(t("panel.addToMusicSheet.toast.fail")); } }}> )} /> )} height={vmax(70)} /> ); } const style = StyleSheet.create({ wrapper: { width: "100%", flex: 1, }, header: { paddingHorizontal: rpx(24), marginTop: rpx(36), marginBottom: rpx(36), }, }); ================================================ FILE: src/components/panels/types/associateLrc.tsx ================================================ import rpx, { vmax } from "@/utils/rpx"; import React, { useState } from "react"; import { StyleSheet } from "react-native"; import { fontSizeConst } from "@/constants/uiConst"; import lyricManager from "@/core/lyricManager"; import mediaCache from "@/core/mediaCache"; import useColors from "@/hooks/useColors"; import { errorLog } from "@/utils/log"; import { parseMediaUniqueKey } from "@/utils/mediaUtils"; import Toast from "@/utils/toast"; import Clipboard from "@react-native-clipboard/clipboard"; import { TextInput } from "react-native-gesture-handler"; import PanelBase from "../base/panelBase"; import PanelHeader from "../base/panelHeader"; import { hidePanel } from "../usePanel"; import { useI18N } from "@/core/i18n"; interface INewMusicSheetProps { musicItem: IMusic.IMusicItem; } export default function AssociateLrc(props: INewMusicSheetProps) { const { musicItem } = props; const [input, setInput] = useState(""); const colors = useColors(); const { t } = useI18N(); return ( ( <> { const inputValue = input ?? (await Clipboard.getString()); if (inputValue) { try { const targetMedia = parseMediaUniqueKey( inputValue.trim(), ); // 目标也要写进去 const targetCache = mediaCache.getMediaCache(targetMedia); if (!targetCache) { Toast.warn( t("panel.associateLrc.targetExpired"), ); // TODO: ERROR CODE throw new Error("CLIPBOARD TIMEOUT"); } lyricManager.associateLyric(musicItem, { ...targetMedia, ...targetCache, }); Toast.success(t("panel.associateLrc.toast.success")); hidePanel(); } catch (e: any) { if (e.message !== "CLIPBOARD TIMEOUT") { Toast.warn(t("panel.associateLrc.toast.fail")); } errorLog("关联歌词失败", e?.message); } } else { lyricManager.unassociateLyric(musicItem); Toast.success(t("panel.associateLrc.toast.unlinkSuccess")); hidePanel(); } }} /> { setInput(_); }} style={[ style.input, { color: colors.text, backgroundColor: colors.placeholder, }, ]} placeholderTextColor={colors.textSecondary} placeholder={t("panel.associateLrc.inputPlaceholder")} maxLength={80} /> )} /> ); } const style = StyleSheet.create({ opeartions: { width: rpx(750), paddingHorizontal: rpx(24), flexDirection: "row", height: rpx(100), alignItems: "center", justifyContent: "space-between", }, input: { margin: rpx(24), borderRadius: rpx(12), fontSize: fontSizeConst.content, lineHeight: fontSizeConst.content * 1.5, padding: rpx(12), }, }); ================================================ FILE: src/components/panels/types/colorPicker.tsx ================================================ import React, { useMemo, useRef, useState, useCallback, useEffect } from "react"; import { Image, StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import PanelBase from "../base/panelBase"; import LinearGradient from "react-native-linear-gradient"; import Color from "color"; import { Gesture, GestureDetector, TextInput } from "react-native-gesture-handler"; import { hidePanel } from "../usePanel"; import { ImgAsset } from "@/constants/assetsConst"; import PanelHeader from "../base/panelHeader"; import { useI18N } from "@/core/i18n"; interface IColorPickerProps { defaultColor?: string; onSelected?: (color: Color) => void; closePanelWhenSelected?: boolean; } const areaSize = rpx(420); export default function ColorPicker(props: IColorPickerProps) { const { onSelected, defaultColor = "#66ccff", closePanelWhenSelected = true, } = props; const { t } = useI18N(); const [currentHue, setCurrentHue] = useState(Color(defaultColor).hue()); const [currentSaturation, setCurrentSaturation] = useState( Color(defaultColor).saturationl(), ); const [currentLightness, setCurrentLightness] = useState( Color(defaultColor).lightness(), ); const [currentAlpha, setCurrentAlpha] = useState( Color(defaultColor).alpha(), ); const [inputValue, setInputValue] = useState(() => Color(defaultColor).rgb().hexa().toString() ); const hueColor = useMemo( () => Color.hsl(currentHue, 100, 50), [currentHue] ); const currentColor = useMemo( () => Color.hsl(currentHue, currentSaturation, currentLightness), [currentHue, currentSaturation, currentLightness], ); const currentColorWithAlpha = useMemo( () => currentColor.alpha(currentAlpha), [currentColor, currentAlpha], ); const hueColorString = useMemo(() => hueColor.toString(), [hueColor]); const currentColorString = useMemo(() => currentColor.toString(), [currentColor]); const currentColorWithAlphaString = useMemo(() => currentColorWithAlpha.toString(), [currentColorWithAlpha]); const currentColorAlpha0String = useMemo(() => currentColor.alpha(0).toString(), [currentColor]); const colorHexString = useMemo(() => currentColorWithAlpha.rgb().hexa().toString(), [currentColorWithAlpha]); // 同步colorHexString到inputValue const syncInputValue = useCallback(() => { setInputValue(colorHexString); }, [colorHexString]); // 当颜色通过滑块改变时,同步输入框 useEffect(() => { syncInputValue(); }, [syncInputValue]); const slThumbStyle = useMemo(() => ({ left: -rpx(15) + (currentSaturation / 100) * areaSize, bottom: -rpx(15) + (currentLightness / 100) * areaSize, backgroundColor: currentColorString, }), [currentSaturation, currentLightness, currentColorString]); const hueThumbStyle = useMemo(() => ({ top: -rpx(7) + (currentHue / 360) * areaSize, }), [currentHue]); const alphaThumbStyle = useMemo(() => ({ top: -rpx(7) + (1 - currentAlpha) * areaSize, }), [currentAlpha]); const handleSLUpdate = useCallback((x: number, y: number) => { const xRate = Math.min(1, Math.max(0, x / areaSize)); const yRate = Math.min(1, Math.max(0, y / areaSize)); setCurrentSaturation(xRate * 100); setCurrentLightness((1 - yRate) * 100); }, []); const handleHueUpdate = useCallback((y: number) => { const yRate = Math.min(1, Math.max(0, y / areaSize)); setCurrentHue(yRate * 360); }, []); const handleAlphaUpdate = useCallback((y: number) => { const yRate = Math.min(1, Math.max(0, y / areaSize)); setCurrentAlpha(1 - yRate); }, []); const slTap = Gesture.Tap() .onStart(event => { const { x, y } = event; handleSLUpdate(x, y); }) .runOnJS(true); const lastTimestampRef = useRef(Date.now()); const slPan = Gesture.Pan() .onUpdate(event => { const newTimeStamp = Date.now(); if (newTimeStamp - lastTimestampRef.current > 32) { lastTimestampRef.current = newTimeStamp; const { x, y } = event; handleSLUpdate(x, y); } }) .runOnJS(true); const slComposed = Gesture.Race(slTap, slPan); const hueTap = Gesture.Tap() .onStart(event => { const { y } = event; handleHueUpdate(y); }) .runOnJS(true); const huePan = Gesture.Pan() .onUpdate(event => { const { y } = event; handleHueUpdate(y); }) .runOnJS(true); const hueComposed = Gesture.Race(hueTap, huePan); const alphaTap = Gesture.Tap() .onStart(event => { const { y } = event; handleAlphaUpdate(y); }) .runOnJS(true); const alphaPan = Gesture.Pan() .onUpdate(event => { const { y } = event; handleAlphaUpdate(y); }) .runOnJS(true); const alphaComposed = Gesture.Race(alphaTap, alphaPan); const handleColorInputChange = useCallback((text: string) => { setInputValue(text); }, []); const handleColorInputSubmit = useCallback(() => { try { const color = Color(inputValue); const hsl = color.hsl(); setCurrentHue(hsl.hue() || 0); setCurrentSaturation(hsl.saturationl()); setCurrentLightness(hsl.lightness()); setCurrentAlpha(color.alpha()); } catch (error) { // 如果输入的颜色无效,恢复到当前颜色 setInputValue(colorHexString); } }, [inputValue, colorHexString]); const handleColorInputBlur = useCallback(() => { handleColorInputSubmit(); }, [handleColorInputSubmit]); return ( ( <> { // 检查输入框的值是否与当前颜色不同 if (inputValue !== colorHexString) { try { const color = Color(inputValue); const hsl = color.hsl(); // 更新颜色状态 setCurrentHue(hsl.hue() || 0); setCurrentSaturation(hsl.saturationl()); setCurrentLightness(hsl.lightness()); setCurrentAlpha(color.alpha()); // 使用输入的颜色进行提交 onSelected?.(color); } catch (error) { // 如果输入的颜色无效,使用当前颜色 onSelected?.(currentColorWithAlpha); } } else { // 输入值与当前颜色相同,直接使用当前颜色 onSelected?.(currentColorWithAlpha); } if (closePanelWhenSelected) { hidePanel(); } }} title={t("panel.colorPicker.title")} /> )} /> ); } const styles = StyleSheet.create({ opeartions: { width: "100%", paddingHorizontal: rpx(36), flexDirection: "row", height: rpx(100), alignItems: "center", justifyContent: "space-between", }, container: { width: "100%", paddingHorizontal: rpx(48), paddingTop: rpx(36), flexDirection: "row", }, slContainer: { width: areaSize, height: areaSize, }, layer1: { position: "absolute", zIndex: 1, left: 0, top: 0, }, layer2: { position: "absolute", zIndex: 2, left: 0, top: 0, }, hueContainer: { width: rpx(48), height: areaSize, marginLeft: rpx(90), }, alphaContainer: { marginLeft: rpx(48), }, slThumb: { position: "absolute", width: rpx(24), height: rpx(24), borderRadius: rpx(12), borderWidth: rpx(3), borderStyle: "solid", borderColor: "#ccc", zIndex: 3, }, hueThumb: { position: "absolute", width: rpx(56), height: rpx(8), left: -rpx(4), top: 0, borderWidth: rpx(3), borderStyle: "solid", borderColor: "#ccc", }, showBar: { width: rpx(76), height: rpx(50), borderWidth: 1, borderStyle: "solid", borderColor: "#ccc", }, showBarContent: { width: "100%", height: "100%", position: "absolute", left: 0, top: 0, }, showArea: { width: "100%", marginTop: rpx(36), paddingHorizontal: rpx(48), flexDirection: "row", alignItems: "center", }, colorStr: { marginLeft: rpx(24), }, transparentBg: { position: "absolute", zIndex: -1, width: "100%", height: "100%", left: 0, top: 0, }, colorInput: { marginLeft: rpx(24), minWidth: rpx(150), height: rpx(40), borderWidth: 1, borderColor: "#ccc", borderRadius: rpx(4), paddingHorizontal: rpx(12), paddingVertical: 0, fontSize: rpx(28), color: "#333", backgroundColor: "#fff", }, }); ================================================ FILE: src/components/panels/types/createMusicSheet.tsx ================================================ import { fontSizeConst } from "@/constants/uiConst"; import useColors from "@/hooks/useColors"; import rpx, { vmax } from "@/utils/rpx"; import React, { useState } from "react"; import { StyleSheet } from "react-native"; import MusicSheet from "@/core/musicSheet"; import { TextInput } from "react-native-gesture-handler"; import PanelBase from "../base/panelBase"; import PanelHeader from "../base/panelHeader"; import { hidePanel } from "../usePanel"; import { useI18N } from "@/core/i18n"; interface ICreateMusicSheetProps { defaultName?: string; onSheetCreated?: (sheetId: string) => void; onCancel?: () => void; } export default function CreateMusicSheet(props: ICreateMusicSheetProps) { const { t } = useI18N(); const { onSheetCreated, onCancel, defaultName = t("panel.createMusicSheet.title") } = props; const [input, setInput] = useState(""); const colors = useColors(); return ( ( <> { onCancel ? onCancel() : hidePanel(); }} onOk={async () => { const sheetId = await MusicSheet.addSheet( input || defaultName, ); onSheetCreated?.(sheetId); hidePanel(); }} /> { setInput(_); }} autoFocus accessible accessibilityLabel={t("panel.createMusicSheet.inputLabel")} accessibilityHint={t("panel.createMusicSheet.title")} style={[ style.input, { color: colors.text, backgroundColor: colors.placeholder, }, ]} placeholderTextColor={colors.textSecondary} placeholder={defaultName} maxLength={200} /> )} /> ); } const style = StyleSheet.create({ wrapper: { width: rpx(750), }, operations: { width: rpx(750), paddingHorizontal: rpx(24), flexDirection: "row", height: rpx(100), alignItems: "center", justifyContent: "space-between", }, input: { margin: rpx(24), borderRadius: rpx(12), fontSize: fontSizeConst.content, lineHeight: fontSizeConst.content * 1.5, padding: rpx(12), }, }); ================================================ FILE: src/components/panels/types/editMusicSheetInfo.tsx ================================================ import AppBar from "@/components/base/appBar.tsx"; import Image from "@/components/base/image.tsx"; import Input from "@/components/base/input.tsx"; import ThemeText from "@/components/base/themeText.tsx"; import VerticalSafeAreaView from "@/components/base/verticalSafeAreaView.tsx"; import PanelFullscreen from "@/components/panels/base/panelFullscreen.tsx"; import { hidePanel } from "@/components/panels/usePanel.ts"; import { ImgAsset } from "@/constants/assetsConst.ts"; import globalStyle from "@/constants/globalStyle.ts"; import pathConst from "@/constants/pathConst.ts"; import { fontSizeConst } from "@/constants/uiConst.ts"; import { useI18N } from "@/core/i18n"; import MusicSheet from "@/core/musicSheet"; import useColors from "@/hooks/useColors.ts"; import { addFileScheme, addRandomHash } from "@/utils/fileUtils.ts"; import rpx from "@/utils/rpx"; import Toast from "@/utils/toast.ts"; import { readAsStringAsync } from "expo-file-system"; import React, { useState } from "react"; import { StyleSheet, TouchableOpacity, View } from "react-native"; import { exists, unlink, writeFile } from "react-native-fs"; import { launchImageLibrary } from "react-native-image-picker"; interface IEditSheetDetailProps { musicSheet: IMusic.IMusicSheetItem; } export default function EditMusicSheetInfo(props: IEditSheetDetailProps) { const { musicSheet } = props; const colors = useColors(); const { t } = useI18N(); const [coverImg, setCoverImg] = useState(musicSheet?.coverImg); const [title, setTitle] = useState(musicSheet?.title); const onChangeCoverPress = async () => { try { const result = await launchImageLibrary({ mediaType: "photo", }); const uri = result.assets?.[0].uri; if (!uri) { return; } console.log(uri); setCoverImg(uri); } catch (e) { console.log(e); } }; function onTitleChange(_: string) { setTitle(_); } async function onConfirm() { // 判断是否相同 if ( coverImg === musicSheet?.coverImg && title === musicSheet?.title ) { hidePanel(); return; } let newCoverImg = coverImg; if (coverImg && coverImg !== musicSheet?.coverImg) { newCoverImg = addFileScheme( `${pathConst.dataPath}sheet${musicSheet.id}${coverImg.substring( coverImg.lastIndexOf("."), )}`, ); try { if ((await exists(newCoverImg))) { await unlink(newCoverImg); } // Copy const rawImage = await readAsStringAsync(coverImg, { encoding: "base64", }); await writeFile(newCoverImg, rawImage, "base64"); } catch (e) { console.log(e); } } let _title = title; if (!_title?.length) { _title = musicSheet.title; } // 更新歌单信息 MusicSheet.updateMusicSheetBase(musicSheet.id, { coverImg: newCoverImg ? addRandomHash(newCoverImg) : undefined, title: _title, }).then(() => { Toast.success(t("panel.editMusicSheetInfo.toast.updateSuccess")); }); hidePanel(); } return ( {t("panel.editMusicSheetInfo.title")} {t("common.cover")} { setCoverImg(undefined); }}> {t("panel.editMusicSheetInfo.sheetName")} {t("common.confirm")} ); } const style = StyleSheet.create({ row: { marginTop: rpx(28), height: rpx(120), flexDirection: "row", justifyContent: "space-between", alignItems: "center", paddingBottom: rpx(12), paddingHorizontal: rpx(24), }, coverImg: { width: rpx(100), height: rpx(100), borderRadius: rpx(28), }, button: { marginHorizontal: rpx(24), borderRadius: rpx(8), height: rpx(72), marginTop: rpx(24), justifyContent: "center", alignItems: "center", }, }); ================================================ FILE: src/components/panels/types/imageViewer.tsx ================================================ import React from "react"; import { Image, StyleSheet } from "react-native"; import rpx, { vh, vw } from "@/utils/rpx"; import Toast from "@/utils/toast"; import useOrientation from "@/hooks/useOrientation.ts"; import { saveToGallery } from "@/utils/fileUtils.ts"; import { errorLog } from "@/utils/log.ts"; import PanelFullscreen from "@/components/panels/base/panelFullscreen.tsx"; import { Button } from "@/components/base/button.tsx"; import { useI18N } from "@/core/i18n"; interface IImageViewerProps { // 图片路径 url: string; } export default function ImageViewer(props: IImageViewerProps) { const { url } = props; const orientation = useOrientation(); const { t } = useI18N(); return ( )} /> ); } const style = StyleSheet.create({ wrapper: { width: rpx(750), paddingTop: rpx(36), flex: 1, }, titleContainer: { flexDirection: "row", alignItems: "center", marginBottom: rpx(6), paddingHorizontal: rpx(24), }, opeartions: { width: rpx(750), paddingHorizontal: rpx(24), flexDirection: "row", height: rpx(100), alignItems: "center", justifyContent: "space-between", }, input: { borderRadius: rpx(12), fontSize: fontSizeConst.content, lineHeight: fontSizeConst.content * 1.5, padding: rpx(12), flex: 1, }, searchBtn: { marginLeft: rpx(12), }, }); function LyricResultBodyWrapper() { const [index, setIndex] = useState(0); const { t } = useI18N(); const routes = useMemo(() => PluginManager.getSortedSearchablePlugins("lyric")?.map?.( _ => ({ key: _.hash, title: _.name, }), ) ?? [], []); const sceneMap = useMemo(() => { const scene: Record = {}; routes.forEach(r => { scene[r.key] = LyricList; }); return SceneMap(scene); }, [routes]); const colors = useColors(); return routes?.length ? ( ( ( {route.title ?? t("panel.searchLrc.unnamed")} )} indicatorStyle={{ backgroundColor: colors.primary, height: rpx(4), }} /> )} renderScene={sceneMap} onIndexChange={setIndex} initialLayout={{ width: vw(100) }} /> ) : ( ); } ================================================ FILE: src/components/panels/types/searchLrc/searchResultStore.ts ================================================ import { RequestStateCode } from "@/constants/commonConst"; import { GlobalState } from "@/utils/stateMapper"; export interface ISearchLyricResult { data: ILyric.ILyricItem[]; state: RequestStateCode; page: number; } interface ISearchLyricStoreData { query?: string; // plugin - result data: Record; } export default new GlobalState({ data: {} }); ================================================ FILE: src/components/panels/types/searchLrc/useSearchLrc.ts ================================================ import { RequestStateCode } from "@/constants/commonConst"; import PluginManager, { Plugin } from "@/core/pluginManager"; import { devLog, errorLog } from "@/utils/log"; import { produce } from "immer"; import { useCallback, useRef } from "react"; import searchResultStore from "./searchResultStore"; export default function useSearchLrc() { // 当前正在搜索 const currentQueryRef = useRef(""); /** * query: 搜索词 * queryPage: 搜索页码 * pluginHash: 搜索条件 */ const search = useCallback(async function ( query?: string, queryPage?: number, pluginHash?: string, ) { /** 如果没有指定插件,就用所有插件搜索 */ console.log("SEARCH LRC", query, queryPage); let plugins: Plugin[] = []; if (pluginHash) { const tgtPlugin = PluginManager.getByHash(pluginHash); tgtPlugin && (plugins = [tgtPlugin]); } else { plugins = PluginManager.getSearchablePlugins("lyric"); } if (plugins.length === 0) { searchResultStore.setValue( produce(draft => { draft.data = {}; }), ); return; } // 使用选中插件搜素 plugins.forEach(async plugin => { const _platform = plugin.instance.platform; const _hash = plugin.hash; if (!_platform || !_hash) { // 插件无效,此时直接进入结果页 searchResultStore.setValue( produce(draft => { draft.data = {}; }), ); return; } // 上一份搜索结果 const prevPluginResult = searchResultStore.getValue().data[plugin.hash]; /** 上一份搜索还没返回/已经结束 */ if ( (prevPluginResult?.state === RequestStateCode.PENDING_FIRST_PAGE || prevPluginResult?.state === RequestStateCode.PENDING_REST_PAGE || prevPluginResult?.state === RequestStateCode.FINISHED) && undefined === query ) { return; } // 是否是一次新的搜索 const newSearch = query || prevPluginResult?.page === undefined || queryPage === 1; // 本次搜索关键词 currentQueryRef.current = query = query ?? searchResultStore.getValue().query ?? ""; /** 搜索的页码 */ const page = queryPage ?? newSearch ? 1 : (prevPluginResult?.page ?? 0) + 1; try { searchResultStore.setValue( produce(draft => { const prevMediaResult = draft.data; prevMediaResult[_hash] = { state: newSearch ? RequestStateCode.PENDING_FIRST_PAGE : RequestStateCode.PENDING_REST_PAGE, // @ts-ignore data: newSearch ? [] : prevMediaResult[_hash]?.data ?? [], page, }; }), ); const result = await plugin?.methods?.search?.( query, page, "lyric", ); /** 如果搜索结果不是本次结果 */ if (currentQueryRef.current !== query) { return; } /** 切换到结果页 */ if (!result) { throw new Error("搜索结果为空"); } searchResultStore.setValue( produce(draft => { const prevMediaResult = draft.data; const prevPluginResult: any = prevMediaResult[ _hash ] ?? { data: [], }; const currResult = result.data ?? []; prevMediaResult[_hash] = { state: // result?.isEnd === false && result?.data?.length // ? RequestStateCode.PARTLY_DONE // : RequestStateCode.FINISHED, RequestStateCode.FINISHED, page, data: newSearch ? currResult : (prevPluginResult.data ?? []).concat( currResult, ), }; return draft; }), ); } catch (e: any) { errorLog("搜索失败", e?.message); devLog( "error", "搜索失败", `Plugin: ${plugin.name} Query: ${query} Page: ${page}`, e, e?.message, ); /** 如果搜索结果不是本次结果 */ if (currentQueryRef.current !== query) { return; } searchResultStore.setValue( produce(draft => { const prevMediaResult = draft.data; const prevPluginResult = prevMediaResult[_hash] ?? { data: [], }; prevPluginResult.state = RequestStateCode.FINISHED; return draft; }), ); } }); }, []); return search; } ================================================ FILE: src/components/panels/types/setFontSize.tsx ================================================ import React, { useState } from "react"; import { StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import ThemeText from "@/components/base/themeText"; import PanelBase from "../base/panelBase"; import Slider from "@react-native-community/slider"; import useColors from "@/hooks/useColors"; import PanelHeader from "../base/panelHeader"; import { useI18N } from "@/core/i18n"; interface IProps { defaultSelect?: number; /** 点击回调 */ onSelectChange: (value: number) => void; } export default function SetFontSize(props: IProps) { const { defaultSelect, onSelectChange } = props ?? {}; const colors = useColors(); const i18n = useI18N(); const [selected, setSelected] = useState(defaultSelect ?? 1); return ( ( <> { setSelected(val); onSelectChange?.(val); }} minimumValue={0} maximumValue={3} /> {i18n.t("panel.setFontSize.small")} {i18n.t("panel.setFontSize.standard")} {i18n.t("panel.setFontSize.large")} {i18n.t("panel.setFontSize.extraLarge")} )} /> ); } const styles = StyleSheet.create({ header: { width: "100%", flexDirection: "row", padding: rpx(24), }, container: { flex: 1, paddingHorizontal: rpx(24), width: "100%", marginTop: rpx(88), }, sliderContainer: { height: rpx(80), }, label: { position: "absolute", top: rpx(80), width: rpx(72), textAlign: "center", left: rpx(24), opacity: 0.5, }, label1: { left: rpx(234), }, label2: { left: rpx(442), }, label3: { left: rpx(646), }, }); ================================================ FILE: src/components/panels/types/setLyricOffset.tsx ================================================ import React, { useState } from "react"; import { StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import ThemeText from "@/components/base/themeText"; import PanelBase from "../base/panelBase"; import { iconSizeConst } from "@/constants/uiConst"; import PanelHeader from "../base/panelHeader"; import { TouchableOpacity } from "react-native-gesture-handler"; import { hidePanel } from "../usePanel"; import useColors from "@/hooks/useColors"; import Icon from "@/components/base/icon.tsx"; import { getMediaExtraProperty } from "@/utils/mediaExtra"; import { useI18N } from "@/core/i18n"; interface IProps { musicItem: IMusic.IMusicItem; /** 点击回调 */ onSubmit?: (offset: number) => void; } export default function SetLyricOffset(props: IProps) { const { musicItem, onSubmit } = props ?? {}; const { t } = useI18N(); const [offset, setOffset] = useState( getMediaExtraProperty(musicItem, "lyricOffset") ?? 0 ); const colors = useColors(); let titleStr = offset === 0 ? t("panel.setLyricOffset.normal") : offset < 0 ? t("panel.setLyricOffset.delay", { time: (-offset).toFixed(1) }) : t("panel.setLyricOffset.advance", { time: offset.toFixed(1) }); return ( ( <> { onSubmit?.(offset); }} onCancel={hidePanel} /> { setOffset(prev => prev - 0.2); }}> -0.2s { setOffset(0); }}> {t("panel.setLyricOffset.reset")} { setOffset(prev => prev + 0.2); }}> +0.2s )} /> ); } const styles = StyleSheet.create({ header: { width: "100%", flexDirection: "row", padding: rpx(24), }, container: { flex: 1, paddingHorizontal: rpx(24), paddingBottom: rpx(36), width: "100%", flexDirection: "row", alignItems: "center", justifyContent: "space-around", }, btn: { width: rpx(144), height: rpx(144), alignItems: "center", justifyContent: "space-around", }, }); ================================================ FILE: src/components/panels/types/setUserVariables.tsx ================================================ import React, { useRef } from "react"; import { KeyboardAvoidingView, StyleSheet } from "react-native"; import rpx, { vmax } from "@/utils/rpx"; import useColors from "@/hooks/useColors"; import ThemeText from "@/components/base/themeText"; import { ScrollView } from "react-native-gesture-handler"; import PanelBase from "../base/panelBase"; import { hidePanel } from "../usePanel"; import ListItem from "@/components/base/listItem"; import Input from "@/components/base/input"; import globalStyle from "@/constants/globalStyle"; import PanelHeader from "../base/panelHeader"; interface IUserVariablesProps { title?: string; onOk: (values: Record, closePanel: () => void) => void; variables: IPlugin.IUserVariable[]; initValues?: Record; onCancel?: () => void; } export default function SetUserVariables(props: IUserVariablesProps) { const { onOk, onCancel, variables, initValues = {}, title } = props; const colors = useColors(); const resultRef = useRef({ ...initValues }); return ( ( <> { onCancel?.(); hidePanel(); }} onOk={async () => { onOk(resultRef.current, hidePanel); }} /> {variables.map(it => ( {it.name ?? it.key} { resultRef.current[it.key] = e; }} style={[ styles.input, { backgroundColor: colors.placeholder, }, ]} placeholder={it.hint} /> ))} )} /> ); } const styles = StyleSheet.create({ wrapper: { width: rpx(750), }, opeartions: { width: rpx(750), paddingHorizontal: rpx(24), flexDirection: "row", height: rpx(100), alignItems: "center", justifyContent: "space-between", }, listItem: { justifyContent: "space-between", }, varName: { maxWidth: "35%", }, input: { width: "50%", paddingVertical: rpx(8), paddingHorizontal: rpx(12), borderRadius: rpx(8), }, }); ================================================ FILE: src/components/panels/types/sheetTags.tsx ================================================ import React from "react"; import { StyleSheet, View } from "react-native"; import rpx, { vh } from "@/utils/rpx"; import ThemeText from "@/components/base/themeText"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import PanelBase from "../base/panelBase"; import { ScrollView } from "react-native-gesture-handler"; import TypeTag from "@/components/base/typeTag"; import PanelHeader from "../base/panelHeader"; import { useI18N } from "@/core/i18n"; interface ISheetTagsProps { tags: IMusic.IMusicSheetGroupItem[]; /** 点击tag */ onTagPressed: (tag: ICommon.IUnique) => void; } export default function SheetTags(props: ISheetTagsProps) { const { tags, onTagPressed } = props ?? {}; const i18n = useI18N(); const safeAreaInsets = useSafeAreaInsets(); return ( ( <> { onTagPressed({ title: i18n.t("common.default"), id: "", }); }} /> {tags.map((tagGroupItem, index) => ( <> {tagGroupItem.title ? ( {tagGroupItem.title} ) : null} {tagGroupItem.data.map(_ => ( { onTagPressed(_); }} /> ))} ))} )} /> ); } const style = StyleSheet.create({ header: { width: "100%", flexDirection: "row", padding: rpx(24), marginTop: rpx(12), }, body: { flex: 1, paddingHorizontal: rpx(24), }, item: { height: rpx(96), justifyContent: "center", }, groupItem: { flexDirection: "row", paddingVertical: rpx(12), flexWrap: "wrap", }, tagItem: { marginLeft: 0, marginBottom: rpx(20), }, }); ================================================ FILE: src/components/panels/types/simpleInput.tsx ================================================ import React, { useState } from "react"; import { StyleSheet, View } from "react-native"; import rpx, { vmax } from "@/utils/rpx"; import { fontSizeConst } from "@/constants/uiConst"; import useColors from "@/hooks/useColors"; import ThemeText from "@/components/base/themeText"; import { ScrollView, TextInput } from "react-native-gesture-handler"; import PanelBase from "../base/panelBase"; import { hidePanel } from "../usePanel"; import PanelHeader from "../base/panelHeader"; import { useI18N } from "@/core/i18n"; interface ISimpleInputProps { title?: string; onOk: (text: string, closePanel: () => void) => void; hints?: string[]; onCancel?: () => void; maxLength?: number; placeholder?: string; autoFocus?: boolean; } export default function SimpleInput(props: ISimpleInputProps) { const { t } = useI18N(); const { onOk, onCancel, placeholder, maxLength = 80, hints, title, autoFocus = true, } = props; const [input, setInput] = useState(""); const colors = useColors(); return ( ( <> { onCancel?.(); hidePanel(); }} onOk={async () => { onOk(input, hidePanel); }} /> { setInput(_); }} style={[ style.input, { color: colors.text, backgroundColor: colors.placeholder, }, ]} placeholderTextColor={colors.textSecondary} placeholder={placeholder ?? ""} maxLength={maxLength} /> {hints?.length ? ( {hints.map((_, index) => ( ○ {_} ))} ) : null} )} /> ); } const style = StyleSheet.create({ wrapper: { width: rpx(750), }, opeartions: { width: rpx(750), paddingHorizontal: rpx(24), flexDirection: "row", height: rpx(100), alignItems: "center", justifyContent: "space-between", }, input: { margin: rpx(24), borderRadius: rpx(12), fontSize: fontSizeConst.content, lineHeight: fontSizeConst.content * 1.5, padding: rpx(12), }, hints: { marginTop: rpx(24), paddingHorizontal: rpx(24), }, hintLine: { marginBottom: rpx(12), }, }); ================================================ FILE: src/components/panels/types/simpleSelect.tsx ================================================ import React, { Fragment } from "react"; import { ScrollView, StyleSheet } from "react-native"; import rpx from "@/utils/rpx"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import PanelBase from "../base/panelBase"; import { hidePanel } from "../usePanel"; import ListItem from "@/components/base/listItem"; import PanelHeader from "../base/panelHeader"; interface ICandidateItem { title?: string; value: any; } interface ISimpleSelectProps { height?: number; header?: string; candidates?: Array; onPress?: (item: ICandidateItem) => void; } export default function SimpleSelect(props: ISimpleSelectProps) { const { height = rpx(520), header = "", candidates = [], onPress, } = props ?? {}; const safeAreaInsets = useSafeAreaInsets(); return ( ( <> {candidates.map((it, index) => { return ( { onPress?.(it); hidePanel(); }}> ); })} )} /> ); } const styles = StyleSheet.create({ header: { width: "100%", flexDirection: "row", padding: rpx(24), }, body: { flex: 1, }, item: { height: rpx(96), justifyContent: "center", }, }); ================================================ FILE: src/components/panels/types/timingClose.tsx ================================================ import React from "react"; import { StyleSheet, TouchableOpacity, View } from "react-native"; import rpx from "@/utils/rpx"; import ThemeText from "@/components/base/themeText"; import { setCloseAfterPlayEnd, setScheduleClose, useCloseAfterPlayEnd, useScheduleCloseCountDown } from "@/utils/scheduleClose"; import timeformat from "@/utils/timeformat"; import PanelBase from "../base/panelBase"; import Divider from "@/components/base/divider"; import PanelHeader from "../base/panelHeader"; import Checkbox from "@/components/base/checkbox"; import { Pressable } from "react-native-gesture-handler"; import { useI18N } from "@/core/i18n"; import { showDialog } from "@/components/dialogs/useDialog"; const shortCutTimes = [10, 20, 30, 45, 60] as const; function CountDownHeader() { const countDown = useScheduleCloseCountDown(); const { t } = useI18N(); return ( ); } export default function TimingClose() { const closeAfterPlay = useCloseAfterPlayEnd(); const countDown = useScheduleCloseCountDown(); const isCountingDown = countDown !== null; const { t } = useI18N(); return ( ( <> {shortCutTimes.map((time, index) => ( { setScheduleClose( Date.now() + time * 60000, ); }}> {time} ))} { showDialog("SetScheduleCloseTimeDialog", { onOk: (minutes: number) => { setScheduleClose(Date.now() + minutes * 60000); }, }); }}> {t("panel.timingClose.customize")} { setCloseAfterPlayEnd(!closeAfterPlay); }}> {t("panel.timingClose.closeAfterPlay")} {isCountingDown && ( { setScheduleClose(null); }}> {t("panel.timingClose.cancelScheduleClose")} )} )} /> ); } const styles = StyleSheet.create({ header: { width: rpx(750), paddingHorizontal: rpx(24), height: rpx(90), flexDirection: "row", alignItems: "center", justifyContent: "space-between", }, bodyContainer: { width: "100%", height: rpx(160), padding: rpx(24), gap: rpx(16), flexDirection: "row", }, timeItem: { flex: 1, backgroundColor: "#99999999", borderRadius: rpx(12), alignItems: "center", justifyContent: "center", }, bottomLine: { width: "100%", marginTop: rpx(36), height: rpx(64), paddingHorizontal: rpx(24), flexDirection: "row", justifyContent: "space-between", alignItems: "center", }, cancelButton: { paddingHorizontal: rpx(16), paddingVertical: rpx(8), backgroundColor: "#ff666699", borderRadius: rpx(8), }, cancelButtonText: { color: "#ffffff", fontSize: rpx(24), }, closeAfterPlayContainer: { flexDirection: "row", alignItems: "center", }, bottomLineText: { marginLeft: rpx(12), }, }); ================================================ FILE: src/components/panels/usePanel.ts ================================================ import { GlobalState } from "@/utils/stateMapper"; import { DeviceEventEmitter } from "react-native"; import panels from "./types"; type IPanel = typeof panels; type IPanelkeys = keyof IPanel; interface IPanelInfo { name: IPanelkeys | null; payload: any; } /** 浮层信息 */ export const panelInfoStore = new GlobalState({ name: null, payload: null, }); export function showPanel( name: T, payload?: Parameters[0], ) { if (panelInfoStore.getValue().name) { DeviceEventEmitter.emit("hidePanel", () => { panelInfoStore.setValue({ name, payload, }); }); } else { panelInfoStore.setValue({ name, payload, }); } } export function hidePanel() { DeviceEventEmitter.emit("hidePanel"); } ================================================ FILE: src/constants/assetsConst.ts ================================================ export const ImgAsset = { albumDefault: require("@/assets/imgs/album-default.jpeg"), addBackground: require("@/assets/imgs/add-image.png"), add: require("@/assets/imgs/add.png"), logo: require("@/assets/imgs/logo.png"), author: require("@/assets/imgs/author.jpg"), logoTransparent: require("@/assets/imgs/logo-transparent.png"), wechatChannel: require("@/assets/imgs/wechat_channel.jpg"), // 音质 quality: { low: require("@/assets/imgs/low-quality.png"), standard: require("@/assets/imgs/standard-quality.png"), high: require("@/assets/imgs/high-quality.png"), super: require("@/assets/imgs/super-quality.png"), }, rate: { 50: require("@/assets/imgs/50x.png"), 75: require("@/assets/imgs/75x.png"), 100: require("@/assets/imgs/100x.png"), 125: require("@/assets/imgs/125x.png"), 150: require("@/assets/imgs/150x.png"), 175: require("@/assets/imgs/175x.png"), 200: require("@/assets/imgs/200x.png"), } as any, transparentBg: require("@/assets/imgs/transparent-bg.png"), } as const; export const B64Asset = { share: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAoHBwgHBgoICAgLCgoLDhgQDg0NDh0VFhEYIx8lJCIfIiEmKzcvJik0KSEiMEExNDk7Pj4+JS5ESUM8SDc9Pjv/2wBDAQoLCw4NDhwQEBw7KCIoOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozv/wgARCAOOA0gDAREAAhEBAxEB/8QAGwABAQADAQEBAAAAAAAAAAAAAAECAwQFBgf/xAAbAQEBAAMBAQEAAAAAAAAAAAAAAQIDBAUGB//aAAwDAQACEAMQAAAA+85/YFQAUAFAsoAAAAKUAAAFAAAgoIpAAAApns4dm7ylBIAAAAAIAAAAAAAQAUABKAJFACgASHLxfTUAFCkFKioZRKAAFABQAAChAUAICVSwBCFCgGezh2bvKUkABSAAACAAAAAAAEAAFACUQCKAoAEHJxfT1ABQApKBZQAACgAoAAKAAAAJQQAAUAAz2cO3f5UCIAAAAAAAEAAAAAABABQQJkYxSoFAUATk4vp6gFEKoABbKQAAoKAAACgAAAAS0IgKAAFBls4du/yixigAAAAAAAAQAAAAAEAAAGSYwKlFAUAOTi+mqAUSktAChKSgBQCgAAFCAoAACWgCRQAAFBns4dm7ylpBBJQLURAAAAAAAIAAAAQAADJJAqCAyoAHLxfSigCVVIVBSoJQoKAAAAUAAACAUUAAIAASgz2cOzd5a2oISTIC2RAgAAAAAAgAAAABAAMkARCFTKgAcvF9KKJQFUpEFKmK2iUoAAKEKCFAAAS0SKKAKEAAIQZ7OLZ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YEBRIjJwkKDA/9oACAEDAQk/AP8AkBrBwsFqduN4cDiccGLqLNjGMcoY5YxjljGP2tsfYtxt4XPLoPrNGh9V2Xh4hdRdMWPFj9rSn953Dx/eHkpfIX3tj6PtW+2hC+E/fdWx6w84ee6oXaQsUL31PDw+4+7UVgxjHgxj9khYUMcW8dvB1DGWoYyh671RWSyQvYXChT1QzSmhjFgtOEeZ6/hV8EtyjjijiLBCFghdl4vNjHgxj/4H13HC+pr0T9W+4vdv/BSyf0a/8XOhCEIQhCEIQhCEIQhCEIX1V/JI4ihCyWCFKOIvmLFFYOaFghC+YX4CP39IhCK+aoqLioe5ofRZ0vlVjULeC6G3FHj5pYLBiHs0XD1CEbZfyihYaHCjj0hjH0H1jwKNfLXFRcIX8saGPZouForvPF/BeR7wUKNDmvxV2mPBe9oqLXZqb7yxePEWHL3amp8nkWsV1Li+8slrJSqF7dC6I30FCjbx32H30KayReD9stQxC0WMcvZse40iouGX8rqGM3D6DEPrDjcrHXql6p6LGOKGOGWMuNo1FxX5dLGhDHNGhw+1fo2PBjmzXQZ5lSxi/JqHisEKVFY8hxfotMf8ij+sLUWXFFjzf5tYvtUPfqX1bhn9YWpsWysXkvVv1NDGPBGsWP5x46XaeS+XdHKFhrsOV8pWFQi8KKh/NrQs1Gh4McKHC+Q8dhSsEIUoXyujkcjkcjkcjkcjkcjkcjkcjkcjkcjkcjkcjkMr/Qn/AP/Z", }; ================================================ FILE: src/constants/commonConst.ts ================================================ import { Easing, EasingFunction } from "react-native-reanimated"; export const internalSymbolKey = Symbol.for("$"); // 加入播放列表的时间;app内使用,无法被序列化 export const timeStampSymbol = Symbol.for("time-stamp"); // 加入播放列表的辅助顺序 export const sortIndexSymbol = Symbol.for("sort-index"); export const internalSerializeKey = "$"; export const localMusicSheetId = "local-music-sheet"; export const musicHistorySheetId = "history-music-sheet"; export const localPluginPlatform = "本地"; export const localPluginHash = "local-plugin-hash"; export const internalFakeSoundKey = "fake-key"; const emptyFunction = () => {}; Object.freeze(emptyFunction); export { emptyFunction }; export enum RequestStateCode { /** 空闲 */ IDLE = 0b00000000, PENDING_FIRST_PAGE = 0b00000010, LOADING = 0b00000010, /** 检索中 */ PENDING_REST_PAGE = 0b00000011, /** 部分结束 */ PARTLY_DONE = 0b00000100, /** 全部结束 */ FINISHED = 0b0001000, /** 出错了 */ ERROR = 0b10000000, } export const StorageKeys = { /** @deprecated */ MediaMetaKeys: "media-meta-keys", PluginMetaKey: "plugin-meta", MediaCache: "media-cache", LocalMusicSheet: "local-music-sheet", }; export const CacheControl = { Cache: "cache", NoCache: "no-cache", NoStore: "no-store", }; export const supportLocalMediaType = [ ".mp3", ".flac", ".wma", ".wav", ".m4a", ".ogg", ".acc", ".aac", ".ape", ".opus", ]; const ANIMATION_EASING: EasingFunction = Easing.out(Easing.exp); const ANIMATION_DURATION = 150; const animationFast = { duration: ANIMATION_DURATION, easing: ANIMATION_EASING, }; const animationNormal = { duration: 250, easing: ANIMATION_EASING, }; const animationSlow = { duration: 500, easing: ANIMATION_EASING, }; export const timingConfig = { animationFast, animationNormal, animationSlow, }; export const enum SortType { // 未排序 None = "None", // 按标题排序 Title = "title", // 按作者排序 Artist = "artist", // 按专辑名排序 Album = "album", // 按时间排序 Newest = "time", // 按时间逆序 Oldest = "time-rev", } export const enum ResumeMode { Append = "append", Overwrite = "overwrite", OverwriteDefault = "overwrite-default", } ================================================ FILE: src/constants/globalStyle.ts ================================================ import { StyleSheet } from "react-native"; const globalStyle = StyleSheet.create({ /** flex 1 */ flex1: { flex: 1, }, /** 满宽度 flex1 */ fwflex1: { width: "100%", flex: 1, }, /** row 满宽度 flex1 */ rowfwflex1: { width: "100%", flex: 1, flexDirection: "row", }, /** 居中 */ fullCenter: { width: "100%", flex: 1, justifyContent: "center", alignItems: "center", }, notShrink: { flexShrink: 0, flexGrow: 0, }, grow: { flexShrink: 0, flexGrow: 1, }, } as const); export default globalStyle; ================================================ FILE: src/constants/pathConst.ts ================================================ import { Platform } from "react-native"; import RNFS, { CachesDirectoryPath } from "react-native-fs"; export const basePath = Platform.OS === "android" ? RNFS.ExternalDirectoryPath : RNFS.DocumentDirectoryPath; export default { basePath, pluginPath: `${basePath}/plugins/`, logPath: `${basePath}/log/`, dataPath: `${basePath}/data/`, cachePath: `${basePath}/cache/`, musicCachePath: CachesDirectoryPath + "/TrackPlayer", imageCachePath: CachesDirectoryPath + "/image_manager_disk_cache", localLrcPath: `${basePath}/local_lrc/`, lrcCachePath: `${basePath}/cache/lrc/`, downloadCachePath: `${basePath}/cache/download/`, downloadPath: `${basePath}/download/`, downloadMusicPath: `${basePath}/download/music/`, mmkvPath: `${basePath}/mmkv`, mmkvCachePath: `${basePath}/cache/mmkv`, }; ================================================ FILE: src/constants/repeatModeConst.ts ================================================ export enum MusicRepeatMode { /** 随机播放 */ SHUFFLE = "SHUFFLE", /** 列表循环 */ QUEUE = "QUEUE", /** 单曲循环 */ SINGLE = "SINGLE", } export default { [MusicRepeatMode.QUEUE]: { icon: "repeat-song-1", text: "列表循环", }, [MusicRepeatMode.SINGLE]: { icon: "repeat-song", text: "单曲循环", }, [MusicRepeatMode.SHUFFLE]: { icon: "shuffle", text: "随机播放", }, } as const; ================================================ FILE: src/constants/uiConst.ts ================================================ import { CustomizedColors } from "@/hooks/useColors"; import rpx from "@/utils/rpx"; const fontSizeConst = { /** 标签 */ tag: rpx(20), /** 描述文本等字体 */ description: rpx(22), /** 副标题 */ subTitle: rpx(26), /** 正文字体 */ content: rpx(28), /** 标题字体 */ title: rpx(32), /** appbar的字体 */ appbar: rpx(36), }; const fontWeightConst = { regular: "400", medium: "500", semibold: "600", bold: "700", bolder: "800", } as const; const iconSizeConst = { small: rpx(30), light: rpx(36), normal: rpx(42), big: rpx(60), large: rpx(72), }; type ColorKey = "normal" | "secondary" | "highlight" | "primary"; const colorMap: Record = { normal: "text", secondary: "textSecondary", highlight: "textHighlight", primary: "primary", } as const; export { fontSizeConst, fontWeightConst, iconSizeConst, colorMap }; export type { ColorKey }; ================================================ FILE: src/core/appConfig.ts ================================================ import { useMMKVObject } from "react-native-mmkv"; import { getStorage, removeStorage } from "@/utils/storage"; import getOrCreateMMKV from "@/utils/getOrCreateMMKV.ts"; import type { AppConfigPropertyKey, IAppConfig, IAppConfigProperties } from "@/types/core/config"; import { safeStringify } from "@/utils/jsonUtil"; const configStore = getOrCreateMMKV("App.config"); class AppConfig implements IAppConfig { // 迁移函数 private async migrateConfig(): Promise { const schemaVersion = !configStore.contains("$schema") ? 0 : parseInt(configStore.getString("$schema") || "0", 10); if (schemaVersion < 1) { // 获取旧配置 const oldConfig = await getStorage("local-config"); // 如果没有旧配置,直接初始化新配置 if (!oldConfig) { configStore.set("$schema", "1"); return; } // 迁移每个字段 const mapping: [string, AppConfigPropertyKey][] = [ // Basic [ "setting.basic.autoPlayWhenAppStart", "basic.autoPlayWhenAppStart", ], [ "setting.basic.useCelluarNetworkPlay", "basic.useCelluarNetworkPlay", ], [ "setting.basic.useCelluarNetworkDownload", "basic.useCelluarNetworkDownload", ], ["setting.basic.maxDownload", "basic.maxDownload"], ["setting.basic.clickMusicInSearch", "basic.clickMusicInSearch"], ["setting.basic.clickMusicInAlbum", "basic.clickMusicInAlbum"], ["setting.basic.downloadPath", "basic.downloadPath"], ["setting.basic.notInterrupt", "basic.notInterrupt"], ["setting.basic.tempRemoteDuck", "basic.tempRemoteDuck"], ["setting.basic.autoStopWhenError", "basic.autoStopWhenError"], ["setting.basic.pluginCacheControl", "basic.pluginCacheControl"], ["setting.basic.maxCacheSize", "basic.maxCacheSize"], ["setting.basic.defaultPlayQuality", "basic.defaultPlayQuality"], ["setting.basic.playQualityOrder", "basic.playQualityOrder"], [ "setting.basic.defaultDownloadQuality", "basic.defaultDownloadQuality", ], [ "setting.basic.downloadQualityOrder", "basic.downloadQualityOrder", ], ["setting.basic.musicDetailDefault", "basic.musicDetailDefault"], ["setting.basic.musicDetailAwake", "basic.musicDetailAwake"], ["setting.basic.debug.errorLog", "debug.errorLog"], ["setting.basic.debug.traceLog", "debug.traceLog"], ["setting.basic.debug.devLog", "debug.devLog"], ["setting.basic.maxHistoryLen", "basic.maxHistoryLen"], ["setting.basic.autoUpdatePlugin", "basic.autoUpdatePlugin"], [ "setting.basic.notCheckPluginVersion", "basic.notCheckPluginVersion", ], ["setting.basic.associateLyricType", "basic.associateLyricType"], [ "setting.basic.showExitOnNotification", "basic.showExitOnNotification", ], [ "setting.basic.musicOrderInLocalSheet", "basic.musicOrderInLocalSheet", ], [ "setting.basic.tryChangeSourceWhenPlayFail", "basic.tryChangeSourceWhenPlayFail", ], // Lyric ["setting.lyric.showStatusBarLyric", "lyric.showStatusBarLyric"], ["setting.lyric.topPercent", "lyric.topPercent"], ["setting.lyric.leftPercent", "lyric.leftPercent"], ["setting.lyric.align", "lyric.align"], ["setting.lyric.color", "lyric.color"], ["setting.lyric.backgroundColor", "lyric.backgroundColor"], ["setting.lyric.widthPercent", "lyric.widthPercent"], ["setting.lyric.fontSize", "lyric.fontSize"], ["setting.lyric.detailFontSize", "lyric.detailFontSize"], ["setting.lyric.autoSearchLyric", "lyric.autoSearchLyric"], // Theme ["setting.theme.background", "theme.background"], ["setting.theme.backgroundOpacity", "theme.backgroundOpacity"], ["setting.theme.backgroundBlur", "theme.backgroundBlur"], ["setting.theme.colors", "theme.colors"], ["setting.theme.customColors", "theme.customColors"], ["setting.theme.followSystem", "theme.followSystem"], ["setting.theme.selectedTheme", "theme.selectedTheme"], // Backup ["setting.backup.resumeMode", "backup.resumeMode"], // Plugin ["setting.plugin.subscribeUrl", "plugin.subscribeUrl"], // WebDAV ["setting.webdav.url", "webdav.url"], ["setting.webdav.username", "webdav.username"], ["setting.webdav.password", "webdav.password"], ]; // 执行迁移 function getPathValue(obj: Record, path: string) { const keys = path.split("."); let tmp = obj; for (let i = 0; i < keys.length; ++i) { tmp = tmp?.[keys[i]]; } return tmp; } mapping.forEach(([oldPath, newKey]) => { const value = getPathValue(oldConfig, oldPath); if (value !== undefined) { configStore.set(newKey, safeStringify(value)); } }); // 设置版本标识 configStore.set("$schema", "1"); // 清理旧配置 await removeStorage("local-config"); // 根据需求决定是否删除旧配置 } if (schemaVersion < 2) { // @ts-expect-error 兼容旧版本 if (this.getConfig("basic.clickMusicInSearch") === "播放歌曲") { this.setConfig("basic.clickMusicInSearch", "playMusic"); } else { this.setConfig("basic.clickMusicInSearch", "playMusicAndReplace"); } // @ts-expect-error 兼容旧版本 if (this.getConfig("basic.clickMusicInAlbum") === "播放专辑") { this.setConfig("basic.clickMusicInAlbum", "playAlbum"); } else { this.setConfig("basic.clickMusicInAlbum", "playMusic"); } // @ts-expect-error 兼容旧版本 if (this.getConfig("basic.tempRemoteDuck") === "暂停") { this.setConfig("basic.tempRemoteDuck", "pause"); } else { this.setConfig("basic.tempRemoteDuck", "lowerVolume"); } configStore.set("$schema", "2"); } } async setup(): Promise { await this.migrateConfig(); } setConfig( key: K, value?: IAppConfigProperties[K] | undefined, ): void { if (value === undefined) { configStore.delete(key); } else { configStore.set(key, safeStringify(value)); } } getConfig( key: K, ): IAppConfigProperties[K] | undefined { const value = configStore.getString(key); if (value === undefined) { return undefined; } return JSON.parse(value); } } const appConfig = new AppConfig(); export default appConfig; /***** hooks *****/ export function useAppConfig(key: K): IAppConfigProperties[K] | undefined { return useMMKVObject(key, configStore)[0]; } ================================================ FILE: src/core/appMeta.ts ================================================ import getOrCreateMMKV from "@/utils/getOrCreateMMKV"; class AppMeta { private getAppMeta(key: string) { const metaMMKV = getOrCreateMMKV("App.meta"); return metaMMKV.getString(key); } private setAppMeta(key: string, value: any) { const metaMMKV = getOrCreateMMKV("App.meta"); return metaMMKV.set(key, value); } /// 歌单的版本号 get musicSheetVersion(): number { const version = this.getAppMeta("MusicSheetVersion"); if (version?.length) { return +version; } return 0; } setMusicSheetVersion(version: number) { this.setAppMeta("MusicSheetVersion", "" + version); } get historySheetVersion(): number { const version = this.getAppMeta("HistorySheetVersion"); if (version?.length) { return +version; } return 0; } setHistorySheetVersion(version: number) { this.setAppMeta("HistorySheetVersion", "" + version); } } const appMeta = new AppMeta(); export default appMeta; ================================================ FILE: src/core/backup.ts ================================================ /** 备份与恢复 */ /** 歌单、插件 */ import { compare } from "compare-versions"; import PluginManager from "./pluginManager"; import MusicSheet from "@/core/musicSheet"; import { ResumeMode } from "@/constants/commonConst.ts"; /** * 结果:一份大的json文件 * { * musicSheets: [], * plugins: [], * } */ interface IBackJson { musicSheets: IMusic.IMusicSheetItem[]; plugins: Array<{ srcUrl: string; version: string }>; } function backup() { const musicSheets = MusicSheet.backupSheets(); const plugins = PluginManager.getEnabledPlugins(); const normalizedPlugins = plugins.map(_ => ({ srcUrl: _.instance.srcUrl, version: _.instance.version, })); return JSON.stringify({ musicSheets: musicSheets, plugins: normalizedPlugins, }); } async function resume( raw: string | Object, resumeMode: ResumeMode = ResumeMode.Append, ) { let obj: IBackJson; if (typeof raw === "string") { obj = JSON.parse(raw); } else { obj = raw as IBackJson; } const { plugins, musicSheets } = obj ?? {}; /** 恢复插件 */ const validPlugins = PluginManager.getEnabledPlugins(); const resumePlugins = plugins?.map(_ => { // 校验是否安装过: 同源且本地版本更高就忽略掉 if ( validPlugins.find( plugin => plugin.instance.srcUrl === _.srcUrl && compare( plugin.instance.version ?? "0.0.0", _.version ?? "0.0.1", ">=", ), ) ) { return; } return PluginManager.installPluginFromUrl(_.srcUrl); }); /** 恢复歌单 */ const resumeMusicSheets = MusicSheet.resumeSheets(musicSheets, resumeMode); return Promise.all([...(resumePlugins ?? []), resumeMusicSheets]); } const Backup = { backup, resume, }; export default Backup; ================================================ FILE: src/core/downloader.ts ================================================ import { internalSerializeKey, supportLocalMediaType } from "@/constants/commonConst"; import pathConst from "@/constants/pathConst"; import { IAppConfig } from "@/types/core/config"; import { IInjectable } from "@/types/infra"; import { addFileScheme, escapeCharacter, mkdirR } from "@/utils/fileUtils"; import { errorLog } from "@/utils/log"; import { patchMediaExtra } from "@/utils/mediaExtra"; import { getMediaUniqueKey, isSameMediaItem } from "@/utils/mediaUtils"; import network from "@/utils/network"; import { getQualityOrder } from "@/utils/qualities"; import EventEmitter from "eventemitter3"; import { atom, getDefaultStore, useAtomValue } from "jotai"; import { nanoid } from "nanoid"; import path from "path-browserify"; import { useEffect, useState } from "react"; import { copyFile, downloadFile, exists, unlink } from "react-native-fs"; import LocalMusicSheet from "./localMusicSheet"; import { IPluginManager } from "@/types/core/pluginManager"; export enum DownloadStatus { // 等待下载 Pending, // 准备下载链接 Preparing, // 下载中 Downloading, // 下载完成 Completed, // 下载失败 Error } export enum DownloaderEvent { // 某次下载行为出错 DownloadError = "download-error", // 下载任务更新 DownloadTaskUpdate = "download-task-update", // 下载某个音乐时出错 DownloadTaskError = "download-task-error", // 下载完成 DownloadQueueCompleted = "download-queue-completed", } export enum DownloadFailReason { /** 无网络 */ NetworkOffline = "network-offline", /** 设置-禁止在移动网络下下载 */ NotAllowToDownloadInCellular = "not-allow-to-download-in-cellular", /** 无法获取到媒体源 */ FailToFetchSource = "no-valid-source", /** 没有文件写入的权限 */ NoWritePermission = "no-write-permission", Unknown = "unknown", } interface IDownloadTaskInfo { // 状态 status: DownloadStatus; // 目标文件名 filename: string; // 下载id jobId?: number; // 下载音质 quality?: IMusic.IQualityKey; // 文件大小 fileSize?: number; // 已下载大小 downloadedSize?: number; // 音乐信息 musicItem: IMusic.IMusicItem; // 如果下载失败,下载失败的原因 errorReason?: DownloadFailReason; } const downloadQueueAtom = atom([]); const downloadTasks = new Map(); interface IEvents { /** 某次下载行为出现报错 */ [DownloaderEvent.DownloadError]: (reason: DownloadFailReason, error?: Error) => void; /** 下载某个媒体时报错 */ [DownloaderEvent.DownloadTaskError]: (reason: DownloadFailReason, mediaItem: IMusic.IMusicItem, error?: Error) => void; /** 下载任务更新 */ [DownloaderEvent.DownloadTaskUpdate]: (task: IDownloadTaskInfo) => void; /** 下载队列清空 */ [DownloaderEvent.DownloadQueueCompleted]: () => void; } class Downloader extends EventEmitter implements IInjectable { private configService!: IAppConfig; private pluginManagerService!: IPluginManager; private downloadingCount = 0; private static generateFilename(musicItem: IMusic.IMusicItem) { return `${escapeCharacter(musicItem.platform)}@${escapeCharacter( musicItem.id, )}@${escapeCharacter(musicItem.title)}@${escapeCharacter( musicItem.artist, )}`.slice(0, 200); } injectDependencies(configService: IAppConfig, pluginManager: IPluginManager): void { this.configService = configService; this.pluginManagerService = pluginManager; } private updateDownloadTask(musicItem: IMusic.IMusicItem, patch: Partial) { const newValue = { ...downloadTasks.get(getMediaUniqueKey(musicItem)), ...patch, } as IDownloadTaskInfo; downloadTasks.set(getMediaUniqueKey(musicItem), newValue); this.emit(DownloaderEvent.DownloadTaskUpdate, newValue); return newValue; } // 开始下载 private markTaskAsStarted(musicItem: IMusic.IMusicItem) { this.downloadingCount++; this.updateDownloadTask(musicItem, { status: DownloadStatus.Preparing, }); } private markTaskAsCompleted(musicItem: IMusic.IMusicItem) { this.downloadingCount--; this.updateDownloadTask(musicItem, { status: DownloadStatus.Completed, }); } private markTaskAsError(musicItem: IMusic.IMusicItem, reason: DownloadFailReason, error?: Error) { this.downloadingCount--; this.updateDownloadTask(musicItem, { status: DownloadStatus.Error, errorReason: reason, }); this.emit(DownloaderEvent.DownloadTaskError, reason, musicItem, error); } /** 匹配文件后缀 */ private getExtensionName(url: string) { const regResult = url.match( /^https?\:\/\/.+\.([^\?\.]+?$)|(?:([^\.]+?)\?.+$)/, ); if (regResult) { return regResult[1] ?? regResult[2] ?? "mp3"; } else { return "mp3"; } }; /** 获取下载路径 */ private getDownloadPath(fileName: string) { const dlPath = this.configService.getConfig("basic.downloadPath") ?? pathConst.downloadMusicPath; if (!dlPath.endsWith("/")) { return `${dlPath}/${fileName ?? ""}`; } return fileName ? dlPath + fileName : dlPath; }; /** 获取缓存的下载路径 */ private getCacheDownloadPath(fileName: string) { const cachePath = pathConst.downloadCachePath; if (!cachePath.endsWith("/")) { return `${cachePath}/${fileName ?? ""}`; } return fileName ? cachePath + fileName : cachePath; } private async downloadNextPendingTask() { const maxDownloadCount = Math.max(1, Math.min(+(this.configService.getConfig("basic.maxDownload") || 3), 10)); const downloadQueue = getDefaultStore().get(downloadQueueAtom); // 如果超过最大下载数量,或者没有下载任务,则不执行 if (this.downloadingCount >= maxDownloadCount || this.downloadingCount >= downloadQueue.length) { return; } // 寻找下一个pending task let nextTask: IDownloadTaskInfo | null = null; for (let i = 0; i < downloadQueue.length; i++) { const musicItem = downloadQueue[i]; const key = getMediaUniqueKey(musicItem); const task = downloadTasks.get(key); if (task && task.status === DownloadStatus.Pending) { nextTask = task; break; } } // 没有下一个任务了 if (!nextTask) { if (this.downloadingCount === 0) { this.emit(DownloaderEvent.DownloadQueueCompleted); } return; } const musicItem = nextTask.musicItem; // 更新下载状态 this.markTaskAsStarted(musicItem); let url = musicItem.url; let headers = musicItem.headers; const plugin = this.pluginManagerService.getByName(musicItem.platform); try { if (plugin) { const qualityOrder = getQualityOrder( nextTask.quality ?? this.configService.getConfig("basic.defaultDownloadQuality") ?? "standard", this.configService.getConfig("basic.downloadQualityOrder") ?? "asc", ); let data: IPlugin.IMediaSourceResult | null = null; for (let quality of qualityOrder) { try { data = await plugin.methods.getMediaSource( musicItem, quality, 1, true, ); if (!data?.url) { continue; } break; } catch { } } url = data?.url ?? url; headers = data?.headers; } if (!url) { throw new Error(DownloadFailReason.FailToFetchSource); } } catch (e: any) { /** 无法下载,跳过 */ errorLog("下载失败-无法获取下载链接", { item: { id: musicItem.id, title: musicItem.title, platform: musicItem.platform, quality: nextTask.quality, }, reason: e?.message ?? e, }); if (e.message === DownloadFailReason.FailToFetchSource) { this.markTaskAsError(musicItem, DownloadFailReason.FailToFetchSource, e); } else { this.markTaskAsError(musicItem, DownloadFailReason.Unknown, e); } return; } // 预处理完成,可以开始处理下一个任务 this.downloadNextPendingTask(); // 下载逻辑 // 识别文件后缀 let extension = this.getExtensionName(url); if (supportLocalMediaType.every(item => item !== ("." + extension))) { extension = "mp3"; } // 缓存下载地址 const cacheDownloadPath = addFileScheme( this.getCacheDownloadPath(`${nanoid()}.${extension}`), ); // 真实下载地址 const targetDownloadPath = addFileScheme( this.getDownloadPath(`${nextTask.filename}.${extension}`), ); // 检测下载位置是否存在 try { const folder = path.dirname(targetDownloadPath); const folderExists = await exists(folder); if (!folderExists) { await mkdirR(folder); } } catch (e: any) { this.emit(DownloaderEvent.DownloadTaskError, DownloadFailReason.NoWritePermission, musicItem, e); return; } // 下载 const { promise } = downloadFile({ fromUrl: url ?? "", toFile: cacheDownloadPath, headers: headers, background: true, begin: (res) => { this.updateDownloadTask(musicItem, { status: DownloadStatus.Downloading, downloadedSize: 0, fileSize: res.contentLength, jobId: res.jobId, }); }, progress: (res) => { this.updateDownloadTask(musicItem, { status: DownloadStatus.Downloading, downloadedSize: res.bytesWritten, fileSize: res.contentLength, jobId: res.jobId, }); }, }); try { await promise; // 下载完成,移动文件 await copyFile(cacheDownloadPath, targetDownloadPath); LocalMusicSheet.addMusic({ ...musicItem, [internalSerializeKey]: { localPath: targetDownloadPath, }, }); patchMediaExtra(musicItem, { downloaded: true, localPath: targetDownloadPath, }); this.markTaskAsCompleted(musicItem); } catch (e: any) { this.markTaskAsError(musicItem, DownloadFailReason.Unknown, e); } // 清理工作 await unlink(cacheDownloadPath); this.downloadNextPendingTask(); // 如果任务状态是完成,则从队列中移除 const key = getMediaUniqueKey(musicItem); if (downloadTasks.get(key)?.status === DownloadStatus.Completed) { downloadTasks.delete(key); const downloadQueue = getDefaultStore().get(downloadQueueAtom); const newDownloadQueue = downloadQueue.filter(item => !isSameMediaItem(item, musicItem)); getDefaultStore().set(downloadQueueAtom, newDownloadQueue); } } download(musicItems: IMusic.IMusicItem | IMusic.IMusicItem[], quality?: IMusic.IQualityKey) { if (network.isOffline) { this.emit(DownloaderEvent.DownloadError, DownloadFailReason.NetworkOffline); return; } if (network.isCellular && !this.configService.getConfig("basic.useCelluarNetworkDownload")) { this.emit(DownloaderEvent.DownloadError, DownloadFailReason.NotAllowToDownloadInCellular); return; } // 整理成数组 if (!Array.isArray(musicItems)) { musicItems = [musicItems]; } // 防止重复下载 musicItems = musicItems.filter(m => { const key = getMediaUniqueKey(m); // 如果存在下载任务 if (downloadTasks.has(key)) { return false; } // TODO: 如果已经下载了,也应该返回false if (LocalMusicSheet.isLocalMusic(m)) { return false; } // 设置下载任务 downloadTasks.set(getMediaUniqueKey(m), { status: DownloadStatus.Pending, filename: Downloader.generateFilename(m), quality: quality, musicItem: m, }); return true; }); if (!musicItems.length) { return; } // 添加进任务队列 const downloadQueue = getDefaultStore().get(downloadQueueAtom); const newDownloadQueue = [...downloadQueue, ...musicItems]; getDefaultStore().set(downloadQueueAtom, newDownloadQueue); this.downloadNextPendingTask(); } remove(musicItem: IMusic.IMusicItem) { // 删除下载任务 const key = getMediaUniqueKey(musicItem); const task = downloadTasks.get(key); if (!task) { return false; } if (task.status === DownloadStatus.Pending || task.status === DownloadStatus.Error) { downloadTasks.delete(key); const downloadQueue = getDefaultStore().get(downloadQueueAtom); const newDownloadQueue = downloadQueue.filter(item => !isSameMediaItem(item, musicItem)); getDefaultStore().set(downloadQueueAtom, newDownloadQueue); return true; } return false; } } const downloader = new Downloader(); export default downloader; export function useDownloadTask(musicItem: IMusic.IMusicItem) { const [downloadStatus, setDownloadStatus] = useState(downloadTasks.get(getMediaUniqueKey(musicItem)) ?? null); useEffect(() => { const callback = (task: IDownloadTaskInfo) => { if (isSameMediaItem(task?.musicItem, musicItem)) { setDownloadStatus(task); } }; downloader.on(DownloaderEvent.DownloadTaskUpdate, callback); return () => { downloader.off(DownloaderEvent.DownloadTaskUpdate, callback); }; }, [musicItem]); return downloadStatus; } export const useDownloadQueue = () => useAtomValue(downloadQueueAtom); ================================================ FILE: src/core/i18n/index.ts ================================================ import type { ILanguage, ILanguageData } from "@/types/core/i18n"; import { atom, getDefaultStore, useAtomValue } from "jotai"; import PersistStatus from "@/utils/persistStatus"; import zhCN from "./languages/zh-cn.json"; import enUS from "./languages/en-us.json"; import zhTW from "./languages/zh-tw.json"; const allLanguages: ILanguage[] = [{ locale: "zh-CN", name: "简体中文", languageData: zhCN, }, { locale: "zh-TW", name: "繁体中文", languageData: zhTW, }, { locale: "en-US", name: "English", languageData: enUS, }]; const defaultLocale = PersistStatus.get("app.language") || "zh-CN"; const currentLanguageAtom = atom(allLanguages.find(item => item.locale === defaultLocale) ?? allLanguages[0]); class I18N { setup() { } getSupportedLanguages() { return allLanguages; } getLanguage() { return getDefaultStore().get(currentLanguageAtom); } setLanguage(locale: string) { const language = allLanguages.find(item => item.locale === locale) ?? allLanguages[0]; getDefaultStore().set(currentLanguageAtom, language); PersistStatus.set("app.language", language.locale); } t(key: K, args?: Record): ILanguageData[K] { const language = getDefaultStore().get(currentLanguageAtom); if (!language) { return ""; } const value = language.languageData[key] ?? allLanguages[0].languageData[key] ?? ""; if (!args) { return value as ILanguageData[K]; } return value.replace(/{(\w+)}/g, (_, argKey) => args[argKey] ?? ""); } } const i18n = new I18N(); export default i18n; export function useI18N(): I18N { useAtomValue(currentLanguageAtom); // 用来通知组件刷新 return i18n; } ================================================ FILE: src/core/i18n/languages/en-us.json ================================================ { "common.setting": "Settings", "common.software": "Software", "common.language": "Language", "common.theme": "Theme", "common.other": "Other", "common.cancel": "Cancel", "common.about": "About", "common.batchEdit": "Batch Edit", "common.selectAll": "Select All", "common.unselectAll": "Unselect All", "common.save": "Save", "common.play": "Play", "common.download": "Download", "common.delete": "Delete", "common.unknownName": "Unnamed", "common.default": "Default", "common.search": "Search", "common.clear": "Clear", "common.singleMusic": "Single", "common.album": "Album", "common.artist": "Artist", "common.sheet": "Playlist", "common.done": "Done", "common.edit": "Edit", "common.local": "Local", "common.sure": "OK", "common.confirm": "Confirm", "common.view": "View", "common.open": "Open", "common.username": "Username", "common.password": "Password", "common.cover": "Cover", "common.name": "Name", "common.comment": "Comment", "sidebar.basicSettings": "Basic Settings", "sidebar.pluginManagement": "Plugin Management", "sidebar.themeSettings": "Theme Settings", "sidebar.scheduleClose": "Schedule Close", "sidebar.backupAndResume": "Backup & Restore", "sidebar.permissionManagement": "Permission Management", "sidebar.checkUpdate": "Check Update", "sidebar.currentVersion": "V", "sidebar.backToDesktop": "Back to Desktop", "sidebar.exitApp": "Exit App", "sidebar.languageSettings": "Language Settings", "checkUpdate.error.latestVersion": "Already the latest version", "home.recommendSheet": "Recommended Playlists", "home.topList": "Charts", "home.playHistory": "Play History", "home.localMusic": "Local Music", "home.openSidebar.a11y": "Open Sidebar", "home.myPlaylists": "My Playlists", "home.starredPlaylists": "Starred Playlists", "home.newPlaylist.a11y": "New Playlist", "home.importPlaylist.a11y": "Import Playlist", "home.myPlaylistsCount.a11y": "My Playlists, {count} total", "home.starredPlaylistsCount.a11y": "Starred Playlists, {count} total", "home.songCount": "{count} songs", "home.clickToSearch": "Click here to start searching", "dialog.deleteSheetTitle": "Delete Playlist", "dialog.deleteSheetContent": "Are you sure to delete playlist「{name}」?", "toast.deleteSuccess": "Deleted successfully", "toast.hasStarred": "Playlist starred", "toast.hasUnstarred": "Playlist unstarred", "toast.importSuccess": "Imported successfully", "toast.saveSuccess": "Saved successfully", "toast.sortHasBeenUpdated": "Sort order updated", "toast.currentQualityNotAvailableForCurrentMusic": "Current quality not available for this song", "toast.commmentNotAvaliableForCurrentMusic": "No comments available for current song", "toast.addToNextPlay": "Added to play next", "toast.beginDownload": "Download started, please don't close the app until all downloads complete", "toast.rememberToSave": "Remember to save~", "localMusic.scanLocalMusic": "Scan Local Music", "localMusic.beginScan": "Start Scan", "localMusic.downloadList": "Download List", "lyric.lyricLinkedFrom": "Lyrics linked from「{platform} - {title}」", "lyric.unlinkLyric": "Unlink Lyrics", "lyric.noLyric": "No lyrics available", "lyric.searchLyric": "Search Lyrics", "musicListEditor.selectMusicCount": "{count} songs selected", "musicListEditor.addToNextPlay": "Play Next", "musicListEditor.addToSheet": "Add to Playlist", "permissionSetting.title": "Permission Management", "permissionSetting.description": "This lists all permissions required by this app. You can enable or disable certain permissions here.", "permissionSetting.floatWindowPermission": "Float Window Permission", "permissionSetting.floatWindowPermissionDescription": "Used to display desktop lyrics", "permissionSetting.fileReadWritePermission": "File Read/Write Permission", "permissionSetting.fileReadWritePermissionDescription": "Used to download songs and cache data", "recommendSheet.title": "Recommended", "searchMusicList.searchPlaceHolder": "Search songs in list", "searchMusicList.searchLabel.a11y": "Search Box", "searchPage.searchPlaceHolder": "Enter song to search", "searchPage.searchLabel.a11y": "Search Box", "searchPage.history": "History", "searchPage.artistResultWorksNum": "{count} works", "searchPage.comingSoon": "Coming Soon", "topList.title": "Charts", "sheetDetail.totalMusicCount": "{count} songs total", "sheetDetail.editSheetInfo": "Edit Playlist Info", "sheetDetail.batchEditMusic": "Batch Edit Songs", "sheetDetail.sortMusic": "Sort Songs", "sheetDetail.sortMusicOption.byTitle": "Sort by Song Title", "sheetDetail.sortMusicOption.byArtist": "Sort by Artist", "sheetDetail.sortMusicOption.byAlbum": "Sort by Album", "sheetDetail.sortMusicOption.newest": "Sort by Add Time (Newest First)", "sheetDetail.sortMusicOption.oldest": "Sort by Add Time (Oldest First)", "sheetDetail.deleteSheet": "Delete Playlist", "sheetDetail.deleteSheetContent": "Are you sure to delete playlist「{name}」?", "history.title": "Play History", "history.clearHistory": "Clear Play History", "downloading.title": "Downloading", "downloading.downloadFailReason.noWritePermission": "No write permission", "downloading.downloadFailReason.failToFetchSource": "Failed to fetch music source", "downloading.downloadFailReason.unknown": "Unknown error", "downloading.downloadStatus.completed": "Download completed", "downloading.downloadStatus.downloadProgress": "Downloading: {progress} / {totalSize}", "downloading.downloadStatus.pending": "Waiting to download", "downloading.downloadStatus.preparing": "Getting music resource link", "artistDetail.fansCount": "Fans: {count}", "artistDetail.menu.batchEditMusic": "Batch Edit Songs", "artistDetail.musicSheet": "{artist} - Singles", "pluginSetting.pluginItem.options.updatePlugin": "Update Plugin", "pluginSetting.pluginItem.options.sharePlugin": "Share Plugin", "pluginSetting.pluginItem.options.uninstallPlugin": "Uninstall Plugin", "pluginSetting.pluginItem.options.uninstallPluginContent": "Are you sure to uninstall plugin「{name}」?", "pluginSetting.pluginItem.options.alternativePlugin": "Plugin Redirect", "pluginSetting.pluginItem.alternativePlugin": "This plugin actually uses「{name}」plugin to parse music sources", "pluginSetting.pluginItem.dialog.setAlternativePluginTitle": "Set Plugin Redirect", "pluginSetting.pluginItem.dialog.setAlternativePluginTip": "The selected plugin will be used to parse music sources for this plugin\nRandom settings may cause songs to fail to play, please operate with caution", "pluginSetting.pluginItem.options.importMusic": "Import Song", "pluginSetting.pluginItem.options.importMusicPlaceHolder": "Enter target song", "pluginSetting.pluginItem.options.importDialogTitle": "Prepare to Import", "pluginSetting.pluginItem.options.importMusicDialogContent": "Found song「{name}」, import it?", "pluginSetting.pluginItem.options.importMusicToSheetName": "{name} Imported Songs", "pluginSetting.pluginItem.options.importSheet": "Import Playlist", "pluginSetting.pluginItem.options.importSheetPlaceHolder": "Enter target playlist", "pluginSetting.pluginItem.options.importSheetDialogContent": "Found {count} songs, import them?", "pluginSetting.pluginItem.options.userVariables": "User Variables", "pluginSetting.pluginItem.versionHint": "Version: {version}", "pluginSetting.pluginItem.author": "Author: {author}", "pluginSetting.menu.subscriptionSetting": "Subscription Settings", "pluginSetting.menu.sort": "Plugin Sort", "pluginSetting.menu.uninstallAll": "Uninstall All Plugins", "pluginSetting.menu.uninstallAllContent": "Are you sure to uninstall all plugins? This action cannot be undone!", "pluginSetting.menu.installPlugin": "Install Plugin", "pluginSetting.menu.installPluginDialogPlaceholder": "Enter plugin URL", "pluginSetting.menu.pluginInstallFailedDialogTitle": "Plugin Installation Failed", "pluginSetting.menu.pluginUpdateFailedDialogTitle": "Plugin Update Failed", "pluginSetting.fabOptions.installFromLocal": "Install Plugin from Local", "pluginSetting.fabOptions.installFromNetwork": "Install Plugin from Network", "pluginSetting.fabOptions.updateAllPlugins": "Update All Plugins", "pluginSetting.fabOptions.updateSubscription": "Update Subscription", "pluginSetting.failReason": "Failure reason: {reason}", "pluginSetting.pluginInstallFailedDialogContent": "The following plugins failed to install: \n {detail}", "pluginSetting.pluginUpdateFailedDialogContent": "The following plugins failed to update: \n {detail}", "toast.pluginUpdateSuccess": "Updated to latest version", "toast.failToUpdatePlugin": "Failed to update plugin", "toast.copiedToClipboard": "Copied to clipboard", "toast.copiedToClipboardFailed": "Copy failed", "toast.failToSharePlugin": "Failed to share plugin", "toast.pluginUninstalled": "Plugin uninstalled", "toast.toast.pluginUninstalled": "Failed to uninstall plugin", "toast.failToImportMusic": "Failed to import song", "toast.importing": "Importing...", "toast.failToImportSheet": "Failed to import playlist", "toast.settingSuccess": "Settings saved successfully~", "toast.installPluginSuccess": "Plugin installed successfully", "toast.updatePluginSuccess": "Plugin updated successfully", "toast.installPluginFail": "Plugin installation failed: {reason}", "toast.allPluginInstallFailed": "All plugins installation failed", "toast.partialPluginInstallFailed": "Some plugins installation failed", "toast.partialPluginInstallFailedWithReason": "Some plugins installation failed: {reason}", "toast.allPluginUpdateFailed": "All plugins update failed", "toast.partialPluginUpdateFailed": "Some plugins update failed", "toast.noSubscription": "No subscription", "toast.subscriptionInvalid": "Invalid subscription", "toast.subscriptionHaveToEndWithJs": "Subscription URL must end with .js or .json", "toast.unknownError": "Unknown error, please try again later: {reason}", "themeSettings.displayStyle": "Display Style", "themeSettings.followSystemTheme": "Follow System Dark Mode", "themeSettings.setTheme": "Theme Settings", "themeSettings.lightMode": "Light Mode", "themeSettings.darkMode": "Dark Mode", "themeSettings.customMode": "Custom Background", "setCustomTheme.customizeBackground": "Customize Background", "setCustomTheme.blur": "Blur", "setCustomTheme.opacity": "Opacity", "setCustomTheme.primaryColor": "Primary Color", "setCustomTheme.textColor": "Text Color", "setCustomTheme.appBarColor": "App Bar Background Color", "setCustomTheme.appBarTextColor": "App Bar Text Color", "setCustomTheme.musicBarColor": "Music Bar Background Color", "setCustomTheme.musicBarTextColor": "Music Bar Text Color", "setCustomTheme.pageBackgroundColor": "Page Background Color", "setCustomTheme.backdropColor": "Dialog & Overlay Background Color", "setCustomTheme.cardColor": "Card Background Color", "setCustomTheme.placeholderColor": "Input Field Background Color", "setCustomTheme.tabBarColor": "Tab Bar Background Color", "setCustomTheme.notificationColor": "Notification & Tips Background Color", "backupAndResume.beginBackup": "Start Backup", "backupAndResume.backupDialogTitle": "Backup Local Music", "backupAndResume.backuping": "Backing up...", "toast.backupSuccess": "Backup successful", "toast.backupFail": "Backup failed: {reason}", "backupAndResume.resumeFromLocalFile": "Restore from Local File", "backupAndResume.resuming": "Restoring...", "toast.resumeSuccess": "Restore successful", "toast.resumeFail": "Restore failed: {reason}", "backupAndResume.resumeFromUrlDialogTitle": "Restore from Remote URL", "backupAndResume.resumeFromUrlDialogPlaceHolder": "Enter URL ending with json or txt", "toast.backupFileNotFound": "Backup file not found", "toast.resumePreCheckFailed": "Please configure in「Webdav Settings」first, then restore", "backupAndResume.setResumeMode": "Set Restore Mode", "backupAndResume.resumeMode": "Restore Mode", "backupAndResume.localBackup": "Local Backup", "backupAndResume.backupToLocal": "Backup to Local", "backupAndResume.webdavSettings": "Webdav Settings", "backupAndResume.webdavUrl": "Webdav Server URL", "backupAndResume.backupToWebdav": "Backup to Webdav", "backupAndResume.resumeFromWebdav": "Restore from Webdav", "backupAndResume.resumeMode.append": "Restore as New Playlists", "backupAndResume.resumeMode.overwrite-default": "Merge Default Playlist, Others as New Playlists", "backupAndResume.resumeMode.overwrite": "Merge Same Name Playlists", "basicSettings.common": "General", "basicSettings.maxHistoryLength": "Maximum History Records", "basicSettings.musicDetailDefault": "When opening song detail page", "basicSettings.musicDetailDefault.album": "Show album cover by default", "basicSettings.musicDetailDefault.lyric": "Show lyrics page by default", "basicSettings.musicDetailAwake": "Keep screen on when in song detail page", "basicSettings.associateLyricType": "Associate Lyrics Method", "basicSettings.associateLyricType.input": "Input Song ID", "basicSettings.associateLyricType.search": "Search Lyrics", "basicSettings.showExitOnNotification": "Show close button in notification bar (Restart required)", "basicSettings.sheetAndAlbum": "Playlist & Album", "basicSettings.clickMusicInSearch": "When clicking song in search results", "basicSettings.clickMusicInSearch.playMusic": "Play Song", "basicSettings.clickMusicInSearch.playMusicAndReplace": "Play Song and Replace Playlist", "basicSettings.clickMusicInAlbum": "When clicking song in album", "basicSettings.clickMusicInAlbum.playMusic": "Play Song", "basicSettings.clickMusicInAlbum.playAlbum": "Play Album", "basicSettings.musicOrderInLocalSheet": "Default song order when creating new playlist", "basicSettings.musicOrderInLocalSheet.title": "Sort by Song Title", "basicSettings.musicOrderInLocalSheet.artist": "Sort by Artist", "basicSettings.musicOrderInLocalSheet.album": "Sort by Album", "basicSettings.musicOrderInLocalSheet.newest": "Sort by Add Time (Newest First)", "basicSettings.musicOrderInLocalSheet.oldest": "Sort by Add Time (Oldest First)", "basicSettings.plugin": "Plugin", "basicSettings.autoUpdatePlugin": "Auto update plugins on app start", "basicSettings.notCheckPluginVersion": "Don't check version when installing plugins", "basicSettings.lazyLoadPlugin": "Enable plugin lazy loading", "basicSettings.playback": "Playback", "basicSettings.notInterrupt": "Allow simultaneous playback with other apps", "basicSettings.autoPlayWhenAppStart": "Auto play when app starts", "basicSettings.tryChangeSourceWhenPlayFail": "Try different source when playback fails", "basicSettings.autoStopWhenError": "Auto pause when playback fails", "basicSettings.tempRemoteDuck": "When playback is temporarily interrupted", "basicSettings.tempRemoteDuck.pause": "Pause playback", "basicSettings.tempRemoteDuck.lowerVolume": "Lower volume", "basicSettings.tempRemoteDuck.volumeDecreaseLevel": "Volume Decrease Level", "basicSettings.defaultPlayQuality": "Default Playback Quality", "basicSettings.playQualityOrder": "When default playback quality is unavailable", "basicSettings.playQualityOrder.asc": "Play higher quality", "basicSettings.playQualityOrder.desc": "Play lower quality", "basicSettings.download": "Download", "basicSettings.downloadPath": "Download Path", "basicSettings.fileSelector.selectFolder": "Select Folder", "basicSettings.maxDownload": "Maximum Concurrent Downloads", "basicSettings.defaultDownloadQuality": "Default Download Quality", "basicSettings.downloadQualityOrder": "When default download quality is unavailable", "basicSettings.downloadQualityOrder.asc": "Download higher quality", "basicSettings.downloadQualityOrder.desc": "Download lower quality", "basicSettings.network": "Network", "basicSettings.useCelluarNetworkPlay": "Use cellular network for playback", "basicSettings.useCelluarNetworkDownload": "Use cellular network for downloads", "basicSettings.lyric": "Lyrics", "basicSettings.lyric.autoSearchLyric": "Auto search lyrics when missing", "basicSettings.lyric.showStatusBarLyric": "Enable desktop lyrics", "basicSettings.lyric.align": "Alignment", "basicSettings.lyric.align.left": "Left", "basicSettings.lyric.align.center": "Center", "basicSettings.lyric.align.right": "Right", "basicSettings.lyric.leftRightDistance": "Left/Right Distance", "basicSettings.lyric.topBottomDistance": "Top/Bottom Distance", "basicSettings.lyric.width": "Lyrics Width", "basicSettings.lyric.fontSize": "Font Size", "basicSettings.lyric.textColor": "Text Color", "basicSettings.lyric.backgroundColor": "Text Background Color", "basicSettings.cache": "Cache", "basicSettings.cache.musicCacheLimit": "Music Cache Limit", "basicSettings.cache.clearMusicCache": "Clear Music Cache", "basicSettings.cache.clearLyricCache": "Clear Lyrics Cache", "basicSettings.cache.clearImageCache": "Clear Image Cache", "basicSettings.developer": "Developer Options", "basicSettings.developer.errorLog": "Record Error Logs", "basicSettings.developer.traceLog": "Record Detailed Logs", "basicSettings.developer.devLog": "Debug Panel", "basicSettings.developer.viewErrorLog": "View Error Logs", "basicSettings.developer.clearLog": "Clear Logs", "dialog.loading.reinitializeTrackPlayer": "Initializing track player...", "dialog.setCacheTitle": "Set Cache", "dialog.setCachePlaceholder": "Enter cache limit, 100M-8192M, unit: M", "dialog.clearMusicCacheTitle": "Clear Music Cache", "dialog.clearMusicCacheContent": "Are you sure to clear music cache?", "dialog.clearLyricCacheTitle": "Clear Lyrics Cache", "dialog.clearLyricCacheContent": "Are you sure to clear lyrics cache?", "dialog.clearImageCacheTitle": "Clear Image Cache", "dialog.clearImageCacheContent": "Are you sure to clear image cache?", "dialog.errorLogTitle": "Error Logs", "dialog.errorLogNoRecord": "No records", "dialog.errorLogKnow": "I understand", "dialog.errorLogCopy": "Copy Logs", "dialog.setScheduleCloseTime.title": "Set Schedule Close Time", "dialog.setScheduleCloseTime.placeholder": "Enter time", "dialog.setScheduleCloseTime.unit": "minutes", "dialog.setScheduleCloseTime.hint": "Maximum 24 hours (1440 minutes) supported", "toast.cacheSetSuccess": "Settings saved successfully", "toast.musicCacheCleared": "Music cache cleared", "toast.lyricCacheCleared": "Lyrics cache cleared", "toast.imageCacheCleared": "Image cache cleared", "toast.logCleared": "Logs cleared", "toast.noFloatWindowPermission": "No float window permission", "toast.folderNotExistOrNoPermission": "Folder doesn't exist or no permission", "musicQuality.low": "Low Quality", "musicQuality.standard": "Standard Quality", "musicQuality.high": "High Quality", "musicQuality.super": "Super High Quality", "common.emptyList": "Nothing here~", "common.loading": "Loading...", "common.error": "Error...", "common.clickToRetry": "Click to retry", "common.failToLoad": "Failed to load", "common.listReachEnd": "~~~ End of list ~~~", "playAllBar.title": "Play All", "noPlugin.title": "No plugins installed yet", "noPlugin.titleWithType": "No plugins supporting「{type}」function installed yet", "noPlugin.description": "Go to「Sidebar - Plugin Management」to install plugins~", "dialog.checkStorage.title": "Storage Permission", "dialog.checkStorage.content.0": "MusicFree needs file read/write permission for playlist backup and song downloads.", "dialog.checkStorage.content.1": "Click「Grant Permission」to go to settings and grant file management permission.", "dialog.checkStorage.content.2": "If you don't need to backup playlists or download songs, you can skip this permission for now.", "dialog.checkStorage.content.3": "You can grant or revoke this permission anytime in Sidebar「Permission Management」->「File Read/Write Permission」.", "dialog.checkStorage.button.grantPermission": "Grant Permission", "dialog.checkStorage.button.doNotShowAgain": "Don't show again", "dialog.downloadDialog.title": "New version found ({version})", "dialog.downloadDialog.skipThisVersion": "Skip this version", "dialog.downloadDialog.downloadUsingBrowser": "Download with browser", "dialog.downloadDialog.backupUrl": "Backup link", "dialog.editSheetDetail.sheetName": "Playlist Name", "dialog.subscriptionPluginDialog.title": "Subscription", "dialog.markdownDialog.openExternalLink": "Open browser to visit the page. Please stay safe and beware of phishing websites.", "dialog.markdownDialog.clickToShowImage": "Click to show image", "dialog.markdownDialog.loadFailed": "Image load failed", "panel.playList.title": "Play List", "panel.playList.count": " ({count} songs)", "panel.searchLrc.inputPlaceholder": "Enter song name", "panel.searchLrc.toast.settingSuccess": "Settings saved successfully~", "panel.searchLrc.toast.failToSearch": "Settings failed!", "panel.addToMusicSheet.title": "Add to Playlist ({count} songs)", "panel.addToMusicSheet.newMusicSheet": "New Playlist", "panel.addToMusicSheet.count": "{count} songs", "panel.addToMusicSheet.toast.success": "Added to playlist", "panel.addToMusicSheet.toast.fail": "Failed to add to playlist", "panel.associateLrc.title": "Associate Lyrics", "panel.associateLrc.inputPlaceholder": "Enter song ID to associate lyrics", "panel.associateLrc.targetExpired": "Link expired, please copy again~", "panel.associateLrc.toast.success": "Lyrics associated successfully", "panel.associateLrc.toast.fail": "Failed to associate lyrics", "panel.associateLrc.toast.unlinkSuccess": "Lyrics unlinked successfully", "panel.createMusicSheet.title": "New Playlist", "panel.editMusicSheetInfo.title": "Edit Playlist Info", "panel.editMusicSheetInfo.sheetName": "Playlist Name", "panel.editMusicSheetInfo.toast.updateSuccess": "Playlist info updated successfully~", "panel.imageViewer.saveImage": "Save Image", "panel.imageViewer.saveImageSuccess": "Image saved to {path}", "panel.imageViewer.saveImageFail": "Failed to save image: {reason}", "panel.colorPicker.title": "Select Color", "panel.createMusicSheet.inputLabel": "Input Box", "panel.importMusicSheet.title": "Import Playlist", "panel.importMusicSheet.placeholder": "Enter target playlist", "panel.importMusicSheet.importing": "Importing...", "panel.importMusicSheet.prepareImport": "Prepare to Import", "panel.importMusicSheet.foundSongs": "Found {count} songs! Start importing now?", "panel.importMusicSheet.invalidLink": "Invalid link or target playlist is empty", "panel.musicItemLyricOptions.author": "Artist: {artist}", "panel.musicItemLyricOptions.album": "Album: {album}", "panel.musicItemLyricOptions.toggleDesktopLyric": "{status} Desktop Lyrics", "panel.musicItemLyricOptions.enableDesktopLyric": "Enable", "panel.musicItemLyricOptions.disableDesktopLyric": "Disable", "panel.musicItemLyricOptions.desktopLyricPermissionError": "Failed to enable desktop lyrics, no float window permission", "panel.musicItemLyricOptions.uploadLocalLyric": "Upload Local Lyrics", "panel.musicItemLyricOptions.uploadLocalLyricTranslation": "Upload Local Lyrics Translation", "panel.musicItemLyricOptions.deleteLocalLyric": "Delete Local Lyrics", "panel.musicItemLyricOptions.settingFail": "Settings failed: {reason}", "panel.musicItemLyricOptions.deleteFail": "Delete failed: {reason}", "panel.musicItemOptions.author": "Artist: {artist}", "panel.musicItemOptions.album": "Album: {album}", "panel.musicItemOptions.downloaded": "Downloaded", "panel.musicItemOptions.readComment": "Read Comments", "panel.musicItemOptions.deleteLocalDownload": "Delete Local Download", "panel.musicItemOptions.deleteLocalDownloadConfirm": "This will delete the downloaded local file, continue?", "panel.musicItemOptions.associatedLyric": "Associated lyrics {platform}@{id}", "panel.musicItemOptions.associateLyric": "Associate Lyrics", "panel.musicItemOptions.unassociateLyric": "Unassociate Lyrics", "panel.musicItemOptions.unassociateLyricSuccess": "Lyrics unassociated successfully", "panel.musicItemOptions.timingClose": "Timing Close", "panel.musicItemOptions.clearPluginCache": "Clear Plugin Cache (Use when playback error)", "panel.musicItemOptions.cacheCleared": "Cache cleared", "panel.musicItemOptions.deleteFailed": "Delete failed", "panel.musicQuality.title": "Set {type} Quality", "panel.searchLrc.unnamed": "(Unnamed)", "panel.searchLrc.notSupported": "Search Lyrics", "panel.setFontSize.title": "Set Font Size", "panel.setFontSize.small": "Small", "panel.setFontSize.standard": "Standard", "panel.setFontSize.large": "Large", "panel.setFontSize.extraLarge": "Extra Large", "panel.setLyricOffset.title": "Set Lyrics Offset ({status})", "panel.setLyricOffset.normal": "Normal", "panel.setLyricOffset.delay": "Delay {time}s", "panel.setLyricOffset.advance": "Advance {time}s", "panel.setLyricOffset.reset": "Reset", "panel.simpleInput.inputLabel": "Input Box", "panel.timingClose.countdown": "Close countdown {time}", "panel.timingClose.customize": "Customize", "panel.timingClose.cancelScheduleClose": "Cancel Scheduled Close", "panel.timingClose.closeAfterPlay": "Close after playing current song", "panel.playRate.title": "Playback Speed", "panel.sheetTags.title": "Playlist Categories", "repeatMode.SHUFFLE": "Shuffle", "repeatMode.QUEUE": "Repeat Queue", "repeatMode.SINGLE": "Repeat Single" } ================================================ FILE: src/core/i18n/languages/zh-cn.json ================================================ { "common.setting": "设置", "common.software": "软件", "common.language": "语言", "common.theme": "主题", "common.other": "其他", "common.cancel": "取消", "common.about": "关于", "common.batchEdit": "批量编辑", "common.selectAll": "全选", "common.unselectAll": "取消全选", "common.save": "保存", "common.play": "播放", "common.download": "下载", "common.delete": "删除", "common.unknownName": "未命名", "common.default": "默认", "common.search": "搜索", "common.clear": "清空", "common.singleMusic": "单曲", "common.album": "专辑", "common.artist": "作者", "common.sheet": "歌单", "common.done": "完成", "common.edit": "编辑", "common.local": "本地", "common.sure": "确定", "common.confirm": "确认", "common.view": "查看", "common.username": "用户名", "common.password": "密码", "common.cover": "封面", "common.name": "名称", "common.comment": "评论", "common.open": "打开", "sidebar.basicSettings": "基本设置", "sidebar.pluginManagement": "插件管理", "sidebar.themeSettings": "主题设置", "sidebar.scheduleClose": "定时关闭", "sidebar.backupAndResume": "备份与恢复", "sidebar.permissionManagement": "权限管理", "sidebar.checkUpdate": "检查更新", "sidebar.currentVersion": "当前版本: ", "sidebar.backToDesktop": "返回桌面", "sidebar.exitApp": "退出应用", "sidebar.languageSettings": "语言设置", "checkUpdate.error.latestVersion": "当前已是最新版本", "home.recommendSheet": "推荐歌单", "home.topList": "榜单", "home.playHistory": "播放历史", "home.localMusic": "本地音乐", "home.openSidebar.a11y": "打开侧边栏", "home.myPlaylists": "我的歌单", "home.starredPlaylists": "收藏歌单", "home.newPlaylist.a11y": "新建歌单", "home.importPlaylist.a11y": "导入歌单", "home.myPlaylistsCount.a11y": "我的歌单,共{count}个", "home.starredPlaylistsCount.a11y": "收藏歌单,共{count}个", "home.songCount": "{count}首", "home.clickToSearch": "点击这里开始搜索", "dialog.deleteSheetTitle": "删除歌单", "dialog.deleteSheetContent": "确认删除歌单「{name}」吗?", "toast.deleteSuccess": "删除成功", "toast.hasStarred": "已收藏歌单", "toast.hasUnstarred": "已取消收藏歌单", "toast.importSuccess": "导入成功", "toast.saveSuccess": "保存成功", "toast.sortHasBeenUpdated": "排序已更新", "toast.currentQualityNotAvailableForCurrentMusic": "当前暂无此音质音乐", "toast.commmentNotAvaliableForCurrentMusic": "当前歌曲暂无评论", "toast.addToNextPlay": "已添加到下一首播放", "toast.beginDownload": "开始下载,全部下载完成之前请不要关闭应用", "toast.rememberToSave": "记得保存哦~", "localMusic.scanLocalMusic": "扫描本地音乐", "localMusic.beginScan": "开始扫描", "localMusic.downloadList": "下载列表", "lyric.lyricLinkedFrom": "歌词关联自「{platform} - {title}」", "lyric.unlinkLyric": "解除关联", "lyric.noLyric": "暂无歌词", "lyric.searchLyric": "搜索歌词", "musicListEditor.selectMusicCount": "已选择 {count} 首", "musicListEditor.addToNextPlay": "下一首播放", "musicListEditor.addToSheet": "加入歌单", "permissionSetting.title": "权限管理", "permissionSetting.description": "此处列出了本 APP 需要的所有权限,你可以从这里开启或关闭某些权限。", "permissionSetting.floatWindowPermission": "悬浮窗权限", "permissionSetting.floatWindowPermissionDescription": "用以展示桌面歌词", "permissionSetting.fileReadWritePermission": "文件读写权限", "permissionSetting.fileReadWritePermissionDescription": "用以下载歌曲、缓存数据", "recommendSheet.title": "推荐歌单", "searchMusicList.searchPlaceHolder": "在列表中搜索歌曲", "searchMusicList.searchLabel.a11y": "搜索框", "searchPage.searchPlaceHolder": "输入要搜索的歌曲", "searchPage.searchLabel.a11y": "搜索框", "searchPage.history": "历史记录", "searchPage.artistResultWorksNum": "{count} 个作品", "searchPage.comingSoon": "敬请期待", "topList.title": "榜单", "sheetDetail.totalMusicCount": "共 {count} 首", "sheetDetail.editSheetInfo": "编辑歌单信息", "sheetDetail.batchEditMusic": "批量编辑歌曲", "sheetDetail.sortMusic": "歌曲排序", "sheetDetail.sortMusicOption.byTitle": "按歌曲名排序", "sheetDetail.sortMusicOption.byArtist": "按作者名排序", "sheetDetail.sortMusicOption.byAlbum": "按专辑名排序", "sheetDetail.sortMusicOption.newest": "按收藏时间从新到旧排序", "sheetDetail.sortMusicOption.oldest": "按收藏时间从旧到新排序", "sheetDetail.deleteSheet": "删除歌单", "sheetDetail.deleteSheetContent": "确认删除歌单「{name}」吗?", "history.title": "播放记录", "history.clearHistory": "清空播放记录", "downloading.title": "正在下载", "downloading.downloadFailReason.noWritePermission": "没有写入文件的权限", "downloading.downloadFailReason.failToFetchSource": "获取音乐源失败", "downloading.downloadFailReason.unknown": "未知错误", "downloading.downloadStatus.completed": "下载完成", "downloading.downloadStatus.downloadProgress": "下载中: {progress} / {totalSize}", "downloading.downloadStatus.pending": "等待下载", "downloading.downloadStatus.preparing": "正在获取音乐资源链接", "artistDetail.fansCount": "粉丝数: {count}", "artistDetail.menu.batchEditMusic": "批量编辑歌曲", "artistDetail.musicSheet": "{artist} - 单曲", "pluginSetting.pluginItem.options.updatePlugin": "更新插件", "pluginSetting.pluginItem.options.sharePlugin": "分享插件", "pluginSetting.pluginItem.options.uninstallPlugin": "卸载插件", "pluginSetting.pluginItem.options.uninstallPluginContent": "确认卸载插件「{name}」吗?", "pluginSetting.pluginItem.options.alternativePlugin": "音源重定向", "pluginSetting.pluginItem.dialog.setAlternativePluginTitle": "设置音源重定向", "pluginSetting.pluginItem.dialog.setAlternativePluginTip": "将使用选定的插件解析该插件的音源\n随便设置可能导致无法播放歌曲,请谨慎操作", "pluginSetting.pluginItem.options.importMusic": "导入单曲", "pluginSetting.pluginItem.options.importMusicPlaceHolder": "输入目标歌曲", "pluginSetting.pluginItem.options.importDialogTitle": "准备导入", "pluginSetting.pluginItem.options.importMusicDialogContent": "发现歌曲「{name}」,是否导入?", "pluginSetting.pluginItem.options.importMusicToSheetName": "{name}导入歌曲", "pluginSetting.pluginItem.options.importSheet": "导入歌单", "pluginSetting.pluginItem.options.importSheetPlaceHolder": "输入目标歌单", "pluginSetting.pluginItem.options.importSheetDialogContent": "发现 {count} 首歌曲,是否导入?", "pluginSetting.pluginItem.options.userVariables": "用户变量", "pluginSetting.pluginItem.versionHint": "版本号: {version}", "pluginSetting.pluginItem.author": "作者: {author}", "pluginSetting.pluginItem.alternativePlugin": "该插件实际使用「{name}」插件解析音乐的音源", "pluginSetting.menu.subscriptionSetting": "订阅设置", "pluginSetting.menu.sort": "插件排序", "pluginSetting.menu.uninstallAll": "卸载全部插件", "pluginSetting.menu.uninstallAllContent": "确认卸载全部插件吗?此操作不可恢复!", "pluginSetting.menu.installPlugin": "安装插件", "pluginSetting.menu.installPluginDialogPlaceholder": "输入插件URL", "pluginSetting.menu.pluginInstallFailedDialogTitle": "插件安装失败", "pluginSetting.menu.pluginUpdateFailedDialogTitle": "插件更新失败", "pluginSetting.fabOptions.installFromLocal": "从本地安装插件", "pluginSetting.fabOptions.installFromNetwork": "从网络安装插件", "pluginSetting.fabOptions.updateAllPlugins": "更新全部插件", "pluginSetting.fabOptions.updateSubscription": "更新订阅", "pluginSetting.failReason": "失败原因: {reason}", "pluginSetting.pluginInstallFailedDialogContent": "以下插件安装失败: \n {detail}", "pluginSetting.pluginUpdateFailedDialogContent": "以下插件安装失败: \n {detail}", "toast.pluginUpdateSuccess": "已更新到最新版本", "toast.failToUpdatePlugin": "更新插件失败", "toast.copiedToClipboard": "已复制到剪贴板", "toast.copiedToClipboardFailed": "复制失败", "toast.failToSharePlugin": "分享插件失败", "toast.pluginUninstalled": "插件已卸载", "toast.toast.pluginUninstalled": "卸载插件失败", "toast.failToImportMusic": "导入歌曲失败", "toast.importing": "正在导入中...", "toast.failToImportSheet": "导入歌单失败", "toast.settingSuccess": "设置成功~", "toast.installPluginSuccess": "插件安装成功", "toast.updatePluginSuccess": "插件更新成功", "toast.installPluginFail": "插件安装失败: {reason}", "toast.allPluginInstallFailed": "所有插件安装失败", "toast.partialPluginInstallFailed": "部分插件安装失败", "toast.partialPluginInstallFailedWithReason": "部分插件安装失败: {reason}", "toast.allPluginUpdateFailed": "所有插件更新失败", "toast.partialPluginUpdateFailed": "部分插件更新失败", "toast.noSubscription": "暂无订阅", "toast.subscriptionInvalid": "订阅无效", "toast.subscriptionHaveToEndWithJs": "订阅地址必须以.js或.json结尾", "toast.unknownError": "未知错误,请稍后再试: {reason}", "themeSettings.displayStyle": "显示样式", "themeSettings.followSystemTheme": "跟随系统深色设置", "themeSettings.setTheme": "主题设置", "themeSettings.lightMode": "浅色模式", "themeSettings.darkMode": "深色模式", "themeSettings.customMode": "自定义背景", "setCustomTheme.customizeBackground": "自定义背景", "setCustomTheme.blur": "模糊度", "setCustomTheme.opacity": "透明度", "setCustomTheme.primaryColor": "主题色", "setCustomTheme.textColor": "文字颜色", "setCustomTheme.appBarColor": "标题栏背景色", "setCustomTheme.appBarTextColor": "标题栏文字颜色", "setCustomTheme.musicBarColor": "音乐栏背景色", "setCustomTheme.musicBarTextColor": "音乐栏文字颜色", "setCustomTheme.pageBackgroundColor": "页面背景色", "setCustomTheme.backdropColor": "弹窗、浮层背景色", "setCustomTheme.cardColor": "卡片背景色", "setCustomTheme.placeholderColor": "输入框背景色", "setCustomTheme.tabBarColor": "导航栏背景色", "setCustomTheme.notificationColor": "提示、tips背景色", "backupAndResume.beginBackup": "开始备份", "backupAndResume.backupDialogTitle": "备份本地音乐", "backupAndResume.backuping": "正在备份中...", "toast.backupSuccess": "备份成功", "toast.backupFail": "备份失败: {reason}", "backupAndResume.resumeFromLocalFile": "从本地文件恢复", "backupAndResume.resuming": "正在恢复中...", "toast.resumeSuccess": "恢复成功", "toast.resumeFail": "恢复失败: {reason}", "backupAndResume.resumeFromUrlDialogTitle": "从远程URL中恢复", "backupAndResume.resumeFromUrlDialogPlaceHolder": "输入以json或txt结尾的URL", "toast.backupFileNotFound": "备份文件未找到", "toast.resumePreCheckFailed": "请先在「Webdav设置」中完成配置,再执行恢复", "backupAndResume.setResumeMode": "设置恢复方式", "backupAndResume.resumeMode": "恢复方式", "backupAndResume.localBackup": "本地备份", "backupAndResume.backupToLocal": "备份到本地", "backupAndResume.webdavSettings": "Webdav设置", "backupAndResume.webdavUrl": "webdav服务地址", "backupAndResume.backupToWebdav": "备份到Webdav", "backupAndResume.resumeFromWebdav": "从Webdav中恢复", "backupAndResume.resumeMode.append": "恢复为新歌单", "backupAndResume.resumeMode.overwrite-default": "合并默认歌单,其他歌单恢复为新歌单", "backupAndResume.resumeMode.overwrite": "合并同名歌单", "basicSettings.common": "常规", "basicSettings.maxHistoryLength": "历史记录最多保存条数", "basicSettings.musicDetailDefault": "打开歌曲详情页时", "basicSettings.musicDetailDefault.album": "默认展示歌曲封面", "basicSettings.musicDetailDefault.lyric": "默认展示歌词页", "basicSettings.musicDetailAwake": "处于歌曲详情页时常亮", "basicSettings.associateLyricType": "关联歌词方式", "basicSettings.associateLyricType.input": "输入歌曲ID", "basicSettings.associateLyricType.search": "搜索歌词", "basicSettings.showExitOnNotification": "通知栏显示关闭按钮 (重启后生效)", "basicSettings.sheetAndAlbum": "歌单&专辑", "basicSettings.clickMusicInSearch": "点击搜索结果内单曲时", "basicSettings.clickMusicInSearch.playMusic": "播放歌曲", "basicSettings.clickMusicInSearch.playMusicAndReplace": "播放歌曲并替换播放列表", "basicSettings.clickMusicInAlbum": "点击专辑内单曲时", "basicSettings.clickMusicInAlbum.playMusic": "播放歌曲", "basicSettings.clickMusicInAlbum.playAlbum": "播放专辑", "basicSettings.musicOrderInLocalSheet": "新建歌单时默认歌曲排序", "basicSettings.musicOrderInLocalSheet.title": "按歌曲名排序", "basicSettings.musicOrderInLocalSheet.artist": "按作者名排序", "basicSettings.musicOrderInLocalSheet.album": "按专辑名排序", "basicSettings.musicOrderInLocalSheet.newest": "按收藏时间从新到旧排序", "basicSettings.musicOrderInLocalSheet.oldest": "按收藏时间从旧到新排序", "basicSettings.plugin": "插件", "basicSettings.autoUpdatePlugin": "软件启动时自动更新插件", "basicSettings.notCheckPluginVersion": "安装插件时不校验版本", "basicSettings.lazyLoadPlugin": "启用插件懒加载", "basicSettings.playback": "播放", "basicSettings.notInterrupt": "允许与其他应用同时播放", "basicSettings.autoPlayWhenAppStart": "软件启动时自动播放歌曲", "basicSettings.tryChangeSourceWhenPlayFail": "播放失败时尝试更换音源", "basicSettings.autoStopWhenError": "播放失败时自动暂停", "basicSettings.tempRemoteDuck": "播放被暂时打断时", "basicSettings.tempRemoteDuck.pause": "暂停播放", "basicSettings.tempRemoteDuck.lowerVolume": "降低音量", "basicSettings.tempRemoteDuck.volumeDecreaseLevel": "音量降低幅度", "basicSettings.defaultPlayQuality": "默认播放音质", "basicSettings.playQualityOrder": "默认播放音质缺失时", "basicSettings.playQualityOrder.asc": "播放更高音质", "basicSettings.playQualityOrder.desc": "播放更低音质", "basicSettings.download": "下载", "basicSettings.downloadPath": "下载路径", "basicSettings.fileSelector.selectFolder": "选择文件夹", "basicSettings.maxDownload": "最大同时下载数目", "basicSettings.defaultDownloadQuality": "默认下载音质", "basicSettings.downloadQualityOrder": "默认下载音质缺失时", "basicSettings.downloadQualityOrder.asc": "下载更高音质", "basicSettings.downloadQualityOrder.desc": "下载更低音质", "basicSettings.network": "网络", "basicSettings.useCelluarNetworkPlay": "使用移动网络播放", "basicSettings.useCelluarNetworkDownload": "使用移动网络下载", "basicSettings.lyric": "歌词", "basicSettings.lyric.autoSearchLyric": "歌词缺失时自动搜索歌词", "basicSettings.lyric.showStatusBarLyric": "开启桌面歌词", "basicSettings.lyric.align": "对齐方式", "basicSettings.lyric.align.left": "左对齐", "basicSettings.lyric.align.center": "居中对齐", "basicSettings.lyric.align.right": "右对齐", "basicSettings.lyric.leftRightDistance": "左右距离", "basicSettings.lyric.topBottomDistance": "上下距离", "basicSettings.lyric.width": "歌词宽度", "basicSettings.lyric.fontSize": "字体大小", "basicSettings.lyric.textColor": "文本颜色", "basicSettings.lyric.backgroundColor": "文本背景色", "basicSettings.cache": "缓存", "basicSettings.cache.musicCacheLimit": "音乐缓存上限", "basicSettings.cache.clearMusicCache": "清除音乐缓存", "basicSettings.cache.clearLyricCache": "清除歌词缓存", "basicSettings.cache.clearImageCache": "清除图片缓存", "basicSettings.developer": "开发选项", "basicSettings.developer.errorLog": "记录错误日志", "basicSettings.developer.traceLog": "记录详细日志", "basicSettings.developer.devLog": "调试面板", "basicSettings.developer.viewErrorLog": "查看错误日志", "basicSettings.developer.clearLog": "清空日志", "dialog.loading.reinitializeTrackPlayer": "初始化播放器中...", "dialog.setCacheTitle": "设置缓存", "dialog.setCachePlaceholder": "输入缓存占用上限,100M-8192M,单位M", "dialog.clearMusicCacheTitle": "清除音乐缓存", "dialog.clearMusicCacheContent": "确定清除音乐缓存吗?", "dialog.clearLyricCacheTitle": "清除歌词缓存", "dialog.clearLyricCacheContent": "确定清除歌词缓存吗?", "dialog.clearImageCacheTitle": "清除图片缓存", "dialog.clearImageCacheContent": "确定清除图片缓存吗?", "dialog.errorLogTitle": "错误日志", "dialog.errorLogNoRecord": "暂无记录", "dialog.errorLogKnow": "我知道了", "dialog.errorLogCopy": "复制日志", "dialog.setScheduleCloseTime.title": "设置定时关闭时间", "dialog.setScheduleCloseTime.placeholder": "请输入时间", "dialog.setScheduleCloseTime.unit": "分钟", "dialog.setScheduleCloseTime.hint": "最长支持设置24小时(1440分钟)", "toast.cacheSetSuccess": "设置成功", "toast.musicCacheCleared": "已清除音乐缓存", "toast.lyricCacheCleared": "已清除歌词缓存", "toast.imageCacheCleared": "已清除图片缓存", "toast.logCleared": "日志已清空", "toast.noFloatWindowPermission": "无悬浮窗权限", "toast.folderNotExistOrNoPermission": "文件夹不存在或无权限", "musicQuality.low": "低音质", "musicQuality.standard": "标准音质", "musicQuality.high": "高音质", "musicQuality.super": "超高音质", "common.emptyList": "什么都没有呀~", "common.loading": "加载中...", "common.error": "出错啦...", "common.clickToRetry": "点击重试", "common.failToLoad": "加载失败", "common.listReachEnd": "~~~ 到底啦 ~~~", "playAllBar.title": "播放全部", "noPlugin.title": "还没有安装插件哦", "noPlugin.titleWithType": "还没有安装支持「{type}」功能的插件哦", "noPlugin.description": "先去「侧边栏-插件管理」里安装插件吧~", "dialog.checkStorage.title": "存储权限", "dialog.checkStorage.content.0": "MusicFree 需要文件读写权限来进行歌单备份到本地、歌曲下载等操作。", "dialog.checkStorage.content.1": "点击「去授予权限」跳转至设置界面授予文件管理权限。", "dialog.checkStorage.content.2": "如果您不需要备份歌单或者下载歌曲,您也可以暂时不授予此权限。", "dialog.checkStorage.content.3": "您可以随时在侧边栏「权限管理」->「文件读写权限」授予或取消授予权限。", "dialog.checkStorage.button.grantPermission": "去授予权限", "dialog.checkStorage.button.doNotShowAgain": "不再提示", "dialog.downloadDialog.title": "发现新版本({version})", "dialog.downloadDialog.skipThisVersion": "跳过此版本", "dialog.downloadDialog.downloadUsingBrowser": "从浏览器下载", "dialog.downloadDialog.backupUrl": "备用链接", "dialog.editSheetDetail.sheetName": "歌单名", "dialog.subscriptionPluginDialog.title": "订阅", "dialog.markdownDialog.openExternalLink": "请打开浏览器访问页面。请注意安全,谨防钓鱼网站。", "dialog.markdownDialog.clickToShowImage": "点击展示图片", "dialog.markdownDialog.loadFailed": "图片加载失败", "panel.playList.title": "播放列表", "panel.playList.count": " ({count}首)", "panel.searchLrc.inputPlaceholder": "输入歌曲名称", "panel.searchLrc.toast.settingSuccess": "设置成功~", "panel.searchLrc.toast.failToSearch": "设置失败!", "panel.addToMusicSheet.title": "添加到歌单 ({count}首)", "panel.addToMusicSheet.newMusicSheet": "新建歌单", "panel.addToMusicSheet.count": "{count}首", "panel.addToMusicSheet.toast.success": "已添加到歌单", "panel.addToMusicSheet.toast.fail": "添加到歌单失败", "panel.associateLrc.title": "关联歌词", "panel.associateLrc.inputPlaceholder": "输入要关联歌词的歌曲ID", "panel.associateLrc.targetExpired": "地址失效了,重新复制一下吧~", "panel.associateLrc.toast.success": "关联歌词成功", "panel.associateLrc.toast.fail": "关联歌词失败", "panel.associateLrc.toast.unlinkSuccess": "取消关联歌词成功", "panel.createMusicSheet.title": "新建歌单", "panel.editMusicSheetInfo.title": "编辑歌单信息", "panel.editMusicSheetInfo.sheetName": "歌单名", "panel.editMusicSheetInfo.toast.updateSuccess": "更新歌单信息成功~", "panel.imageViewer.saveImage": "保存图片", "panel.imageViewer.saveImageSuccess": "图片已保存到 {path}", "panel.imageViewer.saveImageFail": "保存图片失败: {reason}", "panel.colorPicker.title": "选择颜色", "panel.createMusicSheet.inputLabel": "输入框", "panel.importMusicSheet.title": "导入歌单", "panel.importMusicSheet.placeholder": "输入目标歌单", "panel.importMusicSheet.importing": "正在导入中...", "panel.importMusicSheet.prepareImport": "准备导入", "panel.importMusicSheet.foundSongs": "发现{count}首歌曲! 现在开始导入吗?", "panel.importMusicSheet.invalidLink": "链接有误或目标歌单为空", "panel.musicItemLyricOptions.author": "作者: {artist}", "panel.musicItemLyricOptions.album": "专辑: {album}", "panel.musicItemLyricOptions.toggleDesktopLyric": "{status}桌面歌词", "panel.musicItemLyricOptions.enableDesktopLyric": "开启", "panel.musicItemLyricOptions.disableDesktopLyric": "关闭", "panel.musicItemLyricOptions.desktopLyricPermissionError": "开启桌面歌词失败,无悬浮窗权限", "panel.musicItemLyricOptions.uploadLocalLyric": "上传本地歌词", "panel.musicItemLyricOptions.uploadLocalLyricTranslation": "上传本地歌词翻译", "panel.musicItemLyricOptions.deleteLocalLyric": "删除本地歌词", "panel.musicItemLyricOptions.settingFail": "设置失败: {reason}", "panel.musicItemLyricOptions.deleteFail": "删除失败: {reason}", "panel.musicItemOptions.author": "作者: {artist}", "panel.musicItemOptions.album": "专辑: {album}", "panel.musicItemOptions.downloaded": "已下载", "panel.musicItemOptions.readComment": "查看评论", "panel.musicItemOptions.deleteLocalDownload": "删除本地下载", "panel.musicItemOptions.deleteLocalDownloadConfirm": "将会删除已下载的本地文件,确定继续吗?", "panel.musicItemOptions.associatedLyric": "已关联歌词 {platform}@{id}", "panel.musicItemOptions.associateLyric": "关联歌词", "panel.musicItemOptions.unassociateLyric": "解除关联歌词", "panel.musicItemOptions.unassociateLyricSuccess": "已解除关联歌词", "panel.musicItemOptions.timingClose": "定时关闭", "panel.musicItemOptions.clearPluginCache": "清除插件缓存(播放异常时使用)", "panel.musicItemOptions.cacheCleared": "缓存已清除", "panel.musicItemOptions.deleteFailed": "删除失败", "panel.musicQuality.title": "设置{type}音质", "panel.searchLrc.unnamed": "(未命名)", "panel.searchLrc.notSupported": "搜索歌词", "panel.setFontSize.title": "设置字体大小", "panel.setFontSize.small": "小", "panel.setFontSize.standard": "标准", "panel.setFontSize.large": "大", "panel.setFontSize.extraLarge": "超大", "panel.setLyricOffset.title": "设置歌词进度 ({status})", "panel.setLyricOffset.normal": "正常", "panel.setLyricOffset.delay": "延后{time}s", "panel.setLyricOffset.advance": "提前{time}s", "panel.setLyricOffset.reset": "重置", "panel.simpleInput.inputLabel": "输入框", "panel.timingClose.countdown": "关闭倒计时 {time}", "panel.timingClose.customize": "自定义", "panel.timingClose.cancelScheduleClose": "取消定时关闭", "panel.timingClose.closeAfterPlay": "播放完歌曲再关闭", "panel.playRate.title": "播放速度", "panel.sheetTags.title": "歌单类别", "repeatMode.SHUFFLE": "随机播放", "repeatMode.QUEUE": "列表循环", "repeatMode.SINGLE": "单曲循环" } ================================================ FILE: src/core/i18n/languages/zh-tw.json ================================================ { "common.setting": "設定", "common.software": "軟體", "common.language": "語言", "common.theme": "主題", "common.other": "其他", "common.cancel": "取消", "common.about": "關於", "common.batchEdit": "批次編輯", "common.selectAll": "全選", "common.unselectAll": "取消全選", "common.save": "儲存", "common.play": "播放", "common.download": "下載", "common.delete": "刪除", "common.unknownName": "未命名", "common.default": "預設", "common.search": "搜尋", "common.clear": "清空", "common.singleMusic": "單曲", "common.album": "專輯", "common.artist": "作者", "common.sheet": "歌單", "common.done": "完成", "common.edit": "編輯", "common.local": "本地", "common.sure": "確定", "common.confirm": "確認", "common.view": "查看", "common.open": "打開", "common.username": "用戶名", "common.password": "密碼", "common.cover": "封面", "common.name": "名稱", "common.comment": "評論", "sidebar.basicSettings": "基本設定", "sidebar.pluginManagement": "外掛管理", "sidebar.themeSettings": "主題設定", "sidebar.scheduleClose": "定時關閉", "sidebar.backupAndResume": "備份與恢復", "sidebar.permissionManagement": "權限管理", "sidebar.checkUpdate": "檢查更新", "sidebar.currentVersion": "當前版本: ", "sidebar.backToDesktop": "返回桌面", "sidebar.exitApp": "退出應用", "sidebar.languageSettings": "語言設定", "checkUpdate.error.latestVersion": "當前已是最新版本", "home.recommendSheet": "推薦歌單", "home.topList": "榜單", "home.playHistory": "播放歷史", "home.localMusic": "本地音樂", "home.openSidebar.a11y": "打開側邊欄", "home.myPlaylists": "我的歌單", "home.starredPlaylists": "收藏歌單", "home.newPlaylist.a11y": "新建歌單", "home.importPlaylist.a11y": "導入歌單", "home.myPlaylistsCount.a11y": "我的歌單,共{count}個", "home.starredPlaylistsCount.a11y": "收藏歌單,共{count}個", "home.songCount": "{count}首", "home.clickToSearch": "點擊這裡開始搜尋", "dialog.deleteSheetTitle": "刪除歌單", "dialog.deleteSheetContent": "確認刪除歌單「{name}」嗎?", "toast.deleteSuccess": "刪除成功", "toast.hasStarred": "已收藏歌單", "toast.hasUnstarred": "已取消收藏歌單", "toast.importSuccess": "導入成功", "toast.saveSuccess": "儲存成功", "toast.sortHasBeenUpdated": "排序已更新", "toast.currentQualityNotAvailableForCurrentMusic": "當前暫無此音質音樂", "toast.commmentNotAvaliableForCurrentMusic": "當前歌曲暫無評論", "toast.addToNextPlay": "已添加到下一首播放", "toast.beginDownload": "開始下載,全部下載完成之前請不要關閉應用", "toast.rememberToSave": "記得儲存哦~", "localMusic.scanLocalMusic": "掃描本地音樂", "localMusic.beginScan": "開始掃描", "localMusic.downloadList": "下載列表", "lyric.lyricLinkedFrom": "歌詞關聯自「{platform} - {title}」", "lyric.unlinkLyric": "解除關聯", "lyric.noLyric": "暫無歌詞", "lyric.searchLyric": "搜尋歌詞", "musicListEditor.selectMusicCount": "已選擇 {count} 首", "musicListEditor.addToNextPlay": "下一首播放", "musicListEditor.addToSheet": "加入歌單", "permissionSetting.title": "權限管理", "permissionSetting.description": "此處列出了本 APP 需要的所有權限,你可以從這裡開啟或關閉某些權限。", "permissionSetting.floatWindowPermission": "懸浮窗權限", "permissionSetting.floatWindowPermissionDescription": "用以展示桌面歌詞", "permissionSetting.fileReadWritePermission": "文件讀寫權限", "permissionSetting.fileReadWritePermissionDescription": "用以下載歌曲、快取資料", "recommendSheet.title": "推薦歌單", "searchMusicList.searchPlaceHolder": "在列表中搜尋歌曲", "searchMusicList.searchLabel.a11y": "搜尋框", "searchPage.searchPlaceHolder": "輸入要搜尋的歌曲", "searchPage.searchLabel.a11y": "搜尋框", "searchPage.history": "歷史紀錄", "searchPage.artistResultWorksNum": "{count} 個作品", "searchPage.comingSoon": "敬請期待", "topList.title": "榜單", "sheetDetail.totalMusicCount": "共 {count} 首", "sheetDetail.editSheetInfo": "編輯歌單資訊", "sheetDetail.batchEditMusic": "批量編輯歌曲", "sheetDetail.sortMusic": "歌曲排序", "sheetDetail.sortMusicOption.byTitle": "按歌曲名排序", "sheetDetail.sortMusicOption.byArtist": "按作者名排序", "sheetDetail.sortMusicOption.byAlbum": "按專輯名排序", "sheetDetail.sortMusicOption.newest": "按收藏時間從新到舊排序", "sheetDetail.sortMusicOption.oldest": "按收藏時間從舊到新排序", "sheetDetail.deleteSheet": "刪除歌單", "sheetDetail.deleteSheetContent": "確認刪除歌單「{name}」嗎?", "history.title": "播放紀錄", "history.clearHistory": "清空播放紀錄", "downloading.title": "正在下載", "downloading.downloadFailReason.noWritePermission": "沒有寫入文件的權限", "downloading.downloadFailReason.failToFetchSource": "獲取音樂源失敗", "downloading.downloadFailReason.unknown": "未知錯誤", "downloading.downloadStatus.completed": "下載完成", "downloading.downloadStatus.downloadProgress": "下載中: {progress} / {totalSize}", "downloading.downloadStatus.pending": "等待下載", "downloading.downloadStatus.preparing": "正在獲取音樂資源連結", "artistDetail.fansCount": "粉絲數: {count}", "artistDetail.menu.batchEditMusic": "批量編輯歌曲", "artistDetail.musicSheet": "{artist} - 單曲", "pluginSetting.pluginItem.options.updatePlugin": "更新外掛", "pluginSetting.pluginItem.options.sharePlugin": "分享外掛", "pluginSetting.pluginItem.options.uninstallPlugin": "卸載外掛", "pluginSetting.pluginItem.options.uninstallPluginContent": "確認卸載外掛「{name}」嗎?", "pluginSetting.pluginItem.options.alternativePlugin": "音源重定向", "pluginSetting.pluginItem.alternativePlugin": "該外掛實際使用「{name}」外掛解析音樂的音源", "pluginSetting.pluginItem.dialog.setAlternativePluginTitle": "設置音源重定向", "pluginSetting.pluginItem.dialog.setAlternativePluginTip": "將使用選定的外掛解析該外掛的音源\n隨便設置可能導致無法播放歌曲,請謹慎操作", "pluginSetting.pluginItem.options.importMusic": "導入單曲", "pluginSetting.pluginItem.options.importMusicPlaceHolder": "輸入目標歌曲", "pluginSetting.pluginItem.options.importDialogTitle": "準備導入", "pluginSetting.pluginItem.options.importMusicDialogContent": "發現歌曲「{name}」,是否導入?", "pluginSetting.pluginItem.options.importMusicToSheetName": "{name}導入歌曲", "pluginSetting.pluginItem.options.importSheet": "導入歌單", "pluginSetting.pluginItem.options.importSheetPlaceHolder": "輸入目標歌單", "pluginSetting.pluginItem.options.importSheetDialogContent": "發現 {count} 首歌曲,是否導入?", "pluginSetting.pluginItem.options.userVariables": "用戶變數", "pluginSetting.pluginItem.versionHint": "版本號: {version}", "pluginSetting.pluginItem.author": "作者: {author}", "pluginSetting.menu.subscriptionSetting": "訂閱設定", "pluginSetting.menu.sort": "外掛排序", "pluginSetting.menu.uninstallAll": "卸載全部外掛", "pluginSetting.menu.uninstallAllContent": "確認卸載全部外掛嗎?此操作不可恢復!", "pluginSetting.menu.installPlugin": "安裝外掛", "pluginSetting.menu.installPluginDialogPlaceholder": "輸入外掛URL", "pluginSetting.menu.pluginInstallFailedDialogTitle": "外掛安裝失敗", "pluginSetting.menu.pluginUpdateFailedDialogTitle": "外掛更新失敗", "pluginSetting.fabOptions.installFromLocal": "從本地安裝外掛", "pluginSetting.fabOptions.installFromNetwork": "從網路安裝外掛", "pluginSetting.fabOptions.updateAllPlugins": "更新全部外掛", "pluginSetting.fabOptions.updateSubscription": "更新訂閱", "pluginSetting.failReason": "失敗原因: {reason}", "pluginSetting.pluginInstallFailedDialogContent": "以下外掛安裝失敗: \n {detail}", "pluginSetting.pluginUpdateFailedDialogContent": "以下外掛安裝失敗: \n {detail}", "toast.pluginUpdateSuccess": "已更新到最新版本", "toast.failToUpdatePlugin": "更新外掛失敗", "toast.copiedToClipboard": "已複製到剪貼板", "toast.copiedToClipboardFailed": "複製失敗", "toast.failToSharePlugin": "分享外掛失敗", "toast.pluginUninstalled": "外掛已卸載", "toast.toast.pluginUninstalled": "卸載外掛失敗", "toast.failToImportMusic": "導入歌曲失敗", "toast.importing": "正在導入中...", "toast.failToImportSheet": "導入歌單失敗", "toast.settingSuccess": "設定成功~", "toast.installPluginSuccess": "外掛安裝成功", "toast.updatePluginSuccess": "外掛更新成功", "toast.installPluginFail": "外掛安裝失敗: {reason}", "toast.allPluginInstallFailed": "所有外掛安裝失敗", "toast.partialPluginInstallFailed": "部分外掛安裝失敗", "toast.partialPluginInstallFailedWithReason": "部分外掛安裝失敗: {reason}", "toast.allPluginUpdateFailed": "所有外掛更新失敗", "toast.partialPluginUpdateFailed": "部分外掛更新失敗", "toast.noSubscription": "暫無訂閱", "toast.subscriptionInvalid": "訂閱無效", "toast.subscriptionHaveToEndWithJs": "訂閱地址必須以.js或.json結尾", "toast.unknownError": "未知錯誤,請稍後再試: {reason}", "themeSettings.displayStyle": "顯示樣式", "themeSettings.followSystemTheme": "跟隨系統深色設定", "themeSettings.setTheme": "主題設定", "themeSettings.lightMode": "淺色模式", "themeSettings.darkMode": "深色模式", "themeSettings.customMode": "自訂背景", "setCustomTheme.customizeBackground": "自訂背景", "setCustomTheme.blur": "模糊度", "setCustomTheme.opacity": "透明度", "setCustomTheme.primaryColor": "主題色", "setCustomTheme.textColor": "文字顏色", "setCustomTheme.appBarColor": "標題欄背景色", "setCustomTheme.appBarTextColor": "標題欄文字顏色", "setCustomTheme.musicBarColor": "音樂欄背景色", "setCustomTheme.musicBarTextColor": "音樂欄文字顏色", "setCustomTheme.pageBackgroundColor": "頁面背景色", "setCustomTheme.backdropColor": "彈窗、浮層背景色", "setCustomTheme.cardColor": "卡片背景色", "setCustomTheme.placeholderColor": "輸入框背景色", "setCustomTheme.tabBarColor": "導航欄背景色", "setCustomTheme.notificationColor": "提示、tips背景色", "backupAndResume.beginBackup": "開始備份", "backupAndResume.backupDialogTitle": "備份本地音樂", "backupAndResume.backuping": "正在備份中...", "toast.backupSuccess": "備份成功", "toast.backupFail": "備份失敗: {reason}", "backupAndResume.resumeFromLocalFile": "從本地文件恢復", "backupAndResume.resuming": "正在恢復中...", "toast.resumeSuccess": "恢復成功", "toast.resumeFail": "恢復失敗: {reason}", "backupAndResume.resumeFromUrlDialogTitle": "從遠程URL中恢復", "backupAndResume.resumeFromUrlDialogPlaceHolder": "輸入以json或txt結尾的URL", "toast.backupFileNotFound": "備份文件未找到", "toast.resumePreCheckFailed": "請先在「Webdav設定」中完成配置,再執行恢復", "backupAndResume.setResumeMode": "設定恢復方式", "backupAndResume.resumeMode": "恢復方式", "backupAndResume.localBackup": "本地備份", "backupAndResume.backupToLocal": "備份到本地", "backupAndResume.webdavSettings": "Webdav設定", "backupAndResume.webdavUrl": "webdav服務地址", "backupAndResume.backupToWebdav": "備份到Webdav", "backupAndResume.resumeFromWebdav": "從Webdav中恢復", "backupAndResume.resumeMode.append": "恢復為新歌單", "backupAndResume.resumeMode.overwrite-default": "合併預設歌單,其他歌單恢復為新歌單", "backupAndResume.resumeMode.overwrite": "合併同名歌單", "basicSettings.common": "常規", "basicSettings.maxHistoryLength": "歷史紀錄最多保存條數", "basicSettings.musicDetailDefault": "打開歌曲詳情頁時", "basicSettings.musicDetailDefault.album": "預設展示歌曲封面", "basicSettings.musicDetailDefault.lyric": "預設展示歌詞頁", "basicSettings.musicDetailAwake": "處於歌曲詳情頁時常亮", "basicSettings.associateLyricType": "關聯歌詞方式", "basicSettings.associateLyricType.input": "輸入歌曲ID", "basicSettings.associateLyricType.search": "搜尋歌詞", "basicSettings.showExitOnNotification": "通知欄顯示關閉按鈕 (重啟後生效)", "basicSettings.sheetAndAlbum": "歌單&專輯", "basicSettings.clickMusicInSearch": "點擊搜尋結果內單曲時", "basicSettings.clickMusicInSearch.playMusic": "播放歌曲", "basicSettings.clickMusicInSearch.playMusicAndReplace": "播放歌曲並替換播放列表", "basicSettings.clickMusicInAlbum": "點擊專輯內單曲時", "basicSettings.clickMusicInAlbum.playMusic": "播放歌曲", "basicSettings.clickMusicInAlbum.playAlbum": "播放專輯", "basicSettings.musicOrderInLocalSheet": "新建歌單時預設歌曲排序", "basicSettings.musicOrderInLocalSheet.title": "按歌曲名排序", "basicSettings.musicOrderInLocalSheet.artist": "按作者名排序", "basicSettings.musicOrderInLocalSheet.album": "按專輯名排序", "basicSettings.musicOrderInLocalSheet.newest": "按收藏時間從新到舊排序", "basicSettings.musicOrderInLocalSheet.oldest": "按收藏時間從舊到新排序", "basicSettings.plugin": "外掛", "basicSettings.autoUpdatePlugin": "軟體啟動時自動更新外掛", "basicSettings.notCheckPluginVersion": "安裝外掛時不校驗版本", "basicSettings.lazyLoadPlugin": "啟用插件懶加載", "basicSettings.playback": "播放", "basicSettings.notInterrupt": "允許與其他應用同時播放", "basicSettings.autoPlayWhenAppStart": "軟體啟動時自動播放歌曲", "basicSettings.tryChangeSourceWhenPlayFail": "播放失敗時嘗試更換音源", "basicSettings.autoStopWhenError": "播放失敗時自動暫停", "basicSettings.tempRemoteDuck": "播放被暫時打斷時", "basicSettings.tempRemoteDuck.pause": "暫停播放", "basicSettings.tempRemoteDuck.lowerVolume": "降低音量", "basicSettings.tempRemoteDuck.volumeDecreaseLevel": "音量調降程度", "basicSettings.defaultPlayQuality": "預設播放音質", "basicSettings.playQualityOrder": "預設播放音質缺失時", "basicSettings.playQualityOrder.asc": "播放更高音質", "basicSettings.playQualityOrder.desc": "播放更低音質", "basicSettings.download": "下載", "basicSettings.downloadPath": "下載路徑", "basicSettings.fileSelector.selectFolder": "選擇文件夾", "basicSettings.maxDownload": "最大同時下載數目", "basicSettings.defaultDownloadQuality": "預設下載音質", "basicSettings.downloadQualityOrder": "預設下載音質缺失時", "basicSettings.downloadQualityOrder.asc": "下載更高音質", "basicSettings.downloadQualityOrder.desc": "下載更低音質", "basicSettings.network": "網路", "basicSettings.useCelluarNetworkPlay": "使用行動網路播放", "basicSettings.useCelluarNetworkDownload": "使用行動網路下載", "basicSettings.lyric": "歌詞", "basicSettings.lyric.autoSearchLyric": "歌詞缺失時自動搜尋歌詞", "basicSettings.lyric.showStatusBarLyric": "開啟桌面歌詞", "basicSettings.lyric.align": "對齊方式", "basicSettings.lyric.align.left": "左對齊", "basicSettings.lyric.align.center": "居中對齊", "basicSettings.lyric.align.right": "右對齊", "basicSettings.lyric.leftRightDistance": "左右距離", "basicSettings.lyric.topBottomDistance": "上下距離", "basicSettings.lyric.width": "歌詞寬度", "basicSettings.lyric.fontSize": "字體大小", "basicSettings.lyric.textColor": "文本顏色", "basicSettings.lyric.backgroundColor": "文本背景色", "basicSettings.cache": "快取", "basicSettings.cache.musicCacheLimit": "音樂快取上限", "basicSettings.cache.clearMusicCache": "清除音樂快取", "basicSettings.cache.clearLyricCache": "清除歌詞快取", "basicSettings.cache.clearImageCache": "清除圖片快取", "basicSettings.developer": "開發選項", "basicSettings.developer.errorLog": "記錄錯誤日誌", "basicSettings.developer.traceLog": "記錄詳細日誌", "basicSettings.developer.devLog": "調試面板", "basicSettings.developer.viewErrorLog": "查看錯誤日誌", "basicSettings.developer.clearLog": "清空日誌", "dialog.loading.reinitializeTrackPlayer": "初始化播放器中...", "dialog.setCacheTitle": "設定快取", "dialog.setCachePlaceholder": "輸入快取佔用上限,100M-8192M,單位M", "dialog.clearMusicCacheTitle": "清除音樂快取", "dialog.clearMusicCacheContent": "確定清除音樂快取嗎?", "dialog.clearLyricCacheTitle": "清除歌詞快取", "dialog.clearLyricCacheContent": "確定清除歌詞快取嗎?", "dialog.clearImageCacheTitle": "清除圖片快取", "dialog.clearImageCacheContent": "確定清除圖片快取嗎?", "dialog.errorLogTitle": "錯誤日誌", "dialog.errorLogNoRecord": "暫無記錄", "dialog.errorLogKnow": "我知道了", "dialog.errorLogCopy": "複製日誌", "dialog.setScheduleCloseTime.title": "設定定時關閉時間", "dialog.setScheduleCloseTime.placeholder": "請輸入時間", "dialog.setScheduleCloseTime.unit": "分鐘", "dialog.setScheduleCloseTime.hint": "最長支持設定24小時(1440分鐘)", "toast.cacheSetSuccess": "設定成功", "toast.musicCacheCleared": "已清除音樂快取", "toast.lyricCacheCleared": "已清除歌詞快取", "toast.imageCacheCleared": "已清除圖片快取", "toast.logCleared": "日誌已清空", "toast.noFloatWindowPermission": "無懸浮窗權限", "toast.folderNotExistOrNoPermission": "文件夾不存在或無權限", "musicQuality.low": "低音質", "musicQuality.standard": "標準音質", "musicQuality.high": "高音質", "musicQuality.super": "超高音質", "common.emptyList": "什麼都沒有呀~", "common.loading": "加載中...", "common.error": "出錯啦...", "common.clickToRetry": "點擊重試", "common.failToLoad": "加載失敗", "common.listReachEnd": "~~~ 到底啦 ~~~", "playAllBar.title": "播放全部", "noPlugin.title": "還沒有安裝外掛哦", "noPlugin.titleWithType": "還沒有安裝支援「{type}」功能的外掛哦", "noPlugin.description": "先去「側邊欄-外掛管理」裡安裝外掛吧~", "dialog.checkStorage.title": "儲存權限", "dialog.checkStorage.content.0": "MusicFree 需要文件讀寫權限來進行歌單備份到本地、歌曲下載等操作。", "dialog.checkStorage.content.1": "點擊「去授予權限」跳轉至設定介面授予文件管理權限。", "dialog.checkStorage.content.2": "如果您不需要備份歌單或者下載歌曲,您也可以暫時不授予此權限。", "dialog.checkStorage.content.3": "您可以隨時在側邊欄「權限管理」->「文件讀寫權限」授予或取消授予權限。", "dialog.checkStorage.button.grantPermission": "去授予權限", "dialog.checkStorage.button.doNotShowAgain": "不再提示", "dialog.downloadDialog.title": "發現新版本({version})", "dialog.downloadDialog.skipThisVersion": "跳過此版本", "dialog.downloadDialog.downloadUsingBrowser": "從瀏覽器下載", "dialog.downloadDialog.backupUrl": "備用連結", "dialog.editSheetDetail.sheetName": "歌單名", "dialog.subscriptionPluginDialog.title": "訂閱", "dialog.markdownDialog.openExternalLink": "請打開瀏覽器訪問頁面。請注意安全,謹防釣魚網站。", "dialog.markdownDialog.clickToShowImage": "點擊展示圖片", "dialog.markdownDialog.loadFailed": "圖片載入失敗", "panel.playList.title": "播放列表", "panel.playList.count": " ({count}首)", "panel.searchLrc.inputPlaceholder": "輸入歌曲名稱", "panel.searchLrc.toast.settingSuccess": "設定成功~", "panel.searchLrc.toast.failToSearch": "設定失敗!", "panel.addToMusicSheet.title": "添加到歌單 ({count}首)", "panel.addToMusicSheet.newMusicSheet": "新建歌單", "panel.addToMusicSheet.count": "{count}首", "panel.addToMusicSheet.toast.success": "已添加到歌單", "panel.addToMusicSheet.toast.fail": "添加到歌單失敗", "panel.associateLrc.title": "關聯歌詞", "panel.associateLrc.inputPlaceholder": "輸入要關聯歌詞的歌曲ID", "panel.associateLrc.targetExpired": "地址失效了,重新複製一下吧~", "panel.associateLrc.toast.success": "關聯歌詞成功", "panel.associateLrc.toast.fail": "關聯歌詞失敗", "panel.associateLrc.toast.unlinkSuccess": "取消關聯歌詞成功", "panel.createMusicSheet.title": "新建歌單", "panel.editMusicSheetInfo.title": "編輯歌單資訊", "panel.editMusicSheetInfo.sheetName": "歌單名", "panel.editMusicSheetInfo.toast.updateSuccess": "更新歌單資訊成功~", "panel.imageViewer.saveImage": "儲存圖片", "panel.imageViewer.saveImageSuccess": "圖片已儲存到 {path}", "panel.imageViewer.saveImageFail": "儲存圖片失敗: {reason}", "panel.colorPicker.title": "選擇顏色", "panel.createMusicSheet.inputLabel": "輸入框", "panel.importMusicSheet.title": "導入歌單", "panel.importMusicSheet.placeholder": "輸入目標歌單", "panel.importMusicSheet.importing": "正在導入中...", "panel.importMusicSheet.prepareImport": "準備導入", "panel.importMusicSheet.foundSongs": "發現{count}首歌曲! 現在開始導入嗎?", "panel.importMusicSheet.invalidLink": "連結有誤或目標歌單為空", "panel.musicItemLyricOptions.author": "作者: {artist}", "panel.musicItemLyricOptions.album": "專輯: {album}", "panel.musicItemLyricOptions.toggleDesktopLyric": "{status}桌面歌詞", "panel.musicItemLyricOptions.enableDesktopLyric": "開啟", "panel.musicItemLyricOptions.disableDesktopLyric": "關閉", "panel.musicItemLyricOptions.desktopLyricPermissionError": "開啟桌面歌詞失敗,無懸浮窗權限", "panel.musicItemLyricOptions.uploadLocalLyric": "上傳本地歌詞", "panel.musicItemLyricOptions.uploadLocalLyricTranslation": "上傳本地歌詞翻譯", "panel.musicItemLyricOptions.deleteLocalLyric": "刪除本地歌詞", "panel.musicItemLyricOptions.settingFail": "設定失敗: {reason}", "panel.musicItemLyricOptions.deleteFail": "刪除失敗: {reason}", "panel.musicItemOptions.author": "作者: {artist}", "panel.musicItemOptions.album": "專輯: {album}", "panel.musicItemOptions.downloaded": "已下載", "panel.musicItemOptions.readComment": "查看評論", "panel.musicItemOptions.deleteLocalDownload": "刪除本機下載", "panel.musicItemOptions.deleteLocalDownloadConfirm": "將會刪除已下載的本機檔案,確定繼續嗎?", "panel.musicItemOptions.associatedLyric": "已關聯歌詞 {platform}@{id}", "panel.musicItemOptions.associateLyric": "關聯歌詞", "panel.musicItemOptions.unassociateLyric": "解除關聯歌詞", "panel.musicItemOptions.unassociateLyricSuccess": "已解除關聯歌詞", "panel.musicItemOptions.timingClose": "定時關閉", "panel.musicItemOptions.clearPluginCache": "清除外掛快取(播放異常時使用)", "panel.musicItemOptions.cacheCleared": "快取已清除", "panel.musicItemOptions.deleteFailed": "刪除失敗", "panel.musicQuality.title": "設定{type}音質", "panel.searchLrc.unnamed": "(未命名)", "panel.searchLrc.notSupported": "搜尋歌詞", "panel.setFontSize.title": "設定字型大小", "panel.setFontSize.small": "小", "panel.setFontSize.standard": "標準", "panel.setFontSize.large": "大", "panel.setFontSize.extraLarge": "超大", "panel.setLyricOffset.title": "設定歌詞進度 ({status})", "panel.setLyricOffset.normal": "正常", "panel.setLyricOffset.delay": "延後{time}s", "panel.setLyricOffset.advance": "提前{time}s", "panel.setLyricOffset.reset": "重設", "panel.simpleInput.inputLabel": "輸入框", "panel.timingClose.countdown": "關閉倒數計時 {time}", "panel.timingClose.customize": "自訂關閉時間", "panel.timingClose.cancelScheduleClose": "取消定時關閉", "panel.timingClose.closeAfterPlay": "播放完歌曲再關閉", "panel.playRate.title": "播放速度", "panel.sheetTags.title": "歌單類別", "repeatMode.SHUFFLE": "隨機播放", "repeatMode.QUEUE": "清單循環", "repeatMode.SINGLE": "單曲循環" } ================================================ FILE: src/core/localMusicSheet.ts ================================================ import { StorageKeys, internalSerializeKey, supportLocalMediaType, } from "@/constants/commonConst"; import mp3Util, { IBasicMeta } from "@/native/mp3Util"; import { addFileScheme, getFileName } from "@/utils/fileUtils.ts"; import { getLocalPath, isSameMediaItem, } from "@/utils/mediaUtils"; import StateMapper from "@/utils/stateMapper"; import { getStorage, setStorage } from "@/utils/storage"; import CryptoJs from "crypto-js"; import { nanoid } from "nanoid"; import { useEffect, useState } from "react"; import { ReadDirItem, exists, readDir, unlink } from "react-native-fs"; let localSheet: IMusic.IMusicItem[] = []; const localSheetStateMapper = new StateMapper(() => localSheet); export async function setup() { const sheet = await getStorage(StorageKeys.LocalMusicSheet); if (sheet) { let validSheet: IMusic.IMusicItem[] = []; for (let musicItem of sheet) { const localPath = getLocalPath(musicItem); if (localPath && (await exists(localPath))) { validSheet.push(musicItem); } } if (validSheet.length !== sheet.length) { await setStorage(StorageKeys.LocalMusicSheet, validSheet); } localSheet = validSheet; } else { await setStorage(StorageKeys.LocalMusicSheet, []); } localSheetStateMapper.notify(); } export async function addMusic( musicItem: IMusic.IMusicItem | IMusic.IMusicItem[], ) { if (!Array.isArray(musicItem)) { musicItem = [musicItem]; } let newSheet = [...localSheet]; musicItem.forEach(mi => { if (localSheet.findIndex(_ => isSameMediaItem(mi, _)) === -1) { newSheet.push(mi); } }); await setStorage(StorageKeys.LocalMusicSheet, newSheet); localSheet = newSheet; localSheetStateMapper.notify(); } function addMusicDraft(musicItem: IMusic.IMusicItem | IMusic.IMusicItem[]) { if (!Array.isArray(musicItem)) { musicItem = [musicItem]; } let newSheet = [...localSheet]; musicItem.forEach(mi => { if (localSheet.findIndex(_ => isSameMediaItem(mi, _)) === -1) { newSheet.push(mi); } }); localSheet = newSheet; localSheetStateMapper.notify(); } async function saveLocalSheet() { await setStorage(StorageKeys.LocalMusicSheet, localSheet); } export async function removeMusic( musicItem: IMusic.IMusicItem, deleteOriginalFile = false, ) { const idx = localSheet.findIndex(_ => isSameMediaItem(_, musicItem)); let newSheet = [...localSheet]; if (idx !== -1) { const localMusicItem = localSheet[idx]; newSheet.splice(idx, 1); const localPath = musicItem[internalSerializeKey]?.localPath ?? localMusicItem[internalSerializeKey]?.localPath; if (deleteOriginalFile && localPath) { try { await unlink(localPath); } catch (e: any) { if (e.message !== "File does not exist") { throw e; } } } } localSheet = newSheet; localSheetStateMapper.notify(); saveLocalSheet(); } function parseFilename(fn: string): Partial | null { const data = fn.slice(0, fn.lastIndexOf(".")).split("@"); const [platform, id, title, artist] = data; if (!platform || !id) { return null; } return { id, platform: platform, title: title ?? "", artist: artist ?? "", }; } function localMediaFilter(filename: string) { return supportLocalMediaType.some(ext => filename.toLowerCase().endsWith(ext)); } let importToken: string | null = null; // 获取本地的文件列表 async function getMusicStats(folderPaths: string[]) { const _importToken = nanoid(); importToken = _importToken; const musicList: string[] = []; let peek: string | undefined; let dirFiles: ReadDirItem[] = []; while (folderPaths.length !== 0) { if (importToken !== _importToken) { throw new Error("Import Broken"); } peek = folderPaths.shift() as string; try { dirFiles = await readDir(peek); } catch { dirFiles = []; } dirFiles.forEach(item => { if (item.isDirectory() && !folderPaths.includes(item.path)) { folderPaths.push(item.path); } else if (localMediaFilter(item.path)) { musicList.push(item.path); } }); } return { musicList, token: _importToken }; } function cancelImportLocal() { importToken = null; } // 导入本地音乐 const groupNum = 25; async function importLocal(_folderPaths: string[]) { const folderPaths = [..._folderPaths.map(it => addFileScheme(it))]; const { musicList, token } = await getMusicStats(folderPaths); if (token !== importToken) { throw new Error("Import Broken"); } // 分组请求,不然序列化可能出问题 let metas: IBasicMeta[] = []; const groups = Math.ceil(musicList.length / groupNum); for (let i = 0; i < groups; ++i) { metas = metas.concat( await mp3Util.getMediaMeta( musicList.slice(i * groupNum, (i + 1) * groupNum), ), ); } if (token !== importToken) { throw new Error("Import Broken"); } const musicItems: IMusic.IMusicItem[] = await Promise.all( musicList.map(async (musicPath, index) => { let { platform, id, title, artist } = parseFilename(getFileName(musicPath, true)) ?? {}; const meta = metas[index]; if (!platform || !id) { platform = "本地"; id = CryptoJs.MD5(musicPath).toString(CryptoJs.enc.Hex); } return { id, platform, title: title ?? meta?.title ?? getFileName(musicPath), artist: artist ?? meta?.artist ?? "未知歌手", duration: parseInt(meta?.duration ?? "0", 10) / 1000, album: meta?.album ?? "未知专辑", artwork: "", [internalSerializeKey]: { localPath: musicPath, }, } as IMusic.IMusicItem; }), ); if (token !== importToken) { throw new Error("Import Broken"); } addMusic(musicItems); } /** 是否为本地音乐 */ function isLocalMusic( musicItem: ICommon.IMediaBase | null, ): IMusic.IMusicItem | undefined { return musicItem ? localSheet.find(_ => isSameMediaItem(_, musicItem)) : undefined; } /** 状态-是否为本地音乐 */ function useIsLocal(musicItem: IMusic.IMusicItem | null) { const localMusicState = localSheetStateMapper.useMappedState(); const [isLocal, setIsLocal] = useState(!!isLocalMusic(musicItem)); useEffect(() => { if (!musicItem) { setIsLocal(false); } else { setIsLocal(!!isLocalMusic(musicItem)); } }, [localMusicState, musicItem]); return isLocal; } function getMusicList() { return localSheet; } async function updateMusicList(newSheet: IMusic.IMusicItem[]) { const _localSheet = [...newSheet]; try { await setStorage(StorageKeys.LocalMusicSheet, _localSheet); localSheet = _localSheet; localSheetStateMapper.notify(); } catch {} } const LocalMusicSheet = { setup, addMusic, removeMusic, addMusicDraft, saveLocalSheet, importLocal, cancelImportLocal, isLocalMusic, useIsLocal, getMusicList, useMusicList: localSheetStateMapper.useMappedState, updateMusicList, }; export default LocalMusicSheet; ================================================ FILE: src/core/lyricManager.ts ================================================ import { IAppConfig } from "@/types/core/config"; import { ITrackPlayer } from "@/types/core/trackPlayer"; import { IInjectable } from "@/types/infra"; import LyricParser, { IParsedLrcItem } from "@/utils/lrcParser"; import { getMediaExtraProperty, patchMediaExtra } from "@/utils/mediaExtra"; import { isSameMediaItem } from "@/utils/mediaUtils"; import minDistance from "@/utils/minDistance"; import { atom, getDefaultStore, useAtomValue } from "jotai"; import { Plugin } from "./pluginManager"; import pathConst from "@/constants/pathConst"; import LyricUtil from "@/native/lyricUtil"; import { checkAndCreateDir } from "@/utils/fileUtils"; import PersistStatus from "@/utils/persistStatus"; import CryptoJs from "crypto-js"; import { unlink, writeFile } from "react-native-fs"; import RNTrackPlayer, { Event } from "react-native-track-player"; import { TrackPlayerEvents } from "@/core.defination/trackPlayer"; import { IPluginManager } from "@/types/core/pluginManager"; interface ILyricState { loading: boolean; lyrics: IParsedLrcItem[]; hasTranslation: boolean; meta?: Record; } const defaultLyricState = { loading: true, lyrics: [], hasTranslation: false, }; const lyricStateAtom = atom(defaultLyricState); const currentLyricItemAtom = atom(null); class LyricManager implements IInjectable { private trackPlayer!: ITrackPlayer; private appConfig!: IAppConfig; private pluginManager!: IPluginManager; private lyricParser: LyricParser | null = null; get currentLyricItem() { return getDefaultStore().get(currentLyricItemAtom); } get lyricState() { return getDefaultStore().get(lyricStateAtom); } injectDependencies(trackPlayerService: ITrackPlayer, appConfigService: IAppConfig, pluginManager: IPluginManager): void { this.trackPlayer = trackPlayerService; this.appConfig = appConfigService; this.pluginManager = pluginManager; } setup() { // 更新歌词 this.trackPlayer.on(TrackPlayerEvents.CurrentMusicChanged, (musicItem) => { this.refreshLyric(true, true); if (this.appConfig.getConfig("lyric.showStatusBarLyric")) { if (musicItem) { LyricUtil.setStatusBarLyricText( `${musicItem.title} - ${musicItem.artist}`,); } else { LyricUtil.setStatusBarLyricText("MusicFree"); } } }); RNTrackPlayer.addEventListener(Event.PlaybackProgressUpdated, evt => { const parser = this.lyricParser; if (!parser || !this.trackPlayer.isCurrentMusic(parser.musicItem)) { return; } const currentLyricItem = getDefaultStore().get(currentLyricItemAtom); const newLyricItem = parser.getPosition(evt.position); if (currentLyricItem?.lrc !== newLyricItem?.lrc) { // 更新当前歌词状态 getDefaultStore().set(currentLyricItemAtom, newLyricItem ?? null); // 更新状态栏歌词 const showTranslation = PersistStatus.get("lyric.showTranslation"); if (this.appConfig.getConfig("lyric.showStatusBarLyric")) { LyricUtil.setStatusBarLyricText( (newLyricItem?.lrc ?? "") + (showTranslation ? `\n${newLyricItem?.translation ?? ""}` : ""), ); } } }); if (this.appConfig.getConfig("lyric.showStatusBarLyric")) { const statusBarLyricConfig = { topPercent: this.appConfig.getConfig("lyric.topPercent"), leftPercent: this.appConfig.getConfig("lyric.leftPercent"), align: this.appConfig.getConfig("lyric.align"), color: this.appConfig.getConfig("lyric.color"), backgroundColor: this.appConfig.getConfig("lyric.backgroundColor"), widthPercent: this.appConfig.getConfig("lyric.widthPercent"), fontSize: this.appConfig.getConfig("lyric.fontSize"), }; LyricUtil.showStatusBarLyric( "MusicFree", statusBarLyricConfig ?? {} ); } this.refreshLyric(true); } associateLyric(musicItem: IMusic.IMusicItem, linkToMusicItem: ICommon.IMediaBase) { if (!musicItem || !linkToMusicItem) { return false; } // 如果当前音乐项和关联的音乐项相同,则不需要重新关联 if (isSameMediaItem(musicItem, linkToMusicItem)) { patchMediaExtra(musicItem, { associatedLrc: undefined, }); return false; } else { patchMediaExtra(musicItem, { associatedLrc: linkToMusicItem, }); if (this.trackPlayer.isCurrentMusic(musicItem)) { this.refreshLyric(false); } return true; } } unassociateLyric(musicItem: IMusic.IMusicItem) { if (!musicItem) { return; } patchMediaExtra(musicItem, { associatedLrc: undefined, }); if (this.trackPlayer.isCurrentMusic(musicItem)) { this.refreshLyric(false); } } async uploadLocalLyric(musicItem: IMusic.IMusicItem, lyricContent: string, type: "raw" | "translation" = "raw") { if (!musicItem) { return; } const platformHash = CryptoJs.MD5(musicItem.platform).toString( CryptoJs.enc.Hex, ); const idHash: string = CryptoJs.MD5(musicItem.id).toString( CryptoJs.enc.Hex, ); // 检查是否缓存文件夹存在 await checkAndCreateDir(pathConst.localLrcPath + platformHash); await writeFile(pathConst.localLrcPath + platformHash + "/" + idHash + (type === "raw" ? "" : ".tran") + ".lrc", lyricContent, "utf8"); if (this.trackPlayer.isCurrentMusic(musicItem)) { this.refreshLyric(false, false); } } async removeLocalLyric(musicItem: IMusic.IMusicItem) { if (!musicItem) { return; } const platformHash = CryptoJs.MD5(musicItem.platform).toString( CryptoJs.enc.Hex, ); const idHash: string = CryptoJs.MD5(musicItem.id).toString( CryptoJs.enc.Hex, ); const basePath = pathConst.localLrcPath + platformHash + "/" + idHash; await unlink(basePath + ".lrc").catch(() => { }); await unlink(basePath + ".tran.lrc").catch(() => { }); if (this.trackPlayer.isCurrentMusic(musicItem)) { this.refreshLyric(false, false); } } updateLyricOffset(musicItem: IMusic.IMusicItem, offset: number) { if (!musicItem) { return; } // 更新歌词偏移 patchMediaExtra(musicItem, { lyricOffset: offset, }); if (this.trackPlayer.isCurrentMusic(musicItem)) { this.refreshLyric(true, false); } } private setLyricAsLoadingState() { getDefaultStore().set(lyricStateAtom, { loading: true, lyrics: [], hasTranslation: false, }); getDefaultStore().set(currentLyricItemAtom, null); } private setLyricAsNoLyricState() { getDefaultStore().set(lyricStateAtom, { loading: false, lyrics: [], hasTranslation: false, }); getDefaultStore().set(currentLyricItemAtom, null); if (this.appConfig.getConfig("lyric.showStatusBarLyric")) { const musicItem = this.trackPlayer.currentMusic; LyricUtil.setStatusBarLyricText(musicItem ? `${musicItem.title} - ${musicItem.artist}` : "MusicFree"); } } private async refreshLyric(skipFetchLyricSourceIfSame: boolean = true, ignoreProgress: boolean = false) { const currentMusicItem = this.trackPlayer.currentMusic; // 如果没有当前音乐项,重置歌词状态 if (!currentMusicItem) { this.setLyricAsNoLyricState(); return; } try { let lrcSource: ILyric.ILyricSource | null; if (skipFetchLyricSourceIfSame && this.lyricParser && this.trackPlayer.isCurrentMusic(this.lyricParser.musicItem)) { lrcSource = this.lyricParser.lyricSource ?? null; } else { // 重置歌词状态 this.setLyricAsLoadingState(); lrcSource = (await this.pluginManager.getByMedia(currentMusicItem)?.methods?.getLyric(currentMusicItem)) ?? null; } // 切换到其他歌曲了, 直接返回 if (!this.trackPlayer.isCurrentMusic(currentMusicItem)) { return; } // 如果歌词源不存在,并且开启自动搜索歌词 if (!lrcSource && this.appConfig.getConfig("lyric.autoSearchLyric")) { // 重置歌词状态 this.setLyricAsLoadingState(); lrcSource = await this.searchSimilarLyric(currentMusicItem); } // 切换到其他歌曲了, 直接返回 if (!this.trackPlayer.isCurrentMusic(currentMusicItem)) { return; } // 如果源不存在,恢复默认设置 if (!lrcSource) { this.setLyricAsNoLyricState(); this.lyricParser = null; return; } this.lyricParser = new LyricParser(lrcSource.rawLrc!, { extra: { offset: (getMediaExtraProperty(currentMusicItem, "lyricOffset") || 0) * -1, }, musicItem: currentMusicItem, lyricSource: lrcSource, translation: lrcSource.translation, }); getDefaultStore().set(lyricStateAtom, { loading: false, lyrics: this.lyricParser.getLyricItems(), hasTranslation: !!lrcSource.translation, meta: this.lyricParser.getMeta(), }); const currentLyric = ignoreProgress ? (this.lyricParser.getLyricItems()?.[0] ?? null) : this.lyricParser.getPosition((await this.trackPlayer.getProgress()).position); getDefaultStore().set(currentLyricItemAtom, currentLyric || null); if (this.appConfig.getConfig("lyric.showStatusBarLyric")) { if (currentLyric) { LyricUtil.setStatusBarLyricText( (currentLyric?.lrc ?? "") + (this.lyricParser.hasTranslation ? `\n${currentLyric?.translation ?? ""}` : ""), ); } else { const musicItem = this.trackPlayer.currentMusic; LyricUtil.setStatusBarLyricText(musicItem ? `${musicItem.title} - ${musicItem.artist}` : "MusicFree"); } } } catch (err) { if (this.trackPlayer.isCurrentMusic(currentMusicItem)) { this.lyricParser = null; this.setLyricAsNoLyricState(); } } } /** * 检索最接近的歌词 * @param musicItem * @returns */ private async searchSimilarLyric(musicItem: IMusic.IMusicItem) { const keyword = musicItem.alias || musicItem.title; const plugins = this.pluginManager.getSearchablePlugins("lyric"); let distance = Infinity; let minDistanceMusicItem; let targetPlugin: Plugin | null = null; for (let plugin of plugins) { // 如果插件不是当前音乐的插件,或者当前音乐不是正在播放的音乐,则跳过 if ( !this.trackPlayer.isCurrentMusic(musicItem) ) { return null; } if (plugin.name === musicItem.platform) { // 如果插件是当前音乐的插件,则跳过 continue; } const results = await plugin.methods .search(keyword, 1, "lyric") .catch(() => null); // 取前两个 const firstTwo = results?.data?.slice(0, 2) || []; for (let item of firstTwo) { if ( item.title === keyword && item.artist === musicItem.artist ) { distance = 0; minDistanceMusicItem = item; targetPlugin = plugin; break; } else { const dist = minDistance(keyword, musicItem.title) + minDistance(item.artist, musicItem.artist); if (dist < distance) { distance = dist; minDistanceMusicItem = item; targetPlugin = plugin; } } } if (distance === 0) { break; } } if (minDistanceMusicItem && targetPlugin) { return await targetPlugin.methods .getLyric(minDistanceMusicItem) .catch(() => null); } return null; } } const lyricManager = new LyricManager(); export default lyricManager; export const useLyricState = () => useAtomValue(lyricStateAtom); export const useCurrentLyricItem = () => useAtomValue(currentLyricItemAtom); ================================================ FILE: src/core/mediaCache.ts ================================================ import { addFileScheme } from "@/utils/fileUtils"; import getOrCreateMMKV from "@/utils/getOrCreateMMKV"; import { safeParse } from "@/utils/jsonUtil"; import { getMediaUniqueKey } from "@/utils/mediaUtils"; import { exists, unlink } from "react-native-fs"; // Internal Method const mediaCacheStore = getOrCreateMMKV("cache.MediaCache", true); // 最多缓存800条数据 const maxCacheCount = 800; /** 获取meta信息 */ const getMediaCache = (mediaItem: ICommon.IMediaBase) => { if (mediaItem.platform && mediaItem.id) { const cacheMediaItem = mediaCacheStore.getString( getMediaUniqueKey(mediaItem), ); return cacheMediaItem ? safeParse(cacheMediaItem) : null; } return null; }; /** 设置meta信息 */ const setMediaCache = (mediaItem: ICommon.IMediaBase) => { if (mediaItem.platform && mediaItem.id) { const allKeys = mediaCacheStore.getAllKeys(); if (allKeys.length >= maxCacheCount) { // TODO: 随机删一半 for (let i = 0; i < maxCacheCount / 2; ++i) { const rawCacheMedia = mediaCacheStore.getString(allKeys[i]); const cacheData = rawCacheMedia ? safeParse(rawCacheMedia) : null; clearLocalCaches(cacheData); mediaCacheStore.delete(allKeys[i]); } } mediaCacheStore.set(getMediaUniqueKey(mediaItem), JSON.stringify(mediaItem)); return true; } return false; }; async function clearLocalCaches(cacheData: IMusic.IMusicItemCache) { if (cacheData.$localLyric) { await checkPathAndRemove(cacheData.$localLyric.rawLrc); await checkPathAndRemove(cacheData.$localLyric.translation); } } async function checkPathAndRemove(filePath?: string) { if (!filePath) { return; } filePath = addFileScheme(filePath); if (await exists(filePath)) { unlink(filePath); } } /** 移除缓存信息 */ const removeMediaCache = (mediaItem: ICommon.IMediaBase) => { if (mediaItem.platform && mediaItem.id) { mediaCacheStore.delete(getMediaUniqueKey(mediaItem)); } return false; }; const MediaCache = { getMediaCache, setMediaCache, removeMediaCache, }; export default MediaCache; ================================================ FILE: src/core/musicHistory.ts ================================================ import { musicHistorySheetId } from "@/constants/commonConst"; import { isSameMediaItem } from "@/utils/mediaUtils"; import { getStorage } from "@/utils/storage"; import { atom, getDefaultStore, useAtomValue } from "jotai"; import type { IAppConfig } from "@/types/core/config"; import type { IMusicHistory } from "@/types/core/musicHistory.js"; import type { IInjectable } from "@/types/infra"; import appMeta from "./appMeta"; import getOrCreateMMKV from "@/utils/getOrCreateMMKV"; import { safeParse, safeStringify } from "@/utils/jsonUtil"; const musicHistoryAtom = atom([]); const musicHistoryStore = getOrCreateMMKV("music.MusicHistory"); class MusicHistory implements IMusicHistory, IInjectable { private configService!: IAppConfig; injectDependencies(configService: IAppConfig): void { this.configService = configService; } get history() { return getDefaultStore().get(musicHistoryAtom); } async setup() { if (appMeta.historySheetVersion < 1) { await this.migrateToMMKV(); } const history = safeParse(musicHistoryStore.getString("history") ?? "[]") as IMusic.IMusicItem[]; getDefaultStore().set(musicHistoryAtom, history ?? []); } async addMusic(musicItem: IMusic.IMusicItem) { const newMusicHistory = [ musicItem, ...this.history .filter(item => !isSameMediaItem(item, musicItem)), ].slice(0, this.configService.getConfig("basic.maxHistoryLen") ?? 50); musicHistoryStore.set("history", safeStringify(newMusicHistory)); getDefaultStore().set(musicHistoryAtom, newMusicHistory); } async removeMusic(musicItem: IMusic.IMusicItem) { const newMusicHistory = this.history .filter(item => !isSameMediaItem(item, musicItem)); musicHistoryStore.set("history", safeStringify(newMusicHistory)); getDefaultStore().set(musicHistoryAtom, newMusicHistory); } async clearMusic() { musicHistoryStore.set("history", safeStringify([])); getDefaultStore().set(musicHistoryAtom, []); } async setHistory(newHistory: IMusic.IMusicItem[]) { musicHistoryStore.set("history", safeStringify(newHistory)); getDefaultStore().set(musicHistoryAtom, newHistory); } async migrateToMMKV() { const history = await getStorage(musicHistorySheetId); if (history?.length) { musicHistoryStore.set("history", safeStringify(history)); } appMeta.setHistorySheetVersion(1); } } export function useMusicHistory() { return useAtomValue(musicHistoryAtom); } const musicHistory = new MusicHistory(); export default musicHistory; ================================================ FILE: src/core/musicSheet/index.ts ================================================ /** * 歌单管理 */ import { ResumeMode, SortType, localPluginPlatform } from "@/constants/commonConst.ts"; import { IAppConfig } from "@/types/core/config"; import { IInjectable } from "@/types/infra"; import { isSameMediaItem } from "@/utils/mediaUtils"; import EventEmitter from "eventemitter3"; import { Immer } from "immer"; import { atom, getDefaultStore, useAtomValue } from "jotai"; import { nanoid } from "nanoid"; import { useEffect, useMemo, useState } from "react"; import migrate, { migrateV2 } from "./migrate.ts"; import SortedMusicList from "./sortedMusicList.ts"; import storage from "./storage.ts"; const produce = new Immer({ autoFreeze: false, }).produce; const _defaultSheet: IMusic.IMusicSheetItemBase = { id: "favorite", platform: localPluginPlatform, coverImg: undefined, title: "我喜欢", worksNum: 0, }; const musicSheetsBaseAtom = atom([]); const starredMusicSheetsAtom = atom([]); // key: sheetId, value: musicList const musicListMap = new Map(); const ee = new EventEmitter<{ UpdateMusicList: (updateInfo: { sheetId: string; updateType: "length" | "resort"; // 更新类型 }) => void; UpdateSheetBasic: (data: { sheetId: string; }) => void; }>(); class MusicSheetClazz implements IInjectable { private appConfig!: IAppConfig; defaultSheet: IMusic.IMusicSheetItemBase = _defaultSheet; injectDependencies(appConfigService: IAppConfig): void { this.appConfig = appConfigService; } async setup() { // 升级逻辑 - 从 AsyncStorage 升级到 MMKV await migrate(); try { const allSheets: IMusic.IMusicSheetItemBase[] = storage.getSheets(); if (!Array.isArray(allSheets)) { throw new Error("not exist"); } let needRestore = false; if (!allSheets.length) { allSheets.push({ ..._defaultSheet, }); needRestore = true; } if (allSheets[0].id !== _defaultSheet.id) { const defaultSheetIndex = allSheets.findIndex( it => it.id === _defaultSheet.id, ); if (defaultSheetIndex === -1) { allSheets.unshift({ ..._defaultSheet, }); } else { const firstSheet = allSheets.splice(defaultSheetIndex, 1); allSheets.unshift(firstSheet[0]); } needRestore = true; } if (needRestore) { await storage.setSheets(allSheets); } for (let sheet of allSheets) { const musicList = storage.getMusicList(sheet.id); const sortType = storage.getSheetMeta(sheet.id, "sort") as SortType; sheet.worksNum = musicList.length; migrateV2.migrate(sheet.id, musicList); musicListMap.set( sheet.id, new SortedMusicList(musicList, sortType, true), ); sheet.worksNum = musicList.length; ee.emit("UpdateMusicList", { sheetId: sheet.id, updateType: "length", }); } migrateV2.done(); getDefaultStore().set(musicSheetsBaseAtom, allSheets); // 收藏的歌单 const starredSheets: IMusic.IMusicSheetItem[] = storage.getStarredSheets() || []; getDefaultStore().set(starredMusicSheetsAtom, starredSheets); } catch (e: any) { if (e.message === "not exist") { await storage.setSheets([_defaultSheet]); await storage.setMusicList(_defaultSheet.id, []); getDefaultStore().set(musicSheetsBaseAtom, [_defaultSheet]); musicListMap.set( _defaultSheet.id, new SortedMusicList([], SortType.None, true), ); } } } // 获取音乐 getSortedMusicListBySheetId(sheetId: string) { let musicList: SortedMusicList; if (!musicListMap.has(sheetId)) { musicList = new SortedMusicList([], SortType.None, true); musicListMap.set(sheetId, musicList); } else { musicList = musicListMap.get(sheetId)!; } return musicList; } /** * 更新基本信息 * @param sheetId 歌单ID * @param data 歌单数据 */ async updateMusicSheetBase( sheetId: string, data: Partial, ) { const musicSheets = getDefaultStore().get(musicSheetsBaseAtom); const targetSheetIndex = musicSheets.findIndex(it => it.id === sheetId); if (targetSheetIndex === -1) { return; } const newMusicSheets = produce(musicSheets, draft => { draft[targetSheetIndex] = { ...draft[targetSheetIndex], ...data, id: sheetId, }; return draft; }); await storage.setSheets(newMusicSheets); getDefaultStore().set(musicSheetsBaseAtom, newMusicSheets); ee.emit("UpdateSheetBasic", { sheetId, }); } /** * 新建歌单 * @param title 歌单名称 */ async addSheet(title: string) { const newId = nanoid(); const musicSheets = getDefaultStore().get(musicSheetsBaseAtom); const newSheets: IMusic.IMusicSheetItemBase[] = [ musicSheets[0], { title, platform: localPluginPlatform, id: newId, coverImg: undefined, worksNum: 0, createAt: Date.now(), }, ...musicSheets.slice(1), ]; // 写入存储 await storage.setSheets(newSheets); await storage.setMusicList(newId, []); // 更新状态 getDefaultStore().set(musicSheetsBaseAtom, newSheets); let defaultSortType = this.appConfig.getConfig("basic.musicOrderInLocalSheet"); if ( defaultSortType && [ SortType.Newest, SortType.Artist, SortType.Album, SortType.Oldest, SortType.Title, ].includes(defaultSortType) ) { storage.setSheetMeta(newId, "sort", defaultSortType); } else { defaultSortType = SortType.None; } musicListMap.set(newId, new SortedMusicList([], defaultSortType, true)); return newId; } backupSheets() { const allSheets = getDefaultStore().get(musicSheetsBaseAtom); return allSheets.map(it => ({ ...it, musicList: musicListMap.get(it.id)?.musicList || [], })) as IMusic.IMusicSheetItem[]; } async resumeSheets( sheets: IMusic.IMusicSheetItem[], resumeMode: ResumeMode, ) { if (resumeMode === ResumeMode.Append) { // 逆序恢复,最新创建的在最上方 for (let i = sheets.length - 1; i >= 0; --i) { const newSheetId = await this.addSheet(sheets[i].title || ""); await this.addMusic(newSheetId, sheets[i].musicList || []); } return; } // 1. 分离默认歌单和其他歌单 const defaultSheetIndex = sheets.findIndex(it => it.id === _defaultSheet.id); let exportedDefaultSheet: IMusic.IMusicSheetItem | null = null; if (defaultSheetIndex !== -1) { exportedDefaultSheet = sheets.splice(defaultSheetIndex, 1)[0]; } // 2. 合并默认歌单 await this.addMusic(_defaultSheet.id, exportedDefaultSheet?.musicList || []); // 3. 合并其他歌单 if (resumeMode === ResumeMode.OverwriteDefault) { // 逆序恢复,最新创建的在最上方 for (let i = sheets.length - 1; i >= 0; --i) { const newSheetId = await this.addSheet(sheets[i].title || ""); await this.addMusic(newSheetId, sheets[i].musicList || []); } } else { // 合并同名 const existsSheetIdMap: Record = {}; const allSheets = getDefaultStore().get(musicSheetsBaseAtom); allSheets.forEach(it => { existsSheetIdMap[it.title!] = it.id; }); for (let i = sheets.length - 1; i >= 0; --i) { let newSheetId = existsSheetIdMap[sheets[i].title || ""]; if (!newSheetId) { newSheetId = await this.addSheet(sheets[i].title || ""); } await this.addMusic(newSheetId, sheets[i].musicList || []); } } } /** * 删除歌单 * @param sheetId 歌单id */ async removeSheet(sheetId: string) { // 只能删除非默认歌单 if (sheetId === _defaultSheet.id) { return; } const musicSheets = getDefaultStore().get(musicSheetsBaseAtom); // 删除后的歌单 const newSheets = musicSheets.filter(item => item.id !== sheetId); // 写入存储 storage.removeMusicList(sheetId); await storage.setSheets(newSheets); // 修改状态 getDefaultStore().set(musicSheetsBaseAtom, newSheets); musicListMap.delete(sheetId); } /** * 向歌单内添加音乐 * @param sheetId 歌单id * @param musicItem 音乐 */ async addMusic( sheetId: string, musicItem: IMusic.IMusicItem | Array, ) { const now = Date.now(); if (!Array.isArray(musicItem)) { musicItem = [musicItem]; } const taggedMusicItems = musicItem.map((it, index) => ({ ...it, $timestamp: now, $sortIndex: musicItem.length - index, })); let musicList = this.getSortedMusicListBySheetId(sheetId); const addedCount = musicList.add(taggedMusicItems); // Update if (!addedCount) { return; } const musicSheets = getDefaultStore().get(musicSheetsBaseAtom); if ( !musicSheets .find(_ => _.id === sheetId) ?.coverImg?.startsWith?.("file://") ) { await this.updateMusicSheetBase(sheetId, { coverImg: musicList.at(0)?.artwork, }); } // 更新音乐数量 getDefaultStore().set( musicSheetsBaseAtom, produce(draft => { const musicSheet = draft.find(it => it.id === sheetId); if (musicSheet) { musicSheet.worksNum = musicList.length; } }), ); await storage.setMusicList(sheetId, musicList.musicList); ee.emit("UpdateMusicList", { sheetId, updateType: "length", }); } async removeMusicByIndex(sheetId: string, indices: number | number[]) { if (!Array.isArray(indices)) { indices = [indices]; } const musicList = this.getSortedMusicListBySheetId(sheetId); musicList.removeByIndex(indices); // Update const musicSheets = getDefaultStore().get(musicSheetsBaseAtom); if ( !musicSheets .find(_ => _.id === sheetId) ?.coverImg?.startsWith("file://") ) { await this.updateMusicSheetBase(sheetId, { coverImg: musicList.at(0)?.artwork, }); } // 更新音乐数量 getDefaultStore().set( musicSheetsBaseAtom, produce(draft => { const musicSheet = draft.find(it => it.id === sheetId); if (musicSheet) { musicSheet.worksNum = musicList.length; } }), ); await storage.setMusicList(sheetId, musicList.musicList); ee.emit("UpdateMusicList", { sheetId, updateType: "length", }); } async removeMusic( sheetId: string, musicItems: IMusic.IMusicItem | IMusic.IMusicItem[], ) { if (!Array.isArray(musicItems)) { musicItems = [musicItems]; } const musicList = this.getSortedMusicListBySheetId(sheetId); musicList.remove(musicItems); // Update const musicSheets = getDefaultStore().get(musicSheetsBaseAtom); let patchData: Partial = {}; if ( !musicSheets .find(_ => _.id === sheetId) ?.coverImg?.startsWith?.("file://") ) { patchData.coverImg = musicList.at(0)?.artwork; } patchData.worksNum = musicList.length; await this.updateMusicSheetBase(sheetId, { coverImg: musicList.at(0)?.artwork, }); await storage.setMusicList(sheetId, musicList.musicList); ee.emit("UpdateMusicList", { sheetId, updateType: "length", }); } async setSortType(sheetId: string, sortType: SortType) { const musicList = this.getSortedMusicListBySheetId(sheetId); musicList.setSortType(sortType); // update await storage.setMusicList(sheetId, musicList.musicList); storage.setSheetMeta(sheetId, "sort", sortType); ee.emit("UpdateMusicList", { sheetId, updateType: "resort", }); } async manualSort( sheetId: string, musicListAfterSort: IMusic.IMusicItem[], ) { const musicList = this.getSortedMusicListBySheetId(sheetId); musicList.manualSort(musicListAfterSort); // update await storage.setMusicList(sheetId, musicList.musicList); storage.setSheetMeta(sheetId, "sort", SortType.None); ee.emit("UpdateMusicList", { sheetId, updateType: "resort", }); } getSheetMeta = storage.getSheetMeta; /*********** 远程歌单的收藏逻辑 ***********/ async starMusicSheet(musicSheet: IMusic.IMusicSheetItem) { const store = getDefaultStore(); const starredSheets: IMusic.IMusicSheetItem[] = store.get( starredMusicSheetsAtom, ); const newVal = [musicSheet, ...starredSheets]; store.set(starredMusicSheetsAtom, newVal); await storage.setStarredSheets(newVal); } async unstarMusicSheet(musicSheet: IMusic.IMusicSheetItemBase) { const store = getDefaultStore(); const starredSheets: IMusic.IMusicSheetItem[] = store.get( starredMusicSheetsAtom, ); const newVal = starredSheets.filter( it => !isSameMediaItem( it as ICommon.IMediaBase, musicSheet as ICommon.IMediaBase, ), ); store.set(starredMusicSheetsAtom, newVal); await storage.setStarredSheets(newVal); } } const MusicSheet = new MusicSheetClazz(); export default MusicSheet; function useSheetsBase() { return useAtomValue(musicSheetsBaseAtom); } // sheetId should not change function useSheetItem(sheetId: string) { const sheetsBase = useAtomValue(musicSheetsBaseAtom); const [sheetItem, setSheetItem] = useState({ ...(sheetsBase.find(it => it.id === sheetId) || ({} as IMusic.IMusicSheetItemBase)), musicList: musicListMap.get(sheetId)?.musicList || [], }); useEffect(() => { const onUpdateMusicList = ({ sheetId: updatedSheetId }) => { if (updatedSheetId !== sheetId) { return; } setSheetItem(prev => ({ ...prev, musicList: musicListMap.get(sheetId)?.musicList || [], })); }; const onUpdateSheetBasic = ({ sheetId: updatedSheetId }) => { if (updatedSheetId !== sheetId) { return; } setSheetItem(prev => ({ ...prev, ...(getDefaultStore() .get(musicSheetsBaseAtom) .find(it => it.id === sheetId) || {}), })); }; ee.on("UpdateMusicList", onUpdateMusicList); ee.on("UpdateSheetBasic", onUpdateSheetBasic); return () => { ee.off("UpdateMusicList", onUpdateMusicList); ee.off("UpdateSheetBasic", onUpdateSheetBasic); }; }, []); return sheetItem; } function useFavorite(musicItem: IMusic.IMusicItem | null) { const [fav, setFav] = useState(false); useEffect(() => { const onUpdateMusicList = ({ sheetId: updatedSheetId, updateType }) => { if (updatedSheetId !== _defaultSheet.id || updateType === "resort") { return; } setFav(musicListMap.get(_defaultSheet.id)?.has(musicItem) || false); }; ee.on("UpdateMusicList", onUpdateMusicList); setFav(musicListMap.get(_defaultSheet.id)?.has(musicItem) || false); return () => { ee.off("UpdateMusicList", onUpdateMusicList); }; }, [musicItem]); return fav; } function useSheetIsStarred( musicSheet?: IMusic.IMusicSheetItem | null, ) { // TODO: 类型有问题 const musicSheets = useAtomValue(starredMusicSheetsAtom); return useMemo(() => { if (!musicSheet) { return false; } return ( musicSheets.findIndex(it => isSameMediaItem( it as ICommon.IMediaBase, musicSheet as ICommon.IMediaBase, ), ) !== -1 ); }, [musicSheet, musicSheets]); } function useStarredSheets() { return useAtomValue(starredMusicSheetsAtom); } export { useSheetIsStarred, useSheetsBase, useSheetItem, useStarredSheets, useFavorite }; ================================================ FILE: src/core/musicSheet/migrate.ts ================================================ import { getStorage as oldGetStorage } from "@/utils/storage"; import storage from "@/core/musicSheet/storage.ts"; import AsyncStorage from "@react-native-async-storage/async-storage"; import appMeta from "../appMeta"; export default async function migrate() { const dbUpdated = appMeta.musicSheetVersion > 1; if (dbUpdated) { return; } try { // 原来的musicSheets const musicSheets: IMusic.IMusicSheetItemBase[] = await oldGetStorage( "music-sheets", ); if (!musicSheets) { appMeta.setMusicSheetVersion(1); return; } await storage.setSheets(musicSheets); await AsyncStorage.removeItem("music-sheets"); for (let sheet of musicSheets) { const musicList = await oldGetStorage(sheet.id); await storage.setMusicList(sheet.id, musicList); await AsyncStorage.removeItem(sheet.id); } appMeta.setMusicSheetVersion(1); } catch (e) { console.warn("升级失败", e); } } export const migrateV2 = { migrate(sheetId: string, musicItems: IMusic.IMusicItem[]) { const dbUpdated = appMeta.musicSheetVersion === 2; if (dbUpdated) { return; } let dirty = false; const now = Date.now(); musicItems.forEach((it, index) => { if (!it.$timestamp || it.$sortIndex === undefined) { it.$timestamp = now; it.$sortIndex = index; dirty = true; } }); if (dirty) { storage.setMusicList(sheetId, musicItems); } }, done() { appMeta.setMusicSheetVersion(2); }, }; ================================================ FILE: src/core/musicSheet/sortedMusicList.ts ================================================ import { SortType } from "@/constants/commonConst.ts"; import { isSameMediaItem } from "@/utils/mediaUtils"; import { createMediaIndexMap } from "@/utils/mediaIndexMap.ts"; // Bug: localeCompare is slow sometimes https://github.com/facebook/hermes/issues/867 const collator = new Intl.Collator("zh"); /// Compare Functions const compareTitle = (a: IMusic.IMusicItem, b: IMusic.IMusicItem) => collator.compare(a.title, b.title); const compareArtist = (a: IMusic.IMusicItem, b: IMusic.IMusicItem) => collator.compare(a.artist, b.artist); const compareAlbum = (a: IMusic.IMusicItem, b: IMusic.IMusicItem) => collator.compare(a.album, b.album); const compareTimeNewToOld = (b: IMusic.IMusicItem, a: IMusic.IMusicItem) => { const timestamp = (a.$timestamp || 0) - (b.$timestamp || 0); if (timestamp === 0) { return (a.$sortIndex || 0) - (b.$sortIndex || 0); } else { return timestamp; } }; const compareTimeOldToNew = (a: IMusic.IMusicItem, b: IMusic.IMusicItem) => { const timestamp = (a.$timestamp || 0) - (b.$timestamp || 0); if (timestamp === 0) { return (a.$sortIndex || 0) - (b.$sortIndex || 0); } else { return timestamp; } }; const compareFunctionMap = { [SortType.Title]: compareTitle, [SortType.Artist]: compareArtist, [SortType.Album]: compareAlbum, [SortType.Newest]: compareTimeNewToOld, [SortType.Oldest]: compareTimeOldToNew, } as const; export default class SortedMusicList { private array: IMusic.IMusicItem[] = []; private sortType: SortType = SortType.None; private countMap = new Map>(); get musicList() { return this.array; } get firstMusic() { return this.array[0] || null; } get platforms() { return [...this.countMap.keys()]; } get length() { return this.array.length; } constructor( musicItems: IMusic.IMusicItem[], sortType = SortType.None, skipInitialSort = false, ) { this.array = [...musicItems]; this.addToCountMap(this.array); this.sortType = sortType; if (!skipInitialSort) { this.resort(); } } at(index: number) { return this.array[index] || null; } has(musicItem: IMusic.IMusicItem | null) { if (!musicItem) { return false; } const platform = musicItem.platform.toString(); const id = musicItem.id.toString(); return this.countMap.get(platform)?.has(id) || false; } // 设置排序类型 setSortType(sortType: SortType) { if ( this.sortType === sortType && this.sortType !== SortType.None && this.sortType ) { return; } this.sortType = sortType; this.resort(); } manualSort(newMusicItems: IMusic.IMusicItem[]) { this.array = newMusicItems; this.sortType = SortType.None; } add(musicItems: IMusic.IMusicItem[]) { musicItems = musicItems.filter(it => !this.has(it)); if (!musicItems.length) { return 0; } this.addToCountMap(musicItems); if (!compareFunctionMap[this.sortType]) { this.array = musicItems.concat(this.array); return musicItems.length; } // 如果歌单内歌曲比较少 if ( this.array.length + musicItems.length < 500 || musicItems.length / (this.array.length + 1) > 10 ) { this.array = musicItems.concat(this.array); this.resort(); return musicItems.length; } // 如果歌单内歌曲比较多 musicItems.sort(compareFunctionMap[this.sortType]); this.array = this.mergeArray(musicItems, this.array, this.sortType); return musicItems.length; } remove(musicItems: IMusic.IMusicItem[]) { const indexMap = createMediaIndexMap(musicItems); this.array = this.array.filter(it => !indexMap.has(it)); this.removeFromCountMap(musicItems); } removeByIndex(indices: number[]) { const indicesSet = new Set(indices); const removedItems: IMusic.IMusicItem[] = []; this.array = this.array.filter((it, index) => { if (indicesSet.has(index)) { removedItems.push(it); return false; } return true; }); this.removeFromCountMap(removedItems); } clearAll() { this.array = []; } private addToCountMap(musicItems: IMusic.IMusicItem[]) { for (let musicItem of musicItems) { const platform = musicItem.platform.toString(); const id = musicItem.id.toString(); if (this.countMap.has(platform)) { this.countMap.get(platform)!.add(id); } else { this.countMap.set(platform, new Set([id])); } } } private removeFromCountMap(musicItems: IMusic.IMusicItem[]) { for (let musicItem of musicItems) { const platform = musicItem.platform.toString(); const id = musicItem.id.toString(); if (this.countMap.has(platform)) { const set = this.countMap.get(platform)!; set.delete(id); if (set.size === 0) { this.countMap.delete(platform); } } } } /** * 合并两个有序列表 * @param musicList1 * @param musicList2 * @param sortType * @private */ private mergeArray( musicList1: IMusic.IMusicItem[], musicList2: IMusic.IMusicItem[], sortType: SortType, ) { // 无序 const compareFn = compareFunctionMap[sortType]; if (!compareFn) { return musicList1.concat(musicList2); } let [p1, p2] = [0, 0]; let resultArray: IMusic.IMusicItem[] = []; let peek1: IMusic.IMusicItem, peek2: IMusic.IMusicItem; while (p1 < musicList1.length && p2 < musicList2.length) { peek1 = musicList1[p1]; peek2 = musicList2[p2]; if (compareFn(peek1, peek2) < 0) { resultArray.push(peek1); ++p1; } else { resultArray.push(peek2); ++p2; } } if (p1 < musicList1.length) { return resultArray.concat(musicList1.slice(p1)); } if (p2 < musicList2.length) { return resultArray.concat(musicList2.slice(p2)); } return resultArray; } /** * 寻找musicItem * @param musicItem * @private */ public findIndex(musicItem: IMusic.IMusicItem) { if (!compareFunctionMap[this.sortType]) { return this.array.find(it => isSameMediaItem(it, musicItem)); } let [left, right] = [0, this.array.length]; let mid: number; while (left < right) { mid = Math.floor((left + right) / 2); let compareResult = compareFunctionMap[this.sortType]( this.array[mid], musicItem, ); if (compareResult < 0) { left = mid + 1; } else if (compareResult === 0) { left = mid; break; } else { right = mid; } } return left === right ? -1 : left; } // 重新排序 private resort() { const compareFn = compareFunctionMap[this.sortType]; if (!compareFn) { return; } this.array.sort(compareFn); this.array = [...this.array]; return; } } ================================================ FILE: src/core/musicSheet/storage.ts ================================================ import getOrCreateMMKV from "@/utils/getOrCreateMMKV.ts"; import { InteractionManager } from "react-native"; import { SortType } from "@/constants/commonConst.ts"; import { safeParse, safeStringify } from "@/utils/jsonUtil"; function getStorageData(key: string) { const mmkv = getOrCreateMMKV(`LocalSheet.${key}`); return safeParse(mmkv.getString("data")); } async function setStorageData(key: string, value: any) { return InteractionManager.runAfterInteractions(() => { const mmkv = getOrCreateMMKV(`LocalSheet.${key}`); mmkv.set("data", safeStringify(value)); }); } function removeStorageData(key: string) { const mmkv = getOrCreateMMKV(`LocalSheet.${key}`); mmkv.clearAll(); } /** * 存储歌单的基本信息 * @param sheets 歌单数据 */ async function setSheets(sheets: IMusic.IMusicSheetItemBase[]) { return await setStorageData("music-sheets", sheets); } /** * 获取歌单的基本信息 */ function getSheets(): IMusic.IMusicSheetItemBase[] { return getStorageData("music-sheets"); } /** * 存储歌单的基本信息 * @param sheets 歌单数据 */ async function setStarredSheets(sheets: IMusic.IMusicSheetItemBase[]) { return await setStorageData("starred-sheets", sheets); } /** * 获取歌单的基本信息 */ function getStarredSheets(): IMusic.IMusicSheetItem[] { return getStorageData("starred-sheets"); } /** * 存储歌单内的歌曲 * @param sheetId 歌单id * @param musicList 歌曲列表 */ async function setMusicList(sheetId: string, musicList: IMusic.IMusicItem[]) { return await setStorageData(sheetId, musicList); } /** * 获取歌单内的歌曲 * @param sheetId 歌单id * @returns 歌曲列表 */ function getMusicList(sheetId: string): IMusic.IMusicItem[] { return getStorageData(sheetId); } /** * 清空歌单内的歌曲/其他信息 * @param sheetId */ function removeMusicList(sheetId: string) { return removeStorageData(sheetId); } interface IMusicSheetMeta extends Record { sort: SortType; } function setSheetMeta( sheetId: string, key: K, value: IMusicSheetMeta[K], ) { const mmkv = getOrCreateMMKV(`LocalSheet.${sheetId}`); mmkv.set("meta." + key, value); } function getSheetMeta( sheetId: string, key: K, ): IMusicSheetMeta[K] | null { const mmkv = getOrCreateMMKV(`LocalSheet.${sheetId}`); return mmkv.getString("meta." + key) || null; } const storage = { setSheets, getSheets, setMusicList, getMusicList, removeMusicList, setSheetMeta, getSheetMeta, setStarredSheets, getStarredSheets, }; export default storage; ================================================ FILE: src/core/pluginManager/index.ts ================================================ import { emptyFunction, localPluginHash, localPluginPlatform, } from "@/constants/commonConst"; import pathConst from "@/constants/pathConst"; import { IInstallPluginConfig, IInstallPluginResult, IPluginManager, } from "@/types/core/pluginManager"; import { removeAllMediaExtra } from "@/utils/mediaExtra"; import axios from "axios"; import { compare } from "compare-versions"; import EventEmitter from "eventemitter3"; import { readAsStringAsync } from "expo-file-system"; import { atom, getDefaultStore, useAtomValue } from "jotai"; import { nanoid } from "nanoid"; import { useEffect, useState } from "react"; import { ToastAndroid } from "react-native"; import { copyFile, readDir, readFile, unlink, writeFile } from "react-native-fs"; import { devLog, errorLog, trace } from "../../utils/log"; import pluginMeta from "./meta"; import { localFilePlugin, Plugin, PluginState } from "./plugin"; import i18n from "../i18n"; import getOrCreateMMKV from "@/utils/getOrCreateMMKV"; import { safeParse } from "@/utils/jsonUtil"; import { IInjectable } from "@/types/infra"; import { IAppConfig } from "@/types/core/config"; import delay from "@/utils/delay"; const pluginsAtom = atom([]); const pluginCacheStore = getOrCreateMMKV("plugin.cache"); const ee = new EventEmitter<{ "order-updated": () => void; "enabled-updated": (pluginName: string, enabled: boolean) => void; }>(); class PluginManager implements IPluginManager, IInjectable { private appConfigService!: IAppConfig; injectDependencies(config: IAppConfig): void { this.appConfigService = config; } /** * 获取当前存储的插件列表 * @returns 插件实例数组 */ private getPlugins() { return getDefaultStore().get(pluginsAtom); } /** * 更新存储中的插件列表 * @param plugins - 要设置的插件实例数组 */ private setPlugins(plugins: Plugin[]) { getDefaultStore().set(pluginsAtom, plugins); // 清理缓存中已卸载的插件 const cachedKeys = pluginCacheStore.getAllKeys(); cachedKeys.forEach(key => { if (!plugins.find(it => it.path === key)) { pluginCacheStore.delete(key); } }); plugins.forEach(it => { this.updatePluginCache(it); }); } private updatePluginCache(plugin: Plugin) { if (plugin.path && plugin.state === PluginState.Mounted) { pluginCacheStore.set( plugin.path, JSON.stringify({ name: plugin.name, hash: plugin.hash, path: plugin.path, instance: plugin.instance, supportedMethods: [...plugin.supportedMethods], }), ); } } /** * 初始化插件管理器,从文件系统加载所有插件 * 读取插件目录中的所有.js文件并创建插件实例 * @throws 如果插件初始化失败则抛出异常 */ async setup() { try { await pluginMeta.migratePluginMeta(); // 加载插件 const pluginsFileItems = await readDir(pathConst.pluginPath); const allPlugins: Array = []; for (let i = 0; i < pluginsFileItems.length; ++i) { const pluginFileItem = pluginsFileItems[i]; trace("初始化插件", pluginFileItem); if ( pluginFileItem.isFile() && (pluginFileItem.name?.endsWith?.(".js") || pluginFileItem.path?.endsWith?.(".js")) ) { // 如果存在缓存信息 let plugin: Plugin; let isLazyLoad = false; if ( this.appConfigService.getConfig( "basic.lazyLoadPlugin", ) && pluginCacheStore.contains(pluginFileItem.path) ) { isLazyLoad = true; const lazyProps = safeParse(pluginCacheStore.getString(pluginFileItem.path)); lazyProps.loadFuncCode = async () => await readFile(pluginFileItem.path, "utf8"); plugin = new Plugin( null, pluginFileItem.path, lazyProps, ); } else { const funcCode = await readFile( pluginFileItem.path, "utf8", ); plugin = new Plugin(funcCode, pluginFileItem.path); } const _pluginIndex = allPlugins.findIndex( p => p.hash === plugin.hash, ); if (_pluginIndex !== -1) { // 重复插件,直接忽略 continue; } if (plugin.state === PluginState.Mounted || isLazyLoad) { allPlugins.push(plugin); } } } this.setPlugins(allPlugins); // 异步初始化插件 delay(10_000, true).then(async () => { for (let i = 0; i < allPlugins.length; ++i) { const plugin = allPlugins[i]; if (plugin.state === PluginState.Initializing) { await plugin.ensureMounted(); this.updatePluginCache(plugin); } } }); } catch (e: any) { ToastAndroid.show( `插件初始化失败:${e?.message ?? e}`, ToastAndroid.LONG, ); errorLog("插件初始化失败", e?.message); throw e; } Plugin.injectDependencies(this); } /** * 从本地文件安装插件 * @param pluginPath - 插件文件路径 * @param config - 安装配置选项 * @param config.notCheckVersion - 为true时跳过版本检查 * @param config.useExpoFs - 为true时使用Expo文件系统代替React Native的文件系统 * @returns 安装结果,包含成功状态和相关信息 */ async installPluginFromLocalFile( pluginPath: string, config?: IInstallPluginConfig & { useExpoFs?: boolean; }, ): Promise { let funcCode: string; if (config?.useExpoFs) { funcCode = await readAsStringAsync(pluginPath); } else { funcCode = await readFile(pluginPath, "utf8"); } if (funcCode) { const plugin = new Plugin(funcCode, pluginPath); let allPlugins = [...this.getPlugins()]; const _pluginIndex = allPlugins.findIndex( p => p.hash === plugin.hash, ); if (_pluginIndex !== -1) { // 静默忽略 return { success: true, message: "插件已安装", pluginName: plugin.name, pluginHash: plugin.hash, }; } const oldVersionPlugin = allPlugins.find( p => p.name === plugin.name, ); if (oldVersionPlugin && !config?.notCheckVersion) { if ( compare( oldVersionPlugin.instance.version ?? "", plugin.instance.version ?? "", ">", ) ) { return { success: false, message: "已安装更新版本的插件", pluginName: plugin.name, pluginHash: plugin.hash, }; } } if (plugin.state === PluginState.Mounted) { const fn = nanoid(); if (oldVersionPlugin) { allPlugins = allPlugins.filter( _ => _.hash !== oldVersionPlugin.hash, ); try { await unlink(oldVersionPlugin.path); } catch {} } const _pluginPath = `${pathConst.pluginPath}${fn}.js`; await copyFile(pluginPath, _pluginPath); plugin.path = _pluginPath; allPlugins = allPlugins.concat(plugin); this.setPlugins(allPlugins); return { success: true, pluginName: plugin.name, pluginHash: plugin.hash, }; } return { success: false, message: "插件无法解析", }; } return { success: false, message: "插件无法识别", }; } /** * 从URL安装插件 * @param url - 下载插件的URL * @param config - 安装配置选项 * @param config.notCheckVersion - 为true时跳过版本检查 * @returns 安装结果,包含成功状态和相关信息 */ async installPluginFromUrl( url: string, config?: IInstallPluginConfig, ): Promise { try { const funcCode = ( await axios.get(url, { headers: { "Cache-Control": "no-cache", Pragma: "no-cache", Expires: "0", }, }) ).data; if (funcCode) { const plugin = new Plugin(funcCode, ""); let allPlugins = [...this.getPlugins()]; const pluginIndex = allPlugins.findIndex( p => p.hash === plugin.hash, ); if (pluginIndex !== -1) { // 静默忽略 return { success: true, message: "插件已安装", pluginName: plugin.name, pluginHash: plugin.hash, pluginUrl: url, }; } const oldVersionPlugin = allPlugins.find( p => p.name === plugin.name, ); if (oldVersionPlugin && !config?.notCheckVersion) { if ( compare( oldVersionPlugin.instance.version ?? "", plugin.instance.version ?? "", ">", ) ) { return { success: false, message: "已安装更新版本的插件", pluginName: plugin.name, pluginHash: plugin.hash, pluginUrl: url, }; } } if (plugin.hash !== "") { const fn = nanoid(); const _pluginPath = `${pathConst.pluginPath}${fn}.js`; await writeFile(_pluginPath, funcCode, "utf8"); plugin.path = _pluginPath; allPlugins = allPlugins.concat(plugin); if (oldVersionPlugin) { allPlugins = allPlugins.filter( _ => _.hash !== oldVersionPlugin.hash, ); try { await unlink(oldVersionPlugin.path); } catch {} } this.setPlugins(allPlugins); return { success: true, pluginName: plugin.name, pluginHash: plugin.hash, pluginUrl: url, }; } return { success: false, message: "插件无法解析", pluginUrl: url, }; } else { return { success: false, message: "插件无法识别", pluginUrl: url, }; } } catch (e: any) { devLog("error", "URL安装插件失败", e, e?.message); errorLog("URL安装插件失败", e); if (e?.response?.statusCode === 404) { return { success: false, message: "插件不存在,请联系插件作者", pluginUrl: url, }; } else { return { success: false, message: e?.message ?? "", pluginUrl: url, }; } } } /** * 通过哈希值卸载插件 * @param hash - 要卸载的插件哈希值 */ async uninstallPlugin(hash: string) { let plugins = [...this.getPlugins()]; const targetIndex = plugins.findIndex(_ => _.hash === hash); if (targetIndex !== -1) { try { const pluginName = plugins[targetIndex].name; await unlink(plugins[targetIndex].path); plugins = plugins.filter(_ => _.hash !== hash); this.setPlugins(plugins); // 防止其他重名 if (plugins.every(_ => _.name !== pluginName)) { removeAllMediaExtra(pluginName); } } catch {} } } /** * 卸载系统中的所有插件 * 同时清理媒体额外数据并删除插件文件 */ async uninstallAllPlugins() { await Promise.all( this.getPlugins().map(async plugin => { try { const pluginName = plugin.name; await unlink(plugin.path); removeAllMediaExtra(pluginName); } catch (e) {} }), ); this.setPlugins([]); /** 清除空余文件,异步做就可以了 */ readDir(pathConst.pluginPath) .then(fns => { fns.forEach(fn => { unlink(fn.path).catch(emptyFunction); }); }) .catch(emptyFunction); } /** * 使用插件的源URL更新插件 * @param plugin - 要更新的插件实例 * @throws 如果插件没有源URL或更新失败时抛出错误 */ async updatePlugin(plugin: Plugin) { const updateUrl = plugin.instance.srcUrl; if (!updateUrl) { throw new Error("没有更新源"); } try { await this.installPluginFromUrl(updateUrl); } catch (e: any) { if (e.message === "插件已安装") { throw new Error(i18n.t("checkUpdate.error.latestVersion")); } else { throw e; } } } /** * 通过媒体项的平台信息获取对应的插件 * @param mediaItem - 包含平台信息的媒体项 * @returns 与媒体平台匹配的插件实例或undefined */ getByMedia(mediaItem: ICommon.IMediaBase) { return this.getByName(mediaItem?.platform); } /** * 通过名称获取插件 * @param name - 要查找的插件名称 * @returns 匹配名称的插件实例或本地文件插件 */ getByName(name: string) { return name === localPluginPlatform ? localFilePlugin : this.getPlugins().find(_ => _.name === name); } /** * 通过哈希值获取插件 * @param hash - 要查找的插件哈希值 * @returns 匹配哈希的插件实例或本地文件插件 */ getByHash(hash: string) { return hash === localPluginHash ? localFilePlugin : this.getPlugins().find(_ => _.hash === hash); } /** * 获取所有已启用的插件 * @returns 已启用的插件实例数组 */ getEnabledPlugins() { return this.getPlugins().filter(it => pluginMeta.isPluginEnabled(it.name), ); } /** * 获取按顺序排序的所有插件 * @returns 按定义顺序排序的插件实例数组 */ getSortedPlugins() { const order = pluginMeta.getPluginOrder(); return [...this.getPlugins()].sort((a, b) => (order[a.name] ?? Infinity) - (order[b.name] ?? Infinity) < 0 ? -1 : 1, ); } /** * 获取所有支持搜索功能的已启用插件 * @param supportedSearchType - 可选的搜索媒体类型过滤器 * @returns 可搜索的插件实例数组 */ getSearchablePlugins(supportedSearchType?: ICommon.SupportMediaType) { return this.getPlugins().filter( it => pluginMeta.isPluginEnabled(it.name) && it.supportedMethods.has("search") && (supportedSearchType && it.instance.supportedSearchType ? it.instance.supportedSearchType.includes( supportedSearchType, ) : true), ); } /** * 获取所有支持搜索功能的已启用插件,并按顺序排序 * @param supportedSearchType - 可选的搜索媒体类型过滤器 * @returns 按顺序排序的可搜索插件实例数组 */ getSortedSearchablePlugins(supportedSearchType?: ICommon.SupportMediaType) { const order = pluginMeta.getPluginOrder(); return [...this.getSearchablePlugins(supportedSearchType)].sort( (a, b) => (order[a.name] ?? Infinity) - (order[b.name] ?? Infinity) < 0 ? -1 : 1, ); } /** * 获取所有实现特定功能的已启用插件 * @param ability - 要检查的方法/功能名称 * @returns 具有指定功能的插件实例数组 */ getPluginsWithAbility(ability: keyof IPlugin.IPluginInstanceMethods) { return this.getPlugins().filter( it => pluginMeta.isPluginEnabled(it.name) && it.supportedMethods.has(ability), ); } /** * 获取所有实现特定功能的已启用插件,并按顺序排序 * @param ability - 要检查的方法/功能名称 * @returns 按顺序排序的具有指定功能的插件实例数组 */ getSortedPluginsWithAbility(ability: keyof IPlugin.IPluginInstanceMethods) { const order = pluginMeta.getPluginOrder(); return [...this.getPluginsWithAbility(ability)].sort((a, b) => (order[a.name] ?? Infinity) - (order[b.name] ?? Infinity) < 0 ? -1 : 1, ); } /** * 设置插件的启用状态并发送事件通知 * @param plugin - 要修改的插件实例 * @param enabled - 是否启用插件 */ setPluginEnabled(plugin: Plugin, enabled: boolean) { ee.emit("enabled-updated", plugin.name, enabled); pluginMeta.setPluginEnabled(plugin.name, enabled); } /** * 检查插件是否已启用 * @param plugin - 要检查的插件实例 * @returns 表示插件是否启用的布尔值 */ isPluginEnabled(plugin: Plugin) { return pluginMeta.isPluginEnabled(plugin.name); } /** * 设置插件的排序顺序并发送顺序更新事件 * @param sortedPlugins - 按期望顺序排列的插件实例数组 */ setPluginOrder(sortedPlugins: Plugin[]) { const orderMap: Record = {}; sortedPlugins.forEach((plugin, index) => { orderMap[plugin.name] = index; }); pluginMeta.setPluginOrder(orderMap); ee.emit("order-updated"); } setUserVariables(plugin: Plugin, userVariables: Record) { pluginMeta.setUserVariables(plugin.name, userVariables); } getUserVariables(plugin: Plugin) { return pluginMeta.getUserVariables(plugin.name); } setAlternativePluginName(plugin: Plugin, alternativePluginName: string) { pluginMeta.setAlternativePlugin(plugin.name, alternativePluginName); } getAlternativePluginName(plugin: Plugin) { return pluginMeta.getAlternativePlugin(plugin.name); } getAlternativePlugin(plugin: Plugin) { const alternativePluginName = this.getAlternativePluginName(plugin); if (alternativePluginName) { return this.getByName(alternativePluginName); } return null; } } const pluginManager = new PluginManager(); export const usePlugins = () => useAtomValue(pluginsAtom); export function useSortedPlugins() { const plugins = useAtomValue(pluginsAtom); const [sortedPlugins, setSortedPlugins] = useState( pluginManager.getSortedPlugins(), ); useEffect(() => { const callback = () => { const order = pluginMeta.getPluginOrder(); setSortedPlugins( [...plugins].sort((a, b) => (order[a.name] ?? Infinity) - (order[b.name] ?? Infinity) < 0 ? -1 : 1, ), ); }; ee.on("order-updated", callback); callback(); return () => { ee.off("order-updated", callback); }; }, [plugins]); return sortedPlugins; } export function usePluginEnabled(plugin: Plugin) { const [enabled, setEnabled] = useState( pluginManager.isPluginEnabled(plugin), ); useEffect(() => { const callback = (pluginName: string, _enabled: boolean) => { if (pluginName === plugin?.name) { setEnabled(_enabled); } }; ee.on("enabled-updated", callback); return () => { ee.off("enabled-updated", callback); }; }, [plugin]); return enabled; } export default pluginManager; export { Plugin }; ================================================ FILE: src/core/pluginManager/meta.ts ================================================ import getOrCreateMMKV from "@/utils/getOrCreateMMKV"; import { safeParse, safeStringify } from "@/utils/jsonUtil"; import { errorLog } from "@/utils/log"; import { getStorage, removeStorage } from "@/utils/storage"; type IPluginPlatform = string; interface IPluginMetaStorage { $version: number; order: Record; disabledPlugins: Array; [key: `${IPluginPlatform}.alternativePlugin`]: IPluginPlatform | null; [key: `${IPluginPlatform}.userVariables`]: Record; } const storage = getOrCreateMMKV("plugin-meta"); class PluginMeta { private cachedDisabledPlugins: Set | null = null; private getMetaStorage(key: K): IPluginMetaStorage[K] | null { return safeParse(storage.getString(key)); } private setMetaStorage(key: K, value: IPluginMetaStorage[K]) { const storageValue = safeStringify(value); storage.set(key, storageValue); } async migratePluginMeta() { const metaVersion = storage.getNumber("$version") ?? -1; if (metaVersion < 0) { // 从async storage迁移到mmkv try { const rawMeta = await getStorage("plugin-meta"); const order: Record = {}; const disabledPlugins = new Set(); if (rawMeta !== null) { for (let platformName in rawMeta) { const metaVal = rawMeta[platformName]; if (!metaVal) { continue; } if (metaVal?.order !== undefined && metaVal.order !== null) { order[platformName] = metaVal.order; } if (metaVal?.enabled !== undefined && metaVal.enabled === false) { disabledPlugins.add(platformName); } if (metaVal?.userVariables !== undefined && metaVal.userVariables !== null) { storage.set(platformName + ".userVariables", safeStringify(metaVal.userVariables)); } } } // 将 order 和 disabledPlugins 存储到 mmkv storage.set("order", safeStringify(order)); storage.set("disabledPlugins", safeStringify(Array.from(disabledPlugins))); // 移除 await removeStorage("plugin-meta"); } catch (e) { errorLog("迁移 plugin meta 失败", e); } storage.set("$version", 1); } } getPluginOrder() { return this.getMetaStorage("order") ?? {}; } setPluginOrder(orderMap: Record) { this.setMetaStorage("order", orderMap); } public get disabledPlugins() { if (this.cachedDisabledPlugins) { return this.cachedDisabledPlugins; } const disabledPlugins = this.getMetaStorage("disabledPlugins") ?? []; this.cachedDisabledPlugins = new Set(disabledPlugins); return this.cachedDisabledPlugins; } isPluginEnabled(pluginPlatform: IPluginPlatform) { const disabledPluginsSet = this.disabledPlugins; return !disabledPluginsSet.has(pluginPlatform); } setPluginEnabled(pluginPlatform: IPluginPlatform, enabled: boolean) { const disabledPluginsSet = this.disabledPlugins; if (enabled) { disabledPluginsSet.delete(pluginPlatform); } else { disabledPluginsSet.add(pluginPlatform); } this.setMetaStorage("disabledPlugins", Array.from(disabledPluginsSet)); this.cachedDisabledPlugins = disabledPluginsSet; } getUserVariables(pluginPlatform: IPluginPlatform) { const userVariables = this.getMetaStorage(`${pluginPlatform}.userVariables`) ?? {}; return userVariables; } setUserVariables(pluginPlatform: IPluginPlatform, userVariables: Record) { this.setMetaStorage(`${pluginPlatform}.userVariables`, userVariables); } setAlternativePlugin(pluginPlatform: IPluginPlatform, alternativePluginPlatform: IPluginPlatform) { this.setMetaStorage(`${pluginPlatform}.alternativePlugin`, alternativePluginPlatform); } getAlternativePlugin(pluginPlatform: IPluginPlatform): IPluginPlatform | null { const alternativePlugin = this.getMetaStorage(`${pluginPlatform}.alternativePlugin`); if (alternativePlugin) { return alternativePlugin; } return null; } } const _internalPluginMeta = new PluginMeta(); export default _internalPluginMeta; ================================================ FILE: src/core/pluginManager/plugin.ts ================================================ import { CacheControl, internalSerializeKey, localPluginPlatform, } from "@/constants/commonConst"; import pathConst from "@/constants/pathConst"; import Mp3Util from "@/native/mp3Util"; import Base64 from "@/utils/base64"; import delay from "@/utils/delay"; import { addFileScheme, getFileName } from "@/utils/fileUtils"; import { getMediaExtraProperty, patchMediaExtra } from "@/utils/mediaExtra"; import { getLocalPath, isSameMediaItem, resetMediaItem } from "@/utils/mediaUtils"; import notImplementedFunction from "@/utils/notImplementedFunction.ts"; import axios from "axios"; import bigInt from "big-integer"; import * as cheerio from "cheerio"; import { satisfies } from "compare-versions"; import CryptoJs from "crypto-js"; import dayjs from "dayjs"; import he from "he"; import { produce } from "immer"; import { nanoid } from "nanoid"; import objectPath from "object-path"; import qs from "qs"; import { default as DeviceInfo, default as deviceInfoModule } from "react-native-device-info"; import RNFS, { exists, readFile, stat, writeFile } from "react-native-fs"; import { URL } from "react-native-url-polyfill"; import * as webdav from "webdav"; import { devLog, errorLog, trace } from "../../utils/log"; import Network from "../../utils/network"; import MediaCache from "../mediaCache"; import _internalPluginMeta from "./meta"; import { IPluginManager } from "@/types/core/pluginManager"; axios.defaults.timeout = 2000; axios.interceptors.response.use((response) => { // 统一setcookie格式,nodejs环境是数组,移动端环境都放在第一个元素 const setCookie = response.headers["set-cookie"]; if(setCookie && setCookie.length === 1) { const splitedCookie = setCookie[0].split(","); response.headers["set-cookie"] = splitedCookie; response.headers["x-set-cookie"] = setCookie; } return response; }); const sha256 = CryptoJs.SHA256; const deprecatedCookieManager = { get: notImplementedFunction, set: notImplementedFunction, flush: notImplementedFunction, }; const packages: Record = { cheerio, "crypto-js": CryptoJs, axios, dayjs, "big-integer": bigInt, qs, he, "@react-native-cookies/cookies": deprecatedCookieManager, webdav, }; const _require = (packageName: string) => { let pkg = packages[packageName]; pkg.default = pkg; return pkg; }; const _consoleBind = function ( method: "log" | "error" | "info" | "warn", ...args: any ) { const fn = console[method]; if (fn) { fn(...args); devLog(method, ...args); } }; const _console = { log: _consoleBind.bind(null, "log"), warn: _consoleBind.bind(null, "warn"), info: _consoleBind.bind(null, "info"), error: _consoleBind.bind(null, "error"), }; const appVersion = deviceInfoModule.getVersion(); function formatAuthUrl(url: string) { const urlObj = new URL(url); try { if (urlObj.username && urlObj.password) { const auth = `Basic ${Base64.btoa( `${decodeURIComponent(urlObj.username)}:${decodeURIComponent( urlObj.password, )}`, )}`; urlObj.username = ""; urlObj.password = ""; return { url: urlObj.toString(), auth, }; } } catch (e) { return { url, }; } return { url, }; } export enum PluginState { // 初始化 Initializing, // 加载中 Loading, // 已加载 Mounted, // 出现错误 Error } export enum PluginErrorReason { // 版本不匹配 VersionNotMatch, // 无法解析 CannotParse, } export interface ILazyProps { name: string; hash: string; path: string; supportedMethods?: string[]; loadFuncCode?: () => Promise; instance?: IPlugin.IPluginDefine; } class PluginMethodsWrapper implements IPlugin.IPluginInstanceMethods { private plugin: Plugin; private ensurePluginIsMounted: () => Promise; constructor(plugin: Plugin, ensurePluginIsMounted: () => Promise) { this.plugin = plugin; this.ensurePluginIsMounted = ensurePluginIsMounted; } /** 搜索 */ async search( query: string, page: number, type: T, ): Promise> { await this.ensurePluginIsMounted(); if (!this.plugin.instance.search) { return { isEnd: true, data: [], }; } const result = (await this.plugin.instance.search(query, page, type)) ?? {}; if (Array.isArray(result.data)) { result.data.forEach(_ => { resetMediaItem(_, this.plugin.name); }); return { isEnd: result.isEnd ?? true, data: result.data, }; } return { isEnd: true, data: [], }; } /** 获取真实源 */ async getMediaSource( musicItem: IMusic.IMusicItemBase, quality: IMusic.IQualityKey = "standard", retryCount = 1, notUpdateCache = false, ): Promise { await this.ensurePluginIsMounted(); // 1. 本地搜索 其实直接读mediameta就好了 const localPathInMediaExtra = getMediaExtraProperty(musicItem, "localPath"); const localPath = getLocalPath(musicItem); if (localPath && (await exists(localPath))) { trace("本地播放", localPath); if (localPathInMediaExtra !== localPath) { // 修正一下本地数据 patchMediaExtra(musicItem, { localPath, }); } return { url: addFileScheme(localPath), }; } else if (localPathInMediaExtra) { patchMediaExtra(musicItem, { localPath: undefined, }); } if (musicItem.platform === localPluginPlatform) { throw new Error("本地音乐不存在"); } // 2. 缓存播放 const mediaCache = MediaCache.getMediaCache( musicItem, ) as IMusic.IMusicItem | null; const pluginCacheControl = this.plugin.instance.cacheControl ?? "no-cache"; if ( mediaCache && mediaCache?.source?.[quality]?.url && (pluginCacheControl === CacheControl.Cache || (pluginCacheControl === CacheControl.NoCache && Network.isOffline)) ) { trace("播放", "缓存播放"); const qualityInfo = mediaCache.source[quality]; return { url: qualityInfo!.url, headers: mediaCache.headers, userAgent: mediaCache.userAgent ?? mediaCache.headers?.["user-agent"], }; } // 3. 替代插件 const alternativePlugin = Plugin.pluginManager?.getAlternativePlugin(this.plugin) as Plugin | null; const parserPlugin = alternativePlugin?.instance?.getMediaSource ? alternativePlugin : this.plugin; if (alternativePlugin) { devLog("info", "设置了替代插件,实际使用的插件为", parserPlugin.name); } // 4. 插件解析 if (!parserPlugin.instance.getMediaSource) { const { url, auth } = formatAuthUrl( musicItem?.qualities?.[quality]?.url ?? musicItem.url, ); return { url: url, headers: auth ? { Authorization: auth, } : undefined, }; } try { const { url, headers } = (await parserPlugin.instance.getMediaSource( musicItem, quality, )) ?? { url: musicItem?.qualities?.[quality]?.url }; if (!url) { throw new Error("NOT RETRY"); } trace("播放", "插件播放"); const result = { url, headers, userAgent: headers?.["user-agent"], } as IPlugin.IMediaSourceResult; const authFormattedResult = formatAuthUrl(result.url!); if (authFormattedResult.auth) { result.url = authFormattedResult.url; result.headers = { ...(result.headers ?? {}), Authorization: authFormattedResult.auth, }; } if ( pluginCacheControl !== CacheControl.NoStore && !notUpdateCache ) { // 更新缓存 const cacheSource = { headers: result.headers, userAgent: result.userAgent, url, }; let realMusicItem = { ...musicItem, ...(mediaCache || {}), }; realMusicItem.source = { ...(realMusicItem.source || {}), [quality]: cacheSource, }; MediaCache.setMediaCache(realMusicItem); } return result; } catch (e: any) { if (retryCount > 0 && e?.message !== "NOT RETRY") { await delay(150); return this.getMediaSource(musicItem, quality, --retryCount); } errorLog("获取真实源失败", e?.message); devLog("error", "获取真实源失败", e, e?.message); return null; } } /** 获取音乐详情 */ async getMusicInfo( musicItem: ICommon.IMediaBase, ): Promise | null> { await this.ensurePluginIsMounted(); if (!this.plugin.instance.getMusicInfo) { return null; } try { return ( this.plugin.instance.getMusicInfo( resetMediaItem(musicItem, undefined, true), ) ?? null ); } catch (e: any) { devLog("error", "获取音乐详情失败", e, e?.message); return null; } } /** * * getLyric(musicItem) => { * lyric: string; * trans: string; * } * */ /** 获取歌词 */ async getLyric( originalMusicItem: IMusic.IMusicItemBase, ): Promise { await this.ensurePluginIsMounted(); // 1.额外存储的meta信息(关联歌词) const associatedLrc = getMediaExtraProperty(originalMusicItem, "associatedLrc"); let musicItem: IMusic.IMusicItem; if (associatedLrc) { musicItem = associatedLrc as IMusic.IMusicItem; } else { musicItem = originalMusicItem as IMusic.IMusicItem; } const musicItemCache = MediaCache.getMediaCache( musicItem, ) as IMusic.IMusicItemCache | null; /** 原始歌词文本 */ let rawLrc: string | null = musicItem.rawLrc || null; let translation: string | null = null; // 2. 本地手动设置的歌词 const platformHash = CryptoJs.MD5(musicItem.platform).toString( CryptoJs.enc.Hex, ); const idHash = CryptoJs.MD5(musicItem.id).toString(CryptoJs.enc.Hex); if ( await RNFS.exists( pathConst.localLrcPath + platformHash + "/" + idHash + ".lrc", ) ) { rawLrc = await RNFS.readFile( pathConst.localLrcPath + platformHash + "/" + idHash + ".lrc", "utf8", ); if ( await RNFS.exists( pathConst.localLrcPath + platformHash + "/" + idHash + ".tran.lrc", ) ) { translation = (await RNFS.readFile( pathConst.localLrcPath + platformHash + "/" + idHash + ".tran.lrc", "utf8", )) || null; } return { rawLrc, translation: translation || undefined, // TODO: 这里写的不好 }; } // 2. 缓存歌词 / 对象上本身的歌词 if (musicItemCache?.lyric) { // 缓存的远程结果 let cacheLyric: ILyric.ILyricSource | null = musicItemCache.lyric || null; // 缓存的本地结果 let localLyric: ILyric.ILyricSource | null = musicItemCache.$localLyric || null; // 优先用缓存的结果 if (cacheLyric.rawLrc || cacheLyric.translation) { return { rawLrc: cacheLyric.rawLrc, translation: cacheLyric.translation, }; } // 本地其实是缓存的路径 if (localLyric) { let needRefetch = false; if (localLyric.rawLrc && (await exists(localLyric.rawLrc))) { rawLrc = await readFile(localLyric.rawLrc, "utf8"); } else if (localLyric.rawLrc) { needRefetch = true; } if ( localLyric.translation && (await exists(localLyric.translation)) ) { translation = await readFile( localLyric.translation, "utf8", ); } else if (localLyric.translation) { needRefetch = true; } if (!needRefetch && (rawLrc || translation)) { return { rawLrc: rawLrc || undefined, translation: translation || undefined, }; } } } // 3. 无缓存歌词/无自带歌词/无本地歌词 let lrcSource: ILyric.ILyricSource | null; if (isSameMediaItem(originalMusicItem, musicItem)) { lrcSource = (await this.plugin.instance ?.getLyric?.(resetMediaItem(musicItem, undefined, true)) ?.catch(() => null)) || null; } else { lrcSource = (await Plugin.pluginManager?.getByMedia(musicItem) ?.instance?.getLyric?.( resetMediaItem(musicItem, undefined, true), ) ?.catch(() => null)) || null; } if (lrcSource) { rawLrc = lrcSource?.rawLrc || rawLrc; translation = lrcSource?.translation || null; const deprecatedLrcUrl = lrcSource?.lrc || musicItem.lrc; // 本地的文件名 let filename: string | undefined = `${pathConst.lrcCachePath }${nanoid()}.lrc`; let filenameTrans: string | undefined = `${pathConst.lrcCachePath }${nanoid()}.lrc`; // 旧版本兼容 if (!(rawLrc || translation)) { if (deprecatedLrcUrl) { rawLrc = ( await axios .get(deprecatedLrcUrl, { timeout: 3000 }) .catch(() => null) )?.data; } else if (musicItem.rawLrc) { rawLrc = musicItem.rawLrc; } } if (rawLrc) { await writeFile(filename, rawLrc, "utf8"); } else { filename = undefined; } if (translation) { await writeFile(filenameTrans, translation, "utf8"); } else { filenameTrans = undefined; } if (rawLrc || translation) { MediaCache.setMediaCache( produce(musicItemCache || musicItem, draft => { musicItemCache?.$localLyric?.rawLrc; objectPath.set(draft, "$localLyric.rawLrc", filename); objectPath.set( draft, "$localLyric.translation", filenameTrans, ); return draft; }), ); return { rawLrc: rawLrc || undefined, translation: translation || undefined, }; } } // 6. 如果是本地文件 const localFilePath = getLocalPath(originalMusicItem); if ( originalMusicItem.platform !== localPluginPlatform && localFilePath ) { const res = await localFilePluginDefine!.getLyric!(originalMusicItem); devLog("info", "本地文件歌词"); if (res) { return res; } } devLog("warn", "无歌词"); return null; } /** 获取专辑信息 */ async getAlbumInfo( albumItem: IAlbum.IAlbumItemBase, page: number = 1, ): Promise { await this.ensurePluginIsMounted(); if (!this.plugin.instance.getAlbumInfo) { return { albumItem, musicList: (albumItem?.musicList ?? []).map( resetMediaItem, this.plugin.name, true, ), isEnd: true, }; } try { const result = await this.plugin.instance.getAlbumInfo( resetMediaItem(albumItem, undefined, true), page, ); if (!result) { throw new Error(); } result?.musicList?.forEach(_ => { resetMediaItem(_, this.plugin.name); _.album = albumItem.title; }); if (page <= 1) { // 合并信息 return { albumItem: { ...albumItem, ...(result?.albumItem ?? {}) }, isEnd: result.isEnd === false ? false : true, musicList: result.musicList, }; } else { return { isEnd: result.isEnd === false ? false : true, musicList: result.musicList, }; } } catch (e: any) { trace("获取专辑信息失败", e?.message); devLog("error", "获取专辑信息失败", e, e?.message); return null; } } /** 获取歌单信息 */ async getMusicSheetInfo( sheetItem: IMusic.IMusicSheetItem, page: number = 1, ): Promise { await this.ensurePluginIsMounted(); if (!this.plugin.instance.getMusicSheetInfo) { return { sheetItem, musicList: sheetItem?.musicList ?? [], isEnd: true, }; } try { const result = await this.plugin.instance?.getMusicSheetInfo?.( resetMediaItem(sheetItem, undefined, true), page, ); if (!result) { throw new Error(); } result?.musicList?.forEach(_ => { resetMediaItem(_, this.plugin.name); }); if (page <= 1) { // 合并信息 return { sheetItem: { ...sheetItem, ...(result?.sheetItem ?? {}) }, isEnd: result.isEnd === false ? false : true, musicList: result.musicList, }; } else { return { isEnd: result.isEnd === false ? false : true, musicList: result.musicList, }; } } catch (e: any) { trace("获取歌单信息失败", e, e?.message); devLog("error", "获取歌单信息失败", e, e?.message); return null; } } /** 查询作者信息 */ async getArtistWorks( artistItem: IArtist.IArtistItem, page: number, type: T, ): Promise> { await this.ensurePluginIsMounted(); if (!this.plugin.instance.getArtistWorks) { return { isEnd: true, data: [], }; } try { const result = await this.plugin.instance.getArtistWorks( artistItem, page, type, ); if (!result.data) { return { isEnd: true, data: [], }; } result.data?.forEach(_ => resetMediaItem(_, this.plugin.name)); return { isEnd: result.isEnd ?? true, data: result.data, }; } catch (e: any) { trace("查询作者信息失败", e?.message); devLog("error", "查询作者信息失败", e, e?.message); throw e; } } /** 导入歌单 */ async importMusicSheet(urlLike: string): Promise { await this.ensurePluginIsMounted(); try { const result = (await this.plugin.instance?.importMusicSheet?.(urlLike)) ?? []; result.forEach(_ => resetMediaItem(_, this.plugin.name)); return result; } catch (e: any) { console.log(e); devLog("error", "导入歌单失败", e, e?.message); return []; } } /** 导入单曲 */ async importMusicItem(urlLike: string): Promise { await this.ensurePluginIsMounted(); try { const result = await this.plugin.instance?.importMusicItem?.( urlLike, ); if (!result) { throw new Error(); } resetMediaItem(result, this.plugin.name); return result; } catch (e: any) { devLog("error", "导入单曲失败", e, e?.message); return null; } } /** 获取榜单 */ async getTopLists(): Promise { await this.ensurePluginIsMounted(); try { const result = await this.plugin.instance?.getTopLists?.(); if (!result) { throw new Error(); } return result; } catch (e: any) { devLog("error", "获取榜单失败", e, e?.message); return []; } } /** 获取榜单详情 */ async getTopListDetail( topListItem: IMusic.IMusicSheetItemBase, page: number, ): Promise { await this.ensurePluginIsMounted(); const result = await this.plugin.instance?.getTopListDetail?.( topListItem, page, ); if (!result) { throw new Error(); } if (result.musicList) { result.musicList.forEach(_ => resetMediaItem(_, this.plugin.name), ); } else { result.musicList = []; } if (result.isEnd !== false) { result.isEnd = true; } return result; } /** 获取推荐歌单的tag */ async getRecommendSheetTags(): Promise { await this.ensurePluginIsMounted(); try { const result = await this.plugin.instance?.getRecommendSheetTags?.(); if (!result) { throw new Error(); } return result; } catch (e: any) { devLog("error", "获取推荐歌单失败", e, e?.message); return { data: [], }; } } /** 获取某个tag的推荐歌单 */ async getRecommendSheetsByTag( tagItem: ICommon.IUnique, page?: number, ): Promise> { await this.ensurePluginIsMounted(); try { const result = await this.plugin.instance?.getRecommendSheetsByTag?.( tagItem, page ?? 1, ); if (!result) { throw new Error(); } if (result.isEnd !== false) { result.isEnd = true; } if (!result.data) { result.data = []; } result.data.forEach(item => resetMediaItem(item, this.plugin.name)); return result; } catch (e: any) { devLog("error", "获取推荐歌单详情失败", e, e?.message); return { isEnd: true, data: [], }; } } async getMusicComments( musicItem: IMusic.IMusicItem, page?: number ): Promise> { await this.ensurePluginIsMounted(); const result = await this.plugin.instance?.getMusicComments?.( musicItem, page ?? 1 ); if (!result) { throw new Error(); } if (result.isEnd !== false) { result.isEnd = true; } if (!result.data) { result.data = []; } return result; } } //#region 插件类 export class Plugin { /** 插件名 */ public name: string = ""; /** 插件的hash,作为唯一id */ public hash: string = ""; /** 插件状态:激活、关闭、错误 */ public state: PluginState = PluginState.Initializing; /** 插件出错时的原因 */ public errorReason?: PluginErrorReason; /** 插件的实例 */ public instance: IPlugin.IPluginDefine = { platform: "" }; /** 插件路径 */ public path: string = ""; /** 插件方法,内部进行标准化和校验 */ public methods!: IPlugin.IPluginInstanceMethods; public supportedMethods: Set = new Set(); private lazyProps: ILazyProps | null = null; static pluginManager: IPluginManager; static injectDependencies( pluginManager: IPluginManager, ) { Plugin.pluginManager = pluginManager; } constructor( funcCode: string | (() => IPlugin.IPluginDefine) | null, pluginPath: string, lazyProps: ILazyProps | null = null ) { this.lazyProps = lazyProps; if (!lazyProps) { // 如果没有懒加载,直接挂载并初始化 this.mountPlugin(funcCode!, pluginPath); this.methods = new PluginMethodsWrapper(this, async () => {}); } else { // 使用懒加载参数初始化 this.name = lazyProps.name; this.hash = lazyProps.hash; this.path = lazyProps.path; this.instance = lazyProps.instance ?? { platform: lazyProps.name, }; this.supportedMethods = new Set((lazyProps.supportedMethods ?? []) as any); // 初始化方法,但实际调用时会先挂载插件 this.methods = new PluginMethodsWrapper(this, this.ensureMounted.bind(this)); } } async ensureMounted() { if ((this.state === PluginState.Initializing) && this.lazyProps) { this.state = PluginState.Loading; // 懒加载 const loadFuncCode = this.lazyProps.loadFuncCode ?? (() => ""); try { const funcCode = await loadFuncCode(); this.mountPlugin(funcCode, this.lazyProps.path); } catch { this.state = PluginState.Error; this.errorReason = this.errorReason ?? PluginErrorReason.CannotParse; } } } private mountPlugin( funcCode: string | (() => IPlugin.IPluginDefine), pluginPath: string) { this.state = PluginState.Loading; let _instance: IPlugin.IPluginDefine; const _module: any = { exports: {} }; try { if (typeof funcCode === "string") { // 插件的环境变量 const env = { getUserVariables: () => { return ( _internalPluginMeta.getUserVariables(this.name) ); }, get userVariables() { return this.getUserVariables() ?? {}; }, appVersion, os: "android", lang: "zh-CN", }; const _process = { platform: "android", version: appVersion, env, }; // eslint-disable-next-line no-new-func _instance = Function(` 'use strict'; return function(require, __musicfree_require, module, exports, console, env, URL, process) { ${funcCode} } `)()( _require, _require, _module, _module.exports, _console, env, URL, _process ); if (_module.exports.default) { _instance = _module.exports .default as IPlugin.IPluginInstance; } else { _instance = _module.exports as IPlugin.IPluginInstance; } } else { _instance = funcCode(); } // 插件初始化后的一些操作 if (Array.isArray(_instance.userVariables)) { _instance.userVariables = _instance.userVariables.filter( it => it?.key, ); } this.checkValid(_instance); } catch (e: any) { this.state = PluginState.Error; this.errorReason = e?.errorReason ?? PluginErrorReason.CannotParse; errorLog(`${pluginPath}插件无法解析 `, { errorReason: this.errorReason, message: e?.message, stack: e?.stack, }); _instance = e?.instance ?? { platform: "", appVersion: "", async getMediaSource() { return null; }, async search() { return {}; }, async getAlbumInfo() { return null; }, }; } this.instance = _instance; this.path = pluginPath; this.name = _instance.platform; this.supportedMethods = new Set(Object.keys(_instance).filter( key => typeof (_instance[key]) === "function", ) as any); // 检测name & 计算hash if ( this.name === "" || !this.name ) { this.hash = ""; this.state = PluginState.Error; this.errorReason = this.errorReason ?? PluginErrorReason.CannotParse; } else { if (typeof funcCode === "string") { this.hash = sha256(funcCode).toString(); } else { this.hash = sha256(pluginPath + "@" + appVersion).toString(); } } if (this.state !== PluginState.Error) { this.state = PluginState.Mounted; } } private checkValid(_instance: IPlugin.IPluginDefine) { /** 版本号校验 */ if ( _instance.appVersion && !satisfies(DeviceInfo.getVersion(), _instance.appVersion) ) { throw { instance: _instance, state: PluginState.Error, errorReason: PluginErrorReason.VersionNotMatch, }; } return true; } } const localFilePluginDefine: IPlugin.IPluginDefine = { platform: localPluginPlatform, async getMusicInfo(musicBase) { const localPath = getLocalPath(musicBase); if (localPath) { const coverImg = await Mp3Util.getMediaCoverImg(localPath); return { artwork: coverImg, }; } return null; }, async getLyric(musicBase) { const localPath = getLocalPath(musicBase); let rawLrc: string | null = null; if (localPath) { // 读取内嵌歌词 try { rawLrc = await Mp3Util.getLyric(localPath); } catch (e) { console.log("读取内嵌歌词失败", e); } if (!rawLrc) { // 读取配置歌词 const lastDot = localPath.lastIndexOf("."); const lrcPath = localPath.slice(0, lastDot) + ".lrc"; try { if (await exists(lrcPath)) { rawLrc = await readFile(lrcPath, "utf8"); } } catch { } } } return rawLrc ? { rawLrc, } : null; }, async importMusicItem(urlLike) { // 绝对路径 let meta: any = {}; let id: string; try { meta = await Mp3Util.getBasicMeta(urlLike); const fileStat = await stat(urlLike); id = CryptoJs.MD5(fileStat.originalFilepath).toString( CryptoJs.enc.Hex, ) || nanoid(); } catch { id = nanoid(); } return { id: id, platform: localPluginPlatform, title: meta?.title ?? getFileName(urlLike), artist: meta?.artist ?? "未知歌手", duration: parseInt(meta?.duration ?? "0", 10) / 1000, album: meta?.album ?? "未知专辑", artwork: "", [internalSerializeKey]: { localPath: urlLike, }, url: urlLike, }; }, async getMediaSource(musicItem, quality) { if (quality === "standard") { return { url: addFileScheme(musicItem.$?.localPath || musicItem.url), }; } return null; }, }; export const localFilePlugin = new Plugin(function () { return localFilePluginDefine; }, "internal-plugin://local-file-plugin"); ================================================ FILE: src/core/router/index.ts ================================================ import { useNavigation, useRoute } from "@react-navigation/native"; import { useCallback } from "react"; import { LogBox } from "react-native"; LogBox.ignoreLogs([ "Non-serializable values were found in the navigation state", ]); /** 路由key */ export const ROUTE_PATH = { /** 主页 */ HOME: "home", /** 音乐播放页 */ MUSIC_DETAIL: "music-detail", /** 搜索页 */ SEARCH_PAGE: "search-page", /** 本地歌单页 */ LOCAL_SHEET_DETAIL: "local-sheet-detail", /** 专辑页 */ ALBUM_DETAIL: "album-detail", /** 歌手页 */ ARTIST_DETAIL: "artist-detail", /** 榜单页 */ TOP_LIST: "top-list", /** 榜单详情页 */ TOP_LIST_DETAIL: "top-list-detail", /** 设置页 */ SETTING: "setting", /** 本地音乐 */ LOCAL: "local", /** 正在下载 */ DOWNLOADING: "downloading", /** 从歌曲列表中搜索 */ SEARCH_MUSIC_LIST: "search-music-list", /** 批量编辑 */ MUSIC_LIST_EDITOR: "music-list-editor", /** 选择文件夹 */ FILE_SELECTOR: "file-selector", /** 推荐歌单 */ RECOMMEND_SHEETS: "recommend-sheets", /** 歌单详情 */ PLUGIN_SHEET_DETAIL: "plugin-sheet-detail", /** 历史记录 */ HISTORY: "history", /** 自定义主题 */ SET_CUSTOM_THEME: "set-custom-theme", /** 权限管理 */ PERMISSIONS: "permissions", } as const; type ValueOf = T[keyof T]; type RoutePaths = ValueOf; type RouterParamsBase = Record; /** 路由参数 */ interface RouterParams extends RouterParamsBase { home: undefined; "music-detail": undefined; "search-page": undefined; "local-sheet-detail": { id: string; }; "album-detail": { albumItem: IAlbum.IAlbumItem; }; "artist-detail": { artistItem: IArtist.IArtistItem; pluginHash: string; }; setting: { type: string; // anchor?: string | number; }; local: undefined; downloading: undefined; "search-music-list": { musicList: IMusic.IMusicItem[] | null; musicSheet?: IMusic.IMusicSheetItem; }; "music-list-editor": { musicSheet?: Partial; musicList: IMusic.IMusicItem[] | null; }; "file-selector": { fileType?: "folder" | "file" | "file-and-folder"; // 10: folder 11: file and folder, multi?: boolean; // 是否多选 actionText?: string; // 底部行动点的文本 actionIcon?: string; // 底部行动点的图标 onAction?: ( selectedFiles: { path: string; type: "file" | "folder"; }[], ) => Promise; // true会自动关闭,false会停在当前页面 matchExtension?: (path: string) => boolean; }; "top-list-detail": { pluginHash: string; topList: IMusic.IMusicSheetItemBase; }; "plugin-sheet-detail": { pluginHash?: string; sheetInfo: IMusic.IMusicSheetItemBase; }; } /** 路由参数Hook */ export function useParams(): RouterParams[T] { const route = useRoute(); const routeParams = route?.params as RouterParams[T]; return routeParams; } /** 导航 */ export function useNavigate() { const navigation = useNavigation(); const navigate = useCallback(function ( route: T, params?: RouterParams[T], ) { navigation.navigate(route, params); }, []); return navigate; } ================================================ FILE: src/core/router/routes.tsx ================================================ import Home from "@/pages/home"; import MusicDetail from "@/pages/musicDetail"; import TopList from "@/pages/topList"; import TopListDetail from "@/pages/topListDetail"; import SearchPage from "@/pages/searchPage"; import SheetDetail from "@/pages/sheetDetail"; import AlbumDetail from "@/pages/albumDetail"; import ArtistDetail from "@/pages/artistDetail"; import Setting from "@/pages/setting"; import LocalMusic from "@/pages/localMusic"; import Downloading from "@/pages/downloading"; import SearchMusicList from "@/pages/searchMusicList"; import MusicListEditor from "@/pages/musicListEditor"; import FileSelector from "@/pages/fileSelector"; import RecommendSheets from "@/pages/recommendSheets"; import PluginSheetDetail from "@/pages/pluginSheetDetail"; import History from "@/pages/history"; import SetCustomTheme from "@/pages/setCustomTheme"; import Permissions from "@/pages/permissions"; import { ROUTE_PATH } from "@/core/router/index.ts"; type ValueOf = T[keyof T]; export type RoutePaths = ValueOf; type IRoutes = { path: RoutePaths; component: (...args: any[]) => JSX.Element; }; export const routes: Array = [ { path: ROUTE_PATH.HOME, component: Home, }, { path: ROUTE_PATH.MUSIC_DETAIL, component: MusicDetail, }, { path: ROUTE_PATH.TOP_LIST, component: TopList, }, { path: ROUTE_PATH.TOP_LIST_DETAIL, component: TopListDetail, }, { path: ROUTE_PATH.SEARCH_PAGE, component: SearchPage, }, { path: ROUTE_PATH.LOCAL_SHEET_DETAIL, component: SheetDetail, }, { path: ROUTE_PATH.ALBUM_DETAIL, component: AlbumDetail, }, { path: ROUTE_PATH.ARTIST_DETAIL, component: ArtistDetail, }, { path: ROUTE_PATH.SETTING, component: Setting, }, { path: ROUTE_PATH.LOCAL, component: LocalMusic, }, { path: ROUTE_PATH.DOWNLOADING, component: Downloading, }, { path: ROUTE_PATH.SEARCH_MUSIC_LIST, component: SearchMusicList, }, { path: ROUTE_PATH.MUSIC_LIST_EDITOR, component: MusicListEditor, }, { path: ROUTE_PATH.FILE_SELECTOR, component: FileSelector, }, { path: ROUTE_PATH.RECOMMEND_SHEETS, component: RecommendSheets, }, { path: ROUTE_PATH.PLUGIN_SHEET_DETAIL, component: PluginSheetDetail, }, { path: ROUTE_PATH.HISTORY, component: History, }, { path: ROUTE_PATH.SET_CUSTOM_THEME, component: SetCustomTheme, }, { path: ROUTE_PATH.PERMISSIONS, component: Permissions, }, ]; ================================================ FILE: src/core/theme.ts ================================================ import Config from "@/core/appConfig"; import { DarkTheme as _DarkTheme, DefaultTheme as _DefaultTheme } from "@react-navigation/native"; import { GlobalState } from "@/utils/stateMapper"; import { CustomizedColors } from "@/hooks/useColors"; import Color from "color"; export const lightTheme = { id: "p-light", ..._DefaultTheme, colors: { ..._DefaultTheme.colors, background: "transparent", text: "#333333", textSecondary: Color("#333333").alpha(0.7).toString(), primary: "#f17d34", pageBackground: "#fafafa", shadow: "#000", appBar: "#f17d34", appBarText: "#fefefe", musicBar: "#f2f2f2", musicBarText: "#333333", divider: "rgba(0,0,0,0.1)", listActive: "rgba(0,0,0,0.1)", // 在手机上表现是ripple mask: "rgba(51,51,51,0.2)", backdrop: "#f0f0f0", tabBar: "#f0f0f0", placeholder: "#eaeaea", success: "#08A34C", danger: "#FC5F5F", info: "#0A95C8", card: "#e2e2e288", notification: "#f0f0f0", }, }; export const darkTheme = { id: "p-dark", ..._DarkTheme, colors: { ..._DarkTheme.colors, background: "transparent", text: "#fcfcfc", textSecondary: Color("#fcfcfc").alpha(0.7).toString(), primary: "#3FA3B5", pageBackground: "#202020", shadow: "#999", appBar: "#262626", appBarText: "#fcfcfc", musicBar: "#262626", musicBarText: "#fcfcfc", divider: "rgba(255,255,255,0.1)", listActive: "rgba(255,255,255,0.1)", // 在手机上表现是ripple mask: "rgba(33,33,33,0.8)", backdrop: "#303030", tabBar: "#303030", placeholder: "#424242", success: "#08A34C", danger: "#FC5F5F", info: "#0A95C8", card: "#33333388", notification: "#303030", }, }; interface IBackgroundInfo { url?: string; blur?: number; opacity?: number; } const themeStore = new GlobalState(darkTheme); const backgroundStore = new GlobalState(null); function setup() { const currentTheme = Config.getConfig("theme.selectedTheme") ?? "p-dark"; if (currentTheme === "p-dark") { themeStore.setValue(darkTheme); } else if (currentTheme === "p-light") { themeStore.setValue(lightTheme); } else { themeStore.setValue({ id: currentTheme, dark: true, // @ts-ignore colors: (Config.getConfig("theme.colors") as CustomizedColors) ?? darkTheme.colors, }); } const bgUrl = Config.getConfig("theme.background"); const bgBlur = Config.getConfig("theme.backgroundBlur"); const bgOpacity = Config.getConfig("theme.backgroundOpacity"); backgroundStore.setValue({ url: bgUrl, blur: bgBlur ?? 20, opacity: bgOpacity ?? 0.6, }); } function setTheme( themeName: string, extra?: { colors?: Partial; background?: IBackgroundInfo; }, ) { if (themeName === "p-light") { themeStore.setValue(lightTheme); } else if (themeName === "p-dark") { themeStore.setValue(darkTheme); } else { themeStore.setValue({ id: themeName, dark: true, colors: { ...darkTheme.colors, ...(extra?.colors ?? {}), }, }); } Config.setConfig("theme.selectedTheme", themeName); Config.setConfig("theme.colors", themeStore.getValue().colors); if (extra?.background) { const currentBg = backgroundStore.getValue(); let newBg: IBackgroundInfo = { blur: 20, opacity: 0.6, ...(currentBg ?? {}), url: undefined, }; if (typeof extra.background.blur === "number") { newBg.blur = extra.background.blur; } if (typeof extra.background.opacity === "number") { newBg.opacity = extra.background.opacity; } if (extra.background.url) { newBg.url = extra.background.url; } Config.setConfig("theme.background", newBg.url); Config.setConfig("theme.backgroundBlur", newBg.blur); Config.setConfig("theme.backgroundOpacity", newBg.opacity); backgroundStore.setValue(newBg); } } function setColors(colors: Partial) { const currentTheme = themeStore.getValue(); if (currentTheme.id !== "p-light" && currentTheme.id !== "p-dark") { const newTheme = { ...currentTheme, colors: { ...currentTheme.colors, ...colors, }, }; Config.setConfig("theme.customColors", newTheme.colors); Config.setConfig("theme.colors", newTheme.colors); themeStore.setValue(newTheme); } } function setBackground(backgroundInfo: Partial) { const currentBackgroundInfo = backgroundStore.getValue(); let newBgInfo = { ...(currentBackgroundInfo ?? { opacity: 0.6, blur: 20, }), }; if (typeof backgroundInfo.blur === "number") { Config.setConfig("theme.backgroundBlur", backgroundInfo.blur); newBgInfo.blur = backgroundInfo.blur; } if (typeof backgroundInfo.opacity === "number") { Config.setConfig("theme.backgroundOpacity", backgroundInfo.opacity); newBgInfo.opacity = backgroundInfo.opacity; } if (backgroundInfo.url !== undefined) { Config.setConfig("theme.background", backgroundInfo.url); newBgInfo.url = backgroundInfo.url; } backgroundStore.setValue(newBgInfo); } const configableColorKey: Array = [ "primary", "text", "appBar", "appBarText", "musicBar", "musicBarText", "pageBackground", "backdrop", "card", "placeholder", "tabBar", "notification", ]; const Theme = { setup, setTheme, setBackground, setColors, useTheme: themeStore.useValue, getTheme: themeStore.getValue, useBackground: backgroundStore.useValue, configableColorKey, }; export default Theme; ================================================ FILE: src/core/trackPlayer/index.ts ================================================ import { getCurrentDialog, showDialog } from "@/components/dialogs/useDialog"; import { internalFakeSoundKey, sortIndexSymbol, timeStampSymbol, } from "@/constants/commonConst"; import { MusicRepeatMode } from "@/constants/repeatModeConst"; import delay from "@/utils/delay"; import getUrlExt from "@/utils/getUrlExt"; import { errorLog, trace } from "@/utils/log"; import { createMediaIndexMap } from "@/utils/mediaIndexMap"; import { getLocalPath, isSameMediaItem, } from "@/utils/mediaUtils"; import Network from "@/utils/network"; import PersistStatus from "@/utils/persistStatus"; import { getQualityOrder } from "@/utils/qualities"; import { musicIsPaused } from "@/utils/trackUtils"; import EventEmitter from "eventemitter3"; import { produce } from "immer"; import { atom, getDefaultStore, useAtomValue } from "jotai"; import shuffle from "lodash.shuffle"; import ReactNativeTrackPlayer, { Event, State, Track, TrackMetadataBase, usePlaybackState, useProgress, } from "react-native-track-player"; import LocalMusicSheet from "../localMusicSheet"; import { TrackPlayerEvents } from "@/core.defination/trackPlayer"; import type { IAppConfig } from "@/types/core/config"; import type { IMusicHistory } from "@/types/core/musicHistory"; import { ITrackPlayer } from "@/types/core/trackPlayer/index"; import minDistance from "@/utils/minDistance"; import { IPluginManager } from "@/types/core/pluginManager"; import { ImgAsset } from "@/constants/assetsConst"; import { resolveImportedAssetOrPath } from "@/utils/fileUtils"; const currentMusicAtom = atom(null); const repeatModeAtom = atom(MusicRepeatMode.QUEUE); const qualityAtom = atom("standard"); const playListAtom = atom([]); class TrackPlayer extends EventEmitter<{ [TrackPlayerEvents.PlayEnd]: () => void; [TrackPlayerEvents.CurrentMusicChanged]: (musicItem: IMusic.IMusicItem | null) => void; [TrackPlayerEvents.ProgressChanged]: (progress: { position: number; duration: number; }) => void; }> implements ITrackPlayer { // 依赖 private configService!: IAppConfig; private musicHistoryService!: IMusicHistory; private pluginManagerService!: IPluginManager; // 当前播放的音乐下标 private currentIndex = -1; // 音乐播放器服务是否启动 private serviceInited = false; // 播放队列索引map private playListIndexMap = createMediaIndexMap([] as IMusic.IMusicItem[]); private static maxMusicQueueLength = 10000; private static halfMaxMusicQueueLength = 5000; private static toggleRepeatMapping = { [MusicRepeatMode.SHUFFLE]: MusicRepeatMode.SINGLE, [MusicRepeatMode.SINGLE]: MusicRepeatMode.QUEUE, [MusicRepeatMode.QUEUE]: MusicRepeatMode.SHUFFLE, }; private static fakeAudioUrl = "musicfree://fake-audio"; private static proposedAudioUrl = "musicfree://proposed-audio"; constructor() { super(); } public get previousMusic() { const currentMusic = this.currentMusic; if (!currentMusic) { return null; } return this.getPlayListMusicAt(this.currentIndex - 1); } public get currentMusic() { return getDefaultStore().get(currentMusicAtom); } public get nextMusic() { const currentMusic = this.currentMusic; if (!currentMusic) { return null; } return this.getPlayListMusicAt(this.currentIndex + 1); } public get repeatMode() { return getDefaultStore().get(repeatModeAtom); } public get quality() { return getDefaultStore().get(qualityAtom); } public get playList() { return getDefaultStore().get(playListAtom); } injectDependencies(configService: IAppConfig, musicHistoryService: IMusicHistory, pluginManager: IPluginManager): void { this.configService = configService; this.musicHistoryService = musicHistoryService; this.pluginManagerService = pluginManager; } async setupTrackPlayer() { const rate = PersistStatus.get("music.rate"); const musicQueue = PersistStatus.get("music.playList"); const repeatMode = PersistStatus.get("music.repeatMode"); const progress = PersistStatus.get("music.progress"); const track = PersistStatus.get("music.musicItem"); const quality = PersistStatus.get("music.quality") || this.configService.getConfig("basic.defaultPlayQuality") || "standard"; // 状态恢复 if (rate) { ReactNativeTrackPlayer.setRate(+rate / 100); } if (repeatMode) { getDefaultStore().set(repeatModeAtom, repeatMode as MusicRepeatMode); } if (musicQueue && Array.isArray(musicQueue)) { this.addAll( musicQueue, undefined, repeatMode === MusicRepeatMode.SHUFFLE, ); } if (track && this.isInPlayList(track)) { if (!this.configService.getConfig("basic.autoPlayWhenAppStart")) { track.isInit = true; } // 异步 this.pluginManagerService.getByMedia(track) ?.methods.getMediaSource(track, quality) .then(async newSource => { track.url = newSource?.url || track.url; track.headers = newSource?.headers || track.headers; if (isSameMediaItem(this.currentMusic, track)) { await this.setTrackSource(track as Track, false); if (progress) { // 异步 this.seekTo(progress); } } }); this.setCurrentMusic(track); if (progress) { // 异步 this.seekTo(progress); } } if (!this.serviceInited) { /** * 此事件可能会被触发多次(比如直接替换queue) 参考代码:https://github.com/doublesymmetry/KotlinAudio */ ReactNativeTrackPlayer.addEventListener( Event.PlaybackActiveTrackChanged, async evt => { if ( evt.index === 1 && evt.lastIndex === 0 && evt.track?.url === TrackPlayer.fakeAudioUrl ) { trace("队列末尾,播放下一首"); this.emit(TrackPlayerEvents.PlayEnd); if ( this.repeatMode === MusicRepeatMode.SINGLE ) { await this.play(null, true); } else { // 当前生效的歌曲是下一曲的标记 await this.skipToNext(); } } }, ); ReactNativeTrackPlayer.addEventListener( Event.PlaybackError, async e => { errorLog("播放出错", e.message); // WARNING: 不稳定,报错的时候有可能track已经变到下一首歌去了 const currentTrack = await ReactNativeTrackPlayer.getActiveTrack(); if (currentTrack?.isInit) { // HACK: 避免初始失败的情况 ReactNativeTrackPlayer.updateMetadataForTrack(0, { ...currentTrack, // @ts-ignore isInit: undefined, }); return; } if ( currentTrack?.url !== TrackPlayer.fakeAudioUrl && currentTrack?.url !== TrackPlayer.proposedAudioUrl && (await ReactNativeTrackPlayer.getActiveTrackIndex()) === 0 && e.message && e.message !== "android-io-file-not-found" ) { trace("播放出错", { message: e.message, code: e.code, }); this.handlePlayFail(); } }, ); this.serviceInited = true; } } /**************** 播放队列 ******************/ getMusicIndexInPlayList(musicItem?: IMusic.IMusicItem | null) { if (!musicItem) { return -1; } return this.playListIndexMap.getIndex(musicItem); } isInPlayList(musicItem?: IMusic.IMusicItem | null) { if (!musicItem) { return false; } return this.playListIndexMap.has(musicItem); } getPlayListMusicAt(index: number): IMusic.IMusicItem | null { const playList = this.playList; const len = playList.length; if (len === 0) { return null; } return playList[(index + len) % len]; } isPlayListEmpty() { return this.playList.length === 0; } /****** 播放逻辑 *****/ addAll( musicItems: Array, beforeIndex?: number, shouldShuffle?: boolean, ): void { const now = Date.now(); let newPlayList: IMusic.IMusicItem[] = []; let currentPlayList = this.playList; musicItems.forEach((item, index) => { item[timeStampSymbol] = now; item[sortIndexSymbol] = index; }); if (beforeIndex === undefined || beforeIndex < 0) { // 1.1. 添加到歌单末尾,并过滤掉已有的歌曲 newPlayList = currentPlayList.concat( musicItems.filter(item => !this.isInPlayList(item)), ); } else { // 1.2. 新的播放列表,插入 const indexMap = createMediaIndexMap(musicItems); const beforeDraft = currentPlayList .slice(0, beforeIndex) .filter(item => !indexMap.has(item)); const afterDraft = currentPlayList .slice(beforeIndex) .filter(item => !indexMap.has(item)); newPlayList = [...beforeDraft, ...musicItems, ...afterDraft]; } // 如果太长了 if (newPlayList.length > TrackPlayer.maxMusicQueueLength) { newPlayList = this.shrinkPlayListToSize( newPlayList, beforeIndex ?? newPlayList.length - 1, ); } // 2. 如果需要随机 if (shouldShuffle) { newPlayList = shuffle(newPlayList); } // 3. 设置播放列表 this.setPlayList(newPlayList); } add( musicItem: IMusic.IMusicItem | IMusic.IMusicItem[], beforeIndex?: number, ): void { this.addAll( Array.isArray(musicItem) ? musicItem : [musicItem], beforeIndex, ); } addNext(musicItem: IMusic.IMusicItem | IMusic.IMusicItem[]): void { const shouldAutoPlay = this.isPlayListEmpty() || !this.currentMusic; this.add(musicItem, this.currentIndex + 1); if (shouldAutoPlay) { this.play(Array.isArray(musicItem) ? musicItem[0] : musicItem); } } async remove(musicItem: IMusic.IMusicItem): Promise { const playList = this.playList; let newPlayList: IMusic.IMusicItem[] = []; let currentMusic: IMusic.IMusicItem | null = this.currentMusic; const targetIndex = this.getMusicIndexInPlayList(musicItem); let shouldPlayCurrent: boolean | null = null; if (targetIndex === -1) { // 1. 这种情况应该是出错了 return; } // 2. 移除的是当前项 if (this.currentIndex === targetIndex) { // 2.1 停止播放,移除当前项 newPlayList = produce(playList, draft => { draft.splice(targetIndex, 1); }); // 2.2 设置新的播放列表,并更新当前音乐 if (newPlayList.length === 0) { currentMusic = null; shouldPlayCurrent = false; } else { currentMusic = newPlayList[this.currentIndex % newPlayList.length]; try { const state = ( await ReactNativeTrackPlayer.getPlaybackState() ).state; shouldPlayCurrent = !musicIsPaused(state); } catch { shouldPlayCurrent = false; } } this.setCurrentMusic(currentMusic); } else { // 3. 删除 newPlayList = produce(playList, draft => { draft.splice(targetIndex, 1); }); } this.setPlayList(newPlayList); if (shouldPlayCurrent === true) { await this.play(currentMusic, true); } else if (shouldPlayCurrent === false) { await ReactNativeTrackPlayer.reset(); } } isCurrentMusic(musicItem?: IMusic.IMusicItem | null) { return isSameMediaItem(musicItem, this.currentMusic); } async play( musicItem?: IMusic.IMusicItem | null, forcePlay?: boolean, ): Promise { try { // 如果不传参,默认是播放当前音乐 if (!musicItem) { musicItem = this.currentMusic; } if (!musicItem) { throw new Error(PlayFailReason.PLAY_LIST_IS_EMPTY); } // 1. 移动网络禁止播放 const localPath = getLocalPath(musicItem); if ( Network.isCellular && !this.configService.getConfig("basic.useCelluarNetworkPlay") && !LocalMusicSheet.isLocalMusic(musicItem) && !localPath ) { await ReactNativeTrackPlayer.reset(); throw new Error(PlayFailReason.FORBID_CELLUAR_NETWORK_PLAY); } // 2. 如果是当前正在播放的音频 if (this.isCurrentMusic(musicItem)) { // 获取底层播放器中的track const currentTrack = await ReactNativeTrackPlayer.getTrack(0); // 2.1 如果当前有源 if ( currentTrack?.url && isSameMediaItem( musicItem, currentTrack as IMusic.IMusicItem, ) ) { const currentActiveIndex = await ReactNativeTrackPlayer.getActiveTrackIndex(); if (currentActiveIndex !== 0) { await ReactNativeTrackPlayer.skip(0); } if (forcePlay) { // 2.1.1 强制重新开始 await this.seekTo(0); } const currentState = ( await ReactNativeTrackPlayer.getPlaybackState() ).state; if (currentState === State.Stopped) { await this.setTrackSource(currentTrack); } if (currentState !== State.Playing) { // 2.1.2 恢复播放 await ReactNativeTrackPlayer.play(); } // 这种情况下,播放队列和当前歌曲都不需要变化 return; } // 2.2 其他情况:重新获取源 } // 3. 如果没有在播放列表中,添加到队尾;同时更新列表状态 const inPlayList = this.isInPlayList(musicItem); if (!inPlayList) { this.add(musicItem); } // 4. 更新列表状态和当前音乐 this.setCurrentMusic(musicItem); await ReactNativeTrackPlayer.setQueue([{ ...musicItem, url: TrackPlayer.proposedAudioUrl, artwork: resolveImportedAssetOrPath(musicItem.artwork?.trim?.()?.length ? musicItem.artwork : ImgAsset.albumDefault) as unknown as any, }, this.getFakeNextTrack()]); // 5. 获取音源 let track: IMusic.IMusicItem; // 5.1 通过插件获取音源 const plugin = this.pluginManagerService.getByName(musicItem.platform); // 5.2 获取音质排序 const qualityOrder = getQualityOrder( this.configService.getConfig("basic.defaultPlayQuality") ?? "standard", this.configService.getConfig("basic.playQualityOrder") ?? "asc", ); // 5.3 插件返回音源 let source: IPlugin.IMediaSourceResult | null = null; for (let quality of qualityOrder) { if (this.isCurrentMusic(musicItem)) { source = (await plugin?.methods?.getMediaSource( musicItem, quality, )) ?? null; // 5.3.1 获取到真实源 if (source) { this.setQuality(quality); break; } } else { // 5.3.2 已经切换到其他歌曲了, return; } } if (!this.isCurrentMusic(musicItem)) { return; } if (!source) { // 如果有source if (musicItem.source) { for (let quality of qualityOrder) { if (musicItem.source[quality]?.url) { source = musicItem.source[quality]!; this.setQuality(quality); break; } } } // 5.4 没有返回源 if (!source && !musicItem.url) { // 插件失效的情况 if (this.configService.getConfig("basic.tryChangeSourceWhenPlayFail")) { // 重试 const similarMusic = await this.getSimilarMusic( musicItem, "music", () => !this.isCurrentMusic(musicItem), ); if (similarMusic) { const similarMusicPlugin = this.pluginManagerService.getByMedia(similarMusic); for (let quality of qualityOrder) { if (this.isCurrentMusic(musicItem)) { source = (await similarMusicPlugin?.methods?.getMediaSource( similarMusic, quality, )) ?? null; // 5.4.1 获取到真实源 if (source) { this.setQuality(quality); break; } } else { // 5.4.2 已经切换到其他歌曲了, return; } } } if (!source) { throw new Error(PlayFailReason.INVALID_SOURCE); } } else { throw new Error(PlayFailReason.INVALID_SOURCE); } } else { source = { url: musicItem.url, }; this.setQuality("standard"); } } // 6. 特殊类型源 if (getUrlExt(source.url) === ".m3u8") { // @ts-ignore source.type = "hls"; } // 7. 合并结果 track = this.mergeTrackSource(musicItem, source) as IMusic.IMusicItem; // 8. 新增历史记录 this.musicHistoryService.addMusic(musicItem); trace("获取音源成功", track); // 9. 设置音源 await this.setTrackSource(track as Track); // 10. 获取补充信息 let info: Partial | null = null; try { info = (await plugin?.methods?.getMusicInfo?.(musicItem)) ?? null; if ( (typeof info?.url === "string" && info.url.trim() === "") || (info?.url && typeof info.url !== "string") ) { delete info.url; } } catch { } // 11. 设置补充信息 if (info && this.isCurrentMusic(musicItem)) { const mergedTrack = this.mergeTrackSource(track, info); getDefaultStore().set(currentMusicAtom, mergedTrack as IMusic.IMusicItem); await ReactNativeTrackPlayer.updateMetadataForTrack( 0, mergedTrack as TrackMetadataBase, ); } } catch (e: any) { const message = e?.message; if ( message === "The player is not initialized. Call setupPlayer first." ) { await ReactNativeTrackPlayer.setupPlayer(); this.play(musicItem, forcePlay); } else if (message === PlayFailReason.FORBID_CELLUAR_NETWORK_PLAY) { if (getCurrentDialog()?.name !== "SimpleDialog") { showDialog("SimpleDialog", { title: "流量提醒", content: "当前非WIFI环境,侧边栏设置中打开【使用移动网络播放】功能后可继续播放", }); } } else if (message === PlayFailReason.INVALID_SOURCE) { trace("音源为空,播放失败"); await this.handlePlayFail(); } else if (message === PlayFailReason.PLAY_LIST_IS_EMPTY) { // 队列是空的,不应该出现这种情况 } } } async pause(): Promise { await ReactNativeTrackPlayer.pause(); } toggleRepeatMode(): void { this.setRepeatMode(TrackPlayer.toggleRepeatMapping[this.repeatMode]); } // 清空播放队列 async clearPlayList(): Promise { this.setPlayList([]); this.setCurrentMusic(null); await ReactNativeTrackPlayer.reset(); PersistStatus.set("music.musicItem", undefined); PersistStatus.set("music.progress", 0); } async skipToNext(): Promise { if (this.isPlayListEmpty()) { this.setCurrentMusic(null); return; } await this.play(this.getPlayListMusicAt(this.currentIndex + 1), true); } async skipToPrevious(): Promise { if (this.isPlayListEmpty()) { this.setCurrentMusic(null); return; } await this.play( this.getPlayListMusicAt(this.currentIndex === -1 ? 0 : this.currentIndex - 1), true, ); } async changeQuality(newQuality: IMusic.IQualityKey): Promise { // 获取当前的音乐和进度 if (newQuality === this.quality) { return true; } // 获取当前歌曲 const musicItem = this.currentMusic; if (!musicItem) { return false; } try { const progress = await ReactNativeTrackPlayer.getProgress(); const plugin = this.pluginManagerService.getByMedia(musicItem); const newSource = await plugin?.methods?.getMediaSource( musicItem, newQuality, ); if (!newSource?.url) { throw new Error(PlayFailReason.INVALID_SOURCE); } if (this.isCurrentMusic(musicItem)) { const playingState = ( await ReactNativeTrackPlayer.getPlaybackState() ).state; await this.setTrackSource( this.mergeTrackSource(musicItem, newSource) as unknown as Track, !musicIsPaused(playingState), ); await this.seekTo(progress.position ?? 0); this.setQuality(newQuality); } return true; } catch { // 修改失败 return false; } } async playWithReplacePlayList( musicItem: IMusic.IMusicItem, newPlayList: IMusic.IMusicItem[], ): Promise { if (newPlayList.length !== 0) { const now = Date.now(); if (newPlayList.length > TrackPlayer.maxMusicQueueLength) { newPlayList = this.shrinkPlayListToSize( newPlayList, newPlayList.findIndex(it => isSameMediaItem(it, musicItem)), ); } newPlayList.forEach((it, index) => { it[timeStampSymbol] = now; it[sortIndexSymbol] = index; }); this.setPlayList( this.repeatMode === MusicRepeatMode.SHUFFLE ? shuffle(newPlayList) : newPlayList, ); await this.play(musicItem, true); } } async seekTo(progress: number) { PersistStatus.set("music.progress", progress); return ReactNativeTrackPlayer.seekTo(progress); } getProgress = ReactNativeTrackPlayer.getProgress; getRate = ReactNativeTrackPlayer.getRate; setRate = ReactNativeTrackPlayer.setRate; reset = ReactNativeTrackPlayer.reset; /**************** 辅助函数 -- 设置内部状态 ****************/ private setCurrentMusic(musicItem?: IMusic.IMusicItem | null) { // 设置UI内部状态的musicitem if (!musicItem) { this.currentIndex = -1; getDefaultStore().set(currentMusicAtom, null); PersistStatus.set("music.musicItem", undefined); PersistStatus.set("music.progress", 0); this.emit(TrackPlayerEvents.CurrentMusicChanged, null); return; } if (typeof musicItem.artwork !== "string") { musicItem.artwork = ImgAsset.albumDefault; } this.currentIndex = this.getMusicIndexInPlayList(musicItem); getDefaultStore().set(currentMusicAtom, musicItem); this.emit(TrackPlayerEvents.CurrentMusicChanged, musicItem); } private setRepeatMode(mode: MusicRepeatMode) { const playList = this.playList; let newPlayList: IMusic.IMusicItem[]; const prevMode = getDefaultStore().get(repeatModeAtom); if ( (prevMode === MusicRepeatMode.SHUFFLE && mode !== MusicRepeatMode.SHUFFLE) || (mode === MusicRepeatMode.SHUFFLE && prevMode !== MusicRepeatMode.SHUFFLE) ) { if (mode === MusicRepeatMode.SHUFFLE) { newPlayList = shuffle(playList); } else { newPlayList = this.sortByTimestampAndIndex(playList, true); } this.setPlayList(newPlayList); } getDefaultStore().set(repeatModeAtom, mode); // 更新下一首歌的信息 ReactNativeTrackPlayer.updateMetadataForTrack( 1, this.getFakeNextTrack(), ); // 记录 PersistStatus.set("music.repeatMode", mode); } private setQuality(quality: IMusic.IQualityKey) { getDefaultStore().set(qualityAtom, quality); PersistStatus.set("music.quality", quality); } // 设置音源 private async setTrackSource(track: Track, autoPlay = true) { const clonedTrack = this.patchMediaArtwork(track); if (!clonedTrack) { return; } await ReactNativeTrackPlayer.setQueue([clonedTrack, this.getFakeNextTrack()]); PersistStatus.set("music.musicItem", track as IMusic.IMusicItem); PersistStatus.set("music.progress", 0); if (autoPlay) { await ReactNativeTrackPlayer.play(); } } /** * 设置播放队列 * @param newPlayList 播放队列 * @param persist 是否持久化 */ private setPlayList(newPlayList: IMusic.IMusicItem[], persist = true) { getDefaultStore().set(playListAtom, newPlayList); this.playListIndexMap = createMediaIndexMap(newPlayList); if (persist) { PersistStatus.set("music.playList", newPlayList); } this.currentIndex = this.getMusicIndexInPlayList(this.currentMusic); } /**************** 辅助函数 -- 工具方法 ****************/ private shrinkPlayListToSize = ( queue: IMusic.IMusicItem[], targetIndex = this.currentIndex, ) => { // 播放列表上限,太多无法缓存状态 if (queue.length > TrackPlayer.maxMusicQueueLength) { if (targetIndex < TrackPlayer.halfMaxMusicQueueLength) { queue = queue.slice(0, TrackPlayer.maxMusicQueueLength); } else { const right = Math.min( queue.length, targetIndex + TrackPlayer.halfMaxMusicQueueLength, ); const left = Math.max(0, right - TrackPlayer.maxMusicQueueLength); queue = queue.slice(left, right); } } return queue; }; private mergeTrackSource( mediaItem: ICommon.IMediaBase, props: Record | undefined, ) { return props ? { ...mediaItem, ...props, id: mediaItem.id, platform: mediaItem.platform, } : mediaItem; } private sortByTimestampAndIndex(array: any[], newArray = false) { if (newArray) { array = [...array]; } return array.sort((a, b) => { const ts = a[timeStampSymbol] - b[timeStampSymbol]; if (ts !== 0) { return ts; } return a[sortIndexSymbol] - b[sortIndexSymbol]; }); } private getFakeNextTrack() { let track: Track | undefined; const repeatMode = this.repeatMode; if (repeatMode === MusicRepeatMode.SINGLE) { // 单曲循环 track = this.getPlayListMusicAt(this.currentIndex) as Track; } else { // 下一曲 track = this.getPlayListMusicAt(this.currentIndex + 1) as Track; } if (track) { return produce(track, _ => { _.url = TrackPlayer.fakeAudioUrl; _.$ = internalFakeSoundKey; _.artwork = resolveImportedAssetOrPath(ImgAsset.albumDefault) as unknown as any; }); } else { // 只有列表长度为0时才会出现的特殊情况 return { url: TrackPlayer.fakeAudioUrl, $: internalFakeSoundKey, } as Track; } } private async handlePlayFail() { // 如果自动跳转下一曲, 500s后自动跳转 if (!this.configService.getConfig("basic.autoStopWhenError")) { await delay(500); await this.skipToNext(); } } /** * * @param musicItem 音乐类型 * @param type 媒体类型 * @param abortFunction 如果函数为true,则中断 * @returns */ private async getSimilarMusic( musicItem: IMusic.IMusicItem, type: T = "music" as T, abortFunction?: () => boolean, ): Promise { const keyword = musicItem.alias || musicItem.title; const plugins = this.pluginManagerService.getSearchablePlugins(type); let distance = Infinity; let minDistanceMusicItem; let targetPlugin; const startTime = Date.now(); for (let plugin of plugins) { // 超时时间:8s if (abortFunction?.() || Date.now() - startTime > 8000) { break; } if (plugin.name === musicItem.platform) { continue; } const results = await plugin.methods .search(keyword, 1, type) .catch(() => null); // 取前两个 const firstTwo = results?.data?.slice(0, 2) || []; for (let item of firstTwo) { if (item.title === keyword && item.artist === musicItem.artist) { distance = 0; minDistanceMusicItem = item; targetPlugin = plugin; break; } else { const dist = minDistance(keyword, musicItem.title) + minDistance(item.artist, musicItem.artist); if (dist < distance) { distance = dist; minDistanceMusicItem = item; targetPlugin = plugin; } } } if (distance === 0) { break; } } if (minDistanceMusicItem && targetPlugin) { return minDistanceMusicItem as ICommon.SupportMediaItemBase[T]; } return null; } private patchMediaArtwork(track: Track) { // Bug: React native track player 在设置音频时,artwork不能为null,并且部分情况下artwork不能为ImageSource类型 if (!track) { return null; } return { ...track, artwork: resolveImportedAssetOrPath( track.artwork?.trim?.()?.length ? track.artwork : ImgAsset.albumDefault, ) as unknown as any, }; } } export const usePlayList = () => useAtomValue(playListAtom); export const useCurrentMusic = () => useAtomValue(currentMusicAtom); export const useRepeatMode = () => useAtomValue(repeatModeAtom); export const useMusicQuality = () => useAtomValue(qualityAtom); export function useMusicState() { const playbackState = usePlaybackState(); return playbackState.state; } export { State as MusicState, useProgress }; enum PlayFailReason { /** 禁止移动网络播放 */ FORBID_CELLUAR_NETWORK_PLAY = "FORBID_CELLUAR_NETWORK_PLAY", /** 播放列表为空 */ PLAY_LIST_IS_EMPTY = "PLAY_LIST_IS_EMPTY", /** 无效源 */ INVALID_SOURCE = "INVALID_SOURCE", /** 非当前音乐 */ } const trackPlayer = new TrackPlayer(); export default trackPlayer; ================================================ FILE: src/core.defination/trackPlayer/index.ts ================================================ export enum TrackPlayerEvents { // 一首歌曲播放结束 PlayEnd = "play-end", // 更换正在播放的歌曲 CurrentMusicChanged = "current-music-changed", // 进度更新 ProgressChanged = "progress-changed", } ================================================ FILE: src/entry/bootstrap/BootstrapComponent.tsx ================================================ import { useAppConfig } from "@/core/appConfig"; import Theme from "@/core/theme"; import useCheckUpdate from "@/hooks/useCheckUpdate"; import { useListenOrientationChange } from "@/hooks/useOrientation"; import { getDefaultStore, useAtomValue } from "jotai"; import { useEffect } from "react"; import { AppState, NativeEventSubscription, useColorScheme } from "react-native"; import bootstrapAtom from "./bootstrap.atom"; import { initTrackPlayer } from "./bootstrap"; import { showDialog } from "@/components/dialogs/useDialog"; import i18n from "@/core/i18n"; export function BootstrapComponent() { const bootstrapState = useAtomValue(bootstrapAtom); useListenOrientationChange(); useCheckUpdate(); const followSystem = useAppConfig("theme.followSystem"); const colorScheme = useColorScheme(); useEffect(() => { if (followSystem) { if (colorScheme === "dark") { Theme.setTheme("p-dark"); } else if (colorScheme === "light") { Theme.setTheme("p-light"); } } }, [colorScheme, followSystem]); useEffect(() => { let appStateEventSubscription: NativeEventSubscription | null = null; const reinitializeTrackPlayerWithDialog = () => { showDialog("LoadingDialog", { title: i18n.t("dialog.loading.reinitializeTrackPlayer"), promise: initTrackPlayer(), onResolve(data, hideDialog) { hideDialog(); }, onReject(reason, hideDialog) { hideDialog(); }, }); }; if (bootstrapState.state === "TrackPlayerError") { if (AppState.currentState === "active") { reinitializeTrackPlayerWithDialog(); } else { appStateEventSubscription = AppState.addEventListener("change", (nextState) => { if (nextState === "active" && getDefaultStore().get(bootstrapAtom).state === "TrackPlayerError") { reinitializeTrackPlayerWithDialog(); } }); } } return () => { if (appStateEventSubscription) { appStateEventSubscription.remove(); } }; }, [bootstrapState]); return null; } ================================================ FILE: src/entry/bootstrap/bootstrap.atom.ts ================================================ import { atom } from "jotai"; interface IBootStrapState { state: "Loading" | "Done" | "Fatal" | "TrackPlayerError" reason?: Error, } const bootstrapAtom = atom({ state: "Loading", }); export default bootstrapAtom; ================================================ FILE: src/entry/bootstrap/bootstrap.ts ================================================ import "react-native-get-random-values"; import { getCurrentDialog, showDialog } from "@/components/dialogs/useDialog.ts"; import { ImgAsset } from "@/constants/assetsConst"; import { emptyFunction, localPluginHash, supportLocalMediaType } from "@/constants/commonConst"; import pathConst from "@/constants/pathConst"; import Config from "@/core/appConfig"; import downloader, { DownloadFailReason, DownloaderEvent } from "@/core/downloader"; import LocalMusicSheet from "@/core/localMusicSheet"; import lyricManager from "@/core/lyricManager"; import musicHistory from "@/core/musicHistory"; import MusicSheet from "@/core/musicSheet"; import PluginManager from "@/core/pluginManager"; import Theme from "@/core/theme"; import TrackPlayer from "@/core/trackPlayer"; import NativeUtils from "@/native/utils"; import { checkAndCreateDir } from "@/utils/fileUtils"; import { errorLog, trace } from "@/utils/log"; import { IPerfLogger, perfLogger } from "@/utils/perfLogger"; import PersistStatus from "@/utils/persistStatus"; import Toast from "@/utils/toast"; import * as SplashScreen from "expo-splash-screen"; import { Linking, Platform } from "react-native"; import { PERMISSIONS, check, request } from "react-native-permissions"; import RNTrackPlayer, { AppKilledPlaybackBehavior, Capability } from "react-native-track-player"; import i18n from "@/core/i18n"; import bootstrapAtom from "./bootstrap.atom"; import { getDefaultStore } from "jotai"; // 依赖管理 PluginManager.injectDependencies(Config); musicHistory.injectDependencies(Config); TrackPlayer.injectDependencies(Config, musicHistory, PluginManager); downloader.injectDependencies(Config, PluginManager); lyricManager.injectDependencies(TrackPlayer, Config, PluginManager); MusicSheet.injectDependencies(Config); async function bootstrapImpl() { await SplashScreen.preventAutoHideAsync() .then(result => console.log( `SplashScreen.preventAutoHideAsync() succeeded: ${result}`, ), ) .catch(console.warn); // it's good to explicitly catch and inspect any error const logger = perfLogger(); // 1. 检查权限 if (Platform.OS === "android" && Platform.Version >= 30) { const hasPermission = await NativeUtils.checkStoragePermission(); if ( !hasPermission && !PersistStatus.get("app.skipBootstrapStorageDialog") ) { showDialog("CheckStorage"); } } else { const [readStoragePermission, writeStoragePermission] = await Promise.all([ check(PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE), check(PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE), ]); if ( !( readStoragePermission === "granted" && writeStoragePermission === "granted" ) ) { await request(PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE); await request(PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE); } } logger.mark("权限检查完成"); // 2. 数据初始化 /** 初始化路径 */ await setupFolder(); trace("文件夹初始化完成"); logger.mark("文件夹初始化完成"); // 加载配置 await Promise.all([ Config.setup().then(() => { logger.mark("Config"); }), MusicSheet.setup().then(() => { logger.mark("MusicSheet"); }), musicHistory.setup().then(() => { logger.mark("musicHistory"); }), ]); trace("配置初始化完成"); logger.mark("配置初始化完成"); // 加载插件 await PluginManager.setup(); logger.mark("插件初始化完成"); trace("插件初始化完成"); await initTrackPlayer(logger).catch(err => { // 初始化播放器出错,延迟初始化 const bootstrapState = getDefaultStore().get(bootstrapAtom); if (bootstrapState.state === "Loading") { getDefaultStore().set(bootstrapAtom, { state: "TrackPlayerError", reason: err, }); } }); await LocalMusicSheet.setup(); trace("本地音乐初始化完成"); logger.mark("本地音乐初始化完成"); Theme.setup(); trace("主题初始化完成"); logger.mark("主题初始化完成"); extraMakeup(); i18n.setup(); logger.mark("语言模块初始化完成"); ErrorUtils.setGlobalHandler(error => { errorLog("未捕获的错误", error); }); } /** 初始化 */ async function setupFolder() { await Promise.all([ checkAndCreateDir(pathConst.dataPath), checkAndCreateDir(pathConst.logPath), checkAndCreateDir(pathConst.cachePath), checkAndCreateDir(pathConst.pluginPath), checkAndCreateDir(pathConst.lrcCachePath), checkAndCreateDir(pathConst.downloadCachePath), checkAndCreateDir(pathConst.localLrcPath), checkAndCreateDir(pathConst.downloadPath).then(() => { checkAndCreateDir(pathConst.downloadMusicPath); }), ]); } export async function initTrackPlayer(logger?: IPerfLogger) { try { await RNTrackPlayer.setupPlayer({ maxCacheSize: Config.getConfig("basic.maxCacheSize") ?? 1024 * 1024 * 512, }); } catch (e: any) { if ( e?.message !== "The player has already been initialized via setupPlayer." ) { throw e; } } logger?.mark("加载播放器"); const capabilities = Config.getConfig("basic.showExitOnNotification") ? [ Capability.Play, Capability.Pause, Capability.SkipToNext, Capability.SkipToPrevious, Capability.Stop, ] : [ Capability.Play, Capability.Pause, Capability.SkipToNext, Capability.SkipToPrevious, ]; await RNTrackPlayer.updateOptions({ icon: ImgAsset.logoTransparent, progressUpdateEventInterval: 1, android: { alwaysPauseOnInterruption: true, appKilledPlaybackBehavior: AppKilledPlaybackBehavior.ContinuePlayback, }, capabilities: capabilities, compactCapabilities: capabilities, notificationCapabilities: [...capabilities, Capability.SeekTo], }); logger?.mark("播放器初始化完成"); trace("播放器初始化完成"); await TrackPlayer.setupTrackPlayer(); trace("播放列表初始化完成"); logger?.mark("播放列表初始化完成"); await lyricManager.setup(); logger?.mark("歌词初始化完成"); } /** 不需要阻塞的 */ async function extraMakeup() { // 自动更新 try { if (Config.getConfig("basic.autoUpdatePlugin")) { const lastUpdated = PersistStatus.get("app.pluginUpdateTime") || 0; const now = Date.now(); if (Math.abs(now - lastUpdated) > 86400000) { PersistStatus.set("app.pluginUpdateTime", now); const plugins = PluginManager.getEnabledPlugins(); for (let i = 0; i < plugins.length; ++i) { const srcUrl = plugins[i].instance.srcUrl; if (srcUrl) { // 静默失败 await PluginManager.installPluginFromUrl(srcUrl).catch(emptyFunction); } } } } } catch { } async function handleLinkingUrl(url: string) { // 插件 try { if (url.startsWith("musicfree://install/")) { const plugins = url .slice(20) .split(",") .map(decodeURIComponent); await Promise.all( plugins.map(it => PluginManager.installPluginFromUrl(it).catch(emptyFunction), ), ); Toast.success("安装成功~"); } else if (url.endsWith(".js")) { PluginManager.installPluginFromLocalFile(url, { notCheckVersion: Config.getConfig( "basic.notCheckPluginVersion", ), }) .then(res => { if (res.success) { Toast.success(`插件「${res.pluginName}」安装成功~`); } else { Toast.warn("安装失败: " + res.message); } }) .catch(e => { console.log(e); Toast.warn(e?.message ?? "无法识别此插件"); }); } else if (supportLocalMediaType.some(it => url.endsWith(it))) { // 本地播放 const musicItem = await PluginManager.getByHash( localPluginHash, )?.instance?.importMusicItem?.(url); console.log(musicItem); if (musicItem) { TrackPlayer.play(musicItem); } } } catch { } } // 开启监听 Linking.addEventListener("url", data => { if (data.url) { handleLinkingUrl(data.url); } }); const initUrl = await Linking.getInitialURL(); if (initUrl) { handleLinkingUrl(initUrl); } if (Config.getConfig("basic.autoPlayWhenAppStart")) { TrackPlayer.play(); } } function bindEvents() { // 下载事件 downloader.on(DownloaderEvent.DownloadError, (reason) => { if (reason === DownloadFailReason.NetworkOffline) { Toast.warn("当前无网络连接,请等待网络恢复后重试"); } else if (reason === DownloadFailReason.NotAllowToDownloadInCellular) { if (getCurrentDialog()?.name !== "SimpleDialog") { showDialog("SimpleDialog", { title: "流量提醒", content: "当前非WIFI环境,为节省流量,请到侧边栏设置中打开【使用移动网络下载】功能后方可继续下载", }); } } }); downloader.on(DownloaderEvent.DownloadQueueCompleted, () => { Toast.success("下载任务已完成"); }); } export default async function () { try { getDefaultStore().set(bootstrapAtom, { "state": "Loading", }); await bootstrapImpl(); bindEvents(); getDefaultStore().set(bootstrapAtom, { "state": "Done", }); } catch (e: any) { errorLog("初始化出错", e); if (getDefaultStore().get(bootstrapAtom).state === "Loading") { getDefaultStore().set(bootstrapAtom, { state: "Fatal", reason: e, }); } } // 隐藏开屏动画 console.log("HIDE"); await SplashScreen.hideAsync(); } ================================================ FILE: src/entry/index.tsx ================================================ import React from "react"; import { NavigationContainer } from "@react-navigation/native"; import { createNativeStackNavigator } from "@react-navigation/native-stack"; import bootstrap from "./bootstrap/bootstrap"; import { GestureHandlerRootView } from "react-native-gesture-handler"; import Dialogs from "@/components/dialogs"; import Panels from "@/components/panels"; import PageBackground from "@/components/base/pageBackground"; import { SafeAreaProvider } from "react-native-safe-area-context"; import Debug from "@/components/debug"; import { PortalHost } from "@/components/base/portal"; import globalStyle from "@/constants/globalStyle"; import Theme from "@/core/theme"; import { BootstrapComponent } from "./bootstrap/BootstrapComponent"; import { ToastBaseComponent } from "@/components/base/toast"; import { StatusBar } from "react-native"; import { ReduceMotion, ReducedMotionConfig } from "react-native-reanimated"; import { routes } from "@/core/router/routes.tsx"; import ErrorBoundary from "@/components/errorBoundary"; /** * 字体颜色 */ StatusBar.setBackgroundColor("transparent"); StatusBar.setTranslucent(true); bootstrap(); const Stack = createNativeStackNavigator(); export default function Pages() { const theme = Theme.useTheme(); return ( {routes.map(route => ( ))} ); } ================================================ FILE: src/hooks/useCheckUpdate.ts ================================================ import { showDialog } from "@/components/dialogs/useDialog"; import PersistStatus from "@/utils/persistStatus"; import checkUpdate from "@/utils/checkUpdate"; import Toast from "@/utils/toast"; import { compare } from "compare-versions"; import { useEffect } from "react"; import i18n from "@/core/i18n"; export const checkUpdateAndShowResult = ( showToast = false, checkSkip = false, ) => { checkUpdate().then(updateInfo => { if (updateInfo?.needUpdate) { const { data } = updateInfo; const skipVersion = PersistStatus.get("app.skipVersion"); console.log(skipVersion, data); if ( checkSkip && skipVersion && compare(skipVersion, data.version, ">=") ) { return; } showDialog("DownloadDialog", { version: data.version, content: data.changeLog, fromUrl: data.download[0], backUrl: data.download[1], }); } else { if (showToast) { Toast.success(i18n.t("checkUpdate.error.latestVersion")); } } }); }; export default function (callOnMount = true) { useEffect(() => { if (callOnMount) { checkUpdateAndShowResult(false, true); } }, []); return checkUpdateAndShowResult; } ================================================ FILE: src/hooks/useColors.ts ================================================ import { Theme, useTheme } from "@react-navigation/native"; import Color from "color"; import { useMemo } from "react"; type IColors = Theme["colors"]; export interface CustomizedColors extends IColors { /** 普通文字 */ text: string; /** 副标题文字颜色 */ textSecondary?: string; /** 高亮文本颜色,也就是主色调 */ textHighlight?: string; /** 页面背景 */ pageBackground?: string; /** 阴影 */ shadow?: string; /** 标题栏颜色 */ appBar?: string; /** 标题栏字体颜色 */ appBarText?: string; /** 音乐栏颜色 */ musicBar?: string; /** 音乐栏字体颜色 */ musicBarText?: string; /** 分割线 */ divider?: string; /** 高亮颜色 */ listActive?: string; /** 输入框背景色 */ placeholder?: string; /** 弹窗、浮层、菜单背景色 */ backdrop?: string; /** 卡片背景色 */ card: string; /** paneltabbar 背景色 */ tabBar?: string; } export default function useColors() { const { colors } = useTheme(); const cColors: CustomizedColors = useMemo(() => { return { ...colors, textSecondary: Color(colors.text).alpha(0.7).toString(), // @ts-ignore background: colors.pageBackground ?? colors.background, }; }, [colors]); return cColors; } ================================================ FILE: src/hooks/useDelayFalsy.ts ================================================ import { useRef, useState } from "react"; export default function useDelayFalsy( init?: T, ms: number = 0, ) { const [_state, _setState] = useState(init); const timer = useRef(); function setState(st: T) { if (st === undefined || st === null || st === false) { timer.current && clearTimeout(timer.current); timer.current = setTimeout(() => { _setState(st); timer.current = undefined; }, ms); return; } timer.current && clearTimeout(timer.current); timer.current = undefined; _setState(st); } return [_state, setState, _setState] as [ ...ReturnType>, ReturnType>[1], ]; } ================================================ FILE: src/hooks/useHardwareBack.ts ================================================ import { useEffect, useRef } from "react"; import { BackHandler, NativeEventSubscription } from "react-native"; export default function ( onHardwareBackPress: () => boolean | null | undefined, deps: any[] = [], ) { const backHandlerRef = useRef(); useEffect(() => { if (backHandlerRef.current) { backHandlerRef.current.remove(); backHandlerRef.current = undefined; } backHandlerRef.current = BackHandler.addEventListener( "hardwareBackPress", onHardwareBackPress, ); return () => { if (backHandlerRef.current) { backHandlerRef.current.remove(); backHandlerRef.current = undefined; } }; }, deps); } ================================================ FILE: src/hooks/useLogRerender.ts ================================================ import { useEffect, useRef } from "react"; export default function (msg?: string, deps: any[] = []) { const idRef = useRef(); useEffect(() => { idRef.current = Math.random(); console.log("Mount", msg ?? "", idRef.current); return () => { console.log("Unmount", msg ?? "", idRef.current); }; }, []); useEffect(() => { if (deps?.length !== 0) { console.log("State Change", msg ?? "", idRef.current); } }, deps); useEffect(() => { idRef.current && console.log("Rerender: ", msg ?? "", idRef.current); }); } ================================================ FILE: src/hooks/useMounted.ts ================================================ import { useCallback, useEffect, useRef, useState } from "react"; export function useOnMounted() { const onMounted = useRef(false); const [isLoading, setLoading] = useState(true); useEffect(() => { onMounted.current = true; setTimeout(() => { setLoading(false); }); return () => { onMounted.current = false; }; }, []); return { onMounted: useCallback(() => onMounted.current, []), isLoading }; } ================================================ FILE: src/hooks/useOnceEffect.ts ================================================ import { useEffect, useRef } from "react"; export default function useOnceEffect( cb: () => (() => void) | void, deps?: any[], ) { const flag = useRef(false); useEffect(() => { let result; if (flag.current) { return result; } if (!deps || deps.every(_ => !!_)) { flag.current = true; result = cb(); } return result; }, deps); } ================================================ FILE: src/hooks/useOrientation.ts ================================================ import { atom, useAtomValue, useSetAtom } from "jotai"; import { useEffect } from "react"; import { Dimensions } from "react-native"; const orientationAtom = atom<"vertical" | "horizontal">("vertical"); export function useListenOrientationChange() { const setOrientationAtom = useSetAtom(orientationAtom); useEffect(() => { const windowSize = Dimensions.get("window"); const { width, height } = windowSize; if (width < height) { setOrientationAtom("vertical"); } else { setOrientationAtom("horizontal"); } const subscription = Dimensions.addEventListener("change", e => { if (e.window.width < e.window.height) { setOrientationAtom("vertical"); } else { setOrientationAtom("horizontal"); } }); return () => { subscription?.remove(); }; }, []); } export default function useOrientation() { return useAtomValue(orientationAtom); } ================================================ FILE: src/hooks/usePrimaryColor.ts ================================================ import useColors from "./useColors"; export default function usePrimaryColor() { const colors = useColors(); return colors.primary; } ================================================ FILE: src/hooks/useRerender.ts ================================================ import { useCallback, useState } from "react"; export default function useRerender() { const [, setRerender] = useState(0); const rerender = useCallback(() => { setRerender((prev) => prev + 1); }, []); return rerender; } ================================================ FILE: src/hooks/useTextColor.ts ================================================ import useColors from "./useColors"; export default function useTextColor() { const colors = useColors(); return colors.text; } ================================================ FILE: src/lib/react-native-vdebug/index.js ================================================ /// 魔改自 https://github.com/itenl/react-native-vdebug import PropTypes from 'prop-types'; import React, {PureComponent} from 'react'; import { Animated, Dimensions, Keyboard, KeyboardAvoidingView, NativeModules, PanResponder, Platform, ScrollView, StyleSheet, Text, TextInput, TouchableOpacity, View, } from 'react-native'; import event from './src/event'; // import Network, { traceNetwork } from './src/network'; import Log, {traceLog} from './src/log'; import HocComp from './src/hoc'; import Storage from './src/storage'; import {replaceReg} from './src/tool'; const {width, height} = Dimensions.get('window'); let commandContext = global; export const setExternalContext = externalContext => { if (externalContext) commandContext = externalContext; }; // Log/network trace when Element is not initialized. export const initTrace = () => { traceLog(); // traceNetwork(); }; class VDebug extends PureComponent { static propTypes = { // Expansion panel (Optional) panels: PropTypes.array, }; static defaultProps = { panels: null, }; constructor(props) { super(props); initTrace(); this.containerHeight = (height / 3) * 2; this.refsObj = {}; this.state = { commandValue: '', showPanel: false, currentPageIndex: 0, pan: new Animated.ValueXY(), scale: new Animated.Value(1), panelHeight: new Animated.Value(0), panels: this.addPanels(), history: [], historyFilter: [], showHistory: false, }; this.panResponder = PanResponder.create({ onStartShouldSetPanResponder: () => true, onPanResponderGrant: () => { this.state.pan.setOffset({ x: this.state.pan.x._value, y: this.state.pan.y._value, }); this.state.pan.setValue({x: 0, y: 0}); Animated.spring(this.state.scale, { useNativeDriver: true, toValue: 1.3, friction: 7, }).start(); }, onPanResponderMove: Animated.event([ null, {dx: this.state.pan.x, dy: this.state.pan.y}, ]), onPanResponderRelease: ({nativeEvent}, gestureState) => { if ( Math.abs(gestureState.dx) < 5 && Math.abs(gestureState.dy) < 5 ) this.togglePanel(); setTimeout(() => { Animated.spring(this.state.scale, { useNativeDriver: true, toValue: 1, friction: 7, }).start(() => { this.setState({ top: nativeEvent.pageY, }); }); this.state.pan.flattenOffset(); }, 0); }, }); } componentDidMount() { this.state.pan.setValue({x: 0, y: 0}); Storage.support() && Storage.get('react-native-vdebug@history').then(res => { if (res) { this.setState({ history: res, }); } }); } getRef(index) { return ref => { if (!this.refsObj[index]) this.refsObj[index] = ref; }; } addPanels() { let defaultPanels = [ { title: 'Log', component: HocComp(Log, this.getRef(0)), }, // { // title: 'Network', // component: HocComp(Network, this.getRef(1)) // }, ]; if (this.props.panels && this.props.panels.length) { this.props.panels.forEach((item, index) => { // support up to five extended panels if (index >= 3) return; if (item.title && item.component) { item.component = HocComp( item.component, this.getRef(defaultPanels.length), ); defaultPanels.push(item); } }); } return defaultPanels; } togglePanel() { this.state.panelHeight.setValue( this.state.panelHeight._value ? 0 : this.containerHeight, ); } clearLogs() { const tabName = this.state.panels[this.state.currentPageIndex].title; event.trigger('clear', tabName); } showDev() { NativeModules?.DevMenu?.show(); } reloadDev() { NativeModules?.DevMenu?.reload(); } evalInContext(js, context) { return function (str) { let result = ''; try { // eslint-disable-next-line no-eval result = eval(str); } catch (err) { result = 'Invalid input'; } return event.trigger('addLog', result); }.call(context, `with(this) { ${js} } `); } execCommand() { if (!this.state.commandValue) return; this.evalInContext(this.state.commandValue, commandContext); this.syncHistory(); Keyboard.dismiss(); } clearCommand() { this.textInput.clear(); this.setState({ historyFilter: [], }); } scrollToPage(index, animated = true) { this.scrollToCard(index, animated); } scrollToCard(cardIndex, animated = true) { if (cardIndex < 0) cardIndex = 0; else if (cardIndex >= this.cardCount) cardIndex = this.cardCount - 1; if (this.scrollView) { this.scrollView.scrollTo({ x: width * cardIndex, y: 0, animated: animated, }); } } scrollToTop() { const item = this.refsObj[this.state.currentPageIndex]; const instance = item?.getScrollRef && item?.getScrollRef(); if (instance) { // FlatList instance.scrollToOffset && instance.scrollToOffset({ animated: true, viewPosition: 0, index: 0, }); // ScrollView instance.scrollTo && instance.scrollTo({x: 0, y: 0, animated: true}); } } renderPanelHeader() { return ( {this.state.panels.map((item, index) => ( { if (index != this.state.currentPageIndex) { this.scrollToPage(index); this.setState({currentPageIndex: index}); } else { this.scrollToTop(); } }} style={[ styles.panelHeaderItem, index === this.state.currentPageIndex && styles.activeTab, ]}> {item.title} ))} ); } syncHistory() { if (!Storage.support()) return; const res = this.state.history.filter(f => { return f == this.state.commandValue; }); if (res && res.length) return; this.state.history.splice(0, 0, this.state.commandValue); this.state.historyFilter.splice(0, 0, this.state.commandValue); this.setState( { history: this.state.history, historyFilter: this.state.historyFilter, }, () => { Storage.save('react-native-vdebug@history', this.state.history); this.forceUpdate(); }, ); } onChange(text) { const state = {commandValue: text}; if (text) { const res = this.state.history.filter(f => f.toLowerCase().match(replaceReg(text)), ); if (res && res.length) state.historyFilter = res; } else { state.historyFilter = []; } this.setState(state); } renderCommandBar() { return ( {this.state.historyFilter.map(text => { return ( { if (text && text.toString) { this.setState({ commandValue: text.toString(), }); } }}> {text} ); })} { this.textInput = ref; }} style={styles.commandBarInput} placeholderTextColor={'#000000a1'} placeholder="Command..." onChangeText={this.onChange.bind(this)} value={this.state.commandValue} onFocus={() => { this.setState({showHistory: true}); }} onSubmitEditing={this.execCommand.bind(this)} /> X OK ); } renderPanelFooter() { return ( Clear {__DEV__ && Platform.OS == 'ios' && ( Dev )} Hide ); } onScrollAnimationEnd({nativeEvent}) { const currentPageIndex = Math.floor( nativeEvent.contentOffset.x / Math.floor(width), ); currentPageIndex != this.state.currentPageIndex && this.setState({ currentPageIndex: currentPageIndex, }); } renderPanel() { return ( {this.renderPanelHeader()} { this.scrollView = ref; }} pagingEnabled={true} showsHorizontalScrollIndicator={false} horizontal={true} style={styles.panelContent}> {this.state.panels.map((item, index) => { return ( ); })} {this.renderCommandBar()} {this.renderPanelFooter()} ); } renderDebugBtn() { const {pan, scale} = this.state; const [translateX, translateY] = [pan.x, pan.y]; const btnStyle = {transform: [{translateX}, {translateY}, {scale}]}; return ( 调试 ); } render() { return ( {this.renderPanel()} {this.renderDebugBtn()} ); } } const styles = StyleSheet.create({ activeTab: { backgroundColor: '#fff', }, panel: { position: 'absolute', zIndex: 99998, elevation: 99998, backgroundColor: '#fff', width, bottom: 0, right: 0, }, panelHeader: { width, backgroundColor: '#eee', flexDirection: 'row', borderWidth: StyleSheet.hairlineWidth, borderColor: '#d9d9d9', }, panelHeaderItem: { flex: 1, height: 40, color: '#000', borderRightWidth: StyleSheet.hairlineWidth, borderColor: '#d9d9d9', justifyContent: 'center', }, panelHeaderItemText: { textAlign: 'center', }, panelContent: { width, flex: 0.9, }, panelBottom: { width, borderWidth: StyleSheet.hairlineWidth, borderColor: '#d9d9d9', flexDirection: 'row', alignItems: 'center', backgroundColor: '#eee', height: 40, }, panelBottomBtn: { flex: 1, height: 40, borderRightWidth: StyleSheet.hairlineWidth, borderColor: '#d9d9d9', justifyContent: 'center', }, panelBottomBtnText: { color: '#000', fontSize: 14, textAlign: 'center', }, panelEmpty: { flex: 1, alignItems: 'center', justifyContent: 'center', }, homeBtn: { width: 60, paddingVertical: 5, backgroundColor: '#04be02', borderRadius: 4, alignItems: 'center', justifyContent: 'center', position: 'absolute', zIndex: 99999, bottom: height / 2, right: 0, shadowColor: 'rgb(18,34,74)', shadowOffset: {width: 0, height: 1}, shadowOpacity: 0.08, elevation: 99999, }, homeBtnText: { color: '#fff', }, commandBar: { borderWidth: StyleSheet.hairlineWidth, borderColor: '#d9d9d9', flexDirection: 'row', height: 40, }, commandBarInput: { flex: 1, paddingLeft: 10, backgroundColor: '#ffffff', color: '#000000', }, commandBarBtn: { width: 40, alignItems: 'center', justifyContent: 'center', backgroundColor: '#eee', }, historyContainer: { borderTopWidth: 1, borderTopColor: '#d9d9d9', backgroundColor: '#ffffff', paddingHorizontal: 10, }, }); export default VDebug; ================================================ FILE: src/lib/react-native-vdebug/src/event.js ================================================ export default class Event { constructor() { this.eventList = {}; } on(eventName, callback) { if (!this.eventList[eventName]) { this.eventList[eventName] = []; } this.eventList[eventName].push(callback); return this; } trigger(...args) { const key = Array.prototype.shift.call(args); const fns = this.eventList[key]; if (!fns || fns.length === 0) { return this; } for (let i = 0, fn; (fn = fns[i++]); ) { fn.apply(this, args); } return this; } off(key, fn) { const fns = this.eventList[key]; if (!fns) { return this; } if (!fn) { if (fns) { fns.length = 0; } } else { for (let i = fns.length - 1; i >= 0; i--) { const _fn = fns[i]; if (_fn === fn) { fns.splice(i, 1); } } } return this; } } let event; module.exports = (function () { if (!event) { event = new Event(); } return event; })(); ================================================ FILE: src/lib/react-native-vdebug/src/hoc.js ================================================ import React, {PureComponent} from 'react'; export default (WrappedComponent, getRef = () => {}) => { return class Hoc extends PureComponent { constructor(props) { super(props); } render() { return ( { this.comp = comp; getRef && getRef(comp); }} {...this.props} /> ); } }; }; ================================================ FILE: src/lib/react-native-vdebug/src/log.js ================================================ import React, {Component} from 'react'; import { Alert, FlatList, StyleSheet, Text, TextInput, TouchableOpacity, TouchableWithoutFeedback, View, } from 'react-native'; import event from './event'; import {debounce} from './tool'; const LEVEL_ENUM = { All: '', Log: 'log', Info: 'info', Warn: 'warn', Error: 'error', }; let logStack = null; class LogStack { constructor() { this.logs = []; this.maxLength = 200; this.listeners = []; this.notify = debounce(10, false, this.notify); } getLogs() { return this.logs; } addLog(method, data) { if (this.logs.length > this.maxLength) { this.logs.splice(this.logs.length - 1, 1); } const date = new Date(); this.logs.splice(0, 0, { index: this.logs.length + 1, method, data: strLog(data), time: `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}:${date.getMilliseconds()}`, id: unixId(), }); this.notify(); } clearLogs() { this.logs = []; this.notify(); } notify() { this.listeners.forEach(callback => { callback(); }); } attach(callback) { this.listeners.push(callback); } } class Log extends Component { constructor(props) { super(props); this.name = 'Log'; this.mountState = false; this.state = { logs: [], filterLevel: '', // filterValue: '' }; logStack.attach(() => { if (this.mountState) { const logs = logStack.getLogs(); this.setState({ logs, }); } }); } getScrollRef() { return this.flatList; } componentDidMount() { this.mountState = true; this.setState({ logs: logStack.getLogs(), }); // 类方法用bind会指向不同地址,导致off失败 event.on('clear', this.clearLogs); event.on('addLog', this.addLog); } componentWillUnmount() { this.mountState = false; event.off('clear', this.clearLogs); event.off('addLog', this.addLog); } addLog = msg => { logStack.addLog('log', [msg]); }; clearLogs = name => { if (name === this.name) { logStack.clearLogs(); } }; ListHeaderComponent() { return ( Index Method {Object.keys(LEVEL_ENUM).map((key, index) => { return ( { this.setState({ filterLevel: LEVEL_ENUM[key], }); }} style={[ styles.headerBtnLevel, this.state.filterLevel == LEVEL_ENUM[key] && { backgroundColor: '#eeeeee', borderColor: '#959595a1', borderWidth: 1, }, ]}> {key} ); })} { this.textInput = ref; }} style={styles.filterValueBarInput} placeholderTextColor={'#000000a1'} placeholder="输入过滤条件..." onSubmitEditing={({nativeEvent}) => { if (nativeEvent) { this.regInstance = new RegExp( nativeEvent.text, 'ig', ); this.setState({filterValue: nativeEvent.text}); } }} /> X ); } clearFilterValue() { this.setState( { filterValue: '', }, () => { this.textInput.clear(); }, ); } renderItem({item}) { if (this.state.filterLevel && this.state.filterLevel != item.method) return null; if ( this.state.filterValue && this.regInstance && !this.regInstance.test(item.data) ) return null; return ( { try { Alert.alert('提示', '复制成功', [{text: '确认'}]); } catch (error) {} }}> {item.index} {item.method} {item.time} {item.data} ); } render() { return ( { this.flatList = ref; }} legacyImplementation // initialNumToRender={20} showsVerticalScrollIndicator extraData={this.state} data={this.state.logs} stickyHeaderIndices={[0]} ListHeaderComponent={this.ListHeaderComponent.bind(this)} renderItem={this.renderItem.bind(this)} ListEmptyComponent={() => Loading...} keyExtractor={item => item.id} /> ); } } const styles = StyleSheet.create({ log: { color: '#000', }, info: { color: '#000', }, warn: { color: 'orange', backgroundColor: '#fffacd', borderColor: '#ffb930', }, error: { color: '#dc143c', backgroundColor: '#ffe4e1', borderColor: '#f4a0ab', }, logItem: { borderBottomWidth: StyleSheet.hairlineWidth, borderColor: '#eee', }, logItemText: { fontSize: 12, paddingHorizontal: 10, paddingVertical: 8, }, logItemTime: { marginLeft: 5, fontSize: 11, fontWeight: '700', }, filterValueBarBtn: { width: 40, alignItems: 'center', justifyContent: 'center', backgroundColor: '#eee', }, filterValueBarInput: { flex: 1, paddingLeft: 10, backgroundColor: '#ffffff', color: '#000000', }, filterValueBar: { flexDirection: 'row', height: 40, borderWidth: 1, borderColor: '#eee', }, headerText: { flex: 0.8, borderColor: '#eee', borderWidth: StyleSheet.hairlineWidth, paddingVertical: 4, paddingHorizontal: 2, fontWeight: '700', }, headerBtnLevel: { flex: 1, borderColor: '#eee', borderWidth: StyleSheet.hairlineWidth, paddingHorizontal: 2, }, headerTextLevel: { fontWeight: '700', textAlign: 'center', }, }); function unixId() { return Math.round(Math.random() * 1000000).toString(16); } function strLog(logs) { const arr = logs.map(data => formatLog(data)); return arr.join(' '); } function formatLog(obj) { if ( obj === null || obj === undefined || typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || typeof obj === 'function' ) { return `"${String(obj)}"`; } if (obj instanceof Date) { return `Date(${obj.toISOString()})`; } if (Array.isArray(obj)) { return `Array(${obj.length})[${obj.map(elem => formatLog(elem))}]`; } if (obj.toString) { try { return `object(${JSON.stringify(obj, null, 2)})`; } catch (err) { return 'Invalid symbol'; } } return 'unknown data'; } export default Log; export const traceLog = () => { if (!logStack) { logStack = new LogStack(); } }; export const addLog = (level, ...args) => { logStack.addLog(level, args); }; ================================================ FILE: src/lib/react-native-vdebug/src/network.js ================================================ import React, {Component} from 'react'; import {Clipboard, FlatList, StyleSheet, Text, TextInput, TouchableOpacity, View,} from 'react-native'; import event from './event'; import {debounce} from './tool'; let ajaxStack = null; class AjaxStack { constructor() { this.requestIds = []; this.requests = {}; this.maxLength = 200; this.listeners = []; this.notify = debounce(10, false, this.notify); } getRequestIds() { return this.requestIds; } getRequests() { return this.requests; } getRequest(id) { return this.requests[id] || {}; } readBlobAsText(blob, encoding = 'utf-8') { return new Promise((resolve, reject) => { resolve('undefined'); // const fr = new FileReader(); // fr.onload = event => { // resolve(fr.result); // }; // fr.onerror = err => { // reject(err); // }; // fr.readAsText(blob, encoding); }); } JSONTryParse(jsonStr) { try { return JSON.parse(jsonStr); } catch (error) { return {}; } } formatResponse(response) { if (response) { if (typeof response === 'string') response = this.JSONTryParse(response); return JSON.stringify(response, null, 2); } else { return '{}'; } } updateRequest(id, data) { // update item const item = this.requests[id] || {}; if (this.requestIds.length > this.maxLength) { const _id = this.requestIds[this.requestIds.length - 1]; this.requestIds.splice(this.requestIds.length - 1, 1); this.requests[id] && delete this.requests[_id]; } for (const key in data) { item[key] = data[key]; } // update dom const domData = { id, index: item.index ?? this.requestIds.length + 1, host: item.host, url: item.url, status: item.status, method: item.method || '-', costTime: item.costTime > 0 ? `${item.costTime} ms` : '-', resHeaders: item.resHeaders || null, reqHeaders: item.reqHeaders || null, getData: item.getData || null, postData: item.postData || null, response: null, actived: !!item.actived, startTime: item.startTime, endTime: item.endTime, }; switch (item.responseType) { case '': case 'text': // try to parse JSON if (typeof item.response === 'string') { try { domData.response = this.formatResponse(item.response); } catch (e) { // not a JSON string domData.response = item.response; } } else if (typeof item.response !== 'undefined') { domData.response = Object.prototype.toString.call( item.response, ); } break; case 'json': if (typeof item.response !== 'undefined') { domData.response = this.formatResponse(item.response); } break; case 'blob': case 'document': case 'arraybuffer': default: if (item.response && typeof item.response !== 'undefined') { this.readBlobAsText(item.response).then(res => { domData.response = this.formatResponse(res); }); } break; } if (item.readyState === 0 || item.readyState === 1) { domData.status = 'Pending'; } else if (item.readyState === 2 || item.readyState === 3) { domData.status = 'Loading'; } else if (item.readyState === 4) { // do nothing } else { domData.status = 'Unknown'; } if (this.requestIds.indexOf(id) === -1) { this.requestIds.splice(0, 0, id); } this.requests[id] = domData; this.notify(this.requests[id]); } clearRequests() { this.requestIds = []; this.requests = {}; this.notify(); } notify(args) { this.listeners.forEach(callback => { callback(args); }); } attach(callback) { this.listeners.push(callback); } } class Network extends Component { constructor(props) { super(props); this.name = 'Network'; this.mountState = false; this.state = { showingId: null, requestIds: [], requests: {}, filterValue: '', }; ajaxStack.attach(currentRequest => { if (this.mountState) { this.setState({ requestIds: ajaxStack.getRequestIds(), requests: ajaxStack.getRequests(), }); } }); } getScrollRef() { return this.flatList; } componentDidMount() { this.mountState = true; this.setState({ requestIds: ajaxStack.getRequestIds(), requests: ajaxStack.getRequests(), }); event.on('clear', this.clearRequests.bind(this)); } componentWillUnmount() { this.mountState = false; event.off('clear', this.clearRequests.bind(this)); } clearRequests(name) { if (name === this.name) { ajaxStack.clearRequests(); } } ListHeaderComponent() { const count = Object.keys(this.state.requests).length || 0; return ( ({count})Host Method Status Time/Retry { this.textInput = ref; }} style={styles.filterValueBarInput} placeholderTextColor={'#000000a1'} placeholder="输入过滤条件..." onSubmitEditing={({nativeEvent}) => { if (nativeEvent) { this.regInstance = new RegExp( nativeEvent.text, 'ig', ); this.setState({filterValue: nativeEvent.text}); } }} /> X ); } clearFilterValue() { this.setState( { filterValue: '', }, () => { this.textInput.clear(); }, ); } copy2cURL(item) { let headerStr = ''; if (item.reqHeaders) { Object.keys(item.reqHeaders).forEach(key => { let reqHeaders = item.reqHeaders[key]; if (reqHeaders) { headerStr += ` -H '${key}: ${reqHeaders}'`; } }); } let cURL = `curl -X ${item.method} '${item.url}' ${headerStr}`; if (item.method === 'POST' && item.postData) cURL += ` --data-binary '${item.postData}'`; Clipboard.setString(cURL); } retryFetch(item) { let options = { method: item.method, }; if (item.reqHeaders) options.headers = item.reqHeaders; if (item.method == 'POST' && item.postData) options.body = item.postData; fetch(item.url, options); } renderItem({item}) { const _item = this.state.requests[item] || {}; if ( this.state.filterValue && this.regInstance && !this.regInstance.test(_item.url) ) return null; return ( { this.setState(state => ({ showingId: state.showingId === _item.id ? null : _item.id, })); }}> = 400 && styles.error, ]}> {`(${_item.index})${_item.host}`} {_item.method} {_item.status} { this.retryFetch(_item); }} style={[ styles.nwHeaderTitle, { width: 90, borderRadius: 20, borderColor: '#eeeeee', borderWidth: 1, }, ]}> {_item.costTime} {this.state.showingId === _item.id && ( Operate { this.copy2cURL(_item); }}> {'[ Copy cURL to clipboard ]'} { Clipboard.setString(_item.response); }}> {'[ Copy response to clipboard ]'} General URL: {_item.url} startTime: {_item.startTime} endTime: {_item.endTime} {_item.reqHeaders && ( Request Header {Object.keys(_item.reqHeaders).map(key => ( {key}: {_item.reqHeaders[key]} ))} )} {_item.resHeaders && ( Response Header {Object.keys(_item.resHeaders).map(key => ( {key}: {_item.resHeaders[key]} ))} )} {_item.getData && ( Query String Parameters {Object.keys(_item.getData).map(key => ( {key}: {_item.getData[key]} ))} )} {_item.postData && ( Form Data {_item.postData} )} Response {_item.response || ''} )} ); } render() { return ( { this.flatList = ref; }} showsVerticalScrollIndicator={true} ListHeaderComponent={this.ListHeaderComponent.bind(this)} extraData={this.state} data={this.state.requestIds} stickyHeaderIndices={[0]} renderItem={this.renderItem.bind(this)} ListEmptyComponent={() => Loading...} keyExtractor={item => item} /> ); } } const styles = StyleSheet.create({ bold: { fontWeight: '700', }, active: { backgroundColor: '#fffacd', }, flex3: { flex: 3, }, flex1: { flex: 1, }, error: { backgroundColor: '#ffe4e1', borderColor: '#ffb930', }, nwHeader: { flexDirection: 'row', backgroundColor: '#fff', }, nwHeaderTitle: { borderColor: '#eee', borderWidth: StyleSheet.hairlineWidth, paddingVertical: 4, paddingHorizontal: 2, }, nwItem: {}, nwItemDetail: { borderColor: '#eee', borderLeftWidth: StyleSheet.hairlineWidth, }, nwItemDetailHeader: { paddingLeft: 5, paddingVertical: 4, backgroundColor: '#eee', }, nwDetailItem: { paddingLeft: 5, flexDirection: 'row', }, filterValueBarBtn: { width: 40, alignItems: 'center', justifyContent: 'center', backgroundColor: '#eee', }, filterValueBarInput: { flex: 1, paddingLeft: 10, backgroundColor: '#ffffff', color: '#000000', }, filterValueBar: { flexDirection: 'row', height: 40, borderWidth: 1, borderColor: '#eee', }, }); function unixId() { return Math.round(Math.random() * 1000000).toString(16); } function proxyAjax(XHR, stack) { if (!XHR) { return; } const _open = XHR.prototype.open; const _send = XHR.prototype.send; this._open = _open; this._send = _send; // mock open() XHR.prototype.open = function (...args) { const XMLReq = this; const method = args[0]; const url = args[1]; const id = unixId(); let timer = null; // may be used by other functions XMLReq._requestID = id; XMLReq._method = method; XMLReq._url = url; // mock onreadystatechange const _onreadystatechange = XMLReq.onreadystatechange || function () {}; const onreadystatechange = function () { const item = stack.getRequest(id); // update status item.readyState = XMLReq.readyState; item.status = 0; if (XMLReq.readyState > 1) { item.status = XMLReq.status; } item.responseType = XMLReq.responseType; if (XMLReq.readyState === 0) { // UNSENT if (!item.startTime) { item.startTime = +new Date(); } } else if (XMLReq.readyState === 1) { // OPENED if (!item.startTime) { item.startTime = +new Date(); } } else if (XMLReq.readyState === 2) { // HEADERS_RECEIVED item.resHeaders = {}; const resHeaders = XMLReq.getAllResponseHeaders() || ''; const resHeadersArr = resHeaders.split('\n'); // extract plain text to key-value format for (let i = 0; i < resHeadersArr.length; i++) { const line = resHeadersArr[i]; if (!line) { // eslint-disable-next-line no-continue continue; } const arr = line.split(': '); const key = arr[0]; const value = arr.slice(1).join(': '); item.resHeaders[key] = value; } } else if (XMLReq.readyState === 3) { // LOADING } else if (XMLReq.readyState === 4) { // DONE clearInterval(timer); item.endTime = +new Date(); item.costTime = item.endTime - (item.startTime || item.endTime); item.response = XMLReq.response; } else { clearInterval(timer); } if (!XMLReq._noVConsole) { stack.updateRequest(id, item); } return _onreadystatechange.apply(XMLReq, args); }; XMLReq.onreadystatechange = onreadystatechange; // some 3rd libraries will change XHR's default function // so we use a timer to avoid lost tracking of readyState let preState = -1; timer = setInterval(() => { if (preState !== XMLReq.readyState) { preState = XMLReq.readyState; onreadystatechange.call(XMLReq); } }, 10); return _open.apply(XMLReq, args); }; // mock send() XHR.prototype.send = function (...args) { const XMLReq = this; const data = args[0]; const item = stack.getRequest(XMLReq._requestID); item.method = XMLReq._method.toUpperCase(); let query = XMLReq._url.split('?'); // a.php?b=c&d=?e => ['a.php', 'b=c&d=', '?e'] item.url = XMLReq._url; item.host = query[0]; if (query.length == 2) { item.getData = {}; query = query[1].split('&'); // => ['b=c', 'd=?e'] for (let q of query) { q = q.split('='); item.getData[q[0]] = decodeURIComponent(q[1]); } } item.reqHeaders = XMLReq._headers; if (item.method === 'POST' && data) { // save POST data if (typeof data === 'string') { item.postData = data; } else { try { item.postData = JSON.stringify(data); } catch (error) {} } } if (!XMLReq._noVConsole) { stack.updateRequest(XMLReq._requestID, item); } return _send.apply(XMLReq, args); }; } export default Network; export const traceNetwork = () => { if (!ajaxStack) { ajaxStack = new AjaxStack(); proxyAjax( global.originalXMLHttpRequest || global.XMLHttpRequest, ajaxStack, ); } }; ================================================ FILE: src/lib/react-native-vdebug/src/storage.js ================================================ const storage = { support: function () { return false; }, }; export default storage; ================================================ FILE: src/lib/react-native-vdebug/src/tool.js ================================================ function throttle(delay, noTrailing, callback, debounceMode) { let timeoutID; let lastExec = 0; if (typeof noTrailing !== 'boolean') { debounceMode = callback; callback = noTrailing; noTrailing = undefined; } function wrapper(...args) { const self = this; const elapsed = Number(new Date()) - lastExec; function exec() { lastExec = Number(new Date()); callback.apply(self, args); } function clear() { timeoutID = undefined; } if (debounceMode && !timeoutID) { exec(); } if (timeoutID) { clearTimeout(timeoutID); } if (!debounceMode && elapsed > delay) { exec(); } else if (noTrailing !== true) { timeoutID = setTimeout( debounceMode ? clear : exec, !debounceMode ? delay - elapsed : delay, ); } } return wrapper; } function debounce(delay, atBegin, callback) { return callback === undefined ? throttle(delay, atBegin, false) : throttle(delay, callback, atBegin !== false); } function replaceReg(str) { const regStr = /\\|\$|\(|\)|\*|\+|\.|\[|\]|\?|\^|\{|\}|\|/gi; return str.replace(regStr, function (input) { return `\\${input}`; }); } module.exports = { throttle, debounce, replaceReg, }; ================================================ FILE: src/native/lyricUtil/index.ts ================================================ import Config from "@/core/appConfig"; import Toast from "@/utils/toast"; import { NativeModule, NativeModules } from "react-native"; import { errorLog } from "@/utils/log.ts"; export enum NativeTextAlignment { // 左对齐 LEFT = 3, // 右对齐 RIGHT = 5, // 居中 CENTER = 17, } // 状态栏歌词的工具 interface ILyricUtil extends NativeModule { /** 显示状态栏歌词 */ showStatusBarLyric: ( initLyric?: string, config?: Record, ) => Promise; /** 隐藏状态栏歌词 */ hideStatusBarLyric: () => Promise; /** 设置歌词文本 */ setStatusBarLyricText: (lyric: string) => Promise; /** 设置距离顶部的距离 */ setStatusBarLyricTop: (percent: number) => Promise; /** 设置距离左部的距离 */ setStatusBarLyricLeft: (percent: number) => Promise; /** 设置宽度 */ setStatusBarLyricWidth: (percent: number) => Promise; /** 设置字体 */ setStatusBarLyricFontSize: (fontSize: number) => Promise; /** 设置对齐 */ setStatusBarLyricAlign: (alignment: NativeTextAlignment) => Promise; /** 设置颜色 */ setStatusBarColors: ( textColor: string | null, backgroundColor: string | null, ) => Promise; /** 检查权限 */ checkSystemAlertPermission: () => Promise; /** 请求悬浮窗 */ requestSystemAlertPermission: () => Promise; } const LyricUtil: ILyricUtil = NativeModules.LyricUtil; const originalShowStatusBarLyric = LyricUtil.showStatusBarLyric; const showStatusBarLyric: ILyricUtil["showStatusBarLyric"] = async ( initLyric, config, ) => { try { await originalShowStatusBarLyric(initLyric, config); } catch (e) { errorLog("状态栏歌词开启失败", e); Toast.warn("状态栏歌词开启失败,请到手机系统设置打开悬浮窗权限"); Config.setConfig("lyric.showStatusBarLyric", false); } }; LyricUtil.showStatusBarLyric = showStatusBarLyric; export default LyricUtil; ================================================ FILE: src/native/mp3Util/index.ts ================================================ import { NativeModules } from "react-native"; export interface IBasicMeta { album?: string; artist?: string; author?: string; duration?: string; title?: string; } export interface IWritableMeta extends IBasicMeta { lyric?: string; comment?: string; } interface IMp3Util { getBasicMeta: (fileName: string) => Promise; getMediaMeta: (fileNames: string[]) => Promise; getMediaCoverImg: (mediaPath: string) => Promise; /** 读取内嵌歌词 */ getLyric: (mediaPath: string) => Promise; /** 写入meta信息 */ setMediaTag: (filePath: string, meta: IWritableMeta) => Promise; getMediaTag: (filePath: string) => Promise; } const Mp3Util = NativeModules.Mp3Util; export default Mp3Util as IMp3Util; ================================================ FILE: src/native/utils/index.ts ================================================ import { NativeModule, NativeModules } from "react-native"; interface INativeUtils extends NativeModule { exitApp: () => void; checkStoragePermission: () => Promise; requestStoragePermission: () => void; getWindowDimensions: () => { width: number, height: number }; // Fix bug: https://github.com/facebook/react-native/issues/47080 } const NativeUtils = NativeModules.NativeUtils; export default NativeUtils as INativeUtils; ================================================ FILE: src/pages/albumDetail/hooks/useAlbumMusicList.ts ================================================ import { RequestStateCode } from "@/constants/commonConst"; import PluginManager from "@/core/pluginManager"; import { useCallback, useEffect, useRef, useState } from "react"; export default function useAlbumDetail( originalAlbumItem: IAlbum.IAlbumItem | null, ) { const currentPageRef = useRef(1); const [requestState, setRequestState] = useState(RequestStateCode.IDLE); const [albumItem, setAlbumItem] = useState( originalAlbumItem, ); const [musicList, setMusicList] = useState( originalAlbumItem?.musicList ?? [], ); const getAlbumDetail = useCallback( async function () { // 加载中:直接退出 if (originalAlbumItem === null || requestState === RequestStateCode.FINISHED || requestState === RequestStateCode.PENDING_FIRST_PAGE || requestState === RequestStateCode.PENDING_REST_PAGE) { return; } try { if (currentPageRef.current === 1) { setRequestState(RequestStateCode.PENDING_FIRST_PAGE); } else { setRequestState(RequestStateCode.PENDING_REST_PAGE); } const result = await PluginManager.getByMedia( originalAlbumItem, )?.methods?.getAlbumInfo?.( originalAlbumItem, currentPageRef.current, ); if (!result) { throw new Error(); } if (result?.albumItem) { setAlbumItem(prev => ({ ...(prev ?? {}), ...(result.albumItem as IAlbum.IAlbumItemBase), platform: originalAlbumItem.platform, })); } if (result?.musicList) { setMusicList(prev => { if (currentPageRef.current === 1) { return result?.musicList ?? prev; } else { return [...prev, ...(result.musicList ?? [])]; } }); } if (result.isEnd) { setRequestState(RequestStateCode.FINISHED); } else { setRequestState(RequestStateCode.PARTLY_DONE); } currentPageRef.current += 1; } catch { setRequestState(RequestStateCode.ERROR); } }, [requestState], ); useEffect(() => { getAlbumDetail(); }, []); return [requestState, albumItem, musicList, getAlbumDetail] as const; } ================================================ FILE: src/pages/albumDetail/index.tsx ================================================ import React from "react"; import useAlbumDetail from "./hooks/useAlbumMusicList"; import { useParams } from "@/core/router"; import MusicSheetPage from "@/components/musicSheetPage"; import { useI18N } from "@/core/i18n"; export default function AlbumDetail() { const { albumItem: originalAlbumItem } = useParams<"album-detail">(); const [requestStateCode, albumItem, musicList, getAlbumDetail] = useAlbumDetail(originalAlbumItem); const { t } = useI18N(); return ( ); } ================================================ FILE: src/pages/artistDetail/components/body.tsx ================================================ import React, { useState } from "react"; import { StyleSheet, Text } from "react-native"; import rpx from "@/utils/rpx"; import { SceneMap, TabBar, TabView } from "react-native-tab-view"; import { fontWeightConst } from "@/constants/uiConst"; import ResultList from "./resultList"; import { useAtomValue } from "jotai"; import { queryResultAtom } from "../store/atoms"; import content from "./content"; import useColors from "@/hooks/useColors"; import { useI18N } from "@/core/i18n"; const sceneMap: Record = { album: BodyContentWrapper, music: BodyContentWrapper, }; const routes = [ { key: "music", i18nKey: "common.singleMusic", title: "单曲", }, { key: "album", i18nKey: "common.album", title: "专辑", }, ]; export default function Body() { const [index, setIndex] = useState(0); const colors = useColors(); const { t } = useI18N(); return ( ( null} pressColor="transparent" inactiveColor={colors.text} activeColor={colors.primary} renderLabel={({ route, focused, color }) => ( {t(route.i18nKey as any) ?? route.title} )} /> )} renderScene={SceneMap(sceneMap)} onIndexChange={setIndex} initialLayout={{ width: rpx(750) }} /> ); } export function BodyContentWrapper(props: any) { const tab: IArtist.ArtistMediaType = props.route.key; const queryResult = useAtomValue(queryResultAtom); const Component = content[tab]; const renderItem = ({ item, index }: any) => ( ); return ( ); } const style = StyleSheet.create({ wrapper: { zIndex: 100, }, transparentColor: { backgroundColor: "transparent", shadowColor: "transparent", borderColor: "transparent", }, }); ================================================ FILE: src/pages/artistDetail/components/content/albumContentItem.tsx ================================================ import React from "react"; import AlbumItem from "@/components/mediaItem/albumItem"; interface IAlbumContentProps { item: IAlbum.IAlbumItem; } export default function AlbumContentItem(props: IAlbumContentProps) { const { item } = props; return ; } ================================================ FILE: src/pages/artistDetail/components/content/index.ts ================================================ import AlbumContentItem from "./albumContentItem"; import MusicContentItem from "./musicContentItem"; const content: Record JSX.Element> = { music: MusicContentItem, album: AlbumContentItem, } as const; export default content; ================================================ FILE: src/pages/artistDetail/components/content/musicContentItem.tsx ================================================ import React from "react"; import MusicItem from "@/components/mediaItem/musicItem"; interface IMusicContentProps { item: IMusic.IMusicItem; } export default function MusicContentItem(props: IMusicContentProps) { const { item } = props; return ; } ================================================ FILE: src/pages/artistDetail/components/header.tsx ================================================ import React, { useEffect } from "react"; import { StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import Animated, { useAnimatedStyle, useSharedValue, withTiming, } from "react-native-reanimated"; import { useAtomValue } from "jotai"; import { scrollToTopAtom } from "../store/atoms"; import ThemeText from "@/components/base/themeText"; import Tag from "@/components/base/tag"; import { useParams } from "@/core/router"; import Image from "@/components/base/image"; import { ImgAsset } from "@/constants/assetsConst"; import { useI18N } from "@/core/i18n"; const headerHeight = rpx(350); interface IHeaderProps { neverFold?: boolean; } export default function Header(props: IHeaderProps) { const { neverFold } = props; const { artistItem } = useParams<"artist-detail">(); const heightValue = useSharedValue(headerHeight); const opacityValue = useSharedValue(1); const scrollToTopState = useAtomValue(scrollToTopAtom); const { t } = useI18N(); const heightStyle = useAnimatedStyle(() => { return { height: heightValue.value, opacity: opacityValue.value, }; }); const avatar = artistItem.avatar?.startsWith("//") ? `https:${artistItem.avatar}` : artistItem.avatar; /** 折叠 */ useEffect(() => { if (neverFold) { heightValue.value = withTiming(headerHeight); opacityValue.value = withTiming(1); return; } if (scrollToTopState) { heightValue.value = withTiming(headerHeight); opacityValue.value = withTiming(1); } else { heightValue.value = withTiming(0); opacityValue.value = withTiming(0); } }, [scrollToTopState, neverFold]); return ( {artistItem?.name ?? ""} {artistItem.platform ? ( ) : null} {artistItem.fans ? ( {t("artistDetail.fansCount", { count: artistItem.fans, })} ) : null} {artistItem?.description ?? ""} ); } const styles = StyleSheet.create({ wrapper: { width: rpx(750), height: headerHeight, backgroundColor: "rgba(28, 28, 28, 0.1)", zIndex: 1, }, artist: { width: rpx(144), height: rpx(144), borderRadius: rpx(16), }, headerWrapper: { width: rpx(750), paddingTop: rpx(24), paddingHorizontal: rpx(24), height: rpx(240), flexDirection: "row", alignItems: "center", }, info: { marginLeft: rpx(24), justifyContent: "space-around", height: rpx(144), }, title: { flexDirection: "row", alignItems: "center", }, titleText: { marginRight: rpx(18), maxWidth: rpx(400), }, description: { marginTop: rpx(24), width: rpx(750), paddingHorizontal: rpx(24), }, }); ================================================ FILE: src/pages/artistDetail/components/resultList.tsx ================================================ import ListEmpty from "@/components/base/listEmpty"; import ListFooter from "@/components/base/listFooter"; import { RequestStateCode } from "@/constants/commonConst"; import { useParams } from "@/core/router"; import rpx from "@/utils/rpx"; import { FlashList } from "@shopify/flash-list"; import { useAtom } from "jotai"; import React, { useEffect, useRef, useState } from "react"; import useQueryArtist from "../hooks/useQuery"; import { IQueryResult, scrollToTopAtom } from "../store/atoms"; const ITEM_HEIGHT = rpx(120); interface IResultListProps { tab: T; data: IQueryResult; renderItem: (...args: any) => any; } export default function ResultList(props: IResultListProps) { const { data, renderItem, tab } = props; const [scrollToTopState, setScrollToTopState] = useAtom(scrollToTopAtom); const lastScrollY = useRef(0); const { pluginHash, artistItem } = useParams<"artist-detail">(); const [queryState, setQueryState] = useState( data?.state ?? RequestStateCode.IDLE, ); const queryArtist = useQueryArtist(pluginHash); useEffect(() => { queryState === RequestStateCode.IDLE && queryArtist(artistItem, 1, tab); }, []); useEffect(() => { setQueryState(data?.state ?? RequestStateCode.IDLE); }, [data]); return ( { const currentY = e.nativeEvent.contentOffset.y; if ( !scrollToTopState && currentY < ITEM_HEIGHT * 8 - rpx(350) ) { currentY < lastScrollY.current && setScrollToTopState(true); } else { if (scrollToTopState && currentY > ITEM_HEIGHT * 8) { currentY > lastScrollY.current && setScrollToTopState(false); } } lastScrollY.current = currentY; }} ListEmptyComponent={ { queryArtist(artistItem, 1, tab); }}/>} ListFooterComponent={ data.data?.length ? { queryArtist(artistItem, undefined, tab); }}/> : null } onEndReached={() => { (queryState === RequestStateCode.IDLE || queryState === RequestStateCode.PARTLY_DONE) && queryArtist(artistItem, undefined, tab); }} estimatedItemSize={ITEM_HEIGHT} overScrollMode="always" data={data.data ?? []} renderItem={renderItem} /> ); } ================================================ FILE: src/pages/artistDetail/hooks/useQuery.ts ================================================ import { errorLog } from "@/utils/log"; import { RequestStateCode } from "@/constants/commonConst"; import { produce } from "immer"; import { useAtom } from "jotai"; import { useCallback } from "react"; import { queryResultAtom } from "../store/atoms"; import PluginManager from "@/core/pluginManager"; export default function useQueryArtist(pluginHash: string) { const [queryResults, setQueryResults] = useAtom(queryResultAtom); const queryArtist = useCallback( async ( artist: IArtist.IArtistItem, page?: number, type: IArtist.ArtistMediaType = "music", ) => { const plugin = PluginManager.getByHash(pluginHash); const prevResult = queryResults[type]; if ( prevResult?.state === RequestStateCode.PENDING_FIRST_PAGE || prevResult?.state === RequestStateCode.PENDING_REST_PAGE || prevResult?.state === RequestStateCode.FINISHED ) { return; } page = page ?? ((prevResult.page ?? 0) + 1); try { setQueryResults( produce(draft => { draft[type].state = page === 1 ? RequestStateCode.PENDING_FIRST_PAGE : RequestStateCode.PENDING_REST_PAGE; }), ); const result = await plugin?.methods?.getArtistWorks?.( artist, page, type, ); setQueryResults( produce(draft => { draft[type].page = page; draft[type].state = result?.isEnd === false ? RequestStateCode.PARTLY_DONE : RequestStateCode.FINISHED; if (page === 1) { // 首页 draft[type].data = result?.data ?? []; } else { draft[type].data = (draft[type].data ?? []).concat( result?.data ?? [], ); } }), ); } catch (e) { errorLog("拉取作者信息失败", e); setQueryResults( produce(draft => { draft[type].state = RequestStateCode.ERROR; }), ); } }, [queryResults], ); return queryArtist; } ================================================ FILE: src/pages/artistDetail/index.tsx ================================================ import React, { useEffect } from "react"; import { StyleSheet, View } from "react-native"; import MusicBar from "@/components/musicBar"; import Header from "./components/header"; import Body from "./components/body"; import { useAtom, useSetAtom } from "jotai"; import { initQueryResult, queryResultAtom, scrollToTopAtom } from "./store/atoms"; import { ROUTE_PATH, useNavigate, useParams } from "@/core/router"; import VerticalSafeAreaView from "@/components/base/verticalSafeAreaView"; import globalStyle from "@/constants/globalStyle"; import useOrientation from "@/hooks/useOrientation"; import AppBar from "@/components/base/appBar"; import { useI18N } from "@/core/i18n"; export default function ArtistDetail() { const [queryResult, setQueryResult] = useAtom(queryResultAtom); const { artistItem } = useParams<"artist-detail">(); const setScrollToTopState = useSetAtom(scrollToTopAtom); const navigate = useNavigate(); const orientation = useOrientation(); const { t } = useI18N(); useEffect(() => { return () => { setQueryResult(initQueryResult); setScrollToTopState(true); }; }, []); return ( {t("common.artist")}
); } const style = StyleSheet.create({ horizontal: { flexDirection: "row", flex: 1, }, }); ================================================ FILE: src/pages/artistDetail/store/atoms.ts ================================================ import { RequestStateCode } from "@/constants/commonConst"; import { atom } from "jotai"; export const scrollToTopAtom = atom(true); export interface IQueryResult< T extends IArtist.ArtistMediaType = IArtist.ArtistMediaType, > { state?: RequestStateCode; page?: number; data?: ICommon.SupportMediaItemBase[T]; } type IQueryResults< K extends IArtist.ArtistMediaType = IArtist.ArtistMediaType, > = { [T in K]: IQueryResult; }; export const initQueryResult: IQueryResults = { music: {}, album: {}, }; export const queryResultAtom = atom(initQueryResult); ================================================ FILE: src/pages/downloading/downloadingList.tsx ================================================ import React from "react"; import { StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import ListItem from "@/components/base/listItem"; import { sizeFormatter } from "@/utils/fileUtils"; import { DownloadFailReason, DownloadStatus, useDownloadQueue, useDownloadTask } from "@/core/downloader"; import { FlashList } from "@shopify/flash-list"; import { useI18N } from "@/core/i18n"; interface DownloadingListItemProps { musicItem: IMusic.IMusicItem; } function DownloadingListItem(props: DownloadingListItemProps) { const { musicItem } = props; const taskInfo = useDownloadTask(musicItem); const { t } = useI18N(); const status = taskInfo?.status ?? DownloadStatus.Error; let description = ""; if (status === DownloadStatus.Error) { const reason = taskInfo?.errorReason; if (reason === DownloadFailReason.NoWritePermission) { description = t("downloading.downloadFailReason.noWritePermission"); } else if (reason === DownloadFailReason.FailToFetchSource) { description = t("downloading.downloadFailReason.failToFetchSource"); } else { description = t("downloading.downloadFailReason.unknown"); } } else if (status === DownloadStatus.Completed) { description = t("downloading.downloadStatus.completed"); } else if (status === DownloadStatus.Downloading) { const progress = taskInfo?.downloadedSize ? sizeFormatter(taskInfo.downloadedSize) : "-"; const totalSize = taskInfo?.fileSize ? sizeFormatter(taskInfo.fileSize) : "-"; description = t("downloading.downloadStatus.downloadProgress", { progress, totalSize, }); } else if (status === DownloadStatus.Pending) { description = t("downloading.downloadStatus.pending"); } else if (status === DownloadStatus.Preparing) { description = t("downloading.downloadStatus.preparing"); } return ; } export default function DownloadingList() { const downloadQueue = useDownloadQueue(); return ( `dl${_.platform}.${_.id}`} renderItem={({ item }) => { return ; }} /> ); } const style = StyleSheet.create({ wrapper: { width: rpx(750), flex: 1, }, downloading: { flexGrow: 0, }, }); ================================================ FILE: src/pages/downloading/index.tsx ================================================ import React from "react"; import StatusBar from "@/components/base/statusBar"; import DownloadingList from "./downloadingList"; import MusicBar from "@/components/musicBar"; import VerticalSafeAreaView from "@/components/base/verticalSafeAreaView"; import globalStyle from "@/constants/globalStyle"; import AppBar from "@/components/base/appBar"; import { useI18N } from "@/core/i18n"; export default function Downloading() { const { t } = useI18N(); return ( {t("downloading.title")} ); } ================================================ FILE: src/pages/fileSelector/fileItem.tsx ================================================ import React, { memo } from "react"; import { Pressable, StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import ThemeText from "@/components/base/themeText"; import useTextColor from "@/hooks/useTextColor"; import Checkbox from "@/components/base/checkbox"; import { TouchableOpacity } from "react-native-gesture-handler"; import Icon from "@/components/base/icon.tsx"; import { iconSizeConst } from "@/constants/uiConst.ts"; const ITEM_HEIGHT = rpx(96); interface IProps { type: "folder" | "file"; path: string; parentPath: string; checked?: boolean; onItemPress: (currentChecked?: boolean) => void; onCheckedChange: (checked: boolean) => void; } function FileItem(props: IProps) { const { type, path, parentPath, checked, onItemPress, onCheckedChange: onCheckChange, } = props; const textColor = useTextColor(); // 返回逻辑 return ( { onItemPress(checked); }} style={styles.pathWrapper}> {path.substring( parentPath === "/" ? 1 : parentPath.length + 1, )} { onCheckChange(!checked); }} style={styles.checkIcon}> ); } export default memo( FileItem, (prev, curr) => prev.checked === curr.checked && prev.parentPath === curr.parentPath && prev.path === curr.path, ); const styles = StyleSheet.create({ container: { width: "100%", height: ITEM_HEIGHT, paddingHorizontal: rpx(24), flexDirection: "row", alignItems: "center", justifyContent: "space-between", }, folderIcon: { fontSize: rpx(32), marginRight: rpx(14), }, pathWrapper: { flexDirection: "row", flex: 1, alignItems: "center", height: "100%", marginRight: rpx(60), }, path: { height: "100%", textAlignVertical: "center", }, checkIcon: { padding: rpx(14), }, }); ================================================ FILE: src/pages/fileSelector/index.tsx ================================================ import Empty from "@/components/base/empty"; import IconButton from "@/components/base/iconButton"; import Loading from "@/components/base/loading"; import StatusBar from "@/components/base/statusBar"; import Button from "@/components/base/textButton.tsx"; import ThemeText from "@/components/base/themeText"; import VerticalSafeAreaView from "@/components/base/verticalSafeAreaView"; import globalStyle from "@/constants/globalStyle"; import i18n from "@/core/i18n"; import { useParams } from "@/core/router"; import useColors from "@/hooks/useColors"; import useHardwareBack from "@/hooks/useHardwareBack"; import rpx from "@/utils/rpx"; import { useNavigation } from "@react-navigation/native"; import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Pressable, StyleSheet, View } from "react-native"; import { ExternalStorageDirectoryPath, exists, getAllExternalFilesDirs, readDir, } from "react-native-fs"; import { FlatList } from "react-native-gesture-handler"; import FileItem from "./fileItem"; interface IPathItem { path: string; parent: null | IPathItem; } interface IFileItem { path: string; type: "file" | "folder"; } const ITEM_HEIGHT = rpx(96); export default function FileSelector() { const { fileType = "file-and-folder", multi = true, actionText = i18n.t("common.sure"), matchExtension, onAction, } = useParams<"file-selector">() ?? {}; const [currentPath, setCurrentPath] = useState({ path: "/", parent: null, }); const currentPathRef = useRef(currentPath); const [filesData, setFilesData] = useState([]); const [checkedItems, setCheckedItems] = useState([]); const checkedPaths = useMemo( () => checkedItems.map(_ => _.path), [checkedItems], ); const navigation = useNavigation(); const colors = useColors(); const [loading, setLoading] = useState(false); useEffect(() => { (async () => { // 路径变化时,重新读取 setLoading(true); try { if (currentPath.path === "/") { try { const allExt = await getAllExternalFilesDirs(); if (allExt.length > 1) { const sdCardPaths = allExt.map(sdp => sdp.substring(0, sdp.indexOf("/Android")), ); if ( ( await Promise.all( sdCardPaths.map(_ => exists(_)), ) ).every(val => val) ) { setFilesData( sdCardPaths.map(_ => ({ type: "folder", path: _, })), ); } } else { setCurrentPath({ path: ExternalStorageDirectoryPath, parent: null, }); return; } } catch { setCurrentPath({ path: ExternalStorageDirectoryPath, parent: null, }); return; } } else { const res = (await readDir(currentPath.path)) ?? []; let folders: IFileItem[] = []; let files: IFileItem[] = []; if ( fileType === "folder" || fileType === "file-and-folder" ) { folders = res .filter(_ => _.isDirectory()) .map(_ => ({ type: "folder", path: _.path, })); } if (fileType === "file" || fileType === "file-and-folder") { files = res .filter( _ => _.isFile() && (matchExtension ? matchExtension(_.path) : true), ) .map(_ => ({ type: "file", path: _.path, })); } setFilesData([...folders, ...files]); } } catch { setFilesData([]); } setLoading(false); currentPathRef.current = currentPath; })(); }, [currentPath.path]); useHardwareBack(() => { // 注意闭包 const _currentPath = currentPathRef.current; if (_currentPath.parent !== null) { setCurrentPath(_currentPath.parent); } else { navigation.goBack(); } return true; }); const selectPath = useCallback( (item: IFileItem | IFileItem[], nextChecked: boolean) => { if (multi) { if (!Array.isArray(item)) { item = [item]; } setCheckedItems(prev => { const itemPaths = (item as IFileItem[]).map(_ => _.path); const newCheckedItem = prev.filter( _ => !itemPaths.includes(_.path), ); if (nextChecked) { return [...newCheckedItem, ...(item as IFileItem[])]; } else { return newCheckedItem; } }); } else { setCheckedItems( nextChecked ? (Array.isArray(item) ? item : [item]) : [], ); } }, [], ); const renderItem = ({ item }: { item: IFileItem }) => ( { if (item.type === "folder") { setCurrentPath(prev => ({ parent: prev, path: item.path, })); } else { selectPath(item, !currentChecked); } }} checked={checkedPaths.includes(item.path)} onCheckedChange={checked => { selectPath(item, checked); }} /> ); const currentPageAllChecked = useMemo(() => { return ( filesData.length && filesData.every(file => checkedPaths.includes(file.path)) ); }, [filesData, checkedPaths]); const renderHeader = () => { return multi ? ( ) : null; }; return ( { // 返回上一级 if (currentPath.parent !== null) { setCurrentPath(currentPath.parent); } }} /> {currentPath.path} {loading ? ( ) : ( <> ({ length: ITEM_HEIGHT, offset: ITEM_HEIGHT * index, index, })} renderItem={renderItem} /> )} { if (checkedItems.length) { const shouldBack = await onAction?.(checkedItems); if (shouldBack) { navigation.goBack(); } } }}> 0 ? undefined : 0.6}> {actionText} {multi && checkedItems?.length > 0 ? ` (选中${checkedItems.length})` : ""} ); } const style = StyleSheet.create({ header: { height: rpx(88), flexDirection: "row", alignItems: "center", width: "100%", paddingHorizontal: rpx(24), }, headerPath: { marginLeft: rpx(28), }, scanBtn: { width: "100%", height: rpx(120), alignItems: "center", justifyContent: "center", }, selectAll: { width: "100%", height: ITEM_HEIGHT, paddingHorizontal: rpx(24), flexDirection: "row", alignItems: "center", }, }); ================================================ FILE: src/pages/history/index.tsx ================================================ import React from "react"; import VerticalSafeAreaView from "@/components/base/verticalSafeAreaView"; import globalStyle from "@/constants/globalStyle"; import StatusBar from "@/components/base/statusBar"; import musicHistory, { useMusicHistory } from "@/core/musicHistory"; import MusicList from "@/components/musicList"; import { musicHistorySheetId, RequestStateCode } from "@/constants/commonConst"; import MusicBar from "@/components/musicBar"; import AppBar from "@/components/base/appBar"; import { ROUTE_PATH, useNavigate } from "@/core/router"; import { useI18N } from "@/core/i18n"; export default function History() { const musicHistoryList = useMusicHistory(); const navigate = useNavigate(); const { t } = useI18N(); return ( {t("history.title")} ); } ================================================ FILE: src/pages/home/components/ActionButton.tsx ================================================ import ThemeText from "@/components/base/themeText"; import useColors from "@/hooks/useColors"; import rpx from "@/utils/rpx"; import React from "react"; import { StyleProp, StyleSheet, ViewStyle } from "react-native"; import { TouchableOpacity } from "react-native-gesture-handler"; import Icon, { IIconName } from "@/components/base/icon.tsx"; interface IActionButtonProps { iconName: IIconName; iconColor?: string; title: string; action?: () => void; style?: StyleProp; } export default function ActionButton(props: IActionButtonProps) { const { iconName, iconColor, title, action, style } = props; const colors = useColors(); // rippleColor="rgba(0, 0, 0, .32)" return ( <> {title} ); } const styles = StyleSheet.create({ wrapper: { width: rpx(140), height: rpx(144), borderRadius: rpx(12), flexGrow: 1, flexShrink: 0, flexDirection: "column", alignItems: "center", justifyContent: "center", }, text: { marginTop: rpx(12), }, }); ================================================ FILE: src/pages/home/components/drawer/index.tsx ================================================ import Divider from "@/components/base/divider"; import { IIconName } from "@/components/base/icon.tsx"; import ListItem from "@/components/base/listItem"; import PageBackground from "@/components/base/pageBackground"; import ThemeText from "@/components/base/themeText"; import { showDialog } from "@/components/dialogs/useDialog"; import { showPanel } from "@/components/panels/usePanel"; import { useI18N } from "@/core/i18n"; import { ROUTE_PATH, useNavigate } from "@/core/router"; import TrackPlayer from "@/core/trackPlayer"; import { checkUpdateAndShowResult } from "@/hooks/useCheckUpdate.ts"; import NativeUtils from "@/native/utils"; import rpx from "@/utils/rpx"; import { useScheduleCloseCountDown } from "@/utils/scheduleClose"; import timeformat from "@/utils/timeformat"; import { DrawerContentScrollView } from "@react-navigation/drawer"; import React, { memo } from "react"; import { BackHandler, Platform, StyleSheet, View } from "react-native"; import { default as DeviceInfo, default as deviceInfoModule } from "react-native-device-info"; const ITEM_HEIGHT = rpx(108); interface ISettingOptions { icon: IIconName; title: string; onPress?: () => void; } function HomeDrawer(props: any) { const navigate = useNavigate(); function navigateToSetting(settingType: string) { navigate(ROUTE_PATH.SETTING, { type: settingType, }); } const { t, getSupportedLanguages, getLanguage, setLanguage } = useI18N(); const basicSetting: ISettingOptions[] = [ { icon: "cog-8-tooth", title: t("sidebar.basicSettings"), onPress: () => { navigateToSetting("basic"); }, }, { icon: "javascript", title: t("sidebar.pluginManagement"), onPress: () => { navigateToSetting("plugin"); }, }, { icon: "t-shirt-outline", title: t("sidebar.themeSettings"), onPress: () => { navigateToSetting("theme"); }, }, ]; const otherSetting: ISettingOptions[] = [ { icon: "circle-stack", title: t("sidebar.backupAndResume"), onPress: () => { navigateToSetting("backup"); }, }, ]; if (Platform.OS === "android") { otherSetting.push({ icon: "shield-keyhole-outline", title: t("sidebar.permissionManagement"), onPress: () => { navigate(ROUTE_PATH.PERMISSIONS); }, }); } return ( <> {DeviceInfo.getApplicationName()} {/* */} {t("common.setting")} {basicSetting.map((item, index) => ( ))} {t("common.other")} {otherSetting.map((item, index) => ( ))} { showDialog("RadioDialog", { "content": getSupportedLanguages().map(item => ({ title: item.name, value: item.locale, label: item.name, })), title: t("sidebar.languageSettings"), onOk(value) { setLanguage(value as string); }, defaultSelected: getLanguage().locale, }); }}> {getLanguage().name} {t("common.software")} { checkUpdateAndShowResult(true); }}> {`${t("sidebar.currentVersion")}${deviceInfoModule.getVersion()}`} { navigateToSetting("about"); }}> { // 仅安卓生效 BackHandler.exitApp(); }}> { await TrackPlayer.reset(); NativeUtils.exitApp(); }}> ); } export default memo(HomeDrawer, () => true); const style = StyleSheet.create({ wrapper: { flex: 1, backgroundColor: "#999999", }, scrollWrapper: { paddingTop: rpx(12), }, header: { height: rpx(120), width: "100%", flexDirection: "row", justifyContent: "space-between", alignItems: "center", marginLeft: rpx(24), }, card: { marginBottom: rpx(24), }, cardContent: { paddingHorizontal: 0, }, /** 倒计时 */ countDownText: { height: ITEM_HEIGHT, textAlignVertical: "center", }, }); function _CountDownItem() { const countDown = useScheduleCloseCountDown(); const { t } = useI18N(); return ( { showPanel("TimingClose"); }}> {countDown ? timeformat(countDown) : ""} ); } const CountDownItem = memo(_CountDownItem, () => true); ================================================ FILE: src/pages/home/components/homeBody/index.tsx ================================================ import React from "react"; import globalStyle from "@/constants/globalStyle"; import Operations from "./operations"; import Sheets from "./sheets"; import { ScrollView } from "react-native-gesture-handler"; export default function HomeBody() { return ( ); } ================================================ FILE: src/pages/home/components/homeBody/operations.tsx ================================================ import { useI18N } from "@/core/i18n"; import { ROUTE_PATH, useNavigate } from "@/core/router"; import rpx from "@/utils/rpx"; import React from "react"; import { StyleSheet, View } from "react-native"; import ActionButton from "../ActionButton"; export default function Operations() { const navigate = useNavigate(); const { t } = useI18N(); const actionButtons = [ { iconName: "fire", title: t("home.recommendSheet"), action() { navigate(ROUTE_PATH.RECOMMEND_SHEETS); }, }, { iconName: "trophy", title: t("home.topList"), action() { navigate(ROUTE_PATH.TOP_LIST); }, }, { iconName: "clock-outline", title: t("home.playHistory"), action() { navigate(ROUTE_PATH.HISTORY); }, }, { iconName: "folder-music-outline", title: t("home.localMusic"), action() { navigate(ROUTE_PATH.LOCAL); }, }, ] as const; return ( {actionButtons.map((action, index) => ( ))} ); } const styles = StyleSheet.create({ container: { width: rpx(750), paddingHorizontal: rpx(24), marginVertical: rpx(32), flexDirection: "row", flexWrap: "nowrap", }, actionButtonStyle: { width: rpx(157.5), height: rpx(160), borderRadius: rpx(18), }, actionMarginLeft: { marginLeft: rpx(24), }, }); ================================================ FILE: src/pages/home/components/homeBody/sheets.tsx ================================================ import Empty from "@/components/base/empty"; import IconButton from "@/components/base/iconButton"; import ListItem from "@/components/base/listItem"; import ThemeText from "@/components/base/themeText"; import { showDialog } from "@/components/dialogs/useDialog"; import { showPanel } from "@/components/panels/usePanel"; import { ImgAsset } from "@/constants/assetsConst"; import { localPluginPlatform } from "@/constants/commonConst"; import { useI18N } from "@/core/i18n"; import MusicSheet, { useSheetsBase, useStarredSheets } from "@/core/musicSheet"; import { ROUTE_PATH, useNavigate } from "@/core/router"; import useColors from "@/hooks/useColors"; import rpx from "@/utils/rpx"; import Toast from "@/utils/toast"; import { FlashList } from "@shopify/flash-list"; import React, { useMemo, useState } from "react"; import { StyleSheet, View } from "react-native"; import { TouchableWithoutFeedback } from "react-native-gesture-handler"; export default function Sheets() { const [index, setIndex] = useState(0); const colors = useColors(); const navigate = useNavigate(); const allSheets = useSheetsBase(); const staredSheets = useStarredSheets(); const { t } = useI18N(); const selectedTabTextStyle = useMemo(() => { return [ styles.selectTabText, { borderBottomColor: colors.primary, }, ]; }, [colors]); return ( <> { setIndex(0); }}> {t("home.myPlaylists")} {" "} ({allSheets.length}) { setIndex(1); }}> {t("home.starredPlaylists")} {" "} ({staredSheets.length}) { showPanel("CreateMusicSheet"); }} /> { showPanel("ImportMusicSheet"); }} /> } extraData={{ t }} data={(index === 0 ? allSheets : staredSheets) ?? []} estimatedItemSize={ListItem.Size.big} renderItem={({ item: sheet }) => { const isLocalSheet = !( sheet.platform && sheet.platform !== localPluginPlatform ); return ( { if (isLocalSheet) { navigate(ROUTE_PATH.LOCAL_SHEET_DETAIL, { id: sheet.id, }); } else { navigate(ROUTE_PATH.PLUGIN_SHEET_DETAIL, { sheetInfo: sheet, }); } }}> {sheet.id !== MusicSheet.defaultSheet.id ? ( { showDialog("SimpleDialog", { title: t("dialog.deleteSheetTitle"), content: t("dialog.deleteSheetContent", { name: sheet.title, }), onOk: async () => { if (isLocalSheet) { await MusicSheet.removeSheet( sheet.id, ); Toast.success(t("toast.deleteSuccess")); } else { await MusicSheet.unstarMusicSheet( sheet, ); Toast.success(t("toast.hasUnstarred")); } }, }); }} /> ) : null} ); }} nestedScrollEnabled /> ); } const styles = StyleSheet.create({ subTitleContainer: { paddingHorizontal: rpx(24), flexDirection: "row", alignItems: "flex-start", marginBottom: rpx(12), }, subTitleLeft: { flexDirection: "row", }, tabContainer: { flexDirection: "row", marginRight: rpx(32), }, tabText: { lineHeight: rpx(64), }, selectTabText: { borderBottomWidth: rpx(6), fontWeight: "bold", }, more: { height: rpx(64), marginTop: rpx(3), flexGrow: 1, flexDirection: "row", justifyContent: "flex-end", }, newSheetButton: { marginRight: rpx(24), }, }); ================================================ FILE: src/pages/home/components/homeBodyHorizontal/index.tsx ================================================ import React from "react"; import globalStyle from "@/constants/globalStyle"; import Operations from "./operations"; import { View } from "react-native"; import Sheets from "../homeBody/sheets"; export default function HomeBodyHorizontal() { return ( ); } ================================================ FILE: src/pages/home/components/homeBodyHorizontal/operations.tsx ================================================ import { useI18N } from "@/core/i18n"; import { ROUTE_PATH, useNavigate } from "@/core/router"; import rpx from "@/utils/rpx"; import React from "react"; import { StyleSheet } from "react-native"; import { ScrollView } from "react-native-gesture-handler"; import ActionButton from "../ActionButton"; export default function Operations() { const navigate = useNavigate(); const { t } = useI18N(); const actionButtons = [ { iconName: "fire", title: t("home.recommendSheet"), action() { navigate(ROUTE_PATH.RECOMMEND_SHEETS); }, }, { iconName: "trophy", title: t("home.topList"), action() { navigate(ROUTE_PATH.TOP_LIST); }, }, { iconName: "clock-outline", title: t("home.playHistory"), action() { navigate(ROUTE_PATH.HISTORY); }, }, { iconName: "folder-music-outline", title: t("home.localMusic"), action() { navigate(ROUTE_PATH.LOCAL); }, }, ] as const; return ( {actionButtons.map((action, index) => ( ))} ); } const styles = StyleSheet.create({ container: { width: rpx(200), flexGrow: 0, flexShrink: 0, paddingHorizontal: rpx(24), marginVertical: rpx(32), flexDirection: "row", flexWrap: "wrap", }, actionButtonStyle: { width: rpx(157.5), height: rpx(160), borderRadius: rpx(18), }, actionMarginLeft: { marginTop: rpx(24), }, }); ================================================ FILE: src/pages/home/components/navBar.tsx ================================================ import { ROUTE_PATH } from "@/core/router"; import { useNavigation } from "@react-navigation/native"; import React from "react"; import { Pressable, StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import useColors from "@/hooks/useColors"; import ThemeText from "@/components/base/themeText"; import Color from "color"; import IconButton from "@/components/base/iconButton"; import Icon from "@/components/base/icon.tsx"; import { useI18N } from "@/core/i18n"; // todo icon: = musicFree(引入自定义字体 居中) search export default function NavBar() { const navigation = useNavigation(); const colors = useColors(); const { t } = useI18N(); return ( { navigation?.openDrawer(); }} /> { navigation.navigate(ROUTE_PATH.SEARCH_PAGE); }}> {t("home.clickToSearch")} ); } const styles = StyleSheet.create({ appbar: { backgroundColor: "transparent", shadowColor: "transparent", flexDirection: "row", alignItems: "center", width: "100%", height: rpx(88), }, searchBar: { marginHorizontal: rpx(24), flexDirection: "row", alignItems: "center", flex: 1, height: "72%", maxHeight: rpx(64), borderRadius: rpx(36), paddingHorizontal: rpx(20), }, text: { marginLeft: rpx(12), opacity: 0.6, }, menu: { marginLeft: rpx(24), }, }); ================================================ FILE: src/pages/home/index.tsx ================================================ import React from "react"; import { StyleSheet } from "react-native"; import NavBar from "./components/navBar"; import MusicBar from "@/components/musicBar"; import { createDrawerNavigator } from "@react-navigation/drawer"; import HomeDrawer from "./components/drawer"; import { SafeAreaView } from "react-native-safe-area-context"; import StatusBar from "@/components/base/statusBar"; import HorizontalSafeAreaView from "@/components/base/horizontalSafeAreaView.tsx"; import globalStyle from "@/constants/globalStyle"; import Theme from "@/core/theme"; import HomeBody from "./components/homeBody"; import HomeBodyHorizontal from "./components/homeBodyHorizontal"; import useOrientation from "@/hooks/useOrientation"; function Home() { const orientation = useOrientation(); return ( <> {orientation === "vertical" ? ( ) : ( )} ); } function HomeStatusBar() { const theme = Theme.useTheme(); return ( ); } // function Body() { // const orientation = useOrientation(); // return ( // // // // ); // } const LeftDrawer = createDrawerNavigator(); export default function App() { return ( }> ); } const styles = StyleSheet.create({ appWrapper: { flexDirection: "column", flex: 1, }, flexRow: { flexDirection: "row", }, }); ================================================ FILE: src/pages/localMusic/index.tsx ================================================ import React from "react"; import MainPage from "./mainPage"; import VerticalSafeAreaView from "@/components/base/verticalSafeAreaView"; import globalStyle from "@/constants/globalStyle"; export default function LocalMusic() { return ( ); } ================================================ FILE: src/pages/localMusic/mainPage/index.tsx ================================================ import React from "react"; import LocalMusicSheet from "@/core/localMusicSheet"; import { ROUTE_PATH, useNavigate } from "@/core/router"; import LocalMusicList from "./localMusicList"; import MusicBar from "@/components/musicBar"; import { localMusicSheetId } from "@/constants/commonConst"; import Toast from "@/utils/toast"; import { showDialog } from "@/components/dialogs/useDialog"; import AppBar from "@/components/base/appBar"; import { useI18N } from "@/core/i18n"; export default function MainPage() { const navigate = useNavigate(); const { t } = useI18N(); return ( <> { showDialog("LoadingDialog", { title: t("localMusic.scanLocalMusic"), promise: LocalMusicSheet.importLocal( selectedFiles.map( _ => _.path, ), ), onResolve(data, hideDialog) { Toast.success(t("toast.importSuccess")); hideDialog(); resolve(true); }, onCancel(hideDialog) { LocalMusicSheet.cancelImportLocal(); hideDialog(); resolve(false); }, }); }); }, }); }, }, { icon: "pencil-square", title: t("common.batchEdit"), async onPress() { navigate(ROUTE_PATH.MUSIC_LIST_EDITOR, { musicList: LocalMusicSheet.getMusicList(), musicSheet: { id: localMusicSheetId, }, }); }, }, { icon: "arrow-down-tray", title: t("localMusic.downloadList"), async onPress() { navigate(ROUTE_PATH.DOWNLOADING); }, }, ]}> {t("home.localMusic")} ); } ================================================ FILE: src/pages/localMusic/mainPage/localMusicList.tsx ================================================ import React from "react"; import MusicList from "@/components/musicList"; import LocalMusicSheet from "@/core/localMusicSheet"; import { localMusicSheetId, localPluginPlatform, RequestStateCode } from "@/constants/commonConst"; import HorizontalSafeAreaView from "@/components/base/horizontalSafeAreaView.tsx"; import globalStyle from "@/constants/globalStyle"; import { useI18N } from "@/core/i18n"; export default function LocalMusicList() { const musicList = LocalMusicSheet.useMusicList(); const { t } = useI18N(); return ( ); } ================================================ FILE: src/pages/musicDetail/components/background.tsx ================================================ import React, { useMemo } from "react"; import { Image, StyleSheet, View } from "react-native"; import { ImgAsset } from "@/constants/assetsConst"; import { useCurrentMusic } from "@/core/trackPlayer"; export default function Background() { const musicItem = useCurrentMusic(); const artworkSource = useMemo(() => { if (!musicItem?.artwork) { return ImgAsset.albumDefault; } if(typeof musicItem.artwork === "string") { return { uri: musicItem.artwork, }; } return musicItem.artwork; }, [musicItem?.artwork]); return ( <> ); } const style = StyleSheet.create({ background: { width: "100%", height: "100%", position: "absolute", top: 0, left: 0, right: 0, bottom: 0, backgroundColor: "#000", }, blur: { width: "100%", height: "100%", position: "absolute", top: 0, left: 0, right: 0, bottom: 0, opacity: 0.5, }, }); ================================================ FILE: src/pages/musicDetail/components/bottom/index.tsx ================================================ import React from "react"; import { StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import SeekBar from "./seekBar"; import PlayControl from "./playControl"; import useOrientation from "@/hooks/useOrientation"; export default function Bottom() { const orientation = useOrientation(); return ( ); } const style = StyleSheet.create({ wrapper: { width: "100%", height: rpx(240), }, }); ================================================ FILE: src/pages/musicDetail/components/bottom/playControl.tsx ================================================ import repeatModeConst from "@/constants/repeatModeConst"; import rpx from "@/utils/rpx"; import React from "react"; import { InteractionManager, StyleSheet, View } from "react-native"; import Icon from "@/components/base/icon.tsx"; import { showPanel } from "@/components/panels/usePanel"; import TrackPlayer, { useMusicState, useRepeatMode } from "@/core/trackPlayer"; import useOrientation from "@/hooks/useOrientation"; import delay from "@/utils/delay"; import { musicIsPaused } from "@/utils/trackUtils"; export default function () { const repeatMode = useRepeatMode(); const musicState = useMusicState(); const orientation = useOrientation(); console.log(repeatMode, repeatModeConst[repeatMode]); return ( <> { InteractionManager.runAfterInteractions(async () => { await delay(20, false); TrackPlayer.toggleRepeatMode(); }); }} /> { TrackPlayer.skipToPrevious(); }} /> { if (musicIsPaused(musicState)) { TrackPlayer.play(); } else { TrackPlayer.pause(); } }} /> { TrackPlayer.skipToNext(); }} /> { showPanel("PlayList"); }} /> ); } const style = StyleSheet.create({ wrapper: { width: "100%", marginTop: rpx(36), height: rpx(100), flexDirection: "row", justifyContent: "space-around", alignItems: "center", }, }); ================================================ FILE: src/pages/musicDetail/components/bottom/seekBar.tsx ================================================ import React, { useRef, useState } from "react"; import { StyleSheet, Text, View } from "react-native"; import rpx from "@/utils/rpx"; import Slider from "@react-native-community/slider"; import timeformat from "@/utils/timeformat"; import { fontSizeConst } from "@/constants/uiConst"; import TrackPlayer, { useProgress } from "@/core/trackPlayer"; interface ITimeLabelProps { time: number; } function TimeLabel(props: ITimeLabelProps) { return ( {timeformat(Math.max(props.time, 0))} ); } export default function SeekBar() { const progress = useProgress(1000); const [tmpProgress, setTmpProgress] = useState(null); const slidingRef = useRef(false); return ( { slidingRef.current = true; }} onValueChange={val => { if (slidingRef.current) { setTmpProgress(val); } }} onSlidingComplete={val => { slidingRef.current = false; setTmpProgress(null); if (val >= progress.duration - 2) { val = progress.duration - 2; } TrackPlayer.seekTo(val); }} value={progress.position} /> ); } const style = StyleSheet.create({ wrapper: { width: "100%", height: rpx(40), justifyContent: "center", alignItems: "center", flexDirection: "row", }, slider: { width: "73%", height: rpx(40), }, text: { fontSize: fontSizeConst.description, includeFontPadding: false, color: "#cccccc", }, }); ================================================ FILE: src/pages/musicDetail/components/content/albumCover/index.tsx ================================================ import React, { useMemo } from "react"; import rpx from "@/utils/rpx"; import { ImgAsset } from "@/constants/assetsConst"; import FastImage from "@/components/base/fastImage"; import useOrientation from "@/hooks/useOrientation"; import { Gesture, GestureDetector } from "react-native-gesture-handler"; import { useCurrentMusic } from "@/core/trackPlayer"; import globalStyle from "@/constants/globalStyle"; import { View } from "react-native"; import Operations from "./operations"; import { showPanel } from "@/components/panels/usePanel.ts"; interface IProps { onTurnPageClick?: () => void; } export default function AlbumCover(props: IProps) { const { onTurnPageClick } = props; const musicItem = useCurrentMusic(); const orientation = useOrientation(); const artworkStyle = useMemo(() => { if (orientation === "vertical") { return { width: rpx(500), height: rpx(500), }; } else { return { width: rpx(260), height: rpx(260), }; } }, [orientation]); const longPress = Gesture.LongPress() .onStart(() => { if (musicItem?.artwork) { showPanel("ImageViewer", { url: musicItem.artwork, }); } }) .runOnJS(true); const tap = Gesture.Tap() .onStart(() => { onTurnPageClick?.(); }) .runOnJS(true); const combineGesture = Gesture.Race(tap, longPress); return ( <> ); } ================================================ FILE: src/pages/musicDetail/components/content/albumCover/operations.tsx ================================================ import React, { useMemo } from "react"; import { Image, Pressable, StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import LocalMusicSheet from "@/core/localMusicSheet"; import { ROUTE_PATH } from "@/core/router"; import { ImgAsset } from "@/constants/assetsConst"; import Toast from "@/utils/toast"; import toast from "@/utils/toast"; import useOrientation from "@/hooks/useOrientation"; import { showPanel } from "@/components/panels/usePanel"; import TrackPlayer, { useCurrentMusic, useMusicQuality } from "@/core/trackPlayer"; import { iconSizeConst } from "@/constants/uiConst"; import PersistStatus from "@/utils/persistStatus"; import HeartIcon from "../heartIcon"; import Icon from "@/components/base/icon.tsx"; import PluginManager from "@/core/pluginManager"; import downloader from "@/core/downloader"; import i18n from "@/core/i18n"; export default function Operations() { const musicItem = useCurrentMusic(); const currentQuality = useMusicQuality(); const isDownloaded = LocalMusicSheet.useIsLocal(musicItem); const rate = PersistStatus.useValue("music.rate", 100); const orientation = useOrientation(); const supportComment = useMemo(() => { return !musicItem ? false : !!PluginManager.getByMedia(musicItem)?.supportedMethods.has("getMusicComments"); }, [musicItem]); return ( { if (!musicItem) { return; } showPanel("MusicQuality", { musicItem, async onQualityPress(quality) { const changeResult = await TrackPlayer.changeQuality(quality); if (!changeResult) { Toast.warn(i18n.t("toast.currentQualityNotAvailableForCurrentMusic")); } }, }); }}> { if (musicItem && !isDownloaded) { showPanel("MusicQuality", { type: "download", musicItem, async onQualityPress(quality) { downloader.download(musicItem, quality); }, }); } }} /> { if (!musicItem) { return; } showPanel("PlayRate", { async onRatePress(newRate) { if (rate !== newRate) { try { await TrackPlayer.setRate(newRate / 100); PersistStatus.set("music.rate", newRate); } catch { } } }, }); }}> { if (!supportComment) { toast.warn(i18n.t("toast.commmentNotAvaliableForCurrentMusic")); return; } if (musicItem) { showPanel("MusicComment", { musicItem, }); } }} /> { if (musicItem) { showPanel("MusicItemOptions", { musicItem: musicItem, from: ROUTE_PATH.MUSIC_DETAIL, }); } }} /> ); } const styles = StyleSheet.create({ wrapper: { width: "100%", height: rpx(80), marginBottom: rpx(24), flexDirection: "row", alignItems: "center", justifyContent: "space-around", }, horizontalWrapper: { marginBottom: 0, }, quality: { width: rpx(52), height: rpx(52), }, }); ================================================ FILE: src/pages/musicDetail/components/content/heartIcon/index.tsx ================================================ import React from "react"; import { iconSizeConst } from "@/constants/uiConst"; import { useCurrentMusic } from "@/core/trackPlayer"; import Icon from "@/components/base/icon.tsx"; import MusicSheet, { useFavorite } from "@/core/musicSheet"; export default function () { const musicItem = useCurrentMusic(); const isFavorite = useFavorite(musicItem); return isFavorite ? ( { if (!musicItem) { return; } MusicSheet.removeMusic(MusicSheet.defaultSheet.id, musicItem); }} /> ) : ( { if (musicItem) { MusicSheet.addMusic(MusicSheet.defaultSheet.id, musicItem); } }} /> ); } ================================================ FILE: src/pages/musicDetail/components/content/index.tsx ================================================ import React, { useState } from "react"; import { View } from "react-native"; import AlbumCover from "./albumCover"; import Lyric from "./lyric"; import useOrientation from "@/hooks/useOrientation"; import Config from "@/core/appConfig"; import globalStyle from "@/constants/globalStyle"; export default function Content() { const [tab, selectTab] = useState<"album" | "lyric">( Config.getConfig("basic.musicDetailDefault") || "album", ); const orientation = useOrientation(); const showAlbumCover = tab === "album" || orientation === "horizontal"; const onTurnPageClick = () => { if (orientation === "horizontal") { return; } if (tab === "album") { selectTab("lyric"); } else { selectTab("album"); } }; return ( {showAlbumCover ? ( ) : ( )} ); } ================================================ FILE: src/pages/musicDetail/components/content/lyric/draggingTime.tsx ================================================ import React from "react"; import { StyleSheet, Text } from "react-native"; import rpx from "@/utils/rpx"; import timeformat from "@/utils/timeformat"; import { fontSizeConst } from "@/constants/uiConst"; import { useProgress } from "@/core/trackPlayer"; export default function DraggingTime(props: { time: number }) { const progress = useProgress(); return ( {timeformat( Math.max(Math.min(props.time, progress.duration ?? 0), 0), )} ); } const style = StyleSheet.create({ draggingTimeText: { color: "#dddddd", paddingHorizontal: rpx(8), paddingVertical: rpx(6), borderRadius: rpx(12), backgroundColor: "rgba(255,255,255,0.1)", fontSize: fontSizeConst.description, }, }); ================================================ FILE: src/pages/musicDetail/components/content/lyric/index.tsx ================================================ import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { LayoutRectangle, StyleSheet, Text, View } from "react-native"; import rpx from "@/utils/rpx"; import useDelayFalsy from "@/hooks/useDelayFalsy"; import { FlatList, Gesture, GestureDetector, TapGestureHandler } from "react-native-gesture-handler"; import { fontSizeConst } from "@/constants/uiConst"; import Loading from "@/components/base/loading"; import globalStyle from "@/constants/globalStyle"; import { showPanel } from "@/components/panels/usePanel"; import TrackPlayer, { useCurrentMusic, useMusicState } from "@/core/trackPlayer"; import { musicIsPaused } from "@/utils/trackUtils"; import delay from "@/utils/delay"; import DraggingTime from "./draggingTime"; import LyricItemComponent from "./lyricItem"; import PersistStatus from "@/utils/persistStatus"; import LyricOperations from "./lyricOperations"; import { IParsedLrcItem } from "@/utils/lrcParser"; import { IconButtonWithGesture } from "@/components/base/iconButton.tsx"; import { getMediaExtraProperty } from "@/utils/mediaExtra"; import lyricManager, { useCurrentLyricItem, useLyricState } from "@/core/lyricManager"; import { useI18N } from "@/core/i18n"; const ITEM_HEIGHT = rpx(92); interface IItemHeights { blankHeight?: number; [k: number]: number; } interface IProps { onTurnPageClick?: () => void; } const fontSizeMap = { 0: rpx(24), 1: rpx(30), 2: rpx(36), 3: rpx(42), } as Record; export default function Lyric(props: IProps) { const { onTurnPageClick } = props; const { loading, meta, lyrics, hasTranslation } = useLyricState(); const currentLrcItem = useCurrentLyricItem(); const showTranslation = PersistStatus.useValue( "lyric.showTranslation", false, ); const fontSizeKey = PersistStatus.useValue("lyric.detailFontSize", 1); const fontSizeStyle = useMemo( () => ({ fontSize: fontSizeMap[fontSizeKey!], }), [fontSizeKey], ); const [draggingIndex, setDraggingIndex, setDraggingIndexImmi] = useDelayFalsy(undefined, 2000); const musicState = useMusicState(); const { t } = useI18N(); const [layout, setLayout] = useState(); const listRef = useRef | null>(); const currentMusicItem = useCurrentMusic(); const associateMusicItem = getMediaExtraProperty(currentMusicItem, "associatedLrc"); // 是否展示拖拽 const dragShownRef = useRef(false); // 组件是否挂载 const isMountedRef = useRef(true); // 用来缓存高度 const itemHeightsRef = useRef({}); // 设置空白组件,获取组件高度 const blankComponent = useMemo(() => { return ( { itemHeightsRef.current.blankHeight = evt.nativeEvent.layout.height; }} /> ); }, []); const handleLyricItemLayout = useCallback( (index: number, height: number) => { itemHeightsRef.current[index] = height; }, [], ); // 滚到当前item const scrollToCurrentLrcItem = useCallback(() => { if (!listRef.current) { return; } const currentLyricItem = lyricManager.currentLyricItem; const currentLyrics = lyricManager.lyricState?.lyrics; if (currentLyricItem?.index === -1 || !currentLyricItem) { listRef.current?.scrollToIndex({ index: 0, viewPosition: 0.5, }); } else { listRef.current?.scrollToIndex({ index: Math.min(currentLyricItem.index ?? 0, currentLyrics.length - 1), viewPosition: 0.5, }); } }, []); const delayedScrollToCurrentLrcItem = useMemo(() => { let sto: number; return () => { if (sto) { clearTimeout(sto); } sto = setTimeout(() => { if (isMountedRef.current) { scrollToCurrentLrcItem(); } }, 200) as any; }; }, []); useEffect(() => { // 暂停且拖拽才返回 if ( lyrics.length === 0 || draggingIndex !== undefined || (draggingIndex === undefined && musicIsPaused(musicState)) || lyrics[lyrics.length - 1].time < 1 ) { return; } if (currentLrcItem?.index === -1 || !currentLrcItem) { listRef.current?.scrollToIndex({ index: 0, viewPosition: 0.5, }); } else { listRef.current?.scrollToIndex({ index: Math.min(currentLrcItem.index ?? 0, lyrics.length - 1), viewPosition: 0.5, }); } // 音乐暂停状态不应该影响到滑动,所以不放在依赖里,但是这样写不好。。 }, [currentLrcItem, lyrics, draggingIndex]); useEffect(() => { scrollToCurrentLrcItem(); return () => { isMountedRef.current = false; }; }, []); // 开始滚动时拖拽生效 const onScrollBeginDrag = () => { dragShownRef.current = true; }; const onScrollEndDrag = async () => { if (draggingIndex !== undefined) { setDraggingIndex(undefined); } dragShownRef.current = false; }; const onScroll = (e: any) => { if (dragShownRef.current) { const offset = e.nativeEvent.contentOffset.y + e.nativeEvent.layoutMeasurement.height / 2; const itemHeights = itemHeightsRef.current; let height = itemHeights.blankHeight!; if (offset <= height) { setDraggingIndex(0); return; } for (let i = 0; i < lyrics.length; ++i) { height += itemHeights[i] ?? 0; if (height > offset) { setDraggingIndex(i); return; } } } }; const onLyricSeekPress = async () => { if (draggingIndex !== undefined) { const time = lyrics[draggingIndex].time + +(meta?.offset ?? 0); if (time !== undefined && !isNaN(time)) { await TrackPlayer.seekTo(time); await TrackPlayer.play(); setDraggingIndexImmi(undefined); } } }; const tapGesture = Gesture.Tap() .onStart(() => { onTurnPageClick?.(); }) .runOnJS(true); const unlinkTapGesture = Gesture.Tap() .onStart(() => { if (currentMusicItem) { lyricManager.unassociateLyric(currentMusicItem); } }) .runOnJS(true); return ( <> {loading ? ( ) : lyrics?.length ? ( { listRef.current = _; }} onLayout={e => { setLayout(e.nativeEvent.layout); }} viewabilityConfig={{ itemVisiblePercentThreshold: 100, }} onScrollToIndexFailed={({ index }) => { delay(120).then(() => { listRef.current?.scrollToIndex({ index: Math.min( index ?? 0, lyrics.length - 1, ), viewPosition: 0.5, }); }); }} fadingEdgeLength={120} ListHeaderComponent={ <> {blankComponent} {associateMusicItem ? ( <> {t("lyric.lyricLinkedFrom", { platform: associateMusicItem.platform, title: associateMusicItem.title || "", })} {t("lyric.unlinkLyric")} ) : null} } ListFooterComponent={blankComponent} onScrollBeginDrag={onScrollBeginDrag} onMomentumScrollEnd={onScrollEndDrag} onScroll={onScroll} scrollEventThrottle={32} style={styles.wrapper} data={lyrics} initialNumToRender={30} overScrollMode="never" extraData={currentLrcItem} renderItem={({ item, index }) => { let text = item.lrc; if (showTranslation && hasTranslation) { text += `\n${item?.translation ?? ""}`; } return ( ); }} /> ) : ( {t("lyric.noLyric")} { showPanel("SearchLrc", { musicItem: TrackPlayer.currentMusic, }); }}> {t("lyric.searchLyric")} )} {draggingIndex !== undefined && ( )} ); } const styles = StyleSheet.create({ wrapper: { width: "100%", marginVertical: rpx(48), flex: 1, }, empty: { paddingTop: "70%", }, white: { color: "white", }, lyricMeta: { position: "absolute", width: "100%", flexDirection: "row", justifyContent: "center", alignItems: "center", left: 0, paddingHorizontal: rpx(48), bottom: rpx(48), }, lyricMetaText: { color: "white", opacity: 0.8, maxWidth: "80%", }, linkText: { color: "#66ccff", textDecorationLine: "underline", }, draggingTime: { position: "absolute", width: "100%", height: ITEM_HEIGHT, top: "40%", marginTop: rpx(48), paddingHorizontal: rpx(18), right: 0, flexDirection: "row", alignItems: "center", justifyContent: "space-between", }, draggingTimeText: { color: "#dddddd", fontSize: fontSizeConst.description, width: rpx(90), }, singleLine: { width: "67%", height: 1, backgroundColor: "#cccccc", opacity: 0.4, }, playIcon: { width: rpx(100), textAlign: "right", color: "white", }, searchLyric: { width: rpx(180), marginTop: rpx(14), paddingVertical: rpx(10), textAlign: "center", alignSelf: "center", color: "#66eeff", textDecorationLine: "underline", }, }); ================================================ FILE: src/pages/musicDetail/components/content/lyric/lyricItem.tsx ================================================ import React, { memo } from "react"; import { StyleSheet, Text } from "react-native"; import rpx from "@/utils/rpx"; import useColors from "@/hooks/useColors"; import { fontSizeConst } from "@/constants/uiConst"; interface ILyricItemComponentProps { // 行号 index?: number; // 显示 light?: boolean; // 高亮 highlight?: boolean; // 文本 text?: string; // 字体大小 fontSize?: number; onLayout?: (index: number, height: number) => void; } function _LyricItemComponent(props: ILyricItemComponentProps) { const { light, highlight, text, onLayout, index, fontSize } = props; const colors = useColors(); return ( { if (index !== undefined) { onLayout?.(index, nativeEvent.layout.height); } }} style={[ lyricStyles.item, { fontSize: fontSize || fontSizeConst.content, }, highlight ? [ lyricStyles.highlightItem, { color: colors.primary, }, ] : null, light ? lyricStyles.draggingItem : null, ]}> {text} ); } // 歌词 const LyricItemComponent = memo( _LyricItemComponent, (prev, curr) => prev.light === curr.light && prev.highlight === curr.highlight && prev.text === curr.text && prev.index === curr.index && prev.fontSize === curr.fontSize, ); export default LyricItemComponent; const lyricStyles = StyleSheet.create({ highlightItem: { opacity: 1, }, item: { color: "white", opacity: 0.6, paddingHorizontal: rpx(64), paddingVertical: rpx(24), width: "100%", textAlign: "center", textAlignVertical: "center", }, draggingItem: { opacity: 0.9, color: "white", }, }); ================================================ FILE: src/pages/musicDetail/components/content/lyric/lyricOperations.tsx ================================================ import React from "react"; import { StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import { iconSizeConst } from "@/constants/uiConst"; import TranslationIcon from "@/assets/icons/translation.svg"; import { useAppConfig } from "@/core/appConfig"; import useColors from "@/hooks/useColors"; import Toast from "@/utils/toast"; import { hidePanel, showPanel } from "@/components/panels/usePanel"; import TrackPlayer from "@/core/trackPlayer"; import PersistStatus from "@/utils/persistStatus"; import useOrientation from "@/hooks/useOrientation"; import HeartIcon from "../heartIcon"; import Icon from "@/components/base/icon.tsx"; import lyricManager, { useLyricState } from "@/core/lyricManager"; interface ILyricOperationsProps { scrollToCurrentLrcItem: () => void; } export default function LyricOperations(props: ILyricOperationsProps) { const { scrollToCurrentLrcItem } = props; const detailFontSize = useAppConfig("lyric.detailFontSize"); const { hasTranslation } = useLyricState(); const showTranslation = PersistStatus.useValue( "lyric.showTranslation", false, ); const colors = useColors(); const orientation = useOrientation(); return ( {orientation === "vertical" ? : null} { showPanel("SetFontSize", { defaultSelect: detailFontSize ?? 1, onSelectChange(value) { PersistStatus.set("lyric.detailFontSize", value); scrollToCurrentLrcItem(); }, }); }} /> { const currentMusicItem = TrackPlayer.currentMusic; if (currentMusicItem) { showPanel("SetLyricOffset", { musicItem: currentMusicItem, onSubmit(offset) { lyricManager.updateLyricOffset(currentMusicItem, offset); scrollToCurrentLrcItem(); hidePanel(); }, }); } }} /> { const currentMusic = TrackPlayer.currentMusic; if (!currentMusic) { return; } // if ( // Config.get('setting.basic.associateLyricType') === // 'input' // ) { // showPanel('AssociateLrc', { // musicItem: currentMusic, // }); // } else { showPanel("SearchLrc", { musicItem: currentMusic, }); // } }} /> { if (!hasTranslation) { Toast.warn("当前歌曲无翻译"); return; } PersistStatus.set( "lyric.showTranslation", !showTranslation, ); scrollToCurrentLrcItem(); }} /> { const currentMusic = TrackPlayer.currentMusic; if (currentMusic) { showPanel("MusicItemLyricOptions", { musicItem: currentMusic, }); } }} /> ); } const styles = StyleSheet.create({ container: { height: rpx(80), marginBottom: rpx(24), width: "100%", flexDirection: "row", alignItems: "center", justifyContent: "space-around", }, }); ================================================ FILE: src/pages/musicDetail/components/navBar.tsx ================================================ import React from "react"; import { StyleSheet, Text, View } from "react-native"; import rpx from "@/utils/rpx"; import { useNavigation } from "@react-navigation/native"; import Tag from "@/components/base/tag"; import { fontSizeConst, fontWeightConst } from "@/constants/uiConst"; import Share from "react-native-share"; import { B64Asset } from "@/constants/assetsConst"; import IconButton from "@/components/base/iconButton"; import { useCurrentMusic } from "@/core/trackPlayer"; export default function NavBar() { const navigation = useNavigation(); const musicItem = useCurrentMusic(); // const {showShare} = useShare(); return ( { navigation.goBack(); }} /> {musicItem?.title ?? "--"} {musicItem?.artist} {musicItem?.platform ? ( ) : null} { try { await Share.open({ type: "image/jpeg", title: "MusicFree-一个插件化的免费音乐播放器", message: "MusicFree-一个插件化的免费音乐播放器", url: B64Asset.share, subject: "MusicFree分享", }); } catch {} }} /> ); } const styles = StyleSheet.create({ container: { width: "100%", height: rpx(150), flexDirection: "row", alignItems: "center", justifyContent: "space-between", }, button: { marginHorizontal: rpx(24), }, headerContent: { flex: 1, height: rpx(150), justifyContent: "center", alignItems: "center", }, headerTitleText: { color: "white", fontWeight: fontWeightConst.semibold, fontSize: fontSizeConst.title, marginBottom: rpx(12), includeFontPadding: false, }, headerDesc: { height: rpx(32), flexDirection: "row", alignItems: "center", paddingHorizontal: rpx(40), }, headerArtistText: { color: "white", fontSize: fontSizeConst.subTitle, includeFontPadding: false, }, tagBg: { backgroundColor: "rgba(255, 255, 255, 0.2)", }, tagText: { color: "white", }, }); ================================================ FILE: src/pages/musicDetail/index.tsx ================================================ import StatusBar from "@/components/base/statusBar"; import globalStyle from "@/constants/globalStyle"; import useOrientation from "@/hooks/useOrientation"; import React, { useEffect } from "react"; import { StyleSheet, View } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; import Background from "./components/background"; import Bottom from "./components/bottom"; import Content from "./components/content"; import Lyric from "./components/content/lyric"; import NavBar from "./components/navBar"; import Config from "@/core/appConfig"; import { activateKeepAwakeAsync, deactivateKeepAwake } from "expo-keep-awake"; export default function MusicDetail() { const orientation = useOrientation(); useEffect(() => { const needAwake = Config.getConfig("basic.musicDetailAwake"); if (needAwake) { activateKeepAwakeAsync(); } return () => { if (needAwake) { deactivateKeepAwake(); } }; }, []); return ( <> {orientation === "horizontal" ? ( ) : null} ); } const style = StyleSheet.create({ bodyWrapper: { width: "100%", flex: 1, flexDirection: "row", }, }); ================================================ FILE: src/pages/musicListEditor/components/body.tsx ================================================ import React, { useMemo } from "react"; import { StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import Button from "@/components/base/textButton.tsx"; import { useAtom } from "jotai"; import { editingMusicListAtom, musicListChangedAtom } from "../store/atom"; import Toast from "@/utils/toast"; import MusicList from "./musicList"; import { useParams } from "@/core/router"; import { localMusicSheetId, musicHistorySheetId } from "@/constants/commonConst"; import LocalMusicSheet from "@/core/localMusicSheet"; import HorizontalSafeAreaView from "@/components/base/horizontalSafeAreaView.tsx"; import globalStyle from "@/constants/globalStyle"; import musicHistory from "@/core/musicHistory"; import MusicSheet from "@/core/musicSheet"; import { useI18N } from "@/core/i18n"; export default function Body() { const { musicSheet } = useParams<"music-list-editor">(); const { t } = useI18N(); const [editingMusicList, setEditingMusicList] = useAtom(editingMusicListAtom); const [musicListChanged, setMusicListChanged] = useAtom(musicListChangedAtom); const selectedItems = useMemo( () => editingMusicList.filter(_ => _.checked), [editingMusicList], ); return ( ); } const style = StyleSheet.create({ header: { flexDirection: "row", height: rpx(88), paddingHorizontal: rpx(24), alignItems: "center", justifyContent: "space-between", }, }); ================================================ FILE: src/pages/musicListEditor/components/bottom.tsx ================================================ import Icon, { IIconName } from "@/components/base/icon.tsx"; import ThemeText from "@/components/base/themeText"; import { showPanel } from "@/components/panels/usePanel"; import { iconSizeConst } from "@/constants/uiConst"; import downloader from "@/core/downloader"; import { useI18N } from "@/core/i18n"; import { useParams } from "@/core/router"; import TrackPlayer from "@/core/trackPlayer"; import useColors from "@/hooks/useColors"; import rpx from "@/utils/rpx"; import Toast from "@/utils/toast"; import { produce } from "immer"; import { useAtom, useSetAtom } from "jotai"; import React, { useMemo } from "react"; import { Pressable, StyleSheet, View } from "react-native"; import { editingMusicListAtom, musicListChangedAtom } from "../store/atom"; export default function Bottom() { const { musicSheet } = useParams<"music-list-editor">(); const [editingMusicList, setEditingMusicList] = useAtom(editingMusicListAtom); const setMusicListChanged = useSetAtom(musicListChangedAtom); const { t } = useI18N(); const selectedEditorItems = useMemo( () => editingMusicList.filter(_ => _.checked), [editingMusicList], ); const selectedItems = useMemo( () => selectedEditorItems.map(_ => _.musicItem), [selectedEditorItems], ); function resetSelectedIndices() { setEditingMusicList( editingMusicList.map(_ => ({ musicItem: _.musicItem, checked: false, })), ); } return ( { TrackPlayer.addNext(selectedItems); resetSelectedIndices(); Toast.success(t("toast.addToNextPlay")); }} /> { if (selectedItems.length) { showPanel("AddToMusicSheet", { musicItem: selectedItems, }); resetSelectedIndices(); } }} /> { if (selectedItems.length) { downloader.download(selectedItems); Toast.success( t("toast.beginDownload"), ); resetSelectedIndices(); } }} /> { if (selectedItems.length && musicSheet?.id) { setEditingMusicList( produce(prev => prev.filter(_ => !_.checked)), ); setMusicListChanged(true); Toast.warn(t("toast.rememberToSave")); } }} /> ); } interface IBottomIconProps { icon: IIconName; title: string; color?: "text" | "textSecondary"; onPress: () => void; } function BottomIcon(props: IBottomIconProps) { const { icon, title, onPress, color = "text" } = props; const colors = useColors(); return ( {title} ); } const style = StyleSheet.create({ wrapper: { width: "100%", height: rpx(144), flexDirection: "row", }, bottomIconWrapper: { flex: 1, height: "100%", alignItems: "center", justifyContent: "center", }, bottomIconText: { marginTop: rpx(12), }, opacity_06: { opacity: 0.6, }, }); ================================================ FILE: src/pages/musicListEditor/components/musicList.tsx ================================================ import React, { memo, useCallback } from "react"; import { StatusBar, StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import MusicItem from "@/components/mediaItem/musicItem"; import { produce } from "immer"; import { useAtom, useSetAtom } from "jotai"; import { IEditorMusicItem, editingMusicListAtom, musicListChangedAtom, } from "../store/atom"; import SortableFlatList from "@/components/base/SortableFlatList"; import CheckBox from "@/components/base/checkbox"; import useColors from "@/hooks/useColors"; import Empty from "@/components/base/empty"; const ITEM_HEIGHT = rpx(120); interface IMusicEditorItemProps { index: number; editorMusicItem: IEditorMusicItem; } function _MusicEditorItem(props: IMusicEditorItemProps) { const { index, editorMusicItem } = props; const setEditingMusicList = useSetAtom(editingMusicListAtom); const onPress = useCallback(() => { setEditingMusicList( produce(draft => { draft[index].checked = !draft[index].checked; }), ); }, [index]); return ( ( )} showMoreIcon={false} itemPaddingRight={rpx(100)} onItemPress={onPress} /> ); } const MusicEditorItem = memo( _MusicEditorItem, (prev, curr) => prev.editorMusicItem === curr.editorMusicItem && prev.index === curr.index, ); /** 音乐列表 */ const marginTop = rpx(88) * 2 + (StatusBar.currentHeight ?? 0); export default function MusicList() { const [editingMusicList, setEditingMusicList] = useAtom(editingMusicListAtom); const setMusicListChanged = useSetAtom(musicListChangedAtom); const renderItem = useCallback( ({ index, item }: any) => { return ; }, [editingMusicList], ); const colors = useColors(); return editingMusicList?.length ? ( { setEditingMusicList(newData); setMusicListChanged(true); }} /> ) : ( ); } const style = StyleSheet.create({ checkBox: { height: "100%", justifyContent: "center", marginRight: rpx(16), }, }); ================================================ FILE: src/pages/musicListEditor/index.tsx ================================================ import AppBar from "@/components/base/appBar"; import StatusBar from "@/components/base/statusBar"; import VerticalSafeAreaView from "@/components/base/verticalSafeAreaView"; import globalStyle from "@/constants/globalStyle"; import i18n from "@/core/i18n"; import { useParams } from "@/core/router"; import { useSetAtom } from "jotai"; import React, { useEffect } from "react"; import Body from "./components/body"; import Bottom from "./components/bottom"; import { editingMusicListAtom, musicListChangedAtom } from "./store/atom"; export default function MusicListEditor() { const { musicSheet, musicList } = useParams<"music-list-editor">(); const setEditingMusicList = useSetAtom(editingMusicListAtom); const setMusicListChanged = useSetAtom(musicListChangedAtom); useEffect(() => { setEditingMusicList( (musicList ?? []).map(_ => ({ musicItem: _, checked: false })), ); return () => { setEditingMusicList([]); setMusicListChanged(false); }; }, []); return ( {musicSheet?.title ?? i18n.t("common.sheet")} ); } ================================================ FILE: src/pages/musicListEditor/store/atom.ts ================================================ import { atom } from "jotai"; export interface IEditorMusicItem { musicItem: IMusic.IMusicItem; checked?: boolean; } /** 编辑页中的音乐条目 */ const editingMusicListAtom = atom([]); /** 是否变动过 */ const musicListChangedAtom = atom(false); export { editingMusicListAtom, musicListChangedAtom }; ================================================ FILE: src/pages/permissions/index.tsx ================================================ import AppBar from "@/components/base/appBar"; import ListItem from "@/components/base/listItem"; import StatusBar from "@/components/base/statusBar"; import ThemeSwitch from "@/components/base/switch"; import ThemeText from "@/components/base/themeText"; import VerticalSafeAreaView from "@/components/base/verticalSafeAreaView"; import globalStyle from "@/constants/globalStyle"; import { useI18N } from "@/core/i18n"; import LyricUtil from "@/native/lyricUtil"; import NativeUtils from "@/native/utils"; import rpx from "@/utils/rpx"; import React, { useEffect, useRef, useState } from "react"; import { AppState, StyleSheet } from "react-native"; type IPermissionTypes = "floatingWindow" | "fileStorage"; export default function Permissions() { const appState = useRef(AppState.currentState); const [permissions, setPermissions] = useState< Record >({ floatingWindow: false, fileStorage: false, // background: false, }); const { t } = useI18N(); async function checkPermission(type?: IPermissionTypes) { let newPermission = { ...permissions, }; if (!type || type === "floatingWindow") { const hasPermission = await LyricUtil.checkSystemAlertPermission(); newPermission.floatingWindow = hasPermission; } if (!type || type === "fileStorage") { const hasPermission = await NativeUtils.checkStoragePermission(); console.log("HAS", hasPermission); newPermission.fileStorage = hasPermission; } // if (!type || type === 'background') { // } setPermissions(newPermission); } useEffect(() => { checkPermission(); const subscription = AppState.addEventListener( "change", nextAppState => { if ( appState.current.match(/inactive|background/) && nextAppState === "active" ) { checkPermission(); } appState.current = nextAppState; }, ); return () => { subscription.remove(); }; }, []); return ( {t("permissionSetting.title")} {t("permissionSetting.description")} { LyricUtil.requestSystemAlertPermission(); }}> { NativeUtils.requestStoragePermission(); }}> {/* */} ); } const styles = StyleSheet.create({ description: { width: "100%", paddingHorizontal: rpx(24), marginVertical: rpx(36), }, }); ================================================ FILE: src/pages/pluginSheetDetail/hooks/usePluginSheetMusicList.ts ================================================ import { RequestStateCode } from "@/constants/commonConst"; import PluginManager from "@/core/pluginManager"; import { useCallback, useEffect, useRef, useState } from "react"; export default function usePluginSheetMusicList( originalSheetItem: IMusic.IMusicSheetItem | null, ) { const currentPageRef = useRef(1); const [requestState, setRequestState] = useState(RequestStateCode.IDLE); const [sheetItem, setSheetItem] = useState( originalSheetItem, ); const [musicList, setMusicList] = useState( originalSheetItem?.musicList ?? [], ); const getSheetDetail = useCallback( async function () { // 加载中:直接退出 if (originalSheetItem === null || requestState === RequestStateCode.FINISHED || requestState === RequestStateCode.PENDING_FIRST_PAGE || requestState === RequestStateCode.PENDING_REST_PAGE) { return; } try { if (currentPageRef.current === 1) { setRequestState(RequestStateCode.PENDING_FIRST_PAGE); } else { setRequestState(RequestStateCode.PENDING_REST_PAGE); } const result = await PluginManager.getByMedia( originalSheetItem as any, )?.methods?.getMusicSheetInfo?.( originalSheetItem, currentPageRef.current, ); if (!result) { throw new Error(); } if (result?.sheetItem) { setSheetItem(prev => ({ ...(prev ?? {}), ...(result.sheetItem as IMusic.IMusicSheetItem), platform: originalSheetItem.platform, })); } if (result?.musicList) { setMusicList(prev => { if (currentPageRef.current === 1) { return result?.musicList ?? prev; } else { return [...prev, ...(result.musicList ?? [])]; } }); } if (result.isEnd) { setRequestState(RequestStateCode.FINISHED); } else { setRequestState(RequestStateCode.PARTLY_DONE); } currentPageRef.current += 1; } catch { setRequestState(RequestStateCode.ERROR); } }, [requestState], ); useEffect(() => { getSheetDetail(); }, []); return [requestState, sheetItem, musicList, getSheetDetail] as const; } ================================================ FILE: src/pages/pluginSheetDetail/index.tsx ================================================ import React from "react"; import MusicSheetPage from "@/components/musicSheetPage"; import { useParams } from "@/core/router"; import usePluginSheetMusicList from "./hooks/usePluginSheetMusicList"; import i18n from "@/core/i18n"; export default function PluginSheetDetail() { const { sheetInfo } = useParams<"plugin-sheet-detail">(); const [requestState, sheetItem, musicList, getSheetDetail] = usePluginSheetMusicList(sheetInfo as IMusic.IMusicSheetItem); return ( ); } ================================================ FILE: src/pages/recommendSheets/components/body/index.tsx ================================================ import NoPlugin from "@/components/base/noPlugin"; import { fontWeightConst } from "@/constants/uiConst"; import { useI18N } from "@/core/i18n"; import PluginManager from "@/core/pluginManager"; import useColors from "@/hooks/useColors"; import rpx, { vw } from "@/utils/rpx"; import React, { useState } from "react"; import { Text } from "react-native"; import { TabBar, TabView } from "react-native-tab-view"; import SheetBody from "./sheetBody"; export default function Body() { const [index, setIndex] = useState(0); const colors = useColors(); const routes = PluginManager.getSortedPluginsWithAbility("getRecommendSheetsByTag").map( _ => ({ key: _.hash, title: _.name, }), ); const { t } = useI18N(); const renderTabBar = (_: any) => ( ( {route.title ?? `(${t("common.unknownName")})`} )} indicatorStyle={{ backgroundColor: colors.primary, height: rpx(4), }} /> ); if (!routes?.length) { return ; } return ( { return ; }} onIndexChange={setIndex} initialLayout={{ width: vw(100) }} /> ); } ================================================ FILE: src/pages/recommendSheets/components/body/sheetBody.tsx ================================================ import React, { memo, useMemo, useState } from "react"; import { StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import globalStyle from "@/constants/globalStyle"; import { ScrollView } from "react-native-gesture-handler"; import TypeTag from "../../../../components/base/typeTag"; import useRecommendList from "../../hooks/useRecommendListTags"; import SheetList from "./sheetList"; import { hidePanel, showPanel } from "@/components/panels/usePanel"; import { useI18N } from "@/core/i18n"; interface IProps { hash: string; } function SheetBody(props: IProps) { const { hash } = props; const { t } = useI18N(); const defaultTag: ICommon.IUnique = useMemo(() => ({ title: t("common.default"), id: "", }), [t]); // 选中的tag const [selectedTag, setSelectedTag] = useState(defaultTag); // 第一个tag const [firstTag, setFirstTag] = useState(defaultTag); // 所有tag const tags = useRecommendList(hash); return ( { // 拉起浮层 showPanel("SheetTags", { tags: tags?.data ?? [], onTagPressed(tag) { setSelectedTag(tag); setFirstTag(tag); hidePanel(); }, }); }} /> {(tags?.pinned ?? []).map(_ => ( { setSelectedTag(_); }} /> ))} ); } export default memo(SheetBody, (prev, curr) => prev.hash === curr.hash); const style = StyleSheet.create({ headerWrapper: { height: rpx(100), flexGrow: 0, }, header: { height: rpx(100), alignItems: "center", }, }); ================================================ FILE: src/pages/recommendSheets/components/body/sheetList.tsx ================================================ import React, { memo, useCallback } from "react"; import rpx from "@/utils/rpx"; import { FlashList } from "@shopify/flash-list"; import useRecommendSheets from "../../hooks/useRecommendSheets"; import SheetItem from "@/components/mediaItem/sheetItem"; import useOrientation from "@/hooks/useOrientation"; import ListEmpty from "@/components/base/listEmpty"; import ListFooter from "@/components/base/listFooter"; interface ISheetListProps { tag: ICommon.IUnique; pluginHash: string; } function SheetList(props: ISheetListProps) { const { tag, pluginHash } = props ?? {}; const [query, sheets, status] = useRecommendSheets(pluginHash, tag); function renderItem({ item }: { item: IMusic.IMusicSheetItemBase }) { return ; } const orientation = useOrientation(); const keyExtractor = useCallback( (item: any, i: number) => `${i}-${item.platform}-${item.id}`, [], ); return ( } ListFooterComponent={ sheets.length ? : null } onEndReached={() => { query(); }} onEndReachedThreshold={0.1} estimatedItemSize={rpx(306)} numColumns={orientation === "vertical" ? 3 : 4} renderItem={renderItem} data={sheets} keyExtractor={keyExtractor} /> ); } export default memo( SheetList, (prev, curr) => prev.tag.id === curr.tag.id && prev.pluginHash === curr.pluginHash, ); ================================================ FILE: src/pages/recommendSheets/hooks/useRecommendListTags.ts ================================================ import PluginManager from "@/core/pluginManager"; import { useCallback, useEffect, useState } from "react"; export default function (hash: string) { const [tags, setTags] = useState(null); const query = useCallback(async () => { const plugin = PluginManager.getByHash(hash); if (plugin) { try { const result = await plugin.methods?.getRecommendSheetTags?.(); if (!result) { throw new Error(); } setTags(result); } catch { setTags(null); } } }, []); useEffect(() => { query(); }, []); return tags; } ================================================ FILE: src/pages/recommendSheets/hooks/useRecommendSheets.ts ================================================ import { RequestStateCode } from "@/constants/commonConst"; import PluginManager from "@/core/pluginManager"; import { resetMediaItem } from "@/utils/mediaUtils"; import { useCallback, useEffect, useRef, useState } from "react"; export default function (pluginHash: string, tag: ICommon.IUnique) { const [sheets, setSheets] = useState([]); const [requestState, setRequestState] = useState(RequestStateCode.IDLE); const currentTagRef = useRef(); const pageRef = useRef(0); const query = useCallback(async () => { if ( (requestState === RequestStateCode.FINISHED || requestState === RequestStateCode.PENDING_FIRST_PAGE || requestState === RequestStateCode.PENDING_REST_PAGE) && currentTagRef.current === tag.id ) { return; } try { if (currentTagRef.current !== tag.id) { setSheets([]); pageRef.current = 0; } pageRef.current++; currentTagRef.current = tag.id; const plugin = PluginManager.getByHash(pluginHash); if (plugin) { if (pageRef.current === 1) { setRequestState(RequestStateCode.PENDING_FIRST_PAGE); } else { setRequestState(RequestStateCode.PENDING_REST_PAGE); } const res = await plugin.methods?.getRecommendSheetsByTag?.( tag, pageRef.current, ); if (res.isEnd) { setRequestState(RequestStateCode.FINISHED); } else { setRequestState(RequestStateCode.PARTLY_DONE); } if (tag.id === currentTagRef.current) { setSheets(prev => [ ...prev, ...res.data!.map(item => resetMediaItem(item, plugin.instance.platform), ), ]); } } else { setRequestState(RequestStateCode.FINISHED); setSheets([]); } } catch { setRequestState(RequestStateCode.ERROR); } }, [tag, requestState]); useEffect(() => { query(); }, [tag]); return [query, sheets, requestState] as const; } ================================================ FILE: src/pages/recommendSheets/index.tsx ================================================ import AppBar from "@/components/base/appBar"; import StatusBar from "@/components/base/statusBar"; import VerticalSafeAreaView from "@/components/base/verticalSafeAreaView"; import MusicBar from "@/components/musicBar"; import globalStyle from "@/constants/globalStyle"; import { useI18N } from "@/core/i18n"; import React from "react"; import Body from "./components/body"; export default function RecommendSheets() { const { t } = useI18N(); return ( {t("recommendSheet.title")} ); } ================================================ FILE: src/pages/searchMusicList/index.tsx ================================================ import AppBar from "@/components/base/appBar"; import Input from "@/components/base/input"; import StatusBar from "@/components/base/statusBar"; import VerticalSafeAreaView from "@/components/base/verticalSafeAreaView"; import MusicBar from "@/components/musicBar"; import globalStyle from "@/constants/globalStyle"; import { fontSizeConst } from "@/constants/uiConst"; import { useI18N } from "@/core/i18n"; import { useParams } from "@/core/router"; import useColors from "@/hooks/useColors"; import rpx from "@/utils/rpx"; import React, { useState } from "react"; import { StyleSheet } from "react-native"; import SearchResult from "./searchResult"; function filterMusic(query: string, musicList: IMusic.IMusicItem[]) { if (query?.length === 0) { return musicList; } return musicList.filter(_ => `${_.title} ${_.artist} ${_.album} ${_.platform}` .toLowerCase() .includes(query.toLowerCase()), ); } export default function SearchMusicList() { const { musicList, musicSheet } = useParams<"search-music-list">(); const [result, setResult] = useState(musicList ?? []); const [query, setQuery] = useState(""); const colors = useColors(); const { t } = useI18N(); const onChangeSearch = (_: string) => { setQuery(_); // useTransition做优化 setResult(filterMusic(_.trim(), musicList ?? [])); }; return ( ); } const style = StyleSheet.create({ appbar: { shadowColor: "transparent", backgroundColor: "#2b333eaa", }, searchBar: { minWidth: rpx(375), flex: 1, borderRadius: rpx(64), height: rpx(64), fontSize: rpx(32), }, input: { padding: 0, color: "#666666", height: rpx(64), fontSize: fontSizeConst.subTitle, textAlignVertical: "center", includeFontPadding: false, }, }); ================================================ FILE: src/pages/searchMusicList/searchResult.tsx ================================================ import React from "react"; import MusicItem from "@/components/mediaItem/musicItem"; import Empty from "@/components/base/empty"; import { FlashList } from "@shopify/flash-list"; import rpx from "@/utils/rpx.ts"; interface ISearchResultProps { result: IMusic.IMusicItem[]; musicSheet?: IMusic.IMusicSheetItem; } const ITEM_HEIGHT = rpx(120); export default function SearchResult(props: ISearchResultProps) { const { result, musicSheet } = props; return ( } data={result} renderItem={({ item }) => ( )} /> ); } ================================================ FILE: src/pages/searchPage/common/historySearch.ts ================================================ import { getStorage, setStorage } from "@/utils/storage"; export async function getHistory() { return (await getStorage("history-search")) ?? []; } export async function addHistory(query: string) { let searchList = await getHistory(); searchList = [query].concat(searchList.filter((_: string) => _ !== query)); await setStorage("history-search", searchList); } export async function removeHistory(query: string) { let searchList = await getHistory(); searchList = searchList.filter((_: string) => _ !== query); await setStorage("history-search", searchList); } export async function removeAllHistory() { await setStorage("history-search", []); } ================================================ FILE: src/pages/searchPage/components/historyPanel.tsx ================================================ import React, { useEffect, useState } from "react"; import { ScrollView, StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import Loading from "@/components/base/loading"; import Chip from "@/components/base/chip"; import useSearch from "../hooks/useSearch"; import { addHistory, getHistory, removeAllHistory, removeHistory, } from "../common/historySearch"; import { useSetAtom } from "jotai"; import { PageStatus, initSearchResults, pageStatusAtom, queryAtom, searchResultsAtom, } from "../store/atoms"; import ThemeText from "@/components/base/themeText"; import Button from "@/components/base/textButton.tsx"; import Empty from "@/components/base/empty"; import { useI18N } from "@/core/i18n"; export default function () { const [history, setHistory] = useState(null); const search = useSearch(); const setQuery = useSetAtom(queryAtom); const setPageStatus = useSetAtom(pageStatusAtom); const setSearchResultsState = useSetAtom(searchResultsAtom); const { t } = useI18N(); useEffect(() => { getHistory().then(setHistory); }, []); return ( {history === null ? ( ) : ( <> {t("searchPage.history")} {history.length ? ( history.map(_ => ( { await removeHistory(_); getHistory().then(setHistory); }} onPress={() => { setSearchResultsState( initSearchResults, ); setPageStatus(PageStatus.SEARCHING); search(_, 1); addHistory(_); setQuery(_); }}> {_} )) ) : ( )} )} ); } const style = StyleSheet.create({ wrapper: { width: "100%", maxWidth: "100%", flexDirection: "column", padding: rpx(24), flex: 1, }, header: { width: "100%", flexDirection: "row", paddingVertical: rpx(28), justifyContent: "space-between", alignItems: "center", }, historyContent: { width: "100%", flex: 1, }, historyContentConainer: { flexDirection: "row", flexWrap: "wrap", }, chip: { flexGrow: 0, marginRight: rpx(24), marginBottom: rpx(24), }, }); ================================================ FILE: src/pages/searchPage/components/navBar.tsx ================================================ import AppBar from "@/components/base/appBar"; import Icon from "@/components/base/icon.tsx"; import IconButton from "@/components/base/iconButton"; import Input from "@/components/base/input"; import Button from "@/components/base/textButton.tsx"; import { iconSizeConst } from "@/constants/uiConst"; import { useI18N } from "@/core/i18n"; import useColors from "@/hooks/useColors"; import rpx from "@/utils/rpx"; import Color from "color"; import { useAtom, useSetAtom } from "jotai"; import React from "react"; import { StyleSheet, View } from "react-native"; import { addHistory } from "../common/historySearch"; import useSearch from "../hooks/useSearch"; import { PageStatus, initSearchResults, pageStatusAtom, queryAtom, searchResultsAtom, } from "../store/atoms"; export default function NavBar() { const search = useSearch(); const [query, setQuery] = useAtom(queryAtom); const setPageStatus = useSetAtom(pageStatusAtom); const colors = useColors(); const setSearchResultsState = useSetAtom(searchResultsAtom); const { t } = useI18N(); const onSearchSubmit = async () => { if (query === "") { return; } setSearchResultsState(initSearchResults); setPageStatus(prev => prev === PageStatus.EDITING ? PageStatus.SEARCHING : prev, ); await search(query, 1); await addHistory(query); }; const hintTextColor = Color(colors.text).alpha(0.6).toString(); return ( { setPageStatus(PageStatus.EDITING); }} placeholderTextColor={hintTextColor} placeholder={t("searchPage.searchPlaceHolder")} onSubmitEditing={onSearchSubmit} onChangeText={_ => { if (_ === "") { setPageStatus(PageStatus.EDITING); } setQuery(_); }} value={query} /> {query.length ? ( { setQuery(""); setPageStatus(PageStatus.EDITING); }} color={hintTextColor} name="x-mark" /> ) : null} ); } const style = StyleSheet.create({ appbar: { paddingRight: 0, }, button: { paddingHorizontal: rpx(24), height: "100%", justifyContent: "center", flexDirection: "row", alignItems: "center", }, searchBarContainer: { flex: 1, flexDirection: "row", alignItems: "center", }, searchBar: { minWidth: rpx(375), flex: 1, paddingHorizontal: rpx(64), borderRadius: rpx(64), height: rpx(64), maxHeight: rpx(64), alignItems: "center", }, magnify: { position: "absolute", left: rpx(16), zIndex: 100, }, close: { position: "absolute", right: rpx(16), }, }); ================================================ FILE: src/pages/searchPage/components/resultPanel/index.tsx ================================================ /** * 搜索结果面板 一级页 */ import React, { memo, useState } from "react"; import { Text } from "react-native"; import rpx, { vw } from "@/utils/rpx"; import { SceneMap, TabBar, TabView } from "react-native-tab-view"; import ResultSubPanel from "./resultSubPanel"; import results from "./results"; import { fontWeightConst } from "@/constants/uiConst"; import useColors from "@/hooks/useColors"; import { useI18N } from "@/core/i18n"; const routes = results; const getRouterScene = ( routes: Array<{ key: ICommon.SupportMediaType; title: string }>, ) => { const scene: Record JSX.Element> = {}; routes.forEach(r => { scene[r.key] = () => ; }); return SceneMap(scene); }; const renderScene = getRouterScene(routes); function ResultPanel() { const [index, setIndex] = useState(0); const colors = useColors(); const { t } = useI18N(); return ( ( ( {route.i18nKey ? t(route.i18nKey as any) : route.title} )} indicatorStyle={{ backgroundColor: colors.primary, height: rpx(4), }} /> )} renderScene={renderScene} onIndexChange={setIndex} initialLayout={{ width: vw(100) }} /> ); } export default memo(ResultPanel); ================================================ FILE: src/pages/searchPage/components/resultPanel/resultSubPanel.tsx ================================================ import Empty from "@/components/base/empty"; import { fontWeightConst } from "@/constants/uiConst"; import { useI18N } from "@/core/i18n"; import PluginManager from "@/core/pluginManager"; import useColors from "@/hooks/useColors"; import rpx, { vw } from "@/utils/rpx"; import { useAtomValue } from "jotai"; import React, { memo, useEffect, useMemo, useRef, useState } from "react"; import { Text } from "react-native"; import { SceneMap, TabBar, TabView } from "react-native-tab-view"; import { searchResultsAtom } from "../../store/atoms"; import { renderMap } from "./results"; import DefaultResults from "./results/defaultResults"; import ResultWrapper from "./resultWrapper"; interface IResultSubPanelProps { tab: ICommon.SupportMediaType; } // 展示结果的视图 function getResultComponent( tab: ICommon.SupportMediaType, pluginHash: string, pluginName: string, ) { return tab in renderMap ? memo( () => { const searchResults = useAtomValue(searchResultsAtom); const pluginSearchResult = searchResults[tab][pluginHash]; const pluginSearchResultRef = useRef(pluginSearchResult); useEffect(() => { pluginSearchResultRef.current = pluginSearchResult; }, [pluginSearchResult]); return ( ); }, () => true, ) : () => ; } /** 结果scene */ function getSubRouterScene( tab: ICommon.SupportMediaType, routes: Array<{ key: string; title: string }>, ) { const scene: Record = {}; routes.forEach(r => { // todo: 是否声明不可搜索 scene[r.key] = getResultComponent(tab, r.key, r.title); }); return SceneMap(scene); } function ResultSubPanel(props: IResultSubPanelProps) { const [index, setIndex] = useState(0); const colors = useColors(); const { t } = useI18N(); const routes = PluginManager.getSortedSearchablePlugins(props.tab).map( _ => ({ key: _.hash, title: _.name, }), ); const renderScene = useMemo( () => getSubRouterScene(props.tab, routes), [props.tab], ); if (!routes.length) { return ; } return ( ( null} pressColor="transparent" renderLabel={({ route, focused, color }) => ( {route.title ?? `(${t("common.unknownName")})`} )} /> )} renderScene={renderScene} onIndexChange={setIndex} initialLayout={{ width: vw(100) }} /> ); } // 不然会一直重新渲染 export default memo(ResultSubPanel); ================================================ FILE: src/pages/searchPage/components/resultPanel/resultWrapper.tsx ================================================ import ListEmpty from "@/components/base/listEmpty"; import ListFooter from "@/components/base/listFooter"; import Loading from "@/components/base/loading"; import { RequestStateCode } from "@/constants/commonConst"; import useOrientation from "@/hooks/useOrientation"; import rpx from "@/utils/rpx"; import { FlashList } from "@shopify/flash-list"; import { useAtomValue } from "jotai"; import React, { memo, useCallback, useEffect, useState } from "react"; import useSearch from "../../hooks/useSearch"; import { ISearchResult, queryAtom } from "../../store/atoms"; import { renderMap } from "./results"; interface IResultWrapperProps< T extends ICommon.SupportMediaType = ICommon.SupportMediaType, > { tab: T; pluginHash: string; pluginName: string; searchResult: ISearchResult; pluginSearchResultRef: React.MutableRefObject>; } function ResultWrapper(props: IResultWrapperProps) { const { tab, pluginHash, searchResult, pluginSearchResultRef } = props; const search = useSearch(); const [searchState, setSearchState] = useState( searchResult?.state ?? RequestStateCode.IDLE, ); const orientation = useOrientation(); const query = useAtomValue(queryAtom); const ResultComponent = renderMap[tab]!; const data: any = searchResult?.data ?? []; const keyExtractor = useCallback( (item: any, i: number) => `${i}-${item.platform}-${item.id}`, [], ); useEffect(() => { if (searchState === RequestStateCode.IDLE) { search(query, 1, tab, pluginHash); } }, []); useEffect(() => { setSearchState(searchResult?.state ?? RequestStateCode.IDLE); }, [searchResult]); const renderItem = ({ item, index }: any) => ( ); return searchState === RequestStateCode.PENDING_FIRST_PAGE ? ( ) : ( { search(query, 1, tab, pluginHash); }} />} ListFooterComponent={data?.length ? { search(query, undefined, tab, pluginHash); }} /> : null} data={data} refreshing={false} onRefresh={() => { search(query, 1, tab, pluginHash); }} onEndReached={() => { (searchState === RequestStateCode.PARTLY_DONE || searchState === RequestStateCode.IDLE) && search(undefined, undefined, tab, pluginHash); }} estimatedItemSize={tab === "sheet" ? rpx(306) : rpx(120)} numColumns={ tab === "sheet" ? (orientation === "vertical" ? 3 : 4) : 1 } renderItem={renderItem} keyExtractor={keyExtractor} /> ); } export default memo(ResultWrapper); ================================================ FILE: src/pages/searchPage/components/resultPanel/results/albumResultItem.tsx ================================================ import React from "react"; import AlbumItem from "@/components/mediaItem/albumItem"; interface IAlbumResultsProps { item: IAlbum.IAlbumItem; index: number; } export default function AlbumResultItem(props: IAlbumResultsProps) { const { item: albumItem } = props; return ; } ================================================ FILE: src/pages/searchPage/components/resultPanel/results/artistResultItem.tsx ================================================ import React from "react"; import ListItem from "@/components/base/listItem"; import { ImgAsset } from "@/constants/assetsConst"; import { ROUTE_PATH, useNavigate } from "@/core/router"; import TitleAndTag from "@/components/mediaItem/titleAndTag"; import { useI18N } from "@/core/i18n"; interface IArtistResultsProps { item: IArtist.IArtistItem; index: number; pluginHash: string; } export default function ArtistResultItem(props: IArtistResultsProps) { const { item: artistItem, pluginHash } = props; const navigate = useNavigate(); const { t } = useI18N(); return ( { navigate(ROUTE_PATH.ARTIST_DETAIL, { artistItem: artistItem, pluginHash, }); }}> } /> ); } ================================================ FILE: src/pages/searchPage/components/resultPanel/results/defaultResults.tsx ================================================ import React from "react"; import { StyleSheet, Text, View } from "react-native"; import rpx from "@/utils/rpx"; import i18n from "@/core/i18n"; export default function DefaultResults() { return ( {i18n.t("searchPage.comingSoon")} ); } const style = StyleSheet.create({ wrapper: { width: rpx(750), }, }); ================================================ FILE: src/pages/searchPage/components/resultPanel/results/index.ts ================================================ import React from "react"; import AlbumResultItem from "./albumResultItem"; import ArtistResultItem from "./artistResultItem"; import MusicResultItem from "./musicResultItem"; import MusicSheetResultItem from "./musicSheetResultItem"; const results: Array<{ key: ICommon.SupportMediaType; i18nKey?: string; title: string; component: React.FC; }> = [ { key: "music", i18nKey: "common.singleMusic", title: "单曲", component: MusicResultItem, }, { key: "album", i18nKey: "common.album", title: "专辑", component: AlbumResultItem, }, { key: "artist", i18nKey: "common.artist", title: "作者", component: ArtistResultItem, }, { key: "sheet", i18nKey: "common.sheet", title: "歌单", component: MusicSheetResultItem, }, ]; const renderMap: Partial>> = {}; results.forEach(_ => (renderMap[_.key] = _.component)); export default results; export { renderMap }; ================================================ FILE: src/pages/searchPage/components/resultPanel/results/musicResultItem.tsx ================================================ import React from "react"; import MusicItem from "@/components/mediaItem/musicItem"; import Config from "@/core/appConfig"; import { ISearchResult } from "@/pages/searchPage/store/atoms"; import TrackPlayer from "@/core/trackPlayer"; interface IMusicResultsProps { item: IMusic.IMusicItem; index: number; pluginSearchResultRef: React.MutableRefObject>; } export default function MusicResultItem(props: IMusicResultsProps) { const { item: musicItem, pluginSearchResultRef } = props; return ( { const clickBehavior = Config.getConfig( "basic.clickMusicInSearch", ); if (clickBehavior === "playMusicAndReplace") { TrackPlayer.playWithReplacePlayList( musicItem, (pluginSearchResultRef?.current?.data ?? [ musicItem, ]) as IMusic.IMusicItem[], ); } else { TrackPlayer.play(musicItem); } }} /> ); } ================================================ FILE: src/pages/searchPage/components/resultPanel/results/musicSheetResultItem.tsx ================================================ import React from "react"; import SheetItem from "@/components/mediaItem/sheetItem"; interface IMusicSheetResultItemProps { item: IMusic.IMusicSheetItem; pluginHash: string; } export default function MusicSheetResultItem( props: IMusicSheetResultItemProps, ) { const { item, pluginHash } = props; return ; } ================================================ FILE: src/pages/searchPage/hooks/useSearch.ts ================================================ import { devLog, errorLog, trace } from "@/utils/log"; import { RequestStateCode } from "@/constants/commonConst"; import { produce } from "immer"; import { getDefaultStore, useAtom, useSetAtom } from "jotai"; import { useCallback, useRef } from "react"; import { PageStatus, pageStatusAtom, searchResultsAtom } from "../store/atoms"; import PluginManager, { Plugin } from "@/core/pluginManager"; export default function useSearch() { const setPageStatus = useSetAtom(pageStatusAtom); const [searchResults, setSearchResults] = useAtom(searchResultsAtom); // 当前正在搜索 const currentQueryRef = useRef(""); /** * query: 搜索词 * queryPage: 搜索页码 * type: 搜索类型 * pluginHash: 搜索条件 */ const search = useCallback( async function ( query?: string, queryPage?: number, type?: ICommon.SupportMediaType, pluginHash?: string, ) { /** 如果没有指定插件,就用所有插件搜索 */ let plugins: Plugin[] = []; if (pluginHash) { const tgtPlugin = PluginManager.getByHash(pluginHash); tgtPlugin && (plugins = [tgtPlugin]); } else { plugins = PluginManager.getSearchablePlugins(); } if (plugins.length === 0) { setPageStatus(PageStatus.NO_PLUGIN); return; } // 使用选中插件搜素 plugins.forEach(async plugin => { const _platform = plugin.instance.platform; const _hash = plugin.hash; if (!_platform || !_hash) { // 插件无效,此时直接进入结果页 setPageStatus(PageStatus.RESULT); return; } const searchType = type ?? plugin.instance.defaultSearchType ?? "music"; // 上一份搜索结果 const prevPluginResult = searchResults[searchType][plugin.hash]; /** 上一份搜索还没返回/已经结束 */ if ( (prevPluginResult?.state === RequestStateCode.PENDING_REST_PAGE || prevPluginResult?.state === RequestStateCode.FINISHED) && undefined === query ) { return; } // 是否是一次新的搜索 const newSearch = query || prevPluginResult?.page === undefined || queryPage === 1; // 本次搜索关键词 currentQueryRef.current = query = query ?? prevPluginResult?.query ?? ""; /** 搜索的页码 */ const page = queryPage ?? newSearch ? 1 : (prevPluginResult?.page ?? 0) + 1; trace("开始搜索", { _platform, query, page, searchType, }); try { setSearchResults( produce(draft => { const prevMediaResult: any = draft[searchType]; prevMediaResult[_hash] = { state: newSearch ? RequestStateCode.PENDING_FIRST_PAGE : RequestStateCode.PENDING_REST_PAGE, // @ts-ignore data: newSearch ? [] : prevMediaResult[_hash]?.data ?? [], query: query, page, }; }), ); // !! jscore的promise有问题,改成hermes就好了,可能和JIT有关,不知道。 const result = await plugin?.methods?.search?.( query, page, searchType, ); /** 如果搜索结果不是本次结果 */ if (currentQueryRef.current !== query) { return; } /** 切换到结果页 */ const currentPageStatus = getDefaultStore().get(pageStatusAtom); if (currentPageStatus !== PageStatus.EDITING) { setPageStatus(PageStatus.RESULT); } if (!result) { throw new Error("搜索结果为空"); } setSearchResults( produce(draft => { const prevMediaResult = draft[searchType]; const prevPluginResult: any = prevMediaResult[ _hash ] ?? { data: [], }; const currResult = result.data ?? []; prevMediaResult[_hash] = { state: result?.isEnd === false && result?.data?.length ? RequestStateCode.PARTLY_DONE : RequestStateCode.FINISHED, query, page, data: newSearch ? currResult : (prevPluginResult.data ?? []).concat( currResult, ), }; return draft; }), ); } catch (e: any) { errorLog("搜索失败", e?.message); devLog( "error", "搜索失败", `Plugin: ${plugin.name} Query: ${query} Page: ${page}`, e, e?.message, ); const currentPageStatus = getDefaultStore().get(pageStatusAtom); if (currentPageStatus !== PageStatus.EDITING) { setPageStatus(PageStatus.RESULT); } setSearchResults( produce(draft => { const prevMediaResult = draft[searchType]; const prevPluginResult = prevMediaResult[_hash] ?? { data: [], }; prevPluginResult.state = RequestStateCode.ERROR; return draft; }), ); } }); }, [searchResults], ); return search; } ================================================ FILE: src/pages/searchPage/index.tsx ================================================ import React, { useEffect } from "react"; import { StyleSheet, View } from "react-native"; import NavBar from "./components/navBar"; import { useAtom, useSetAtom } from "jotai"; import { PageStatus, initSearchResults, pageStatusAtom, queryAtom, searchResultsAtom, } from "./store/atoms"; import HistoryPanel from "./components/historyPanel"; import ResultPanel from "./components/resultPanel"; import MusicBar from "@/components/musicBar"; import Loading from "@/components/base/loading"; import { SafeAreaView } from "react-native-safe-area-context"; import StatusBar from "@/components/base/statusBar"; import NoPlugin from "../../components/base/noPlugin"; import { useI18N } from "@/core/i18n"; export default function () { const [pageStatus, setPageStatus] = useAtom(pageStatusAtom); const setQuery = useSetAtom(queryAtom); const setSearchResultsState = useSetAtom(searchResultsAtom); const { t } = useI18N(); useEffect(() => { setSearchResultsState(initSearchResults); return () => { setPageStatus(PageStatus.EDITING); setQuery(""); }; }, []); return ( {pageStatus === PageStatus.EDITING && } {pageStatus === PageStatus.SEARCHING && } {pageStatus === PageStatus.RESULT && } {pageStatus === PageStatus.NO_PLUGIN && ( )} ); } const style = StyleSheet.create({ wrapper: { width: "100%", flex: 1, }, flex1: { flex: 1, }, }); ================================================ FILE: src/pages/searchPage/store/atoms.ts ================================================ import { RequestStateCode } from "@/constants/commonConst"; import { atom } from "jotai"; /** 搜索状态 */ export interface ISearchResult { /** 当前页码 */ page?: number; /** 搜索词 */ query?: string; /** 搜索状态 */ state: RequestStateCode; /** 数据 */ data: ICommon.SupportMediaItemBase[T][]; } type ISearchResults< T extends keyof ICommon.SupportMediaItemBase = ICommon.SupportMediaType, > = { [K in T]: Record>; }; /** 初始值 */ export const initSearchResults: ISearchResults = { music: {}, album: {}, artist: {}, sheet: {}, lyric: {}, }; /** key: pluginhash value: searchResult */ const searchResultsAtom = atom(initSearchResults); export enum PageStatus { /** 编辑中 */ EDITING = "EDITING", /** 搜索中 */ SEARCHING = "SEARCHING", /** 有结果 */ RESULT = "RESULT", /** 没有安装插件 */ NO_PLUGIN = "NO_PLUGIN", } /** 当前正在搜索的 */ const pageStatusAtom = atom(PageStatus.EDITING); const queryAtom = atom(""); export { pageStatusAtom, searchResultsAtom, queryAtom }; ================================================ FILE: src/pages/setCustomTheme/body.tsx ================================================ import Image from "@/components/base/image"; import ThemeText from "@/components/base/themeText"; import { showPanel } from "@/components/panels/usePanel"; import { ImgAsset } from "@/constants/assetsConst"; import globalStyle from "@/constants/globalStyle"; import pathConst from "@/constants/pathConst"; import { useI18N } from "@/core/i18n"; import Theme from "@/core/theme"; import { CustomizedColors } from "@/hooks/useColors"; import { grayRate } from "@/utils/colorUtil"; import rpx from "@/utils/rpx"; import Slider from "@react-native-community/slider"; import Color from "color"; import React from "react"; import { StyleSheet, View } from "react-native"; import { copyFile } from "react-native-fs"; import { ScrollView, TouchableOpacity } from "react-native-gesture-handler"; import ImageColors from "react-native-image-colors"; import { launchImageLibrary } from "react-native-image-picker"; export default function Body() { const theme = Theme.useTheme(); const backgroundInfo = Theme.useBackground(); const { t } = useI18N(); async function onImageClick() { try { const result = await launchImageLibrary({ mediaType: "photo", }); const uri = result.assets?.[0].uri; if (!uri) { return; } const bgPath = `${pathConst.dataPath}background${uri.substring( uri.lastIndexOf("."), )}`; await copyFile(uri, bgPath); const colorsResult = await ImageColors.getColors(uri, { fallback: "#ffffff", }); const colors = { primary: colorsResult.platform === "android" ? colorsResult.dominant : colorsResult.platform === "ios" ? colorsResult.primary : colorsResult.vibrant, average: colorsResult.platform === "android" ? colorsResult.average : colorsResult.platform === "ios" ? colorsResult.detail : colorsResult.dominant, vibrant: colorsResult.platform === "android" ? colorsResult.vibrant : colorsResult.platform === "ios" ? colorsResult.secondary : colorsResult.vibrant, }; const primaryGrayRate = grayRate(colors.primary!); let themeColors: Partial; if (primaryGrayRate < -0.4) { const primaryColor = Color(colors.primary!); console.log( colors.primary, primaryGrayRate, primaryColor .whiten(3 * primaryGrayRate) .hex() .toString(), ); themeColors = { appBar: colors.primary, primary: primaryColor .darken(primaryGrayRate * 5) .toString(), musicBar: colors.primary, card: "rgba(0,0,0,0.2)", tabBar: primaryColor.alpha(0.2).toString(), }; } else if (primaryGrayRate > 0.4) { themeColors = { appBar: colors.primary, primary: Color(colors.primary) .darken(primaryGrayRate * 5) .toString(), musicBar: colors.primary, card: "rgba(0,0,0,0.2)", }; } else { // const primaryColor = Color(colors.primary!); themeColors = { appBar: colors.primary, primary: Color(colors.primary) .saturate(Math.abs(primaryGrayRate) * 2 + 2) .toString(), musicBar: colors.primary, card: "rgba(0,0,0,0.2)", }; } Theme.setTheme("custom", { colors: themeColors, background: { url: `file://${bgPath}#${Date.now()}`, }, }); // Config.set('setting.theme.colors', { // primary: primaryColor, // textHighlight: textHighlight, // accent: textHighlight, // }); } catch (e) { console.log(e); } } return ( {t("setCustomTheme.blur")} { Theme.setBackground({ blur: val, }); }} value={backgroundInfo?.blur ?? 20} /> {t("setCustomTheme.opacity")} { Theme.setBackground({ opacity: val, }); }} value={backgroundInfo?.opacity ?? 0.7} /> {Theme.configableColorKey.map(key => ( {t("setCustomTheme." + key + "Color" as any)} { showPanel("ColorPicker", { // @ts-ignore defaultColor: theme.colors[key], onSelected(color) { Theme.setColors({ [key]: color.hexa().toString(), }); }, }); }} style={styles.colorItemBlockContainer}> { /** @ts-ignore */ Color(theme.colors[key]).hexa().toString() } ))} ); } const styles = StyleSheet.create({ container: { width: "100%", flex: 1, }, image: { marginTop: rpx(36), borderRadius: rpx(12), width: rpx(460), height: rpx(690), alignSelf: "center", }, sliderWrapper: { marginTop: rpx(48), width: "100%", paddingHorizontal: rpx(24), flexDirection: "row", justifyContent: "space-between", alignItems: "center", }, slider: { flex: 1, height: rpx(40), }, colorsContainer: { width: "100%", flex: 1, flexDirection: "row", flexWrap: "wrap", marginTop: rpx(48), paddingHorizontal: rpx(24), justifyContent: "space-between", }, colorItem: { flex: 1, flexBasis: "40%", marginBottom: rpx(36), }, colorBlockContainer: { width: rpx(76), height: rpx(50), borderWidth: 1, borderStyle: "solid", borderColor: "#ccc", }, colorBlock: { width: "100%", height: "100%", position: "absolute", top: 0, left: 0, zIndex: 2, }, colorItemBlockContainer: { marginTop: rpx(18), flexDirection: "row", alignItems: "center", }, colorText: { marginLeft: rpx(8), }, transparentBg: { position: "absolute", zIndex: -1, width: "100%", height: "100%", left: 0, top: 0, }, }); ================================================ FILE: src/pages/setCustomTheme/index.tsx ================================================ import React from "react"; import { StyleSheet } from "react-native"; import rpx from "@/utils/rpx"; import AppBar from "@/components/base/appBar"; import VerticalSafeAreaView from "@/components/base/verticalSafeAreaView"; import globalStyle from "@/constants/globalStyle"; import Button from "@/components/base/textButton.tsx"; import Body from "./body"; import { useNavigation } from "@react-navigation/native"; import { useI18N } from "@/core/i18n"; export default function SetCustomTheme() { const navigation = useNavigation(); const { t } = useI18N(); return ( { navigation.goBack(); }} fontColor="appBarText"> {t("common.done")} }> {t("setCustomTheme.customizeBackground")} ); } const styles = StyleSheet.create({ container: { width: rpx(750), }, submit: { justifyContent: "center", }, }); ================================================ FILE: src/pages/setting/index.tsx ================================================ import React from "react"; import { StyleSheet } from "react-native"; import settingTypes from "./settingTypes"; import { SafeAreaView } from "react-native-safe-area-context"; import StatusBar from "@/components/base/statusBar"; import { useParams } from "@/core/router"; import HorizontalSafeAreaView from "@/components/base/horizontalSafeAreaView.tsx"; import AppBar from "@/components/base/appBar"; import { useI18N } from "@/core/i18n"; export default function Setting() { const { type } = useParams<"setting">(); const settingItem = settingTypes[type]; const { t } = useI18N(); return ( {settingItem.showNav === false ? null : ( {t(settingItem.i18nKey as any)} )} {type === "plugin" ? ( ) : ( )} ); } const style = StyleSheet.create({ wrapper: { width: "100%", flex: 1, }, appbar: { shadowColor: "transparent", backgroundColor: "#2b333eaa", }, header: { backgroundColor: "transparent", shadowColor: "transparent", }, }); ================================================ FILE: src/pages/setting/settingTypes/aboutSetting.tsx ================================================ import React from "react"; import { Image, ScrollView, StyleSheet, TouchableOpacity, View, } from "react-native"; import rpx from "@/utils/rpx"; import { ImgAsset } from "@/constants/assetsConst"; import ThemeText from "@/components/base/themeText"; import LinkText from "@/components/base/linkText"; import useCheckUpdate from "@/hooks/useCheckUpdate.ts"; import useOrientation from "@/hooks/useOrientation"; import Divider from "@/components/base/divider"; export default function AboutSetting() { const checkAndShowResult = useCheckUpdate(); const orientation = useOrientation(); return ( { checkAndShowResult(true); }}> 软件作者: 猫头猫 公众号: 【一只猫头猫】 B站:{" "} 不想睡觉猫头猫 小红书:{" "} 一只猫头猫 开发者的话: 软件作者是猫头猫 🐱,不是猫头鹰🦉,也不是什么其他的奇奇怪怪。软件没有其他版本,如果你下载到了付费版/广告版/挂羊头卖狗肉版,那说明你被坏蛋骗了😒。 软件相关信息会发布在公众号【 一只猫头猫 】中👇,也简单做了个 官方网站 。(手机版和桌面版的)下载地址、使用方式、插件开发方式、常见问题都在站点中。 本软件完全免费,并基于{" "} AGPL3.0 协议{" "} 开源,如果需要使用此代码进行二次开发,请遵守如下约定: 1. 二次分发版必须同样遵循 AGPL 3.0 协议,开源且免费 2. 合法合规使用代码,不要用于商业用途; 修改后的软件造成的任何问题由使用此代码的开发者承担 3. 打包、二次分发时请保留代码出处:https://github.com/maotoumao/MusicFree 4. 如果开源协议变更,将在此 Github 仓库更新,不另行通知 代码已开源到{" "} Github ,如果打不开试试把链接中的 github 换成 gitcode。 本软件需要通过插件来完成包括播放、搜索在内的大部分功能,如果你是从第三方下载的插件, 请一定谨慎识别这些插件的安全性,保护好自己。(注意:插件以及插件可能产生的数据与本软件无关,请使用者合理合法使用。) 还请注意本软件只是个人的业余项目,距离稳定版也有很长一段距离。 如果你在找成熟稳定的音乐软件,可以考虑其他优秀的软件。当然我会一直维护,让它变得尽可能的完善一些。业余时间用爱发电,进度慢还请见谅。 如果有问题或者建议,可以直接去 Github issue 区留言,也可以去公众号【一只猫头猫】留言,也可以去{" "} QQ 频道 {" "} 发帖。 开发这个软件的最初目的是自用,顺便分享出来给有需要的人。如果这个软件能对你有些帮助,那这就是 MusicFree 存在的意义。 by: 猫头猫 ); } const style = StyleSheet.create({ wrapper: { width: "100%", flex: 1, }, header: { width: rpx(750), height: rpx(400), justifyContent: "center", alignItems: "center", }, contactContainer: { flexDirection: "row", alignItems: "center", justifyContent: "center", gap: rpx(24), }, horizontalSize: { width: rpx(600), height: "100%", }, image: { width: rpx(150), height: rpx(150), borderRadius: rpx(28), }, margin: { marginTop: rpx(24), }, content: { marginTop: rpx(24), lineHeight: rpx(48), }, wcChannel: { width: rpx(330), height: rpx(330), marginLeft: rpx(210), marginTop: rpx(24), }, scrollView: { flex: 1, paddingHorizontal: rpx(24), paddingVertical: rpx(48), }, scrollViewContainer: { paddingBottom: rpx(96), }, }); ================================================ FILE: src/pages/setting/settingTypes/backupSetting.tsx ================================================ import ListItem, { ListItemHeader } from "@/components/base/listItem"; import Backup from "@/core/backup"; import { ROUTE_PATH, useNavigate } from "@/core/router"; import Toast from "@/utils/toast"; import React from "react"; import { ScrollView, StyleSheet } from "react-native"; import { showDialog } from "@/components/dialogs/useDialog"; import { showPanel } from "@/components/panels/usePanel"; import axios from "axios"; import { ResumeMode } from "@/constants/commonConst.ts"; import Config, { useAppConfig } from "@/core/appConfig"; import { useI18N } from "@/core/i18n"; import delay from "@/utils/delay"; import { writeInChunks } from "@/utils/fileUtils.ts"; import { errorLog } from "@/utils/log.ts"; import { getDocumentAsync } from "expo-document-picker"; import { readAsStringAsync } from "expo-file-system"; import { AuthType, createClient } from "webdav"; export default function BackupSetting() { const { t } = useI18N(); const navigate = useNavigate(); const resumeMode = useAppConfig("backup.resumeMode"); const webdavUrl = useAppConfig("webdav.url"); const webdavUsername = useAppConfig("webdav.username"); const webdavPassword = useAppConfig("webdav.password"); const onBackupToLocal = async () => { navigate(ROUTE_PATH.FILE_SELECTOR, { fileType: "folder", multi: false, actionText: t("backupAndResume.beginBackup"), async onAction(selectedFiles) { const raw = Backup.backup(); const folder = selectedFiles[0]?.path; return new Promise(resolve => { showDialog("LoadingDialog", { title: t("backupAndResume.backupDialogTitle"), loadingText: t("backupAndResume.backuping"), promise: writeInChunks( `${folder}${folder?.endsWith("/") ? "" : "/" }backup.json`, raw, ), onResolve(_, hideDialog) { Toast.success(t("toast.backupSuccess")); hideDialog(); resolve(true); }, onCancel(hideDialog) { hideDialog(); resolve(false); }, onReject(reason, hideDialog) { hideDialog(); resolve(false); console.log(reason); Toast.warn(t("toast.backupFail", { reason: reason?.message ?? reason })); }, }); }); }, }); }; async function onResumeFromLocal() { try { const pickResult = await getDocumentAsync({ copyToCacheDirectory: true, type: "application/json", }); if (pickResult.canceled) { return; } const result = await readAsStringAsync(pickResult.assets[0].uri); return new Promise(resolve => { showDialog("LoadingDialog", { title: t("backupAndResume.resumeFromLocalFile"), loadingText: t("backupAndResume.resuming"), async task() { await delay(300, false); return Backup.resume(result, resumeMode); }, onResolve(_, hideDialog) { Toast.success(t("toast.resumeSuccess")); hideDialog(); resolve(true); }, onCancel(hideDialog) { hideDialog(); resolve(false); }, onReject(reason, hideDialog) { hideDialog(); resolve(false); console.log(reason); Toast.warn(t("toast.resumeFail", { reason: reason?.message ?? reason })); }, }); }); } catch (e: any) { errorLog("恢复失败", e); Toast.warn(t("toast.resumeFail", { reason: e?.message ?? e })); } } async function onResumeFromUrl() { showPanel("SimpleInput", { title: t("backupAndResume.resumeFromUrlDialogTitle"), placeholder: t("backupAndResume.resumeFromUrlDialogPlaceHolder"), maxLength: 1024, async onOk(text, closePanel) { try { const url = text.trim(); if (url.endsWith(".json") || url.endsWith(".txt")) { const raw = (await axios.get(text)).data; await Backup.resume(raw, resumeMode); Toast.success(t("toast.resumeSuccess")); closePanel(); } else { throw "无效的URL"; } } catch (e: any) { Toast.warn(t("toast.resumeFail", { reason: e?.message ?? e })); } }, }); } async function onResumeFromWebdav() { const url = Config.getConfig("webdav.url"); const username = Config.getConfig("webdav.username"); const password = Config.getConfig("webdav.password"); if (!(username && password && url)) { Toast.warn(t("toast.resumePreCheckFailed")); return; } const client = createClient(url, { authType: AuthType.Password, username: username, password: password, }); if (!(await client.exists("/MusicFree/MusicFreeBackup.json"))) { Toast.warn(t("toast.backupFileNotFound")); return; } try { const resumeData = await client.getFileContents( "/MusicFree/MusicFreeBackup.json", { format: "text", }, ); await Backup.resume( resumeData, Config.getConfig("backup.resumeMode"), ); Toast.success(t("toast.resumeSuccess")); } catch (e: any) { Toast.warn(t("toast.resumeFail", { reason: e?.message ?? e })); } } async function onBackupToWebdav() { const username = Config.getConfig("webdav.username"); const password = Config.getConfig("webdav.password"); const url = Config.getConfig("webdav.url"); if (!(username && password && url)) { Toast.warn(t("toast.resumePreCheckFailed")); return; } try { const client = createClient(url, { authType: AuthType.Password, username: username, password: password, }); const raw = Backup.backup(); if (!(await client.exists("/MusicFree"))) { await client.createDirectory("/MusicFree"); } // 临时文件 await client.putFileContents( "/MusicFree/MusicFreeBackup.json", raw, { overwrite: true, }, ); Toast.success(t("toast.backupSuccess")); } catch (e: any) { Toast.warn(t("toast.backupFail", { reason: e?.message ?? e })); } } return ( {t("sidebar.backupAndResume")} { showDialog("RadioDialog", { title: t("backupAndResume.setResumeMode"), content: [ { label: t(("backupAndResume.resumeMode." + ResumeMode.Append) as any), value: ResumeMode.Append, }, { label: t(("backupAndResume.resumeMode." + ResumeMode.OverwriteDefault) as any), value: ResumeMode.OverwriteDefault, }, { label: t(("backupAndResume.resumeMode." + ResumeMode.Overwrite) as any), value: ResumeMode.Overwrite, }, ], onOk(value) { Config.setConfig( "backup.resumeMode", value as any, ); }, }); }}> { t(("backupAndResume.resumeMode." + ((resumeMode as ResumeMode) || ResumeMode.Append)) as any) } {t("backupAndResume.localBackup")} Webdav { showPanel("SetUserVariables", { title: t("backupAndResume.webdavSettings"), initValues: { url: webdavUrl ?? "", username: webdavUsername ?? "", password: webdavPassword ?? "", }, variables: [ { key: "url", name: "URL", hint: t("backupAndResume.webdavUrl"), }, { key: "username", name: t("common.username"), }, { key: "password", name: t("common.password"), }, ], onOk(values, closePanel) { Config.setConfig("webdav.url", values?.url); Config.setConfig("webdav.username", values?.username); Config.setConfig("webdav.password", values?.password); Toast.success(t("toast.saveSuccess")); closePanel(); }, }); }}> ); } const style = StyleSheet.create({ wrapper: { width: "100%", flex: 1, }, }); ================================================ FILE: src/pages/setting/settingTypes/basicSetting.tsx ================================================ import ColorBlock from "@/components/base/colorBlock"; import ListItem from "@/components/base/listItem"; import Paragraph from "@/components/base/paragraph"; import ThemeSwitch from "@/components/base/switch"; import ThemeText from "@/components/base/themeText"; import { showDialog } from "@/components/dialogs/useDialog"; import { showPanel } from "@/components/panels/usePanel"; import { SortType } from "@/constants/commonConst.ts"; import pathConst from "@/constants/pathConst"; import Config, { useAppConfig } from "@/core/appConfig"; import { useI18N } from "@/core/i18n"; import { ROUTE_PATH, useNavigate } from "@/core/router"; import useColors from "@/hooks/useColors"; import LyricUtil, { NativeTextAlignment } from "@/native/lyricUtil"; import { AppConfigPropertyKey } from "@/types/core/config"; import { clearCache, getCacheSize, sizeFormatter } from "@/utils/fileUtils"; import { clearLog, getErrorLogContent } from "@/utils/log"; import { qualityKeys } from "@/utils/qualities"; import rpx from "@/utils/rpx"; import Toast from "@/utils/toast"; import Clipboard from "@react-native-clipboard/clipboard"; import Slider from "@react-native-community/slider"; import React, { useCallback, useEffect, useRef, useState } from "react"; import { SectionList, StyleSheet, TouchableOpacity, View } from "react-native"; import { readdir } from "react-native-fs"; import { FlatList, ScrollView } from "react-native-gesture-handler"; function createSwitch( title: string, changeKey: AppConfigPropertyKey, value: boolean, callback?: (newValue: boolean) => void, ) { const onPress = () => { if (callback) { callback(!value); } else { Config.setConfig(changeKey, !value); } }; return { title, onPress, right: , }; } const createRadio = function ( title: string, changeKey: AppConfigPropertyKey, candidates: Array, value: string | number, valueMap?: Record, onChange?: (value: string | number) => void, ) { const onPress = () => { showDialog("RadioDialog", { title, content: valueMap ? candidates.map(_ => ({ label: valueMap[_] as string, value: _, })) : candidates, onOk(val) { Config.setConfig(changeKey, val); onChange?.(val); }, }); }; return { title, right: ( {valueMap ? valueMap[value] : value} ), onPress, }; }; function useCacheSize() { const [cacheSize, setCacheSize] = useState({ music: 0, lyric: 0, image: 0, }); const refreshCacheSize = useCallback(async () => { const [musicCache, lyricCache, imageCache] = await Promise.all([ getCacheSize("music"), getCacheSize("lyric"), getCacheSize("image"), ]); setCacheSize({ music: musicCache, lyric: lyricCache, image: imageCache, }); }, []); return [cacheSize, refreshCacheSize] as const; } export default function BasicSetting() { const autoPlayWhenAppStart = useAppConfig("basic.autoPlayWhenAppStart"); const useCelluarNetworkPlay = useAppConfig("basic.useCelluarNetworkPlay"); const useCelluarNetworkDownload = useAppConfig("basic.useCelluarNetworkDownload"); const maxDownload = useAppConfig("basic.maxDownload"); const clickMusicInSearch = useAppConfig("basic.clickMusicInSearch"); const clickMusicInAlbum = useAppConfig("basic.clickMusicInAlbum"); const downloadPath = useAppConfig("basic.downloadPath"); const notInterrupt = useAppConfig("basic.notInterrupt"); const tempRemoteDuck = useAppConfig("basic.tempRemoteDuck"); const tempRemoteDuckVolume = useAppConfig("basic.tempRemoteDuckVolume"); const autoStopWhenError = useAppConfig("basic.autoStopWhenError"); const maxCacheSize = useAppConfig("basic.maxCacheSize"); const defaultPlayQuality = useAppConfig("basic.defaultPlayQuality"); const playQualityOrder = useAppConfig("basic.playQualityOrder"); const defaultDownloadQuality = useAppConfig("basic.defaultDownloadQuality"); const downloadQualityOrder = useAppConfig("basic.downloadQualityOrder"); const musicDetailDefault = useAppConfig("basic.musicDetailDefault"); const musicDetailAwake = useAppConfig("basic.musicDetailAwake"); const maxHistoryLen = useAppConfig("basic.maxHistoryLen"); const autoUpdatePlugin = useAppConfig("basic.autoUpdatePlugin"); const notCheckPluginVersion = useAppConfig("basic.notCheckPluginVersion"); const lazyLoadPlugin = useAppConfig("basic.lazyLoadPlugin"); const associateLyricType = useAppConfig("basic.associateLyricType"); const showExitOnNotification = useAppConfig("basic.showExitOnNotification"); const musicOrderInLocalSheet = useAppConfig("basic.musicOrderInLocalSheet"); const tryChangeSourceWhenPlayFail = useAppConfig("basic.tryChangeSourceWhenPlayFail"); const { t } = useI18N(); const debugEnableErrorLog = useAppConfig("debug.errorLog"); const debugEnableTraceLog = useAppConfig("debug.traceLog"); const debugEnableDevLog = useAppConfig("debug.devLog"); const navigate = useNavigate(); const [cacheSize, refreshCacheSize] = useCacheSize(); const sectionListRef = useRef(null); // const titleListRef = useRef(null); useEffect(() => { refreshCacheSize(); }, []); const basicOptions = [ { title: t("basicSettings.common"), data: [ createRadio( t("basicSettings.maxHistoryLength"), "basic.maxHistoryLen", [20, 50, 100, 200, 500], maxHistoryLen ?? 50, ), createRadio( t("basicSettings.musicDetailDefault"), "basic.musicDetailDefault", ["album", "lyric"], musicDetailDefault ?? "album", { album: t("basicSettings.musicDetailDefault.album"), lyric: t("basicSettings.musicDetailDefault.lyric"), }, ), createSwitch( t("basicSettings.musicDetailAwake"), "basic.musicDetailAwake", musicDetailAwake ?? false, ), createRadio( t("basicSettings.associateLyricType"), "basic.associateLyricType", ["input", "search"], associateLyricType ?? "search", { input: t("basicSettings.associateLyricType.input"), search: t("basicSettings.associateLyricType.search"), }, ), createSwitch( t("basicSettings.showExitOnNotification"), "basic.showExitOnNotification", showExitOnNotification ?? false, ), ], }, { title: t("basicSettings.sheetAndAlbum"), data: [ createRadio( t("basicSettings.clickMusicInSearch"), "basic.clickMusicInSearch", ["playMusic", "playMusicAndReplace"], clickMusicInSearch ?? "playMusic", { playMusic: t("basicSettings.clickMusicInSearch.playMusic"), playMusicAndReplace: t("basicSettings.clickMusicInSearch.playMusicAndReplace"), }, ), createRadio( t("basicSettings.clickMusicInAlbum"), "basic.clickMusicInAlbum", ["playMusic", "playAlbum"], clickMusicInAlbum ?? "playAlbum", { playMusic: t("basicSettings.clickMusicInAlbum.playMusic"), playAlbum: t("basicSettings.clickMusicInAlbum.playAlbum"), }, ), createRadio( t("basicSettings.musicDetailDefault"), "basic.musicDetailDefault", ["album", "lyric"], musicDetailDefault ?? "album", { album: t("basicSettings.musicDetailDefault.album"), lyric: t("basicSettings.musicDetailDefault.lyric"), }, ), createRadio( t("basicSettings.musicOrderInLocalSheet"), "basic.musicOrderInLocalSheet", [ SortType.Title, SortType.Artist, SortType.Album, SortType.Newest, SortType.Oldest, ], musicOrderInLocalSheet ?? "end", { [SortType.Title]: t("basicSettings.musicOrderInLocalSheet.title"), [SortType.Artist]: t("basicSettings.musicOrderInLocalSheet.artist"), [SortType.Album]: t("basicSettings.musicOrderInLocalSheet.album"), [SortType.Newest]: t("basicSettings.musicOrderInLocalSheet.newest"), [SortType.Oldest]: t("basicSettings.musicOrderInLocalSheet.oldest"), }, ), ], }, { title: t("basicSettings.plugin"), data: [ createSwitch( t("basicSettings.autoUpdatePlugin"), "basic.autoUpdatePlugin", autoUpdatePlugin ?? false, ), createSwitch( t("basicSettings.notCheckPluginVersion"), "basic.notCheckPluginVersion", notCheckPluginVersion ?? false, ), createSwitch( t("basicSettings.lazyLoadPlugin"), "basic.lazyLoadPlugin", lazyLoadPlugin ?? false, ), ], }, { title: t("basicSettings.playback"), data: [ createSwitch( t("basicSettings.notInterrupt"), "basic.notInterrupt", notInterrupt ?? false, ), createSwitch( t("basicSettings.autoPlayWhenAppStart"), "basic.autoPlayWhenAppStart", autoPlayWhenAppStart ?? false, ), createSwitch( t("basicSettings.tryChangeSourceWhenPlayFail"), "basic.tryChangeSourceWhenPlayFail", tryChangeSourceWhenPlayFail ?? false, ), createSwitch( t("basicSettings.autoStopWhenError"), "basic.autoStopWhenError", autoStopWhenError ?? false, ), createRadio( t("basicSettings.tempRemoteDuck"), "basic.tempRemoteDuck", ["pause", "lowerVolume"], tempRemoteDuck ?? "pause", { pause: t("basicSettings.tempRemoteDuck.pause"), "lowerVolume": t("basicSettings.tempRemoteDuck.lowerVolume"), } ), ...(tempRemoteDuck === "lowerVolume" ? [ createRadio( t("basicSettings.tempRemoteDuck.volumeDecreaseLevel"), "basic.tempRemoteDuckVolume", [0.3, 0.5, 0.8], tempRemoteDuckVolume ?? 0.5, { 0.3: "30%", 0.5: "50%", 0.8: "80%", } ), ] : []), createRadio( t("basicSettings.defaultPlayQuality"), "basic.defaultPlayQuality", qualityKeys, defaultPlayQuality ?? "standard", { low: t("musicQuality.low"), standard: t("musicQuality.standard"), high: t("musicQuality.high"), super: t("musicQuality.super"), }, ), createRadio( t("basicSettings.playQualityOrder"), "basic.playQualityOrder", ["asc", "desc"], playQualityOrder ?? "asc", { asc: t("basicSettings.playQualityOrder.asc"), desc: t("basicSettings.playQualityOrder.desc"), }, ), ], }, { title: t("basicSettings.download"), data: [ { title: t("basicSettings.downloadPath"), right: ( {downloadPath ?? pathConst.downloadMusicPath} ), onPress() { navigate<"file-selector">(ROUTE_PATH.FILE_SELECTOR, { fileType: "folder", multi: false, actionText: t("basicSettings.fileSelector.selectFolder"), async onAction(selectedFiles) { try { const targetDir = selectedFiles[0]; await readdir(targetDir.path); Config.setConfig( "basic.downloadPath", targetDir.path, ); return true; } catch { Toast.warn(t("toast.folderNotExistOrNoPermission")); return false; } }, }); }, }, createRadio( t("basicSettings.maxDownload"), "basic.maxDownload", [1, 3, 5, 7], maxDownload ?? 3, ), createRadio( t("basicSettings.defaultDownloadQuality"), "basic.defaultDownloadQuality", qualityKeys, defaultDownloadQuality ?? "standard", { low: t("musicQuality.low"), standard: t("musicQuality.standard"), high: t("musicQuality.high"), super: t("musicQuality.super"), }, ), createRadio( t("basicSettings.downloadQualityOrder"), "basic.downloadQualityOrder", ["asc", "desc"], downloadQualityOrder ?? "asc", { asc: t("basicSettings.downloadQualityOrder.asc"), desc: t("basicSettings.downloadQualityOrder.desc"), }, ), ], }, { title: t("basicSettings.network"), data: [ createSwitch( t("basicSettings.useCelluarNetworkPlay"), "basic.useCelluarNetworkPlay", useCelluarNetworkPlay ?? false, ), createSwitch( t("basicSettings.useCelluarNetworkDownload"), "basic.useCelluarNetworkDownload", useCelluarNetworkDownload ?? false, ), ], }, { title: t("basicSettings.lyric"), data: [], footer: , }, { title: t("basicSettings.cache"), data: [ { title: t("basicSettings.cache.musicCacheLimit"), right: ( {maxCacheSize ? sizeFormatter(maxCacheSize) : "512M"} ), onPress() { showPanel("SimpleInput", { title: t("dialog.setCacheTitle"), placeholder: t("dialog.setCachePlaceholder"), onOk(text, closePanel) { let val = parseInt(text); if (val < 100) { val = 100; } else if (val > 8192) { val = 8192; } if (val >= 100 && val <= 8192) { Config.setConfig( "basic.maxCacheSize", val * 1024 * 1024, ); closePanel(); Toast.success(t("toast.cacheSetSuccess")); } }, }); }, }, { title: t("basicSettings.cache.clearMusicCache"), right: ( {sizeFormatter(cacheSize.music)} ), onPress() { showDialog("SimpleDialog", { title: t("dialog.clearMusicCacheTitle"), content: t("dialog.clearMusicCacheContent"), async onOk() { await clearCache("music"); Toast.success(t("toast.musicCacheCleared")); refreshCacheSize(); }, }); }, }, { title: t("basicSettings.cache.clearLyricCache"), right: ( {sizeFormatter(cacheSize.lyric)} ), onPress() { showDialog("SimpleDialog", { title: t("dialog.clearLyricCacheTitle"), content: t("dialog.clearLyricCacheContent"), async onOk() { await clearCache("lyric"); Toast.success(t("toast.lyricCacheCleared")); refreshCacheSize(); }, }); }, }, { title: t("basicSettings.cache.clearImageCache"), right: ( {sizeFormatter(cacheSize.image)} ), onPress() { showDialog("SimpleDialog", { title: t("dialog.clearImageCacheTitle"), content: t("dialog.clearImageCacheContent"), async onOk() { await clearCache("image"); Toast.success(t("toast.imageCacheCleared")); refreshCacheSize(); }, }); }, }, ], }, { title: t("basicSettings.developer"), data: [ createSwitch( t("basicSettings.developer.errorLog"), "debug.errorLog", debugEnableErrorLog ?? false, ), createSwitch( t("basicSettings.developer.traceLog"), "debug.traceLog", debugEnableTraceLog ?? false, ), createSwitch( t("basicSettings.developer.devLog"), "debug.devLog", debugEnableDevLog ?? false, ), { title: t("basicSettings.developer.viewErrorLog"), right: undefined, async onPress() { // 获取日志文件夹 const errorLogContent = await getErrorLogContent(); showDialog("SimpleDialog", { title: t("dialog.errorLogTitle"), content: ( {errorLogContent || t("dialog.errorLogNoRecord")} ), cancelText: t("dialog.errorLogKnow"), okText: t("dialog.errorLogCopy"), onOk() { Clipboard.setString(errorLogContent); Toast.success(t("toast.copiedToClipboard")); }, }); }, }, { title: t("basicSettings.developer.clearLog"), right: undefined, async onPress() { try { await clearLog(); Toast.success(t("toast.logCleared")); } catch { } }, }, ], }, ]; return ( it.title)} renderItem={({ item, index }) => ( { sectionListRef.current?.scrollToLocation({ sectionIndex: index, itemIndex: 0, }); }} activeOpacity={0.7} style={styles.headerItemStyle}> {item} )} /> ( {section.title} )} ref={sectionListRef} renderSectionFooter={({ section }) => { return section.footer ?? null; }} renderItem={({ item }) => { const Right = item.right; return ( {Right} ); }} /> ); } const styles = StyleSheet.create({ wrapper: { width: "100%", paddingBottom: rpx(24), flex: 1, }, centerText: { textAlignVertical: "center", maxWidth: rpx(400), }, sectionHeader: { paddingHorizontal: rpx(24), height: rpx(72), flexDirection: "row", alignItems: "center", marginTop: rpx(20), }, headerContainer: { height: rpx(80), }, headerContentContainer: { height: rpx(80), alignItems: "center", paddingHorizontal: rpx(24), }, headerItemStyle: { paddingHorizontal: rpx(36), height: rpx(80), justifyContent: "center", alignItems: "center", }, }); function LyricSetting() { /** * // Lyric * "lyric.showStatusBarLyric": boolean; * "lyric.topPercent": number; * "lyric.leftPercent": number; * "lyric.align": number; * "lyric.color": string; * "lyric.backgroundColor": string; * "lyric.widthPercent": number; * "lyric.fontSize": number; * "lyric.detailFontSize": number; * "lyric.autoSearchLyric": boolean; */ const showStatusBarLyric = useAppConfig("lyric.showStatusBarLyric"); const topPercent = useAppConfig("lyric.topPercent"); const leftPercent = useAppConfig("lyric.leftPercent"); const align = useAppConfig("lyric.align"); const color = useAppConfig("lyric.color"); const backgroundColor = useAppConfig("lyric.backgroundColor"); const widthPercent = useAppConfig("lyric.widthPercent"); const fontSize = useAppConfig("lyric.fontSize"); const enableAutoSearchLyric = useAppConfig("lyric.autoSearchLyric"); const colors = useColors(); const { t } = useI18N(); const autoSearchLyric = createSwitch( t("basicSettings.lyric.autoSearchLyric"), "lyric.autoSearchLyric", enableAutoSearchLyric ?? false, ); const openStatusBarLyric = createSwitch( t("basicSettings.lyric.showStatusBarLyric"), "lyric.showStatusBarLyric", showStatusBarLyric ?? false, async newValue => { try { if (newValue) { const hasPermission = await LyricUtil.checkSystemAlertPermission(); if (hasPermission) { const statusBarLyricConfig = { topPercent: Config.getConfig("lyric.topPercent"), leftPercent: Config.getConfig("lyric.leftPercent"), align: Config.getConfig("lyric.align"), color: Config.getConfig("lyric.color"), backgroundColor: Config.getConfig("lyric.backgroundColor"), widthPercent: Config.getConfig("lyric.widthPercent"), fontSize: Config.getConfig("lyric.fontSize"), }; LyricUtil.showStatusBarLyric( "MusicFree", statusBarLyricConfig ?? {} ); Config.setConfig("lyric.showStatusBarLyric", true); } else { LyricUtil.requestSystemAlertPermission().finally(() => { Toast.warn(t("toast.noFloatWindowPermission")); }); } } else { LyricUtil.hideStatusBarLyric(); Config.setConfig("lyric.showStatusBarLyric", false); } } catch { } }, ); const alignStatusBarLyric = createRadio( t("basicSettings.lyric.align"), "lyric.align", [ NativeTextAlignment.LEFT, NativeTextAlignment.CENTER, NativeTextAlignment.RIGHT, ], align ?? NativeTextAlignment.CENTER, { [NativeTextAlignment.LEFT]: t("basicSettings.lyric.align.left"), [NativeTextAlignment.CENTER]: t("basicSettings.lyric.align.center"), [NativeTextAlignment.RIGHT]: t("basicSettings.lyric.align.right"), }, newVal => { if (showStatusBarLyric) { LyricUtil.setStatusBarLyricAlign(newVal as any); } }, ); return ( {autoSearchLyric.right} {openStatusBarLyric.right} {t("basicSettings.lyric.leftRightDistance")} { if (showStatusBarLyric) { LyricUtil.setStatusBarLyricLeft(val); } }} onSlidingComplete={val => { Config.setConfig("lyric.leftPercent", val); }} /> {t("basicSettings.lyric.topBottomDistance")} { if (showStatusBarLyric) { LyricUtil.setStatusBarLyricTop(val); } }} onSlidingComplete={val => { Config.setConfig("lyric.topPercent", val); }} /> {t("basicSettings.lyric.width")} { if (showStatusBarLyric) { LyricUtil.setStatusBarLyricWidth(val); } }} onSlidingComplete={val => { Config.setConfig("lyric.widthPercent", val); }} /> {t("basicSettings.lyric.fontSize")} { if (showStatusBarLyric) { LyricUtil.setStatusBarLyricFontSize(val); } }} onSlidingComplete={val => { Config.setConfig("lyric.fontSize", val); }} /> {alignStatusBarLyric.right} { showPanel("ColorPicker", { closePanelWhenSelected: true, defaultColor: color ?? "transparent", onSelected(color) { if (showStatusBarLyric) { const colorStr = color.hexa(); LyricUtil.setStatusBarColors(colorStr, null); Config.setConfig("lyric.color", colorStr); } }, }); }}> { showPanel("ColorPicker", { closePanelWhenSelected: true, defaultColor: backgroundColor ?? "transparent", onSelected(color) { if (showStatusBarLyric) { const colorStr = color.hexa(); LyricUtil.setStatusBarColors(null, colorStr); Config.setConfig( "lyric.backgroundColor", colorStr, ); } }, }); }}> ); } const lyricStyles = StyleSheet.create({ slider: { flex: 1, marginLeft: rpx(24), }, sliderContainer: { height: rpx(96), width: "100%", flexDirection: "row", alignItems: "center", paddingHorizontal: rpx(24), }, }); ================================================ FILE: src/pages/setting/settingTypes/index.ts ================================================ import deviceInfoModule from "react-native-device-info"; import AboutSetting from "./aboutSetting"; import BackupSetting from "./backupSetting"; import BasicSetting from "./basicSetting"; import PluginSetting from "./pluginSetting"; import ThemeSetting from "./themeSetting"; const settingTypes: Record< string, { title: string; component: (...args: any) => JSX.Element; showNav?: boolean; i18nKey: string; } > = { basic: { title: "基本设置", i18nKey: "sidebar.basicSettings", component: BasicSetting, }, plugin: { title: "插件管理", i18nKey: "sidebar.pluginManagement", component: PluginSetting, showNav: false, }, theme: { title: "主题设置", i18nKey: "sidebar.themeSettings", component: ThemeSetting, }, backup: { title: "备份与恢复", i18nKey: "sidebar.backupAndResume", component: BackupSetting, }, about: { title: `关于${deviceInfoModule.getApplicationName()}`, i18nKey: "common.about", component: AboutSetting, }, }; export default settingTypes; ================================================ FILE: src/pages/setting/settingTypes/pluginSetting/components/pluginItem.tsx ================================================ import React, { memo } from "react"; import useColors from "@/hooks/useColors"; import pluginManager, { Plugin, usePluginEnabled } from "@/core/pluginManager"; import Toast from "@/utils/toast"; import Clipboard from "@react-native-clipboard/clipboard"; import { showDialog } from "@/components/dialogs/useDialog"; import { showPanel } from "@/components/panels/usePanel"; import rpx from "@/utils/rpx"; import { StyleSheet, View } from "react-native"; import ThemeText from "@/components/base/themeText"; import IconTextButton from "@/components/base/iconTextButton"; import ThemeSwitch from "@/components/base/switch"; import { IIconName } from "@/components/base/icon.tsx"; import { useI18N } from "@/core/i18n"; import IconButton from "@/components/base/iconButton"; import useRerender from "@/hooks/useRerender"; interface IPluginItemProps { plugin: Plugin; } interface IOption { title: string; icon: IIconName; onPress?: () => void; show?: boolean; } function _PluginItem(props: IPluginItemProps) { const { plugin } = props; const colors = useColors(); const enabled = usePluginEnabled(plugin); const { t } = useI18N(); const rerender = useRerender(); const alternativePluginName = pluginManager.getAlternativePluginName(plugin); const options: IOption[] = [ { title: t("pluginSetting.pluginItem.options.updatePlugin"), icon: "arrow-path", async onPress() { try { await pluginManager.updatePlugin(plugin); Toast.success(t("toast.pluginUpdateSuccess")); } catch (e: any) { Toast.warn(e?.message ?? t("toast.failToUpdatePlugin")); } }, show: !!plugin.instance.srcUrl, }, { title: t("pluginSetting.pluginItem.options.sharePlugin"), icon: "share", async onPress() { try { Clipboard.setString(plugin.instance.srcUrl!); Toast.success(t("toast.copiedToClipboard")); } catch (e: any) { Toast.warn(e?.message ?? t("toast.failToSharePlugin")); } }, show: !!plugin.instance.srcUrl, }, { title: t("pluginSetting.pluginItem.options.uninstallPlugin"), icon: "trash-outline", show: true, onPress() { showDialog("SimpleDialog", { title: t("pluginSetting.pluginItem.options.uninstallPlugin"), content: t("pluginSetting.pluginItem.options.uninstallPluginContent", { name: plugin.name, }), async onOk() { try { await pluginManager.uninstallPlugin(plugin.hash); Toast.success(t("toast.pluginUninstalled")); } catch { Toast.warn(t("toast.failToUpdatePlugin")); } }, }); }, }, { title: t("pluginSetting.pluginItem.options.alternativePlugin"), icon: "strategy", show: true, onPress() { showDialog("RadioDialog", { content: (pluginManager.getSortedPluginsWithAbility("getMediaSource").map(it => it.name)), title: t("pluginSetting.pluginItem.dialog.setAlternativePluginTitle"), defaultSelected: pluginManager.getAlternativePluginName(plugin) as any, onOk(value) { if (value === plugin.name) { pluginManager.setAlternativePluginName(plugin, null as any); } else { pluginManager.setAlternativePluginName(plugin, value as any); } rerender(); }, tip: t("pluginSetting.pluginItem.dialog.setAlternativePluginTip"), }); }, }, { title: t("pluginSetting.pluginItem.options.importMusic"), icon: "arrow-right-end-on-rectangle", onPress() { showPanel("SimpleInput", { title: t("pluginSetting.pluginItem.options.importMusic"), placeholder: t("pluginSetting.pluginItem.options.importMusicPlaceHolder"), hints: plugin.instance.hints?.importMusicItem, maxLength: 1000, async onOk(text) { const result = await plugin.methods.importMusicItem( text, ); if (result) { showDialog("SimpleDialog", { title: t("pluginSetting.pluginItem.options.importDialogTitle"), content: t("pluginSetting.pluginItem.options.importMusicDialogContent", { name: result.title, }), onOk() { showPanel("AddToMusicSheet", { musicItem: result, newSheetDefaultName: t("pluginSetting.pluginItem.options.importMusicToSheetName", { name: plugin.name, }), }); }, }); } else { Toast.warn(t("toast.failToImportMusic")); } }, }); }, show: !!plugin.supportedMethods.has("importMusicItem"), }, { title: t("pluginSetting.pluginItem.options.importSheet"), icon: "arrow-right-end-on-rectangle", onPress() { showPanel("SimpleInput", { title: t("pluginSetting.pluginItem.options.importSheet"), placeholder: t("pluginSetting.pluginItem.options.importSheetPlaceHolder"), hints: plugin.instance.hints?.importMusicSheet, maxLength: 1000, async onOk(text, closePanel) { Toast.success(t("toast.importing")); closePanel(); const result = await plugin.methods.importMusicSheet( text, ); if (result && result.length > 0) { showDialog("SimpleDialog", { title: t("pluginSetting.pluginItem.options.importDialogTitle"), content: t("pluginSetting.pluginItem.options.importSheetDialogContent", { count: result.length, }), onOk() { showPanel("AddToMusicSheet", { musicItem: result, }); }, }); } else { Toast.warn(t("toast.failToImportSheet")); } }, }); }, show: !!plugin.supportedMethods.has("importMusicSheet"), }, { title: t("pluginSetting.pluginItem.options.userVariables"), icon: "code-bracket-square", onPress() { if (Array.isArray(plugin.instance.userVariables)) { showPanel("SetUserVariables", { async onOk(newValue, closePanel) { pluginManager.setUserVariables(plugin, newValue); Toast.success(t("toast.settingSuccess")); closePanel(); }, variables: plugin.instance.userVariables, initValues: pluginManager.getUserVariables(plugin), }); } }, show: Array.isArray(plugin.instance.userVariables), }, ]; return ( {plugin.name} { plugin.instance.description?.length ? { showDialog("MarkdownDialog", { title: plugin.name, markdownContent: plugin.instance.description!, }); }} /> : null } { pluginManager.setPluginEnabled(plugin, val); }} /> {t("pluginSetting.pluginItem.versionHint", { version: plugin.instance.version, })} {plugin.instance.author ? ( {t("pluginSetting.pluginItem.author", { author: plugin.instance.author, })} ) : null} {alternativePluginName ? {t("pluginSetting.pluginItem.alternativePlugin", { name: alternativePluginName, })} : null} {options.map((it, index) => it.show !== false ? ( {it.title} ) : null, )} // // {options.map(_ => // _.show ? ( // // // // // ) : null, // )} // ); } const PluginItem = memo(_PluginItem, (prev, curr) => { return prev.plugin === curr.plugin; }); export default PluginItem; const styles = StyleSheet.create({ container: { flex: 1, borderRadius: rpx(8), marginHorizontal: rpx(24), paddingVertical: rpx(18), marginTop: rpx(36), }, header: { paddingHorizontal: rpx(16), flexDirection: "row", alignItems: "center", }, headerPluginContainer: { flexShrink: 1, flexGrow: 1, flexDirection: "row", gap: rpx(8), alignItems: "center", }, author: { marginLeft: rpx(24), flexShrink: 1, flexGrow: 1, }, description: { marginHorizontal: rpx(16), marginVertical: rpx(24), flexDirection: "row", }, alternativePluginDescription: { marginHorizontal: rpx(16), marginBottom: rpx(24), flexDirection: "row", }, contents: { flexDirection: "row", justifyContent: "space-between", flexWrap: "wrap", gap: rpx(16), }, }); ================================================ FILE: src/pages/setting/settingTypes/pluginSetting/index.tsx ================================================ import React from "react"; import { createNativeStackNavigator } from "@react-navigation/native-stack"; import PluginList from "./views/pluginList"; import PluginSort from "./views/pluginSort"; import PluginSubscribe from "./views/pluginSubscribe"; const Stack = createNativeStackNavigator(); const routes = [ { path: "/pluginsetting/list", component: PluginList, }, { path: "/pluginsetting/sort", component: PluginSort, }, { path: "/pluginsetting/subscribe", component: PluginSubscribe, }, ]; export default function PluginSetting() { return ( {routes.map(route => ( ))} ); } ================================================ FILE: src/pages/setting/settingTypes/pluginSetting/views/pluginList.tsx ================================================ import React, { useState } from "react"; import { FlatList, StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import * as DocumentPicker from "expo-document-picker"; import Loading from "@/components/base/loading"; import PluginManager, { useSortedPlugins } from "@/core/pluginManager"; import { trace } from "@/utils/log"; import Toast from "@/utils/toast"; import axios from "axios"; import { useNavigation } from "@react-navigation/native"; import Config from "@/core/appConfig"; import Empty from "@/components/base/empty"; import HorizontalSafeAreaView from "@/components/base/horizontalSafeAreaView.tsx"; import { showDialog } from "@/components/dialogs/useDialog"; import { showPanel } from "@/components/panels/usePanel"; import AppBar from "@/components/base/appBar"; import Fab from "@/components/base/fab"; import PluginItem from "../components/pluginItem"; import { IIconName } from "@/components/base/icon.tsx"; import { IInstallPluginResult } from "@/types/core/pluginManager"; import { useI18N } from "@/core/i18n"; interface IOption { icon: IIconName; title: string; onPress?: () => void; } export default function PluginList() { const plugins = useSortedPlugins(); const { t } = useI18N(); const [loading, setLoading] = useState(false); const navigator = useNavigation(); const menuOptions: IOption[] = [ { icon: "bookmark-square", title: t("pluginSetting.menu.subscriptionSetting"), async onPress() { navigator.navigate("/pluginsetting/subscribe"); }, }, { icon: "bars-3", title: t("pluginSetting.menu.sort"), onPress() { navigator.navigate("/pluginsetting/sort"); }, }, { icon: "trash-outline", title: t("pluginSetting.menu.uninstallAll"), onPress() { showDialog("SimpleDialog", { title: t("pluginSetting.menu.uninstallAll"), content: t("pluginSetting.menu.uninstallAllContent"), async onOk() { setLoading(true); await PluginManager.uninstallAllPlugins(); setLoading(false); }, }); }, }, ]; async function onInstallFromLocalClick() { try { const results = await DocumentPicker.getDocumentAsync({ copyToCacheDirectory: true, multiple: true, type: ["application/javascript", "text/javascript"], }); if (results.canceled) { // 用户取消 return; } setLoading(true); await Promise.all( results.assets.map(async it => { await PluginManager.installPluginFromLocalFile(it.uri, { notCheckVersion: Config.getConfig( "basic.notCheckPluginVersion", ), useExpoFs: true, }); }), ); // 初步过滤 Toast.success(t("toast.installPluginSuccess")); } catch (e: any) { trace("插件安装失败", e?.message); Toast.warn(t("toast.installPluginFail", { reason: e?.message ?? "", })); } setLoading(false); } async function onInstallFromNetworkClick() { showPanel("SimpleInput", { title: t("pluginSetting.menu.installPlugin"), placeholder: t("pluginSetting.menu.installPluginDialogPlaceholder"), maxLength: 200, async onOk(text, closePanel) { setLoading(true); closePanel(); const result = await installPluginFromUrl(text.trim()); // 检查是否全部安装成功 const successResults: IInstallPluginResult[] = []; const failResults: IInstallPluginResult[] = []; for (let i = 0; i < result.length; ++i) { if (result[i].success) { successResults.push(result[i]); } else { failResults.push(result[i]); } } if (!failResults.length) { Toast.success(t("toast.installPluginSuccess")); } else { Toast.warn(successResults.length ? t("toast.partialPluginInstallFailed") : t("toast.allPluginInstallFailed"), { "type": "warn", "actionText": t("common.view"), "onActionClick": () => { showDialog("SimpleDialog", { title: t("pluginSetting.menu.pluginInstallFailedDialogTitle"), content: t("pluginSetting.pluginInstallFailedDialogContent", { detail: failResults.map(it => (it.pluginUrl ?? "") + "\n" + t("pluginSetting.failReason", { reason: it.message ?? "", })).join("\n-----\n"), }), }); }, }); } setLoading(false); }, }); } async function onSubscribeClick() { const urls = Config.getConfig("plugin.subscribeUrl"); if (!urls) { Toast.warn(t("toast.noSubscription")); } setLoading(true); const successResults: IInstallPluginResult[] = []; const failResults: IInstallPluginResult[] = []; try { const urlItems = JSON.parse(urls!); if (Array.isArray(urlItems)) { for (let i = 0; i < urlItems.length; ++i) { const result = await installPluginFromUrl(urlItems[i].url); if (result[0]) { if (result[0].success) { successResults.push(result[0]); } else { failResults.push(result[0]); } } } } else { throw new Error(); } if (!failResults.length) { Toast.success(t("toast.installPluginSuccess")); } else { Toast.warn((successResults.length ? t("toast.partialPluginInstallFailed") : t("toast.allPluginInstallFailed")), { "type": "warn", "actionText": t("common.view"), "onActionClick": () => { showDialog("SimpleDialog", { title: t("pluginSetting.menu.pluginInstallFailedDialogTitle"), content: t("pluginSetting.pluginInstallFailedDialogContent", { detail: failResults.map(it => (it.pluginUrl ?? "") + "\n" + t("pluginSetting.failReason", { reason: it.message ?? "", })).join("\n-----\n"), }), }); }, }); } } catch { if (urls?.length) { const result = await installPluginFromUrl(urls); if (result[0]) { if (result[0].success) { Toast.success(t("toast.installPluginSuccess")); } else { Toast.warn(t("toast.partialPluginInstallFailedWithReason", { reason: result[0].message ?? "", })); } } else { Toast.warn(t("toast.subscriptionInvalid")); } } } setLoading(false); } async function onUpdateAllClick() { const plugins = PluginManager.getEnabledPlugins(); setLoading(true); const successResults: IInstallPluginResult[] = []; const failResults: IInstallPluginResult[] = []; try { for (let i = 0; i < plugins.length; ++i) { const srcUrl = plugins[i].instance.srcUrl; if (srcUrl) { const result = await installPluginFromUrl(srcUrl); if (result[0]) { if (result[0].success) { successResults.push(result[0]); } else { failResults.push(result[0]); } } } } if (!failResults.length) { Toast.success(t("toast.updatePluginSuccess")); } else { Toast.warn((successResults.length ? t("toast.partialPluginUpdateFailed") : t("toast.allPluginUpdateFailed")), { "type": "warn", "actionText": t("common.view"), "onActionClick": () => { showDialog("SimpleDialog", { title: t("pluginSetting.menu.pluginUpdateFailedDialogTitle"), content: t("pluginSetting.pluginUpdateFailedDialogContent", { detail: failResults.map(it => (it.pluginUrl ?? "") + "\n" + t("pluginSetting.failReason", { reason: it.message ?? "", })).join("\n-----\n"), }), }); }, }); } } catch (e: any) { Toast.warn(t("toast.unknownError", { reason: e?.message ?? e, })); } setLoading(false); } return ( <> {t("sidebar.pluginManagement")} <> {loading ? ( ) : ( } data={plugins ?? []} keyExtractor={_ => _.hash} renderItem={({ item: plugin }) => ( )} /> )} { showPanel("SimpleSelect", { header: t("pluginSetting.menu.installPlugin"), candidates: [ { value: "从本地安装插件", title: t("pluginSetting.fabOptions.installFromLocal"), }, { value: "从网络安装插件", title: t("pluginSetting.fabOptions.installFromNetwork"), }, { value: "更新全部插件", title: t("pluginSetting.fabOptions.updateAllPlugins"), }, { value: "更新订阅", title: t("pluginSetting.fabOptions.updateSubscription"), }, ], onPress(item) { if (item.value === "从本地安装插件") { onInstallFromLocalClick(); } else if ( item.value === "从网络安装插件" ) { onInstallFromNetworkClick(); } else if (item.value === "更新订阅") { onSubscribeClick(); } else if (item.value === "更新全部插件") { onUpdateAllClick(); } }, }); }} /> ); } const style = StyleSheet.create({ wrapper: { width: "100%", flex: 1, }, blank: { height: rpx(200), }, }); async function installPluginFromUrl(text: string): Promise { try { let urls: string[] = []; const inputUrl = text.trim(); if (text.endsWith(".json")) { const jsonFile = ( await axios.get(inputUrl, { headers: { "Cache-Control": "no-cache", Pragma: "no-cache", Expires: "0", }, }) ).data; /** * { * plugins: [{ * version: xxx, * url: xxx * }] * } */ urls = (jsonFile?.plugins ?? []).map((_: any) => _.url); } else { urls = [inputUrl]; } return await Promise.all( urls.map(url => PluginManager.installPluginFromUrl(url, { notCheckVersion: Config.getConfig( "basic.notCheckPluginVersion", ), }), ), ); } catch (e: any) { return [{ success: false, message: e?.message, pluginUrl: text }]; } } ================================================ FILE: src/pages/setting/settingTypes/pluginSetting/views/pluginSort.tsx ================================================ import AppBar from "@/components/base/appBar"; import HorizontalSafeAreaView from "@/components/base/horizontalSafeAreaView.tsx"; import SortableFlatList from "@/components/base/SortableFlatList"; import ThemeText from "@/components/base/themeText"; import globalStyle from "@/constants/globalStyle"; import { useI18N } from "@/core/i18n"; import PluginManager, { Plugin, useSortedPlugins } from "@/core/pluginManager"; import useColors from "@/hooks/useColors"; import rpx from "@/utils/rpx"; import Toast from "@/utils/toast"; import React, { useState } from "react"; import { StatusBar, StyleSheet, TouchableOpacity, View } from "react-native"; const ITEM_HEIGHT = rpx(96); const marginTop = rpx(188) + (StatusBar.currentHeight ?? 0); export default function PluginSort() { const plugins = useSortedPlugins(); const [sortingPlugins, setSortingPlugins] = useState([...plugins]); const colors = useColors(); const { t } = useI18N(); function renderSortingItem({ item }: { item: Plugin }) { return ( {item.name} ); } return ( <> {t("pluginSetting.menu.sort")} <> {t("pluginSetting.menu.sort")} { PluginManager.setPluginOrder(sortingPlugins); Toast.success(t("toast.saveSuccess")); }}> {t("common.done")} { setSortingPlugins(data); }} /> ); } const style = StyleSheet.create({ sortWrapper: { marginHorizontal: rpx(24), marginTop: rpx(36), justifyContent: "space-between", height: rpx(64), alignItems: "center", flexDirection: "row", }, sortItem: { height: ITEM_HEIGHT, width: rpx(500), paddingLeft: rpx(24), justifyContent: "center", }, }); ================================================ FILE: src/pages/setting/settingTypes/pluginSetting/views/pluginSubscribe.tsx ================================================ import React, { useEffect, useState } from "react"; import { StyleSheet } from "react-native"; import rpx from "@/utils/rpx"; import Config, { useAppConfig } from "@/core/appConfig"; import { FlatList } from "react-native-gesture-handler"; import Empty from "@/components/base/empty"; import ListItem from "@/components/base/listItem"; import Toast from "@/utils/toast"; import Clipboard from "@react-native-clipboard/clipboard"; import HorizontalSafeAreaView from "@/components/base/horizontalSafeAreaView.tsx"; import globalStyle from "@/constants/globalStyle"; import { showDialog } from "@/components/dialogs/useDialog"; import AppBar from "@/components/base/appBar"; import Fab from "@/components/base/fab"; import { useI18N } from "@/core/i18n"; interface ISubscribeItem { name: string; url: string; } const ITEM_HEIGHT = rpx(108); export default function PluginSubscribe() { const urls = useAppConfig("plugin.subscribeUrl") ?? ""; const [subscribes, setSubscribes] = useState>([]); const { t } = useI18N(); useEffect(() => { try { const parsed = JSON.parse(urls); if (Array.isArray(parsed)) { setSubscribes(parsed); } else { throw new Error(); } } catch { if (urls.length) { setSubscribes([ { name: t("common.default"), url: urls, }, ]); } else { setSubscribes([]); } } }, [urls]); const onSubmit = ( subscribeItem: ISubscribeItem, hideDialog: () => void, editingIndex?: number, ) => { if ( subscribeItem.url.endsWith(".js") || subscribeItem.url.endsWith(".json") ) { if (editingIndex !== undefined) { Config.setConfig( "plugin.subscribeUrl", JSON.stringify([ ...subscribes.slice(0, editingIndex), subscribeItem, ...subscribes.slice(editingIndex + 1), ]), ); } else { Config.setConfig( "plugin.subscribeUrl", JSON.stringify([...subscribes, subscribeItem]), ); } hideDialog(); } else { Toast.warn(t("toast.subscriptionHaveToEndWithJs")); } }; return ( <> {t("pluginSetting.menu.subscriptionSetting")} { return ( { showDialog("SubscribePluginDialog", { subscribeItem: item, onSubmit, editingIndex: index, onDelete(editingIndex, hideDialog) { Config.setConfig( "plugin.subscribeUrl", JSON.stringify([ ...subscribes.slice( 0, editingIndex, ), ...subscribes.slice( editingIndex + 1, ), ]), ); hideDialog(); Toast.success(t("toast.deleteSuccess")); }, }); }}> { Clipboard.setString(item.url); Toast.success(t("toast.copiedToClipboard")); }} /> ); }} getItemLayout={(_, index) => ({ length: ITEM_HEIGHT, offset: ITEM_HEIGHT * index, index, })} /> { showDialog("SubscribePluginDialog", { onSubmit, }); }} /> ); } const style = StyleSheet.create({ wrapper: { width: rpx(750), flex: 1, }, listWrapper: { marginTop: rpx(24), }, fab: { position: "absolute", right: rpx(36), bottom: rpx(36), }, }); ================================================ FILE: src/pages/setting/settingTypes/themeSetting/background.tsx ================================================ import React from "react"; import { StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import ThemeText from "@/components/base/themeText"; // import pathConst from '@/constants/pathConst'; import Config, { useAppConfig } from "@/core/appConfig"; import ThemeCard from "./themeCard"; import { ROUTE_PATH, useNavigate } from "@/core/router"; import Theme from "@/core/theme"; import { useI18N } from "@/core/i18n"; export default function Background() { const { t } = useI18N(); const themeBackground = useAppConfig("theme.background"); const themeSelectedTheme = useAppConfig("theme.selectedTheme"); const navigate = useNavigate(); // const onCustomBgPress = async () => { // try { // const result = await launchImageLibrary({ // mediaType: 'photo', // }); // const uri = result.assets?.[0].uri; // if (!uri) { // return; // } // const bgPath = `${pathConst.dataPath}background${uri.substring( // uri.lastIndexOf('.'), // )}`; // await copyFile(uri, bgPath); // Config.set( // 'setting.theme.background', // `file://${bgPath}#${Date.now()}`, // ); // const colorsResult = await ImageColors.getColors(uri, { // fallback: '#ffffff', // }); // const colors = { // primary: // colorsResult.platform === 'android' // ? colorsResult.dominant // : colorsResult.platform === 'ios' // ? colorsResult.primary // : colorsResult.vibrant, // average: // colorsResult.platform === 'android' // ? colorsResult.average // : colorsResult.platform === 'ios' // ? colorsResult.detail // : colorsResult.dominant, // vibrant: // colorsResult.platform === 'android' // ? colorsResult.vibrant // : colorsResult.platform === 'ios' // ? colorsResult.secondary // : colorsResult.vibrant, // }; // const primaryColor = Color(colors.primary).darken(0.3).toString(); // // const secondaryColor = Color(colors.average) // // .darken(0.3) // // .toString(); // const textHighlight = Color( // 0xffffff - Color(primaryColor).rgbNumber(), // 'rgb', // ) // .saturate(0.5) // .toString(); // Config.set('setting.theme.mode', 'custom-dark'); // Config.set('setting.theme.colors', { // primary: primaryColor, // textHighlight: textHighlight, // accent: textHighlight, // }); // } catch (e) { // console.log(e); // } // }; return ( {t("themeSettings.setTheme")} { if (themeSelectedTheme !== "p-light") { Theme.setTheme("p-light"); Config.setConfig("theme.followSystem", false); } }} /> { if (themeSelectedTheme !== "p-dark") { Theme.setTheme("p-dark"); Config.setConfig("theme.followSystem", false); } }} /> { if (themeSelectedTheme !== "custom") { Config.setConfig("theme.followSystem", false); Theme.setTheme("custom", { colors: Config.getConfig( "theme.customColors", ), }); } navigate(ROUTE_PATH.SET_CUSTOM_THEME); // showPanel('ColorPicker'); }} /> {/* { Config.set('setting.theme.background', undefined); Config.set('setting.theme.colors', undefined); }} /> */} ); } const style = StyleSheet.create({ header: { marginTop: rpx(36), paddingLeft: rpx(24), }, sectionWrapper: { marginTop: rpx(28), flexDirection: "row", flexWrap: "wrap", paddingHorizontal: rpx(24), }, }); ================================================ FILE: src/pages/setting/settingTypes/themeSetting/index.tsx ================================================ import React from "react"; import { StyleSheet } from "react-native"; import rpx from "@/utils/rpx"; import Mode from "./mode"; import Background from "./background"; import { ScrollView } from "react-native-gesture-handler"; export default function ThemeSetting() { return ( ); } const style = StyleSheet.create({ wrapper: { width: "100%", marginVertical: rpx(24), }, }); ================================================ FILE: src/pages/setting/settingTypes/themeSetting/logoCard.tsx ================================================ import React from "react"; import { Image, Pressable, StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import useColors from "@/hooks/useColors"; import ThemeText from "@/components/base/themeText"; interface ILogoCardProps { selected?: boolean; logo: number; onPress?: () => void; title?: string; } export default function LogoCard(props: ILogoCardProps) { const { selected, logo, onPress, title } = props; const colors = useColors(); return ( {title} ); } const styles = StyleSheet.create({ borderContainer: { width: rpx(160), height: rpx(160), borderRadius: rpx(22), marginRight: rpx(24), justifyContent: "center", alignItems: "center", }, imageContainer: { width: rpx(136), height: rpx(136), borderRadius: rpx(12), }, title: { textAlign: "center", marginTop: rpx(12), width: rpx(160), }, image: { width: "100%", height: "100%", borderRadius: rpx(12), }, }); ================================================ FILE: src/pages/setting/settingTypes/themeSetting/mode.tsx ================================================ import React from "react"; import { Appearance, StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import ThemeText from "@/components/base/themeText"; import ListItem from "@/components/base/listItem"; import ThemeSwitch from "@/components/base/switch"; import Config, { useAppConfig } from "@/core/appConfig"; import Theme from "@/core/theme"; import { useI18N } from "@/core/i18n"; export default function Mode() { const { t } = useI18N(); const mode = useAppConfig("theme.followSystem") ?? false; return ( {t("themeSettings.displayStyle")} {t("themeSettings.followSystemTheme")} { if (e) { const colorScheme = Appearance.getColorScheme(); if (colorScheme === "dark") { Theme.setTheme("p-dark"); } else if (colorScheme === "light") { Theme.setTheme("p-light"); } } Config.setConfig("theme.followSystem", e); }} /> ); } const styles = StyleSheet.create({ header: { paddingLeft: rpx(24), marginTop: rpx(36), }, sectionWrapper: { marginTop: rpx(24), }, itemRow: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", }, }); ================================================ FILE: src/pages/setting/settingTypes/themeSetting/themeCard.tsx ================================================ import React from "react"; import { Pressable, StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import useColors from "@/hooks/useColors"; import ThemeText from "@/components/base/themeText"; import Image from "@/components/base/image"; import { ImgAsset } from "@/constants/assetsConst"; interface IThemeCardProps { selected?: boolean; preview?: string; onPress?: () => void; title?: string; } export default function ThemeCard(props: IThemeCardProps) { const { selected, preview, onPress, title } = props; const isPreviewColor = preview?.startsWith("#") ? true : false; const colors = useColors(); return ( {isPreviewColor ? null : ( )} {title} ); } const styles = StyleSheet.create({ borderContainer: { width: rpx(160), height: rpx(160), borderRadius: rpx(22), marginRight: rpx(24), justifyContent: "center", alignItems: "center", }, container: { width: rpx(136), height: rpx(136), borderRadius: rpx(12), }, title: { textAlign: "center", marginTop: rpx(12), width: rpx(160), }, image: { width: "100%", height: "100%", borderRadius: rpx(12), }, }); ================================================ FILE: src/pages/sheetDetail/components/header.tsx ================================================ import FastImage from "@/components/base/fastImage"; import PlayAllBar from "@/components/base/playAllBar"; import ThemeText from "@/components/base/themeText"; import { ImgAsset } from "@/constants/assetsConst"; import { useI18N } from "@/core/i18n"; import { useSheetItem } from "@/core/musicSheet"; import { useParams } from "@/core/router"; import useColors from "@/hooks/useColors"; import rpx from "@/utils/rpx"; import React from "react"; import { StyleSheet, View } from "react-native"; export default function Header() { const { id = "favorite" } = useParams<"local-sheet-detail">(); const sheet = useSheetItem(id); const colors = useColors(); const { t } = useI18N(); return ( {sheet?.title} {t("sheetDetail.totalMusicCount", { count: sheet?.musicList?.length ?? 0, })} ); } const style = StyleSheet.create({ content: { width: "100%", height: rpx(300), paddingHorizontal: rpx(24), flexDirection: "row", justifyContent: "flex-start", alignItems: "center", }, coverImg: { width: rpx(210), height: rpx(210), borderRadius: rpx(24), }, details: { paddingHorizontal: rpx(36), flex: 1, height: rpx(140), justifyContent: "space-between", gap: rpx(14), }, }); ================================================ FILE: src/pages/sheetDetail/components/navBar.tsx ================================================ import AppBar from "@/components/base/appBar"; import { showDialog } from "@/components/dialogs/useDialog"; import { showPanel } from "@/components/panels/usePanel.ts"; import { SortType } from "@/constants/commonConst.ts"; import { useI18N } from "@/core/i18n"; import MusicSheet, { useSheetItem } from "@/core/musicSheet"; import { ROUTE_PATH, useParams } from "@/core/router"; import { default as Toast, default as toast } from "@/utils/toast"; import { useNavigation } from "@react-navigation/native"; import React from "react"; export default function () { const navigation = useNavigation(); const { id = "favorite" } = useParams<"local-sheet-detail">(); const musicSheet = useSheetItem(id); const { t } = useI18N(); return ( <> { await MusicSheet.removeSheet(id); Toast.success(t("toast.deleteSuccess")); navigation.goBack(); }, }); }, }, ]} actions={[ { icon: "magnifying-glass", onPress() { navigation.navigate(ROUTE_PATH.SEARCH_MUSIC_LIST, { musicList: musicSheet?.musicList, musicSheet: musicSheet, }); }, }, ]}> {t("common.sheet")} ); } ================================================ FILE: src/pages/sheetDetail/components/sheetMusicList.tsx ================================================ import React from "react"; import Header from "./header"; import MusicList from "@/components/musicList"; import { useParams } from "@/core/router"; import HorizontalSafeAreaView from "@/components/base/horizontalSafeAreaView.tsx"; import globalStyle from "@/constants/globalStyle"; import { useSheetItem } from "@/core/musicSheet"; import { RequestStateCode } from "@/constants/commonConst"; import { useCurrentMusic } from "@/core/trackPlayer"; export default function SheetMusicList() { const { id = "favorite" } = useParams<"local-sheet-detail">(); const musicSheet = useSheetItem(id); const currentMusic = useCurrentMusic(); return ( } musicList={musicSheet?.musicList} musicSheet={musicSheet} showIndex state={RequestStateCode.IDLE} highlightMusicItem={currentMusic} /> ); } ================================================ FILE: src/pages/sheetDetail/index.tsx ================================================ import React from "react"; import NavBar from "./components/navBar"; import MusicBar from "@/components/musicBar"; import SheetMusicList from "./components/sheetMusicList"; import StatusBar from "@/components/base/statusBar"; import VerticalSafeAreaView from "@/components/base/verticalSafeAreaView"; import globalStyle from "@/constants/globalStyle"; export default function SheetDetail() { return ( ); } ================================================ FILE: src/pages/topList/components/boardPanel.tsx ================================================ import React, { memo } from "react"; import { SectionList, SectionListProps, StyleSheet, View } from "react-native"; import rpx from "@/utils/rpx"; import { IPluginTopListResult } from "../store/atoms"; import { RequestStateCode } from "@/constants/commonConst"; import Loading from "@/components/base/loading"; import TopListItem from "@/components/mediaItem/topListItem"; import ThemeText from "@/components/base/themeText"; import ListEmpty from "@/components/base/listEmpty"; interface IBoardPanelProps { hash: string; topListData: IPluginTopListResult; } function BoardPanel(props: IBoardPanelProps) { const { hash, topListData } = props ?? {}; const renderItem: SectionListProps["renderItem"] = ({ item }) => { return ; }; const renderSectionHeader: SectionListProps["renderSectionHeader"] = ({ section: { title } }) => { return ( {title} ); }; return topListData?.state !== RequestStateCode.FINISHED ? ( ) : ( } sections={topListData?.data || []} /> ); } export default memo( BoardPanel, (prev, curr) => prev.topListData === curr.topListData, ); const style = StyleSheet.create({ wrapper: { width: rpx(750), }, sectionHeader: { marginTop: rpx(28), marginBottom: rpx(24), marginLeft: rpx(24), }, }); ================================================ FILE: src/pages/topList/components/boardPanelWrapper.tsx ================================================ import React, { useEffect, useMemo } from "react"; import useGetTopList from "../hooks/useGetTopList"; import { useAtomValue } from "jotai"; import { pluginsTopListAtom } from "../store/atoms"; import BoardPanel from "./boardPanel"; interface IBoardPanelProps { hash: string; } export default function BoardPanelWrapper(props: IBoardPanelProps) { const { hash } = props ?? {}; const topLists = useAtomValue(pluginsTopListAtom); const getTopList = useGetTopList(); const topListData = useMemo(() => topLists[hash], [topLists]); useEffect(() => { getTopList(hash); }, []); return ; } ================================================ FILE: src/pages/topList/components/topListBody.tsx ================================================ import React, { useCallback, useState } from "react"; import { StyleSheet, Text } from "react-native"; import rpx from "@/utils/rpx"; import PluginManager from "@/core/pluginManager"; import { TabBar, TabView } from "react-native-tab-view"; import { fontWeightConst } from "@/constants/uiConst"; import BoardPanelWrapper from "./boardPanelWrapper"; import useColors from "@/hooks/useColors"; import NoPlugin from "@/components/base/noPlugin"; import i18n from "@/core/i18n"; export default function TopListBody() { const routes = PluginManager.getSortedPluginsWithAbility("getTopLists").map(_ => ({ key: _.hash, title: _.name, })); const [index, setIndex] = useState(0); const colors = useColors(); const renderScene = useCallback( (props: { route: { key: string } }) => ( ), [], ); if (!routes?.length) { return ; } return ( ( ( {route.title} )} indicatorStyle={{ backgroundColor: colors.primary, height: rpx(4), }} /> )} renderScene={renderScene} onIndexChange={setIndex} initialLayout={{ width: rpx(750) }} /> ); } const styles = StyleSheet.create({ tabBarStyle: { backgroundColor: "transparent", shadowColor: "transparent", borderColor: "transparent", }, tabStyle: { width: "auto", }, }); ================================================ FILE: src/pages/topList/hooks/useGetTopList.ts ================================================ import { RequestStateCode } from "@/constants/commonConst"; import PluginManager from "@/core/pluginManager"; import { produce } from "immer"; import { useAtom } from "jotai"; import { useCallback } from "react"; import { pluginsTopListAtom } from "../store/atoms"; export default function useGetTopList() { const [pluginsTopList, setPluginsTopList] = useAtom(pluginsTopListAtom); const getTopList = useCallback( async (pluginHash: string) => { try { // 有数据/加载中直接返回 if ( pluginsTopList[pluginHash]?.data?.length || pluginsTopList[pluginHash]?.state === RequestStateCode.PENDING_REST_PAGE ) { return; } // 获取plugin const plugin = PluginManager.getByHash(pluginHash); if (!plugin) { return; } setPluginsTopList( produce(draft => { draft[pluginHash] = { state: RequestStateCode.PENDING_REST_PAGE, data: [], }; }), ); const result = await plugin?.methods?.getTopLists(); setPluginsTopList( produce(draft => { draft[pluginHash] = { data: result, state: RequestStateCode.FINISHED, }; }), ); } catch { setPluginsTopList( produce(draft => { draft[pluginHash].state = RequestStateCode.ERROR; }), ); } }, [pluginsTopList], ); return getTopList; } ================================================ FILE: src/pages/topList/index.tsx ================================================ import React from "react"; import TopListBody from "./components/topListBody"; import MusicBar from "@/components/musicBar"; import VerticalSafeAreaView from "@/components/base/verticalSafeAreaView"; import globalStyle from "@/constants/globalStyle"; import HorizontalSafeAreaView from "@/components/base/horizontalSafeAreaView.tsx"; import AppBar from "@/components/base/appBar"; import { useI18N } from "@/core/i18n"; export default function TopList() { const { t } = useI18N(); return ( {t("topList.title")} ); } ================================================ FILE: src/pages/topList/store/atoms.ts ================================================ import { RequestStateCode } from "@/constants/commonConst"; import { atom } from "jotai"; export interface IPluginTopListResult { state: RequestStateCode; data: IMusic.IMusicSheetGroupItem[]; } const pluginsTopListAtom = atom>({}); export { pluginsTopListAtom }; ================================================ FILE: src/pages/topListDetail/hooks/useTopListDetail.ts ================================================ import { RequestStateCode } from "@/constants/commonConst"; import PluginManager from "@/core/pluginManager"; import { useEffect, useRef, useState } from "react"; export default function useTopListDetail( topListItem: IMusic.IMusicSheetItemBase | null, pluginHash: string, ) { const [mergedTopListItem, setMergedTopListItem] = useState | null>( topListItem, ); const pageRef = useRef(1); const [requestState, setRequestState] = useState(RequestStateCode.IDLE); async function loadMore() { if (!topListItem) { return; } try { if ( requestState === RequestStateCode.PENDING_FIRST_PAGE || requestState === RequestStateCode.PENDING_REST_PAGE || requestState === RequestStateCode.FINISHED ) { return; } if (pageRef.current === 1) { setRequestState(RequestStateCode.PENDING_FIRST_PAGE); } else { setRequestState(RequestStateCode.PENDING_REST_PAGE); } const result = await PluginManager.getByHash( pluginHash, )?.methods?.getTopListDetail(topListItem, pageRef.current); if (!result) { throw new Error(); } const currentPage = pageRef.current; setMergedTopListItem( prev => ({ ...prev, ...result.topListItem, musicList: currentPage === 1 ? result.musicList ?? [] : [ ...(prev?.musicList ?? []), ...(result.musicList ?? []), ], } as IMusic.IMusicSheetItem), ); if (result.isEnd === false) { setRequestState(RequestStateCode.PARTLY_DONE); } else { setRequestState(RequestStateCode.FINISHED); } pageRef.current++; } catch { setRequestState(RequestStateCode.ERROR); } } useEffect(() => { if (topListItem === null) { return; } loadMore(); }, []); return [mergedTopListItem, requestState, loadMore] as const; } ================================================ FILE: src/pages/topListDetail/index.tsx ================================================ import MusicSheetPage from "@/components/musicSheetPage"; import { useI18N } from "@/core/i18n"; import { useParams } from "@/core/router"; import React from "react"; import useTopListDetail from "./hooks/useTopListDetail"; export default function TopListDetail() { const { pluginHash, topList } = useParams<"top-list-detail">(); const [topListDetail, state, loadMore] = useTopListDetail( topList, pluginHash, ); const { t } = useI18N(); return ( ); } ================================================ FILE: src/service/index.ts ================================================ import Config from "@/core/appConfig"; import RNTrackPlayer, { Event, State } from "react-native-track-player"; import TrackPlayer from "@/core/trackPlayer"; import { musicIsPaused } from "@/utils/trackUtils"; import PersistStatus from "@/utils/persistStatus"; let resumeState: State | null; module.exports = async function () { RNTrackPlayer.addEventListener(Event.RemotePlay, () => TrackPlayer.play()); RNTrackPlayer.addEventListener(Event.RemotePause, () => TrackPlayer.pause(), ); RNTrackPlayer.addEventListener(Event.RemotePrevious, () => TrackPlayer.skipToPrevious(), ); RNTrackPlayer.addEventListener(Event.RemoteNext, () => TrackPlayer.skipToNext(), ); RNTrackPlayer.addEventListener( Event.RemoteDuck, async ({ paused, permanent }) => { if (Config.getConfig("basic.notInterrupt")) { return; } if (permanent) { return TrackPlayer.pause(); } const tempRemoteDuckConf = Config.getConfig( "basic.tempRemoteDuck", ); if (tempRemoteDuckConf === "lowerVolume") { if (paused) { const tempRemoteDuckVolume = Config.getConfig( "basic.tempRemoteDuckVolume", ) ?? 0.5; return RNTrackPlayer.setVolume(1 - tempRemoteDuckVolume); } else { return RNTrackPlayer.setVolume(1); } } else { if (paused) { resumeState = (await RNTrackPlayer.getPlaybackState()).state ?? State.Paused; return TrackPlayer.pause(); } else { if (resumeState && !musicIsPaused(resumeState)) { resumeState = null; return TrackPlayer.play(); } resumeState = null; } } }, ); RNTrackPlayer.addEventListener(Event.PlaybackProgressUpdated, evt => { PersistStatus.set("music.progress", evt.position); }); RNTrackPlayer.addEventListener(Event.RemoteStop, async () => { RNTrackPlayer.stop(); }); RNTrackPlayer.addEventListener(Event.RemoteSeek, async evt => { TrackPlayer.seekTo(evt.position); }); }; ================================================ FILE: src/types/album.d.ts ================================================ declare namespace IAlbum { export interface IAlbumItemBase extends ICommon.IMediaBase { artwork?: string; title: string; date?: string; artist?: string; description: string; /** 专辑内有多少作品 */ worksNum?: number; } export interface IAlbumItem extends IAlbumItemBase { musicList: IMusic.IMusicItem[]; } } ================================================ FILE: src/types/artist.d.ts ================================================ declare namespace IArtist { export interface IArtistItemBase extends ICommon.IMediaBase { name: string; id: string; fans?: number; description?: string; platform: string; avatar: string; worksNum: number; } export interface IArtistItem extends IArtistItemBase { musicList: IMusic.IMusicItemBase; albumList: IAlbum.IAlbumItemBase; [k: string]: any; } export type ArtistMediaType = IArtist.ArtistMediaType; } ================================================ FILE: src/types/common.d.ts ================================================ declare namespace ICommon { /** 支持搜索的媒体类型 */ export type SupportMediaType = | "music" | "album" | "artist" | "sheet" | "lyric"; /** 媒体定义 */ export type SupportMediaItemBase = { music: IMusic.IMusicItemBase; album: IAlbum.IAlbumItemBase; artist: IArtist.IArtistItemBase; sheet: IMusic.IMusicSheetItemBase; lyric: ILyric.ILyricItem; }; export type IUnique = { id: string; [k: string | symbol]: any; }; export type IMediaBase = { id: string; platform: string; $?: any; [k: symbol]: any; [k: string]: any; }; /** 一些额外信息 */ export type IMediaMeta = { /** 关联歌词信息 */ associatedLrc?: IMediaBase; /** 是否下载过 TODO: 删去 */ downloaded?: boolean; /** 本地下载路径 */ localPath?: string; /** 补充的音乐信息 */ mediaItem?: Partial; /** 歌词偏移 */ lyricOffset?: number; lrc?: string; headers?: Record; url?: string; id?: string; platform?: string; qualities?: IMusic.IQuality; $?: { local?: { localLrc?: string; [k: string]: any; }; [k: string]: any; }; [k: string]: any; [k: symbol]: any; }; export type WithMusicList = T & { musicList?: IMusic.IMusicItem[]; }; export type PaginationResponse = { isEnd?: boolean; data?: T[]; }; export interface IPoint { x: number; y: number; } } ================================================ FILE: src/types/core/config.d.ts ================================================ import type { ResumeMode, SortType } from "@/constants/commonConst.ts"; import type { CustomizedColors } from "@/hooks/useColors"; export interface IAppConfigProperties { $schema: "2"; // Basic "basic.autoPlayWhenAppStart": boolean; "basic.useCelluarNetworkPlay": boolean; "basic.useCelluarNetworkDownload": boolean; "basic.maxDownload": number; "basic.clickMusicInSearch": "playMusic" | "playMusicAndReplace"; "basic.clickMusicInAlbum": "playAlbum" | "playMusic"; "basic.downloadPath": string; "basic.notInterrupt": boolean; "basic.tempRemoteDuck": "pause" | "lowerVolume"; "basic.tempRemoteDuckVolume": 0.3 | 0.5 | 0.8; "basic.autoStopWhenError": boolean; "basic.pluginCacheControl": string; "basic.maxCacheSize": number; "basic.defaultPlayQuality": IMusic.IQualityKey; "basic.playQualityOrder": "asc" | "desc"; "basic.defaultDownloadQuality": IMusic.IQualityKey; "basic.downloadQualityOrder": "asc" | "desc"; "basic.musicDetailDefault": "album" | "lyric"; "basic.musicDetailAwake": boolean; "basic.maxHistoryLen": number; "basic.autoUpdatePlugin": boolean; "basic.notCheckPluginVersion": boolean; "basic.lazyLoadPlugin": boolean; "basic.associateLyricType": "input" | "search"; "basic.showExitOnNotification": boolean; "basic.musicOrderInLocalSheet": SortType; "basic.tryChangeSourceWhenPlayFail": boolean; // Lyric "lyric.showStatusBarLyric": boolean; "lyric.topPercent": number; "lyric.leftPercent": number; "lyric.align": number; "lyric.color": string; "lyric.backgroundColor": string; "lyric.widthPercent": number; "lyric.fontSize": number; "lyric.detailFontSize": number; "lyric.autoSearchLyric": boolean; // Theme "theme.background": string; "theme.backgroundOpacity": number; "theme.backgroundBlur": number; "theme.colors": CustomizedColors; "theme.customColors"?: CustomizedColors; "theme.followSystem": boolean; "theme.selectedTheme": string; // Backup "backup.resumeMode": ResumeMode; // Plugin "plugin.subscribeUrl": string; // WebDAV "webdav.url": string; "webdav.username": string; "webdav.password": string; // Debug(保持嵌套结构) "debug.errorLog": boolean; "debug.traceLog": boolean; "debug.devLog": boolean; } export type AppConfigPropertyKey = keyof IAppConfigProperties; export interface IAppConfig { setup(): Promise; setConfig(key: K, value?: T[K]): void; getConfig(key: K): T[K] | undefined; } ================================================ FILE: src/types/core/i18n/index.d.ts ================================================ // 国际化语言数据接口定义 export interface ILanguageData { // 通用词汇 "common.setting": string; // 设置 "common.software": string; // 软件 "common.language": string; // 语言 "common.theme": string; // 主题 "common.other": string; // 其他 "common.cancel": string; // 取消 "common.about": string; // 关于 "common.batchEdit": string; // 批量编辑 "common.selectAll": string; // 全选 "common.unselectAll": string; // 全不选 "common.save": string; // 保存 "common.download": string; // 下载 "common.play": string; // 播放 "common.delete": string; // 删除 "common.unknownName": string; // 未知名称 "common.default": string; // 默认 "common.search": string; // 搜索 "common.clear": string; // 清除 "common.singleMusic": string; // 单曲 "common.album": string; // 专辑 "common.artist": string; // 艺术家 "common.sheet": string; // 歌单 "common.done": string; // 完成 "common.edit": string; // 编辑 "common.local": string; // 本地 "common.sure": string; // 确定 "common.confirm": string; // 确认 "common.view": string; // 查看 "common.open": string; // 打开 "common.username": string; // 用户名 "common.password": string; // 密码 "common.cover": string; // 封面 "common.name": string; // 名称 "common.comment": string; // 评论 "common.emptyList": string; // 空列表 "common.loading": string; // 加载中 "common.error": string; // 出错 "common.clickToRetry": string; // 点击重试 "common.failToLoad": string; // 加载失败 "common.listReachEnd": string; // 列表到底 // 侧边栏相关 "sidebar.basicSettings": string; // 基本设置 "sidebar.pluginManagement": string; // 插件管理 "sidebar.themeSettings": string; // 主题设置 "sidebar.scheduleClose": string; // 定时关闭 "sidebar.backupAndResume": string; // 备份与恢复 "sidebar.permissionManagement": string; // 权限管理 "sidebar.checkUpdate": string; // 检查更新 "sidebar.currentVersion": string; // 当前版本 "sidebar.backToDesktop": string; // 返回桌面 "sidebar.exitApp": string; // 退出应用 "sidebar.languageSettings": string; // 语言设置 // 检查更新相关 "checkUpdate.error.latestVersion": string; // 当前已是最新版本 // 首页相关 "home.recommendSheet": string; // 推荐歌单 "home.topList": string; // 榜单 "home.playHistory": string; // 播放历史 "home.localMusic": string; // 本地音乐 "home.openSidebar.a11y": string; // 打开侧边栏 "home.myPlaylists": string; // 我的歌单 "home.starredPlaylists": string; // 我喜欢的歌单 "home.newPlaylist.a11y": string; // 新建歌单 "home.importPlaylist.a11y": string; // 导入歌单 "home.myPlaylistsCount.a11y": string; // 我的歌单数量 "home.starredPlaylistsCount.a11y": string; // 我喜欢的歌单数量 "home.songCount": string; // 歌曲数量 "home.clickToSearch": string; // 点击搜索 // 对话框相关 "dialog.deleteSheetTitle": string; // 删除歌单 "dialog.deleteSheetContent": string; // 确定删除该歌单吗? "dialog.loading.reinitializeTrackPlayer": string; // 提示消息相关 "toast.deleteSuccess": string; // 删除成功 "toast.hasStarred": string; // 已收藏歌单 "toast.hasUnstarred": string; // 已取消收藏歌单 "toast.importSuccess": string; // 导入成功 "toast.saveSuccess": string; // 保存成功 "toast.sortHasBeenUpdated": string; // 排序已更新 "toast.currentQualityNotAvailableForCurrentMusic": string; // 当前音乐的质量在此设备上不可用 "toast.commmentNotAvaliableForCurrentMusic": string; // 当前音乐无法进行评论 "toast.addToNextPlay": string; // 添加到下一曲 "toast.beginDownload": string; // 开始下载 "toast.rememberToSave": string; // 请记得保存 // 本地音乐相关 "localMusic.scanLocalMusic": string; // 扫描本地音乐 "localMusic.beginScan": string; // 开始扫描 "localMusic.downloadList": string; // 下载列表 // 歌词相关 "lyric.lyricLinkedFrom": string; // 歌词来自 "lyric.unlinkLyric": string; // 取消链接歌词 "lyric.noLyric": string; // 暂无歌词 "lyric.searchLyric": string; // 搜索歌词 // 音乐列表编辑器相关 "musicListEditor.selectMusicCount": string; // 选择的音乐数量 "musicListEditor.addToNextPlay": string; // 添加到下一曲 "musicListEditor.addToSheet": string; // 添加到歌单 // 权限设置相关 "permissionSetting.title": string; // 权限设置 "permissionSetting.description": string; // 权限设置说明 "permissionSetting.floatWindowPermission": string; // 悬浮窗权限 "permissionSetting.floatWindowPermissionDescription": string; // 悬浮窗权限说明 "permissionSetting.fileReadWritePermission": string; // 文件读写权限 "permissionSetting.fileReadWritePermissionDescription": string; // 文件读写权限说明 // 推荐歌单相关 "recommendSheet.title": string; // 推荐歌单 // 搜索音乐列表相关 "searchMusicList.searchPlaceHolder": string; // 搜索音乐 "searchMusicList.searchLabel.a11y": string; // 搜索音乐标签 // 搜索页面相关 "searchPage.searchPlaceHolder": string; // 搜索 "searchPage.searchLabel.a11y": string; // 搜索标签 "searchPage.history": string; // 历史记录 "searchPage.artistResultWorksNum": string; // 艺术家作品数量 "searchPage.comingSoon": string; // 敬请期待 // 榜单相关 "topList.title": string; // 榜单 // 歌单详情相关 "sheetDetail.totalMusicCount": string; // 歌曲总数 "sheetDetail.editSheetInfo": string; // 编辑歌单信息 "sheetDetail.batchEditMusic": string; // 批量编辑音乐 "sheetDetail.sortMusic": string; // 排序音乐 "sheetDetail.sortMusicOption.byTitle": string; // 按标题排序 "sheetDetail.sortMusicOption.byArtist": string; // 按艺术家排序 "sheetDetail.sortMusicOption.byAlbum": string; // 按专辑排序 "sheetDetail.sortMusicOption.newest": string; // 最新 "sheetDetail.sortMusicOption.oldest": string; // 最旧 "sheetDetail.deleteSheet": string; // 删除歌单 "sheetDetail.deleteSheetContent": string; // 确定删除该歌单吗? // 历史记录相关 "history.title": string; // 历史记录 "history.clearHistory": string; // 清除历史记录 // 下载相关 "downloading.title": string; // 下载 "downloading.downloadFailReason.noWritePermission": string; // 下载失败:没有写入权限 "downloading.downloadFailReason.failToFetchSource": string; // 下载失败:无法获取源 "downloading.downloadFailReason.unknown": string; // 下载失败:未知原因 "downloading.downloadStatus.completed": string; // 下载完成 "downloading.downloadStatus.downloadProgress": string; // 下载进度 "downloading.downloadStatus.pending": string; // 等待中 "downloading.downloadStatus.preparing": string; // 准备中 // 艺术家详情相关 "artistDetail.fansCount": string; // 粉丝数量 "artistDetail.menu.batchEditMusic": string; // 批量编辑音乐 "artistDetail.musicSheet": string; // 音乐歌单 // 插件设置相关 "pluginSetting.pluginItem.options.updatePlugin": string; // 更新插件 "pluginSetting.pluginItem.options.sharePlugin": string; // 分享插件 "pluginSetting.pluginItem.options.uninstallPlugin": string; // 卸载插件 "pluginSetting.pluginItem.options.uninstallPluginContent": string; // 确定卸载该插件吗? "pluginSetting.pluginItem.options.alternativePlugin": string; // 替代插件 "pluginSetting.pluginItem.alternativePlugin": string; // 该插件实际使用的插件 "pluginSetting.pluginItem.dialog.setAlternativePluginTitle": string; // 设置替代插件 "pluginSetting.pluginItem.dialog.setAlternativePluginTip": string; // 将使用替代插件解析此插件的音乐源提示 "pluginSetting.pluginItem.options.importMusic": string; // 导入音乐 "pluginSetting.pluginItem.options.importMusicPlaceHolder": string; // 导入音乐链接 "pluginSetting.pluginItem.options.importDialogTitle": string; // 导入音乐对话框标题 "pluginSetting.pluginItem.options.importMusicDialogContent": string; // 导入音乐对话框内容 "pluginSetting.pluginItem.options.importMusicToSheetName": string; // 导入音乐到歌单 "pluginSetting.pluginItem.options.importSheet": string; // 导入歌单 "pluginSetting.pluginItem.options.importSheetPlaceHolder": string; // 导入歌单链接 "pluginSetting.pluginItem.options.importSheetDialogContent": string; // 导入歌单对话框内容 "pluginSetting.pluginItem.options.userVariables": string; // 用户变量 "pluginSetting.pluginItem.versionHint": string; // 版本提示 "pluginSetting.pluginItem.author": string; // 作者 "pluginSetting.menu.subscriptionSetting": string; // 订阅设置 "pluginSetting.menu.sort": string; // 排序 "pluginSetting.menu.uninstallAll": string; // 卸载所有 "pluginSetting.menu.uninstallAllContent": string; // 确定卸载所有插件吗? "pluginSetting.menu.installPlugin": string; // 安装插件 "pluginSetting.menu.installPluginDialogPlaceholder": string; // 插件安装对话框占位符 "pluginSetting.menu.pluginInstallFailedDialogTitle": string; // 插件安装失败对话框标题 "pluginSetting.menu.pluginUpdateFailedDialogTitle": string; // 插件更新失败对话框标题 "pluginSetting.fabOptions.installFromLocal": string; // 从本地安装 "pluginSetting.fabOptions.installFromNetwork": string; // 从网络安装 "pluginSetting.fabOptions.updateAllPlugins": string; // 更新所有插件 "pluginSetting.fabOptions.updateSubscription": string; // 更新订阅 "pluginSetting.failReason": string; // 失败原因 "pluginSetting.pluginInstallFailedDialogContent": string; // 插件安装失败对话框内容 "pluginSetting.pluginUpdateFailedDialogContent": string; // 插件更新失败对话框内容 // 提示消息相关 - 插件操作 "toast.pluginUpdateSuccess": string; // 插件更新成功 "toast.failToUpdatePlugin": string; // 插件更新失败 "toast.copiedToClipboard": string; // 已复制到剪贴板 "toast.copiedToClipboardFailed": string; // 复制失败 "toast.failToSharePlugin": string; // 插件分享失败 "toast.pluginUninstalled": string; // 插件已卸载 "toast.toast.pluginUninstalled": string; // 插件已卸载 "toast.failToImportMusic": string; // 音乐导入失败 "toast.importing": string; // 正在导入 "toast.failToImportSheet": string; // 歌单导入失败 "toast.settingSuccess": string; // 设置成功 "toast.installPluginSuccess": string; // 插件安装成功 "toast.updatePluginSuccess": string; // 插件更新成功 "toast.installPluginFail": string; // 插件安装失败 "toast.allPluginInstallFailed": string; // 所有插件安装失败 "toast.partialPluginInstallFailed": string; // 部分插件安装失败 "toast.partialPluginInstallFailedWithReason": string; // 部分插件安装失败,原因: "toast.allPluginUpdateFailed": string; // 所有插件更新失败 "toast.partialPluginUpdateFailed": string; // 部分插件更新失败 "toast.noSubscription": string; // 没有订阅 "toast.subscriptionInvalid": string; // 订阅无效 "toast.subscriptionHaveToEndWithJs": string; // 订阅必须以.js结尾 "toast.unknownError": string; // 未知错误 // 主题设置相关 "themeSettings.displayStyle": string; // 显示风格 "themeSettings.followSystemTheme": string; // 跟随系统主题 "themeSettings.setTheme": string; // 设置主题 "themeSettings.lightMode": string; // 明亮模式 "themeSettings.darkMode": string; // 黑暗模式 "themeSettings.customMode": string; // 自定义模式 // 自定义主题相关 "setCustomTheme.customizeBackground": string; // 自定义背景 "setCustomTheme.blur": string; // 模糊 "setCustomTheme.opacity": string; // 不透明度 "setCustomTheme.primaryColor": string; // 主题色 "setCustomTheme.textColor": string; // 文字颜色 "setCustomTheme.appBarColor": string; // 应用栏颜色 "setCustomTheme.appBarTextColor": string; // 应用栏文字色 "setCustomTheme.musicBarColor": string; // 音乐栏颜色 "setCustomTheme.musicBarTextColor": string; // 音乐栏文字色 "setCustomTheme.pageBackgroundColor": string; // 页面背景色 "setCustomTheme.backdropColor": string; // 背景色 "setCustomTheme.cardColor": string; // 卡片背景色 "setCustomTheme.placeholderColor": string; // 输入框背景色 "setCustomTheme.tabBarColor": string; // 导航栏背景色 "setCustomTheme.notificationColor": string; // 提示、tips背景色 // 备份与恢复相关 "backupAndResume.beginBackup": string; // 开始备份 "backupAndResume.backupDialogTitle": string; // 备份对话框标题 "backupAndResume.backuping": string; // 正在备份 "toast.backupSuccess": string; // 备份成功 "toast.backupFail": string; // 备份失败 "backupAndResume.resumeFromLocalFile": string; // 从本地文件恢复 "backupAndResume.resuming": string; // 正在恢复 "toast.resumeSuccess": string; // 恢复成功 "toast.resumeFail": string; // 恢复失败 "backupAndResume.resumeFromUrlDialogTitle": string; // 从URL恢复对话框标题 "backupAndResume.resumeFromUrlDialogPlaceHolder": string; // 从URL恢复对话框占位符 "toast.backupFileNotFound": string; // 备份文件未找到 "toast.resumePreCheckFailed": string; // 恢复前检查失败 "backupAndResume.setResumeMode": string; // 设置恢复模式 "backupAndResume.resumeMode": string; // 恢复模式 "backupAndResume.localBackup": string; // 本地备份 "backupAndResume.backupToLocal": string; // 备份到本地 "backupAndResume.webdavSettings": string; // WebDAV设置 "backupAndResume.webdavUrl": string; // WebDAV URL "backupAndResume.backupToWebdav": string; // 备份到WebDAV "backupAndResume.resumeFromWebdav": string; // 从WebDAV恢复 "backupAndResume.resumeMode.append": string; // 附加 "backupAndResume.resumeMode.overwrite-default": string; // 覆盖(默认) "backupAndResume.resumeMode.overwrite": string; // 覆盖 // 基本设置相关 "basicSettings.common": string; // 通用 "basicSettings.maxHistoryLength": string; // 最大历史记录长度 "basicSettings.musicDetailDefault": string; // 音乐详情默认 "basicSettings.musicDetailDefault.album": string; // 专辑 "basicSettings.musicDetailDefault.lyric": string; // 歌词 "basicSettings.musicDetailAwake": string; // 唤醒音乐详情 "basicSettings.associateLyricType": string; // 关联歌词类型 "basicSettings.associateLyricType.input": string; // 输入 "basicSettings.associateLyricType.search": string; // 搜索 "basicSettings.showExitOnNotification": string; // 通知中显示退出 "basicSettings.sheetAndAlbum": string; // 歌单和专辑 "basicSettings.clickMusicInSearch": string; // 点击搜索中的音乐 "basicSettings.clickMusicInSearch.playMusic": string; // 播放歌曲 "basicSettings.clickMusicInSearch.playMusicAndReplace": string; // 播放歌曲并替换播放列表 "basicSettings.clickMusicInAlbum": string; // 点击专辑内单曲时 "basicSettings.clickMusicInAlbum.playMusic": string; // 播放歌曲 "basicSettings.clickMusicInAlbum.playAlbum": string; // 播放专辑 "basicSettings.musicOrderInLocalSheet": string; // 新建歌单时默认歌曲排序 "basicSettings.musicOrderInLocalSheet.title": string; // 按歌曲名排序 "basicSettings.musicOrderInLocalSheet.artist": string; // 按作者名排序 "basicSettings.musicOrderInLocalSheet.album": string; // 按专辑名排序 "basicSettings.musicOrderInLocalSheet.newest": string; // 按收藏时间从新到旧排序 "basicSettings.musicOrderInLocalSheet.oldest": string; // 按收藏时间从旧到新排序 "basicSettings.plugin": string; // 插件 "basicSettings.autoUpdatePlugin": string; // 软件启动时自动更新插件 "basicSettings.notCheckPluginVersion": string; // 安装插件时不校验版本 "basicSettings.lazyLoadPlugin": string; // 启用插件懒加载(实验性功能) "basicSettings.playback": string; // 播放 "basicSettings.notInterrupt": string; // 允许与其他应用同时播放 "basicSettings.autoPlayWhenAppStart": string; // 软件启动时自动播放歌曲 "basicSettings.tryChangeSourceWhenPlayFail": string; // 播放失败时尝试更换音源 "basicSettings.autoStopWhenError": string; // 播放失败时自动暂停 "basicSettings.tempRemoteDuck": string; // 播放被暂时打断时 "basicSettings.tempRemoteDuck.pause": string; // 暂停播放 "basicSettings.tempRemoteDuck.lowerVolume": string; // 降低音量 "basicSettings.tempRemoteDuck.volumeDecreaseLevel": string; // 音量降低幅度 "basicSettings.defaultPlayQuality": string; // 默认播放音质 "basicSettings.playQualityOrder": string; // 默认播放音质缺失时 "basicSettings.playQualityOrder.asc": string; // 播放更高音质 "basicSettings.playQualityOrder.desc": string; // 播放更低音质 "basicSettings.download": string; // 下载 "basicSettings.downloadPath": string; // 下载路径 "basicSettings.fileSelector.selectFolder": string; // 选择文件夹 "basicSettings.maxDownload": string; // 最大同时下载数目 "basicSettings.defaultDownloadQuality": string; // 默认下载音质 "basicSettings.downloadQualityOrder": string; // 默认下载音质缺失时 "basicSettings.downloadQualityOrder.asc": string; // 下载更高音质 "basicSettings.downloadQualityOrder.desc": string; // 下载更低音质 "basicSettings.network": string; // 网络 "basicSettings.useCelluarNetworkPlay": string; // 使用移动网络播放 "basicSettings.useCelluarNetworkDownload": string; // 使用移动网络下载 "basicSettings.lyric": string; // 歌词 "basicSettings.lyric.autoSearchLyric": string; // 歌词缺失时自动搜索歌词 "basicSettings.lyric.showStatusBarLyric": string; // 开启桌面歌词 "basicSettings.lyric.align": string; // 对齐方式 "basicSettings.lyric.align.left": string; // 左对齐 "basicSettings.lyric.align.center": string; // 居中对齐 "basicSettings.lyric.align.right": string; // 右对齐 "basicSettings.lyric.leftRightDistance": string; // 左右距离 "basicSettings.lyric.topBottomDistance": string; // 上下距离 "basicSettings.lyric.width": string; // 歌词宽度 "basicSettings.lyric.fontSize": string; // 字体大小 "basicSettings.lyric.textColor": string; // 文本颜色 "basicSettings.lyric.backgroundColor": string; // 文本背景色 "basicSettings.cache": string; // 缓存 "basicSettings.cache.musicCacheLimit": string; // 音乐缓存上限 "basicSettings.cache.clearMusicCache": string; // 清除音乐缓存 "basicSettings.cache.clearLyricCache": string; // 清除歌词缓存 "basicSettings.cache.clearImageCache": string; // 清除图片缓存 "basicSettings.developer": string; // 开发选项 "basicSettings.developer.errorLog": string; // 记录错误日志 "basicSettings.developer.traceLog": string; // 记录详细日志 "basicSettings.developer.devLog": string; // 调试面板 "basicSettings.developer.viewErrorLog": string; // 查看错误日志 "basicSettings.developer.clearLog": string; // 清空日志 // 对话框相关 - 缓存设置 "dialog.setCacheTitle": string; // 设置缓存 "dialog.setCachePlaceholder": string; // 输入缓存占用上限提示 "dialog.clearMusicCacheTitle": string; // 清除音乐缓存 "dialog.clearMusicCacheContent": string; // 清除音乐缓存确认内容 "dialog.clearLyricCacheTitle": string; // 清除歌词缓存 "dialog.clearLyricCacheContent": string; // 清除歌词缓存确认内容 "dialog.clearImageCacheTitle": string; // 清除图片缓存 "dialog.clearImageCacheContent": string; // 清除图片缓存确认内容 "dialog.errorLogTitle": string; // 错误日志 "dialog.errorLogNoRecord": string; // 暂无记录 "dialog.errorLogKnow": string; // 我知道了 "dialog.errorLogCopy": string; // 复制日志 "dialog.setScheduleCloseTime.title": string; // 设置定时关闭时间 "dialog.setScheduleCloseTime.placeholder": string; // 请输入时间 "dialog.setScheduleCloseTime.unit": string; // 分钟 "dialog.setScheduleCloseTime.hint": string; // 最长支持设置24小时(1440分钟) // 提示消息相关 - 缓存和日志 "toast.cacheSetSuccess": string; // 设置成功 "toast.musicCacheCleared": string; // 已清除音乐缓存 "toast.lyricCacheCleared": string; // 已清除歌词缓存 "toast.imageCacheCleared": string; // 已清除图片缓存 "toast.logCleared": string; // 日志已清空 "toast.noFloatWindowPermission": string; // 无悬浮窗权限 "toast.folderNotExistOrNoPermission": string; // 文件夹不存在或无权限 // 音质相关 "musicQuality.low": string; // 低音质 "musicQuality.standard": string; // 标准音质 "musicQuality.high": string; // 高音质 "musicQuality.super": string; // 超高音质 // 播放全部栏相关 "playAllBar.title": string; // 播放全部 // 无插件相关 "noPlugin.title": string; // 还没有安装插件 "noPlugin.titleWithType": string; // 还没有安装支持类型的插件 "noPlugin.description": string; // 无插件描述 // 对话框相关 - 存储权限 "dialog.checkStorage.title": string; // 存储权限 "dialog.checkStorage.content.0": string; // 存储权限内容0 "dialog.checkStorage.content.1": string; // 存储权限内容1 "dialog.checkStorage.content.2": string; // 存储权限内容2 "dialog.checkStorage.content.3": string; // 存储权限内容3 "dialog.checkStorage.button.grantPermission": string; // 去授予权限 "dialog.checkStorage.button.doNotShowAgain": string; // 不再提示 // 对话框相关 - 下载 "dialog.downloadDialog.title": string; // 发现新版本 "dialog.downloadDialog.skipThisVersion": string; // 跳过此版本 "dialog.downloadDialog.downloadUsingBrowser": string; // 从浏览器下载 "dialog.downloadDialog.backupUrl": string; // 备用链接 "dialog.editSheetDetail.sheetName": string; // 歌单名 "dialog.subscriptionPluginDialog.title": string; // 订阅 "dialog.markdownDialog.openExternalLink": string; // Markdown对话框打开外部链接 "dialog.markdownDialog.clickToShowImage": string; // 点击展示图片 "dialog.markdownDialog.loadFailed": string; // 图片加载失败 // 面板相关 - 播放列表 "panel.playList.title": string; // 播放列表 "panel.playList.count": string; // 歌曲数量 "panel.searchLrc.inputPlaceholder": string; // 搜索歌词输入占位符 "panel.searchLrc.toast.settingSuccess": string; // 设置成功 "panel.searchLrc.toast.failToSearch": string; // 设置失败 // 面板相关 - 添加到歌单 "panel.addToMusicSheet.title": string; // 添加到歌单 "panel.addToMusicSheet.newMusicSheet": string; // 新建歌单 "panel.addToMusicSheet.count": string; // 歌曲数量 "panel.addToMusicSheet.toast.success": string; // 已添加到歌单 "panel.addToMusicSheet.toast.fail": string; // 添加到歌单失败 "panel.associateLrc.title": string; // 关联歌词 "panel.associateLrc.inputPlaceholder": string; // 输入要关联歌词的歌曲ID "panel.associateLrc.targetExpired": string; // 地址失效 "panel.associateLrc.toast.success": string; // 关联歌词成功 "panel.associateLrc.toast.fail": string; // 关联歌词失败 "panel.associateLrc.toast.unlinkSuccess": string; // 取消关联歌词成功 "panel.createMusicSheet.title": string; // 新建歌单 "panel.editMusicSheetInfo.title": string; // 编辑歌单信息 "panel.editMusicSheetInfo.sheetName": string; // 歌单名 "panel.editMusicSheetInfo.toast.updateSuccess": string; // 更新歌单信息成功 // 面板相关 - 图片查看器 "panel.imageViewer.saveImage": string; // 保存图片 "panel.imageViewer.saveImageSuccess": string; // 图片已保存 "panel.imageViewer.saveImageFail": string; // 保存图片失败 // 面板相关 - 颜色选择器 "panel.colorPicker.title": string; // 选择颜色 "panel.createMusicSheet.inputLabel": string; // 输入框 "panel.importMusicSheet.title": string; // 导入歌单 "panel.importMusicSheet.placeholder": string; // 输入目标歌单 "panel.importMusicSheet.importing": string; // 正在导入中 "panel.importMusicSheet.prepareImport": string; // 准备导入 "panel.importMusicSheet.foundSongs": string; // 发现歌曲 "panel.importMusicSheet.invalidLink": string; // 链接有误或目标歌单为空 // 面板相关 - 音乐项歌词选项 "panel.musicItemLyricOptions.author": string; // 作者 "panel.musicItemLyricOptions.album": string; // 专辑 "panel.musicItemLyricOptions.toggleDesktopLyric": string; // 桌面歌词开关 "panel.musicItemLyricOptions.enableDesktopLyric": string; // 开启 "panel.musicItemLyricOptions.disableDesktopLyric": string; // 关闭 "panel.musicItemLyricOptions.desktopLyricPermissionError": string; // 桌面歌词权限错误 "panel.musicItemLyricOptions.uploadLocalLyric": string; // 上传本地歌词 "panel.musicItemLyricOptions.uploadLocalLyricTranslation": string; // 上传本地歌词翻译 "panel.musicItemLyricOptions.deleteLocalLyric": string; // 删除本地歌词 "panel.musicItemLyricOptions.settingFail": string; // 设置失败 "panel.musicItemLyricOptions.deleteFail": string; // 删除失败 // 面板相关 - 音乐项选项 "panel.musicItemOptions.author": string; // 作者 "panel.musicItemOptions.album": string; // 专辑 "panel.musicItemOptions.downloaded": string; // 已下载 "panel.musicItemOptions.readComment": string; // 查看评论 "panel.musicItemOptions.deleteLocalDownload": string; // 删除本地下载 "panel.musicItemOptions.deleteLocalDownloadConfirm": string; // 删除本地下载确认 "panel.musicItemOptions.associatedLyric": string; // 已关联歌词 "panel.musicItemOptions.associateLyric": string; // 关联歌词 "panel.musicItemOptions.unassociateLyric": string; // 解除关联歌词 "panel.musicItemOptions.unassociateLyricSuccess": string; // 已解除关联歌词 "panel.musicItemOptions.timingClose": string; // 定时关闭 "panel.musicItemOptions.clearPluginCache": string; // 清除插件缓存 "panel.musicItemOptions.cacheCleared": string; // 缓存已清除 "panel.musicItemOptions.deleteFailed": string; // 删除失败 // 面板相关 - 音质设置 "panel.musicQuality.title": string; // 设置音质 // 面板相关 - 搜索歌词 "panel.searchLrc.unnamed": string; // 未命名 "panel.searchLrc.notSupported": string; // 搜索歌词 // 面板相关 - 字体大小设置 "panel.setFontSize.title": string; // 设置字体大小 "panel.setFontSize.small": string; // 小 "panel.setFontSize.standard": string; // 标准 "panel.setFontSize.large": string; // 大 "panel.setFontSize.extraLarge": string; // 超大 // 面板相关 - 歌词偏移设置 "panel.setLyricOffset.title": string; // 设置歌词进度 "panel.setLyricOffset.normal": string; // 正常 "panel.setLyricOffset.delay": string; // 延后 "panel.setLyricOffset.advance": string; // 提前 "panel.setLyricOffset.reset": string; // 重置 // 面板相关 - 简单输入 "panel.simpleInput.inputLabel": string; // 输入框 // 面板相关 - 定时关闭 "panel.timingClose.countdown": string; // 关闭倒计时 "panel.timingClose.customize": string; // 自定义 "panel.timingClose.cancelScheduleClose": string; // 取消定时关闭 "panel.timingClose.closeAfterPlay": string; // 播放完歌曲再关闭 // 面板相关 - 播放速度 "panel.playRate.title": string; // 播放速度 // 面板相关 - 歌单标签 "panel.sheetTags.title": string; // 歌单类别 // 播放模式相关 "repeatMode.SHUFFLE": string; // 随机播放 "repeatMode.QUEUE": string; // 列表循环 "repeatMode.SINGLE": string; // 单曲循环 } // 语言接口定义 export interface ILanguage { locale: string; // 语言代码 name: string; // 语言名称 languageData: ILanguageData; // 语言数据 } ================================================ FILE: src/types/core/musicHistory.d.ts ================================================ import type { IInjectable } from "@/types/infra"; export interface IMusicHistory extends IInjectable { /** * Get current music history */ readonly history: IMusic.IMusicItem[]; /** * Initialize music history from storage */ setup(): Promise; /** * Add a music item to history */ addMusic(musicItem: IMusic.IMusicItem): Promise; /** * Remove a music item from history */ removeMusic(musicItem: IMusic.IMusicItem): Promise; /** * Clear all music history */ clearMusic(): Promise; /** * Set new music history */ setHistory(newHistory: IMusic.IMusicItem[]): Promise; } ================================================ FILE: src/types/core/pluginManager/index.d.ts ================================================ type Plugin = any; // Placeholder for the actual Plugin type /** * 插件安装配置接口 */ export interface IInstallPluginConfig { notCheckVersion?: boolean; } /** * 插件安装结果接口 */ export interface IInstallPluginResult { success: boolean; message?: string; pluginName?: string; pluginHash?: string; pluginUrl?: string; } /** * 插件管理器接口 */ export interface IPluginManager { /** * 初始化插件管理器,从文件系统加载所有插件 * 读取插件目录中的所有.js文件并创建插件实例 * @throws 如果插件初始化失败则抛出异常 */ setup(): Promise; /** * 从本地文件安装插件 * @param pluginPath - 插件文件路径 * @param config - 安装配置选项 * @param config.notCheckVersion - 为true时跳过版本检查 * @param config.useExpoFs - 为true时使用Expo文件系统代替React Native的文件系统 * @returns 安装结果,包含成功状态和相关信息 */ installPluginFromLocalFile( pluginPath: string, config?: IInstallPluginConfig & { useExpoFs?: boolean }, ): Promise; /** * 从URL安装插件 * @param url - 下载插件的URL * @param config - 安装配置选项 * @param config.notCheckVersion - 为true时跳过版本检查 * @returns 安装结果,包含成功状态和相关信息 */ installPluginFromUrl( url: string, config?: IInstallPluginConfig, ): Promise; /** * 通过哈希值卸载插件 * @param hash - 要卸载的插件哈希值 */ uninstallPlugin(hash: string): Promise; /** * 卸载系统中的所有插件 * 同时清理媒体额外数据并删除插件文件 */ uninstallAllPlugins(): Promise; /** * 使用插件的源URL更新插件 * @param plugin - 要更新的插件实例 * @throws 如果插件没有源URL或更新失败时抛出错误 */ updatePlugin(plugin: Plugin): Promise; /** * 通过媒体项的平台信息获取对应的插件 * @param mediaItem - 包含平台信息的媒体项 * @returns 与媒体平台匹配的插件实例或undefined */ getByMedia(mediaItem: ICommon.IMediaBase): Plugin | undefined; /** * 通过名称获取插件 * @param name - 要查找的插件名称 * @returns 匹配名称的插件实例或本地文件插件 */ getByName(name: string): Plugin | undefined; /** * 通过哈希值获取插件 * @param hash - 要查找的插件哈希值 * @returns 匹配哈希的插件实例或本地文件插件 */ getByHash(hash: string): Plugin | undefined; /** * 获取所有已启用的插件 * @returns 已启用的插件实例数组 */ getEnabledPlugins(): Plugin[]; /** * 获取按顺序排序的所有插件 * @returns 按定义顺序排序的插件实例数组 */ getSortedPlugins(): Plugin[]; /** * 获取所有支持搜索功能的已启用插件 * @param supportedSearchType - 可选的搜索媒体类型过滤器 * @returns 可搜索的插件实例数组 */ getSearchablePlugins(supportedSearchType?: ICommon.SupportMediaType): Plugin[]; /** * 获取所有支持搜索功能的已启用插件,并按顺序排序 * @param supportedSearchType - 可选的搜索媒体类型过滤器 * @returns 按顺序排序的可搜索插件实例数组 */ getSortedSearchablePlugins( supportedSearchType?: ICommon.SupportMediaType, ): Plugin[]; /** * 获取所有实现特定功能的已启用插件 * @param ability - 要检查的方法/功能名称 * @returns 具有指定功能的插件实例数组 */ getPluginsWithAbility(ability: keyof IPlugin.IPluginInstanceMethods): Plugin[]; /** * 获取所有实现特定功能的已启用插件,并按顺序排序 * @param ability - 要检查的方法/功能名称 * @returns 按顺序排序的具有指定功能的插件实例数组 */ getSortedPluginsWithAbility(ability: keyof IPlugin.IPluginInstanceMethods): Plugin[]; /** * 设置插件的启用状态并发送事件通知 * @param plugin - 要修改的插件实例 * @param enabled - 是否启用插件 */ setPluginEnabled(plugin: Plugin, enabled: boolean): void; /** * 检查插件是否已启用 * @param plugin - 要检查的插件实例 * @returns 表示插件是否启用的布尔值 */ isPluginEnabled(plugin: Plugin): boolean; /** * 设置插件的排序顺序并发送顺序更新事件 * @param sortedPlugins - 按期望顺序排列的插件实例数组 */ setPluginOrder(sortedPlugins: Plugin[]): void; /** * 设置插件的用户变量 * @param plugin - 要设置用户变量的插件实例 * @param userVariables - 用户变量键值对 */ setUserVariables(plugin: Plugin, userVariables: Record): void; /** * 获取插件的用户变量 * @param plugin - 要获取用户变量的插件实例 * @returns 用户变量键值对 */ getUserVariables(plugin: Plugin): Record; /** * 设置插件的替代插件名称 * @param plugin - 要设置替代插件的插件实例 * @param alternativePluginName - 替代插件的名称 */ setAlternativePluginName(plugin: Plugin, alternativePluginName: string): void; /** * 获取插件的替代插件名称 * @param plugin - 要获取替代插件名称的插件实例 * @returns 替代插件的名称 */ getAlternativePluginName(plugin: Plugin): string | null; /** * 获取插件的替代插件实例 * @param plugin - 要获取替代插件的插件实例 * @returns 替代插件实例或null */ getAlternativePlugin(plugin: Plugin): Plugin | null; } ================================================ FILE: src/types/core/trackPlayer/index.d.ts ================================================ import type { Progress } from "react-native-track-player"; import type { MusicRepeatMode } from "@/constants/repeatModeConst"; import { IInjectable } from "@/types/infra"; import type EventEmitter from "eventemitter3"; import type { TrackPlayerEvents } from "@/core.defination/trackPlayer"; export interface ITrackPlayer extends IInjectable, EventEmitter<{ [TrackPlayerEvents.PlayEnd]: () => void; [TrackPlayerEvents.CurrentMusicChanged]: (musicItem: IMusic.IMusicItem | null) => void; [TrackPlayerEvents.ProgressChanged]: (progress: { position: number; duration: number; }) => void; }> { /** * 上一首歌曲 */ readonly previousMusic: IMusic.IMusicItem | null; /** * 当前播放的歌曲 */ readonly currentMusic: IMusic.IMusicItem | null; /** * 下一首歌曲 */ readonly nextMusic: IMusic.IMusicItem | null; /** * 当前播放模式 */ readonly repeatMode: MusicRepeatMode; /** * 当前播放音质 */ readonly quality: IMusic.IQualityKey; /** * 当前播放列表 */ readonly playList: IMusic.IMusicItem[]; /** * 初始化音乐播放器,恢复上次播放状态 */ setupTrackPlayer(): Promise; /** * 获取音乐在播放列表中的索引 * @param musicItem 要查找的音乐项 * @returns 索引值,如不存在则返回-1 */ getMusicIndexInPlayList(musicItem?: IMusic.IMusicItem | null): number; /** * 判断音乐是否在播放列表中 * @param musicItem 要查找的音乐项 * @returns 是否存在于播放列表 */ isInPlayList(musicItem?: IMusic.IMusicItem | null): boolean; /** * 获取播放列表中指定索引的音乐 * @param index 索引,支持循环索引(负数或超出长度会自动取模) * @returns 音乐项或null(如果列表为空) */ getPlayListMusicAt(index: number): IMusic.IMusicItem | null; /** * 判断播放列表是否为空 * @returns 播放列表是否为空 */ isPlayListEmpty(): boolean; /** * 批量添加音乐到播放列表 * @param musicItems 要添加的音乐列表 * @param beforeIndex 在指定位置之前添加,undefined表示添加到末尾 * @param shouldShuffle 是否随机排序添加的音乐 */ addAll( musicItems: Array, beforeIndex?: number, shouldShuffle?: boolean ): void; /** * 添加音乐到播放列表 * @param musicItem 单曲或音乐列表 * @param beforeIndex 在指定位置之前添加,undefined表示添加到末尾 */ add( musicItem: IMusic.IMusicItem | IMusic.IMusicItem[], beforeIndex?: number ): void; /** * 添加音乐到下一首播放位置 * @param musicItem 单曲或音乐列表 */ addNext(musicItem: IMusic.IMusicItem | IMusic.IMusicItem[]): void; /** * 从播放列表中移除指定音乐 * @param musicItem 要移除的音乐 */ remove(musicItem: IMusic.IMusicItem): Promise; /** * 判断指定音乐是否是当前播放的音乐 * @param musicItem 要判断的音乐 * @returns 是否是当前音乐 */ isCurrentMusic(musicItem?: IMusic.IMusicItem | null): boolean; /** * 跳到播放列表的下一首 */ skipToNext(): Promise; /** * 跳到播放列表的上一首 */ skipToPrevious(): Promise; /** * 播放指定音乐或切换播放状态 * @param musicItem 要播放的音乐项,为空则播放/暂停当前音乐 * @param forcePlay 是否强制从头开始播放 */ play( musicItem?: IMusic.IMusicItem | null, forcePlay?: boolean ): Promise; /** * 播放指定音乐并替换整个播放列表 * @param musicItem 要播放的音乐 * @param newPlayList 新的播放列表 */ playWithReplacePlayList( musicItem: IMusic.IMusicItem, newPlayList: IMusic.IMusicItem[] ): Promise; /** * 暂停播放 */ pause(): Promise; /** * 切换到下一个播放模式(列表循环->随机播放->单曲循环) */ toggleRepeatMode(): void; /** * 清空播放列表并停止播放 */ clearPlayList(): Promise; /** * 切换播放音质 * @param newQuality 目标音质 * @returns 是否切换成功 */ changeQuality(newQuality: IMusic.IQualityKey): Promise; /** * 获取当前播放进度 * @returns 包含播放位置和总时长的对象 */ getProgress(): Promise; /** * 获取当前播放速率 * @returns 当前播放速率 */ getRate(): Promise; /** * 设置播放速率 * @param rate 播放速率 */ setRate(rate: number): Promise; /** * 跳转到指定播放位置 * @param position 目标位置(秒) */ seekTo(position: number): Promise; } ================================================ FILE: src/types/declarations.d.ts ================================================ declare module "*.svg" { import React from "react"; import { SvgProps } from "react-native-svg"; const content: React.FC; export default content; } ================================================ FILE: src/types/infra.d.ts ================================================ export interface IInjectable { injectDependencies (...args: unknown[]): void; } ================================================ FILE: src/types/lyric.d.ts ================================================ declare namespace ILyric { export interface ILyricItem extends IMusic.IMusicItem { /** 歌词(无时间戳) */ rawLrcTxt?: string; } export interface ILyricSource { /** @deprecated 歌词url */ lrc?: string; /** 纯文本格式歌词 */ rawLrc?: string; /** 纯文本格式的翻译 */ translation?: string; } export interface IParsedLrcItem { /** 时间 s */ time: number; /** 歌词 */ lrc: string; /** 下标 */ index?: number; } export type IParsedLrc = IParsedLrcItem[]; } ================================================ FILE: src/types/media.d.ts ================================================ declare namespace IMedia { export interface ICommentItem { id?: string; // 用户名 nickName: string; // 头像 avatar?: string; // 评论内容 comment: string; // 点赞数 like?: number; // 评论时间 createAt?: number; // 地址 location?: string; } export interface IComment extends ICommentItem { // 回复 replies?: IComment[]; } } ================================================ FILE: src/types/music.d.ts ================================================ declare namespace IMusic { export interface IMusicItemBase extends ICommon.IMediaBase { /** 其他属性 */ [k: keyof IMusicItem]: IMusicItem[k]; } /** 音质 */ export type IQualityKey = "low" | "standard" | "high" | "super"; export type IQuality = Record< IQualityKey, { url?: string; size?: string | number; } >; // 音源定义 export interface IMediaSource { headers?: Record; /** 兜底播放 */ url?: string; /** UA */ userAgent?: string; /** 音质 */ quality?: IMusic.IQualityKey; /** 大小 */ size?: number; } export interface IMusicItem { /** 歌曲在平台的唯一编号 */ id: string; /** 平台 */ platform: string; /** 作者 */ artist: string; /** 标题 */ title: string; /** 别名 */ alias?: string; /** 时长(s) */ duration: number; /** 专辑名 */ album: string; /** 专辑封面图 */ artwork: string; /** 默认音源 */ url?: string; /** 音源 */ source?: Partial>; /** 歌词 */ lyric?: ILyric.ILyricSource; /** @deprecated 歌词URL */ lrc?: string; /** @deprecated 歌词(原始文本 有时间戳) */ rawLrc?: string; /** 音质信息 */ qualities?: IQuality; /** 其他可以被序列化的信息 */ [k: string]: any; /** 内部信息 */ [k: symbol]: any; } export interface IMusicItemCache extends IMusicItem { $localLyric?: ILyric.ILyricSource; } } ================================================ FILE: src/types/musicSheet.d.ts ================================================ declare namespace IMusic { export interface IMusicSheetItemBase { /** 封面图 */ coverImg?: string; artwork?: string; /** 标题 */ title?: string; /** 作者 */ artist?: string; /** 歌单id */ id: string; /** 描述 */ description?: string; /** 作品总数 */ worksNum?: number; platform: string; [k: string]: any; } /** 歌单项 */ export interface IMusicSheetItem extends IMusicSheetItemBase { musicList: Array; } export type IMusicSheet = Array; } ================================================ FILE: src/types/musicSheetGroup.d.ts ================================================ declare namespace IMusic { /** 歌单项 */ export interface IMusicSheetGroupItem { title?: string; data: Array; } } ================================================ FILE: src/types/plugin.d.ts ================================================ declare namespace IPlugin { export interface IMediaSourceResult { headers?: Record; /** 兜底播放 */ url?: string; /** UA */ userAgent?: string; /** 音质 */ quality?: IMusic.IQualityKey; } export interface ISearchResult { isEnd?: boolean; data: ICommon.SupportMediaItemBase[T][]; } export type ISearchResultType = ICommon.SupportMediaType; type ISearchFunc = ( query: string, page: number, type: T, ) => Promise>; type IGetArtistWorksFunc = ( artistItem: IArtist.IArtistItem, page: number, type: T, ) => Promise>; interface IUserVariable { /** 键 */ key: string; /** 名称 */ name?: string; /** 提示文案 */ hint?: string; } interface IAlbumInfoResult { isEnd?: boolean; albumItem?: IAlbum.IAlbumItemBase; musicList?: IMusic.IMusicItem[]; } interface ISheetInfoResult { isEnd?: boolean; sheetItem?: IMusic.IMusicSheetItemBase; musicList?: IMusic.IMusicItem[]; } interface ITopListInfoResult { isEnd?: boolean; topListItem?: IMusic.IMusicSheetItem; musicList?: IMusic.IMusicItem[]; } interface IGetRecommendSheetTagsResult { // 固定的tag pinned?: IMusic.IMusicSheetItemBase[]; data?: IMusic.IMusicSheetGroupItem[]; } interface IPluginDefine { /** 来源名 */ platform: string; /** 匹配的版本号 */ appVersion?: string; /** 插件版本 */ version?: string; /** 远程更新的url */ srcUrl?: string; /** 主键,会被存储到mediameta中 */ primaryKey?: string[]; /** 默认搜索类型 */ defaultSearchType?: ICommon.SupportMediaType; /** 有效搜索类型 */ supportedSearchType?: ICommon.SupportMediaType[]; /** 插件缓存控制 */ cacheControl?: "cache" | "no-cache" | "no-store"; /** 插件作者 */ author?: string; /** 插件描述,支持markdown */ description?: string; /** 用户自定义输入 */ userVariables?: IUserVariable[]; /** 提示文本 */ hints?: Record; /** 搜索 */ search?: ISearchFunc; /** 获取根据音乐信息获取url */ getMediaSource?: ( musicItem: IMusic.IMusicItemBase, quality: IMusic.IQualityKey, ) => Promise; /** 根据主键去查询歌曲信息 */ getMusicInfo?: ( musicBase: ICommon.IMediaBase, ) => Promise | null>; /** 获取歌词 */ getLyric?: ( musicItem: IMusic.IMusicItemBase, ) => Promise; /** 获取专辑信息,里面的歌曲分页 */ getAlbumInfo?: ( albumItem: IAlbum.IAlbumItemBase, page: number, ) => Promise; /** 获取歌单信息,有分页 */ getMusicSheetInfo?: ( sheetItem: IMusic.IMusicSheetItem, page: number, ) => Promise; /** 获取作品,有分页 */ getArtistWorks?: IGetArtistWorksFunc; /** 导入歌单 */ // todo: 数据结构应该是IMusicSheetItem importMusicSheet?: ( urlLike: string, ) => Promise; /** 导入单曲 */ importMusicItem?: ( urlLike: string, ) => Promise; /** 获取榜单 */ getTopLists?: () => Promise; /** 获取榜单详情 */ getTopListDetail?: ( topListItem: IMusic.IMusicSheetItemBase, page: number, ) => Promise; /** 获取热门歌单tag */ getRecommendSheetTags?: () => Promise; /** 歌单列表 */ getRecommendSheetsByTag?: ( tag: ICommon.IUnique, page?: number, ) => Promise>; /** 获取评论 */ getMusicComments?: ( musicItem: IMusic.IMusicItem, page?: number ) => Promise>; } export interface IPluginInstance extends IPluginDefine { /** 内部属性 */ /** 插件路径 */ _path: string; } type R = Required; export type IPluginInstanceMethods = { [K in keyof R as R[K] extends (...args: any) => any ? K : never]: R[K]; }; /** 插件其他属性 */ export type IPluginMeta = { order: number; userVariables: Record; enabled?: boolean; }; } ================================================ FILE: src/utils/base64.ts ================================================ /* eslint-disable no-bitwise */ // @ts-nocheck // @flow // Inspired by: https://github.com/davidchambers/Base64.js/blob/master/base64.js const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; const Base64 = { btoa: (input: string = "") => { let str = input; let output = ""; for ( let block = 0, charCode, i = 0, map = chars; str.charAt(i | 0) || ((map = "="), i % 1); output += map.charAt(63 & (block >> (8 - (i % 1) * 8))) ) { charCode = str.charCodeAt((i += 3 / 4)); if (charCode > 0xff) { throw new Error( "'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.", ); } block = (block << 8) | charCode; } return output; }, atob: (input: string = "") => { let str = input.replace(/[=]+$/, ""); let output = ""; if (str.length % 4 == 1) { throw new Error( "'atob' failed: The string to be decoded is not correctly encoded.", ); } for ( let bc = 0, bs = 0, buffer, i = 0; (buffer = str.charAt(i++)); ~buffer && ((bs = bc % 4 ? bs * 64 + buffer : buffer), bc++ % 4) ? (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6)))) : 0 ) { buffer = chars.indexOf(buffer); } return output; }, }; export default Base64; ================================================ FILE: src/utils/checkUpdate.ts ================================================ import axios from "axios"; import { compare } from "compare-versions"; import DeviceInfo from "react-native-device-info"; const updateList = [ "https://gitee.com/maotoumao/MusicFree/raw/master/release/version.json", "https://raw.githubusercontent.com/maotoumao/MusicFree/master/release/version.json", "https://cdn.jsdelivr.net/gh/maotoumao/MusicFree@master/release/version.json", ]; interface IUpdateInfo { needUpdate: boolean; data: { version: string; changeLog: string[]; download: string[]; }; } export default async function checkUpdate(): Promise { const currentVersion = DeviceInfo.getVersion(); for (let i = 0; i < updateList.length; ++i) { try { const rawInfo = (await axios.get(updateList[i])).data; if (compare(rawInfo.version, currentVersion, ">")) { return { needUpdate: true, data: rawInfo, }; } } catch {} } } ================================================ FILE: src/utils/colorUtil.ts ================================================ import Color from "color"; export function grayRate(color: string | Color) { let _color = typeof color === "string" ? Color(color) : color; return ( ((0.299 * _color.red() + 0.587 * _color.green() + 0.114 * _color.blue()) * 2 - 255) / 255 ); } export function grayLevelCode(color: string | Color) { const gray = grayRate(color); console.log(gray); if (gray < 96) { return "dark"; } else if (gray > 160) { return "light"; } else { return "mid"; } } ================================================ FILE: src/utils/delay.ts ================================================ import BackgroundTimer from "react-native-background-timer"; export default function (millsecond: number, background = true) { return new Promise(resolve => { if (background) { BackgroundTimer.setTimeout(resolve, millsecond); } else { setTimeout(resolve, millsecond); } }); } ================================================ FILE: src/utils/eventBus.ts ================================================ import EventEmitter from "eventemitter3"; class EventBus { private ee: EventEmitter; constructor() { this.ee = new EventEmitter(); } /** * 监听 * @param eventName 事件名 * @param callBack 回调 */ on( eventName: K, callBack: (payload: T[K]) => void, ) { this.ee.on(eventName, callBack); } once( eventName: K, callBack: (payload: T[K]) => void, ) { this.ee.once(eventName, callBack); } emit( eventName: K, payload?: T[K], ) { this.ee.emit(eventName, payload); } off( eventName: K, callBack: (payload: T[K]) => void, ) { this.ee.off(eventName, callBack); } } export default EventBus; ================================================ FILE: src/utils/fileUtils.ts ================================================ import pathConst from "@/constants/pathConst"; import FastImage from "react-native-fast-image"; import RNFS, { PicturesDirectoryPath, copyFile, downloadFile, exists, mkdir, readDir, unlink, writeFile, } from "react-native-fs"; import { errorLog } from "./log"; import path from "path-browserify"; import resolveAssetSource from "react-native/Libraries/Image/resolveAssetSource"; const galleryBasePath = `${PicturesDirectoryPath}/MusicFree/`; /** * 将图片保存到相册 * @param src 图片地址 * @returns 保存后的文件路径 */ export async function saveToGallery(src: string) { const fileName = `${galleryBasePath}${Date.now()}.png`; if (!(await exists(galleryBasePath))) { await mkdir(galleryBasePath); } if (await exists(src)) { try { await copyFile(src, fileName); } catch (e) { console.log("... ", e); } } if (src.startsWith("http")) { const { promise } = downloadFile({ fromUrl: src, toFile: fileName, background: true, }); await promise; } if (src.startsWith("data")) { await writeFile(fileName, src); } return fileName; } export function sizeFormatter(bytes: number | string) { if (typeof bytes === "string") { return bytes; } if (bytes === 0) { return "0B"; } let k = 1024, sizes = ["B", "KB", "MB", "GB"], i = Math.floor(Math.log(bytes) / Math.log(k)); return (bytes / Math.pow(k, i)).toFixed(1) + sizes[i]; } export async function checkAndCreateDir(dirPath: string) { const filePath = dirPath; try { if (!(await exists(filePath))) { await mkdir(filePath); } } catch (e) { errorLog("无法初始化目录", { path: dirPath, e }); } } async function getFolderSize(dirPath: string): Promise { let size = 0; try { const fns = await readDir(dirPath); for (let fn of fns) { if (fn.isFile()) { size += fn.size; } // todo: 可以改成并行 promise.all if (fn.isDirectory()) { size += await getFolderSize(fn.path); } } } catch {} return size; } export async function getCacheSize( type: "music" | "lyric" | "image", ): Promise { if (type === "music") { return getFolderSize(pathConst.musicCachePath); } else if (type === "lyric") { return getFolderSize(pathConst.lrcCachePath); } else if (type === "image") { return getFolderSize(pathConst.imageCachePath); } throw new Error(); } export async function clearCache(type: "music" | "lyric" | "image") { if (type === "music") { try { if (await exists(pathConst.musicCachePath)) { return unlink(pathConst.musicCachePath); } } catch {} } else if (type === "lyric") { try { const lrcs = readDir(pathConst.lrcCachePath); return Promise.all((await lrcs).map(_ => unlink(_.path))); } catch {} } else if (type === "image") { return FastImage.clearDiskCache(); } } export function addFileScheme(fileName: string) { if (fileName.startsWith("/")) { return `file://${fileName}`; } return fileName; } export function addRandomHash(url: string) { if (url.indexOf("#") === -1) { return `${url}#${Date.now()}`; } return url; } export function trimHash(url: string) { const index = url.lastIndexOf("#"); if (index === -1) { return url; } return url.substring(0, index); } export function escapeCharacter(str?: string) { return str !== undefined ? `${str}`.replace(/[/|\\?*"<>:]+/g, "_") : ""; } export function getDirectory(dirPath: string) { const lastSlash = dirPath.lastIndexOf("/"); if (lastSlash === -1) { return dirPath; } return dirPath.slice(0, lastSlash); } export function getFileName(filePath: string, withoutExt?: boolean) { const lastSlash = filePath.lastIndexOf("/"); if (lastSlash === -1) { return filePath; } let fileName = filePath.slice(lastSlash + 1); if (withoutExt) { const lastDot = fileName.lastIndexOf("."); fileName = lastDot === -1 ? fileName : fileName.slice(0, lastDot); } try { return decodeURIComponent(fileName); } catch { return fileName; } } export async function mkdirR(directory: string) { let folder = directory; const checkStack: string[] = []; while (folder.length > 15) { checkStack.push(folder); folder = path.dirname(folder); } let existPos = 0; for (let i = 0; i < checkStack.length; ++i) { const isExist = await exists(checkStack[i]); if (isExist) { existPos = i; break; } } for (let j = existPos - 1; j >= 0; --j) { try { await mkdir(checkStack[j]); } catch (e) { console.log("error", e); } } } export async function writeInChunks( filePath: string, data, chunkSize = 1024 * 1024 * 2, ) { let offset = 0; if (await exists(filePath)) { await unlink(filePath); } while (offset < data.length) { const chunk = data.slice(offset, offset + chunkSize); if (offset === 0) { await RNFS.writeFile(filePath, chunk, "utf8"); } else { await RNFS.appendFile(filePath, chunk, "utf8"); } offset += chunkSize; } } export function resolveImportedAssetOrPath(pathOrAsset: string | number | undefined) { return pathOrAsset === undefined ? undefined : typeof pathOrAsset === "string" ? pathOrAsset : resolveImportedAsset(pathOrAsset); } function resolveImportedAsset(id?: number) { return id ? (resolveAssetSource(id) as { uri: string } | null) ?? undefined : undefined; } ================================================ FILE: src/utils/getOrCreateMMKV.ts ================================================ import pathConst from "@/constants/pathConst"; import { MMKV } from "react-native-mmkv"; const _mmkvCache: Record = {}; // @ts-ignore; global.mmkv = _mmkvCache; // Internal Method const getOrCreateMMKV = (dbName: string, cachePath = false) => { if (_mmkvCache[dbName]) { return _mmkvCache[dbName]; } const newStore = new MMKV({ id: dbName, path: cachePath ? pathConst.mmkvCachePath : pathConst.mmkvPath, }); _mmkvCache[dbName] = newStore; return newStore; }; export default getOrCreateMMKV; ================================================ FILE: src/utils/getUrlExt.ts ================================================ import path from "path-browserify"; export default function getUrlExt(url?: string) { if (!url) { return; } const ext = path.extname(url); const extraTag = ext.indexOf("?"); if (ext) { if (extraTag !== -1) { return ext.slice(0, extraTag); } else { return ext; } } return url; } ================================================ FILE: src/utils/htmlUtil.ts ================================================ // HTML sanitizer function to prevent XSS attacks export function sanitizeHtml(html: string): string { // Remove script tags and their content html = html.replace(/)<[^<]*)*<\/script>/gi, ""); // Remove dangerous event handlers html = html.replace(/\s*on\w+\s*=\s*[^>]*/gi, ""); // Remove javascript: URLs html = html.replace(/javascript:/gi, ""); // Remove data: URLs (except safe image types) html = html.replace(/data:(?!image\/(png|jpg|jpeg|gif|svg|webp))[^"'\s>]*/gi, ""); // Remove iframe, object, embed tags html = html.replace(/<(iframe|object|embed|applet|link|meta)\b[^>]*>/gi, ""); html = html.replace(/<\/(iframe|object|embed|applet|link|meta)>/gi, ""); // Remove form tags html = html.replace(/<\/?form\b[^>]*>/gi, ""); // Remove input, button, textarea tags html = html.replace(/<(input|button|textarea)\b[^>]*>/gi, ""); // Sanitize href attributes to only allow safe protocols html = html.replace(/href\s*=\s*["']([^"']*)["']/gi, (match, url) => { const trimmedUrl = url.trim().toLowerCase(); if (trimmedUrl.startsWith("http://") || trimmedUrl.startsWith("https://") || trimmedUrl.startsWith("mailto:") || trimmedUrl.startsWith("#") || trimmedUrl.startsWith("/")) { return match; } return "href=\"#\""; }); // Sanitize src attributes for images html = html.replace(/src\s*=\s*["']([^"']*)["']/gi, (match, url) => { const trimmedUrl = url.trim().toLowerCase(); if ( trimmedUrl.startsWith("http://") || trimmedUrl.startsWith("https://") || trimmedUrl.startsWith("data:image/") || trimmedUrl.startsWith("/")) { return match; } return "src=\"\""; }); return html; } ================================================ FILE: src/utils/jsonUtil.ts ================================================ export function safeStringify(raw: any): string { try { return JSON.stringify(raw); } catch { return ""; } } export function safeParse(raw?: string) { try { if (!raw) { return null; } return JSON.parse(raw) as T; } catch { return null; } } ================================================ FILE: src/utils/log.ts ================================================ import { fileAsyncTransport, logger } from "react-native-logs"; import RNFS, { readDir, readFile } from "react-native-fs"; import pathConst from "@/constants/pathConst"; import Config from "../core/appConfig.ts"; import { addLog } from "@/lib/react-native-vdebug/src/log"; const config = { transport: fileAsyncTransport, transportOptions: { FS: RNFS, filePath: pathConst.logPath, fileName: "error-log-{date-today}.log", }, dateFormat: "local", }; const traceConfig = { transport: fileAsyncTransport, transportOptions: { FS: RNFS, filePath: pathConst.logPath, fileName: "trace-log.log", }, dateFormat: "local", }; const log = logger.createLogger(config); const traceLogger = logger.createLogger(traceConfig); export function trace( desc: string, message?: any, level: "info" | "error" = "info", ) { if (__DEV__) { console.log(desc, message); } // 特殊情况记录操作路径 if (Config.getConfig("debug.traceLog")) { traceLogger[level]({ desc, message, }); } } export async function clearLog() { const files = await RNFS.readDir(pathConst.logPath); await Promise.all( files.map(async file => { if (file.isFile()) { try { await RNFS.unlink(file.path); } catch {} } }), ); } export async function getErrorLogContent() { try { const files = await readDir(pathConst.logPath); console.log(files); const today = new Date(); // 两天的错误日志 const yesterday = new Date(); yesterday.setDate(today.getDate() - 1); const todayLog = files.find( _ => _.isFile() && _.path.endsWith( `error-log-${today.getDate()}-${ today.getMonth() + 1 }-${today.getFullYear()}.log`, ), ); const yesterdayLog = files.find( _ => _.isFile() && _.path.endsWith( `error-log-${yesterday.getDate()}-${ yesterday.getMonth() + 1 }-${yesterday.getFullYear()}.log`, ), ); let logContent = ""; if (todayLog) { logContent += await readFile(todayLog.path, "utf8"); } if (yesterdayLog) { logContent += await readFile(yesterdayLog.path, "utf8"); } return logContent; } catch { return ""; } } export function errorLog(desc: string, message: any) { if (Config.getConfig("debug.errorLog")) { log.error({ desc, message, }); trace(desc, message, "error"); } } export function devLog( method: "log" | "error" | "warn" | "info", ...args: any[] ) { if (Config.getConfig("debug.devLog")) { addLog(method, args); } } export { log }; ================================================ FILE: src/utils/lrcParser.ts ================================================ const timeReg = /\[[\d:.]+\]/g; const metaReg = /\[(.+):(.+)\]/g; type LyricMeta = Record; interface IOptions { musicItem?: IMusic.IMusicItem; lyricSource?: ILyric.ILyricSource; translation?: string; extra?: Record; } export interface IParsedLrcItem { /** 时间 s */ time: number; /** 歌词 */ lrc: string; /** 翻译 */ translation?: string; /** 位置 */ index: number; } export default class LyricParser { private _musicItem?: IMusic.IMusicItem; private meta: LyricMeta; private lrcItems: Array; private extra: Record; private lastSearchIndex = 0; public hasTranslation = false; public lyricSource?: ILyric.ILyricSource; get musicItem() { return this._musicItem; } constructor(raw: string, options?: IOptions) { // init this._musicItem = options?.musicItem; this.extra = options?.extra || {}; this.lyricSource = options?.lyricSource; let translation = options?.translation; if (!raw && translation) { raw = translation; translation = undefined; } const { lrcItems, meta } = this.parseLyricImpl(raw); if (this.extra.offset) { meta.offset = (meta.offset ?? 0) + this.extra.offset; } this.meta = meta; this.lrcItems = lrcItems; if (translation) { this.hasTranslation = true; const transLrcItems = this.parseLyricImpl(translation).lrcItems; // 2 pointer let p1 = 0; let p2 = 0; while (p1 < this.lrcItems.length) { const lrcItem = this.lrcItems[p1]; while ( transLrcItems[p2].time < lrcItem.time && p2 < transLrcItems.length - 1 ) { ++p2; } if (transLrcItems[p2].time === lrcItem.time) { lrcItem.translation = transLrcItems[p2].lrc; } else { lrcItem.translation = ""; } ++p1; } } } getPosition(position: number): IParsedLrcItem | null { position = position - (this.meta?.offset ?? 0); let index; /** 最前面 */ if (!this.lrcItems[0] || position < this.lrcItems[0].time) { this.lastSearchIndex = 0; return null; } for ( index = this.lastSearchIndex; index < this.lrcItems.length - 1; ++index ) { if ( position >= this.lrcItems[index].time && position < this.lrcItems[index + 1].time ) { this.lastSearchIndex = index; return this.lrcItems[index]; } } for (index = 0; index < this.lastSearchIndex; ++index) { if ( position >= this.lrcItems[index].time && position < this.lrcItems[index + 1].time ) { this.lastSearchIndex = index; return this.lrcItems[index]; } } index = this.lrcItems.length - 1; this.lastSearchIndex = index; return this.lrcItems[index]; } getLyricItems() { return this.lrcItems; } getMeta() { return this.meta; } toString(options?: { withTimestamp?: boolean; type?: "raw" | "translation"; }) { const { type = "raw", withTimestamp = true } = options || {}; if (withTimestamp) { return this.lrcItems .map( item => `${this.timeToLrctime(item.time)} ${ type === "raw" ? item.lrc : item.translation }`, ) .join("\r\n"); } else { return this.lrcItems .map(item => (type === "raw" ? item.lrc : item.translation)) .join("\r\n"); } } /** [xx:xx.xx] => x s */ private parseTime(timeStr: string): number { let result = 0; const nums = timeStr.slice(1, timeStr.length - 1).split(":"); for (let i = 0; i < nums.length; ++i) { result = result * 60 + +nums[i]; } return result; } /** x s => [xx:xx.xx] */ private timeToLrctime(sec: number) { const min = Math.floor(sec / 60); sec = sec - min * 60; const secInt = Math.floor(sec); const secFloat = sec - secInt; return `[${min.toFixed(0).padStart(2, "0")}:${secInt .toString() .padStart(2, "0")}.${secFloat.toFixed(2).slice(2)}]`; } private parseMetaImpl(metaStr: string) { if (metaStr === "") { return {}; } const metaArr = metaStr.match(metaReg) ?? []; const meta: any = {}; let k, v; for (const m of metaArr) { k = m.substring(1, m.indexOf(":")); v = m.substring(k.length + 2, m.length - 1); if (k === "offset") { meta[k] = +v / 1000; } else { meta[k] = v; } } return meta; } private parseLyricImpl(raw: string) { raw = raw.trim(); const rawLrcItems: Array = []; const rawLrcs = raw.split(timeReg) ?? []; const rawTimes = raw.match(timeReg) ?? []; const len = rawTimes.length; const meta = this.parseMetaImpl(rawLrcs[0].trim()); rawLrcs.shift(); let counter = 0; let j, lrc; for (let i = 0; i < len; ++i) { counter = 0; while (rawLrcs[0] === "") { ++counter; rawLrcs.shift(); } lrc = rawLrcs[0]?.trim?.() ?? ""; for (j = i; j < i + counter; ++j) { rawLrcItems.push({ time: this.parseTime(rawTimes[j]), lrc, index: j, }); } i += counter; if (i < len) { rawLrcItems.push({ time: this.parseTime(rawTimes[i]), lrc, index: j, }); } rawLrcs.shift(); } let lrcItems = rawLrcItems.sort((a, b) => a.time - b.time); lrcItems.forEach((item, index) => { item.index = index; }); if (lrcItems.length === 0 && raw.length) { lrcItems = raw.split("\n").map((_, index) => ({ time: 0, lrc: _, index, })); } return { lrcItems, meta, }; } } ================================================ FILE: src/utils/mediaExtra.ts ================================================ /** * 媒体资源的附加属性 */ import getOrCreateMMKV from "@/utils/getOrCreateMMKV"; import { getMediaUniqueKey } from "@/utils/mediaUtils"; import { useEffect, useState } from "react"; import { safeParse } from "./jsonUtil"; // Internal Method const getPluginStore = (pluginName: string) => { return getOrCreateMMKV(`MediaExtra.${pluginName}`); }; /** 音乐的附加属性 */ interface IMediaExtraProperties { /** 是否已下载 */ downloaded?: boolean; /** 本地路径 */ localPath?: string; /** 歌词偏移 */ lyricOffset?: number; /** 关联歌词 */ associatedLrc?: ICommon.IMediaBase } const observerCallbacks = new Map void>>(); /** * 获取媒体资源的全部附加属性 * @param mediaItem 媒体资源 * @returns */ function getMediaExtra(mediaItem: ICommon.IMediaBase | null): IMediaExtraProperties | null { if (!mediaItem?.platform || !mediaItem.id) { return null; } const meta = getPluginStore(mediaItem.platform).getString( `${mediaItem.id}`, ); if (!meta) { return null; } const parsedMeta = safeParse(meta); return parsedMeta; } /** * 获取媒体资源的附加属性值 * @param mediaItem * @param key * @returns */ function getMediaExtraProperty(mediaItem: ICommon.IMediaBase | null, key: K): IMediaExtraProperties[K] | null { const meta = getMediaExtra(mediaItem); return meta ? meta[key] : null; } /** * 更新媒体资源的附加属性 * @param mediaItem 媒体资源 * @param extra 附加属性 * @returns */ function patchMediaExtra(mediaItem: ICommon.IMediaBase, extra: Partial) { if (!mediaItem.platform || !mediaItem.id) { return null; } const originalMeta = getMediaExtra(mediaItem); const store = getPluginStore(mediaItem.platform); const newMeta = { ...originalMeta, ...extra, }; store.set(`${mediaItem.id}`, JSON.stringify(newMeta)); // 发送事件更新 const callbacks = observerCallbacks.get(getMediaUniqueKey(mediaItem)); if (callbacks && callbacks.size > 0) { for (const callback of callbacks) { callback(newMeta); } } return newMeta; } /** * 直接替换媒体资源的附加属性 * @param mediaItem 媒体资源 * @param extra 附加属性 * @returns */ function setMediaExtra(mediaItem: ICommon.IMediaBase, extra: IMediaExtraProperties) { if (!mediaItem.platform || !mediaItem.id) { return null; } const store = getPluginStore(mediaItem.platform); store.set(`${mediaItem.id}`, JSON.stringify(extra)); // 发送事件更新 const callbacks = observerCallbacks.get(getMediaUniqueKey(mediaItem)); if (callbacks && callbacks.size > 0) { for (const callback of callbacks) { callback(extra); } } return extra; } /** * 删除媒体资源的附加属性 * @param mediaItem 媒体资源 * @returns */ function removeMediaExtra(mediaItem: ICommon.IMediaBase) { if (!mediaItem.platform || !mediaItem.id) { return false; } const store = getPluginStore(mediaItem.platform); store.delete(`${mediaItem.id}`); // 发送事件更新 const callbacks = observerCallbacks.get(getMediaUniqueKey(mediaItem)); if (callbacks && callbacks.size > 0) { for (const callback of callbacks) { callback(null); } } return true; } /** * 删除所有媒体资源的附加属性 * @param pluginName 插件名称 */ function removeAllMediaExtra(pluginName: string) { const store = getPluginStore(pluginName); store.clearAll(); // 寻找所有pluginName开头的key const keys = observerCallbacks.keys(); for (const key of keys) { if (key.startsWith(pluginName + "@")) { const callbacks = observerCallbacks.get(key); if (callbacks && callbacks.size > 0) { for (const callback of callbacks) { callback(null); } } } } } function useMediaExtra(mediaItem: ICommon.IMediaBase) { const [mediaExtraState, setMediaExtraState] = useState(getMediaExtra(mediaItem)); useEffect(() => { const callback = (mediaExtra: IMediaExtraProperties | null) => { setMediaExtraState(mediaExtra); }; if (!mediaItem) { setMediaExtraState(null); } else { setMediaExtraState(getMediaExtra(mediaItem)); const mediaKey = getMediaUniqueKey(mediaItem); if (!observerCallbacks.has(mediaKey)) { observerCallbacks.set(mediaKey, new Set()); } const callbacks = observerCallbacks.get(mediaKey); if (callbacks) { callbacks.add(callback); } } return () => { const mediaKey = getMediaUniqueKey(mediaItem); if (observerCallbacks.has(mediaKey)) { const callbacks = observerCallbacks.get(mediaKey); if (callbacks) { callbacks.delete(callback); if (callbacks.size === 0) { observerCallbacks.delete(mediaKey); } } } }; }, [mediaItem]); return mediaExtraState; } function useMediaExtraProperty(mediaItem: ICommon.IMediaBase, key: K) { const [mediaExtraPropertyState, setMediaExtraPropertyState] = useState(getMediaExtraProperty(mediaItem, key)); useEffect(() => { const callback = (mediaExtra: IMediaExtraProperties | null) => { setMediaExtraPropertyState(mediaExtra ? mediaExtra[key] : null); }; if (!mediaItem) { setMediaExtraPropertyState(null); } else { setMediaExtraPropertyState(getMediaExtraProperty(mediaItem, key)); const mediaKey = getMediaUniqueKey(mediaItem); if (!observerCallbacks.has(mediaKey)) { observerCallbacks.set(mediaKey, new Set()); } const callbacks = observerCallbacks.get(mediaKey); if (callbacks) { callbacks.add(callback); } } return () => { const mediaKey = getMediaUniqueKey(mediaItem); if (observerCallbacks.has(mediaKey)) { const callbacks = observerCallbacks.get(mediaKey); if (callbacks) { callbacks.delete(callback); if (callbacks.size === 0) { observerCallbacks.delete(mediaKey); } } } }; }, [mediaItem]); return mediaExtraPropertyState; } export { getMediaExtra, getMediaExtraProperty, patchMediaExtra, setMediaExtra, removeMediaExtra, removeAllMediaExtra, useMediaExtra, useMediaExtraProperty, }; ================================================ FILE: src/utils/mediaIndexMap.ts ================================================ export interface IIndexMap { getIndexMap: () => Record>; getIndex: (mediaItem: ICommon.IMediaBase) => number; has: (mediaItem: ICommon.IMediaBase) => boolean; } export function createMediaIndexMap( mediaItems: ICommon.IMediaBase[], ): IIndexMap { const indexMap: Record> = {}; mediaItems.forEach((item, index) => { // 映射中不存在 if (!indexMap[item.platform]) { indexMap[item.platform] = { [item.id]: index, }; } else { // 修改映射 indexMap[item.platform][item.id] = index; } }); function getIndexMap() { return indexMap; } function getIndex(mediaItem: ICommon.IMediaBase) { if (!mediaItem) { return -1; } return indexMap[mediaItem.platform]?.[mediaItem.id] ?? -1; } function has(mediaItem: ICommon.IMediaBase) { if (!mediaItem) { return false; } return indexMap[mediaItem.platform]?.[mediaItem.id] > -1; } return { getIndexMap, getIndex, has, }; } ================================================ FILE: src/utils/mediaUtils.ts ================================================ import { internalSerializeKey, localPluginPlatform, } from "@/constants/commonConst"; import { getMediaExtraProperty } from "./mediaExtra"; /** * 获取媒体资源的唯一key * @param mediaItem * @returns */ export function getMediaUniqueKey(mediaItem: ICommon.IMediaBase) { return `${mediaItem.platform}@${mediaItem.id}`; } /** * 解析媒体资源的唯一key * @param key * @returns */ export function parseMediaUniqueKey(key: string): ICommon.IMediaBase { try { const str = JSON.parse(key.trim()); let platform, id; if (typeof str === "string") { [platform, id] = str.split("@"); } else { platform = str?.platform; id = str?.id; } if (!platform || !id) { throw new Error("mediakey不完整"); } return { platform, id, }; } catch (e: any) { throw e; } } /** * 比较两个媒体资源是否相同 * @param a * @param b * @returns */ export function isSameMediaItem( a: ICommon.IMediaBase | null | undefined, b: ICommon.IMediaBase | null | undefined, ) { // eslint-disable-next-line eqeqeq return !!(a && b && a.id == b.id && a.platform === b.platform); } /** 获取复位的mediaItem */ export function resetMediaItem( mediaItem: T, platform?: string, newObj?: boolean, ): T { // 本地音乐不做处理 if ( mediaItem.platform === localPluginPlatform || platform === localPluginPlatform ) { return newObj ? { ...mediaItem } : mediaItem; } if (!newObj) { mediaItem.platform = platform ?? mediaItem.platform; mediaItem[internalSerializeKey] = undefined; return mediaItem; } else { return { ...mediaItem, platform: platform ?? mediaItem.platform, [internalSerializeKey]: undefined, }; } } /** * 获取媒体资源的本地路径,如果本地路径不存在,则返回null * @param mediaItem * @returns */ export function getLocalPath(mediaItem: ICommon.IMediaBase) { if (!mediaItem) { return null; } // 如果本身就是一个内部音乐 if (mediaItem.url && (mediaItem.url.startsWith("file://") || mediaItem.url.startsWith("content://"))) { return mediaItem.url; } // 尝试从内部数据中获取 -- legacy logic const legacyLocalPath = mediaItem?.[internalSerializeKey]?.localPath; if (legacyLocalPath && typeof legacyLocalPath === "string") { return legacyLocalPath; } // 从附加信息中获取 const localPathInMediaExtra = getMediaExtraProperty(mediaItem, "localPath"); return localPathInMediaExtra ?? null; } ================================================ FILE: src/utils/minDistance.ts ================================================ function makeMatrix(row: number, col: number) { return Array(row) .fill(0) .map(_ => Array(col).fill(Infinity)); } export default function minDistance(word1?: string, word2?: string): number { if (!word1 || !word2) { return word1?.length || word2?.length || 0; } const dp = makeMatrix(word1.length + 1, word2.length + 1); for (let i = 0; i <= word1.length; ++i) { for (let j = 0; j <= word2.length; ++j) { if (i === 0 || j === 0) { dp[i][j] = i || j; continue; } const currentStr1 = word1[i - 1]; const currentStr2 = word2[j - 1]; if (currentStr1 === currentStr2) { dp[i][j] = Math.min( dp[i - 1][j - 1], dp[i - 1][j] + 1, dp[i][j - 1] + 1, ); } else { dp[i][j] = Math.min( dp[i - 1][j - 1] + 1, dp[i - 1][j] + 1, dp[i][j - 1] + 1, ); } } } return dp[word1.length][word2.length]; } ================================================ FILE: src/utils/network.ts ================================================ import { emptyFunction } from "@/constants/commonConst"; import NetInfo from "@react-native-community/netinfo"; enum NetworkState { Offline = "Offline", Wifi = "Wifi", Cellular = "Cellular", } class Network { private _state: NetworkState = NetworkState.Wifi; /** 获取网络状态 */ get state() { return this._state; } /** 是否离线 */ get isOffline() { return this._state === NetworkState.Offline; } /** 是否处于wifi环境 */ get isWifi() { return this._state === NetworkState.Wifi; } /** 是否处于移动网络环境 */ get isCellular() { return this._state === NetworkState.Cellular; } /** 是否链接网络 */ get isConnected() { return this._state !== NetworkState.Offline; } constructor() { NetInfo.fetch().then(state => { this.mapState(state); }).catch(emptyFunction); NetInfo.addEventListener(state => { this.mapState(state); }); } private mapState(state: any) { if (state.type === "none") { this._state = NetworkState.Offline; } else if (state.type === "wifi") { this._state = NetworkState.Wifi; } else { this._state = NetworkState.Cellular; } } } const network = new Network(); export default network; ================================================ FILE: src/utils/notImplementedFunction.ts ================================================ export default function notImplementedFunction() { // Not implemented } ================================================ FILE: src/utils/openUrl.ts ================================================ import { Linking } from "react-native"; import Toast from "./toast"; export default async function (url: string) { try { await Linking.canOpenURL(url); return Linking.openURL(url); } catch { Toast.warn("无法打开链接"); } } ================================================ FILE: src/utils/perfLogger.ts ================================================ export interface IPerfLogger { mark: (label?: string) => void; } export function perfLogger(): IPerfLogger { const s = Date.now(); return { mark(label?: string) { console.log(`[${label || "log"}] ${Date.now() - s}ms`); }, }; } ================================================ FILE: src/utils/persistStatus.ts ================================================ /** * 全局持久化的状态 */ import getOrCreateMMKV from "@/utils/getOrCreateMMKV"; import { useEffect, useState } from "react"; import { safeParse } from "./jsonUtil"; // Internal Method const getStore = () => { return getOrCreateMMKV("App.PersistStatus"); }; interface IPersistStatus { /** 当前的音乐 */ "music.musicItem": IMusic.IMusicItem; /** 进度 */ "music.progress": number; /** 模式 */ "music.repeatMode": string; /** 列表 */ "music.playList": IMusic.IMusicItem[]; /** 速度 */ "music.rate": number; /** 音质 */ "music.quality": IMusic.IQualityKey; /** app */ "app.skipVersion": string; /** 开屏弹窗 */ "app.skipBootstrapStorageDialog": boolean; /** 语言设置 */ "app.language": string; /** 上次更新插件的时间 */ "app.pluginUpdateTime": number; /** 缓存的定时关闭自定义时间(分钟) */ "app.scheduleCloseTime": number; /** 歌词-是否启用翻译 */ "lyric.showTranslation": boolean; /** 歌词-详情页字体大小 */ "lyric.detailFontSize": number; } function set( key: K, value: IPersistStatus[K] | undefined, ) { const store = getStore(); if (value === undefined) { store.delete(key); } else { store.set(key, JSON.stringify(value)); } } function get(key: K): IPersistStatus[K] | null { const store = getStore(); const raw = store.getString(key); if (raw) { return safeParse(raw) as IPersistStatus[K]; } return null; } function useValue( key: K, defaultValue?: IPersistStatus[K], ): IPersistStatus[K] | null { const [state, setState] = useState( get(key) ?? defaultValue ?? null, ); useEffect(() => { const store = getStore(); const sub = store.addOnValueChangedListener(changedKey => { if (key === changedKey) { setState(get(key)); } }); return () => { sub.remove(); }; }, []); return state; } const PersistStatus = { get, set, useValue, }; export default PersistStatus; ================================================ FILE: src/utils/qualities.ts ================================================ /** * 音质相关的所有工具代码 */ export const qualityKeys: IMusic.IQualityKey[] = [ "low", "standard", "high", "super", ]; export const qualityText = { low: "低音质", standard: "标准音质", high: "高音质", super: "超高音质", }; /** 获取音质顺序 */ export function getQualityOrder( qualityKey: IMusic.IQualityKey, sort: "asc" | "desc", ) { const idx = qualityKeys.indexOf(qualityKey); const left = qualityKeys.slice(0, idx); const right = qualityKeys.slice(idx + 1); if (sort === "asc") { /** 优先高音质 */ return [qualityKey, ...right, ...left.reverse()]; } else { /** 优先低音质 */ return [qualityKey, ...left.reverse(), ...right]; } } ================================================ FILE: src/utils/rpx.ts ================================================ import { Dimensions } from "react-native"; const windowWidth = Dimensions.get("window").width; const windowHeight = Dimensions.get("window").height; const minWindowEdge = Math.min(windowHeight, windowWidth); const maxWindowEdge = Math.max(windowHeight, windowWidth); export default function (rpx: number) { return (rpx / 750) * minWindowEdge; } export function vh(pct: number) { return (pct / 100) * Dimensions.get("window").height; } export function vw(pct: number) { return (pct / 100) * Dimensions.get("window").width; } export function vmin(pct: number) { return (pct / 100) * minWindowEdge; } export function vmax(pct: number) { return (pct / 100) * maxWindowEdge; } export function sh(pct: number) { return (pct / 100) * Dimensions.get("screen").height; } export function sw(pct: number) { return (pct / 100) * Dimensions.get("screen").width; } ================================================ FILE: src/utils/scheduleClose.ts ================================================ import { TrackPlayerEvents } from "@/core.defination/trackPlayer"; import TrackPlayer from "@/core/trackPlayer"; import NativeUtils from "@/native/utils"; import { atom, getDefaultStore, useAtomValue } from "jotai"; import { useEffect, useRef, useState } from "react"; import BackgroundTimer from "react-native-background-timer"; const deadlineAtom = atom(null); const closeAfterPlayEndAtom = atom(false); let timerId: any; async function exitApp() { await TrackPlayer.reset(); NativeUtils.exitApp(); } function setScheduleClose(deadline: number | null) { getDefaultStore().set(deadlineAtom, deadline); timerId && BackgroundTimer.clearTimeout(timerId); if (deadline && deadline > Date.now()) { timerId = BackgroundTimer.setTimeout(async () => { const playAfterEnd = getDefaultStore().get(closeAfterPlayEndAtom); if (playAfterEnd) { TrackPlayer.on(TrackPlayerEvents.PlayEnd, exitApp); } else { exitApp(); } }, deadline - Date.now()); } else { if (timerId) { BackgroundTimer.clearTimeout(timerId); } timerId = null; } } function setCloseAfterPlayEnd(closeAfterPlayEnd: boolean) { if (!closeAfterPlayEnd) { // 边界条件:如果倒计时结束后,Trackplayer停止播放前,取消了修改 TrackPlayer.off(TrackPlayerEvents.PlayEnd, exitApp); } getDefaultStore().set(closeAfterPlayEndAtom, closeAfterPlayEnd); } function useScheduleCloseCountDown() { const deadline = useAtomValue(deadlineAtom); const [countDown, setCountDown] = useState( deadline ? deadline - Date.now() : null); const intervalRef = useRef(); useEffect(() => { // deadline改变时,更新定时器 // 清除原有的定时器 intervalRef.current && clearInterval(intervalRef.current); intervalRef.current = null; // 清空定时 if (!deadline || deadline <= Date.now()) { setCountDown(null); return; } else { // 更新倒计时 setCountDown(Math.max(deadline - Date.now(), 0) / 1000); intervalRef.current = setInterval(() => { setCountDown(Math.max(deadline - Date.now(), 0) / 1000); }, 1000); } return () => { // 清除定时器 intervalRef.current && clearInterval(intervalRef.current); intervalRef.current = null; }; }, [deadline]); return countDown; } const useCloseAfterPlayEnd = () => useAtomValue(closeAfterPlayEndAtom); export { setScheduleClose, useScheduleCloseCountDown, setCloseAfterPlayEnd, useCloseAfterPlayEnd }; ================================================ FILE: src/utils/stateMapper.ts ================================================ import { useEffect, useState } from "react"; export default class StateMapper { private getFun: () => T; private cbs: Set = new Set([]); constructor(getFun: () => T) { this.getFun = getFun; } notify = () => { this.cbs.forEach(_ => _?.()); }; useMappedState = () => { const [_state, _setState] = useState(this.getFun); const updateState = () => { _setState(this.getFun()); }; useEffect(() => { this.cbs.add(updateState); return () => { this.cbs.delete(updateState); }; }, []); return _state; }; } type UpdateFunc = (prev: T) => T; export class GlobalState { private value: T; private stateMapper: StateMapper; constructor(initValue: T) { this.value = initValue; this.stateMapper = new StateMapper(this.getValue); } public getValue = () => { return this.value; }; public useValue = () => { return this.stateMapper.useMappedState(); }; public setValue = (value: T | UpdateFunc) => { let newValue: T; if (typeof value === "function") { newValue = (value as UpdateFunc)(this.value); } else { newValue = value; } this.value = newValue; this.stateMapper.notify(); }; } ================================================ FILE: src/utils/storage.ts ================================================ import { errorLog } from "@/utils/log"; import AsyncStorage from "@react-native-async-storage/async-storage"; export async function setStorage(key: string, value: any) { try { await AsyncStorage.setItem(key, JSON.stringify(value, null, "")); } catch (e: any) { errorLog(`存储失败${key}`, e?.message); } } export async function getStorage(key: string) { try { const result = await AsyncStorage.getItem(key); if (result) { return JSON.parse(result); } } catch {} return null; } export async function getMultiStorage(keys: string[]) { if (keys.length === 0) { return []; } const result = await AsyncStorage.multiGet(keys); return result.map(_ => { try { if (_[1]) { return JSON.parse(_[1]); } return null; } catch { return null; } }); } export async function removeStorage(key: string) { return AsyncStorage.removeItem(key); } ================================================ FILE: src/utils/timeformat.ts ================================================ export default function (time: number) { time = Math.round(time); if (time < 60) { return `00:${time.toFixed(0).padStart(2, "0")}`; } const sec = Math.floor(time % 60); time = Math.floor(time / 60); const min = time % 60; time = Math.floor(time / 60); const formatted = `${min.toString().padStart(2, "0")}:${sec .toFixed(0) .padStart(2, "0")}`; if (time === 0) { return formatted; } return `${time}:${formatted}`; } ================================================ FILE: src/utils/toast.ts ================================================ import { IToastConfig, showToast } from "@/components/base/toast"; function success(message: string, config?: IToastConfig) { showToast({ message, ...config, type: "success", }); } function warn(message: string, config?: IToastConfig) { showToast({ message, ...config, type: "warn", }); } const Toast = { success, warn, }; export default Toast; ================================================ FILE: src/utils/trackUtils.ts ================================================ import { State } from "react-native-track-player"; /** * 音乐是否处于停止状态 * @param state * @returns */ export const musicIsPaused = (state: State | undefined) => state !== State.Playing; /** * 音乐是否处于缓冲中状态 * @param state * @returns */ export const musicIsBuffering = (state: State | undefined) => state === State.Loading || state === State.Buffering; ================================================ FILE: tsconfig.json ================================================ { "extends": "@react-native/typescript-config/tsconfig.json", "compilerOptions": { /* Visit https://aka.ms/tsconfig.json to read more about this file */ /* Completeness */ "noImplicitAny": false, "skipLibCheck": true, /* Skip type checking all .d.ts files. */ "baseUrl": ".", "paths": { "@/*": ["./src/*"] }, "types": ["node"] } }