Repository: nini22P/omp Branch: main Commit: 18af251187ec Files: 114 Total size: 341.5 KB Directory structure: gitextract_y64r62ev/ ├── .github/ │ └── workflows/ │ └── ci.yml ├── .gitignore ├── .swcrc ├── CHANGELOG.md ├── LICENSE ├── PRIVACY.md ├── PRIVACY_CN.md ├── README.md ├── README_CN.md ├── android/ │ ├── .gitignore │ ├── app/ │ │ ├── build.gradle │ │ └── src/ │ │ └── main/ │ │ ├── AndroidManifest.xml │ │ ├── java/ │ │ │ └── nini22p/ │ │ │ └── omp/ │ │ │ ├── Application.java │ │ │ ├── DelegationService.java │ │ │ └── LauncherActivity.java │ │ └── res/ │ │ ├── drawable-anydpi/ │ │ │ └── shortcut_legacy_background.xml │ │ ├── mipmap-anydpi-v26/ │ │ │ └── ic_launcher.xml │ │ ├── raw/ │ │ │ └── web_app_manifest.json │ │ ├── values/ │ │ │ ├── colors.xml │ │ │ └── strings.xml │ │ └── xml/ │ │ ├── filepaths.xml │ │ └── shortcuts.xml │ ├── build.gradle │ ├── gradle/ │ │ └── wrapper/ │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties │ ├── gradle.properties │ ├── gradlew │ ├── gradlew.bat │ └── settings.gradle ├── eslint.config.mjs ├── extract_log.py ├── generate-version-info.mjs ├── lingui.config.js ├── package.json ├── postcss.config.js ├── public/ │ └── manifest.json ├── src/ │ ├── App.tsx │ ├── components/ │ │ ├── CommonList/ │ │ │ ├── CommonList.tsx │ │ │ ├── CommonListItem.tsx │ │ │ ├── CommonListItemCard.tsx │ │ │ ├── CommonMenu.tsx │ │ │ └── ShuffleAll.tsx │ │ └── Lyrics/ │ │ └── Lyrics.tsx │ ├── data/ │ │ └── licenses.ts │ ├── graph/ │ │ ├── authConfig.ts │ │ └── graph.ts │ ├── hooks/ │ │ ├── graph/ │ │ │ ├── useFilesData.ts │ │ │ ├── useSync.ts │ │ │ └── useUser.ts │ │ ├── player/ │ │ │ ├── useMediaSession.ts │ │ │ ├── usePlayerControl.ts │ │ │ └── usePlayerCore.ts │ │ ├── ui/ │ │ │ ├── useControlHide.ts │ │ │ ├── useCustomTheme.ts │ │ │ ├── useFullscreen.ts │ │ │ ├── useStyles.ts │ │ │ └── useThemeColor.ts │ │ ├── useDebounce.ts │ │ └── useUtils.ts │ ├── index.css │ ├── index.html │ ├── locales/ │ │ ├── en/ │ │ │ └── messages.po │ │ └── zh-CN/ │ │ └── messages.po │ ├── main.tsx │ ├── pages/ │ │ ├── Files/ │ │ │ ├── BreadcrumbNav.tsx │ │ │ ├── Files.tsx │ │ │ └── FilterMenu.tsx │ │ ├── History.tsx │ │ ├── Loading.tsx │ │ ├── LogIn.tsx │ │ ├── NavBar.tsx │ │ ├── NotFound.tsx │ │ ├── PictureView/ │ │ │ ├── PictureList.tsx │ │ │ ├── PictureListItem.tsx │ │ │ └── PictureView.tsx │ │ ├── Player/ │ │ │ ├── Audio/ │ │ │ │ ├── Audio.tsx │ │ │ │ ├── Classic.tsx │ │ │ │ └── Modern.tsx │ │ │ ├── PlayQueue.tsx │ │ │ ├── Player.tsx │ │ │ ├── PlayerControl.tsx │ │ │ ├── PlayerMenu.tsx │ │ │ ├── VideoPlayer.tsx │ │ │ ├── VideoPlayerTopbar.tsx │ │ │ └── VolumeControl.tsx │ │ ├── Playlist/ │ │ │ └── Playlist.tsx │ │ ├── Refresh.tsx │ │ ├── Search.tsx │ │ ├── Setting.tsx │ │ └── SideBar/ │ │ ├── MobileSideBar.tsx │ │ ├── Playlists.tsx │ │ └── SideBar.tsx │ ├── router.tsx │ ├── store/ │ │ ├── createSelectors.ts │ │ ├── storage.ts │ │ ├── useHistoryStore.ts │ │ ├── useLocalMetaDataStore.ts │ │ ├── usePictureStore.ts │ │ ├── usePlayQueueStore.ts │ │ ├── usePlayerStore.ts │ │ ├── usePlaylistsStore.ts │ │ └── useUiStore.ts │ ├── types/ │ │ ├── MetaData.ts │ │ ├── commonMenu.ts │ │ ├── file.ts │ │ ├── history.ts │ │ ├── picture.ts │ │ ├── playQueue.ts │ │ ├── player.ts │ │ ├── playlist.ts │ │ └── ui.ts │ └── utils.ts ├── tsconfig.json └── webpack.config.cjs ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/ci.yml ================================================ name: ci on: push: branches: - main paths-ignore: - README.md - README_CN.md pull_request: paths-ignore: - README.md - README_CN.md jobs: build-web: runs-on: windows-latest steps: - name: Checkout uses: actions/checkout@v4 - name: Set up Node uses: actions/setup-node@v4 with: node-version: 22 cache: 'npm' - name: Install dependencies run: npm install - name: Build env: ONEDRIVE_AUTH: ${{ secrets.ONEDRIVE_AUTH }} ONEDRIVE_GME: ${{ secrets.ONEDRIVE_GME }} CLIENT_ID: ${{ secrets.CLIENT_ID }} REDIRECT_URI: ${{ secrets.REDIRECT_URI }} run: npm run build - name: Upload artifact id: deployment uses: actions/upload-pages-artifact@v3 with: path: './dist' deploy: if: github.event_name == 'push' && github.ref == 'refs/heads/main' runs-on: ubuntu-latest needs: - build-web permissions: pages: write id-token: write environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} steps: - name: Setup Pages uses: actions/configure-pages@v3 - name: Deploy to GitHub Pages id: deployment uses: actions/deploy-pages@v4 build-android: runs-on: ubuntu-latest env: KEYSTORE: ${{ secrets.KEYSTORE }} steps: - name: Clone repository uses: actions/checkout@v4 - uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: '21' - name: Decode and save keystore if: env.KEYSTORE != '' run: | echo "${{ secrets.KEYSTORE }}" | base64 --decode > android/app/keystore.jks - name: Save key.properties if: env.KEYSTORE != '' run: | echo "storePassword=${{ secrets.STORE_PASSWORD }}" >> android/key.properties echo "keyPassword=${{ secrets.KEY_PASSWORD }}" >> android/key.properties echo "keyAlias=${{ secrets.KEY_ALIAS }}" >> android/key.properties echo "storeFile=keystore.jks" >> android/key.properties - name: Grant execute permission for gradlew run: chmod +x android/gradlew - name: Build release apk if: env.KEYSTORE != '' run: cd android && ./gradlew assembleRelease - name: Rename release apk if: env.KEYSTORE != '' run: mv android/app/build/outputs/apk/release/app-release.apk OMP-android.apk - name: Upload android artifact if: env.KEYSTORE != '' uses: actions/upload-artifact@v4 with: name: OMP-android path: OMP-android.apk - name: Build debug apk if: env.KEYSTORE == '' run: cd android && ./gradlew assembleDebug - name: Rename debug apk if: env.KEYSTORE == '' run: mv android/app/build/outputs/apk/debug/app-debug.apk OMP-android-debug.apk - name: Upload android debug artifact if: env.KEYSTORE == '' uses: actions/upload-artifact@v4 with: name: OMP-android-debug path: OMP-android-debug.apk release: if: github.event_name == 'push' && github.ref == 'refs/heads/main' runs-on: ubuntu-latest needs: - build-web - build-android - deploy env: KEYSTORE: ${{ secrets.KEYSTORE }} steps: - name: Checkout uses: actions/checkout@v4 - name: Get version id: yq uses: mikefarah/yq@master with: cmd: yq -r '.version' package.json - name: Print version run: echo ${{ steps.yq.outputs.result }} - name: Prepare tag name id: tag_name run: | VERSION="${{ steps.yq.outputs.result }}" TAG_NAME="v${VERSION}" echo "TAG_NAME=$TAG_NAME" >> "$GITHUB_OUTPUT" - name: Check tag uses: mukunku/tag-exists-action@v1.6.0 id: check-tag with: tag: ${{ steps.tag_name.outputs.TAG_NAME }} - name: Eextract log if: steps.check-tag.outputs.exists == 'false' run: python extract_log.py ${{ steps.tag_name.outputs.TAG_NAME }} - name: Download android artifact if: steps.check-tag.outputs.exists == 'false' && env.KEYSTORE != '' uses: actions/download-artifact@v4 with: name: OMP-android path: artifacts - name: Release if: steps.check-tag.outputs.exists == 'false' && env.KEYSTORE != '' uses: softprops/action-gh-release@v2 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: tag_name: ${{ steps.tag_name.outputs.TAG_NAME }} body_path: CHANGELOG_${{ steps.tag_name.outputs.TAG_NAME }}.md draft: false prerelease: false files: | artifacts/OMP-android.apk ================================================ FILE: .gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? # env .env .env.development .env.production # auto generated src/data/info.ts src/locales/en/messages.ts src/locales/zh-CN/messages.ts ================================================ FILE: .swcrc ================================================ { "$schema": "https://json.schemastore.org/swcrc", "jsc": { "experimental": { "plugins": [ ["@lingui/swc-plugin",{}] ] }, "parser": { "syntax": "typescript" }, "baseUrl": "./", "paths": { "@/*": [ "src/*" ] } }, "minify": false } ================================================ FILE: CHANGELOG.md ================================================ ## v1.9.4 ### Changelog * Release android PWA apk ### 更新日志 * 发布 android PWA apk ## v1.9.3 ### ⚠ Warning For self-deployed instances, please check [readme.md](https://github.com/nini22P/omp/blob/main/readme.md#running-and-build) before upgrading to add any missing environment variables: `ONEDRIVE_AUTH`, `ONEDRIVE_GME` ### ⚠ 警告 自行部署的在升级前请查看 [readme_cn.md](https://github.com/nini22P/omp/blob/main/readme_cn.md#运行和编译) 添加缺失的环境变量: `ONEDRIVE_AUTH`, `ONEDRIVE_GME` ### Changelog * Support for VNET (self-deployment required, please refer to [readme.md](https://github.com/nini22P/omp/blob/main/readme.md#running-and-build)) @xiaoman1221 * Change title on playback * Hide the option to refetch media metadata in the menu when playing a video ### 更新日志 * 支持世纪互联(需自行部署,具体请查看 [readme_cn.md](https://github.com/nini22P/omp/blob/main/readme_cn.md#运行和编译))@xiaoman1221 * 播放时更改标题 * 播放视频时隐藏菜单中重新获取媒体元数据的选项 ## v1.9.2 ### Changelog * Fixed playback control * Improved album cover color extraction ### 更新日志 * 修复播放控制 * 改进专辑封面颜色提取 ## v1.9.1 ### Changelog * Same time lyrics highlighting to support translated text * Fixed the volume slider triggering swipe gestures ### 更新日志 * 相同时间的歌词高亮显示,以支持翻译文本 * 修复音量滑条触发滑动手势的问题 ## v1.9.0 ### Changelog * Support for embedded lyrics in audio files * Added button tooltips * Added version display ### 更新日志 * 支持音频文件内嵌歌词 * 添加按钮提示 * 添加版本显示 ## v1.8.1 ### Changelog * Added the ability to play multiple discs using the play all button ``` - Folder examples, starting with disc and disk, case insensitive - Disc1 - Disc 2 - Disk3 - Disk 4 ``` * Improved theme color extraction * Improved video player style * Fixed some files not displaying ### 更新日志 * 可使用全部播放按钮多碟播放 ``` - 文件夹样例,disc 和 disk 开头,不区分大小写 - Disc1 - Disc 2 - Disk3 - Disk 4 ``` * 改进主题颜色提取 * 改进视频播放器样式 * 修复部分文件未显示 ## v1.8.0 ### Changelog * Multi-select list support * Improve the file search ### 更新日志 * 列表支持多选操作 * 改进文件搜索 ## v1.7.4 ### Changelog * fix clear play queue on change current account * fix language display issue ### 更新日志 * 修复选择当前账户时清空播放队列的问题 * 修复语言显示的问题 ## v1.7.3 ### Changelog * Supports multiple accounts ### 更新日志 * 支持多账户 ## v1.7.2 ### Changelog * Add more menu options ### 更新日志 * 添加更多菜单选项 ## v1.7.0 ### Changelog * add playback rate menu * i18n migration to lingui ### 更新日志 * 添加播放速度菜单 * i18n 迁移到 lingui ## v1.6.4 ### Changelog * add volume control ### 更新日志 * 添加音量控制 ## v1.6.2 ### Changelog - Fix playlist display bug ### 更新日志 - 修复播放列表显示问题 ## v1.6.1 ### Changelog - Fix float action button display bug ### 更新日志 - 修复浮动按钮显示问题 ## v1.6.0 ### Changelog - Ability to search in the current file list - Improved storage size of the local metadata cache (recommend clearing the local metadata cache once) ### 更新日志 - 能够在当前文件列表搜索 - 优化本地元数据缓存的存储占用(建议清除一次本地元数据缓存) ## v1.5.4 ### Changelog - Improvement of audio playback interface opening animation ### 更新日志 - 改进音频播放界面打开时的动画 ## v1.5.2 ### Changelog - Improved user experience - Fix known bugs ### 更新日志 - 改进用户体验 - 修复已知 bug ## v1.5.1 ### Changelog - Now you don't need to log in to get to the main screen - Improved theme color extraction ### 更新日志 - 现在无需登录即可进入主界面 - 改进主题色提取 ## v1.5.0 ### Changelog - New UI interface - Possibility to generate theme colors using album cover - @MakinoharaShoko has provided a new icon ### 更新日志 - 新的 UI 界面 - 可以从专辑封面生成主题色 - @MakinoharaShoko 提供了新的图标 ## v1.4.2 ### Features - Add multi-column lists and grids to files - Add HD Thumbnails option - Image Viewer Improvements ### 特性 - 文件添加多列列表和网格 - 添加高清缩略图选项 - 改进图像查看器 ## v1.4.1 ### Improved - Improved list performance ### 改进 - 改进了列表的性能 ## v1.4.0 ### Features - Support for viewing images - Add thumbnails to file list - Add sorting to file list ### 特性 - 支持查看图片 - 文件列表添加缩略图 - 文件列表添加排序 ## v1.3.1 ### Fix - Accidental playback after clicking on another file while paused --- ### 修复 - 暂停时点击其他文件后意外播放 ## v1.3.0 ### Features - Ability to hide the title bar on the desktop - Add local metadata cache - Improved display of audio playback interface, playlists and play queues --- ### 特性 - 桌面端可隐藏标题栏 - 添加本地元数据缓存 - 改进音频播放界面、播放列表和播放队列的显示 ## v1.2.0 ### ⚠ Change - Migration to webpack - Changed client ID #### How to retrieve previous data This update has changed the client ID, you need to re-authorize, if you are a user of the old version, it will create new data in the new folder. First close OMP, then open ``Applications`` folder in OneDrive, find ``OMP 1`` folder, delete all files in it, then find ``OMP`` folder, move all files in it to ``OMP 1`` folder, delete ``OMP`` folder, and lastly rename ``OMP 1`` folder to ``OMP``. --- ### ⚠ 变更 - 迁移到 webpack - 更改了客户端 ID #### 如何找回之前的数据 本次更新更换了客户端 ID,需重新授权,如果是旧版本用户使用时会在新文件夹中创建新数据。 首先关闭 OMP,然后打开 OneDrive 中的 `应用` 文件夹,找到 `OMP 1` 文件夹,删除里面的全部文件,然后找到 `OMP` 文件夹,将里面的全部文件移动到 `OMP 1` 文件夹,删除 `OMP` 文件夹,最后将 `OMP 1` 文件夹重命名为 `OMP`。 ## v1.1.0 ### Change * Move account logout to settings page ### 变更 * 账户注销移动到设置页 ## v1.0.0 ### Features - OneDrive Files View - Music Playback - Music Metadata - Video Playback - Play Queue - Dark Mode - Media Session - PWA - History Sync - Playlists Sync --- ### 特性 - OneDrive 文件查看 - 音乐播放 - 音乐元数据 - 视频播放 - 播放队列 - 黑暗模式 - Media Session - PWA - 播放历史同步 - 播放列表同步 ================================================ 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: PRIVACY.md ================================================ # OMP Privacy Policy **Effective Date: [June 3, 2025]** Welcome to OMP (hereinafter referred to as "this Application" or "we")! This Application is a web application designed to help you manage and use media files in your OneDrive through official Microsoft APIs. We highly value your privacy. This Privacy Policy (hereinafter referred to as "this Policy") is intended to explain how we handle (or, more accurately, **do not handle**) your information when you use our services. Please read this Policy carefully to ensure you understand and agree to it before using our services. **1. We Do Not Collect Your Personal Information** We solemnly declare: OMP **will not collect, store, transmit, analyze, or sell any of your personally identifiable information or the content and metadata of your files in OneDrive on the developer's servers.** The design philosophy of this Application is to maximize user privacy protection: * **Client-Side Operation:** This Application primarily runs directly in your browser. * **Direct Interaction:** The Application interacts with your OneDrive account via official Microsoft APIs. All data requests and transmissions occur directly between your local device and your OneDrive, under your authorization. * **No Developer Access:** The developer and this Application's servers (if any, they are only used to host the static web files of the application itself and do not process user data) cannot access, view, or store your personal OneDrive data or any personally identifiable information. **2. Data Usage and Authorization** * **User Authorization:** For this Application to access and operate on files in your OneDrive (e.g., listing files, reading media files for playback), you need to explicitly authorize this Application to access relevant data in your OneDrive account through Microsoft's OAuth 2.0 authorization process. The permissions we request include `User.Read` (to read basic user profile information), `Files.Read` (to read user's OneDrive files), and `Files.ReadWrite.AppFolder` (to read and write data in the application's dedicated folder, used for synchronizing history and playlists). * **Scope of Permission:** This Application will only access your OneDrive data within the scope of your authorization and solely for implementing the core functionalities of the Application (such as Browse, managing, and playing your specified media files, synchronizing your playback history and playlists). We will not request permissions beyond what is necessary for the Application's functions. * **Credential Security:** Your OneDrive login credentials (username and password) are processed and verified directly by Microsoft's authentication services. This Application will not obtain, record, or store these credentials. The MSAL (Microsoft Authentication Library) handles authentication tokens on the client-side (your browser). **3. Data Storage** This Application itself **does not have independent servers to store any of your personal data or file content.** Data you generate or use through this Application is stored in the following locations: * **In Your OneDrive:** * According to the design of this Application, specific application-related data will be stored in the `Apps/OMP` folder in your personal OneDrive. * This data is under your control, and the developer cannot access it. * **In Your Browser's Local Storage:** * **localStorage:** * Used to cache MSAL's authentication state. * Used to store the Application's UI settings (e.g., theme, view preferences). * Used to store the current play queue status. * **IndexedDB:** * Used to cache media file metadata (such as song titles, artists, album cover information) to improve loading speed and reduce network requests. * The data stored locally in your browser is for your personal use only, to enhance application experience and performance, and will not be transmitted to the developer or our servers. **4. Microsoft OneDrive's Privacy Policy** Data you store in OneDrive and authorizations made through Microsoft's authentication services are subject to Microsoft Corporation's privacy policy. We strongly recommend that you review and understand Microsoft's official privacy statement to learn how they collect, use, and protect your data. You can visit [https://privacy.microsoft.com/](https://privacy.microsoft.com/) to view it (please note that this link may change; refer to Microsoft's official latest link). **5. Cookies and Browser Local Storage Technologies** * **Cookies:** This Application currently does not primarily set or rely on Cookies to track users or store permanent personal information directly. Microsoft's authentication services (MSAL) may use Cookies in their processes, which adhere to Microsoft's privacy practices. * **LocalStorage and IndexedDB:** As described in Section 3 "Data Storage," this Application uses browser LocalStorage and IndexedDB technologies to store authentication cache, UI preferences, play queue, and media metadata. * The information stored by these technologies is limited to data necessary for the application's operation and to enhance user experience, and it is retained only in your local browser and not sent to the developer. * You can clear Cookies, LocalStorage, and IndexedDB data at any time through your browser settings. However, please note that clearing this data may reset some application settings to default or require you to log in again. **6. Data Security** * We communicate securely with the Microsoft OneDrive API via the industry-standard OAuth 2.0 protocol to ensure the security of your authorization process and data transmission (between your device and OneDrive). * The security of your personal data also depends on your proper safeguarding of your Microsoft account credentials and the security mechanisms of the Microsoft OneDrive service itself. We recommend using a strong password and enabling two-factor authentication for your Microsoft account. **7. Third-Party Services** Other than the Microsoft OneDrive API and Microsoft authentication services, this Application does not rely on other third-party services that actively collect your personal information and transmit it back to the developer. This Application uses various open-source libraries to build its features (as shown in the `package.json` file), and these libraries follow their respective open-source licensing agreements. **8. Children's Privacy** This Application is not targeted at children under the age of 13 (or other applicable age as defined in your jurisdiction). We do not knowingly collect any personally identifiable information from children. **9. Changes to This Privacy Policy** We may update this Privacy Policy from time to time to reflect changes in our practices or legal requirements. If we make any material changes, we will notify you by posting the updated Privacy Policy on our Application's website and indicating the "Effective Date" at the top of the policy. We encourage you to review this Privacy Policy periodically for any updates. Your continued use of this Application after the changes take effect signifies your acceptance of the revised Privacy Policy. **10. Contact Us** If you have any questions, comments, or suggestions about this Privacy Policy or our handling of your information, please contact us through the following means: * **GitHub:** [https://github.com/nini22P/omp](https://github.com/nini22P/omp) Thank you for using OMP! ================================================ FILE: PRIVACY_CN.md ================================================ # OMP 隐私政策 **生效日期:[2025年6月3日]** 欢迎使用 OMP(以下简称“本应用”或“我们”)!本应用是一款网页应用,旨在通过微软官方 API 帮助您管理和使用您 OneDrive 中的媒体文件。 我们非常重视您的隐私。本隐私政策(以下简称“本政策”)旨在向您说明,当您使用我们的服务时,我们如何处理(或者更准确地说,**不处理**)您的信息。请仔细阅读本政策,确保您在充分理解并同意后使用我们的服务。 **1. 我们不收集您的个人信息** 我们郑重声明:OMP **不会在开发者服务器上收集、存储、传输、分析或出售任何您的个人身份信息或您 OneDrive 中的文件内容及元数据。** 本应用的设计理念是最大限度地保护用户隐私: * **客户端运行:** 本应用主要在您的浏览器中直接运行。 * **直接交互:** 应用通过微软官方 API 与您的 OneDrive 账户进行交互。所有数据请求和传输均在您授权的前提下,在您的本地设备和您的 OneDrive 之间直接进行。 * **开发者无权限:** 开发者及本应用的服务器(如有,也仅用于托管应用本身的静态网页文件,不处理用户数据)无法访问、查看或存储您的个人 OneDrive 数据或任何个人身份信息。 **2. 数据的使用与授权** * **用户授权:** 为了使本应用能够访问并操作您 OneDrive 中的文件(例如,列出文件、读取媒体文件以供播放),您需要通过微软的 OAuth 2.0 授权流程,明确授权本应用访问您 OneDrive 账户中的相关数据。我们请求的权限包括 `User.Read`(读取用户基本配置信息)、`Files.Read`(读取用户 OneDrive 文件)以及 `Files.ReadWrite.AppFolder`(在应用专属文件夹中读写数据,用于同步历史记录和播放列表)。 * **权限范围:** 本应用仅会在您授权的范围内访问您的 OneDrive 数据,并且仅用于实现应用的核心功能(如浏览、管理和播放您指定的媒体文件,同步您的播放历史和播放列表)。我们不会请求超出应用功能所必需的权限。 * **凭据安全:** 您的 OneDrive 登录凭据(用户名和密码)由微软的身份验证服务直接处理和验证,本应用不会获取、记录或存储您的这些凭据。MSAL 库(Microsoft Authentication Library)在客户端(您的浏览器)处理身份验证令牌。 **3. 数据的存储** 本应用本身**不设有独立的服务器来存储您的任何个人数据或文件内容。** 您通过本应用产生或使用的数据存储在以下位置: * **用户 OneDrive 中:** * 根据本应用的的设计,应用相关的特定数据,会存储在您个人 OneDrive 的 `Apps/OMP` 文件夹下。 * 这些数据由您自己掌控,开发者无法访问。 * **浏览器本地存储中:** * **localStorage:** * 用于缓存 MSAL 的身份验证状态。 * 用于存储应用的 UI 设置(例如主题、视图偏好等)。 * 用于存储当前的播放队列状态。 * **IndexedDB:** * 用于缓存媒体文件的元数据(如歌曲标题、艺术家、专辑封面信息等),以提高加载速度和减少网络请求。 * 以上这些存储在浏览器本地的数据仅供您个人在本地设备上使用,用于提升应用体验和性能,不会被传输给开发者或我们的服务器。 **4. 微软 OneDrive 的隐私政策** 您在 OneDrive 中存储的数据以及通过微软身份验证服务进行的授权,均受微软公司隐私政策的约束。我们强烈建议您查阅并理解微软的官方隐私声明,以了解微软如何收集、使用和保护您的数据。您可以访问 [https://privacy.microsoft.com/](https://privacy.microsoft.com/) 查看(请注意,此链接可能会变更,请以微软官方最新链接为准)。 **5. Cookies 和浏览器本地存储技术** * **Cookies:** 本应用目前主要不直接设置和依赖 Cookies 来追踪用户或存储永久性个人信息。微软身份验证服务(MSAL)可能会在其流程中使用 Cookies,这遵循微软的隐私实践。 * **LocalStorage 和 IndexedDB:** 如第3点“数据的存储”中所述,本应用使用浏览器的 LocalStorage 和 IndexedDB 技术来存储身份验证缓存、UI偏好、播放队列以及媒体元数据。 * 这些技术存储的信息仅限于应用运行和提升用户体验所必需的数据,并且仅保留在您的本地浏览器中,不会发送给开发者。 * 您可以随时通过浏览器设置清除 Cookies、LocalStorage 和 IndexedDB 数据。但请注意,清除这些数据可能会导致部分应用设置恢复默认或需要重新登录。 **6. 数据安全** * 我们通过行业标准的 OAuth 2.0 协议与微软 OneDrive API 进行安全通信,以确保您的授权过程和数据传输(在您的设备和 OneDrive 之间)的安全性。 * 您个人数据的安全也依赖于您妥善保管您的微软账户凭据以及微软 OneDrive 服务本身的安全机制。我们建议您使用强密码并为您的微软账户启用双因素认证。 **7. 第三方服务** 除微软 OneDrive API 和微软身份验证服务外,本应用不依赖其他会主动收集您个人信息的第三方服务并将数据回传给开发者。本应用使用了多种开源库来构建功能(如 `package.json` 文件所示),这些库遵循其各自的开源许可协议。 **8. 儿童隐私** 本应用不针对13岁以下的儿童(或您所在司法管辖区定义的其他适用年龄)。我们不会有意收集任何儿童的个人身份信息。 **9. 本隐私政策的变更** 我们可能会不时更新本隐私政策,以反映我们实践的变化或法律法规的要求。如果我们做出任何重大变更,我们将通过在本应用的网站上发布更新后的隐私政策来通知您,并在政策顶部注明“生效日期”。我们鼓励您定期查看本隐私政策以了解任何更新。您在变更生效后继续使用本应用即表示您接受修订后的隐私政策。 **10. 联系我们** 如果您对本隐私政策或我们对您信息的处理有任何疑问、意见或建议,请通过以下方式与我们联系: * **GitHub:** [https://github.com/nini22P/omp](https://github.com/nini22P/omp) 感谢您使用 OMP! ================================================ FILE: README.md ================================================ logo # OMP - OneDrive Media Player ![ci](https://github.com/nini22P/omp/actions/workflows/ci.yml/badge.svg) Afdaian [![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/nini22p) English | [中文](./README_CN.md) **Try OMP Now:** * **[Web Version](https://nini22p.github.io/omp/)** * **[Microsoft Store (PWA)](https://apps.microsoft.com/detail/9p6w6x16q7l9)** * **[Download Android APK (PWA)](https://github.com/nini22P/omp/releases/latest/download/OMP-android.apk)** ## Features - [x] OneDrive Files View - [x] Music Playback - [x] Music Lyrics - [x] Video Playback - [x] Play Queue - [x] Dark Mode - [x] Media Session - [x] PWA - [x] History Sync - [x] Playlists Sync - [x] Support VNET ## Screenshots ![Audio light](./public/screenshots/audio-light.webp) ![Audio dark](./public/screenshots/audio-dark.webp) ## FAQ ### Where is my data stored? All of OMP data is stored in the `Apps / OMP` folder in your OneDrive. Where `history.json` is the history and `playlists.json` is the playlists. If you have lost your data, you can restore an older version by visiting the OneDrive web version. ## Running and Build ### App registrations 1. Go to 2. Into `App registrations` register an application 3. `Supported account types` select the third item (`Accounts in any organizational directory and personal Microsoft accounts`) 4. `Redirect URI` select `SPA`, url enter or the domain of your deploy 5. `API Permissions` add `User.Read` `Files.Read` `Files.ReadWrite.AppFolder` ### Run dev server Add `.env.development` in project path ```env ONEDRIVE_AUTH=https://login.microsoftonline.com/common #VNET(https://login.partner.microsoftonline.cn/common) ONEDRIVE_GME=https://graph.microsoft.com #VNET(https://microsoftgraph.chinacloudapi.cn) CLIENT_ID= REDIRECT_URI=http://localhost:8760 ``` Run `npm i && npm run dev` ### Local build Add `.env` in project path ```env ONEDRIVE_AUTH=https://login.microsoftonline.com/common #VNET(https://login.partner.microsoftonline.cn/common) ONEDRIVE_GME=https://graph.microsoft.com #VNET(https://microsoftgraph.chinacloudapi.cn) CLIENT_ID= REDIRECT_URI= ``` Run `npm i && npm run build` ## Donations This project is free, if you think it works, feel free to donate to support it - [AFDIAN](https://afdian.com/a/nini22P) - [Ko-fi](https://ko-fi.com/nini22p) ## License [AGPL 3.0](https://github.com/nini22P/omp/blob/main/LICENSE) ## Privacy Policy [Privacy Policy](https://github.com/nini22P/omp/blob/main/PRIVACY.md) ## Star History [![Star History Chart](https://api.star-history.com/svg?repos=nini22P/omp&type=Date)](https://star-history.com/#nini22P/omp&Date) ================================================ FILE: README_CN.md ================================================ logo # OMP - OneDrive 媒体播放器 ![ci](https://github.com/nini22P/omp/actions/workflows/ci.yml/badge.svg) Afdaian [![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/nini22p) [English](./README.md) | 中文 **立即体验 OMP:** * **[网页版](https://nini22p.github.io/omp/)** * **[微软商店 (PWA)](https://apps.microsoft.com/detail/9p6w6x16q7l9)** * **[下载 Android APK (PWA)](https://github.com/nini22P/omp/releases/latest/download/OMP-android.apk)** ## 功能 - [x] OneDrive 文件查看 - [x] 音乐播放 - [x] 歌词显示 - [x] 视频播放 - [x] 播放队列 - [x] 黑暗模式 - [x] Media Session - [x] PWA - [x] 播放历史同步 - [x] 播放列表同步 - [x] 支持世纪互联版 ## 截图 ![音频 亮色模式](./public/screenshots/audio-light.webp) ![音频 暗色模式](./public/screenshots/audio-dark.webp) ## FAQ ### 我的数据保存在哪里? OMP 的数据全部保存在你的 OneDrive 中的 `应用 / OMP` 文件夹中。其中 `history.json` 为历史记录,`playlists.json` 为播放列表,如果有数据丢失可以访问 OneDrive 网页版恢复旧版本数据。 ## 运行和编译 ### 注册应用 1. 打开 2. 进入 `应用注册` 添加一个新应用 3. `支持账户类型` 选择第三项 (`任何组织目录中的帐户和个人 Microsoft 帐户`) 4. `重定向 URI` 选择 `SPA`, url 输入 或者你部署访问的域名 5. `API 权限` 添加 `User.Read` `Files.Read` `Files.ReadWrite.AppFolder` ### 运行开发服务器 在项目路径添加 `.env.development` ```env ONEDRIVE_AUTH=https://login.microsoftonline.com/common #世纪互联(https://login.partner.microsoftonline.cn/common) ONEDRIVE_GME=https://graph.microsoft.com #世纪互联(https://microsoftgraph.chinacloudapi.cn) CLIENT_ID= REDIRECT_URI=http://localhost:8760 ``` 运行 `npm i && npm run dev` ### 本地编译 在项目路径添加 `.env` ```env ONEDRIVE_AUTH=https://login.microsoftonline.com/common #世纪互联(https://login.partner.microsoftonline.cn/common) ONEDRIVE_GME=https://graph.microsoft.com #世纪互联(https://microsoftgraph.chinacloudapi.cn) CLIENT_ID= REDIRECT_URI= ``` 运行 `npm i && npm run build` ## 捐赠 这个项目完全免费,如果你觉得好用,欢迎捐赠支持 - [爱发电](https://afdian.com/a/nini22P) - [Ko-fi](https://ko-fi.com/nini22p) ## 许可 [AGPL 3.0](https://github.com/nini22P/omp/blob/main/LICENSE) ## 隐私政策 [隐私政策](https://github.com/nini22P/omp/blob/main/PRIVACY_CN.md) ## Star History [![Star History Chart](https://api.star-history.com/svg?repos=nini22P/omp&type=Date)](https://star-history.com/#nini22P/omp&Date) ================================================ FILE: android/.gitignore ================================================ # Gradle files .gradle/ build/ app/build/ app/release/ # Local configuration file (sdk path, etc) local.properties # Log/OS Files *.log # Android Studio generated files and folders captures/ .externalNativeBuild/ .cxx/ *.apk output.json # IntelliJ *.iml .idea/ misc.xml deploymentTargetDropDown.xml render.experimental.xml # Keystore files key.properties **/*.keystore **/*.jks # Google Services (e.g. APIs or Firebase) google-services.json # Android Profiling *.hprof ================================================ FILE: android/app/build.gradle ================================================ /* * Copyright 2019 Google Inc. * * 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 * * http://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. */ import groovy.xml.MarkupBuilder plugins { id 'com.android.application' } def twaManifest = [ applicationId: 'nini22p.omp', hostName: 'nini22p.github.io', // The domain being opened in the TWA. launchUrl: '/omp/', // The start path for the TWA. Must be relative to the domain. name: 'OMP', // The application name. launcherName: 'OMP', // The name shown on the Android Launcher. themeColor: '#f7f7f7', // The color used for the status bar. themeColorDark: '#3b3b3b', // The color used for the dark status bar. navigationColor: '#f7f7f7', // The color used for the navigation bar. navigationColorDark: '#3b3b3b', // The color used for the dark navbar. navigationDividerColor: '#f7f7f7', // The navbar divider color. navigationDividerColorDark: '#3b3b3b', // The dark navbar divider color. backgroundColor: '#FFFFFF', // The color used for the splash screen background. enableNotifications: false, // Set to true to enable notification delegation. // Every shortcut must include the following fields: // - name: String that will show up in the shortcut. // - short_name: Shorter string used if |name| is too long. // - url: Absolute path of the URL to launch the app with (e.g '/create'). // - icon: Name of the resource in the drawable folder to use as an icon. shortcuts: [], // The duration of fade out animation in milliseconds to be played when removing splash screen. splashScreenFadeOutDuration: 300, generatorApp: 'PWABuilder', // Application that generated the Android Project // The fallback strategy for when Trusted Web Activity is not available. Possible values are // 'customtabs' and 'webview'. fallbackType: 'customtabs', enableSiteSettingsShortcut: 'true', orientation: 'default', ] def keystorePropertiesFile = rootProject.file("key.properties") def keystoreProperties = new Properties() if ( keystorePropertiesFile.exists() ) keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) android { compileSdkVersion 35 namespace "nini22p.omp" defaultConfig { applicationId "nini22p.omp" minSdkVersion 23 targetSdkVersion 35 versionCode 1 versionName "1.0.0.0" // The name for the application resValue "string", "appName", twaManifest.name // The name for the application on the Android Launcher resValue "string", "launcherName", twaManifest.launcherName // The URL that will be used when launching the TWA from the Android Launcher def launchUrl = "https://" + twaManifest.hostName + twaManifest.launchUrl resValue "string", "launchUrl", launchUrl // The URL the Web Manifest for the Progressive Web App that the TWA points to. This // is used by Chrome OS and Meta Quest to open the Web version of the PWA instead of // the TWA, as it will probably give a better user experience for non-mobile devices. resValue "string", "webManifestUrl", 'https://nini22p.github.io/omp/manifest.json' // This is used by Meta Quest. resValue "string", "fullScopeUrl", 'https://nini22p.github.io/omp/' // The hostname is used when building the intent-filter, so the TWA is able to // handle Intents to open host url of the application. resValue "string", "hostName", twaManifest.hostName // This attribute sets the status bar color for the TWA. It can be either set here or in // `res/values/colors.xml`. Setting in both places is an error and the app will not // compile. If not set, the status bar color defaults to #FFFFFF - white. resValue "color", "colorPrimary", twaManifest.themeColor // This attribute sets the dark status bar color for the TWA. It can be either set here or in // `res/values/colors.xml`. Setting in both places is an error and the app will not // compile. If not set, the status bar color defaults to #000000 - white. resValue "color", "colorPrimaryDark", twaManifest.themeColorDark // This attribute sets the navigation bar color for the TWA. It can be either set here or // in `res/values/colors.xml`. Setting in both places is an error and the app will not // compile. If not set, the navigation bar color defaults to #FFFFFF - white. resValue "color", "navigationColor", twaManifest.navigationColor // This attribute sets the dark navigation bar color for the TWA. It can be either set here // or in `res/values/colors.xml`. Setting in both places is an error and the app will not // compile. If not set, the navigation bar color defaults to #000000 - black. resValue "color", "navigationColorDark", twaManifest.navigationColorDark // This attribute sets the navbar divider color for the TWA. It can be either // set here or in `res/values/colors.xml`. Setting in both places is an error and the app // will not compile. If not set, the divider color defaults to #00000000 - transparent. resValue "color", "navigationDividerColor", twaManifest.navigationDividerColor // This attribute sets the dark navbar divider color for the TWA. It can be either // set here or in `res/values/colors.xml`. Setting in both places is an error and the //app will not compile. If not set, the divider color defaults to #000000 - black. resValue "color", "navigationDividerColorDark", twaManifest.navigationDividerColorDark // Sets the color for the background used for the splash screen when launching the // Trusted Web Activity. resValue "color", "backgroundColor", twaManifest.backgroundColor // Defines a provider authority for the Splash Screen resValue "string", "providerAuthority", twaManifest.applicationId + '.fileprovider' // The enableNotification resource is used to enable or disable the // TrustedWebActivityService, by changing the android:enabled and android:exported // attributes resValue "bool", "enableNotification", twaManifest.enableNotifications.toString() twaManifest.shortcuts.eachWithIndex { shortcut, index -> resValue "string", "shortcut_name_$index", "$shortcut.name" resValue "string", "shortcut_short_name_$index", "$shortcut.short_name" } // The splashScreenFadeOutDuration resource is used to set the duration of fade out animation in milliseconds // to be played when removing splash screen. The default is 0 (no animation). resValue "integer", "splashScreenFadeOutDuration", twaManifest.splashScreenFadeOutDuration.toString() resValue "string", "generatorApp", twaManifest.generatorApp resValue "string", "fallbackType", twaManifest.fallbackType resValue "bool", "enableSiteSettingsShortcut", twaManifest.enableSiteSettingsShortcut resValue "string", "orientation", twaManifest.orientation } signingConfigs { if ( keystorePropertiesFile.exists() ) release { storeFile file(keystoreProperties['storeFile']) storePassword keystoreProperties['storePassword'] keyAlias keystoreProperties['keyAlias'] keyPassword keystoreProperties['keyPassword'] } } buildTypes { release { if ( keystorePropertiesFile.exists() ) signingConfig signingConfigs.release minifyEnabled true } } compileOptions { sourceCompatibility JavaVersion.VERSION_21 targetCompatibility JavaVersion.VERSION_21 } lintOptions { checkReleaseBuilds false } } task generateShorcutsFile { assert twaManifest.shortcuts.size() < 5, "You can have at most 4 shortcuts." twaManifest.shortcuts.eachWithIndex { s, i -> assert s.name != null, 'Missing `name` in shortcut #' + i assert s.short_name != null, 'Missing `short_name` in shortcut #' + i assert s.url != null, 'Missing `icon` in shortcut #' + i assert s.icon != null, 'Missing `url` in shortcut #' + i } def shortcutsFile = new File("$projectDir/src/main/res/xml", "shortcuts.xml") def xmlWriter = new StringWriter() def xmlMarkup = new MarkupBuilder(new IndentPrinter(xmlWriter, " ", true)) xmlMarkup .'shortcuts'('xmlns:android': 'http://schemas.android.com/apk/res/android') { twaManifest.shortcuts.eachWithIndex { s, i -> 'shortcut'( 'android:shortcutId': 'shortcut' + i, 'android:enabled': 'true', 'android:icon': '@drawable/' + s.icon, 'android:shortcutShortLabel': '@string/shortcut_short_name_' + i, 'android:shortcutLongLabel': '@string/shortcut_name_' + i) { 'intent'( 'android:action': 'android.intent.action.MAIN', 'android:targetPackage': twaManifest.applicationId, 'android:targetClass': twaManifest.applicationId + '.LauncherActivity', 'android:data': s.url) 'categories'('android:name': 'android.intent.category.LAUNCHER') } } } shortcutsFile.text = xmlWriter.toString() + '\n' } preBuild.dependsOn(generateShorcutsFile) repositories { } dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation 'com.google.androidbrowserhelper:androidbrowserhelper:2.5.0' } ================================================ FILE: android/app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: android/app/src/main/java/nini22p/omp/Application.java ================================================ /* * Copyright 2020 Google Inc. * * 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 * * http://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. */ package nini22p.omp; public class Application extends android.app.Application { @Override public void onCreate() { super.onCreate(); } } ================================================ FILE: android/app/src/main/java/nini22p/omp/DelegationService.java ================================================ package nini22p.omp; public class DelegationService extends com.google.androidbrowserhelper.trusted.DelegationService { @Override public void onCreate() { super.onCreate(); } } ================================================ FILE: android/app/src/main/java/nini22p/omp/LauncherActivity.java ================================================ /* * Copyright 2020 Google Inc. * * 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 * * http://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. */ package nini22p.omp; import android.content.pm.ActivityInfo; import android.net.Uri; import android.os.Build; import android.os.Bundle; public class LauncherActivity extends com.google.androidbrowserhelper.trusted.LauncherActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Setting an orientation crashes the app due to the transparent background on Android 8.0 // Oreo and below. We only set the orientation on Oreo and above. This only affects the // splash screen and Chrome will still respect the orientation. // See https://github.com/GoogleChromeLabs/bubblewrap/issues/496 for details. if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); } } @Override protected Uri getLaunchingUrl() { // Get the original launch Url. Uri uri = super.getLaunchingUrl(); return uri; } } ================================================ FILE: android/app/src/main/res/drawable-anydpi/shortcut_legacy_background.xml ================================================ ================================================ FILE: android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml ================================================ ================================================ FILE: android/app/src/main/res/raw/web_app_manifest.json ================================================ { "name": "OMP", "short_name": "OMP", "start_url": "/omp/", "display": "standalone", "display_override": [ "window-controls-overlay" ], "description": "OneDrive Media Player / OneDrive 媒体播放器", "dir": "auto", "icons": [ { "src": "./favicon.ico", "type": "image/x-icon", "sizes": "32x32" }, { "src": "./icon-192.png", "type": "image/png", "sizes": "192x192" }, { "src": "./icon-512.png", "type": "image/png", "sizes": "512x512" }, { "src": "./icon-192-maskable.png", "type": "image/png", "sizes": "192x192", "purpose": "maskable" }, { "src": "./icon-512-maskable.png", "type": "image/png", "sizes": "512x512", "purpose": "maskable" } ], "screenshots": [ { "src": "./screenshots/audio-light.webp", "sizes": "1317x904", "type": "image/webp", "form_factor": "wide", "description": "Audio Light" }, { "src": "./screenshots/audio-dark.webp", "sizes": "1317x904", "type": "image/webp", "form_factor": "wide", "description": "Audio Dark" }, { "src": "./screenshots/audio-light-narrow.webp", "sizes": "1082x2402", "type": "image/webp", "form_factor": "narrow", "description": "Audio Light" }, { "src": "./screenshots/audio-dark-narrow.webp", "sizes": "1082x2402", "type": "image/webp", "form_factor": "narrow", "description": "Audio Dark" } ], "edge_side_panel": {} } ================================================ FILE: android/app/src/main/res/values/colors.xml ================================================ #F5F5F5 ================================================ FILE: android/app/src/main/res/values/strings.xml ================================================ [{ \"relation\": [\"delegate_permission/common.handle_all_urls\"], \"target\": { \"namespace\": \"web\", \"site\": \"https://nini22p.github.io\" } }] ================================================ FILE: android/app/src/main/res/xml/filepaths.xml ================================================ ================================================ FILE: android/app/src/main/res/xml/shortcuts.xml ================================================ ================================================ FILE: android/build.gradle ================================================ /* * Copyright 2019 Google Inc. * * 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 * * http://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. */ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:8.7.2' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() mavenCentral() } } tasks.register('clean', Delete) { delete rootProject.buildDir } ================================================ FILE: android/gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip networkTimeout=10000 validateDistributionUrl=true ================================================ 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. org.gradle.jvmargs=-Xmx1536m # 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 android.useAndroidX=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. # ############################################################################## # # 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 "${APP_HOME:-./}" > /dev/null && pwd -P ) || 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 @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 ================================================ include ':app' ================================================ FILE: eslint.config.mjs ================================================ import { fixupConfigRules } from '@eslint/compat' import reactRefresh from 'eslint-plugin-react-refresh' import globals from 'globals' import tsParser from '@typescript-eslint/parser' import path from 'node:path' import { fileURLToPath } from 'node:url' import js from '@eslint/js' import { FlatCompat } from '@eslint/eslintrc' const __filename = fileURLToPath(import.meta.url) const __dirname = path.dirname(__filename) const compat = new FlatCompat({ baseDirectory: __dirname, recommendedConfig: js.configs.recommended, allConfig: js.configs.all }) export default [...fixupConfigRules(compat.extends( 'eslint:recommended', 'plugin:@typescript-eslint/recommended', 'plugin:react-hooks/recommended', )), { plugins: { 'react-refresh': reactRefresh, }, languageOptions: { globals: { ...globals.browser, ...globals.node, }, parser: tsParser, ecmaVersion: 'latest', sourceType: 'module', }, rules: { 'react-refresh/only-export-components': 'warn', quotes: ['warn', 'single'], semi: ['warn', 'never'], }, }] ================================================ FILE: extract_log.py ================================================ import sys def extract_log(version): try: with open("CHANGELOG.md", "r", encoding="utf-8") as file: lines = file.readlines() except FileNotFoundError: print("Error: not found CHANGELOG.md") return found = False changelog_lines = [] for line in lines: if line.startswith(f"## {version}"): found = True continue elif line.startswith("## ") and found: break if found: changelog_lines.append(line) while changelog_lines and not changelog_lines[-1].strip(): changelog_lines.pop() output = "".join(changelog_lines).strip() output_file = f"CHANGELOG_{version}.md" with open(output_file, "w", encoding="utf-8") as file: file.write(output) print(f"Changelog for {version} saved to {output_file}") if __name__ == "__main__": if len(sys.argv) != 2: print("Usage: python extract_log.py ") sys.exit(1) version = sys.argv[1] extract_log(version) ================================================ FILE: generate-version-info.mjs ================================================ import { readFile, writeFile } from 'node:fs/promises' const filePath = './src/data/info.ts' const run = async (isDev) => { const packageString = await readFile('./package.json', { encoding: 'utf-8' }) const version = JSON.parse(packageString).version const finalVersion = isDev ? `${version}-dev` : version const newInfo = `const INFO = { version: '${finalVersion}', dev: ${isDev}, buildTime: '${new Date().toISOString()}', } export default INFO` await writeFile(filePath, newInfo, { encoding: 'utf-8' }) console.log(`Generate version info to ${filePath}`) } const isDev = process.argv.includes('--dev') run(isDev).catch(err => { console.error('Error updating the file:', err) }) ================================================ FILE: lingui.config.js ================================================ /** @type {import('@lingui/conf').LinguiConfig} */ module.exports = { locales: ['en', 'zh-CN'], sourceLocale: 'en', catalogs: [ { path: '/src/locales/{locale}/messages', include: ['src'], }, ], format: 'po', } ================================================ FILE: package.json ================================================ { "name": "omp", "description": "OneDrive Media Player", "private": true, "version": "1.9.4", "scripts": { "build": "npm run generate && webpack --mode=production --node-env=production", "build:dev": "npm run generate:dev && webpack --mode=production --node-env=production", "build:android": "cd android && gradlew assembleRelease", "dev": "npm run generate:dev && webpack serve", "lint": "npm run generate && eslint src --report-unused-disable-directives --max-warnings 0", "lint:dev": "npm run generate:dev && eslint src --report-unused-disable-directives --max-warnings 0", "lingui": "lingui extract && lingui compile --typescript", "generate": "node generate-version-info.mjs && npm run lingui", "generate:dev": "node generate-version-info.mjs --dev && npm run lingui" }, "dependencies": { "@azure/msal-browser": "3.28.1", "@azure/msal-react": "2.2.0", "@emotion/react": "11.14.0", "@emotion/styled": "11.14.0", "@fontsource/roboto": "5.2.5", "@lingui/macro": "5.3.2", "@lingui/react": "5.3.2", "@mui/icons-material": "7.1.1", "@mui/material": "7.1.1", "@react-spring/web": "10.0.1", "@use-gesture/react": "^10.3.1", "buffer": "^6.0.3", "color": "5.0.0", "extract-colors": "4.2.0", "idb-keyval": "^6.2.1", "music-metadata-browser": "^2.5.11", "process": "^0.11.10", "react": "^18.3.1", "react-dom": "^18.3.1", "react-router-dom": "7.6.1", "react-virtualized": "9.22.6", "short-uuid": "^5.2.0", "swr": "2.3.3", "zustand": "5.0.5" }, "devDependencies": { "@eslint/compat": "1.2.9", "@eslint/eslintrc": "3.3.1", "@eslint/js": "9.28.0", "@lingui/cli": "5.3.2", "@lingui/swc-plugin": "5.5.2", "@pmmmwh/react-refresh-webpack-plugin": "0.6.0", "@swc/core": "^1.11.29", "@types/color": "4.2.0", "@types/extract-colors": "^1.1.4", "@types/node": "22.15.29", "@types/react": "18.3.12", "@types/react-dom": "18.3.1", "@types/react-virtualized": "9.22.2", "@typescript-eslint/eslint-plugin": "8.33.1", "@typescript-eslint/parser": "8.33.1", "autoprefixer": "10.4.21", "compression-webpack-plugin": "^11.1.0", "copy-webpack-plugin": "13.0.0", "css-loader": "^7.1.2", "dotenv-webpack": "^8.1.0", "eslint": "9.28.0", "eslint-define-config": "^2.1.0", "eslint-plugin-react-hooks": "5.2.0", "eslint-plugin-react-refresh": "0.4.20", "globals": "16.2.0", "html-webpack-plugin": "5.6.3", "postcss": "8.5.4", "postcss-loader": "^8.1.1", "react-refresh": "0.17.0", "style-loader": "^4.0.0", "swc-loader": "^0.2.6", "typescript": "5.8.3", "webpack": "5.99.9", "webpack-cli": "6.0.1", "webpack-dev-server": "5.2.1", "webpack-merge": "6.0.1", "workbox-webpack-plugin": "7.3.0" } } ================================================ FILE: postcss.config.js ================================================ module.exports = { // Add you postcss configuration here // Learn more about it at https://github.com/webpack-contrib/postcss-loader#config-files plugins: [['autoprefixer']], } ================================================ FILE: public/manifest.json ================================================ { "name": "OMP", "short_name": "OMP", "start_url": ".", "display": "standalone", "display_override": [ "window-controls-overlay" ], "description": "OneDrive Media Player / OneDrive 媒体播放器", "dir": "auto", "icons": [ { "src": "./favicon.ico", "type": "image/x-icon", "sizes": "32x32" }, { "src": "./icon-192.png", "type": "image/png", "sizes": "192x192" }, { "src": "./icon-512.png", "type": "image/png", "sizes": "512x512" }, { "src": "./icon-192-maskable.png", "type": "image/png", "sizes": "192x192", "purpose": "maskable" }, { "src": "./icon-512-maskable.png", "type": "image/png", "sizes": "512x512", "purpose": "maskable" } ], "screenshots": [ { "src": "./screenshots/audio-light.webp", "sizes": "1317x904", "type": "image/webp", "form_factor": "wide", "description": "Audio Light" }, { "src": "./screenshots/audio-dark.webp", "sizes": "1317x904", "type": "image/webp", "form_factor": "wide", "description": "Audio Dark" }, { "src": "./screenshots/audio-light-narrow.webp", "sizes": "1082x2402", "type": "image/webp", "form_factor": "narrow", "description": "Audio Light" }, { "src": "./screenshots/audio-dark-narrow.webp", "sizes": "1082x2402", "type": "image/webp", "form_factor": "narrow", "description": "Audio Dark" } ], "edge_side_panel": {} } ================================================ FILE: src/App.tsx ================================================ import { Outlet, useLocation } from 'react-router-dom' import { Container, ThemeProvider, Paper, Box, useMediaQuery } from '@mui/material' import Grid from '@mui/material/Grid' import NavBar from './pages/NavBar' import Player from './pages/Player/Player' import SideBar from './pages/SideBar/SideBar' import MobileSideBar from './pages/SideBar/MobileSideBar' import useUser from './hooks/graph/useUser' import useSync from './hooks/graph/useSync' import useThemeColor from './hooks/ui/useThemeColor' import LogIn from './pages/LogIn' import useUiStore from './store/useUiStore' import { useSpring, animated } from '@react-spring/web' import { useMemo } from 'react' import useCustomTheme from './hooks/ui/useCustomTheme' import Search from './pages/Search' import useStyles from './hooks/ui/useStyles' const App = () => { const customTheme = useCustomTheme() const styles = useStyles(customTheme) useThemeColor(customTheme) const windowControlsOverlayOpen = useMediaQuery('(display-mode: window-controls-overlay)') const { account } = useUser() useSync() const coverColor = useUiStore((state) => state.coverColor) const [{ background }, api] = useSpring( () => ({ background: `linear-gradient(45deg, ${coverColor}33, ${coverColor}15, ${coverColor}05, ${customTheme.palette.background.default})`, }) ) useMemo( () => api.start({ background: `linear-gradient(45deg, ${coverColor}33, ${coverColor}15, ${coverColor}05, ${customTheme.palette.background.default})` }), // eslint-disable-next-line react-hooks/exhaustive-deps [coverColor, customTheme.palette.background.default] ) const location = useLocation() const needLogin = useMemo( () => (['/', '/history'].includes(location.pathname)) && !account, [location, account] ) return ( {/* 侧栏 */} { } {/* 主体内容 */} {needLogin ? : } ) } export default App ================================================ FILE: src/components/CommonList/CommonList.tsx ================================================ import { useState, useEffect, Key, CSSProperties, useRef } from 'react' import Grid from '@mui/material/Grid' import usePlayQueueStore from '../../store/usePlayQueueStore' import usePlayerStore from '../../store/usePlayerStore' import useUiStore from '../../store/useUiStore' import { shufflePlayQueue } from '../../utils' import CommonMenu from './CommonMenu' import { FileItem } from '../../types/file' import CommonListItem from './CommonListItem' import { Box, Fab, List, useMediaQuery, useTheme } from '@mui/material' import { AutoSizer, List as VirtualList } from 'react-virtualized' import CommonListItemCard from './CommonListItemCard' import ShuffleRoundedIcon from '@mui/icons-material/ShuffleRounded' import PlayArrowRoundedIcon from '@mui/icons-material/PlayArrowRounded' import MoreVertRoundedIcon from '@mui/icons-material/MoreVertRounded' import { t } from '@lingui/macro' import { useShallow } from 'zustand/shallow' const CommonList = ( { listData, listType, display = 'list', scrollIndex, activeIndex, disableFAB, func, }: { listData: FileItem[], listType: 'files' | 'playlist' | 'playQueue', display?: 'list' | 'multicolumnList' | 'grid', scrollIndex?: number, activeIndex?: number, disableFAB?: boolean, func?: { open?: (index: number) => void, remove?: (indexArray: number[]) => void, }, }) => { const [shuffle, updateShuffle] = useUiStore(useShallow((state) => [state.shuffle, state.updateShuffle])) const updatePlayQueue = usePlayQueueStore.use.updatePlayQueue() const updateCurrentIndex = usePlayQueueStore.use.updateCurrentIndex() const updateAutoPlay = usePlayerStore((state) => state.updateAutoPlay) const [anchorEl, setAnchorEl] = useState(null) const [menuOpen, setMenuOpen] = useState(false) const [dialogOpen, setDialogOpen] = useState(false) const [selectIndex, setSelectIndex] = useState(null) const [selectIndexArray, setSelectIndexArray] = useState([]) const isSelectMode = selectIndexArray.length > 0 const shuffleDisplay = listData.filter(item => item.fileType === 'audio' || item.fileType === 'video').length > 0 const playAllDisplay = shuffleDisplay || listData.filter(item => item.fileType === 'folder' && /^(disc|disk)\s*\d+$/.test(item.fileName.toLocaleLowerCase())).length > 0 const addSelectIndex = (index: number) => { setSelectIndexArray([...selectIndexArray, index].sort()) } const removeSelectIndex = (index: number) => setSelectIndexArray(selectIndexArray.filter((_index) => index !== _index).sort()) const isSelected = (index: number) => selectIndexArray.includes(index) useEffect(() => setSelectIndexArray([]), [listData]) //列表数据变化时退出选择模式 const switchSelect = (index: number) => isSelected(index) ? removeSelectIndex(index) : addSelectIndex(index) const handleClickItem = (index: number) => { if (func?.open) func.open(index) } const handleClickPlayAll = () => { handleClickItem(listData.findIndex(item => item.fileType === 'audio' || item.fileType === 'video')) } // 点击随机播放全部 const handleClickShuffleAll = () => { if (listData) { const list = listData .filter((item) => item.fileType === 'audio' || item.fileType === 'video') .map((item, index) => { return { index, ...item } }) if (!shuffle) updateShuffle(true) const shuffleList = shufflePlayQueue(list) || [] updatePlayQueue(shuffleList) updateCurrentIndex(shuffleList[0].index) updateAutoPlay(true) } } const openMenu = (event: React.MouseEvent) => { setMenuOpen(true) setAnchorEl(event.currentTarget) } const handleClickMenu = (event: React.MouseEvent, selectIndex: number) => { setSelectIndex(selectIndex) openMenu(event) } const handleClickFABMenu = (event: React.MouseEvent) => { openMenu(event) } const theme = useTheme() const xs = useMediaQuery(theme.breakpoints.up('xs')) const sm = useMediaQuery(theme.breakpoints.up('sm')) const md = useMediaQuery(theme.breakpoints.up('md')) const lg = useMediaQuery(theme.breakpoints.up('lg')) const xl = useMediaQuery(theme.breakpoints.up('xl')) const getGridCols = (): number => { if (xl) return 6 if (lg) return 5 if (md) return 4 if (sm) return 3 if (xs) return 2 return 2 } const getListCols = (): number => { if (xl) return 3 if (lg) return 3 if (md) return 2 if (sm) return 1 if (xs) return 1 return 1 } const gridCols = getGridCols() const listCols = (display === 'multicolumnList') ? getListCols() : 1 const gridRenderer = ({ key, index, style }: { key: Key, index: number, style: CSSProperties }) => { return ( listData && { [...Array(gridCols)].map((_, i) => { const itemIndex = index * gridCols + i const item = listData[itemIndex] return ( item && switchSelect(itemIndex) : handleClickItem} handleClickMenu={handleClickMenu} /> ) }) } ) } const rowRenderer = ({ key, index, style }: { key: Key, index: number, style: CSSProperties }) => { return ( listData && { [...Array(listCols)].map((_, i) => { const itemIndex = index * listCols + i const item = listData[itemIndex] return ( item && switchSelect(itemIndex) : handleClickItem} handleClickMenu={handleClickMenu} /> ) }) } ) } const listRef = useRef(null) const updateListRowHeight = () => listRef.current && listRef.current.recomputeRowHeights() // 打开播放队列时滚动到当前播放文件 useEffect( () => { if (listType === 'playQueue' && listRef.current && typeof scrollIndex === 'number') { setTimeout(() => listRef.current?.scrollToRow(scrollIndex), 100) } }, // eslint-disable-next-line react-hooks/exhaustive-deps [] ) // 滚动到之前点击过的文件夹 useEffect( () => { if (listType === 'files' && listRef.current && typeof scrollIndex === 'number') { let index = scrollIndex if (display === 'grid') index = Math.ceil(scrollIndex / gridCols) - 1 if ((display === 'list' || display === 'multicolumnList')) index = Math.ceil(scrollIndex / listCols) - 1 if (index && index >= 0) { listRef.current?.scrollToRow(index) } } }, // eslint-disable-next-line react-hooks/exhaustive-deps [scrollIndex, gridCols, listCols] ) const scrollRef = useRef(null) const fabRef = useRef(null) const touchStartYRef = useRef(0) useEffect(() => { const scroll = scrollRef.current const fab = fabRef.current if (fab && isSelectMode) { fab.style.transform = 'translateY(0)' } else if (scroll && fab && !isSelectMode) { const onWheel = (e: WheelEvent) => { if (e.deltaY > 0) fab.style.transform = 'translateY(200%)' else fab.style.transform = 'translateY(0)' } const onTouchStart = (e: TouchEvent) => { touchStartYRef.current = (e.touches[0].clientY) } const onTouchMove = (e: TouchEvent) => { if (e.touches[0].clientY > touchStartYRef.current) { fab.style.transform = 'translateY(0)' touchStartYRef.current = (e.touches[0].clientY) } else { fab.style.transform = 'translateY(200%)' touchStartYRef.current = (e.touches[0].clientY) } } scroll.addEventListener('wheel', onWheel) scroll.addEventListener('touchstart', onTouchStart) scroll.addEventListener('touchmove', onTouchMove) return () => { scroll.removeEventListener('wheel', onWheel) scroll.removeEventListener('touchstart', onTouchStart) scroll.removeEventListener('touchmove', onTouchMove) } } }, [isSelectMode]) return ( {/* 文件列表 */} { display === 'grid' && updateListRowHeight()}> { ({ height, width }) => (listRef.current = ref))} height={height - 8} width={width - 8} rowCount={Math.ceil(listData.length / gridCols)} rowHeight={width / gridCols / 4 * 5} rowRenderer={gridRenderer} scrollToAlignment={'center'} style={{ paddingBottom: isSelectMode ? '6rem' : '0rem' }} /> } } { (display === 'list' || display === 'multicolumnList') && updateListRowHeight()}> { ({ height, width }) => (listRef.current = ref))} height={height - 8} width={width - 8} rowCount={Math.ceil(listData.length / listCols)} rowHeight={72} rowRenderer={rowRenderer} scrollToAlignment={'center'} style={{ paddingBottom: isSelectMode ? '6rem' : '0rem' }} /> } } {/* 菜单 */} {/* FAB */} { isSelectMode && } { (listType !== 'playQueue') && !isSelectMode && !disableFAB && <> { shuffleDisplay && } { playAllDisplay && {t`Play all`} } } ) } export default CommonList ================================================ FILE: src/components/CommonList/CommonListItem.tsx ================================================ import { FileItem } from '@/types/file' import { sizeConvert } from '@/utils' import InsertDriveFileRoundedIcon from '@mui/icons-material/InsertDriveFileRounded' import InsertPhotoRoundedIcon from '@mui/icons-material/InsertPhotoRounded' import FolderOpenRoundedIcon from '@mui/icons-material/FolderOpenRounded' import MusicNoteRoundedIcon from '@mui/icons-material/MusicNoteRounded' import MovieRoundedIcon from '@mui/icons-material/MovieRounded' import MoreVertRoundedIcon from '@mui/icons-material/MoreVertRounded' import { ListItem, IconButton, ListItemButton, ListItemAvatar, Avatar, ListItemText, ListItemIcon, useTheme } from '@mui/material' import { t } from '@lingui/macro' const CommonListItem = ({ item, index, active, selected, isSelectMode, handleClickItem, handleClickMenu, }: { item: FileItem, index: number, active?: boolean selected?: boolean, isSelectMode?: boolean, handleClickItem: (index: number) => void, handleClickMenu: (event: React.MouseEvent, index: number) => void, }) => { const theme = useTheme() return ( { event.stopPropagation() handleClickMenu(event, index) }} > } > handleClickItem(index)} className={active ? 'active' : ''} sx={{ outline: selected ? `3px solid ${theme.palette.primary.main}55` : '', outlineOffset: '-5px' }} > {item.fileType === 'folder' && } {item.fileType === 'audio' && } {item.fileType === 'video' && } {item.fileType === 'picture' && } {item.fileType === 'other' && } { (item.thumbnails && item.thumbnails[0]) && { currentTarget.onerror = null currentTarget.style.display = 'none' }} /> } ) } export default CommonListItem ================================================ FILE: src/components/CommonList/CommonListItemCard.tsx ================================================ import { IconButton, ListItemButton, useTheme } from '@mui/material' import { FileItem } from '@/types/file' import InsertDriveFileRoundedIcon from '@mui/icons-material/InsertDriveFileRounded' import InsertPhotoRoundedIcon from '@mui/icons-material/InsertPhotoRounded' import FolderOpenRoundedIcon from '@mui/icons-material/FolderOpenRounded' import MusicNoteRoundedIcon from '@mui/icons-material/MusicNoteRounded' import MovieRoundedIcon from '@mui/icons-material/MovieRounded' import MoreVertRoundedIcon from '@mui/icons-material/MoreVertRounded' import Grid from '@mui/material/Grid' import useUtils from '@/hooks/useUtils' import { sizeConvert } from '@/utils' import { t } from '@lingui/macro' const CommonListItemCard = ({ item, index, active, selected, isSelectMode, handleClickItem, handleClickMenu, }: { item: FileItem, index: number, active?: boolean, selected?: boolean, isSelectMode?: boolean, handleClickItem: (index: number) => void, handleClickMenu: (event: React.MouseEvent, index: number) => void, }) => { const theme = useTheme() const { getThumbnailUrl } = useUtils() const thumbnailUrl = getThumbnailUrl(item) return ( handleClickItem(index)} > {item.fileType === 'folder' && } {item.fileType === 'audio' && } {item.fileType === 'video' && } {item.fileType === 'picture' && } {item.fileType === 'other' && } { thumbnailUrl && { currentTarget.onerror = null currentTarget.style.display = 'none' }} alt={item.fileName} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, width: '100%', height: '100%', objectFit: 'cover', }} /> } {item.fileType === 'folder' && } {item.fileType === 'audio' && } {item.fileType === 'video' && } {item.fileType === 'picture' && } {item.fileType === 'other' && } {item.fileName} {sizeConvert(item.fileSize)} { (item.fileType === 'audio' || item.fileType === 'video') && !isSelectMode && event.stopPropagation()} onTouchStart={(event) => event.stopPropagation()} onKeyDown={(event) => event.stopPropagation()} onClick={(event) => { event.stopPropagation() handleClickMenu(event, index) }} > } ) } export default CommonListItemCard ================================================ FILE: src/components/CommonList/CommonMenu.tsx ================================================ import { t } from '@lingui/macro' import { useNavigate } from 'react-router-dom' import shortUUID from 'short-uuid' import { Menu, MenuItem, ListItemText, Button, Dialog, DialogActions, DialogTitle, List, ListItem, ListItemButton, ListItemIcon } from '@mui/material' import PlaylistAddRoundedIcon from '@mui/icons-material/PlaylistAddRounded' import ListRoundedIcon from '@mui/icons-material/ListRounded' import usePlayQueueStore from '../../store/usePlayQueueStore' import usePlaylistsStore from '../../store/usePlaylistsStore' import useUiStore from '../../store/useUiStore' import { FileItem } from '../../types/file' import { useShallow } from 'zustand/shallow' const CommonMenu = ( { listData, listType, anchorEl, menuOpen, dialogOpen, selectIndex, selectIndexArray, setAnchorEl, setMenuOpen, setDialogOpen, setSelectIndex, setSelectIndexArray, handleClickRemove, } : { listData: FileItem[], listType: 'files' | 'playlist' | 'playQueue', anchorEl: null | HTMLElement, menuOpen: boolean, dialogOpen: boolean, selectIndex: number | null, selectIndexArray: number[], setAnchorEl: (anchorEl: null | HTMLElement) => void, setMenuOpen: (menuOpen: boolean) => void, setDialogOpen: (dialogOpen: boolean) => void, setSelectIndex: (index: number | null) => void setSelectIndexArray: (setSelectIndexArray: number[]) => void, handleClickRemove?: (indexArray: number[]) => void, } ) => { const navigate = useNavigate() const [updateFolderTree] = useUiStore( useShallow((state) => [state.updateFolderTree]) ) const playQueue = usePlayQueueStore.use.playQueue() const updatePlayQueue = usePlayQueueStore.use.updatePlayQueue() const [playlists, insertPlaylist, insertFilesToPlaylist] = usePlaylistsStore( useShallow((state) => [state.playlists, state.insertPlaylist, state.insertFilesToPlaylist]) ) const [updateAudioViewIsShow, updateVideoViewIsShow, updatePlayQueueIsShow] = useUiStore( useShallow((state) => [state.updateAudioViewIsShow, state.updateVideoViewIsShow, state.updatePlayQueueIsShow]) ) const handleCloseMenu = () => { setMenuOpen(false) setAnchorEl(null) } // 新建播放列表 const addNewPlaylist = () => { const id = shortUUID().generate() insertPlaylist({ id, title: t`New playlist`, fileList: [] }) } // 添加到播放列表 const addToPlaylist = (id: string) => { if (typeof selectIndex === 'number') { insertFilesToPlaylist(id, [ { fileName: listData[selectIndex].fileName, filePath: listData[selectIndex].filePath, fileSize: listData[selectIndex].fileSize, fileType: listData[selectIndex].fileType, } ]) setSelectIndex(null) } else if (selectIndexArray.length > 0) { insertFilesToPlaylist(id, selectIndexArray .filter(index => listData[index].fileType === 'audio' || listData[index].fileType === 'video') .map(index => ( { fileName: listData[index].fileName, filePath: listData[index].filePath, fileSize: listData[index].fileSize, fileType: listData[index].fileType, } ))) setSelectIndexArray([]) } setDialogOpen(false) } // 添加到播放队列 const handleClickAddToPlayQueue = () => { if (typeof selectIndex === 'number') { if (playQueue) { updatePlayQueue([...playQueue, { ...listData[selectIndex], index: Math.max(...playQueue.map(item => item.index)) + 1 }]) } else { updatePlayQueue([{ ...listData[selectIndex], index: 0 }]) } } else if (selectIndexArray && selectIndexArray.length > 0) { if (playQueue) { updatePlayQueue([ ...playQueue, ...selectIndexArray .filter(index => listData[index].fileType === 'audio' || listData[index].fileType === 'video') .map((index, _index) => ({ ...listData[index], index: Math.max(...playQueue.map(item => item.index)) + _index + 1 })) ]) } else { updatePlayQueue( selectIndexArray .filter(index => listData[index].fileType === 'audio' || listData[index].fileType === 'video') .map((index, _index) => ({ ...listData[index], index: _index })) ) } } setMenuOpen(false) setSelectIndex(null) setSelectIndexArray([]) } // 打开所在文件夹 const handleClickOpenInFolder = () => { if (typeof selectIndex === 'number') { updateFolderTree(listData[selectIndex].filePath.slice(0, -1)) navigate('/') setMenuOpen(false) setSelectIndex(null) updateAudioViewIsShow(false) updateVideoViewIsShow(false) updatePlayQueueIsShow(false) } } return ( <> { setDialogOpen(true) handleCloseMenu() }}> { (listType !== 'playQueue') && } { // 在 Files 组件中隐藏 handleClickRemove && typeof selectIndex === 'number' && } { handleClickRemove && { if (typeof selectIndex === 'number') { handleClickRemove([selectIndex]) } else if (selectIndexArray.length > 0) { handleClickRemove(selectIndexArray) } setSelectIndex(null) setSelectIndexArray([]) handleCloseMenu() }} > } { typeof selectIndex === 'number' && (selectIndexArray.length === 0) && { if (typeof selectIndex === 'number') { setSelectIndexArray([...selectIndexArray, selectIndex]) } handleCloseMenu() setSelectIndex(null) }}> } { { setSelectIndex(null) setSelectIndexArray(Array.from({ length: listData.length }, (v, i) => i)) handleCloseMenu() }}> } { (selectIndexArray.length > 0) && { setSelectIndex(null) setSelectIndexArray([]) handleCloseMenu() }}> } setDialogOpen(false)} fullWidth maxWidth='xs' > {t`Add to playlist`} {playlists?.map((item, index) => addToPlaylist(item.id)} > )} ) } export default CommonMenu ================================================ FILE: src/components/CommonList/ShuffleAll.tsx ================================================ import { ListItem, ListItemButton, ListItemIcon, ListItemText } from '@mui/material' import { t } from '@lingui/macro' import ShuffleRoundedIcon from '@mui/icons-material/ShuffleRounded' const ShuffleAll = ({ handleClickShuffleAll }: { handleClickShuffleAll: () => void }) => { return ( ) } export default ShuffleAll ================================================ FILE: src/components/Lyrics/Lyrics.tsx ================================================ import { useMemo, useRef } from 'react' import { useMediaQuery, useTheme } from '@mui/material' import { useSpring, animated } from '@react-spring/web' import { t } from '@lingui/macro' const Lyrics = ({ lyrics, currentTime }: { lyrics: string, currentTime: number }) => { const theme = useTheme() const lyricsRef = useRef(null) const isMobile = useMediaQuery('(max-height: 600px) or (max-width: 600px)') const xs = useMediaQuery(theme.breakpoints.up('xs')) const sm = useMediaQuery(theme.breakpoints.up('sm')) const md = useMediaQuery(theme.breakpoints.up('md')) const lg = useMediaQuery(theme.breakpoints.up('lg')) const xl = useMediaQuery(theme.breakpoints.up('xl')) const lyricLineHeight = xl ? 44 : lg ? 46 : md ? 48 : sm ? 48 : xs ? 48 : 50 type Lyrics = { time: number, text: string, }[]; function timeToSeconds(time: string) { const regex = /(\d{2}):(\d{2})\.(\d{2,3})/ const match = time.match(regex) if (match) { const minutes = parseInt(match[1], 10) const seconds = parseInt(match[2], 10) let milliseconds = parseInt(match[3], 10) if (match[3].length === 2) { milliseconds *= 10 } const totalSeconds = minutes * 60 + seconds + milliseconds / 1000 return totalSeconds } else { return -1 } } const lyricsList: Lyrics = lyrics .split(/\r?\n/) .map(item => ( { time: timeToSeconds(item.split(']')[0]), text: item.split(']')[1], } )) .filter(item => item.time !== -1) const currentLyricIndex = useMemo( () => { if (currentTime < lyricsList[0].time) return -1 if (currentTime > lyricsList[lyricsList.length - 1].time) return lyricsList.length - 1 return lyricsList.findIndex(item => item.time > currentTime) - 1 }, [currentTime, lyricsList] ) const { scrollY } = useSpring({ scrollY: currentLyricIndex >= 0 ? currentLyricIndex * lyricLineHeight : 0, config: { mass: 2, tension: 300, friction: 25 }, }) const isHighlight = (time: number) => lyricsList[currentLyricIndex] && time === lyricsList[currentLyricIndex].time return (
{ lyricsList.length === 0 ?
{t`No lyrics`}
: `translateY(-${y}px)`), }} >
{ lyricsList.map((item) =>

{item.text}

) }
}
) } export default Lyrics ================================================ FILE: src/data/licenses.ts ================================================ export const licenses = [ { 'name': '@azure/msal-browser', 'licenseType': 'MIT', 'link': 'https://github.com/AzureAD/microsoft-authentication-library-for-js', }, { 'name': '@azure/msal-react', 'licenseType': 'MIT', 'link': 'https://github.com/AzureAD/microsoft-authentication-library-for-js', }, { 'name': '@emotion/react', 'licenseType': 'MIT', 'link': 'https://github.com/emotion-js/emotion#main', }, { 'name': '@emotion/styled', 'licenseType': 'MIT', 'link': 'https://github.com/emotion-js/emotion#main', 'author': 'n/a' }, { 'name': '@fontsource/roboto', 'licenseType': 'Apache-2.0', 'link': 'https://github.com/fontsource/font-files', 'author': 'Google Inc.' }, { 'name': '@lingui', 'licenseType': 'MIT', 'link': 'https://github.com/lingui/js-lingui', 'author': 'Lingui', }, { 'name': '@mui/icons-material', 'licenseType': 'MIT', 'link': 'https://github.com/mui/material-ui', 'author': 'MUI Team' }, { 'name': '@mui/material', 'licenseType': 'MIT', 'link': 'https://github.com/mui/material-ui', 'author': 'MUI Team' }, { 'name': '@react-spring/web', 'licenseType': 'MIT', 'link': 'https://github.com/pmndrs/react-spring', 'author': 'Poimandres' }, { 'name': '@use-gesture/react', 'licenseType': 'MIT', 'link': 'https://github.com/pmndrs/use-gesture', 'author': 'Poimandres' }, { 'name': 'buffer', 'licenseType': 'MIT', 'link': 'https://github.com/feross/buffer', 'author': 'Feross Aboukhadijeh feross@feross.org https://feross.org' }, { 'name': 'color', 'licenseType': 'MIT', 'link': 'https://github.com/Qix-/color', 'author': 'Josh Junon' }, { 'name': 'extract-colors', 'licenseType': 'GPL-3.0', 'link': 'https://github.com/Namide/extract-colors', 'author': 'damien@doussaud.fr' }, { 'name': 'idb-keyval', 'licenseType': 'Apache-2.0', 'link': 'https://github.com/jakearchibald/idb-keyval', 'author': 'Jake Archibald (https://github.com/jakearchibald)' }, { 'name': 'music-metadata-browser', 'licenseType': 'MIT', 'link': 'https://github.com/Borewit/music-metadata-browser', 'author': 'Borewit https://github.com/Borewit' }, { 'name': 'react', 'licenseType': 'MIT', 'link': 'https://github.com/facebook/react', 'author': 'n/a' }, { 'name': 'react-dom', 'licenseType': 'MIT', 'link': 'https://github.com/facebook/react', 'author': 'n/a' }, { 'name': 'react-router-dom', 'licenseType': 'MIT', 'link': 'https://github.com/remix-run/react-router', 'author': 'Remix Software ' }, { 'name': 'react-virtualized', 'licenseType': 'MIT', 'link': 'https://github.com/bvaughn/react-virtualized', 'author': 'Brian Vaughn', }, { 'name': 'short-uuid', 'licenseType': 'MIT', 'link': 'https://github.com/oculus42/short-uuid', 'author': 'Samuel Rouse' }, { 'name': 'swr', 'licenseType': 'MIT', 'link': 'https://github.com/vercel/swr', 'author': 'Vercel' }, { 'name': 'zustand', 'licenseType': 'MIT', 'link': 'https://github.com/pmndrs/zustand', 'author': 'Poimandres' } ] ================================================ FILE: src/graph/authConfig.ts ================================================ /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { LogLevel } from '@azure/msal-browser' /** * Configuration object to be passed to MSAL instance on creation. * For a full list of MSAL.js configuration parameters, visit: * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/configuration.md */ export const msalConfig = { auth: { clientId: process.env.CLIENT_ID as string, authority: process.env.ONEDRIVE_AUTH, redirectUri: process.env.REDIRECT_URI as string, }, cache: { cacheLocation: 'localStorage', // This configures where your cache will be stored storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge }, system: { loggerOptions: { loggerCallback: (level: unknown, message: string, containsPii: boolean) => { if (containsPii) { return } switch (level) { case LogLevel.Error: console.error(message) return // case LogLevel.Info: // console.info(message) // return case LogLevel.Verbose: console.debug(message) return case LogLevel.Warning: console.warn(message) return } } } } } /** * Scopes you add here will be prompted for user consent during sign-in. * By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login request. * For more information about OIDC scopes, visit: * https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes */ export const loginRequest = { scopes: ['User.Read', 'Files.Read', 'Files.ReadWrite.AppFolder'] } /** * Add here the scopes to request when obtaining an access token for MS Graph API. For more information, see: * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/resources-and-scopes.md */ export const graphConfig = { graphMeEndpoint: process.env.ONEDRIVE_GME + '/v1.0' } ================================================ FILE: src/graph/graph.ts ================================================ import { graphConfig } from './authConfig' /** * Attaches a given access token to an MS Graph API call. Returns information about the user * @param accessToken */ export async function callMsGraph(accessToken: string) { const headers = new Headers() const bearer = `Bearer ${accessToken}` headers.append('Authorization', bearer) const options = { method: 'GET', headers: headers } return fetch(graphConfig.graphMeEndpoint, options) .then(response => response.json()) .catch(error => console.log(error)) } /** * 根据文件夹路径获取文件列表 * @param path * @param accessToken * @returns */ export async function getFiles(path: string, accessToken: string) { const headers = new Headers() const bearer = `Bearer ${accessToken}` headers.append('Authorization', bearer) const options = { method: 'GET', headers: headers } return fetch(`${graphConfig.graphMeEndpoint}/me/drive/root:/${encodeURIComponent(path)}:/children?$top=2147483647&expand=thumbnails`, options) .then(response => response.json()) .catch(error => console.log(error)) } /** * 根据文件路径获取文件信息 * @param path * @param accessToken * @returns */ export async function getFile(path: string, accessToken: string) { const headers = new Headers() const bearer = `Bearer ${accessToken}` headers.append('Authorization', bearer) const options = { method: 'GET', headers: headers } return fetch(`${graphConfig.graphMeEndpoint}/me/drive/root:/${encodeURIComponent(path)}`, options) .then(response => response.json()) .catch(error => console.log(error)) } export const getAppRootFiles = async (path: string, accessToken: string) => { const headers = new Headers() const bearer = `Bearer ${accessToken}` headers.append('Authorization', bearer) const options = { method: 'GET', headers: headers } return fetch(`${graphConfig.graphMeEndpoint}/me/drive/special/approot/${encodeURIComponent(path)}/children`, options) .then(response => response.json()) .catch(error => console.log(error)) } export const uploadAppRootJson = async (fileName: string, fileContent: BodyInit, accessToken: string) => { const headers = new Headers() const bearer = `Bearer ${accessToken}` headers.append('Authorization', bearer) headers.append('Content-Type', 'application/json') const options = { method: 'put', headers: headers, body: fileContent, } return fetch(`${graphConfig.graphMeEndpoint}/me/drive/special/approot:/${fileName}:/content`, options) .then(response => response.json()) .catch(error => console.log(error)) } export const search = async (path: string, searchQuery: string, accessToken: string) => { const headers = new Headers() const bearer = `Bearer ${accessToken}` headers.append('Authorization', bearer) const options = { method: 'GET', headers: headers } return fetch(`${graphConfig.graphMeEndpoint}/me/drive/root:/${encodeURIComponent(path)}:/search(q='${searchQuery}')`, options) .then(response => response.json()) .catch(error => console.log(error)) } ================================================ FILE: src/hooks/graph/useFilesData.ts ================================================ import { getAppRootFiles, getFile, getFiles, search, uploadAppRootJson } from '@/graph/graph' import { loginRequest } from '@/graph/authConfig' import { useMsal } from '@azure/msal-react' import { AccountInfo } from '@azure/msal-browser' const useFilesData = () => { const { instance } = useMsal() /** * 获取文件夹数据 * @param path * @returns */ const getFilesData = async (account: AccountInfo, path: string) => { await instance.initialize() const acquireToken = await instance.acquireTokenSilent({ ...loginRequest, account: account }) const response = await getFiles(path, acquireToken.accessToken) return response.value } /** * 获取文件数据 * @param filePath * @returns */ const getFileData = async (account: AccountInfo, filePath: string) => { await instance.initialize() const acquireToken = await instance.acquireTokenSilent({ ...loginRequest, account: account }) const response = await getFile(filePath, acquireToken.accessToken) return response } const getAppRootFilesData = async (account: AccountInfo, filePath: string) => { await instance.initialize() const acquireToken = await instance.acquireTokenSilent({ ...loginRequest, account: account }) const response = await getAppRootFiles(filePath, acquireToken.accessToken) return response } const uploadAppRootJsonData = async (account: AccountInfo, fileName: string, fileContent: BodyInit) => { await instance.initialize() const acquireToken = await instance.acquireTokenSilent({ ...loginRequest, account: account }) const response = await uploadAppRootJson(fileName, fileContent, acquireToken.accessToken) return response } const getSearchData = async (account: AccountInfo, path: string, searchQuery: string) => { await instance.initialize() const acquireToken = await instance.acquireTokenSilent({ ...loginRequest, account: account }) const response = await search(path, searchQuery, acquireToken.accessToken) return response.value } return { getFilesData, getFileData, getAppRootFilesData, uploadAppRootJsonData, getSearchData, } } export default useFilesData ================================================ FILE: src/hooks/graph/useSync.ts ================================================ import { useEffect, useMemo } from 'react' import useSWR from 'swr' import usePlaylistsStore from '@/store/usePlaylistsStore' import useHistoryStore from '@/store/useHistoryStore' import useFilesData from './useFilesData' import { FileItem } from '@/types/file' import { Playlist } from '@/types/playlist' import { fetchJson } from '@/utils' import useUser from './useUser' import { useShallow } from 'zustand/shallow' const useSync = () => { const { account } = useUser() const [historyList, updateHistoryList] = useHistoryStore( useShallow((state) => [state.historyList, state.updateHistoryList]) ) const [playlists, updatePlaylists] = usePlaylistsStore( useShallow((state) => [state.playlists, state.updatePlaylists]) ) const { getAppRootFilesData, uploadAppRootJsonData } = useFilesData() // 自动从 OneDrive 获取应用数据 const appDatafetcher = async () => { const appRootFiles = await getAppRootFilesData(account, '/') const historyFile = appRootFiles.value.find((item: { name: string }) => item.name === 'history.json') const playlistsFile = appRootFiles.value.find((item: { name: string }) => item.name === 'playlists.json') let history = [] let playlists = [] if (historyFile) { history = await fetchJson(historyFile['@microsoft.graph.downloadUrl']) } if (playlistsFile) { playlists = await fetchJson(playlistsFile['@microsoft.graph.downloadUrl']) } console.log('Get app data') return { history: history.map((item: FileItem) => ( { fileName: item.fileName, filePath: item.filePath, fileSize: item.fileSize, fileType: item.fileType, } )), playlists: playlists.map((playlist: Playlist) => ( { id: playlist.id, title: playlist.title, fileList: playlist.fileList.map((item: FileItem) => ( { fileName: item.fileName, filePath: item.filePath, fileSize: item.fileSize, fileType: item.fileType, } )), } )) } } const { data, error, isLoading } = useSWR<{ history: FileItem[], playlists: Playlist[] }>(account ? `${account.username}/fetchAppData` : null, appDatafetcher) // 自动更新播放历史 useEffect( () => { if (!isLoading && !error && data?.history) { updateHistoryList(data.history) } }, [data, error, isLoading, updateHistoryList] ) // 自动上传播放历史 useMemo( () => (historyList !== null) && uploadAppRootJsonData(account, 'history.json', JSON.stringify(historyList)), // eslint-disable-next-line react-hooks/exhaustive-deps [historyList] ) // 自动更新播放列表 useEffect( () => { if (!isLoading && !error && data?.playlists) { updatePlaylists(data.playlists) } }, [data, error, isLoading, updatePlaylists] ) // 自动上传播放列表 useMemo( () => (playlists !== null) && uploadAppRootJsonData(account, 'playlists.json', JSON.stringify(playlists)), // eslint-disable-next-line react-hooks/exhaustive-deps [playlists] ) } export default useSync ================================================ FILE: src/hooks/graph/useUser.ts ================================================ import { useMsal } from '@azure/msal-react' import { loginRequest } from '@/graph/authConfig' import useUiStore from '@/store/useUiStore' import { AccountInfo } from '@azure/msal-browser' const useUser = () => { const { instance, accounts } = useMsal() const currentAccount = useUiStore(state => state.currentAccount) const account: AccountInfo | null = accounts[currentAccount] || null // 登入 const login = () => { instance.loginRedirect(loginRequest) } //登出 const logout = (account: AccountInfo) => { instance.logoutRedirect({ account: account, postLogoutRedirectUri: '/', }) } return { accounts, account, login, logout } } export default useUser ================================================ FILE: src/hooks/player/useMediaSession.ts ================================================ import { useCallback, useEffect } from 'react' import usePlayerControl from './usePlayerControl' import usePlayerStore from '@/store/usePlayerStore' import { useShallow } from 'zustand/shallow' const useMediaSession = (player: HTMLVideoElement | null) => { const [ currentMetaData, cover, ] = usePlayerStore( useShallow( (state) => [ state.currentMetaData, state.cover, ] ) ) const { seekTo, handleClickPlay, handleClickPause, handleClickNext, handleClickPrev, handleClickSeekforward, handleClickSeekbackward, } = usePlayerControl(player) const defaultSkipTime = 10 // 更新 MediaSession 播放进度 const updatePositionState = useCallback( () => { if ('setPositionState' in navigator.mediaSession && player && !isNaN(player.duration)) { console.log('Update MediaSession Position State') navigator.mediaSession.setPositionState({ duration: player.duration, playbackRate: player.playbackRate, position: player.currentTime, }) } }, [player] ) useEffect( () => { if (player) player.onplaying = () => { updatePositionState() } }, [player, updatePositionState] ) // 设置 MediaSession useEffect( () => { if ('mediaSession' in navigator && currentMetaData) { console.log('Set MediaSession') navigator.mediaSession.metadata = new MediaMetadata({ title: currentMetaData?.title, artist: currentMetaData?.artist, album: currentMetaData?.album, artwork: [{ src: cover }] }) navigator.mediaSession.setActionHandler('play', () => handleClickPlay()) navigator.mediaSession.setActionHandler('pause', () => handleClickPause()) navigator.mediaSession.setActionHandler('nexttrack', () => handleClickNext()) navigator.mediaSession.setActionHandler('previoustrack', () => handleClickPrev()) navigator.mediaSession.setActionHandler('seekbackward', (details) => { const skipTime = details.seekOffset || defaultSkipTime handleClickSeekbackward(skipTime) }) navigator.mediaSession.setActionHandler('seekforward', (details) => { const skipTime = details.seekOffset || defaultSkipTime handleClickSeekforward(skipTime) }) navigator.mediaSession.setActionHandler('seekto', (details) => { if (details.seekTime) { seekTo(details.seekTime) } }) return () => { navigator.mediaSession.metadata = null navigator.mediaSession.setPositionState(undefined) navigator.mediaSession.setActionHandler('play', null) navigator.mediaSession.setActionHandler('pause', null) navigator.mediaSession.setActionHandler('nexttrack', null) navigator.mediaSession.setActionHandler('previoustrack', null) navigator.mediaSession.setActionHandler('seekbackward', null) navigator.mediaSession.setActionHandler('seekforward', null) navigator.mediaSession.setActionHandler('seekto', null) } } }, // eslint-disable-next-line react-hooks/exhaustive-deps [cover, currentMetaData] ) } export default useMediaSession ================================================ FILE: src/hooks/player/usePlayerControl.ts ================================================ import usePlayQueueStore from '@/store/usePlayQueueStore' import usePlayerStore from '@/store/usePlayerStore' import useUiStore from '@/store/useUiStore' import { shufflePlayQueue } from '@/utils' import { useEffect } from 'react' import { useShallow } from 'zustand/shallow' const usePlayerControl = (player: HTMLVideoElement | null) => { const playQueue = usePlayQueueStore.use.playQueue() const currentIndex = usePlayQueueStore.use.currentIndex() const updateCurrentIndex = usePlayQueueStore.use.updateCurrentIndex() const updatePlayQueue = usePlayQueueStore.use.updatePlayQueue() const [ updateAutoPlay, updateCurrentTime, ] = usePlayerStore( useShallow( (state) => [ state.updateAutoPlay, state.updateCurrentTime, ] ) ) const [ shuffle, repeat, volume, playbackRate, updateShuffle, updateRepeat, ] = useUiStore( useShallow( (state) => [ state.shuffle, state.repeat, state.volume, state.playbackRate, state.updateShuffle, state.updateRepeat, ] ) ) // 播放开始 const handleClickPlay = () => { updateAutoPlay(true) player?.play() } // 播放暂停 const handleClickPause = () => { updateAutoPlay(false) player?.pause() } // 下一曲 const handleClickNext = () => { if (player && playQueue) { const next = playQueue[(playQueue.findIndex(item => item.index === currentIndex) + 1)] // player.pause() if (next) { updateCurrentIndex(next.index) } else updateCurrentIndex(playQueue[0].index) } } // 上一曲 const handleClickPrev = () => { if (player && playQueue) { const prev = playQueue[(playQueue.findIndex(item => item.index === currentIndex) - 1)] // player.pause() console.log(prev, playQueue.at(-1)) if (prev) { updateCurrentIndex(prev.index) } else updateCurrentIndex(playQueue[playQueue.length - 1].index) } } /** * 快进 * @param skipTime */ const handleClickSeekbackward = (skipTime: number) => { if (player && !isNaN(player.duration)) { player.currentTime = Math.max(player.currentTime - skipTime, 0) } } /** * 快退 * @param skipTime */ const handleClickSeekforward = (skipTime: number) => { if (player && !isNaN(player.duration)) { player.currentTime = Math.min(player.currentTime + skipTime, player.duration) } } /** * 跳到指定位置 * @param seekTime */ const seekTo = (seekTime: number) => { if (player && !isNaN(player.duration)) { player.currentTime = seekTime } } /** * 点击进度条 * @param current */ const handleTimeRangeonChange = (current: number | number[]) => { if (player && !isNaN(player.duration) && typeof (current) === 'number') { updateCurrentTime(player.duration / 1000 * Number(current)) seekTo(player.duration / 1000 * Number(current)) } } // 随机 useEffect( () => { if (shuffle && playQueue) { const randomPlayQueue = shufflePlayQueue(playQueue, currentIndex) updatePlayQueue(randomPlayQueue) } else if (!shuffle && playQueue) { updatePlayQueue([...playQueue].sort((a, b) => a.index - b.index)) } }, // eslint-disable-next-line react-hooks/exhaustive-deps [shuffle] ) const handleClickShuffle = () => updateShuffle(!shuffle) // 重复 const handleClickRepeat = () => { if (repeat === 'off') updateRepeat('all') if (repeat === 'all') updateRepeat('one') if (repeat === 'one') updateRepeat('off') } useEffect( () => { if (player) { player.volume = (isNaN(volume / 100) || volume < 0 || volume > 100) ? 0.8 : (volume / 100) } }, // eslint-disable-next-line react-hooks/exhaustive-deps [player && player.src, volume] ) // 播放速度 useEffect( () => { if (player) { player.playbackRate = playbackRate } }, // eslint-disable-next-line react-hooks/exhaustive-deps [player && player.src, playbackRate] ) return { seekTo, handleClickPlay, handleClickPause, handleClickNext, handleClickPrev, handleClickSeekforward, handleClickSeekbackward, handleTimeRangeonChange, handleClickShuffle, handleClickRepeat, } } export default usePlayerControl ================================================ FILE: src/hooks/player/usePlayerCore.ts ================================================ import { useState, useMemo, useEffect } from 'react' import useHistoryStore from '@/store/useHistoryStore' import useLocalMetaDataStore from '@/store/useLocalMetaDataStore' import usePlayQueueStore from '@/store/usePlayQueueStore' import usePlayerStore from '@/store/usePlayerStore' import useUiStore from '@/store/useUiStore' import { checkFileType, getNetMetaData, pathConvert } from '@/utils' import useFilesData from '../graph/useFilesData' import { MetaData } from '@/types/MetaData' import useUser from '../graph/useUser' import { useShallow } from 'zustand/shallow' const usePlayerCore = (player: HTMLVideoElement | null) => { const { account } = useUser() const { getFileData } = useFilesData() const [ currentMetaData, metadataUpdate, autoPlay, isLoading, updateCurrentMetaData, updateMetadataUpdate, updateAutoPlay, updateIsLoading, updateCover, updateCurrentTime, updateDuration, ] = usePlayerStore( useShallow( (state) => [ state.currentMetaData, state.metadataUpdate, state.autoPlay, state.isLoading, state.updateCurrentMetaData, state.updateMetadataUpdate, state.updateAutoPlay, state.updateIsLoading, state.updateCover, state.updateCurrentTime, state.updateDuration, ] ) ) const { getLocalMetaData, setLocalMetaData } = useLocalMetaDataStore() const playQueue = usePlayQueueStore.use.playQueue() const currentIndex = usePlayQueueStore.use.currentIndex() const updateCurrentIndex = usePlayQueueStore.use.updateCurrentIndex() const repeat = useUiStore((state) => state.repeat) const [historyList, insertHistory] = useHistoryStore( useShallow((state) => [state.historyList, state.insertHistory]) ) const [url, setUrl] = useState('') const currentFile = playQueue?.filter(item => item.index === currentIndex)[0] const fileType = currentFile && checkFileType(currentFile.fileName) // 获取当前播放文件链接 useMemo( () => { if (player) { player.src = '' } if (playQueue !== null && playQueue.length !== 0 && currentFile) { updateIsLoading(true) try { getFileData(account, pathConvert(currentFile.filePath)).then((res) => { setUrl(res['@microsoft.graph.downloadUrl']) }) } catch (error) { console.error(error) updateAutoPlay(false) updateIsLoading(false) player?.pause() } } return true }, // eslint-disable-next-line react-hooks/exhaustive-deps [currentFile?.filePath] ) useMemo( () => { if (player !== null && playQueue) { updateDuration(0) player.load() player.onloadedmetadata = () => { if (isLoading && autoPlay) { player.play() if (historyList && currentFile) { insertHistory({ fileName: currentFile.fileName, filePath: currentFile.filePath, fileSize: currentFile.fileSize, fileType: currentFile.fileType, }) } } updateIsLoading(false) updateDuration(player.duration) } } return true }, // eslint-disable-next-line react-hooks/exhaustive-deps [url] ) // 设置当前播放进度 useEffect( () => { if (player) player.ontimeupdate = () => { updateCurrentTime(player.currentTime) } }, [player, updateCurrentTime] ) // 播放结束时 const onEnded = () => { if (playQueue) { const next = playQueue[playQueue.findIndex(item => item.index === currentIndex) + 1] const isPlayQueueEnd = currentIndex + 1 === playQueue?.length if (repeat === 'one') { player?.play() } else if (repeat === 'off' || repeat === 'all') { if (isPlayQueueEnd || !next) { if (repeat === 'off') { player?.pause() updateAutoPlay(false) } updateCurrentIndex(playQueue[0].index) } else updateCurrentIndex(next.index) } } } // 更新当前 metadata useEffect( () => { const updateMetaData = async () => { if (playQueue && currentFile) { const metaData: MetaData = await getLocalMetaData(currentFile.filePath) if (!metaData) { updateCover('./cover.svg') updateCurrentMetaData( { title: currentFile.fileName || 'Not playing', artist: '', path: currentFile.filePath, } ) } else if ( fileType === 'audio' && metaData && metaData.path && pathConvert(metaData.path) === pathConvert(currentFile.filePath) ) { console.log('Update current metaData: ', metaData) updateCurrentMetaData(metaData) if (metaData.cover?.length) { const cover = metaData.cover[0] if (cover && 'data' in cover.data && Array.isArray(cover.data.data)) { updateCover(URL.createObjectURL(new Blob([new Uint8Array(cover.data.data as unknown as ArrayBufferLike)], { type: cover.format }))) } else if (cover) { updateCover(URL.createObjectURL(new Blob([new Uint8Array(cover.data as ArrayBufferLike)], { type: cover.format }))) } } else { updateCover('./cover.svg') } } } } updateMetaData() }, // eslint-disable-next-line react-hooks/exhaustive-deps [currentFile?.filePath, metadataUpdate] ) // 获取在线 metadata useEffect( () => { const run = async () => { if (playQueue && fileType === 'audio' && currentMetaData?.path) { const localMetaData = await getLocalMetaData(currentMetaData?.path) if (!localMetaData) { const netMetaData = await getNetMetaData(currentMetaData?.path, url) if (netMetaData) { setLocalMetaData(netMetaData).then(() => updateMetadataUpdate()) } } } } run() }, // eslint-disable-next-line react-hooks/exhaustive-deps [url] ) // 设置标题 useEffect( () => { if (currentMetaData) { document.title = `${currentMetaData.title}${currentMetaData.artist ? ` - ${currentMetaData.artist}` : ''}` } return () => { document.title = 'OMP' } }, [currentMetaData, player?.paused] ) return { url, onEnded, } } export default usePlayerCore ================================================ FILE: src/hooks/ui/useControlHide.ts ================================================ import { useEffect } from 'react' import useUiStore from '../../store/useUiStore' import { useShallow } from 'zustand/shallow' const useControlHide = (type: string) => { const [videoViewIsShow, updateControlIsShow] = useUiStore( useShallow((state) => [state.videoViewIsShow, state.updateControlIsShow]) ) useEffect( () => { if (type === 'video' && videoViewIsShow) { let timer: string | number | NodeJS.Timeout | undefined const resetTimer = () => { updateControlIsShow(true) clearTimeout(timer) timer = (setTimeout(() => updateControlIsShow(false), 5000)) } resetTimer() window.addEventListener('mousemove', resetTimer) window.addEventListener('mousedown', resetTimer) window.addEventListener('keydown', resetTimer) return () => { window.removeEventListener('mousemove', resetTimer) window.removeEventListener('mousedown', resetTimer) window.removeEventListener('keydown', resetTimer) clearTimeout(timer) } } else { updateControlIsShow(true) } }, [type, updateControlIsShow, videoViewIsShow] ) } export default useControlHide ================================================ FILE: src/hooks/ui/useCustomTheme.ts ================================================ import usePlayerStore from '@/store/usePlayerStore' import useUiStore from '@/store/useUiStore' import { createTheme, useMediaQuery } from '@mui/material' import { extractColors } from 'extract-colors' import { useEffect, useMemo, useState } from 'react' import Color, { ColorInstance } from 'color' import { useShallow } from 'zustand/shallow' const useCustomTheme = () => { const [ coverColor, CoverThemeColor, colorMode, updateCoverColor, ] = useUiStore( useShallow( (state) => [ state.coverColor, state.CoverThemeColor, state.colorMode, state.updateCoverColor, ] ) ) const cover = usePlayerStore((state) => state.cover) useEffect( () => { if (colorMode === 'dark' || colorMode === 'light') document.documentElement.setAttribute('data-theme', colorMode) if (colorMode === 'auto') document.documentElement.removeAttribute('data-theme') return () => { document.documentElement.removeAttribute('data-theme') } }, [colorMode] ) const prefersColorSchemeDark = useMediaQuery('(prefers-color-scheme: dark)') const prefersDarkMode = useMemo(() => colorMode === 'light' ? false : prefersColorSchemeDark || colorMode === 'dark', [colorMode, prefersColorSchemeDark]) const [coverColors, setCoverColors] = useState<{ lightMode: string, darkMode: string } | null>(null) // 从专辑封面提取颜色 useEffect( () => { (async () => { if (cover !== './cover.svg') { const color = (await extractColors(cover))[0] const getLightModeColor = (color: ColorInstance): ColorInstance => color.isDark() ? color : getLightModeColor(color.lightness(color.lightness() - 1)) const lightModeColor = getLightModeColor(Color(color.hex)).hex() const getDarkModeColor = (color: ColorInstance): ColorInstance => color.isLight() ? color : getDarkModeColor(color.lightness(color.lightness() + 1)) const darkModeColor = getDarkModeColor(Color(color.hex)).hex() setCoverColors({ lightMode: lightModeColor, darkMode: darkModeColor }) } })() }, [cover] ) useEffect(() => { if (coverColors) { updateCoverColor(prefersDarkMode ? coverColors.darkMode : coverColors.lightMode) } }, [coverColors, prefersDarkMode, updateCoverColor]) const colors = useMemo(() => ({ primary: CoverThemeColor ? coverColor : prefersDarkMode ? '#df7ef9' : '#8e24aa', }), [CoverThemeColor, coverColor, prefersDarkMode]) const customTheme = useMemo(() => createTheme({ palette: { mode: prefersDarkMode ? 'dark' : 'light', background: { default: prefersDarkMode ? '#3b3b3b' : '#f7f7f7', paper: prefersDarkMode ? '#121212' : '#ffffff', }, primary: { main: colors.primary, }, secondary: { main: '#ff3d00', }, error: { main: '#ff1744', }, }, components: { MuiPaper: { styleOverrides: { root: { borderRadius: '0.5rem', }, }, }, MuiDrawer: { styleOverrides: { paper: { top: 'calc(env(titlebar-area-height, 0rem) + 0.25rem)', bottom: '0.25rem', height: 'auto', border: `${prefersDarkMode ? '#f7f7f722' : '#3b3b3b22'} solid 1px`, boxShadow: `0px 5px 5px -3px ${prefersDarkMode ? '#f7f7f733' : '#3b3b3b33'}, 0px 8px 10px 1px ${prefersDarkMode ? '#f7f7f722' : '#3b3b3b22'}, 0px 3px 14px 2px ${prefersDarkMode ? '#f7f7f720' : '#3b3b3b20'}`, }, paperAnchorLeft: { left: '0.25rem', }, paperAnchorRight: { right: '0.25rem', } }, }, MuiBackdrop: { styleOverrides: { root: { backgroundColor: 'transparent', }, }, }, MuiButton: { styleOverrides: { root: { borderRadius: '0.5rem', } } }, MuiList: { styleOverrides: { root: { padding: '0.25rem', borderRadius: '0.5rem', } } }, MuiListItemButton: { styleOverrides: { root: { borderRadius: '0.5rem', paddingLeft: '1rem', paddingRight: '1rem', '&.active': { backgroundColor: prefersDarkMode ? '#f7f7f711' : '#3b3b3b11', }, '&.active .MuiListItemIcon-root': { color: colors.primary, }, '&.active .MuiListItemText-root': { color: colors.primary, } }, }, }, MuiListItemIcon: { styleOverrides: { root: { minWidth: '0px !important', marginRight: '1rem', }, } }, MuiListItemText: { styleOverrides: { primary: { whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', }, secondary: { whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', fontWeight: 'lighter', }, } }, MuiListItemSecondaryAction: { styleOverrides: { root: { right: '0.5rem', } } }, MuiDialog: { styleOverrides: { paper: { border: `${prefersDarkMode ? '#f7f7f722' : '#3b3b3b22'} solid 1px`, boxShadow: `5px 5px 10px 0px ${prefersDarkMode ? '#f7f7f722' : '#3b3b3b22'}`, }, root: { ' .MuiBackdrop-root': { background: `${prefersDarkMode ? '#121212' : '#ffffff'}33`, backdropFilter: 'blur(0.5px)', }, } } }, MuiMenuItem: { styleOverrides: { root: { borderRadius: '0.5rem', } } }, MuiInputBase: { styleOverrides: { input: { borderRadius: '0.5rem', padding: '0.25rem', ':focus': { borderRadius: '0.5rem', backgroundColor: '#00000000', } }, } }, }, }), [colors.primary, prefersDarkMode] ) return customTheme } export default useCustomTheme ================================================ FILE: src/hooks/ui/useFullscreen.ts ================================================ import useUiStore from '@/store/useUiStore' import { useEffect } from 'react' const useFullscreen = () => { const updateFullscreen = useUiStore(state => state.updateFullscreen) // 检测全屏 useEffect(() => { const handleFullscreenChange = () => { updateFullscreen(!!document.fullscreenElement) } document.addEventListener('fullscreenchange', handleFullscreenChange) return () => { document.removeEventListener('fullscreenchange', handleFullscreenChange) } }) const handleClickFullscreen = () => { if (!document.fullscreenElement) { document.documentElement.requestFullscreen() } else if (document.fullscreenElement) { document.exitFullscreen() } } useEffect(() => { const handleClickF11 = (e: KeyboardEvent) => { if (e.code === 'F11') { e.preventDefault() handleClickFullscreen() } } document.addEventListener('keydown', handleClickF11) return () => { document.removeEventListener('keydown', handleClickF11) } }) return { handleClickFullscreen } } export default useFullscreen ================================================ FILE: src/hooks/ui/useStyles.ts ================================================ import { Theme } from '@mui/material' import { useMemo } from 'react' const useStyles = (theme: Theme) => { const scrollbar = useMemo(() => ({ '& ::-webkit-scrollbar': { width: '12px', height: '12px', }, '& ::-webkit-scrollbar-track': { backgroundColor: 'transparent', }, '& ::-webkit-scrollbar-thumb': { background: theme.palette.primary.main, borderRadius: '16px', border: '3.5px solid transparent', backgroundClip: 'content-box', visibility: 'hidden', }, '& :hover::-webkit-scrollbar-thumb': { visibility: 'visible', }, }), [theme.palette.primary.main] ) return { scrollbar } } export default useStyles ================================================ FILE: src/hooks/ui/useThemeColor.ts ================================================ import { useEffect } from 'react' import useUiStore from '../../store/useUiStore' import { blendHex } from '@/utils' import { Theme, useMediaQuery } from '@mui/material' import { useShallow } from 'zustand/shallow' const useThemeColor = (theme: Theme) => { const [ audioViewIsShow, audioViewTheme, videoViewIsShow, coverColor, ] = useUiStore( useShallow( (state) => [ state.audioViewIsShow, state.audioViewTheme, state.videoViewIsShow, state.coverColor, ] ) ) const windowControlsOverlayOpen = useMediaQuery('(display-mode: window-controls-overlay)') useEffect( () => { const themeColorLight = document.getElementById('themeColorLight') as HTMLMetaElement const themeColorDark = document.getElementById('themeColorDark') as HTMLMetaElement if (themeColorLight && themeColorDark) { if (!audioViewIsShow && !videoViewIsShow) { themeColorLight.content = theme.palette.background.default themeColorDark.content = theme.palette.background.default } else if (audioViewIsShow && audioViewTheme === 'classic') { themeColorLight.content = '#1e1e1e' themeColorDark.content = '#1e1e1e' } else if (audioViewIsShow && audioViewTheme === 'modern') { const color = blendHex(`${theme.palette.background.default}`, windowControlsOverlayOpen ? `${coverColor}31` : `${coverColor}33`) themeColorLight.content = color themeColorDark.content = color } } }, [audioViewIsShow, audioViewTheme, coverColor, theme.palette.background.default, videoViewIsShow, windowControlsOverlayOpen] ) } export default useThemeColor ================================================ FILE: src/hooks/useDebounce.ts ================================================ import { useState, useEffect } from 'react' export default function useDebounce(value: T, delay: number): T { const [debouncedValue, setDebouncedValue] = useState(value) useEffect( () => { const handler = setTimeout(() => setDebouncedValue(value), delay) return () => clearTimeout(handler) }, [value, delay] ) return debouncedValue } ================================================ FILE: src/hooks/useUtils.ts ================================================ import useUiStore from '@/store/useUiStore' import { FileItem } from '@/types/file' const useUtils = () => { const hdThumbnails = useUiStore(state => state.hdThumbnails) const getThumbnailUrl = (item: FileItem): string | null => { if (item.thumbnails && item.thumbnails[0]) return hdThumbnails ? item.thumbnails[0].large.url : item.thumbnails[0].medium.url return null } return { getThumbnailUrl } } export default useUtils ================================================ FILE: src/index.css ================================================ * { box-sizing: border-box; padding: 0; margin: 0; /* scrollbar-width: thin; */ } html { background-color: #f7f7f7; } @media (prefers-color-scheme: dark) { html { background-color: #3b3b3b; } } :root { color-scheme: light dark; font-synthesis: none; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; -webkit-text-size-adjust: 100%; text-size-adjust: 100%; font-family: Roboto, Helvetica, Arial, sans-serif; --custom-titlebar-height: 32px; --titlebar-height: env(titlebar-area-height, var(--custom-titlebar-height)); --titlebar-center-safe-width: calc((50dvw - (100dvw - env(titlebar-area-x) - env(titlebar-area-width))) * 2) } :root[data-theme="light"] { color-scheme: light; background-color: #f7f7f7; } :root[data-theme="dark"] { color-scheme: dark; background-color: #3b3b3b; } a { text-decoration: inherit; } .app-region-drag { -webkit-app-region: drag; app-region: drag; } .app-region-no-drag { -webkit-app-region: no-drag; app-region: no-drag; } .pt-titlebar-area-height { padding-top: env(titlebar-area-height, 0) !important; } .show-scrollbar::-webkit-scrollbar-thumb { visibility: visible !important; } ================================================ FILE: src/index.html ================================================ OMP
================================================ FILE: src/locales/en/messages.po ================================================ msgid "" msgstr "" "POT-Creation-Date: 2024-06-01 23:36+0800\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "X-Generator: @lingui/cli\n" "Language: en\n" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" "PO-Revision-Date: \n" "Last-Translator: \n" "Language-Team: \n" "Plural-Forms: \n" #: src/pages/Setting.tsx:161 msgid "About" msgstr "About" #: src/pages/Setting.tsx:95 msgid "Account" msgstr "Account" #: src/pages/Setting.tsx:225 msgid "Add account" msgstr "Add account" #: src/pages/SideBar/Playlists.tsx:52 #: src/pages/Player/PlayerMenu.tsx:358 #: src/components/CommonList/CommonMenu.tsx:257 msgid "Add playlist" msgstr "Add playlist" #: src/components/CommonList/CommonMenu.tsx:161 msgid "Add to play queue" msgstr "Add to play queue" #: src/pages/Player/PlayerMenu.tsx:234 #: src/pages/Player/PlayerMenu.tsx:332 #: src/components/CommonList/CommonMenu.tsx:156 #: src/components/CommonList/CommonMenu.tsx:231 msgid "Add to playlist" msgstr "Add to playlist" #: src/pages/Files/FilterMenu.tsx:105 msgid "Ascending" msgstr "Ascending" #: src/pages/Setting.tsx:137 msgid "Auto" msgstr "Auto" #: src/pages/Setting.tsx:176 msgid "Build time" msgstr "Build time" #: src/pages/Setting.tsx:230 #: src/pages/Playlist/Playlist.tsx:217 #: src/pages/Playlist/Playlist.tsx:240 #: src/pages/Player/PlayerMenu.tsx:363 #: src/components/CommonList/CommonMenu.tsx:262 msgid "Cancel" msgstr "Cancel" #: src/components/CommonList/CommonMenu.tsx:220 msgid "Cancel select" msgstr "Cancel select" #: src/pages/Player/PlayerMenu.tsx:289 msgid "Classic" msgstr "Classic" #: src/pages/Setting.tsx:118 msgid "Clear" msgstr "Clear" #: src/pages/Player/VideoPlayerTopbar.tsx:56 #: src/pages/Player/Audio/Modern.tsx:151 #: src/pages/PictureView/PictureView.tsx:72 msgid "Close" msgstr "Close" #: src/pages/Setting.tsx:144 msgid "Color mode" msgstr "Color mode" #: src/pages/Search.tsx:183 msgid "Current" msgstr "Current" #: src/pages/NavBar.tsx:122 msgid "Currently using a development version, please be careful with your data!" msgstr "Currently using a development version, please be careful with your data!" #: src/pages/Setting.tsx:127 msgid "Customize" msgstr "Customize" #: src/pages/Setting.tsx:139 msgid "Dark" msgstr "Dark" #: src/pages/Setting.tsx:114 msgid "Data" msgstr "Data" #: src/pages/Playlist/Playlist.tsx:191 msgid "Delete" msgstr "Delete" #: src/pages/Files/FilterMenu.tsx:106 msgid "Descending" msgstr "Descending" #: src/pages/Playlist/Playlist.tsx:213 msgid "Enter new title" msgstr "Enter new title" #: src/pages/SideBar/SideBar.tsx:19 msgid "Files" msgstr "Files" #: src/pages/Files/FilterMenu.tsx:114 msgid "Folders first" msgstr "Folders first" #: src/pages/Player/PlayerControl.tsx:316 #: src/pages/Player/Audio/Modern.tsx:201 msgid "Fullscreen" msgstr "Fullscreen" #: src/pages/Search.tsx:182 msgid "Global" msgstr "Global" #: src/pages/Files/FilterMenu.tsx:81 msgid "Grid" msgstr "Grid" #: src/pages/Files/FilterMenu.tsx:118 msgid "HD thumbnails" msgstr "HD thumbnails" #: src/pages/SideBar/SideBar.tsx:20 msgid "History" msgstr "History" #: src/pages/Files/FilterMenu.tsx:94 msgid "Last modified" msgstr "Last modified" #: src/pages/Setting.tsx:138 msgid "Light" msgstr "Light" #: src/pages/Files/FilterMenu.tsx:79 msgid "List" msgstr "List" #: src/pages/Setting.tsx:122 msgid "Local metaData cache" msgstr "Local metaData cache" #: src/pages/Player/Audio/Modern.tsx:184 msgid "Lyrics" msgstr "Lyrics" #: src/pages/Setting.tsx:98 msgid "Manage" msgstr "Manage" #: src/pages/Files/FilterMenu.tsx:115 msgid "Media only" msgstr "Media only" #: src/pages/Player/PlayerMenu.tsx:164 msgid "Menu" msgstr "Menu" #: src/pages/Player/PlayerMenu.tsx:277 msgid "Modern" msgstr "Modern" #: src/pages/Playlist/Playlist.tsx:157 #: src/components/CommonList/CommonListItemCard.tsx:88 #: src/components/CommonList/CommonListItem.tsx:39 msgid "More" msgstr "More" #: src/pages/Files/FilterMenu.tsx:80 msgid "Multicolumn list" msgstr "Multicolumn list" #: src/pages/Files/FilterMenu.tsx:92 msgid "Name" msgstr "Name" #: src/pages/SideBar/Playlists.tsx:19 #: src/pages/Player/PlayerMenu.tsx:131 #: src/components/CommonList/CommonMenu.tsx:71 msgid "New playlist" msgstr "New playlist" #: src/pages/Player/Audio/Modern.tsx:282 #: src/components/Lyrics/Lyrics.tsx:87 msgid "No lyrics" msgstr "No lyrics" #: src/pages/Playlist/Playlist.tsx:224 #: src/pages/Playlist/Playlist.tsx:241 msgid "OK" msgstr "OK" #: src/pages/Player/PlayerMenu.tsx:214 #: src/components/CommonList/CommonMenu.tsx:168 msgid "Open in folder" msgstr "Open in folder" #: src/pages/Setting.tsx:182 msgid "Open source dependencies" msgstr "Open source dependencies" #: src/components/CommonList/CommonList.tsx:383 msgid "Play all" msgstr "Play all" #: src/pages/Player/PlayerMenu.tsx:222 #: src/pages/Player/PlayerControl.tsx:306 #: src/pages/Player/Audio/Modern.tsx:169 msgid "Play queue" msgstr "Play queue" #: src/pages/Player/PlayerMenu.tsx:201 #: src/pages/Player/PlayerMenu.tsx:302 msgid "Playback rate" msgstr "Playback rate" #: src/pages/Setting.tsx:107 #: src/pages/LogIn.tsx:24 msgid "Please use Microsoft account authorization to log in" msgstr "Please use Microsoft account authorization to log in" #: src/pages/Player/PlayerMenu.tsx:251 msgid "Re-fetch metadata" msgstr "Re-fetch metadata" #: src/components/CommonList/CommonMenu.tsx:186 msgid "Remove" msgstr "Remove" #: src/pages/Playlist/Playlist.tsx:185 #: src/pages/Playlist/Playlist.tsx:203 msgid "Rename" msgstr "Rename" #: src/pages/Search.tsx:120 #: src/pages/Search.tsx:143 #: src/pages/Search.tsx:145 #: src/pages/Search.tsx:167 msgid "Search" msgstr "Search" #: src/components/CommonList/CommonMenu.tsx:199 msgid "Select" msgstr "Select" #: src/pages/Setting.tsx:196 msgid "Select account" msgstr "Select account" #: src/components/CommonList/CommonMenu.tsx:209 msgid "Select all" msgstr "Select all" #: src/pages/SideBar/SideBar.tsx:21 msgid "Setting" msgstr "Setting" #: src/components/CommonList/ShuffleAll.tsx:24 msgid "Shuffle all" msgstr "Shuffle all" #: src/pages/LogIn.tsx:26 msgid "Sign in" msgstr "登录" #: src/pages/Setting.tsx:204 msgid "Sign out" msgstr "Sign out" #: src/pages/Files/FilterMenu.tsx:93 msgid "Size" msgstr "Size" #: src/pages/Player/PlayerMenu.tsx:242 msgid "Switch fullscreen" msgstr "Switch fullscreen" #: src/pages/Player/PlayerMenu.tsx:192 #: src/pages/Player/PlayerMenu.tsx:265 msgid "Switch theme" msgstr "Switch theme" #: src/pages/Playlist/Playlist.tsx:237 msgid "The playlist will be deleted" msgstr "The playlist will be deleted" #: src/pages/Setting.tsx:156 msgid "Use album cover theme color" msgstr "Use album cover theme color" #: src/pages/Setting.tsx:170 msgid "Version" msgstr "Version" ================================================ FILE: src/locales/zh-CN/messages.po ================================================ msgid "" msgstr "" "POT-Creation-Date: 2024-06-01 23:36+0800\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "X-Generator: @lingui/cli\n" "Language: zh-CN\n" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" "PO-Revision-Date: \n" "Last-Translator: \n" "Language-Team: \n" "Plural-Forms: \n" #: src/pages/Setting.tsx:161 msgid "About" msgstr "关于" #: src/pages/Setting.tsx:95 msgid "Account" msgstr "账户" #: src/pages/Setting.tsx:225 msgid "Add account" msgstr "添加账户" #: src/pages/SideBar/Playlists.tsx:52 #: src/pages/Player/PlayerMenu.tsx:358 #: src/components/CommonList/CommonMenu.tsx:257 msgid "Add playlist" msgstr "新建播放列表" #: src/components/CommonList/CommonMenu.tsx:161 msgid "Add to play queue" msgstr "添加到播放队列" #: src/pages/Player/PlayerMenu.tsx:234 #: src/pages/Player/PlayerMenu.tsx:332 #: src/components/CommonList/CommonMenu.tsx:156 #: src/components/CommonList/CommonMenu.tsx:231 msgid "Add to playlist" msgstr "添加到播放列表" #: src/pages/Files/FilterMenu.tsx:105 msgid "Ascending" msgstr "正序" #: src/pages/Setting.tsx:137 msgid "Auto" msgstr "自动" #: src/pages/Setting.tsx:176 msgid "Build time" msgstr "编译日期" #: src/pages/Setting.tsx:230 #: src/pages/Playlist/Playlist.tsx:217 #: src/pages/Playlist/Playlist.tsx:240 #: src/pages/Player/PlayerMenu.tsx:363 #: src/components/CommonList/CommonMenu.tsx:262 msgid "Cancel" msgstr "取消" #: src/components/CommonList/CommonMenu.tsx:220 msgid "Cancel select" msgstr "取消选择" #: src/pages/Player/PlayerMenu.tsx:289 msgid "Classic" msgstr "经典" #: src/pages/Setting.tsx:118 msgid "Clear" msgstr "清除" #: src/pages/Player/VideoPlayerTopbar.tsx:56 #: src/pages/Player/Audio/Modern.tsx:151 #: src/pages/PictureView/PictureView.tsx:72 msgid "Close" msgstr "关闭" #: src/pages/Setting.tsx:144 msgid "Color mode" msgstr "颜色模式" #: src/pages/Search.tsx:183 msgid "Current" msgstr "当前" #: src/pages/NavBar.tsx:122 msgid "Currently using a development version, please be careful with your data!" msgstr "当前正在使用开发版本,请注意数据安全!" #: src/pages/Setting.tsx:127 msgid "Customize" msgstr "定制" #: src/pages/Setting.tsx:139 msgid "Dark" msgstr "深色" #: src/pages/Setting.tsx:114 msgid "Data" msgstr "数据" #: src/pages/Playlist/Playlist.tsx:191 msgid "Delete" msgstr "删除" #: src/pages/Files/FilterMenu.tsx:106 msgid "Descending" msgstr "倒序" #: src/pages/Playlist/Playlist.tsx:213 msgid "Enter new title" msgstr "输入新标题" #: src/pages/SideBar/SideBar.tsx:19 msgid "Files" msgstr "文件" #: src/pages/Files/FilterMenu.tsx:114 msgid "Folders first" msgstr "文件夹优先" #: src/pages/Player/PlayerControl.tsx:316 #: src/pages/Player/Audio/Modern.tsx:201 msgid "Fullscreen" msgstr "全屏" #: src/pages/Search.tsx:182 msgid "Global" msgstr "全局" #: src/pages/Files/FilterMenu.tsx:81 msgid "Grid" msgstr "网格" #: src/pages/Files/FilterMenu.tsx:118 msgid "HD thumbnails" msgstr "高清缩略图" #: src/pages/SideBar/SideBar.tsx:20 msgid "History" msgstr "历史" #: src/pages/Files/FilterMenu.tsx:94 msgid "Last modified" msgstr "最后修改" #: src/pages/Setting.tsx:138 msgid "Light" msgstr "浅色" #: src/pages/Files/FilterMenu.tsx:79 msgid "List" msgstr "列表" #: src/pages/Setting.tsx:122 msgid "Local metaData cache" msgstr "本地元数据缓存" #: src/pages/Player/Audio/Modern.tsx:184 msgid "Lyrics" msgstr "歌词" #: src/pages/Setting.tsx:98 msgid "Manage" msgstr "管理" #: src/pages/Files/FilterMenu.tsx:115 msgid "Media only" msgstr "仅限媒体" #: src/pages/Player/PlayerMenu.tsx:164 msgid "Menu" msgstr "菜单" #: src/pages/Player/PlayerMenu.tsx:277 msgid "Modern" msgstr "现代" #: src/pages/Playlist/Playlist.tsx:157 #: src/components/CommonList/CommonListItemCard.tsx:88 #: src/components/CommonList/CommonListItem.tsx:39 msgid "More" msgstr "更多" #: src/pages/Files/FilterMenu.tsx:80 msgid "Multicolumn list" msgstr "多列列表" #: src/pages/Files/FilterMenu.tsx:92 msgid "Name" msgstr "名称" #: src/pages/SideBar/Playlists.tsx:19 #: src/pages/Player/PlayerMenu.tsx:131 #: src/components/CommonList/CommonMenu.tsx:71 msgid "New playlist" msgstr "新播放列表" #: src/pages/Player/Audio/Modern.tsx:282 #: src/components/Lyrics/Lyrics.tsx:87 msgid "No lyrics" msgstr "无歌词" #: src/pages/Playlist/Playlist.tsx:224 #: src/pages/Playlist/Playlist.tsx:241 msgid "OK" msgstr "确定" #: src/pages/Player/PlayerMenu.tsx:214 #: src/components/CommonList/CommonMenu.tsx:168 msgid "Open in folder" msgstr "打开所在文件夹" #: src/pages/Setting.tsx:182 msgid "Open source dependencies" msgstr "开源库" #: src/components/CommonList/CommonList.tsx:383 msgid "Play all" msgstr "全部播放" #: src/pages/Player/PlayerMenu.tsx:222 #: src/pages/Player/PlayerControl.tsx:306 #: src/pages/Player/Audio/Modern.tsx:169 msgid "Play queue" msgstr "播放队列" #: src/pages/Player/PlayerMenu.tsx:201 #: src/pages/Player/PlayerMenu.tsx:302 msgid "Playback rate" msgstr "播放速度" #: src/pages/Setting.tsx:107 #: src/pages/LogIn.tsx:24 msgid "Please use Microsoft account authorization to log in" msgstr "请使用微软账户授权登录" #: src/pages/Player/PlayerMenu.tsx:251 msgid "Re-fetch metadata" msgstr "重新获取元数据" #: src/components/CommonList/CommonMenu.tsx:186 msgid "Remove" msgstr "移除" #: src/pages/Playlist/Playlist.tsx:185 #: src/pages/Playlist/Playlist.tsx:203 msgid "Rename" msgstr "重命名" #: src/pages/Search.tsx:120 #: src/pages/Search.tsx:143 #: src/pages/Search.tsx:145 #: src/pages/Search.tsx:167 msgid "Search" msgstr "搜索" #: src/components/CommonList/CommonMenu.tsx:199 msgid "Select" msgstr "选择" #: src/pages/Setting.tsx:196 msgid "Select account" msgstr "选择账户" #: src/components/CommonList/CommonMenu.tsx:209 msgid "Select all" msgstr "全选" #: src/pages/SideBar/SideBar.tsx:21 msgid "Setting" msgstr "设置" #: src/components/CommonList/ShuffleAll.tsx:24 msgid "Shuffle all" msgstr "全部随机播放" #: src/pages/LogIn.tsx:26 msgid "Sign in" msgstr "登录" #: src/pages/Setting.tsx:204 msgid "Sign out" msgstr "注销" #: src/pages/Files/FilterMenu.tsx:93 msgid "Size" msgstr "大小" #: src/pages/Player/PlayerMenu.tsx:242 msgid "Switch fullscreen" msgstr "切换全屏" #: src/pages/Player/PlayerMenu.tsx:192 #: src/pages/Player/PlayerMenu.tsx:265 msgid "Switch theme" msgstr "切换主题" #: src/pages/Playlist/Playlist.tsx:237 msgid "The playlist will be deleted" msgstr "播放列表将会被删除" #: src/pages/Setting.tsx:156 msgid "Use album cover theme color" msgstr "使用专辑封面主题色" #: src/pages/Setting.tsx:170 msgid "Version" msgstr "版本号" ================================================ FILE: src/main.tsx ================================================ import React from 'react' import ReactDOM from 'react-dom/client' import { PublicClientApplication } from '@azure/msal-browser' import { MsalProvider } from '@azure/msal-react' import { msalConfig } from './graph/authConfig' import { RouterProvider } from 'react-router-dom' import { i18n } from '@lingui/core' import { I18nProvider } from '@lingui/react' import { messages as enMessages } from './locales/en/messages' import { messages as zhCNMessages } from './locales/zh-CN/messages' import './index.css' import '@fontsource/roboto/300.css' import '@fontsource/roboto/400.css' import '@fontsource/roboto/500.css' import '@fontsource/roboto/700.css' import 'react-virtualized/styles.css' import router from './router' const msalInstance = new PublicClientApplication(msalConfig) const messages = { 'en': enMessages, 'zh-CN': zhCNMessages, } const languages = Object.keys(messages) const langage = navigator.language i18n.load(messages) i18n.activate(languages.includes(langage) ? langage : 'en') ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render( ) ================================================ FILE: src/pages/Files/BreadcrumbNav.tsx ================================================ import { Breadcrumbs, Button } from '@mui/material' import useUiStore from '../../store/useUiStore' const BreadcrumbNav = ({ handleClickNav }: { handleClickNav: (index: number) => void }) => { const folderTree = useUiStore((state) => state.folderTree) return ( { folderTree.map((name: string, index: number) => ) } ) } export default BreadcrumbNav ================================================ FILE: src/pages/Files/Files.tsx ================================================ import useSWR from 'swr' import useUiStore from '../../store/useUiStore' import useFilesData from '../../hooks/graph/useFilesData' import BreadcrumbNav from './BreadcrumbNav' import CommonList from '../../components/CommonList/CommonList' import Loading from '../Loading' import { remoteItemToFile, pathConvert } from '../../utils' import { FileItem, RemoteItem } from '../../types/file' import Grid from '@mui/material/Grid' import FilterMenu from './FilterMenu' import PictureView from '../PictureView/PictureView' import { Divider } from '@mui/material' import { useState } from 'react' import useUser from '@/hooks/graph/useUser' import { useNavigate } from 'react-router-dom' import usePictureStore from '@/store/usePictureStore' import usePlayQueueStore from '@/store/usePlayQueueStore' import usePlayerStore from '@/store/usePlayerStore' import { useShallow } from 'zustand/shallow' const Files = () => { const [ shuffle, folderTree, display, sortBy, orderBy, foldersFirst, mediaOnly, updateFolderTree, updateVideoViewIsShow, updateShuffle, ] = useUiStore( useShallow( (state) => [ state.shuffle, state.folderTree, state.display, state.sortBy, state.orderBy, state.foldersFirst, state.mediaOnly, state.updateFolderTree, state.updateVideoViewIsShow, state.updateShuffle, ] ) ) const [updatePictureList, updateCurrentPicture] = usePictureStore( useShallow((state) => [state.updatePictureList, state.updateCurrentPicture]) ) const updatePlayQueue = usePlayQueueStore.use.updatePlayQueue() const updateCurrentIndex = usePlayQueueStore.use.updateCurrentIndex() const updateAutoPlay = usePlayerStore(state => state.updateAutoPlay) const { getFilesData } = useFilesData() const navigate = useNavigate() const { account } = useUser() const path = pathConvert(folderTree) const fileListFetcher = async (path: string) => { const res: RemoteItem[] = await getFilesData(account, path) return remoteItemToFile(res) } const { data: fileListData, error: fileListError, isLoading: fileListIsLoading } = useSWR( `${account.username}/${path}`, () => fileListFetcher(path), { revalidateOnFocus: false } ) const filteredFileList = fileListData?.filter((item) => mediaOnly ? item.fileType !== 'other' : true) const sortedFileList = filteredFileList?.sort((a, b) => { if (foldersFirst) { if (a.fileType === 'folder' && b.fileType !== 'folder') { return -1 } else if (a.fileType !== 'folder' && b.fileType === 'folder') { return 1 } } if (sortBy === 'name') { if (orderBy === 'asc') { return (a.fileName).localeCompare(b.fileName) } else { return (b.fileName).localeCompare(a.fileName) } } else if (sortBy === 'size') { if (orderBy === 'asc') { return a.fileSize - b.fileSize } else { return b.fileSize - a.fileSize } } else if (sortBy === 'datetime' && a.lastModifiedDateTime && b.lastModifiedDateTime) { if (orderBy === 'asc') { return new Date(a.lastModifiedDateTime).getTime() - new Date(b.lastModifiedDateTime).getTime() } else { return new Date(b.lastModifiedDateTime).getTime() - new Date(a.lastModifiedDateTime).getTime() } } else return 0 }) const [scrollPath, setScrollPath] = useState() const scrollIndex = scrollPath ? sortedFileList?.findIndex(item => pathConvert(item.filePath) === pathConvert(scrollPath)) : undefined const handleClickNav = (index: number) => { if (index < folderTree.length - 1) { setScrollPath(folderTree.slice(0, index + 2)) updateFolderTree(folderTree.slice(0, index + 1)) } } const open = (index: number) => { const listData = sortedFileList if (listData) { const currentFile = listData[index] if (currentFile && currentFile.fileType === 'folder') { updateFolderTree(currentFile.filePath) navigate('/') } if (currentFile && currentFile.fileType === 'picture') { const list = listData.filter(item => item.fileType === 'picture') updatePictureList(list) updateCurrentPicture(currentFile) } if (currentFile && (currentFile.fileType === 'audio' || currentFile.fileType === 'video')) { const list = listData .filter((item) => item.fileType === 'audio' || item.fileType === 'video') .map((item, _index) => ({ ...item, index: _index })) if (shuffle) { updateShuffle(false) } updatePlayQueue(list) updateCurrentIndex(list.find(item => pathConvert(item.filePath) === pathConvert(currentFile.filePath))?.index || 0) updateAutoPlay(true) if (currentFile.fileType === 'video') { updateVideoViewIsShow(true) } } if (!currentFile) { const discs = listData.filter(item => item.fileName.toLocaleLowerCase().includes('disc')) if (discs.length > 0) { Promise.all(discs.map(item => getFilesData(account, pathConvert(item.filePath)).then(res => remoteItemToFile(res)))) .then(files => { const list = files .flat() .filter((item) => item.fileType === 'audio' || item.fileType === 'video') .map((item, _index) => ({ ...item, index: _index })) if (list.length > 0) { if (shuffle) { updateShuffle(false) } updatePlayQueue(list) updateCurrentIndex(0) updateAutoPlay(true) if (list[0].fileType === 'video') { updateVideoViewIsShow(true) } } }) } } } } return ( { (fileListIsLoading || !fileListData || !sortedFileList || fileListError) ? : } ) } export default Files ================================================ FILE: src/pages/Files/FilterMenu.tsx ================================================ import useUiStore from '@/store/useUiStore' import FilterListRoundedIcon from '@mui/icons-material/FilterListRounded' import { Checkbox, Divider, FormControlLabel, FormGroup, IconButton, Menu, Radio, RadioGroup } from '@mui/material' import React from 'react' import { t } from '@lingui/macro' import { useShallow } from 'zustand/shallow' const FilterMenu = () => { const [anchorEl, setAnchorEl] = React.useState(null) const open = Boolean(anchorEl) const handleClick = (event: React.MouseEvent) => { setAnchorEl(event.currentTarget) } const handleClose = () => { setAnchorEl(null) } const [ display, sortBy, orderBy, foldersFirst, mediaOnly, hdThumbnails, updateDisplay, updateSortBy, updateOrderBy, updateFoldersFirst, updateMediaOnly, updateHDThumbnails ] = useUiStore( useShallow( (state) => [ state.display, state.sortBy, state.orderBy, state.foldersFirst, state.mediaOnly, state.hdThumbnails, state.updateDisplay, state.updateSortBy, state.updateOrderBy, state.updateFoldersFirst, state.updateMediaOnly, state.updateHDThumbnails, ] ) ) return (
} label={t`List`} onChange={() => updateDisplay('list')} /> } label={t`Multicolumn list`} onChange={() => updateDisplay('multicolumnList')} /> } label={t`Grid`} onChange={() => updateDisplay('grid')} /> } label={t`Name`} onChange={() => updateSortBy('name')} /> } label={t`Size`} onChange={() => updateSortBy('size')} /> } label={t`Last modified`} onChange={() => updateSortBy('datetime')} /> } label={t`Ascending`} onChange={() => updateOrderBy('asc')} /> } label={t`Descending`} onChange={() => updateOrderBy('desc')} /> } label={t`Folders first`} onChange={() => updateFoldersFirst(!foldersFirst)} /> } label={t`Media only`} onChange={() => updateMediaOnly(!mediaOnly)} /> { display === 'grid' && } label={t`HD thumbnails`} onChange={() => updateHDThumbnails(!hdThumbnails)} /> }
) } export default FilterMenu ================================================ FILE: src/pages/History.tsx ================================================ import useHistoryStore from '../store/useHistoryStore' import CommonList from '../components/CommonList/CommonList' import Loading from './Loading' import usePlayQueueStore from '@/store/usePlayQueueStore' import usePlayerStore from '@/store/usePlayerStore' import useUiStore from '@/store/useUiStore' import { checkFileType } from '@/utils' import { useShallow } from 'zustand/shallow' const History = () => { const [historyList, removeHistory] = useHistoryStore( useShallow((state) => [state.historyList, state.removeHistory]) ) const [shuffle, updateVideoViewIsShow, updateShuffle,] = useUiStore( useShallow((state) => [state.shuffle, state.updateVideoViewIsShow, state.updateShuffle]) ) const updatePlayQueue = usePlayQueueStore.use.updatePlayQueue() const updateCurrentIndex = usePlayQueueStore.use.updateCurrentIndex() const updateAutoPlay = usePlayerStore(state => state.updateAutoPlay) const open = (index: number) => { const listData = historyList if (listData) { const currentFile = listData[index] if (currentFile) { const list = listData .map((item, _index) => ({ ...item, index: _index })) if (shuffle) { updateShuffle(false) } updatePlayQueue(list) updateCurrentIndex(list[index].index) updateAutoPlay(true) if (checkFileType(currentFile.fileName) === 'video') { updateVideoViewIsShow(true) } } } } return (
{ (!historyList) ? : }
) } export default History ================================================ FILE: src/pages/Loading.tsx ================================================ import { CircularProgress } from '@mui/material' const Loading = () => { return (
) } export default Loading ================================================ FILE: src/pages/LogIn.tsx ================================================ import { Button, Container, IconButton, Link, Typography } from '@mui/material' import GitHubIcon from '@mui/icons-material/GitHub' import { t } from '@lingui/macro' import useUser from '../hooks/graph/useUser' const LogIn = () => { const { login } = useUser() return (
{t`Please use Microsoft account authorization to log in`}
Made with ❤ from 22
) } export default LogIn ================================================ FILE: src/pages/NavBar.tsx ================================================ import { Box, Typography, Container, IconButton, useMediaQuery, useTheme, Tooltip } from '@mui/material' import MenuRoundedIcon from '@mui/icons-material/MenuRounded' import useUiStore from '../store/useUiStore' import Search from './Search' import { useShallow } from 'zustand/shallow' import INFO from '@/data/info' import { t } from '@lingui/macro' const NavBar = () => { const [ mobileSideBarOpen, audioViewIsShow, videoViewIsShow, updateMobileSideBarOpen, ] = useUiStore( useShallow( (state) => [ state.mobileSideBarOpen, state.audioViewIsShow, state.videoViewIsShow, state.updateMobileSideBarOpen, ] ) ) const windowControlsOverlayOpen = useMediaQuery('(display-mode: window-controls-overlay)') const theme = useTheme() const sm = useMediaQuery(theme.breakpoints.up('sm')) return ( {/* 搜索栏 */} {/* 标题 */} updateMobileSideBarOpen(!mobileSideBarOpen)} sx={{ display: { xs: '', sm: 'none' }, borderRadius: '0.2rem', '.MuiTouchRipple-ripple .MuiTouchRipple-child': { borderRadius: '0.2rem', }, }} className='app-region-no-drag' > logo OMP { INFO.dev && DEV } ) } export default NavBar ================================================ FILE: src/pages/NotFound.tsx ================================================ import { useRouteError } from 'react-router-dom' const NotFound = () => { const error = useRouteError() console.error(error) return (
) } export default NotFound ================================================ FILE: src/pages/PictureView/PictureList.tsx ================================================ import usePictureStore from '@/store/usePictureStore' import { Box } from '@mui/material' import PictureListItem from './PictureListItem' import { Grid, WindowScroller } from 'react-virtualized' import { CSSProperties, Key, useEffect, useRef } from 'react' import { useShallow } from 'zustand/shallow' const PictureList = () => { const [ pictureList, currentPicture, updateCurrentPicture, ] = usePictureStore( useShallow( (state) => [ state.pictureList, state.currentPicture, state.updateCurrentPicture, ] ) ) const currentIndex = pictureList.findIndex(picture => picture.id === currentPicture?.id) const scrollContainerRef = useRef(null) const gridRef = useRef(null) useEffect(() => { const scrollContainer = scrollContainerRef.current const grid = gridRef.current if (scrollContainer && grid) { const onWheel = (e: WheelEvent) => { if (e.deltaY === 0) return e.preventDefault() const gridWidth = grid.props.columnWidth as number * grid.props.columnCount let left: number = grid.state.scrollLeft + e.deltaY * 2 if (left < 0) left = 0 if (left + grid.props.width + 32 > gridWidth) left = gridWidth - grid.props.width + 32 grid.scrollToPosition({ scrollLeft: left, scrollTop: 0 }) } scrollContainer.addEventListener('wheel', onWheel) return () => scrollContainer.removeEventListener('wheel', onWheel) } }, []) const cellRenderer = ({ columnIndex, key, style }: { columnIndex: number, key: Key, style: CSSProperties }) => updateCurrentPicture(pictureList[columnIndex])} key={key} style={style} sx={{ padding: '4px', display: 'flex', justifyContent: 'center', alignItems: 'center' }}> return ( {({ height, width }) => ( gridRef.current = ref} columnCount={pictureList.length} columnWidth={104} rowCount={1} rowHeight={112} height={height} width={width} autoHeight scrollToColumn={currentIndex} scrollToAlignment={'center'} style={{ padding: '0 16px', }} /> )} ) } export default PictureList ================================================ FILE: src/pages/PictureView/PictureListItem.tsx ================================================ import { FileItem } from '@/types/file' import { Paper, useTheme } from '@mui/material' const PictureListItem = ({ picture, isCurrent }: { picture: FileItem, isCurrent: boolean }) => { const theme = useTheme() return ( {picture.fileName} ) } export default PictureListItem ================================================ FILE: src/pages/PictureView/PictureView.tsx ================================================ import usePictureStore from '@/store/usePictureStore' import CloseRoundedIcon from '@mui/icons-material/CloseRounded' import { Box, Dialog, IconButton, Tooltip } from '@mui/material' import PictureList from './PictureList' import { useEffect, useRef } from 'react' import { useShallow } from 'zustand/shallow' import { t } from '@lingui/macro' const PictureView = () => { const [ currentPicture, updatePictureList, updateCurrentPicture, ] = usePictureStore( useShallow( (state) => [ state.currentPicture, state.updatePictureList, state.updateCurrentPicture, ] ) ) const open = currentPicture !== null const handleClose = () => { updatePictureList([]) updateCurrentPicture(null) } const imgRef = useRef(null) useEffect( () => { const imageElement = imgRef.current if (imageElement) { imageElement.src = currentPicture?.url || '' } return () => { if (imageElement) imageElement.src = '' } }, [currentPicture?.url] ) return ( {currentPicture?.fileName} {currentPicture?.fileName} ) } export default PictureView ================================================ FILE: src/pages/Player/Audio/Audio.tsx ================================================ import useUiStore from '@/store/useUiStore' import { useMemo, useRef } from 'react' import Classic from './Classic' import Modern from './Modern' import { animated, useSpring } from '@react-spring/web' import { useDrag } from '@use-gesture/react' import { useShallow } from 'zustand/shallow' const Audio = ({ player }: { player: HTMLVideoElement | null }) => { const [ audioViewIsShow, audioViewTheme, updateAudioViewIsShow, ] = useUiStore( useShallow( (state) => [ state.audioViewIsShow, state.audioViewTheme, state.updateAudioViewIsShow, ] ) ) const topRef = useRef(0) const [{ top, p, borderRadius }, api] = useSpring(() => ({ from: { top: audioViewIsShow ? '0' : '100dvh', p: audioViewIsShow ? '0' : '0.5rem', borderRadius: '0.5rem', }, // config: { // mass: 1, // tension: 190, // friction: 20, // } })) const show = () => api.start({ to: { top: '0', p: '0', borderRadius: '0' }, // config: { clamp: false }, }) const hide = () => { api.start({ from: { top: `${topRef.current}` }, to: { top: '100dvh', p: '0.5rem', borderRadius: '0.5rem' }, // config: { clamp: true }, }) topRef.current = 0 } useMemo( () => audioViewIsShow ? show() : hide(), // eslint-disable-next-line react-hooks/exhaustive-deps [audioViewIsShow] ) const bind = useDrag(({ down, movement: [, my], last, event }) => { const element = event.target as HTMLElement if (element.classList.contains('MuiSlider-thumb')) return if ('pointerType' in event && event.pointerType !== 'touch') { return } if (last) { if (my > 40) { updateAudioViewIsShow(false) } else { topRef.current = 0 show() } } else if (down) { topRef.current = my api.start({ top: my > 0 ? `${my}px` : '0', borderRadius: '0.5rem' }) } }) return ( {audioViewTheme === 'classic' && } {audioViewTheme === 'modern' && } ) } export default Audio ================================================ FILE: src/pages/Player/Audio/Classic.tsx ================================================ import usePlayerControl from '@/hooks/player/usePlayerControl' import useFullscreen from '@/hooks/ui/useFullscreen' import usePlayQueueStore from '@/store/usePlayQueueStore' import usePlayerStore from '@/store/usePlayerStore' import useUiStore from '@/store/useUiStore' import { timeShift } from '@/utils' import { CloseFullscreen, FastForward, FastRewind, KeyboardArrowDownOutlined, OpenInFull, PanoramaOutlined, PauseCircleOutlined, PlayCircleOutlined, QueueMusicOutlined, Repeat, RepeatOne, Shuffle, SkipNext, SkipPrevious } from '@mui/icons-material' import { Container, Box, IconButton, Typography, Slider, CircularProgress } from '@mui/material' import Grid from '@mui/material/Grid' import PlayerMenu from '../PlayerMenu' import { SpringValue, animated } from '@react-spring/web' import { useShallow } from 'zustand/shallow' const Classic = ({ player, styles }: { player: HTMLVideoElement | null, styles: { borderRadius: SpringValue } }) => { const playQueue = usePlayQueueStore.use.playQueue() const [ audioViewIsShow, fullscreen, backgroundIsShow, shuffle, repeat, coverColor, updateAudioViewIsShow, updatePlayQueueIsShow, updateBackgroundIsShow, ] = useUiStore( useShallow( (state) => [ state.audioViewIsShow, state.fullscreen, state.backgroundIsShow, state.shuffle, state.repeat, state.coverColor, state.updateAudioViewIsShow, state.updatePlayQueueIsShow, state.updateBackgroundIsShow, ] ) ) const [ currentMetaData, isLoading, cover, currentTime, duration ] = usePlayerStore( useShallow( (state) => [ state.currentMetaData, state.isLoading, state.cover, state.currentTime, state.duration, ] ) ) const { handleClickPlay, handleClickPause, handleClickNext, handleClickPrev, handleClickSeekforward, handleClickSeekbackward, handleTimeRangeonChange, handleClickShuffle, handleClickRepeat, } = usePlayerControl(player) const { handleClickFullscreen } = useFullscreen() return ( updateAudioViewIsShow(!audioViewIsShow)} className='app-region-no-drag' > updatePlayQueueIsShow(true)} className='app-region-no-drag' > updateBackgroundIsShow(!backgroundIsShow)} className='app-region-no-drag' > handleClickFullscreen()} className='app-region-no-drag' > { fullscreen ? : } {/* 封面和音频信息 */} {/* 封面 */} Cover {/* 音频信息 */} {(!playQueue || !currentMetaData) ? 'Not playing' : currentMetaData.title} {(playQueue && currentMetaData) && currentMetaData.artist} {(playQueue && currentMetaData) && currentMetaData.album} {/* 播放进度条 */} handleTimeRangeonChange(current)} sx={{ color: '#fff', width: '100%' }} /> {timeShift(currentTime)} {timeShift((duration) ? duration : 0)} handleClickShuffle()}> handleClickPrev()} > handleClickSeekbackward(10)} > { (!isLoading && player?.paused) && handleClickPlay()}> } { (!isLoading && !player?.paused) && handleClickPause()}> } { isLoading && } handleClickSeekforward(10)} > handleClickRepeat()} > { (repeat === 'one') ? : } ) } export default Classic ================================================ FILE: src/pages/Player/Audio/Modern.tsx ================================================ import { Box, CircularProgress, Container, IconButton, Slider, Tab, Tabs, Tooltip, Typography, useMediaQuery, useTheme } from '@mui/material' import Grid from '@mui/material/Grid' import useFullscreen from '@/hooks/ui/useFullscreen' import KeyboardArrowDownRoundedIcon from '@mui/icons-material/KeyboardArrowDownRounded' import CloseFullscreenRoundedIcon from '@mui/icons-material/CloseFullscreenRounded' import OpenInFullRoundedIcon from '@mui/icons-material/OpenInFullRounded' import ShuffleRoundedIcon from '@mui/icons-material/ShuffleRounded' import SkipPreviousRoundedIcon from '@mui/icons-material/SkipPreviousRounded' import FastRewindRoundedIcon from '@mui/icons-material/FastRewindRounded' import PlayCircleOutlineRoundedIcon from '@mui/icons-material/PlayCircleOutlineRounded' import PauseCircleOutlineRoundedIcon from '@mui/icons-material/PauseCircleOutlineRounded' import FastForwardRoundedIcon from '@mui/icons-material/FastForwardRounded' import SkipNextRoundedIcon from '@mui/icons-material/SkipNextRounded' import RepeatOneRoundedIcon from '@mui/icons-material/RepeatOneRounded' import RepeatRoundedIcon from '@mui/icons-material/RepeatRounded' import QueueMusicRoundedIcon from '@mui/icons-material/QueueMusicRounded' import LyricsRoundedIcon from '@mui/icons-material/LyricsRounded' import { SpringValue, animated, useSpring } from '@react-spring/web' import { useMemo, useState } from 'react' import { t } from '@lingui/macro' import usePlayerControl from '@/hooks/player/usePlayerControl' import usePlayQueueStore from '@/store/usePlayQueueStore' import usePlayerStore from '@/store/usePlayerStore' import useUiStore from '@/store/useUiStore' import PlayerMenu from '../PlayerMenu' import { timeShift } from '@/utils' import { useShallow } from 'zustand/shallow' import Lyrics from '@/components/Lyrics/Lyrics' import VolumeControl from '../VolumeControl' const Modern = ({ player, styles }: { player: HTMLVideoElement | null, styles: { borderRadius: SpringValue } }) => { const theme = useTheme() const playQueue = usePlayQueueStore.use.playQueue() const [ audioViewIsShow, fullscreen, shuffle, repeat, coverColor, lyricsIsShow, updateAudioViewIsShow, updatePlayQueueIsShow, updateLyricsIsShow, ] = useUiStore( useShallow( (state) => [ state.audioViewIsShow, state.fullscreen, state.shuffle, state.repeat, state.coverColor, state.lyricsIsShow, state.updateAudioViewIsShow, state.updatePlayQueueIsShow, state.updateLyricsIsShow, ] ) ) const [ currentMetaData, isLoading, cover, currentTime, duration ] = usePlayerStore( useShallow( (state) => [ state.currentMetaData, state.isLoading, state.cover, state.currentTime, state.duration, ] ) ) const { handleClickPlay, handleClickPause, handleClickNext, handleClickPrev, handleClickSeekforward, handleClickSeekbackward, handleTimeRangeonChange, handleClickShuffle, handleClickRepeat, } = usePlayerControl(player) const { handleClickFullscreen } = useFullscreen() const [{ background }, api] = useSpring( () => ({ background: `linear-gradient(180deg, ${coverColor}33, ${coverColor}15, ${coverColor}05), ${theme.palette.background.default}`, }) ) useMemo( () => api.start({ background: `linear-gradient(180deg, ${coverColor}33, ${coverColor}15, ${coverColor}05), ${theme.palette.background.default}` }), // eslint-disable-next-line react-hooks/exhaustive-deps [coverColor, theme.palette.background.default] ) const isMobile = useMediaQuery('(max-height: 600px) or (max-width: 600px)') const [currentTab, setCurrentTab] = useState(0) return ( updateAudioViewIsShow(!audioViewIsShow)}> { !isMobile && updatePlayQueueIsShow(true)} className='app-region-no-drag' > } {!isMobile && } { !isMobile && updateLyricsIsShow(!lyricsIsShow)} className='app-region-no-drag' > } handleClickFullscreen()} className='app-region-no-drag' > { fullscreen ? : } {/* 封面 */} Cover {/* 歌词 */} { ((!isMobile && lyricsIsShow) || (isMobile && currentTab === 1)) && { currentMetaData && currentMetaData.lyrics ? :
{t`No lyrics`}
}
} {/* 播放控制 */} { (!isMobile || (isMobile && currentTab === 0)) && {(!playQueue || !currentMetaData) ? 'Not playing' : currentMetaData.title} {(playQueue && currentMetaData) ? currentMetaData.artist : ''} {(playQueue && currentMetaData) ? currentMetaData.album : ''} handleTimeRangeonChange(current)} sx={{ width: '100%', height: '0.25rem', }} /> {timeShift(currentTime)} {timeShift((duration) ? duration : 0)} handleClickShuffle()}> handleClickPrev()} > handleClickSeekbackward(10)} > { (!isLoading && player?.paused) && handleClickPlay()}> } { (!isLoading && !player?.paused) && handleClickPause()}> } { isLoading && } handleClickSeekforward(10)} > handleClickRepeat()} > { (repeat === 'one') ? : } } { isMobile && setCurrentTab(newValue)} aria-label="player-tab" sx={{ '& .MuiTab-root': { padding: 0, minWidth: '3rem' } }} > } aria-label="play" /> } aria-label="lyrics" /> updatePlayQueueIsShow(true)} className='app-region-no-drag' > }
) } export default Modern ================================================ FILE: src/pages/Player/PlayQueue.tsx ================================================ import { Box, Button, Drawer, useTheme } from '@mui/material' import KeyboardArrowRightRoundedIcon from '@mui/icons-material/KeyboardArrowRightRounded' import usePlayQueueStore from '@/store/usePlayQueueStore' import useUiStore from '@/store/useUiStore' import CommonList from '@/components/CommonList/CommonList' import usePlayerStore from '@/store/usePlayerStore' import { useShallow } from 'zustand/shallow' import useStyles from '@/hooks/ui/useStyles' const PlayQueue = () => { const theme = useTheme() const styles = useStyles(theme) const playQueue = usePlayQueueStore.use.playQueue() const currentIndex = usePlayQueueStore.use.currentIndex() const updateCurrentIndex = usePlayQueueStore.use.updateCurrentIndex() const updatePlayQueue = usePlayQueueStore.use.updatePlayQueue() const [ playQueueIsShow, updatePlayQueueIsShow ] = useUiStore( useShallow( (state) => [ state.playQueueIsShow, state.updatePlayQueueIsShow, ] ) ) const updateAutoPlay = usePlayerStore(state => state.updateAutoPlay) const open = (index: number) => { if (playQueue) { updateAutoPlay(true) updateCurrentIndex(playQueue[index].index) } } const remove = (indexArray: number[]) => updatePlayQueue(playQueue?.filter(item => !indexArray.map(index => playQueue[index].index).filter(index => index !== currentIndex).includes(item.index)) || []) return ( updatePlayQueueIsShow(false)} sx={{ '& .MuiDrawer-paper': { width: { xs: 'calc(100vw - 0.5rem)', sm: '400px' } }, ...styles.scrollbar }} > { playQueue && item.index === currentIndex)} scrollIndex={playQueue?.findIndex((item) => item.index === currentIndex)} func={{ open, remove }} /> } ) } export default PlayQueue ================================================ FILE: src/pages/Player/Player.tsx ================================================ import { useRef } from 'react' import { Box } from '@mui/material' import useUiStore from '@/store/useUiStore' import useMediaSession from '@/hooks/player/useMediaSession' import usePlayerCore from '@/hooks/player/usePlayerCore' import VideoPlayer from './VideoPlayer' import Audio from './Audio/Audio' import PlayerControl from './PlayerControl' import PlayQueue from './PlayQueue' import VideoPlayerTopbar from './VideoPlayerTopbar' const Player = () => { const controlIsShow = useUiStore((state) => state.controlIsShow) const playerRef = useRef(null) const player = playerRef.current // 声明播放器对象 const { url, onEnded } = usePlayerCore(player) // 向 mediaSession 发送当前播放进度 useMediaSession(player) return ( <>