Repository: widcardw/D4nm4ku Branch: main Commit: e71d34b43972 Files: 98 Total size: 169.4 KB Directory structure: gitextract_u13ohgz1/ ├── .eslintignore ├── .eslintrc ├── .github/ │ └── workflows/ │ └── release.yml ├── .gitignore ├── .vscode/ │ ├── extensions.json │ └── settings.json ├── LICENSE ├── README.md ├── index.html ├── package.json ├── src/ │ ├── App.vue │ ├── components/ │ │ ├── DarkMode.vue │ │ ├── SideBar.vue │ │ ├── UWidget.vue │ │ ├── danmaku/ │ │ │ ├── UDanmaku.vue │ │ │ ├── UGift.vue │ │ │ ├── UGuardTag.vue │ │ │ ├── UInteraction.vue │ │ │ ├── URenderer.vue │ │ │ └── UWatch.vue │ │ ├── img/ │ │ │ ├── Avatar.vue │ │ │ ├── MyImg.vue │ │ │ └── MyQrCode.vue │ │ ├── send/ │ │ │ └── UMessageSender.vue │ │ ├── settings/ │ │ │ └── Login.vue │ │ ├── superchat/ │ │ │ ├── UScDanmaku.vue │ │ │ ├── USuperChatFloat.vue │ │ │ ├── USuperChatPool.vue │ │ │ └── USuperChatTag.vue │ │ └── ui/ │ │ ├── UBlackList.vue │ │ ├── UCheckBox.vue │ │ ├── UColorPicker.vue │ │ ├── UInputBtn.vue │ │ ├── UMdInput.vue │ │ ├── UMessageProvider.vue │ │ ├── UMultiList.vue │ │ ├── URadio.vue │ │ ├── USelector.vue │ │ ├── USettingsBox.vue │ │ ├── USlider.vue │ │ ├── USwitch.vue │ │ ├── UTabSelector.vue │ │ └── UTag.vue │ ├── composables/ │ │ ├── api.ts │ │ ├── autoSendMsg.ts │ │ ├── components.ts │ │ ├── dark.ts │ │ ├── data.ts │ │ ├── eventEmitter.ts │ │ ├── fetchImgFromBackend.ts │ │ ├── getAvatar.ts │ │ ├── getCookies.ts │ │ ├── getInfoFromUid.ts │ │ ├── getLastMatchedGift.ts │ │ ├── getLiverInfo.ts │ │ ├── injectionKeys.ts │ │ ├── load_pos.ts │ │ ├── loginLoop.ts │ │ ├── logout.ts │ │ ├── msgSend.ts │ │ ├── openLive.ts │ │ ├── parseFanNumbers.ts │ │ ├── priceToSeconds.ts │ │ ├── randomColor.ts │ │ ├── server.ts │ │ ├── shortIdToLong.ts │ │ ├── tooLongSymbols.ts │ │ └── types.ts │ ├── layouts/ │ │ ├── default.vue │ │ └── none.vue │ ├── main.ts │ ├── pages/ │ │ ├── index.vue │ │ ├── live.vue │ │ ├── sender.vue │ │ ├── settings.vue │ │ └── show.vue │ ├── stores/ │ │ ├── index.ts │ │ ├── position.ts │ │ └── store.ts │ ├── styles/ │ │ └── main.css │ ├── types.ts │ └── vite-env.d.ts ├── src-tauri/ │ ├── .gitignore │ ├── Cargo.toml │ ├── build.rs │ ├── icons/ │ │ └── icon.icns │ ├── src/ │ │ ├── fetch_img.rs │ │ ├── load_local_img.rs │ │ ├── main.rs │ │ ├── new_sender.rs │ │ ├── new_view.rs │ │ ├── open_app_dir.rs │ │ └── send_msg.rs │ └── tauri.conf.json ├── tsconfig.json ├── tsconfig.node.json ├── unocss.config.ts └── vite.config.ts ================================================ FILE CONTENTS ================================================ ================================================ FILE: .eslintignore ================================================ dist public src-tauri .vscode .github ================================================ FILE: .eslintrc ================================================ { "extends": "@antfu" } ================================================ FILE: .github/workflows/release.yml ================================================ # 可选,将显示在 GitHub 存储库的“操作”选项卡中的工作流名称 name: Release CI # 指定此工作流的触发器 on: push: # 匹配特定标签 (refs/tags) tags: - 'v*' # 推送事件匹配 v*, 例如 v1.0,v20.15.10 等来触发工作流 # 需要运行的作业组合 jobs: # 任务:创建 release 版本 create-release: runs-on: ubuntu-latest outputs: RELEASE_UPLOAD_ID: ${{ steps.create_release.outputs.id }} steps: - uses: actions/checkout@v2 # 查询版本号(tag) - name: Query version number id: get_version shell: bash run: | echo "using version tag ${GITHUB_REF:10}" echo ::set-output name=version::"${GITHUB_REF:10}" # 根据查询到的版本号创建 release - name: Create Release id: create_release uses: actions/create-release@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: tag_name: '${{ steps.get_version.outputs.VERSION }}' release_name: 'app ${{ steps.get_version.outputs.VERSION }}' body: 'See the assets to download this version and install.' # 编译 Tauri build-tauri: needs: create-release strategy: fail-fast: false matrix: platform: [macos-latest, ubuntu-latest, windows-latest] runs-on: ${{ matrix.platform }} steps: - name: Checkout uses: actions/checkout@v3 - name: Install Node.js uses: actions/setup-node@v3 with: node-version: 16 - name: install dependencies (ubuntu only) if: matrix.platform == 'ubuntu-latest' run: | sudo apt-get update sudo apt-get install -y libgtk-3-dev webkit2gtk-4.0 libappindicator3-dev librsvg2-dev patchelf - uses: pnpm/action-setup@v2.0.1 name: Install pnpm id: pnpm-install with: version: 7 run_install: false - name: Get pnpm store directory id: pnpm-cache run: | echo "::set-output name=pnpm_cache_dir::$(pnpm store path)" - uses: actions/cache@v3 name: Setup pnpm cache with: path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }} key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} restore-keys: | ${{ runner.os }}-pnpm-store- - name: install Rust stable uses: actions-rs/toolchain@v1 with: toolchain: stable - name: Install dependencies and build run: pnpm install && pnpm build - uses: tauri-apps/tauri-action@v0 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: tagName: v__VERSION__ # the action automatically replaces \_\_VERSION\_\_ with the app version releaseName: "App v__VERSION__" releaseBody: "See the assets to download this version and install." releaseDraft: true prerelease: false ================================================ 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 !.vscode/settings.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? *.sublime-workspace # auto import src/auto-imports.d.ts src/components.d.ts ================================================ FILE: .vscode/extensions.json ================================================ { "recommendations": ["Vue.volar"] } ================================================ FILE: .vscode/settings.json ================================================ { "editor.codeActionsOnSave": { "source.fixAll.eslint": true }, "files.associations": { "*.css": "postcss" }, "editor.formatOnSave": false } ================================================ 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: README.md ================================================ # D4nm4ku ![](https://img.shields.io/github/workflow/status/widcardw/D4nm4ku/Release%20CI) ![](https://img.shields.io/github/downloads/widcardw/D4nm4ku/total) 使用 Tauri 和 Vue 实现一个弹幕姬。 > 后续会考虑使用 rust 作为后端来接收弹幕,而前端仅做数据的显示。目前时间和精力不是很足,因此暂时先搁置。 ## 下载 APP 至 [release](https://github.com/widcardw/D4nm4ku/releases) 页面下载 | Platform | Installer | |:--------:|:-------:| | Windows | D4nm4ku_version_x64_en-US.msi | | macOS Apple Silicon | D4nm4ku_version_aarch64.dmg | | macOS Intel x64 | D4nm4ku_version_x64.dmg | | Linux | d4nm4ku_version_amd64.deb
d4nm4ku_version_amd64.AppImage | ## 构建 ```sh pnpm install pnpm tauri dev # dev pnpm tauri build # build ``` ## 功能预想 ### 弹幕部分 #### 弹幕 - [x] 主要:用户头像,用户名,弹幕内容,礼物,人气 - [ ] 可选: - [x] 用户等级 - [x] 谁的舰长 - [ ] 是否为粉丝 - [x] 入场 - [x] 关注主播 #### 主播回复 - [x] 主动输入回复 - [x] 关键字触发回复 - [x] 使用队列存储 - 好像用不着了? - [x] 通过关键字 Hash ,不再回复一段时间内已经重复的内容(设置回复内容的 TTL ) - [x] 过长的弹幕需要分段延迟回复 #### 扩展功能 - [x] 醒目留言 - [x] 可选:是否只显示付费礼物,礼物金额,礼物连击(可能稍微有一点问题,或许还是在队列里面写) - [ ] 可选:语音播报(感谢 xxx 的礼物,关注主播,等等) - [ ] 弹幕投票 ### 其他 - [x] 优化登录界面 - [ ] 不知道有没有自动验证的 API ,这样登录一次就不用再次登录了 - 好像是定时失效的吧,这就不管了,能用就行 - [x] 将弹幕窗口化 - [x] 添加配置 - [x] 窗口背景色 - [x] 窗口透明度 - [x] 弹幕文字颜色 - [x] 舰长加背景色(或者文字颜色) - [x] 可隐藏头像 - [x] 可隐藏时间 - [ ] 粉丝加背景色 - [ ] 考虑要不要加原生 API 的毛玻璃效果 - 来自 tauri 的 API [`run_on_main_thread`](https://docs.rs/tauri/1.1.1/tauri/struct.AppHandle.html#method.run_on_main_thread) 和插件 [window-vibrancy](https://docs.rs/window-vibrancy/0.3.0/window_vibrancy/) 可以实现原生的毛玻璃效果 - [ ] 优化界面 - [x] 考虑是否将启动小窗的界面合并到主界面 - 但是之前测试根目录组件使用带有 store 的组件会报错,说 pinia 未定义 - [ ] 设置界面 - 或许还要加一些功能 - [x] 开播 - [x] 更改直播间标题 - [x] 开播 - [ ] 窗口 - [x] 置顶 - [x] 保存和加载窗口的位置和大小 - [ ] 点击穿透(在 [tao](https://docs.rs/tao/0.14.0/tao/) 的 [API](https://docs.rs/tao/0.14.0/tao/window/struct.Window.html#method.set_ignore_cursor_events) 中已经有了,但是没有开放到 tauri 中) - [ ] tauri 的 [issue](https://github.com/tauri-apps/tao/issues/184#issuecomment-1097109451) 中说要到 v2 时候才会正式公开这个 api - [x] [#184-comment1](https://github.com/tauri-apps/tao/issues/184#issuecomment-1134823892) 给出了 macOS 的解决方案 - [ ] [#184-comment2](https://github.com/tauri-apps/tao/issues/184#issuecomment-1118176176) 给出了 Windows 的解决方案 - [ ] 将弹幕浏览器显示到所有桌面 (macOS) 详见 [#1](https://github.com/widcardw/D4nm4ku/issues/1) ## 部分效果呈现 ### 基本功能 ![basic](./imgs/basic.png) ### 自动回复 ![auto-reply](./imgs/auto-reply.png) ### 开启直播 ![start-live](./imgs/start-live.png) ================================================ FILE: index.html ================================================ Vite + Vue + TS
================================================ FILE: package.json ================================================ { "name": "D4nm4ku", "type": "module", "version": "0.0.0", "private": true, "scripts": { "dev": "vite", "build": "vue-tsc --noEmit && vite build", "preview": "vite preview", "tauri": "tauri", "lint": "eslint ." }, "dependencies": { "@tauri-apps/api": "^1.0.2", "@vueuse/core": "^8.9.4", "@vueuse/integrations": "^9.0.2", "pinia": "^2.0.16", "vue": "^3.2.37", "vue-router": "^4.1.2" }, "devDependencies": { "@antfu/eslint-config": "^0.25.2", "@iconify-json/ri": "^1.1.3", "@tauri-apps/cli": "^1.0.4", "@types/node": "^18.0.6", "@types/qrcode": "^1.4.2", "@unocss/preset-icons": "^0.44.5", "@unocss/reset": "^0.44.5", "@vitejs/plugin-vue": "^3.0.0", "bilibili-live-ws": "^6.2.1", "buffer": "^6.0.3", "eslint": "^8.20.0", "events": "^3.3.0", "pako": "^2.0.4", "qrcode": "^1.5.1", "typescript": "^4.6.4", "unocss": "^0.44.5", "vite": "^3.0.0", "vite-plugin-pages": "^0.25.0", "vite-plugin-vue-layouts": "^0.6.0", "vue-tsc": "^0.38.4" } } ================================================ FILE: src/App.vue ================================================ ================================================ FILE: src/components/DarkMode.vue ================================================ ================================================ FILE: src/components/SideBar.vue ================================================ ================================================ FILE: src/components/UWidget.vue ================================================ ================================================ FILE: src/components/danmaku/UDanmaku.vue ================================================ ================================================ FILE: src/components/danmaku/UGift.vue ================================================ ================================================ FILE: src/components/danmaku/UGuardTag.vue ================================================ ================================================ FILE: src/components/danmaku/UInteraction.vue ================================================ ================================================ FILE: src/components/danmaku/URenderer.vue ================================================ ================================================ FILE: src/components/danmaku/UWatch.vue ================================================ ================================================ FILE: src/components/img/Avatar.vue ================================================ ================================================ FILE: src/components/img/MyImg.vue ================================================ ================================================ FILE: src/components/img/MyQrCode.vue ================================================ ================================================ FILE: src/components/send/UMessageSender.vue ================================================ ================================================ FILE: src/components/settings/Login.vue ================================================ ================================================ FILE: src/components/superchat/UScDanmaku.vue ================================================ ================================================ FILE: src/components/superchat/USuperChatFloat.vue ================================================ ================================================ FILE: src/components/superchat/USuperChatPool.vue ================================================ ================================================ FILE: src/components/superchat/USuperChatTag.vue ================================================ ================================================ FILE: src/components/ui/UBlackList.vue ================================================ ================================================ FILE: src/components/ui/UCheckBox.vue ================================================ ================================================ FILE: src/components/ui/UColorPicker.vue ================================================ ================================================ FILE: src/components/ui/UInputBtn.vue ================================================ ================================================ FILE: src/components/ui/UMdInput.vue ================================================ ================================================ FILE: src/components/ui/UMessageProvider.vue ================================================ ================================================ FILE: src/components/ui/UMultiList.vue ================================================ ================================================ FILE: src/components/ui/URadio.vue ================================================ ================================================ FILE: src/components/ui/USelector.vue ================================================ ================================================ FILE: src/components/ui/USettingsBox.vue ================================================ ================================================ FILE: src/components/ui/USlider.vue ================================================ ================================================ FILE: src/components/ui/USwitch.vue ================================================ ================================================ FILE: src/components/ui/UTabSelector.vue ================================================ ================================================ FILE: src/components/ui/UTag.vue ================================================ ================================================ FILE: src/composables/api.ts ================================================ const spaceInfo = 'https://api.bilibili.com/x/space/app/index?mid=' const cardInfo = 'http://api.bilibili.com/x/web-interface/card?mid=' const giftInfo = 'https://api.live.bilibili.com/xlive/web-room/v1/giftPanel/giftConfig?platform=pc&room_id=' const roomInfo = 'https://api.live.bilibili.com/room/v1/Room/get_info?id=' const qrcodeGet = 'http://passport.bilibili.com/qrcode/getLoginUrl' const qrcodeLogin = 'http://passport.bilibili.com/qrcode/getLoginInfo' const danmakuSend = 'https://api.live.bilibili.com/msg/send' const logOutApi = 'http://passport.bilibili.com/login/exit/v2' const liveAreaInfoListApi = 'http://api.live.bilibili.com/room/v1/Area/getList' const startLiveApi = 'http://api.live.bilibili.com/room/v1/Room/startLive' const stopLiveApi = 'http://api.live.bilibili.com/room/v1/Room/stopLive' const updateLiveTitleApi = 'http://api.live.bilibili.com/room/v1/Room/update' const shortIdToLongApi = 'https://api.live.bilibili.com/room/v1/Room/mobileRoomInit?id=' const getRoomInfoOldApi = 'https://api.live.bilibili.com/room/v1/Room/getRoomInfoOld?mid=' export { spaceInfo, giftInfo, roomInfo, qrcodeGet, qrcodeLogin, cardInfo, danmakuSend, logOutApi, liveAreaInfoListApi, stopLiveApi, startLiveApi, updateLiveTitleApi, shortIdToLongApi, getRoomInfoOldApi, } ================================================ FILE: src/composables/autoSendMsg.ts ================================================ import { sendMsg } from './msgSend' import { useStore } from '~/stores/store' interface Answer { ts: number keywords: string[] answer: string } const store = useStore() function addFAQ(ans: Omit) { store.faqs.push({ ...ans, ts: Date.now(), }) } function removeFAQ(index: number) { store.faqs.splice(index, 1) } const sentQueue: number[] = [] function enqueueAnswerTs(ts: number) { sentQueue.push(ts) setTimeout(() => { sentQueue.shift() }, 30000) } function autoSendByIndex(index: number) { // 已经发过的暂时不发 if (sentQueue.find(it => it === store.getFaqs[index].ts)) return enqueueAnswerTs(store.getFaqs[index].ts) try { sendMsg(store.getFaqs[index].answer) // // eslint-disable-next-line no-console // console.log(store.getFaqs[index].answer) } catch (e: any) { throw new Error(e.toString()) } } function autoSendByWord(word: string) { for (const [index, faq] of store.getFaqs.entries()) { for (const kw of faq.keywords) { if (word.includes(kw)) { autoSendByIndex(index) return } } } } export { addFAQ, removeFAQ, autoSendByWord, } export type { Answer, } ================================================ FILE: src/composables/components.ts ================================================ interface DanmakuProps { type: 'text' content: string uname: string color: string tagColor: number fang: number level: number label: string perhapsGuard: 0 | 1 | 2 | 3 ts: number uid: number } function isDanmakuProps(obj: any): obj is DanmakuProps { return obj !== undefined && obj.type === 'text' } interface GiftProps { type: 'gift' uname: string action: string num: number face: string coinType: 'gold' | 'silver' giftId: number giftName: string price: number ts: number uid: number blindGift: null | { blind_gift_config_id: number from: number gift_action: string original_gift_id: string original_gift_name: string } bgColor: string } function isGiftProps(obj: any): obj is GiftProps { return obj !== undefined && obj.type === 'gift' } type PropsType = 'text' | 'gift' interface SuperChatProps { type: 'superchat' uname: string content: string contentJpn: string face: string price: number ts: number uid: number bgBottomColor: string bgColor: string second: number } function isSuperChatProps(obj: any): obj is SuperChatProps { return obj !== undefined && obj.type === 'superchat' } interface GuardBuyProps { type: 'guard_buy' uname: string face: string uid: number guardLevel: number num: number price: number ts: number } function isGuardBuyProps(obj: any): obj is GuardBuyProps { return obj !== undefined && obj.type === 'guard_buy' } interface InteractProps { type: 'interact' uname: string uid: number unameColor: string ts: number action: 1 | 2 } function isInteractProps(obj: any): obj is InteractProps { return obj !== undefined && obj.type === 'interact' } export type { DanmakuProps, GiftProps, PropsType, GuardBuyProps, SuperChatProps, InteractProps, } export { isDanmakuProps, isGiftProps, isSuperChatProps, isGuardBuyProps, isInteractProps, } ================================================ FILE: src/composables/dark.ts ================================================ import { useDark, usePreferredDark, useToggle } from '@vueuse/core' // these APIs are auto-imported from @vueuse/core export const isDark = useDark() export const toggleDark = useToggle(isDark) export const preferredDark = usePreferredDark() ================================================ FILE: src/composables/data.ts ================================================ const guardType = { 1: { type: 'member', bgColor: '#fae4ab', bgBottomColor: '#e3704d', second: 60, badge: 'https://i0.hdslb.com/bfs/activity-plat/static/20200716/1d0c5a1b042efb59f46d4ba1286c6727/icon-guard1.png@44w_44h.webp', }, 2: { type: 'member', bgColor: '#d5ccef', bgBottomColor: '#633382', second: 300, badge: 'https://i0.hdslb.com/bfs/activity-plat/static/20200716/1d0c5a1b042efb59f46d4ba1286c6727/icon-guard2.png@44w_44h.webp', }, 3: { type: 'member', bgColor: '#e5faff', bgBottomColor: '#657eaa', second: 1800, badge: 'https://i0.hdslb.com/bfs/activity-plat/static/20200716/1d0c5a1b042efb59f46d4ba1286c6727/icon-guard3.png@44w_44h.webp', }, } export { guardType, } ================================================ FILE: src/composables/eventEmitter.ts ================================================ import { WebviewWindow } from '@tauri-apps/api/window' export function eventEmitter(event: string, payload: any) { const showWindow = WebviewWindow.getByLabel('danmakuWidget') if (showWindow) showWindow.emit(event, payload) const senderWindow = WebviewWindow.getByLabel('senderWindow') if (senderWindow) senderWindow.emit(event, payload) } ================================================ FILE: src/composables/fetchImgFromBackend.ts ================================================ import { appDir, join } from '@tauri-apps/api/path' import { invoke } from '@tauri-apps/api/tauri' import { readBinaryFile } from '@tauri-apps/api/fs' import { useStore } from '~/stores/store' const store = useStore() async function getAbsolutePathFromUrl(url: string, fileName: string) { const dir = await appDir() const absolutePath = await join(dir, 'imgs', fileName) const realPath = await invoke('fetch_image', { imgUrl: url, filePath: absolutePath, }) as string return realPath } async function abPath2Blob(path: string) { const imgContent = await readBinaryFile(path) const blob = URL.createObjectURL(new Blob([imgContent.buffer])) return blob } async function processImgUrl2(imgUrl: string, uid?: number) { let fileName: string // 如果是头像 if (uid) { // 文件名 fileName = `avatar_${uid}` } else { // 从 url 截取图片名和路径 const splits = imgUrl.split('/') fileName = splits[splits.length - 1] } // 在 store 中查找是否存在该图片 const found = store.mediaList.find(it => it.fileName === fileName) // 找到了直接返回 blob 链接 if (found) { // // eslint-disable-next-line no-console // console.log('fetch: store', fileName) return { name: fileName, blob: found.blob } } // // eslint-disable-next-line no-console // console.log('fetch: through backend', fileName) // 调用后端,获取头像绝对路径 const absolutePath = await getAbsolutePathFromUrl(imgUrl, fileName) // 读取头像并转为 blob 链接 const blob = await abPath2Blob(absolutePath) // const blob = convertFileSrc(absolutePath) // 存入 cache if (!store.mediaList.find(it => it.fileName === fileName)) store.mediaList.push({ fileName, blob }) return { name: fileName, blob } } export { processImgUrl2, abPath2Blob, } ================================================ FILE: src/composables/getAvatar.ts ================================================ import { invoke } from '@tauri-apps/api/tauri' import { appDir, join } from '@tauri-apps/api/path' import { getCardInfo, getSpaceInfo } from './getInfoFromUid' import type { CardInfoResponse, SpaceApiResponse } from './types' import { abPath2Blob } from './fetchImgFromBackend' import { useStore } from '~/stores/store' const store = useStore() const MAX_REQUEST_BLOCK_TIMES = 10 // https://api.bilibili.com/x/space/app/index?mid=${uid} // https://api.bilibili.com/x/space/acc/info?mid=${uid} async function getAvatar2(uid: number): Promise<{ url: string; isBlob: boolean }> { const found = store.mediaList.find(it => it.fileName === `avatar_${uid}`) if (found) { // // eslint-disable-next-line no-console // console.log('getAvatar: store', uid) return { isBlob: true, url: found.blob } } const dir = await appDir() const localPath = await join(dir, 'imgs', `avatar_${uid}`) const res = await invoke('load_local_image', { uidPath: localPath }) as string if (res.trim() !== '') { // // eslint-disable-next-line no-console // console.log('getAvatar: local', uid) const blob = await abPath2Blob(res) store.mediaList.push({ fileName: `avatar_${uid}`, blob }) return { url: blob, isBlob: true } } if (store.requestBlockedTimes >= MAX_REQUEST_BLOCK_TIMES) return { isBlob: false, url: '' } // // eslint-disable-next-line no-console // console.log('getAvatar: request img url', uid) const responseData = await getCardInfo(uid) as CardInfoResponse if (responseData.code === 0) { const url = `${responseData.data.card.face}@96w_96h` return { url, isBlob: false } } const responseData2 = await getSpaceInfo(uid) as SpaceApiResponse if (responseData2.code === 0) { const url = `${responseData2.data.info.face}@96w_96h` return { url, isBlob: false } } store.requestBlockedTimes++ // // eslint-disable-next-line no-console // console.log(store.requestBlockedTimes) if (store.requestBlockedTimes === MAX_REQUEST_BLOCK_TIMES) throw new Error('头像获取失败!请考虑关闭头像!') return { isBlob: false, url: '' } } export { getAvatar2 } ================================================ FILE: src/composables/getCookies.ts ================================================ import { useStore } from '~/stores/store' const store = useStore() export default function getCookies() { if (!store.getUserInfo.mid) return '' let cookies = '' cookies += `sid=${store.getUserInfo.sid}; ` cookies += `DedeUserID=${store.getUserInfo.mid}; ` cookies += `DedeUserID__ckMd5=${store.getUserInfo.midmd5}; ` cookies += `SESSDATA=${store.getUserInfo.sessdata}; ` cookies += `bili_jct=${store.getUserInfo.bili_jct}` return cookies } ================================================ FILE: src/composables/getInfoFromUid.ts ================================================ import { fetch } from '@tauri-apps/api/http' import { cardInfo, spaceInfo } from './api' import type { CardInfoResponse, SpaceApiResponse } from './types' async function getSpaceInfo(uid: number) { const response = await fetch(`${spaceInfo}${uid}`, { method: 'GET', timeout: 5000, }) return response.data as SpaceApiResponse } async function getCardInfo(uid: number) { const response = await fetch(`${cardInfo}${uid}`, { method: 'GET', timeout: 5000, }) return response.data as CardInfoResponse } export { getSpaceInfo, getCardInfo, } ================================================ FILE: src/composables/getLastMatchedGift.ts ================================================ import type { GiftProps } from '~/composables/components' const getLastMatchedGift = ( danmakuPool: Array, uname: string, giftId: number, ts: number, num: number, ): boolean => { for (let i = danmakuPool.length - 1; i >= 0; i--) { if (danmakuPool[i].type !== 'gift') continue const item = danmakuPool[i] as GiftProps if (item.uname === uname && item.giftId === giftId) { const item = danmakuPool.splice(i, 1) as GiftProps[] item[0].num += num // item[0].ts = ts danmakuPool.push(item[0]) return true } } return false } export default getLastMatchedGift ================================================ FILE: src/composables/getLiverInfo.ts ================================================ import { fetch } from '@tauri-apps/api/http' import { getRoomInfoOldApi, roomInfo } from './api' import { getCardInfo, getSpaceInfo } from './getInfoFromUid' import { useStore } from '~/stores/store' const store = useStore() async function getLiveRoomInfoFromRoomId(roomId: number) { const data = (await fetch(`${roomInfo}${roomId}`, { method: 'GET', timeout: 5000, })).data as { data: { uid: number live_status: 0 | 1 | 2 room_id: number area_id: number } } return data } async function getLiverInfo(roomId: number) { const data = await getLiveRoomInfoFromRoomId(roomId) // console.log(data, data.data.uid) store.liverId = data.data.uid const data2 = await getCardInfo(data.data.uid) as any if (data2.code !== 0) throw new Error('主播信息获取失败!') const fansNumber = data2.data.follower // console.log(fansNumber) return fansNumber as number } async function getLiveRoomInfoFromUid(uid: number) { const spaceData = await getSpaceInfo(uid) return { roomid: spaceData.data.info.live.roomid, title: spaceData.data.info.live.title, } } async function getLiveStatusFromUid(uid: number) { const data = (await fetch(`${getRoomInfoOldApi}${uid}`, { method: 'GET', timeout: 5000, })).data as any const liveStatus = data.data.liveStatus as number return liveStatus } export { getLiverInfo, getLiveRoomInfoFromUid, getLiveRoomInfoFromRoomId, getLiveStatusFromUid, } ================================================ FILE: src/composables/injectionKeys.ts ================================================ import type { InjectionKey, Ref } from 'vue' import type UMessageProvider from '~/components/ui/UMessageProvider.vue' export const msgKey: InjectionKey> = Symbol('') ================================================ FILE: src/composables/load_pos.ts ================================================ import { invoke } from '@tauri-apps/api/tauri' import type { PositionConfig } from '~/stores/position' async function loadPos(conf: PositionConfig) { const res = await invoke('set_viewer_pos_and_size', { conf }) return res } export { loadPos, } ================================================ FILE: src/composables/loginLoop.ts ================================================ import { Body, fetch } from '@tauri-apps/api/http' import { ref } from 'vue' import { qrcodeLogin } from './api' import { getCardInfo } from './getInfoFromUid' import { useStore } from '~/stores/store' const store = useStore() const getUrlParams = (url: string) => { const purl = new URL(url) const paramsStr = purl.search.slice(1) const params = new URLSearchParams(paramsStr) return { DedeUserID: Number.parseInt(params.get('DedeUserID') || ''), DedeUserID__ckMd5: params.get('DedeUserID__ckMd5') || '', SESSDATA: params.get('SESSDATA') || '', bili_jct: params.get('bili_jct') || '', Expires: Number.parseInt(params.get('Expires') || ''), sid: params.get('sid') || '', } } const interval = ref() const clearLoop = () => { if (interval.value) { clearInterval(interval.value) interval.value = undefined } } async function createLoginLoop(oauthKey: string): Promise { return new Promise((resolve) => { interval.value = setInterval(async () => { const response = await fetch(qrcodeLogin, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: Body.form({ oauthKey }), }) const { data: loginResponse, rawHeaders }: { data: { data: -1 | -2 | -4 | -5 | { url: string } message: string } headers: any rawHeaders: { 'set-cookie': string[] } } = response as any if (typeof loginResponse.data === 'object') { clearLoop() const params = getUrlParams(loginResponse.data.url) const fullUserInfo = await getCardInfo(params.DedeUserID) as any store.userInfo = { oauthKey, mid: params.DedeUserID, midmd5: params.DedeUserID__ckMd5, bili_jct: params.bili_jct, expires: params.Expires, sessdata: params.SESSDATA, sid: params.sid === '' ? rawHeaders['set-cookie'][0].split(';')[0].split('=')[1] : params.sid, mname: fullUserInfo.data.card.name, avatarUrl: fullUserInfo.data.card.face, lastLogin: new Date().getTime(), } store.storeUserInfo() // console.log(headers, rawHeaders) resolve(true) } // eslint-disable-next-line no-console console.log('待确认', loginResponse) }, 3000) }) } export { interval, createLoginLoop, clearLoop, } ================================================ FILE: src/composables/logout.ts ================================================ import { Body, fetch } from '@tauri-apps/api/http' import getCookies from './getCookies' import { logOutApi } from './api' import { useStore } from '~/stores/store' const store = useStore() const cookies = getCookies() const form = Body.form({ biliCSRF: store.getUserInfo.bili_jct, }) export default async function logout() { if (cookies === '') throw new Error('尚未登录') const response = await fetch(logOutApi, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'cookie': cookies, }, body: form, }) // eslint-disable-next-line no-console console.log(response.data) return response.data } ================================================ FILE: src/composables/msgSend.ts ================================================ import { invoke } from '@tauri-apps/api/tauri' import getCookies from './getCookies' import { useStore } from '~/stores/store' const store = useStore() const roomId = store.getRoomId const cookie = getCookies() function sendSingleMsg(msg: string) { const payload = { msg, cookie, roomid: roomId, csrf: store.getUserInfo.bili_jct, } invoke('send_message', payload) .then(() => { // eslint-disable-next-line no-console console.log('发送成功') }) .catch((err: string) => { throw new Error(err) }) } function sendMsg(msg: string) { if (cookie === '') throw new Error('尚未登录') for (let i = 0; i * 20 < msg.length; i++) { const partial = msg.substring(i * 20, i * 20 + 20) setTimeout(() => { sendSingleMsg(partial) }, i * 1500) } } export { sendMsg, } ================================================ FILE: src/composables/openLive.ts ================================================ import { Body, fetch } from '@tauri-apps/api/http' import { useStorage } from '@vueuse/core' import { liveAreaInfoListApi, startLiveApi, stopLiveApi, updateLiveTitleApi } from './api' import type { LiveAreaInfo, StartLiveResponse } from './types' import getCookies from './getCookies' import { useStore } from '~/stores/store' const store = useStore() const selectedArea = useStorage('selectedArea', '') const cookie = getCookies() async function getAreaInfoList() { if (store.liveConfig.liveAreaList.length > 0) return const { data } = await fetch(liveAreaInfoListApi) store.liveConfig.liveAreaList = (data as any).data as LiveAreaInfo[] } async function updateLiveTitle(roomId: string, title: string) { if (cookie === '') throw new Error('尚未登录') const { data } = await fetch(updateLiveTitleApi, { method: 'POST', headers: { cookie, 'content-type': 'application/x-www-form-urlencoded', }, body: Body.form({ room_id: roomId, title, csrf: store.getUserInfo.bili_jct, }), }) as any if (data.code !== 0) throw new Error('标题更新失败') } async function startLive(roomId: string, area_v2: number, platform: string) { const { data }: { data: StartLiveResponse } = await fetch(startLiveApi, { method: 'POST', headers: { cookie, 'content-type': 'application/x-www-form-urlencoded', }, body: Body.form({ room_id: roomId, area_v2: area_v2.toString(), platform, csrf: store.getUserInfo.bili_jct, }), }) // // eslint-disable-next-line no-console // console.log(data) if (data.code === 0) { // eslint-disable-next-line no-console console.log('直播开启成功') return data.data.rtmp } else { throw new Error(data.msg) } } async function stopLive(roomId: string) { const { data }: { data: { code: number; msg: string } } = await fetch(stopLiveApi, { method: 'POST', headers: { cookie, 'content-type': 'application/x-www-form-urlencoded', }, body: Body.form({ room_id: roomId, csrf: store.getUserInfo.bili_jct, }), }) // // eslint-disable-next-line no-console // console.log(data) if (data.code === 0) { // eslint-disable-next-line no-console console.log('直播关闭成功') } else { throw new Error(data.msg) } } export { getAreaInfoList, updateLiveTitle, selectedArea, startLive, stopLive, } ================================================ FILE: src/composables/parseFanNumbers.ts ================================================ export default function (num: number) { if (num >= 1e8) return `${(num / 1e8).toFixed(1)} 亿` if (num >= 10000) return `${(num / 10000).toFixed(1)} 万` return `${num}` } ================================================ FILE: src/composables/priceToSeconds.ts ================================================ function priceToSeconds(price: number) { if (price <= 2000) return 5 if (price <= 10000) return 10 if (price <= 30000) return 30 if (price <= 100000) return 60 if (price <= 300000) return 180 return 300 } export { priceToSeconds, } ================================================ FILE: src/composables/randomColor.ts ================================================ function hslToRgb(h: number, s: number, l: number) { s /= 100 l /= 100 const k = (n: number) => (n + h / 30) % 12 const a = s * Math.min(l, 1 - l) const f = (n: number) => l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1))) return [255 * f(0), 255 * f(8), 255 * f(4)].map(Math.round) } function randomColor() { const colorAngle = Math.floor(Math.random() * 360) const [r, g, b] = hslToRgb(colorAngle, 60, 50) return `rgb(${r}, ${g}, ${b})` } function rgbToHex(r: number, g: number, b: number) { let res = '#' res += (r < 16 ? '0' : '') + r.toString(16) res += (g < 16 ? '0' : '') + g.toString(16) res += (b < 16 ? '0' : '') + b.toString(16) return res } function randomColorPair() { const colorAngle = Math.floor(Math.random() * 280 + 80) const [r1, g1, b1] = hslToRgb(colorAngle, 60, 90) const topColor = rgbToHex(r1, g1, b1) const [r2, g2, b2] = hslToRgb(colorAngle, 70, 30) const bottomColor = rgbToHex(r2, g2, b2) return [topColor, bottomColor] } function rgbAppendAlpha(color: string) { return color.replace(/^(rgb)\((\d+, \d+, \d+)\)$/, (match, p1, p2) => `${p1}a(${p2}, 0.5)`) } function getLightnessFromHex(hex: string) { const [r, g, b] = hex.replace(/^#/, '').match(/../g)!.map(n => parseInt(n, 16)) return (r * 299 + g * 587 + b * 114) / 1000 } function getLightnessFromRgb(rgb: string) { const [r, g, b] = rgb.match(/\d+/g)!.map(n => parseInt(n, 10)) return (r * 299 + g * 587 + b * 114) / 1000 } function hex2rgb(hex: string, opacity: string) { const matches = hex.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i) as [string, string, string, string] return `rgba(${parseInt(matches[1], 16)}, ${parseInt(matches[2], 16)}, ${parseInt(matches[3], 16)}, ${parseInt(opacity) / 255})` } const LIGHTNESS_LIMIT = 120 export default randomColor export { rgbAppendAlpha, getLightnessFromHex, getLightnessFromRgb, randomColorPair, LIGHTNESS_LIMIT, hex2rgb, } ================================================ FILE: src/composables/server.ts ================================================ import { KeepLiveWS } from 'bilibili-live-ws' import { fetch } from '@tauri-apps/api/http' import { useStorage } from '@vueuse/core' import { ref } from 'vue' import type { DanmakuProps, GiftProps, InteractProps, SuperChatProps, } from './components' import type { DanmakuMessage, GiftInfo, GuardBuyMessage, InteractiveWordMessage, SendGiftMessage, SuperChatMessage, } from './types' import { giftInfo } from './api' import { autoSendByWord } from './autoSendMsg' import { guardType } from './data' import getLastMatchedGift from './getLastMatchedGift' import parseFanNumbers from './parseFanNumbers' import { randomColorPair } from './randomColor' import { priceToSeconds } from './priceToSeconds' import { processTooLongSymbols } from './tooLongSymbols' import { useStore } from '~/stores/store' const roomId = useStorage('roomId', '') const linked = ref(true) const store = useStore() const fans = ref('') const population = ref('') const danmakuPool = ref>([]) const selectedSc = ref(null) const chatPool = ref>([]) const enterQueue = ref([]) setInterval(() => { if (enterQueue.value.length >= 2) enterQueue.value.shift() }, 500) let live: KeepLiveWS | null = null const pushObject = (obj: DanmakuProps | GiftProps | SuperChatProps | InteractProps) => { danmakuPool.value.push(obj) if (danmakuPool.value.length > 100) danmakuPool.value.shift() } const pushChat = (chat: SuperChatProps) => { chatPool.value.push(chat) setTimeout(() => { chatPool.value = chatPool.value.filter(x => x.ts !== chat.ts) if (selectedSc.value?.ts === chat.ts) selectedSc.value = null }, chat.second * 1000) } const connectRoom = () => { try { live = new KeepLiveWS(Number.parseInt(roomId.value)) linked.value = true live.on('open', () => { // eslint-disable-next-line no-console console.log('WebSocket Open') fetch(`${giftInfo}${roomId.value}`) .then((response) => { store.giftInfoList = (response.data as any).data.list.map((it: any) => { return { id: it.id, webp: it.webp, } as GiftInfo }) }) }) // 结束连接 live.on('close', () => { // eslint-disable-next-line no-console console.log('WebSocket Close') }) live.on('heartbeat', (online: number) => { population.value = parseFanNumbers(online) }) // 好像这个 api 没用,或许是 bilibili-live-ws 没写进去 // 欢迎用户进入直播间的 api 好像也没用 // live.on('ROOM_REAL_TIME_MESSAGE_UPDATA', (data) => { // // eslint-disable-next-line no-console // console.log(data) // const { data: { fans_num } } = data // fans.value = parseFanNumbers(fans_num) // }) live.on('INTERACT_WORD', (data: InteractiveWordMessage) => { const { data: { msg_type, uname, uid, uname_color, trigger_time } } = data const interact: InteractProps = { type: 'interact', ts: trigger_time / 1000, uid, uname, unameColor: uname_color, action: msg_type, } if (store.getConfig.showEnter && msg_type === 1) { // 用户进入直播间 // pushObject(interact) enterQueue.value.push(interact) if (enterQueue.value.length > 20) enterQueue.value.splice(0, 15) } else if (store.getConfig.showSubscribe && msg_type === 2) { // 用户关注主播 pushObject(interact) } }) live.on('SEND_GIFT', (data: SendGiftMessage) => { const { data: { face, timestamp, coin_type, uname, giftName, num, giftId, action, total_coin, uid, blind_gift } } = data if (coin_type === 'silver' && !store.getConfig.showSilverGift) return if (!store.getConfig.showGoldGift) return const [bgColor, bgBottomColor] = randomColorPair() if (danmakuPool.value.length > 0) { if (getLastMatchedGift(danmakuPool.value, uname, giftId, timestamp, num)) return } const gift: GiftProps = { type: 'gift', uname, action, num, coinType: coin_type, face: `${face}@96w_96h`, giftId, giftName, price: total_coin, // 实际价格 * 1000 ts: timestamp, uid, blindGift: blind_gift, bgColor: bgBottomColor, } pushObject(gift) if (store.getConfig.showHighlight && coin_type === 'gold' && store.getConfig.pushGiftIntoHighlight) { const chat: SuperChatProps = { type: 'superchat', uid, uname, face, price: total_coin, // 实际价格 * 1000 content: `${action}${giftName}`, contentJpn: '', ts: timestamp * 1000, second: priceToSeconds(total_coin), bgColor, bgBottomColor, } pushChat(chat) } }) live.on('DANMU_MSG', (data: DanmakuMessage) => { // // eslint-disable-next-line no-console // console.log(data) const { info } = data const perhapsLottery = info[0][9] if (perhapsLottery !== 0) return const [, content, [uid, uname, fang, , , , ,color = ''], [level = 0, label = ''],,,,perhapsGuard] = info const ts = info[0][4] let tagColor = info[3][9] || 0 if (store.getConfig.showGuardTag === 2) tagColor = info[3][4] || 0 if (store.getConfig.blackList.includes(uid)) return if (store.getConfig.autoReply) { setTimeout(() => { autoSendByWord(content) }, 1000) } const danmaku: DanmakuProps = { type: 'text', uid, uname, content: processTooLongSymbols(content), color, tagColor, fang, level, label, perhapsGuard, ts, } if (typeof info[0][13] === 'object') danmaku.content = info[0][13].url pushObject(danmaku) }) live.on('SUPER_CHAT_MESSAGE_JPN', (data: SuperChatMessage) => { // // eslint-disable-next-line no-console // console.log(data) const { data: { uid, user_info: { uname, face }, price, message_jpn, message, ts, time, background_color, background_bottom_color } } = data const chat: SuperChatProps = { type: 'superchat', uid: Number.parseInt(uid), uname, face, price: price * 1000, // 实际价格 * 1000 content: message, contentJpn: message_jpn.trim() !== '' ? message_jpn : message, ts: ts * 1000, second: time, bgColor: background_color, bgBottomColor: background_bottom_color, } // // eslint-disable-next-line no-console // console.log(chat) pushObject(chat) if (store.getConfig.showHighlight) pushChat(chat) }) // live.on('SUPER_CHAT_MESSAGE', (data) => { // // eslint-disable-next-line no-console // console.log(data) // }) live.on('GUARD_BUY', (data: GuardBuyMessage) => { // // eslint-disable-next-line no-console // console.log(data) const { data: { uid, username, num, price, guard_level, ts } } = data const guard: SuperChatProps = { type: 'superchat', uname: username, face: '', uid, price: price * num, // 实际价格 * 1000 content: '欢迎加入大航海', contentJpn: '', second: guardType[guard_level].second, ts: ts * 1000, bgColor: guardType[guard_level].bgColor, bgBottomColor: guardType[guard_level].bgBottomColor, } pushObject(guard) if (store.getConfig.showHighlight) pushChat(guard) }) } catch (e) { // eslint-disable-next-line no-console console.log(e) } } const disconnectRoom = () => { if (live) { live.close() live = null linked.value = false } } export { connectRoom, disconnectRoom, population, fans, danmakuPool, linked, chatPool, selectedSc, pushChat, enterQueue, } ================================================ FILE: src/composables/shortIdToLong.ts ================================================ import { fetch } from '@tauri-apps/api/http' import { shortIdToLongApi } from './api' async function shortToLongResponse(id: number) { const response = (await fetch(`${shortIdToLongApi}${id}`)).data as any return response } async function shortToLong(id: number) { const response = await shortToLongResponse(id) return response.data.room_id as number | undefined } export { shortToLong, } ================================================ FILE: src/composables/tooLongSymbols.ts ================================================ function processTooLongSymbols(content: string) { const match = content.match(/^(.)\1{6,20}$/) if (match) return `${content.slice(0, 6)}...` return content } export { processTooLongSymbols, } ================================================ FILE: src/composables/types.ts ================================================ type MsgCommand = 'INTERACT_WORD' | 'DANMU_MSG' // 弹幕信息 | 'ROOM_REAL_TIME_MESSAGE_UPDATA' // 有关注人数 | 'WATCHED_CHANGE' // 观看人数 | 'ENTRY_EFFECT' // 欢迎舰长进入直播间 | 'WELCOME' // 欢迎xxx进入直播间 | 'WELCOME_GUARD' // 欢迎xxx进入直播间 | 'SEND_GIFT' // 礼物 | 'COMBO_SEND' // 连击 | 'SUPER_CHAT_MESSAGE' // sc | 'SUPER_CHAT_MESSAGE_JPN' | 'GUARD_BUY' // 上舰长 | 'USER_TOAST_MSG' // 续费舰长 | '__CONNECTED__' // 连接成功 | '__ERROR__' // 报错 interface MessageType { cmd: MsgCommand } interface DanmakuMessage extends MessageType { cmd: 'DANMU_MSG' info: [ config: [ n0: number, n1: number, n2: number, n3: number, timestamp: number, n5: number, n6: number, n7: string, n8: number, perhapsLottery: number, // 如果是抽奖弹幕,这个值不是 0 n10: number, n11: any, n12: any, n13: string | { bulge_display: number emoticon_unique: string height: number in_player_area: number is_dynamic: number url: string width: number }, n14: any, ], content: string, userInfo: [uid: number, uname: string, n2: number, n3: number, n4: number, n5: number, n6: number, color: string], label: [level: number, label: string, extLabel: string, roomId: number, colorInt: number, n5: string, n6: number, n7: number, n8: number, n9: number], rank: Array, title: [string, string], n6: number, perhapsGuard: 0 | 1 | 2 | 3, // 不为 0 是舰长 n8: any, ] } interface WatchedMessage extends MessageType { cmd: 'WATCHED_CHANGE' data: { num: number } } interface SubscriberMessage extends MessageType { cmd: 'ROOM_REAL_TIME_MESSAGE_UPDATA' data: { fans: number fans_club: number roomid: number red_notice: number } } interface SendGiftMessage extends MessageType { cmd: 'SEND_GIFT' data: { face: string // 头像地址 giftType: number timestamp: number coin_type: 'gold' | 'silver' uid: number uname: string giftName: string num: number total_coin: number giftId: number action: string blind_gift: { blind_gift_config_id: number from: number gift_action: string original_gift_id: string original_gift_name: string } | null } } interface GuardBuyMessage extends MessageType { cmd: 'GUARD_BUY' data: { uid: number username: string gift_name: string num: number price: number guard_level: 1 | 2 | 3 ts: number } } interface SuperChatMessage extends MessageType { cmd: 'SUPER_CHAT_MESSAGE_JPN' data: { uid: string user_info: { uname: string face: string } price: number message_jpn: string message: string background_bottom_color: string background_color: string ts: number time: number } } interface WelcomeGuardMessage extends MessageType { cmd: 'WELCOME_GUARD' data: { uid: number username: string guard_level: number } } interface InteractiveWordMessage extends MessageType { cmd: 'INTERACT_WORD' data: { contribution: { grade: number } identities: [number] is_spread: number msg_type: 1 | 2 roomid: number uid: number uname: string uname_color: string trigger_time: number // 除以 1000 后就可以是一个合法的时间 timestamp: number // 时间戳 / 1000 } } interface ComboSendMessage extends MessageType { cmd: 'COMBO_SEND' data: { gift_id: number gift_name: string gift_nun: string is_show: number uid: number uname: string action: string batch_combo_id: string batch_combo_num: number combi_id: string combo: number combo_total_coin: number } } interface SendMessageProps { bubble: number // 0 msg: string // 发出的消息 color: number // 颜色 mode: number // 1 fontsize: number // 25 rnd: number // 时间戳 / 1000 roomid: number // 直播间房间号 csrf: string csrf_token: string } interface GiftInfo { id: number webp: string } interface LiveAreaInfo { id: number name: string list: Array<{ id: string name: string }> } interface StartLiveResponse { code: number msg: string data: { change: 0 | 1 status: string rtmp: { addr: string code: string } } } interface SpaceApiResponse { code: number data: { info: { face: string live: { roomid: number title: string } } } } interface CardInfoResponse { code: number data: { card: { face: string } } } export type { MsgCommand, DanmakuMessage, WatchedMessage, SubscriberMessage, SendGiftMessage, GuardBuyMessage, SuperChatMessage, WelcomeGuardMessage, InteractiveWordMessage, ComboSendMessage, GiftInfo, SendMessageProps, LiveAreaInfo, StartLiveResponse, SpaceApiResponse, CardInfoResponse, } ================================================ FILE: src/layouts/default.vue ================================================ ================================================ FILE: src/layouts/none.vue ================================================ ================================================ FILE: src/main.ts ================================================ import { createApp } from 'vue' import { createRouter, createWebHistory } from 'vue-router' import generatedRoutes from 'virtual:generated-pages' import { setupLayouts } from 'virtual:generated-layouts' import { Buffer } from 'buffer/' import { WebviewWindow } from '@tauri-apps/api/window' import { tryOnUnmounted } from '@vueuse/core' import App from './App.vue' import { pinia } from '~/stores' import '@unocss/reset/tailwind.css' import './styles/main.css' import 'uno.css' (window as any).Buffer = Buffer const app = createApp(App) // const pinia = createPinia() const routes = setupLayouts(generatedRoutes) const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes, }) app.use(pinia) app.use(router) app.mount('#app') const mainWindow = WebviewWindow.getByLabel('main'); (async () => { const unlisten = await mainWindow?.onCloseRequested((_event) => { const danmakuWindow = WebviewWindow.getByLabel('danmakuWidget') if (danmakuWindow) danmakuWindow.close() const senderWindow = WebviewWindow.getByLabel('senderWindow') if (senderWindow) senderWindow.close() }) tryOnUnmounted(() => { unlisten?.() }) })() ================================================ FILE: src/pages/index.vue ================================================ ================================================ FILE: src/pages/live.vue ================================================ ================================================ FILE: src/pages/sender.vue ================================================ meta: layout: none ================================================ FILE: src/pages/settings.vue ================================================ ================================================ FILE: src/pages/show.vue ================================================ meta: layout: none ================================================ FILE: src/stores/index.ts ================================================ import { createPinia } from 'pinia' export const pinia = createPinia() ================================================ FILE: src/stores/position.ts ================================================ import { defineStore } from 'pinia' import { invoke } from '@tauri-apps/api/tauri' export interface PositionConfig { width: number height: number x: number y: number } export const usePosition = defineStore('position', { state: () => ({ width: 400, height: 600, x: 0, y: 0, }), getters: { getConfig() { return () => { const localConfigString = localStorage.getItem('position') if (!localConfigString) return { width: 400, height: 600, x: 0, y: 0 } const localConfig = JSON.parse(localConfigString) as PositionConfig return localConfig } }, }, actions: { async storeConfig() { const conf = await invoke('get_viewer_pos_and_size') as PositionConfig this.width = conf.width this.height = conf.height this.x = conf.x this.y = conf.y localStorage.setItem('position', JSON.stringify(conf)) }, }, }) ================================================ FILE: src/stores/store.ts ================================================ import { defineStore } from 'pinia' import type { GiftInfo, LiveAreaInfo } from '../composables/types' import type { Answer } from '~/composables/autoSendMsg' import { eventEmitter } from '~/composables/eventEmitter' interface UserInfo { oauthKey: string mid: number midmd5: string mname: string expires: number bili_jct: string sessdata: string avatarUrl: string lastLogin: number sid: string } interface ConfigProps { showGuardTag: number showAvatar: boolean showTime: boolean showSilverGift: boolean showGoldGift: boolean showPopulation: boolean showHighlight: boolean showEnter: boolean showSubscribe: boolean canSendMessage: boolean textColor: string enableTextShadow: boolean textShadowColor: string bgColor: string bgOpacity: string blur: boolean layout: 'loose' | 'tight' autoReply: boolean readSc: boolean readGift: boolean pushGiftIntoHighlight: boolean fontFamily: string blackList: number[] scLang: 'zh-cn' | 'ja-jp' } const defaultConfig: ConfigProps = { blackList: [], showGuardTag: 0, showAvatar: true, showTime: false, showSilverGift: false, showPopulation: true, showGoldGift: true, showHighlight: true, showEnter: false, showSubscribe: true, pushGiftIntoHighlight: true, canSendMessage: false, textColor: '#ffffff', enableTextShadow: false, textShadowColor: '#000000', bgColor: '#000000', bgOpacity: '128', blur: false, layout: 'loose', autoReply: false, readSc: false, readGift: false, fontFamily: '', scLang: 'zh-cn', } const defaultUserInfo: UserInfo = { oauthKey: '', mid: 0, midmd5: '', mname: '', expires: 0, bili_jct: '', sessdata: '', avatarUrl: '', lastLogin: 0, sid: '', } interface liveConfig { isLive: boolean liveAreaList: LiveAreaInfo[] liveTitle: string addr: string code: string } export const useStore = defineStore('stores', { state: () => ({ roomId: '', liverId: 0, giftInfoList: [] as GiftInfo[], userInfo: {} as UserInfo, config: Object.assign({ ...defaultConfig }, JSON.parse(localStorage.getItem('config') || 'null')) as ConfigProps, requestBlockedTimes: 0, faqs: [] as Answer[], blackList: [] as number[], settingsSaved: true, linked: false, liveConfig: { isLive: false, liveAreaList: [], liveTitle: '', addr: '', code: '', } as liveConfig, mediaList: [] as { fileName: string; blob: string }[], configLoaded: false, clickThrough: false, senderEnabled: false, previousCanSend: false, }), getters: { getUserInfo(): UserInfo { if (!localStorage.getItem('userInfo')) { localStorage.setItem('userInfo', JSON.stringify(defaultUserInfo)) return defaultUserInfo } // 登录过期 if (this.userInfo.lastLogin + this.userInfo.expires * 1000 < new Date().getTime()) { localStorage.removeItem('userInfo') this.userInfo = {} as UserInfo throw new Error('需要重新登录') } if (!this.userInfo.mid) this.userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}') // // eslint-disable-next-line no-console // console.log(this.userInfo) return this.userInfo }, getConfig(): ConfigProps { if (!localStorage.getItem('config')) { localStorage.setItem('config', JSON.stringify(defaultConfig)) this.config = { ...defaultConfig } return this.config } if (!this.configLoaded) { this.config = Object.assign({ ...defaultConfig }, JSON.parse(localStorage.getItem('config') || 'null')) this.configLoaded = true } // this.config = JSON.parse(localStorage.getItem('config') || 'null') // if (!this.config) { // this.config = Object.assign({ ...defaultConfig }, this.config) // localStorage.setItem('config', JSON.stringify(this.config)) // } return this.config }, getRoomId(): string { this.roomId = localStorage.getItem('roomId') || '' return this.roomId }, getFaqs(): Answer[] { this.faqs = JSON.parse(localStorage.getItem('faqs') || '[]') return this.faqs }, }, actions: { storeUserInfo() { localStorage.setItem('userInfo', JSON.stringify(this.userInfo)) }, removeUserInfo() { localStorage.removeItem('userInfo') this.userInfo = { ...defaultUserInfo } }, storeConfig() { localStorage.setItem('config', JSON.stringify(this.config)) // trim faqs this.faqs = this.faqs.filter(it => it.answer.trim() !== '' && it.keywords.length !== 0) localStorage.setItem('faqs', JSON.stringify(this.faqs)) eventEmitter('new-faq', this.faqs) }, removeConfig() { localStorage.setItem('config', JSON.stringify(defaultConfig)) this.config = { ...defaultConfig } eventEmitter('reset-config', this.config) }, setRoomId(id: string) { localStorage.setItem('roomId', id) }, }, }) export type { ConfigProps, } ================================================ FILE: src/styles/main.css ================================================ :root { font-family: Inter, Avenir, Helvetica, Arial, sans-serif; font-size: 16px; line-height: 24px; font-weight: 400; font-synthesis: none; text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; -webkit-text-size-adjust: 100%; } body { margin: 0; min-height: 100vh; } #app { margin: 0 auto; } html { transition: background 0.25s; } .use-dark { min-height: 100vh; } .dark>body>#app>div>.use-dark-msg { background: #242424; color: #ddd; } .dark:has(.use-dark) { background: #242424; color: #ddd; } ================================================ FILE: src/types.ts ================================================ export interface MessageProvider { pushMsg(msg: string, config?: MessageProviderOptions): void } export interface MessageProviderOptions { type?: 'success' | 'error' | 'warning' | 'info' ttl?: number } ================================================ FILE: src/vite-env.d.ts ================================================ /// declare module '*.vue' { import type { DefineComponent } from 'vue' const component: DefineComponent<{}, {}, any> export default component } ================================================ FILE: src-tauri/.gitignore ================================================ # Generated by Cargo # will have compiled files and executables /target/ ================================================ FILE: src-tauri/Cargo.toml ================================================ [package] name = "app" version = "0.1.0" description = "A Tauri App" authors = ["you"] license = "" repository = "" default-run = "app" edition = "2021" rust-version = "1.57" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [build-dependencies] tauri-build = { version = "1.0.4", features = [] } [dependencies] serde_json = "1.0" serde = { version = "1.0", features = ["derive"] } # tao = { version = "0.14.0"} tauri = { version = "1.0.4", features = ["api-all", "macos-private-api"] } reqwest = { version = "0.11.11", features = ["json", "multipart"] } objc = "0.2.7" window-shadows = "0.2.0" [features] # by default Tauri runs in production mode # when `tauri dev` runs it is executed with `cargo run --no-default-features` if `devPath` is an URL default = [ "custom-protocol" ] # this feature is used used for production builds where `devPath` points to the filesystem # DO NOT remove this custom-protocol = [ "tauri/custom-protocol" ] http-multipart = [ "tauri/http-multipart" ] ================================================ FILE: src-tauri/build.rs ================================================ fn main() { tauri_build::build() } ================================================ FILE: src-tauri/src/fetch_img.rs ================================================ use std::io::Write; #[tauri::command] pub async fn fetch_image(img_url: String, file_path: String) -> Result { // println!("{}", img_url); // println!("{}", file_path); if std::path::Path::new(file_path.as_str()).metadata().is_ok() { // println!("File exists!"); return Ok(file_path); } let client = reqwest::Client::new(); let response = client.get(img_url) .send() .await .unwrap(); // println!("Fetched image!"); let dir = std::path::Path::new(file_path.as_str()).parent().unwrap(); if dir.metadata().is_err() { std::fs::create_dir_all(dir).unwrap(); } let mut file = std::fs::File::create(file_path.as_str()).unwrap(); file.write_all(response.bytes().await.unwrap().as_ref()).unwrap(); Ok(file_path) } ================================================ FILE: src-tauri/src/load_local_img.rs ================================================ #[tauri::command] pub async fn load_local_image(uid_path: String) -> Result { if std::path::Path::new(uid_path.as_str()).metadata().is_ok() { return Ok(uid_path); } Ok("".into()) } ================================================ FILE: src-tauri/src/main.rs ================================================ #![cfg_attr( all(not(debug_assertions), target_os = "windows"), windows_subsystem = "windows" )] mod send_msg; mod fetch_img; mod open_app_dir; mod load_local_img; mod new_view; mod new_sender; use send_msg::send_message; use fetch_img::fetch_image; use open_app_dir::open_app_img_dir; use load_local_img::load_local_image; // use tauri::Manager; #[cfg(target_os = "macos")] #[macro_use] extern crate objc; fn main() { tauri::Builder::default() .invoke_handler(tauri::generate_handler![ send_message, fetch_image, open_app_img_dir, load_local_image, new_sender::create_sender_window, new_view::create_new_danmaku_view, new_view::set_click_through, new_view::get_viewer_pos_and_size, new_view::set_viewer_pos_and_size ]) .run(tauri::generate_context!()) .expect("error while running tauri application"); } ================================================ FILE: src-tauri/src/new_sender.rs ================================================ use tauri::Wry; #[tauri::command] pub async fn create_sender_window(app_handle: tauri::AppHandle) { let viewer = tauri::WindowBuilder::new( &app_handle, "senderWindow", tauri::WindowUrl::App("/sender".into()) ) .transparent(true) .decorations(false) .inner_size(400., 40.) .build() .unwrap(); viewer .set_min_size(std::option::Option::Some(tauri::LogicalSize::new(200, 40))) .expect("Failed to set min size!"); viewer .set_max_size(std::option::Option::Some(tauri::LogicalSize::new(800, 40))) .expect("Failed to set min size!"); viewer .set_always_on_top(true) .expect("Failed to set always on top"); window_shadows::set_shadow(&viewer, false) .expect("Failed to set window shadows to false!"); } ================================================ FILE: src-tauri/src/new_view.rs ================================================ use tauri::{Manager, Wry}; #[tauri::command] pub async fn create_new_danmaku_view(app_handle: tauri::AppHandle) { let viewer = tauri::WindowBuilder::new( &app_handle, "danmakuWidget", tauri::WindowUrl::App("/show".into()) ) .transparent(true) .decorations(false) .inner_size(400., 600.) .build() .unwrap(); viewer .set_min_size(std::option::Option::Some(tauri::LogicalSize::new(200, 200))) .expect("Failed to set min size!"); viewer .set_always_on_top(true) .expect("Failed to set always on top"); window_shadows::set_shadow(&viewer, false) .expect("Failed to set window shadows to false!"); } #[tauri::command] pub fn set_click_through(app_handle: tauri::AppHandle, enable: bool) -> Result { let option_window = app_handle.get_window("danmakuWidget"); if let Some(window) = option_window { window.with_webview(move |webview| { #[cfg(target_os = "macos")] unsafe { let () = msg_send![webview.ns_window(), setIgnoresMouseEvents: enable]; } }) .expect("Failed to set click through"); // tao::window::Window::set_ignore_cursor_events(&window, enable); // 怎么把 tauri::Window cast 到 tao::window::Window 呢? } Ok(enable) } #[derive(Copy, Clone, serde::Serialize, serde::Deserialize)] pub struct PosProps { width: u32, height: u32, x: i32, y: i32 } #[tauri::command] pub fn get_viewer_pos_and_size(app_handle: tauri::AppHandle) -> Result { let option_window = app_handle.get_window("danmakuWidget"); if let Some(viewer) = option_window { let size = viewer.inner_size().unwrap(); let pos = viewer.inner_position().unwrap(); let ret = PosProps { width: size.width, height: size.height, x: pos.x, y: pos.y }; return Ok(ret); } Err("Failed to get danmaku window!".into()) } #[tauri::command] pub fn set_viewer_pos_and_size(app_handle: tauri::AppHandle, conf: PosProps) -> Result { let option_window = app_handle.get_window("danmakuWidget"); let PosProps {width, height, x, y} = conf; if let Some(viewer) = option_window { viewer.set_size(tauri::PhysicalSize { width, height }).unwrap(); viewer.set_position(tauri::PhysicalPosition { x, y }).unwrap(); return Ok(true); } Err("Failed to get danmaku window!".into()) } ================================================ FILE: src-tauri/src/open_app_dir.rs ================================================ use std::process::Command; #[tauri::command] pub async fn open_app_img_dir(dir: String) -> Result<(), String> { // println!("{}", dir); if cfg!(target_os = "windows") { Command::new("explorer") .arg(&dir) .spawn() .unwrap(); } else if cfg!(target_os = "macos") { Command::new("open") .arg(&dir) .spawn() .unwrap(); } else { Command::new("xdg-open") .arg(&dir) .spawn() .unwrap(); } Ok(()) } ================================================ FILE: src-tauri/src/send_msg.rs ================================================ #[derive(Clone, serde::Serialize, serde::Deserialize, Debug)] struct Payload { msg: String, cookie: String, csrf: String, roomid: String } static API: &str = "https://api.live.bilibili.com/msg/send"; #[tauri::command] pub async fn send_message(msg: String, cookie: String, csrf: String, roomid: String) -> Result<(), String> { let client = reqwest::Client::new(); let csrf2 = csrf.clone(); let form = reqwest::multipart::Form::new() .text("bubblue", "0") .text("msg", msg) .text("color", "16777215") .text("mode", "1") .text("fontsize", "25") .text("roomid", roomid) .text("csrf", csrf) .text("csrf_token", csrf2) .text("rnd", std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_secs().to_string()); let response = client .post(API) .header("cookie", cookie) .multipart(form) .send() .await .unwrap(); if response.status().is_success() { return Ok(()); } Err(response.status().to_string().into()) } ================================================ FILE: src-tauri/tauri.conf.json ================================================ { "$schema": "../node_modules/@tauri-apps/cli/schema.json", "build": { "beforeBuildCommand": "pnpm build", "beforeDevCommand": "pnpm dev", "devPath": "http://localhost:5173", "distDir": "../dist" }, "package": { "productName": "D4nm4ku", "version": "0.1.13" }, "tauri": { "allowlist": { "all": true, "http":{ "scope":[ "http://**", "https://**" ], "all": true, "request": true }, "fs": { "all": true, "scope": ["$APP/imgs/*"] } }, "macOSPrivateApi": true, "bundle": { "active": true, "category": "DeveloperTool", "copyright": "", "deb": { "depends": [] }, "externalBin": [], "icon": [ "icons/32x32.png", "icons/128x128.png", "icons/128x128@2x.png", "icons/icon.icns", "icons/icon.ico" ], "identifier": "win.widcard.d4nm4ku", "longDescription": "", "macOS": { "entitlements": null, "exceptionDomain": "", "frameworks": [], "providerShortName": null, "signingIdentity": null }, "resources": [], "shortDescription": "", "targets": "all", "windows": { "certificateThumbprint": null, "digestAlgorithm": "sha256", "timestampUrl": "" } }, "security": { "csp": null }, "updater": { "active": false }, "windows": [ { "fullscreen": false, "height": 600, "resizable": true, "title": "D4nm4ku", "width": 800, "label": "main", "minWidth": 800, "minHeight": 600 } ] } } ================================================ FILE: tsconfig.json ================================================ { "compilerOptions": { "baseUrl": ".", "target": "ESNext", "useDefineForClassFields": true, "module": "ESNext", "moduleResolution": "Node", "strict": true, "jsx": "preserve", "sourceMap": true, "resolveJsonModule": true, "isolatedModules": true, "esModuleInterop": true, "lib": ["ESNext", "DOM"], "skipLibCheck": true, "noUnusedLocals": true, "strictNullChecks": true, "forceConsistentCasingInFileNames": true, "types": [ "vite/client", "vite-plugin-pages/client", "vite-plugin-vue-layouts/client" ], "paths": { "~/*": ["src/*"] } }, "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"], "references": [{ "path": "./tsconfig.node.json" }] } ================================================ FILE: tsconfig.node.json ================================================ { "compilerOptions": { "composite": true, "module": "ESNext", "moduleResolution": "Node", "allowSyntheticDefaultImports": true }, "include": ["vite.config.ts"] } ================================================ FILE: unocss.config.ts ================================================ import { defineConfig, presetAttributify, presetIcons, presetUno, presetWebFonts, // transformerDirectives, // transformerVariantGroup, } from 'unocss' // @unocss-include export default defineConfig({ shortcuts: [ ['btn', 'inline-block px-4 py-1 bg-#646cff bg-opacity-80 disabled:opacity-20 disabled:bg-zinc-500 hover:bg-opacity-100 font-500 transition-all text-white'], ['icon-btn', 'text-[0.9em] inline-block cursor-pointer select-none opacity-75 transition duration-200 ease-in-out hover:opacity-100 hover:text-#646cff !outline-none disabled:(cursor-not-allowed op-50 hover:text-zinc)'], ['text-active', 'text-#646cff dark:text-#646cff opacity-100'], ['text-btn', 'cursor-pointer select-none opacity-75 transition duration-200 hover:op-100 hover:text-#646cff !outline-none disabled:(cursor-not-allowed op-50 hover:text-zinc)'], ['m-input', 'border border-zinc-300 dark:border-zinc-600 !outline-none px-2 py-1 bg-transparent leading-normal'], ['wsn', 'whitespace-nowrap'], ], presets: [ presetUno(), presetAttributify(), presetIcons({ scale: 1.2, warn: true, }), presetWebFonts({ fonts: { sans: 'DM Sans', serif: 'DM Serif Display', mono: 'DM Mono', }, }), ], // transformers: [ // transformerDirectives(), // transformerVariantGroup(), // ], }) ================================================ FILE: vite.config.ts ================================================ import path from 'path' import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import Unocss from 'unocss/vite' import Pages from 'vite-plugin-pages' import Layouts from 'vite-plugin-vue-layouts' // https://vitejs.dev/config/ export default defineConfig({ resolve: { alias: { '~/': `${path.resolve(__dirname, 'src')}/`, }, }, plugins: [ vue(), Unocss(), Pages(), Layouts(), ], })