Full Code of widcardw/D4nm4ku for AI

main e71d34b43972 cached
98 files
169.4 KB
49.5k tokens
99 symbols
1 requests
Download .txt
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. <https://fsf.org/>
 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.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    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 <https://www.gnu.org/licenses/>.

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
<https://www.gnu.org/licenses/>.


================================================
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 <br> 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
================================================
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="referrer" content="no-referrer" />
    <title>Vite + Vue + TS</title>
  </head>
  <body>
    <script>
      window.global = window
    </script>
    <div id="app"></div>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>


================================================
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
================================================
<script setup lang="ts">
import { provide, ref } from 'vue'
import UMessageProvider from './components/ui/UMessageProvider.vue'
import { msgKey } from '~/composables/injectionKeys'
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://vuejs.org/api/sfc-script-setup.html#script-setup
const msgRef = ref<typeof UMessageProvider>()
provide(msgKey, msgRef)
</script>

<template>
  <RouterView />
  <UMessageProvider ref="msgRef" />
</template>


================================================
FILE: src/components/DarkMode.vue
================================================
<script setup lang="ts">
import { isDark, toggleDark } from '~/composables/dark'
</script>

<template>
  <div icon-btn @click="toggleDark()">
    <div v-if="!isDark" i-ri-sun-line />
    <div v-else i-ri-moon-line />
  </div>
</template>


================================================
FILE: src/components/SideBar.vue
================================================
<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import DarkMode from './DarkMode.vue'

const router = useRouter()

const curPage = ref(1)
const routerSwitch = (target: string, page: number) => {
  curPage.value = page
  router.push(target)
}
</script>

<template>
  <div h-100vh flex flex-col fixed class="bg-#7f7f7f10">
    <div
      m-2 icon-btn i-ri-home-line
      :class="{ 'text-#646cff': curPage === 1 }"
      @click="routerSwitch('/', 1)"
    />
    <div
      m-2 icon-btn i-ri-settings-5-line
      :class="{ 'text-#646cff': curPage === 2 }"
      @click="routerSwitch('/settings', 2)"
    />
    <div
      m-2 icon-btn i-ri-live-line
      :class="{ 'text-#646cff': curPage === 3 }"
      @click="routerSwitch('/live', 3)"
    />
    <div flex-1 />
    <a href="https://github.com/widcardw/D4nm4ku" target="_blank" m-2 icon-btn>
      <div i-ri-github-fill />
    </a>
    <DarkMode m-2 />
  </div>
</template>


================================================
FILE: src/components/UWidget.vue
================================================
<script setup lang="ts">
import { listen } from '@tauri-apps/api/event'
import { tryOnBeforeUnmount, useStorage } from '@vueuse/core'
import { inject } from 'vue'
import UMessageSender from './send/UMessageSender.vue'
import UInteraction from './danmaku/UInteraction.vue'
import USuperChatPool from '~/components/superchat/USuperChatPool.vue'
import { hex2rgb } from '~/composables/randomColor'
import {
  chatPool,
  connectRoom,
  danmakuPool,
  disconnectRoom,
  enterQueue,
  fans,
  population,
  selectedSc,
} from '~/composables/server'
import { isGiftProps } from '~/composables/components'
import UWatch from '~/components/danmaku/UWatch.vue'
import URenderer from '~/components/danmaku/URenderer.vue'
import { useStore } from '~/stores/store'
import { getLiverInfo } from '~/composables/getLiverInfo'
import parseFanNumbers from '~/composables/parseFanNumbers'
import { msgKey } from '~/composables/injectionKeys'

const store = useStore()
const unlistens: Function[] = []
const msgRef = inject(msgKey)

function parseBoolean(obj: string) {
  return obj === 'true'
}

async function initListens() {
  unlistens.push(await listen('show-avatar', (event) => {
    store.config.showAvatar = parseBoolean(event.payload as string)
  }))
  unlistens.push(await listen('show-guard-tag', (event) => {
    store.config.showGuardTag = parseInt(event.payload as string)
  }))
  unlistens.push(await listen('show-time', (event) => {
    store.config.showTime = parseBoolean(event.payload as string)
  }))
  unlistens.push(await listen('show-silver-gift', (event) => {
    store.config.showSilverGift = parseBoolean(event.payload as string)
  }))
  unlistens.push(await listen('show-gold-gift', (event) => {
    store.config.showGoldGift = parseBoolean(event.payload as string)
  }))
  unlistens.push(await listen('can-send-message', (event) => {
    store.config.canSendMessage = parseBoolean(event.payload as string)
  }))
  unlistens.push(await listen('text-color-changed', (event) => {
    store.config.textColor = event.payload as string
  }))
  unlistens.push(await listen('text-shadow-color-changed', (event) => {
    store.config.textShadowColor = event.payload as string
  }))
  unlistens.push(await listen('enable-text-shadow', (event) => {
    store.config.enableTextShadow = parseBoolean(event.payload as string)
  }))
  unlistens.push(await listen('bg-color-changed', (event) => {
    store.config.bgColor = event.payload as string
  }))
  unlistens.push(await listen('bg-opacity-changed', (event) => {
    store.config.bgOpacity = event.payload as string
  }))
  unlistens.push(await listen('show-population', (event) => {
    store.config.showPopulation = parseBoolean(event.payload as string)
  }))
  unlistens.push(await listen('blur', (event) => {
    store.config.blur = parseBoolean(event.payload as string)
  }))
  unlistens.push(await listen('layout', (event) => {
    store.config.layout = event.payload as 'loose' | 'tight'
  }))
  unlistens.push(await listen('auto-reply', (event) => {
    store.config.autoReply = parseBoolean(event.payload as string)
  }))
  unlistens.push(await listen('show-highlight', (event) => {
    store.config.showHighlight = parseBoolean(event.payload as string)
  }))
  unlistens.push(await listen('show-enter', (event) => {
    store.config.showEnter = parseBoolean(event.payload as string)
  }))
  unlistens.push(await listen('show-subscribe', (event) => {
    store.config.showSubscribe = parseBoolean(event.payload as string)
  }))
  unlistens.push(await listen('font-changed', (event) => {
    store.config.fontFamily = event.payload as string
  }))
  unlistens.push(await listen('blacklist', (event) => {
    store.config.blackList = JSON.parse(event.payload as string) as number[]
  }))
  unlistens.push(await listen('reset-config', (event) => {
    store.config = JSON.parse(event.payload as string)
  }))
  unlistens.push(await listen('new-faq', (event) => {
    store.faqs = JSON.parse(event.payload as string)
  }))
}

initListens()
connectRoom()

const roomId = useStorage('roomId', '')

getLiverInfo(Number.parseInt(roomId.value))
  .then((res) => {
    // console.log(res)
    fans.value = parseFanNumbers(res)
  })
  .catch((err) => {
    msgRef?.value.pushMsg(err.message, { type: 'error' })
  })

tryOnBeforeUnmount(() => {
  unlistens.map(fn => fn())
  disconnectRoom()
})
</script>

<template>
  <div
    flex flex-col h-100vh
    :class="{
      'backdrop-blur-sm': store.getConfig.blur,
    }"
    :style="{
      background: hex2rgb(store.getConfig.bgColor, store.getConfig.bgOpacity),
      color: store.getConfig.textColor,
      textShadow: store.getConfig.enableTextShadow ? `1px 1px 1px ${store.getConfig.textShadowColor}` : 'none',
      fontFamily: store.getConfig.fontFamily,
    }"
  >
    <UWatch
      v-if="store.getConfig.showPopulation"
      data-tauri-drag-region shadow
      :population="population" :fans="fans"
    />
    <USuperChatPool
      v-if="store.getConfig.showHighlight"
      v-show="chatPool.length > 0"
      v-model="selectedSc"
      data-tauri-drag-region
      :chat-pool="chatPool" z-999 shadow
    />
    <TransitionGroup
      tag="div"
      name="list"
      class="scroller"
      flex-1 of-y-auto
      data-tauri-drag-region
    >
      <URenderer
        v-for="it in danmakuPool"
        :key="`${it.ts}${it.uname}${it.type}${isGiftProps(it) ? it.giftId : ''}`"
        :obj="it"
      />
    </TransitionGroup>
    <TransitionGroup
      v-if="enterQueue.length > 0 && store.getConfig.showEnter"
      tag="div"
      name="enter"
      class="h-2rem of-y-hidden"
    >
      <UInteraction
        :key="enterQueue[0].ts"
        type="interact"
        :action="enterQueue[0].action"
        :ts="enterQueue[0].ts"
        :uid="enterQueue[0].uid"
        :uname="enterQueue[0].uname"
        :uname-color="enterQueue[0].unameColor"
      />
    </TransitionGroup>
    <UMessageSender v-if="store.getConfig.canSendMessage" :no-border="true" />
  </div>
</template>

<style scoped>
::-webkit-scrollbar {
  width: 0;
  height: 0;
}

/* ::-webkit-scrollbar-thumb {
  background: rgba(127, 127, 127, 0.5);
  border-radius: 5px;
} */
.scroller {
  overscroll-behavior-y: contain;
  scroll-snap-type: y proximity;
}
.scroller > div:last-child {
  scroll-snap-align: end;
}
/** {
  pointer-events: v-bind(ct);
}*/

.list-move,
.list-enter-active,
.list-leave-active {
  transition: all 0.25s ease;
}
.list-enter-from {
  opacity: 0;
  transform: translateX(30px);
}
.list-leave-to {
  opacity: 0;
}

.enter-enter-active {
  transition: all 0.125s ease;
}
.enter-enter-from {
  opacity: 0;
  transform: translateY(10px);
}
</style>



================================================
FILE: src/components/danmaku/UDanmaku.vue
================================================
<script setup lang="ts">
import { confirm } from '@tauri-apps/api/dialog'
import { WebviewWindow } from '@tauri-apps/api/window'
import { inject, ref } from 'vue'
import MyImg from '../img/MyImg.vue'
import { guardType } from '~/composables/data'
import UGuardTag from '~/components/danmaku/UGuardTag.vue'
import Avatar from '~/components/img/Avatar.vue'
import { getAvatar2 } from '~/composables/getAvatar'
import { useStore } from '~/stores/store'
import { msgKey } from '~/composables/injectionKeys'

const props = withDefaults(defineProps<{
  content: string
  uname: string
  color: string
  level: number
  label: string
  tagColor: number
  fang: number
  perhapsGuard: 0 | 1 | 2 | 3
  ts: number
  uid: number
  showAvatar?: boolean
  showGuardTag?: boolean
  showTime?: boolean
  layout?: 'loose' | 'tight'
}>(), {
  showAvatar: true,
  showGuardTag: true,
  showTime: true,
  layout: 'loose',
})

const store = useStore()

const faceUrl = ref('')

const msgRef = inject(msgKey)
const urlIsBlob = ref(false)

if (props.showAvatar) {
// 异步获取头像的链接,默认为 noface,当加载出来后替换为真实头像
  getAvatar2(props.uid)
    .then(({ url, isBlob }) => {
      faceUrl.value = url
      urlIsBlob.value = isBlob
    })
    .catch((err: Error) => {
      msgRef?.value.pushMsg(err.message, { type: 'error' })
    })
}

async function confirmAddingToBlacklist(e: Event) {
  e.preventDefault()
  const confirmed = await confirm(`确定将用户 "${props.uname}" (uid: ${props.uid}) 加入黑名单吗?`, {
    title: '加入黑名单', type: 'warning',
  })

  if (confirmed) {
    store.config.blackList.push(props.uid)
    const mainWindow = WebviewWindow.getByLabel('main')
    if (mainWindow)
      mainWindow.emit('add-black', props.uid)
  }
}
</script>

<template>
  <div @contextmenu="confirmAddingToBlacklist">
    <div v-if="layout === 'loose'" flex space-x-2 w-full p="x-2 y-1" my-2>
      <!-- 头像 -->
      <Avatar v-if="showAvatar" w-3rem h-3rem :is-blob="urlIsBlob" :src="faceUrl" :uid="uid" />
      <div flex-1>
        <div flex justify-between text-sm>
          <div flex space-x-2>
            <!-- 用户名 -->
            <div leading-normal font-bold of-x-hidden wsn :style="{ color }">
              {{ uname }}
            </div>
            <span
              v-if="store.liverId === uid"
              text="0.75rem amber"
              border="~ rounded amber"
              bg="amber/20"
              px-1
            >主播</span>
            <span
              v-if="fang === 1"
              text="0.75rem amber"
              border="~ rounded amber"
              bg="amber/20"
              px="0.5"
            >房</span>
            <!-- 等级标签 -->
            <UGuardTag
              v-if="level && showGuardTag && tagColor !== 12632256"
              :level="level"
              :label="label"
              :perhaps-guard="perhapsGuard"
              :tag-color="tagColor"
              shadow
            />
            <MyImg v-if="perhapsGuard !== 0 && level >= 20" self-center :src="guardType[perhapsGuard].badge" class="w-1.25rem h-1.25rem" mx-1 rounded-full />
          </div>
          <!-- 弹幕发送时间 -->
          <div v-if="showTime" wsn ml-2>
            {{ new Date(ts).toLocaleTimeString('en-US', {
              hour: '2-digit',
              minute: '2-digit',
            }) }}
          </div>
        </div>
        <!-- 弹幕内容,初步断定为以 http 开头的是链接,采用 img 渲染 -->
        <div text-lg>
          <MyImg v-if="content.startsWith('http://')" class="h-2rem" :src="content" />
          <span v-else break-words>{{ content }}</span>
        </div>
      </div>
    </div>
    <div v-else flex space-x-2 w-full p="x-2 y-1">
      <Avatar v-if="showAvatar" :src="faceUrl" :uid="uid" :is-blob="urlIsBlob" class="w-1.5rem h-1.5rem" />
      <div space-x-1 overflow-ellipsis>
        <span v-if="showTime" wsn text-sm op-50>
          {{ new Date(ts).toLocaleTimeString('en-US', {
            hour: '2-digit',
            minute: '2-digit',
          }) }}
        </span>
        <span leading-normal font-bold wsn text-sm op-70 :style="{ color }">
          {{ uname }}
        </span>
        <span
          v-if="store.liverId === uid"
          text="0.75rem amber"
          border="~ rounded amber"
          bg="amber/20"
          px-1
        >主播</span>
        <span
          v-if="fang === 1"
          text="0.75rem amber"
          border="~ rounded amber"
          bg="amber/20"
          px="0.5"
        >房</span>
        <UGuardTag
          v-if="level && showGuardTag && tagColor !== 12632256"
          inline-flex leading-normal shadow
          :level="level"
          :label="label"
          :perhaps-guard="perhapsGuard"
          :tag-color="tagColor"
        />
        <MyImg v-if="perhapsGuard !== 0 && level >= 20" inline-flex w-1rem h-1rem :src="guardType[perhapsGuard].badge" err-src="/loading.gif" rounded-full />
        <MyImg v-if="content.startsWith('http://')" class="h-2rem" :src="content" inline-flex err-src="/loading.gif" />
        <span v-else break-words>{{ content }}</span>
      </div>
    </div>
  </div>
</template>


================================================
FILE: src/components/danmaku/UGift.vue
================================================
<script setup lang="ts">
import Avatar from '~/components/img/Avatar.vue'
import MyImg from '~/components/img/MyImg.vue'
import { useStore } from '~/stores/store'
defineProps<{
  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
}>()

const store = useStore()

// // eslint-disable-next-line no-console
// console.log('gift', props.ts, new Date(props.ts))
</script>

<template>
  <div flex w-full space-x-2 :style="{ backgroundColor: bgColor }" text-white p-2 rounded my-2>
    <Avatar w-3rem h-3rem :src="face" :uid="uid" :is-blob="false" />
    <div flex-1>
      <div flex justify-between text-sm>
        <div font-bold>
          {{ uname }}
        </div>
        <div v-if="coinType === 'gold'" text-amber text-sm>
          ¥{{ price * num / 1000 }}
        </div>
      </div>
      <div font-bold text-lg flex justify-between items-center>
        <div>{{ action }} <span :class="{ 'text-amber': coinType === 'gold' }">{{ blindGift?.original_gift_name }}</span> <span>{{ blindGift?.gift_action }}</span> <span :class="{ 'text-amber': coinType === 'gold' }">{{ giftName }}</span> × {{ num }}</div>
      </div>
    </div>
    <div grid grid-rows-2 />
    <MyImg
      :src="(store.giftInfoList.find(x => x.id === giftId) || { webp: '' }).webp"
      err-src="/loading.gif"
      class="w-3rem h-3rem"
    />
  </div>
</template>


================================================
FILE: src/components/danmaku/UGuardTag.vue
================================================
<script setup lang="ts">
const props = defineProps<{
  level: number
  label: string
  perhapsGuard: 0 | 1 | 2 | 3
  tagColor: number
}>()
</script>

<template>
  <div
    flex class="text-0.75rem"
  >
    <div
      rounded-l
      px-1
      wsn
      :style="{
        backgroundColor: `#${props.tagColor.toString(16).padStart(6, '0')}`,
      }"
    >
      {{ label }}
    </div>
    <div px-1 wsn bg-white text-black rounded-r text-shadow-none>
      {{ level }}
    </div>
  </div>
</template>


================================================
FILE: src/components/danmaku/UInteraction.vue
================================================
<script setup lang="ts">
import { inject, ref } from 'vue'
import { getAvatar2 } from '../../composables/getAvatar'
import { useStore } from '../../stores/store'
import Avatar from '../img/Avatar.vue'
import { msgKey } from '~/composables/injectionKeys'

const props = defineProps<{
  type: 'interact'
  uname: string
  uid: number
  unameColor: string
  ts: number
  action: 1 | 2
}>()

const store = useStore()
const faceUrl = ref('')
const urlIsBlob = ref(false)
const msgRef = inject(msgKey)

if (store.getConfig.showAvatar) {
  getAvatar2(props.uid)
    .then(({ url, isBlob }) => {
      faceUrl.value = url
      urlIsBlob.value = isBlob
    })
    .catch((err: Error) => {
      msgRef?.value.pushMsg(err.message, { type: 'error' })
    })
}
</script>

<template>
  <div w-full flex space-x-2 p="x-2 y-1">
    <Avatar v-if="store.getConfig.showAvatar" class="w-1.5rem h-1.5rem" :src="faceUrl" :is-blob="urlIsBlob" :uid="uid" />
    <div space-x-1>
      <span leading-normal text-sm op-70 font-bold :style="{ color: unameColor }">
        {{ uname }}
      </span>
      <span leading-normal :style="{ color: action === 1 ? '' : 'gold' }">{{ action === 1 ? '进入了直播间' : '关注了直播间' }}</span>
    </div>
  </div>
</template>


================================================
FILE: src/components/danmaku/URenderer.vue
================================================
<script setup lang="ts">
import UInteraction from './UInteraction.vue'
import UDanmaku from '~/components/danmaku/UDanmaku.vue'
import UGift from '~/components/danmaku/UGift.vue'
import UScDanmaku from '~/components/superchat/UScDanmaku.vue'
import type { DanmakuProps, GiftProps, InteractProps, SuperChatProps } from '~/composables/components'
import { isDanmakuProps, isGiftProps, isInteractProps, isSuperChatProps } from '~/composables/components'
import { useStore } from '~/stores/store'

defineProps<{
  obj?: DanmakuProps | GiftProps | SuperChatProps | InteractProps
}>()

const store = useStore()
</script>

<template>
  <UDanmaku
    v-if="isDanmakuProps(obj)"
    :content="obj.content"
    :uname="obj.uname"
    :level="obj.level"
    :label="obj.label"
    :color="obj.color"
    :tag-color="obj.tagColor"
    :fang="obj.fang"
    :perhaps-guard="obj.perhapsGuard"
    :ts="obj.ts"
    :uid="obj.uid"
    :show-avatar="store.getConfig.showAvatar"
    :show-guard-tag="store.getConfig.showGuardTag > 0"
    :show-time="store.getConfig.showTime"
    :layout="store.getConfig.layout"
  />
  <UGift
    v-else-if="isGiftProps(obj)"
    :uname="obj.uname"
    :action="obj.action"
    :num="obj.num"
    :face="obj.face"
    :coin-type="obj.coinType"
    :gift-id="obj.giftId"
    :gift-name="obj.giftName"
    :price="obj.price"
    :ts="obj.ts"
    :uid="obj.uid"
    :blind-gift="obj.blindGift"
    :bg-color="obj.bgColor"
  />
  <UScDanmaku
    v-else-if="isSuperChatProps(obj)"
    :uname="obj.uname"
    :uid="obj.uid"
    :ts="obj.ts"
    :second="obj.second"
    :face="obj.face"
    :bg-bottom-color="obj.bgBottomColor"
    :bg-color="obj.bgColor"
    :content="obj.content"
    :content-jpn="obj.contentJpn"
    :price="obj.price"
  />
  <UInteraction
    v-else-if="isInteractProps(obj)"
    :type="obj.type"
    :action="obj.action"
    :ts="obj.ts"
    :uid="obj.uid"
    :uname="obj.uname"
    :uname-color="obj.unameColor"
  />
</template>


================================================
FILE: src/components/danmaku/UWatch.vue
================================================
<script setup lang="ts">
defineProps<{
  population: string
  fans: string
}>()
</script>

<template>
  <div
    flex
    p-2
    space-x-1
    items-center
  >
    <div>人气 {{ population }}</div>
    <div flex-1 />
    <div>粉丝数 {{ fans }}</div>
  </div>
</template>



================================================
FILE: src/components/img/Avatar.vue
================================================
<script setup lang="ts">
import MyImg from './MyImg.vue'
defineProps<{
  src: string
  uid?: number
  isBlob?: boolean
}>()
</script>

<template>
  <MyImg :src="src" :uid="uid" :is-blob="isBlob" rounded-full shadow-md err-src="/noface.gif" />
</template>



================================================
FILE: src/components/img/MyImg.vue
================================================
<script setup lang="ts">
// import { readBinaryFile } from '@tauri-apps/api/fs'
import { ref, watch } from 'vue'
import { processImgUrl2 } from '~/composables/fetchImgFromBackend'

const props = withDefaults(defineProps<{
  src: string
  errSrc?: string
  uid?: number
  isBlob?: boolean
}>(), {
  errSrc: '/noface.gif',
  isBlob: false,
})

const realSrc = ref(props.errSrc)

function loadImage() {
  if (props.src.trim() === '')
    return
  if (props.isBlob) {
    realSrc.value = props.src
    return
  }
  processImgUrl2(props.src, props.uid)
    .then(({ blob }) => {
      realSrc.value = blob
    })
}

loadImage()

watch(
  () => props.src,
  loadImage,
)

const onError = () => {
  realSrc.value = props.errSrc
}
</script>

<template>
  <img :loading="errSrc" :src="realSrc" @error="onError">
</template>


================================================
FILE: src/components/img/MyQrCode.vue
================================================
<script setup lang="ts">
import { useQRCode } from '@vueuse/integrations/useQRCode'

const props = defineProps<{
  url: string
}>()

const emits = defineEmits(['close'])

const qrcode = useQRCode(props.url)
</script>

<template>
  <div shadow-lg p-4 bg="white dark:#121212" rounded space-y-2>
    <div absolute right-1 top-1 i-ri-close-line icon-btn text-lg @click="emits('close')" />
    <img :src="qrcode" ma>
    <div>请使用 bilibili 手机客户端扫码</div>
  </div>
</template>


================================================
FILE: src/components/send/UMessageSender.vue
================================================
<script setup lang="ts">
import { inject, ref } from 'vue'
import { sendMsg } from '~/composables/msgSend'
import UInputBtn from '~/components/ui/UInputBtn.vue'
import { useStore } from '~/stores/store'
import { msgKey } from '~/composables/injectionKeys'

withDefaults(defineProps<{
  noBorder?: boolean
}>(), {
  noBorder: false,
})

const msg = ref('')
const btnDisabled = ref(false)
const msgRef = inject(msgKey)
const store = useStore()

const sendMessage = () => {
  if (msg.value.trim() === '') {
    msgRef?.value.pushMsg('发送的消息不能为空!', {
      type: 'warning',
    })
    return
  }
  try {
    btnDisabled.value = true
    sendMsg(msg.value)
    btnDisabled.value = false
    msg.value = ''
  }
  catch (e) {
    msgRef?.value.pushMsg('消息发送失败!请重新登录!', {
      type: 'error',
    })
  }
}
</script>

<template>
  <UInputBtn
    v-model="msg"
    placeholder="Ctrl + Enter 发送"
    :btn-disabled="btnDisabled || !store.getUserInfo.mid || msg.trim() === ''"
    :no-border="noBorder"
    @click-btn="sendMessage"
  >
    发送
  </UInputBtn>
</template>


================================================
FILE: src/components/settings/Login.vue
================================================
<script setup lang="ts">
import { fetch } from '@tauri-apps/api/http'
import { confirm } from '@tauri-apps/api/dialog'
import { inject, ref } from 'vue'
import MyQrCode from '~/components/img/MyQrCode.vue'
import Avatar from '~/components/img/Avatar.vue'
import { clearLoop, createLoginLoop, interval } from '~/composables/loginLoop'
import logoutAccount from '~/composables/logout'
import { qrcodeGet } from '~/composables/api'
import { useStore } from '~/stores/store'
import { msgKey } from '~/composables/injectionKeys'

const store = useStore()
const msgRef = inject(msgKey)

interface QrProps {
  url: string
  oauthKey: string
}

const getQrcodeEnabled = ref(true)
const qrurl = ref('')

// const interval = computed(() => interval.value !== undefined)

const login = async () => {
  getQrcodeEnabled.value = false
  const { data: { data } }: { data: { data: QrProps } } = await fetch(qrcodeGet, { method: 'GET', timeout: 5000 })
  // // eslint-disable-next-line no-console
  // console.log(data)
  getQrcodeEnabled.value = true

  qrurl.value = data.url
  store.userInfo.oauthKey = data.oauthKey

  const success = await createLoginLoop(data.oauthKey)
  if (success)
    msgRef?.value.pushMsg('登录成功!', { type: 'success' })
  msgRef?.value.pushMsg('若头像信息未更新,可点击按钮刷新', { type: 'info' })
}

const cancelLogin = () => {
  clearLoop()
}

const logout = async () => {
  const confirmed = await confirm('确定要退出登录吗?', { title: '退出登录', type: 'warning' })
  if (confirmed) {
    const resData = await logoutAccount() as any
    if (resData.code === 0) {
      store.removeUserInfo()
      msgRef?.value.pushMsg('退出成功', { type: 'success' })
      store.config.autoReply = false
      store.config.canSendMessage = false
    }
    else {
      msgRef?.value.pushMsg('退出失败', { type: 'error' })
    }
  }
}

const refreshLogin = (event: Event) => {
  location.reload();
  (event.target as HTMLElement).classList.toggle('animate-spin')
  setTimeout(() => {
    (event.target as HTMLElement).classList.toggle('animate-spin')
  }, 1000)
}
</script>

<template>
  <div flex space-x-2 items-center>
    <Avatar w-3rem h-3rem :src="store.getUserInfo.avatarUrl || ''" :uid="store.getUserInfo.mid" />
    <div flex-1>
      <div v-if="!store.getUserInfo.mid" flex>
        <div space-x-2 flex items-center>
          <button btn rounded :disabled="!getQrcodeEnabled" @click="login">
            {{ interval ? '刷新' : '登录' }}
          </button>
          <div i-ri-refresh-line icon-btn @click="refreshLogin" />
        </div>
        <div
          v-if="interval" absolute z-998 fixed
          left-0 top-0 bottom-0 right-0
          flex items-center justify-center
          bg="white/80 dark:black/60"
        >
          <MyQrCode absolute :url="qrurl" @close="cancelLogin" />
        </div>
      </div>
      <div v-else>
        <div>
          {{ store.getUserInfo.mname }}
        </div>
        <div>已登录</div>
      </div>
    </div>
    <button v-if="store.getUserInfo.mid" btn rounded @click="logout">
      退出登录
    </button>
  </div>
</template>


================================================
FILE: src/components/superchat/UScDanmaku.vue
================================================
<script setup lang="ts">
import { computed, inject, ref } from 'vue'
import Avatar from '~/components/img/Avatar.vue'
import { getAvatar2 } from '~/composables/getAvatar'
import { msgKey } from '~/composables/injectionKeys'
import { useStore } from '~/stores/store'

import { LIGHTNESS_LIMIT, getLightnessFromHex } from '~/composables/randomColor'

const props = defineProps<{
  uname: string
  content: string
  contentJpn: string
  face: string
  price: number
  ts: number
  uid: number
  bgBottomColor: string
  bgColor: string
  second: number
}>()

const store = useStore()
const faceUrl = ref(props.face)
const msgRef = inject(msgKey)
const urlIsBlob = ref(false)
const lang = ref(store.config.scLang)
const showToggleLang = computed(() => props.contentJpn.trim() !== '')

function toggleLang() {
  if (lang.value === 'zh-cn')
    lang.value = 'ja-jp'
  else
    lang.value = 'zh-cn'
}

if (props.face === '') {
  getAvatar2(props.uid)
    .then(({ url, isBlob }) => {
      faceUrl.value = url
      urlIsBlob.value = isBlob
    })
    .catch(() => {
      msgRef?.value.pushMsg('头像获取失败', { type: 'error' })
    })
}
</script>

<template>
  <div w-full rounded>
    <div
      :style="{
        backgroundColor: bgColor,
        color: getLightnessFromHex(bgColor) > LIGHTNESS_LIMIT ? '#000' : '#fff',
      }"
      flex space-x-2 p-2 rounded-t
    >
      <Avatar w-3rem h-3rem :src="faceUrl" :uid="uid" :is-blob="urlIsBlob" />
      <div flex-1>
        <div font-bold text-lg text-shadow-none>
          {{ uname }}
        </div>
        <div text="sm" text-shadow-none>
          ¥{{ price / 1000 }}
        </div>
      </div>
      <div v-if="showToggleLang" icon-btn i-ri-translate-2 @click="toggleLang" />
    </div>
    <div
      :style="{
        backgroundColor: bgBottomColor,
        color: getLightnessFromHex(bgBottomColor) > LIGHTNESS_LIMIT ? '#000' : '#fff',
      }"
      p-2 rounded-b break-words
    >
      {{ lang === 'zh-cn' ? content : (contentJpn.trim() !== '' ? contentJpn : content) }}
    </div>
  </div>
</template>


================================================
FILE: src/components/superchat/USuperChatFloat.vue
================================================
<script setup lang="ts">
import { computed, inject, ref } from 'vue'
import Avatar from '~/components/img/Avatar.vue'
import { getAvatar2 } from '~/composables/getAvatar'
import { msgKey } from '~/composables/injectionKeys'
import { LIGHTNESS_LIMIT, getLightnessFromHex } from '~/composables/randomColor'
import { useStore } from '~/stores/store'

const props = defineProps<{
  uname: string
  content: string
  contentJpn: string
  face: string
  price: number
  ts: number
  uid: number
  bgBottomColor: string
  bgColor: string
}>()

const store = useStore()
const lang = ref(store.config.scLang)
const showToggleLang = computed(() => props.contentJpn.trim() !== '')

function toggleLang() {
  if (lang.value === 'zh-cn')
    lang.value = 'ja-jp'
  else
    lang.value = 'zh-cn'
}

const faceUrl = ref(props.face)
const msgRef = inject(msgKey)
const urlIsBlob = ref(false)

if (props.face === '') {
  getAvatar2(props.uid)
    .then(({ url, isBlob }) => {
      faceUrl.value = url
      urlIsBlob.value = isBlob
    })
    .catch(() => {
      msgRef?.value.pushMsg('头像获取失败', { type: 'error' })
    })
}
// console.log(getLightnessFromRgb(props.bgBottomColor), getLightnessFromRgb(props.bgColor))
</script>

<template>
  <div w-full rounded text-white>
    <div
      flex items-center shadow space-x-2 p-2 rounded-t
      :style="{
        backgroundColor: bgColor,
        color: getLightnessFromHex(bgColor) > LIGHTNESS_LIMIT ? '#000' : '#fff',
      }"
    >
      <Avatar :src="faceUrl" :uid="uid" class="w-1.5rem h-1.5rem" />
      <div flex-1 text-shadow-none>
        {{ uname }}
      </div>
      <div text-shadow-none>
        ¥{{ price / 1000 }}
      </div>
      <div v-if="showToggleLang" icon-btn i-ri-translate-2 @click="toggleLang" />
    </div>
    <div
      p-2 rounded-b break-words
      :style="{
        backgroundColor: bgBottomColor,
        color: getLightnessFromHex(bgBottomColor) > LIGHTNESS_LIMIT ? '#000' : '#fff',
      }"
    >
      {{ lang === 'zh-cn' ? content : (contentJpn.trim() !== '' ? contentJpn : content) }}
    </div>
  </div>
</template>


================================================
FILE: src/components/superchat/USuperChatPool.vue
================================================
<script setup lang="ts">
import { useVModel } from '@vueuse/core'
import USuperChat from './USuperChatFloat.vue'
import USuperChatTag from './USuperChatTag.vue'
import type { SuperChatProps } from '~/composables/components'
import { chatPool } from '~/composables/server'

const props = defineProps<{
  chatPool: Array<SuperChatProps>
  modelValue: SuperChatProps | null
}>()

const emits = defineEmits(['update:modelValue'])

const sc = useVModel(props, 'modelValue', emits)

const clickSuperChat = (currentSc: SuperChatProps) => {
  if (sc.value?.ts === currentSc.ts)
    sc.value = null

  else
    sc.value = currentSc
}
</script>

<template>
  <div space-y-1 p-1>
    <div
      flex of-x-auto
      space-x-2
    >
      <USuperChatTag
        v-for="it in chatPool" :key="it.ts"
        :face="it.face"
        :uid="it.uid"
        :price="it.price"
        :color="it.bgBottomColor"
        :second="it.second"
        :ts="it.ts"
        cursor-pointer
        @click="clickSuperChat(it)"
      />
    </div>
    <USuperChat
      v-if="sc"
      :ts="sc.ts"
      :uname="sc.uname"
      :content="sc.content"
      :content-jpn="sc.contentJpn"
      :face="sc.face"
      :price="sc.price"
      :uid="sc.uid"
      :bg-bottom-color="sc.bgBottomColor"
      :bg-color="sc.bgColor"
    />
  </div>
</template>

<style scoped>
::-webkit-scrollbar {
  width: 0px;
  height: 0px;
}
</style>


================================================
FILE: src/components/superchat/USuperChatTag.vue
================================================
<script setup lang="ts">
import { useIntervalFn } from '@vueuse/core'
import { inject, ref, watchEffect } from 'vue'
import Avatar from '~/components/img/Avatar.vue'
import { getAvatar2 } from '~/composables/getAvatar'
import { msgKey } from '~/composables/injectionKeys'
import { LIGHTNESS_LIMIT, getLightnessFromHex } from '~/composables/randomColor'

const props = defineProps<{
  face: string
  price: number
  color: string
  second: number
  uid: number
  ts: number
}>()

const timestamp = ref(Date.now())
const color2 = `${props.color}7f` // rgbAppendAlpha(props.color)

const { pause } = useIntervalFn(() => {
  timestamp.value = Date.now()
}, 1000)

watchEffect(() => {
  if (timestamp.value - props.ts > props.second * 1000)
    pause()
})

const faceUrl = ref(props.face)
const msgRef = inject(msgKey)
const urlIsBlob = ref(false)

if (props.face === '') {
  getAvatar2(props.uid)
    .then(({ url, isBlob }) => {
      faceUrl.value = url
      urlIsBlob.value = isBlob
    })
    .catch(() => {
      msgRef?.value.pushMsg('头像获取失败', { type: 'error' })
    })
}
</script>

<template>
  <div
    rounded-full
    inline-flex flex-shrink-0 items-center
    :style="{
      background: `linear-gradient(to right, ${color}, ${color} ${100 - (timestamp - ts) / 10 / second}%, ${color2}  ${100 - (timestamp - ts) / 10 / second + 5}%, ${color2})`,
      color: getLightnessFromHex(color) > LIGHTNESS_LIMIT ? '#000' : '#fff',
    }"
    p="0.75" pr-2 text-white space-x="0.5"
  >
    <Avatar :src="faceUrl" :uid="uid" class="w-1.25rem h-1.25rem" />
    <div text="sm amber">
      ¥{{ price / 1000 }}
    </div>
  </div>
</template>


================================================
FILE: src/components/ui/UBlackList.vue
================================================
<script setup lang="ts">
import { inject } from 'vue'
import UTag from './UTag.vue'
import { useStore } from '~/stores/store'
import { msgKey } from '~/composables/injectionKeys'
const emits = defineEmits(['settingsChanged'])
const store = useStore()
const msgRef = inject(msgKey)

function pushItem(event: Event) {
  const uid = Number((event.target as HTMLInputElement).value.trim())
  if (!isNaN(uid) && !store.getConfig.blackList.includes(uid)) {
    store.config.blackList.push(uid)
    emits('settingsChanged')
  }
  else {
    msgRef?.value.pushMsg('该用户的 uid 已存在或不合法!', {
      type: 'warning',
    })
  }
  (event.target as HTMLInputElement).value = ''
}

function deleteItem(i: number) {
  store.config.blackList.splice(i, 1)
  emits('settingsChanged')
}
</script>

<template>
  <div>
    <span font-bold>
      黑名单
    </span>
    <span text-sm op-50>以下 uid 用户发送的弹幕将被屏蔽,右键弹幕也可将用户加入黑名单</span>
    <hr border="zinc/20" py-1>
    <div
      rounded
      flex-1
      text-sm
      border="~ zinc-300 dark:zinc-700"
      p="t-1 l-1 r"
    >
      <UTag
        v-for="(el, i) in store.getConfig.blackList" :key="el"
        :content="el.toString()"
        m="r-1 b-1"
        @close="deleteItem(i)"
      />
      <input
        leading-normal
        border="~ rounded zinc-300 dark:zinc-700"
        content-border
        class="!outline-none"
        px-2 m="r-1 b-1"
        w-8rem
        bg-transparent
        placeholder="按下回车以添加"
        @keydown.enter="pushItem"
      >
    </div>
  </div>
</template>


================================================
FILE: src/components/ui/UCheckBox.vue
================================================
<script setup lang="ts">
import { useVModel } from '@vueuse/core'

const props = withDefaults(defineProps<{
  modelValue?: boolean
  disabled?: boolean
}>(), {
  modelValue: false,
  disabled: false,
})

const emits = defineEmits(['update:modelValue'])

const checked = useVModel(props, 'modelValue', emits)
</script>

<template>
  <label
    class="inline-flex items-center leading-relaxed select-none space-x-1"
    :class="{ 'op-50 cursor-not-allowed': disabled, 'cursor-pointer': !disabled }"
    :checked="checked || null"
    :disabled="disabled || null"
  >
    <input
      v-model="checked"
      type="checkbox"
      :disabled="disabled"
      display-none
      @keypress.enter="checked = !checked"
    >
    <div flex items-center text-lg>
      <div i-ri-checkbox-blank-line icon-btn />
      <div
        i-ri-checkbox-fill text-active icon-btn absolute
        :class="{ 'scale-0': !checked }"
      />
    </div>

    <span><slot /></span>
  </label>
</template>


================================================
FILE: src/components/ui/UColorPicker.vue
================================================
<script setup lang="ts">
import { useVModel } from '@vueuse/core'

const props = withDefaults(defineProps<{
  modelValue: string
  disabled?: boolean
}>(), {
  disabled: false,
})

const emits = defineEmits(['update:modelValue'])

const value = useVModel(props, 'modelValue', emits)
</script>

<template>
  <label
    class="inline-flex items-center leading-relaxed select-none space-x-1 cursor-pointer"
    :class="{ 'op-50': disabled }"
  >
    <input v-model="value" type="color" :disabled="disabled" absolute w-1px op-0>
    <div text-lg flex items-center>
      <div i-ri-checkbox-blank-fill :style="{ color: value }" op-100 icon-btn />
      <div absolute i-ri-checkbox-blank-line icon-btn />
    </div>
    <span>
      <slot />
    </span>
  </label>
</template>


================================================
FILE: src/components/ui/UInputBtn.vue
================================================
<script setup lang="ts">
import { useVModel } from '@vueuse/core'

const props = withDefaults(defineProps<{
  modelValue: string
  inputDisabled?: boolean
  btnDisabled?: boolean
  noBorder?: boolean
  placeholder?: string
}>(), {
  inputDisabled: false,
  btnDisabled: false,
  noBorder: false,
})

const emits = defineEmits(['update:modelValue', 'clickBtn'])

const emitEvent = () => {
  emits('clickBtn')
  // (event.target as HTMLInputElement).blur()
}

const value = useVModel(props, 'modelValue', emits)
</script>

<template>
  <div rounded flex :class="{ flex: noBorder }">
    <div flex-1>
      <input
        v-model="value"
        m-input rounded-l
        py-1 px-2 w-full
        border-r-none
        :disabled="inputDisabled"
        :placeholder="placeholder"
        :class="{ 'border-none': noBorder }"
        @keydown.ctrl.enter.exact="emitEvent"
      >
    </div>
    <button
      btn
      :class="{ 'border-~ border-#646cff disabled:border-zinc-300/20': !noBorder }"
      rounded-r
      :disabled="btnDisabled"
      @click="emitEvent"
    >
      <slot />
    </button>
  </div>
</template>


================================================
FILE: src/components/ui/UMdInput.vue
================================================
<script setup lang="ts">
import { useFocus, useVModel } from '@vueuse/core'
import { computed, ref } from 'vue'

const props = withDefaults(defineProps<{
  modelValue: string
  disabled?: boolean
  title?: string
}>(), {
  disabled: false,
  title: '请输入',
})

const emits = defineEmits(['update:modelValue', 'blur'])
const value = useVModel(props, 'modelValue', emits)

const inputRef = ref<HTMLInputElement>()
const { focused } = useFocus(inputRef)
const shouldFloat = computed(() => focused.value || value.value !== '')
</script>

<template>
  <div inline-flex m="x-2 y-2">
    <input
      ref="inputRef"
      v-model="value"
      class="bg-transparent !outline-none leading-loose"
      border="2px rounded zinc-300 dark:zinc-700 focus:#646cff"
      p="x-2 y-1"
      w-15rem transition-all
      :disabled="disabled"
      @blur="emits('blur')"
    >
    <div
      absolute transition-all m="x-3 y-10px" op-50
      :class="{
        'scale-80 translate-y--20px bg-white dark:bg-#242424 leading-tight !op-100': shouldFloat,
      }"
      style="transform-origin: left"
      @click="focused = !focused"
    >
      {{ title }}
    </div>
  </div>
</template>


================================================
FILE: src/components/ui/UMessageProvider.vue
================================================
<script setup lang="ts">
import { ref } from 'vue'
import type { MessageProviderOptions } from '~/types'

interface PopMessage {
  ts: number
  content: string
  type: 'success' | 'error' | 'warning' | 'info'
}

const iconsDict = {
  success: 'i-ri-checkbox-circle-line text-green-6',
  error: 'i-ri-close-circle-line text-red-6',
  warning: 'i-ri-error-warning-line text-amber',
  info: 'i-ri-information-line text-blue',
}

const messageQueue = ref<PopMessage[]>([])

const pushMsg = (msg: string, config?: MessageProviderOptions) => {
  const ts = Date.now()
  messageQueue.value.push({
    type: config?.type || 'info',
    content: msg,
    ts,
  })

  setTimeout(() => {
    messageQueue.value.splice(messageQueue.value.findIndex(it => it.ts === ts), 1)
  }, config?.ttl || 3000)
}

defineExpose({ pushMsg })
</script>

<template>
  <TransitionGroup
    tag="div"
    name="msggroup"
    fixed left-0 right-0
    top-2rem
    flex flex-col
    pointer-events-none
    z-999
  >
    <div
      v-for="it in messageQueue" :key="it.ts"
      p="x-4 y-2" my-2 shadow-lg rounded
      ma
      bg="white !dark:zinc-900"
      flex items-center space-x-2
      class="use-dark-msg"
    >
      <div icon-btn :class="iconsDict[it.type]" /><span>{{ it.content }}</span>
    </div>
  </TransitionGroup>
</template>

<style scoped>
.msggroup-move, /* 对移动中的元素应用的过渡 */
.msggroup-enter-active,
.msggroup-leave-active {
  transition: all 0.375s ease;
}

.msggroup-enter-from,
.msggroup-leave-to {
  opacity: 0;
  transform: translateY(-30px) scale(0.01);
}

.msggroup-leave-active {
  position: absolute;
}
</style>


================================================
FILE: src/components/ui/UMultiList.vue
================================================
<script setup lang="ts">
import { confirm } from '@tauri-apps/api/dialog'
import { inject } from 'vue'
import type { Answer } from '../../composables/autoSendMsg'
import UTag from './UTag.vue'
import { useStore } from '~/stores/store'
import { msgKey } from '~/composables/injectionKeys'

const emits = defineEmits(['settingsChanged'])
const store = useStore()
const msgRef = inject(msgKey)

function pushFaq() {
  store.faqs.push({
    ts: Date.now(),
    keywords: [],
    answer: '',
  })
  emits('settingsChanged')
}

function pushKeyWord(event: Event, faq: Answer) {
  const val = (event.target as HTMLInputElement).value.trim()
  if (val === '' || faq.keywords.includes(val)) {
    msgRef?.value.pushMsg('关键词重复!', {
      type: 'warning',
    })
    return
  }

  faq.keywords.push(val);
  (event.target as HTMLInputElement).value = ''
  emits('settingsChanged')
}

async function deleteFaq(index: number) {
  const confirmed = await confirm('确定要删除这个问题吗?', {
    title: '提示', type: 'warning',
  })
  if (confirmed) {
    store.faqs.splice(index, 1)
    emits('settingsChanged')
  }
}

function answerChanged() {
  emits('settingsChanged')
}
</script>

<template>
  <div space-y-2>
    <div
      v-for="(it, index) in store.getFaqs" :key="it.ts"
      py-2 space-y-2
    >
      <div flex items-center space-x-2>
        <div font-bold>
          问题 {{ index + 1 }}
        </div>
        <div flex-1>
          <span v-if="it.answer.trim() === '' || it.keywords.length === 0" text="sm red">*问题不完整,保存时将自动删除</span>
        </div>
        <div i-ri-delete-bin-line icon-btn @click="deleteFaq(index)" />
      </div>
      <div flex space-x-2 items-center>
        <div>关键词语</div>
        <div
          rounded
          flex-1
          text-sm
          border="~ zinc-300 dark:zinc-700"
          p="t-1 l-1 r"
        >
          <UTag
            v-for="(kw, jndex) in it.keywords"
            :key="kw"
            m="r-1 b-1"
            :content="kw"
            @close="it.keywords.splice(jndex, 1)"
          />
          <input
            leading-normal
            border="~ rounded zinc-300 dark:zinc-700"
            content-border
            class="!outline-none"
            px-2 m="r-1 b-1"
            w-8rem
            bg-transparent
            placeholder="按下回车以添加"
            @keydown.enter="pushKeyWord($event, it)"
          >
        </div>
      </div>
      <div flex space-x-2 items-center>
        <div>自动回复</div>
        <input
          v-model="it.answer"
          m-input rounded flex-1 text-sm
          @input="answerChanged"
        >
        <span text="sm zinc" absolute right-6>
          {{ it.answer.length <= 20 ? `${it.answer.length}/20` : '过长的消息将会分条发送' }}
        </span>
      </div>
    </div>
    <button
      flex space-x-2 items-center justify-center
      py-1
      border="~ rounded dashed zinc-300 dark:zinc-600 hover:#646cff"
      block w-full
      class="hover:text-#646cff"
      transition
      @click="pushFaq"
    >
      <div i-ri-add-line /> 添加
    </button>
  </div>
</template>


================================================
FILE: src/components/ui/URadio.vue
================================================
<script setup lang="ts">
import { useVModel } from '@vueuse/core'

const props = withDefaults(defineProps<{
  modelValue?: string
  disabled?: boolean
  name?: string
  value?: string
}>(), {
  disabled: false,
  modelValue: '',
})

const emits = defineEmits(['update:modelValue'])

const model = useVModel(props, 'modelValue', emits)
</script>

<template>
  <label
    class="inline-flex items-center leading-relaxed select-none space-x-1 cursor-pointer"
    :class="{ 'op-50': disabled }"
    :checked="model === value || null"
    :disabled="disabled || null"
  >
    <input
      v-model="model"
      type="radio"
      :value="value"
      :name="name"
      :disabled="disabled"
      display-none
    >
    <div flex items-center text-lg>
      <div i-ri-checkbox-blank-circle-line icon-btn />
      <div
        i-ri-radio-button-line text-active icon-btn absolute
        :class="{ 'scale-0': model !== value }"
      />
    </div>
    <span><slot /></span>
  </label>
</template>


================================================
FILE: src/components/ui/USelector.vue
================================================
<script setup lang="ts">
import { useVModel } from '@vueuse/core'
const props = withDefaults(defineProps<{
  options?: Array<{ label: string; value: number }>
  modelValue?: number
}>(), {
  options: () => [],
  modelValue: 0,
})

const emits = defineEmits(['update:modelValue'])

const value = useVModel(props, 'modelValue', emits)
</script>

<template>
  <div flex items-center>
    <label
      flex="~" items-center absolute
      border="~ zinc rounded"
    >
      <select
        v-model="value"
        bg="transparent"
        appearance="none"
        outline="!none"
        transition-all
        flex-1
        p="l-1 r-6"
      >
        <option v-for="o in options" :key="o.value" :value="o.value">
          {{ o.label }}
        </option>
      </select>
      <div i-ri-arrow-down-s-line absolute right-0 pointer-events="none" />
    </label>
  </div>
</template>


================================================
FILE: src/components/ui/USettingsBox.vue
================================================
<script setup lang="ts">
defineProps<{ title: string }>()
</script>

<template>
  <div>
    <div font-bold>
      {{ title }}
    </div>
    <hr border="zinc/20" py-1>
    <div grid grid-cols-3>
      <slot />
    </div>
  </div>
</template>


================================================
FILE: src/components/ui/USlider.vue
================================================
<script setup lang="ts">
import { useVModel } from '@vueuse/core'

const props = withDefaults(defineProps<{
  modelValue?: string
  disabled?: boolean
  minValue?: number
  maxValue?: number
}>(), {
  modelValue: '0',
  disabled: false,
  minValue: 0,
  maxValue: 100,
})

const emits = defineEmits(['update:modelValue'])

const value = useVModel(props, 'modelValue', emits)
</script>

<template>
  <input v-model="value" inline-block type="range" :min="minValue" :max="maxValue" class="disabled:grayscale">
</template>

<style scoped>
[type="range"] {
    -webkit-appearance: none;
    appearance: none;
    margin: 0;
    outline: 0;
    background-color: transparent;
}
[type="range"]::-webkit-slider-runnable-track {
    height: 4px;
    background: #7f7f7f10;
}
[type="range" i]::-webkit-slider-container {
    height: 20px;
    overflow: hidden;
}
[type="range"]::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background-color: #646cff;
    border: 1px solid transparent;
    margin-top: -8px;
    border-image: linear-gradient(#646cff,#646cff) 0 fill / 8 20 8 0 / 0px 0px 0 2000px;
}
</style>


================================================
FILE: src/components/ui/USwitch.vue
================================================
<script setup lang="ts">
import { useVModel } from '@vueuse/core'

const props = withDefaults(defineProps<{
  modelValue?: boolean
  disabled?: boolean
}>(), {
  modelValue: false,
  disabled: false,
})

const emits = defineEmits(['update:modelValue'])

const checked = useVModel(props, 'modelValue', emits)

const toggleChecked = () => {
  if (!props.disabled)
    checked.value = !checked.value
}
</script>

<template>
  <div
    flex items-center cursor-pointer leading-relaxed
    :class="{ 'opacity-50': disabled }"
    @click="toggleChecked"
  >
    <div
      class="w-2rem h-1.2rem mx-1 bg-opacity-20"
      flex items-center
      rounded-full transition-all
      :class="{
        'bg-#646cff': checked,
        'bg-zinc': !checked,
      }"
    >
      <div
        class="w-1rem h-1rem ml-0.1rem"
        rounded-full border-transparent transition-all
        :class="{
          'ml-0.9rem bg-#646cff shadow': checked,
          'bg-white dark:bg-zinc-500': !checked,
        }"
      />
    </div>
    <span><slot /></span>
  </div>
</template>


================================================
FILE: src/components/ui/UTabSelector.vue
================================================
<script setup lang="ts">
import { onClickOutside, useVModels } from '@vueuse/core'
import { ref } from 'vue'
import { useStore } from '~/stores/store'

const props = defineProps<{
  id: number
  info: string
}>()

const emits = defineEmits(['update:id', 'update:info', 'close'])

const { id, info } = useVModels(props, emits)

const store = useStore()

const currentTab = ref(0)
const currentPage = ref(0)
const dialog = ref<HTMLElement>()

function tabChanged(i: number) {
  currentTab.value = i
  currentPage.value = 0
}

function select(id2: string, area2: string) {
  id.value = parseInt(id2)
  info.value = `${store.liveConfig.liveAreaList[currentTab.value].name} · ${area2}`
}

onClickOutside(dialog, () => {
  emits('close')
})
</script>

<template>
  <div
    fixed
    left-0 top-0 bottom-0 right-0
    flex items-center justify-center
    bg="white/80 dark:black/60"
  >
    <div
      ref="dialog" w-40rem
      h-13rem
      p-6
      shadow absolute
      bg="white dark:#242424"
    >
      <div
        icon-btn absolute top-2 right-2
        i-ri-close-line
        @click="emits('close')"
      />
      <div flex justify-between>
        <button
          v-for="(it, i) in store.liveConfig.liveAreaList"
          :key="it.id"
          :class="{
            'text-#646cff': currentTab === i,
          }"
          icon-btn m="x-2 y-1"
          @click="tabChanged(i)"
        >
          {{ it.name }}
        </button>
      </div>
      <div grid grid-cols-5 text-center place-items-center>
        <button
          v-for="jt in store.liveConfig.liveAreaList[currentTab].list.slice(currentPage * 20, currentPage * 20 + 20)"
          :key="jt.id"
          :title="jt.name"
          icon-btn
          truncate px-4
          w-7rem mb-1
          border="~ zinc-300 dark:zinc-700"
          rounded-full
          @click="select(jt.id, jt.name)"
        >
          {{ jt.name }}
        </button>
      </div>
      <div v-if="store.liveConfig.liveAreaList[currentTab].list.length > 20" flex justify-center>
        <button
          v-for="j in Math.ceil(store.liveConfig.liveAreaList[currentTab].list.length / 20)" :key="j"
          icon-btn
          :class="{ 'text-#646cff': currentPage === j - 1 }"
          m="x-2 y-1"
          @click="currentPage = j - 1"
        >
          {{ j }}
        </button>
      </div>
    </div>
  </div>
</template>


================================================
FILE: src/components/ui/UTag.vue
================================================
<script setup lang="ts">
defineProps<{
  content: string
}>()

const emits = defineEmits(['close'])
</script>

<template>
  <div
    inline-flex
    items-center
    border="~ rounded zinc-300 dark:zinc-700"
    leading-normal
    p="x-2"
    space-x-1
  >
    <span pl-1>{{ content }}</span>
    <div icon-btn text-sm i-ri-close-line @click="emits('close')" />
  </div>
</template>


================================================
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<Answer, 'ts'>) {
  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<any>,
  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<Ref<typeof UMessageProvider>> = 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<NodeJS.Timer>()

const clearLoop = () => {
  if (interval.value) {
    clearInterval(interval.value)
    interval.value = undefined
  }
}

async function createLoginLoop(oauthKey: string): Promise<boolean> {
  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<Array<DanmakuProps | GiftProps | SuperChatProps | InteractProps>>([])
const selectedSc = ref<SuperChatProps | null>(null)
const chatPool = ref<Array<SuperChatProps>>([])
const enterQueue = ref<InteractProps[]>([])

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<any>,
    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
================================================
<script setup lang="ts">
import { listen } from '@tauri-apps/api/event'
import { tryOnBeforeUnmount } from '@vueuse/core'
import SideBar from '~/components/SideBar.vue'
import { useStore } from '~/stores/store'

const store = useStore()
const unlistens: Function[] = []

async function unlistenAdd() {
  unlistens.push(await listen('add-black', (event) => {
    const uid = parseInt(event.payload as string)
    if (!store.config.blackList.includes(uid)) {
      store.config.blackList.push(uid)
      store.settingsSaved = false
    }
  }))
}

unlistenAdd()

tryOnBeforeUnmount(() => {
  unlistens.map(fn => fn())
})
</script>

<template>
  <div class="use-dark">
    <SideBar />
    <div ml-2rem flex-1>
      <RouterView />
    </div>
  </div>
</template>


================================================
FILE: src/layouts/none.vue
================================================
<script setup lang="ts">

</script>

<template>
  <RouterView />
</template>


================================================
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
================================================
<script setup lang="ts">
import { WebviewWindow } from '@tauri-apps/api/window'
import { invoke } from '@tauri-apps/api/tauri'
import { useStorage, useThrottleFn } from '@vueuse/core'
import type { Ref } from 'vue'
import { inject, ref } from 'vue'
import UMdInput from '~/components/ui/UMdInput.vue'
import UCheckBox from '~/components/ui/UCheckBox.vue'
import { shortToLong } from '~/composables/shortIdToLong'
import { useStore } from '~/stores/store'
import { eventEmitter } from '~/composables/eventEmitter'
import { usePosition } from '~/stores/position'
import { loadPos } from '~/composables/load_pos'
import { msgKey } from '~/composables/injectionKeys'
import type { MessageProvider } from '~/types'

const roomId = useStorage('roomId', '')

let webview: WebviewWindow | null = null
const msgRef = inject<Ref<MessageProvider>>(msgKey)
const store = useStore()
const isLoadingRoomId = ref(false)
const pos = usePosition()

async function createWebview() {
  if (roomId.value.trim() === '') {
    msgRef?.value.pushMsg('房间号不能为空!', {
      type: 'warning',
    })
    return
  }
  webview = WebviewWindow.getByLabel('danmakuWidget')
  if (webview) {
    webview.close()
    webview = null
    store.linked = false
    // eslint-disable-next-line no-console
    console.log('关闭窗口')
    const senderWindow = WebviewWindow.getByLabel('senderWindow')
    if (senderWindow)
      senderWindow.close()

    store.clickThrough = false

    return
  }

  await invoke('create_new_danmaku_view')

  store.linked = true
  msgRef?.value.pushMsg('窗口已开启')
}

function tryToCloseDanmaku() {
  webview = WebviewWindow.getByLabel('danmakuWidget')
  if (!webview) {
    webview = new WebviewWindow('danmakuWidget', {
      url: '/show',
      decorations: false,
      width: 400,
      height: 600,
      transparent: true,
      alwaysOnTop: true,
      title: 'D4nm4ku',
      minWidth: 320,
      minHeight: 150,
    })
  }
  if (webview) {
    webview.close()
    webview = null
    store.linked = false
    // eslint-disable-next-line no-console
    console.log('关闭窗口')
  }
}

function roomIdBlured() {
  if (roomId.value.trim() === '')
    return
  const fakeId = Number(roomId.value)
  if (fakeId <= 1000 && fakeId > 0) {
    isLoadingRoomId.value = true
    shortToLong(fakeId)
      .then((id) => {
        roomId.value = String(id)
      })
      .catch((err) => {
        msgRef?.value.pushMsg(err.message, {
          type: 'error',
        })
      })
      .finally(() => {
        isLoadingRoomId.value = false
      })
  }
}

async function setClickThrough() {
  if (store.clickThrough) {
    store.previousCanSend = store.config.canSendMessage
    if (store.config.canSendMessage) {
      eventEmitter('can-send-message', false)
      openSenderWindow()
    }
  }
  else {
    store.config.canSendMessage = store.previousCanSend
    if (store.previousCanSend) {
      eventEmitter('can-send-message', store.config.canSendMessage)
      openSenderWindow()
    }
  }

  // eventEmitter('set-click-through', store.clickThrough)
  const res: boolean = await invoke('set_click_through', { enable: store.clickThrough })
  msgRef?.value.pushMsg(`点击穿透功能已${res ? '开启' : '关闭'}`)
}

async function openSenderWindow() {
  if (!store.getUserInfo.mid) {
    msgRef?.value.pushMsg('发送弹幕需要登录')
    return
  }
  let senderWindow = WebviewWindow.getByLabel('senderWindow')
  if (senderWindow) {
    store.senderEnabled = false
    senderWindow.close()
    senderWindow = null
    return
  }

  await invoke('create_sender_window')
  store.senderEnabled = true
  msgRef?.value.pushMsg('弹幕发送浮窗已开启')
}

const pinned = ref(true)
const pinWidget = () => {
  const danmakuWidget = WebviewWindow.getByLabel('danmakuWidget')
  if (danmakuWidget)
    danmakuWidget.setAlwaysOnTop(pinned.value)
}

const storePosition = useThrottleFn(() => {
  pos.storeConfig()
    .then(() => {
      msgRef?.value.pushMsg('保存成功', { type: 'success' })
    })
    .catch((err) => {
      msgRef?.value.pushMsg(`保存失败, ${err.message}`, { type: 'error' })
    })
})

const loadPosition = useThrottleFn(() => {
  const conf = pos.getConfig()
  loadPos(conf)
    .then(() => {
      msgRef?.value.pushMsg('加载成功', { type: 'success' })
    })
    .catch((err) => {
      msgRef?.value.pushMsg(`加载失败, ${err.message}`, { type: 'error' })
    })
})
</script>

<template>
  <div h-100vh flex flex-col>
    <div flex-1 flex justify-center>
      <div self-end text-2xl>
        D4nm4ku
      </div>
    </div>
    <div flex items-center>
      <div flex-1 />
      <UMdInput
        v-model="roomId"
        title="直播间号"
        :disabled="store.linked"
        @blur="roomIdBlured"
      />
      <div flex-1>
        <button
          p-2 m-2
          bg="#646cff"
          rounded-full
          shadow hover:shadow-lg
          op="90 hover:100"
          text-white
          cursor-pointer
          class="disabled:bg-zinc disabled:dark:bg-zinc-600 disabled:dark:text-zinc-800 disabled:cursor-not-allowed"
          :disabled="!roomId.trim().match(/^\d+$/) || isLoadingRoomId"
          @click="createWebview"
        >
          <div v-if="isLoadingRoomId" i-ri-refresh-line animate-spin />
          <div v-else-if="!store.linked" i-ri-arrow-right-line />
          <div v-else i-ri-stop-fill />
        </button>
      </div>
    </div>
    <div flex-1 flex flex-col>
      <div flex>
        <div flex-1 />
        <div flex flex-col>
          <UCheckBox
            v-model="pinned"
            @update:model-value="pinWidget"
          >
            窗口置顶
          </UCheckBox>
          <UCheckBox
            v-model="store.clickThrough"
            title="开启点击穿透后 弹幕窗口将不接受任何鼠标消息"
            :disabled="!store.linked"
            @update:model-value="setClickThrough"
          >
            点击穿透(仅 macOS)
          </UCheckBox>
          <div
            inline-flex items-center leading-relaxed select-none space-x-1 cursor-pointer
            title="开启额外浮动窗口发送弹幕"
            @click="openSenderWindow"
          >
            <div text-lg flex items-center>
              <div icon-btn i-ri-window-line ml-1 />
            </div>
            <span>打开/关闭弹幕发送浮窗</span>
          </div>
          <div inline-flex items-center leading-relaxed select-none space-x-1>
            <div text-lg flex items-center>
              <div icon-btn i-ri-save-line ml-1 />
            </div>
            <div>
              <button text-btn :disabled="!store.linked" @click="storePosition">
                保存
              </button>/<button :disabled="!store.linked" text-btn @click="loadPosition">
                加载
              </button>窗口大小和位置
            </div>
          </div>
        </div>
        <div flex-1 />
      </div>
      <div flex-1 />
      <div mx-a my-2 i-ri-stop-circle-line icon-btn op="10 hover:100" title="应急关闭" @click="tryToCloseDanmaku" />
    </div>
  </div>
</template>


================================================
FILE: src/pages/live.vue
================================================
<script setup lang="ts">
import { useClipboard, useStorage } from '@vueuse/core'
import type { Ref } from 'vue'
import { inject, ref } from 'vue'
import { getAreaInfoList, startLive, stopLive, updateLiveTitle } from '~/composables/openLive'
import { getLiveRoomInfoFromRoomId, getLiveRoomInfoFromUid } from '~/composables/getLiverInfo'
import { useStore } from '~/stores/store'
import UMdInput from '~/components/ui/UMdInput.vue'
import UTabSelector from '~/components/ui/UTabSelector.vue'
import { shortToLong } from '~/composables/shortIdToLong'
import type { MessageProvider } from '~/types'
import { msgKey } from '~/composables/injectionKeys'

const store = useStore()
const roomId2 = useStorage('roomId2', '')
const selectedAreaId = useStorage('selectedAreaId', 0)
const selectedAreaInfo = useStorage('selectedAreaInfo', '')
const liveTitle = useStorage('liveTitle', '')
const msgRef = inject<Ref<MessageProvider>>(msgKey)
const isShowAreaSelection = ref(false)
const btnEnabled = ref(true)
const firstLoad = ref(0)
const btnUpdateTitleEnabled = ref(true)
const btnShowAreaEnabled = ref(true)

const { copy } = useClipboard()

if (!store.getUserInfo.mid)
  msgRef?.value.pushMsg('需要登录才能开启直播哦')

function updateLiveRoomInfo() {
  if (roomId2.value.trim() === '' || liveTitle.value.trim() === '') {
    getLiveRoomInfoFromUid(store.getUserInfo.mid)
      .then(({ roomid, title }) => {
        roomId2.value = roomid.toString()
        liveTitle.value = title
        return roomid
      })
      .catch((err) => {
        msgRef?.value.pushMsg(`直播间信息获取失败!${err.message}`, {
          type: 'error',
        })
      })
  }
  // 当前如果是开播的状态,但是主播可能手动关闭了弹幕姬,导致弹幕姬只有开播按钮
  // 因此自动检测当前是否在开播状态,如果是,则自动变更按钮
  if (!store.liveConfig.isLive && roomId2.value.trim() !== '' && liveTitle.value.trim() !== '' && selectedAreaId.value) {
    getLiveRoomInfoFromRoomId(parseInt(roomId2.value))
      .then(({ data }) => {
        store.liveConfig.isLive = data.live_status === 1
      })
      .catch((err) => {
        msgRef?.value.pushMsg(err.message, {
          type: 'error',
        })
      })
  }
}

if (store.getUserInfo.mid)
  updateLiveRoomInfo()

function updateLiveTitle2() {
  btnUpdateTitleEnabled.value = false
  updateLiveTitle(roomId2.value, liveTitle.value)
    .then(() => {
      msgRef?.value.pushMsg('标题修改成功', {
        type: 'success',
      })
    })
    .catch((e: Error) => {
      msgRef?.value.pushMsg(
        e.message,
        { type: 'error' },
      )
    })
    .finally(() => {
      btnUpdateTitleEnabled.value = true
    })
}

function showAreaSelection() {
  btnShowAreaEnabled.value = false
  if (firstLoad.value === 0) {
    msgRef?.value.pushMsg('首次加载可能需要一段时间')
    firstLoad.value++
  }
  getAreaInfoList()
    .then(() => {
      isShowAreaSelection.value = !isShowAreaSelection.value
      btnShowAreaEnabled.value = true
    })
}

function startLive2() {
  btnEnabled.value = false
  startLive(roomId2.value, selectedAreaId.value, 'pc')
    .then((rtmp) => {
      store.liveConfig.addr = rtmp.addr
      store.liveConfig.code = rtmp.code
      msgRef?.value.pushMsg('直播开启成功', {
        type: 'success',
      })
      msgRef?.value.pushMsg('请将串流地址和密钥复制到直播软件(如 OBS)后开启推流', {
        ttl: 6000,
      })
      store.liveConfig.isLive = true
    })
    .catch((e: Error) => {
      msgRef?.value.pushMsg(
        e.message,
        { type: 'error' },
      )
    })
    .finally(() => {
      btnEnabled.value = true
    })
}

function stopLive2() {
  btnEnabled.value = false
  stopLive(roomId2.value)
    .then(() => {
      msgRef?.value.pushMsg('直播关闭成功', {
        type: 'success',
      })
      store.liveConfig.addr = ''
      store.liveConfig.code = ''
      store.liveConfig.isLive = false
    })
    .catch((e: Error) => {
      msgRef?.value.pushMsg(
        e.message,
        { type: 'error' },
      )
    }).finally(() => {
      btnEnabled.value = true
    })
}

function copy2(source: string) {
  copy(source)
  msgRef?.value.pushMsg('复制成功', {
    type: 'success',
  })
}

const loadingRoomId = ref(false)

function roomIdBlur() {
  if (roomId2.value.trim() === '')
    return

  const fakeId = Number(roomId2.value)
  if (fakeId <= 1000 && fakeId > 0) {
    loadingRoomId.value = true
    shortToLong(fakeId)
      .then((id) => {
        roomId2.value = String(id)
      })
      .catch((err) => {
        msgRef?.value.pushMsg(err.message, {
          type: 'error',
        })
      })
      .finally(() => {
        loadingRoomId.value = false
      })
  }
}
</script>

<template>
  <div h-100vh flex flex-col>
    <div flex-1 text-2xl flex justify-center>
      <div self-end>
        {{ store.liveConfig.isLive ? '正在直播' : 'Live!' }}
      </div>
    </div>
    <div text-center>
      <div flex items-center>
        <div flex-1 />
        <UMdInput
          v-model="roomId2"
          title="房间号"
          :disabled="store.liveConfig.isLive"
          @blur="roomIdBlur"
        />
        <div flex-1 flex items-center>
          <div v-if="loadingRoomId" i-ri-refresh-line icon-btn animate-spin />
        </div>
      </div>
      <div flex items-center>
        <div flex-1 />
        <UMdInput v-model="liveTitle" title="直播标题" />
        <div flex-1 flex items-center>
          <div
            v-if="btnUpdateTitleEnabled"
            i-ri-save-line
            icon-btn
            :disabled="liveTitle.trim() === '' || !store.getUserInfo.mid"
            @click="updateLiveTitle2"
          />
          <div v-else i-ri-refresh-line animate-spin icon-btn />
        </div>
      </div>
      <div flex items-center>
        <div flex-1 />
        <UMdInput
          v-model="selectedAreaInfo" title="选择分区"
          :disabled="!btnShowAreaEnabled"
          cursor-pointer
          class="disabled:cursor-wait"
          @click="showAreaSelection"
        />
        <div flex-1 flex items-center>
          <div v-if="!btnShowAreaEnabled" i-ri-refresh-line icon-btn animate-spin />
        </div>
      </div>
      <div v-if="store.liveConfig.isLive" flex items-center>
        <div flex-1 />
        <UMdInput v-model="store.liveConfig.addr" title="RTMP 串流地址" />
        <div flex-1 flex items-center>
          <div i-ri-file-copy-2-line icon-btn title="点击复制" @click="copy2(store.liveConfig.addr)" />
        </div>
      </div>
      <div v-if="store.liveConfig.isLive" flex items-center>
        <div flex-1 />
        <UMdInput v-model="store.liveConfig.code" title="RTMP 串流密钥" />
        <div flex-1 flex items-center>
          <div i-ri-file-copy-2-line icon-btn title="点击复制" @click="copy2(store.liveConfig.code)" />
        </div>
      </div>
      <div m-2 space-x-2>
        <button
          v-if="!store.liveConfig.isLive"
          btn rounded
          :disabled="!btnEnabled || !roomId2.trim().match(/^\d+$/) || !store.getUserInfo.mid || !selectedAreaId || liveTitle.trim() === ''"
          @click="startLive2"
        >
          开启直播
        </button>
        <button
          v-else
          :disabled="!btnEnabled"
          btn rounded
          @click="stopLive2"
        >
          关闭直播
        </button>
      </div>
    </div>
    <div flex-1 flex items-end>
      <div mx-a my-2 i-ri-stop-circle-line icon-btn op="10 hover:100" title="应急关闭" @click="stopLive2" />
    </div>
  </div>
  <Transition name="selector">
    <UTabSelector
      v-if="isShowAreaSelection"
      v-model:id="selectedAreaId"
      v-model:info="selectedAreaInfo"
      @update:id="showAreaSelection"
      @close="showAreaSelection"
    />
  </Transition>
</template>

<style scoped>
.selector-enter-active,
.selector-leave-active {
  transition: all 0.200s ease;
}

.selector-enter-from,
.selector-leave-to {
  opacity: 0;
}
</style>


================================================
FILE: src/pages/sender.vue
================================================
<script setup lang="ts">
import { listen } from '@tauri-apps/api/event'
import { tryOnBeforeUnmount } from '@vueuse/core'
import UMessageSender from '../components/send/UMessageSender.vue'
import { useStore } from '../stores/store'
import { hex2rgb } from '~/composables/randomColor'

const store = useStore()

const unlistens: Function[] = []
async function initListens() {
  unlistens.push(await listen('bg-color-changed', (event) => {
    store.config.bgColor = event.payload as string
  }))
  unlistens.push(await listen('bg-opacity-changed', (event) => {
    store.config.bgOpacity = event.payload as string
  }))
  unlistens.push(await listen('text-color-changed', (event) => {
    store.config.textColor = event.payload as string
  }))
  unlistens.push(await listen('text-shadow-color-changed', (event) => {
    store.config.textShadowColor = event.payload as string
  }))
  unlistens.push(await listen('enable-text-shadow', (event) => {
    store.config.enableTextShadow = (event.payload as string) === 'true'
  }))
  unlistens.push(await listen('blur', (event) => {
    store.config.blur = (event.payload as string) === 'true'
  }))
  unlistens.push(await listen('font-changed', (event) => {
    store.config.fontFamily = event.payload as string
  }))
}

initListens()

tryOnBeforeUnmount(() => {
  unlistens.map(fn => fn())
})
</script>

<template>
  <div
    flex items-center
    :class="{
      'backdrop-blur-sm': store.getConfig.blur,
    }"
    :style="{
      background: hex2rgb(store.getConfig.bgColor, store.getConfig.bgOpacity),
      color: store.getConfig.textColor,
      textShadow: store.getConfig.enableTextShadow ? `1px 1px 1px ${store.getConfig.textShadowColor}` : 'none',
      fontFamily: store.getConfig.fontFamily,
    }"
  >
    <div cursor-move i-ri-drag-move-line icon-btn data-tauri-drag-region text-gray ml-2 />
    <UMessageSender :no-border="true" flex-1 />
  </div>
</template>

<route lang="yaml">
meta:
  layout: none
</route>



================================================
FILE: src/pages/settings.vue
================================================
<script setup lang="ts">
import { inject } from 'vue'
import { confirm } from '@tauri-apps/api/dialog'
import { invoke } from '@tauri-apps/api/tauri'
import { appDir } from '@tauri-apps/api/path'
import { useThrottleFn } from '@vueuse/core'
import USettingsBox from '~/components/ui/USettingsBox.vue'
import UCheckBox from '~/components/ui/UCheckBox.vue'
import UColorPicker from '~/components/ui/UColorPicker.vue'
import { useStore } from '~/stores/store'
import Login from '~/components/settings/Login.vue'
import URadio from '~/components/ui/URadio.vue'
import USlider from '~/components/ui/USlider.vue'
import UMultiList from '~/components/ui/UMultiList.vue'
import UBlackList from '~/components/ui/UBlackList.vue'
import { eventEmitter } from '~/composables/eventEmitter'
import USelector from '~/components/ui/USelector.vue'
import { msgKey } from '~/composables/injectionKeys'

const msgRef = inject(msgKey)
const store = useStore()

const saveSettings = useThrottleFn(() => {
  store.settingsSaved = true
  store.storeConfig()
  msgRef?.value.pushMsg('保存成功', { type: 'success' })
}, 1000)

const settingChanged = (event: string, payload: any) => {
  store.settingsSaved = false
  eventEmitter(event, payload)
}

function openAppDir() {
  appDir()
    .then(async (dir) => {
      return await invoke('open_app_img_dir', { dir })
    })
    .catch((err) => {
      msgRef?.value.pushMsg(err.message, { type: 'error' })
    })
}

async function clearConfig() {
  const confirmed = await confirm('确定要清空当前设置吗?', {
    title: '还原默认设置', type: 'warning',
  })
  if (confirmed) {
    store.removeConfig()
    msgRef?.value.pushMsg('设置已还原!')
  }
}

function setCanSend() {
  settingChanged('can-send-message', store.config.canSendMessage)
  if (store.getConfig.canSendMessage)
    msgRef?.value.pushMsg('在点击穿透模式下,窗口将自动分裂为弹幕窗格和发送浮窗', { ttl: 8000 })
}

function setAutoReply() {
  settingChanged('auto-reply', store.config.autoReply)
  if (store.getConfig.autoReply)
    msgRef?.value.pushMsg('保存设置后生效')
}
</script>

<template>
  <div p-4 space-y-4>
    <Login />
    <div flex space-x-2>
      <div font-bold text-xl>
        设置项
      </div>
      <div flex-1 />
      <button
        btn rounded
        :disabled="store.settingsSaved"
        @click="saveSettings"
      >
        保存设置
      </button>
      <button
        border="~ zinc hover:#646cff"
        p="x-4 y-1" op="80 hover:100"
        transition-all
        rounded
        title="如果有些新加的设置项无法修改,请尝试重置设置"
        @click="clearConfig"
      >
        还原默认
      </button>
    </div>
    <USettingsBox title="界面布局">
      <div space-x-2>
        <URadio
          v-model="store.config.layout"
          value="loose" name="layout"
          @update:model-value="settingChanged('layout', store.config.layout)"
        >
          松散
        </URadio>
        <URadio
          v-model="store.config.layout"
          value="tight" name="layout"
          @update:model-value="settingChanged('layout', store.config.layout)"
        >
          紧凑
        </URadio>
      </div>
      <UCheckBox
        v-model="store.config.showPopulation"
        @update:model-value="settingChanged('show-population', store.config.showPopulation)"
      >
        显示顶部栏
      </UCheckBox>
      <UCheckBox
        v-model="store.config.showHighlight"
        @update:model-value="settingChanged('show-highlight', store.config.showHighlight)"
      >
        显示高能榜
      </UCheckBox>
    </USettingsBox>
    <USettingsBox title="常规">
      <UCheckBox
        v-model="store.config.showAvatar"
        title="若弹幕数量过多,建议关闭,以免请求超时"
        @update:model-value="settingChanged('show-avatar', store.config.showAvatar)"
      >
        显示用户头像
      </UCheckBox>
      <UCheckBox
        v-model="store.config.showTime"
        @update:model-value="settingChanged('show-time', store.config.showTime)"
      >
        显示弹幕发送时间
      </UCheckBox>
      <div flex space-x-1 items-center>
        <div text-lg flex items-center>
          <div i-ri-bank-card-line icon-btn ml-1 />
        </div>
        <span>
          标签和等级
        </span>
        <USelector
          v-model="store.config.showGuardTag"
          :options="[{ label: '不显示', value: 0 }, { label: '官方配置', value: 1 }, { label: '全部显示', value: 2 }]"
          @update:model-value="settingChanged('show-guard-tag', store.config.showGuardTag)"
        />
      </div>
      <UCheckBox
        v-model="store.config.showEnter"
        @update:model-value="settingChanged('show-enter', store.config.showEnter)"
      >
        显示进场信息
      </UCheckBox>
      <UCheckBox
        v-model="store.config.showSubscribe"
        @update:model-value="settingChanged('show-subscribe', store.config.showSubscribe)"
      >
        显示关注信息
      </UCheckBox>
      <div
        inline-flex items-center leading-relaxed select-none space-x-1 cursor-pointer
        @click="openAppDir"
      >
        <div text-lg flex items-center>
          <div icon-btn i-ri-folder-open-fill ml-1 />
        </div>
        <span>打开图片缓存目录</span>
      </div>
    </USettingsBox>
    <USettingsBox title="礼物">
      <UCheckBox
        v-model="store.config.showSilverGift"
        @update:model-value="settingChanged('show-silver-gift', store.config.showSilverGift)"
      >
        显示免费礼物
      </UCheckBox>
      <UCheckBox
        v-model="store.config.showGoldGift"
        @update:model-value="settingChanged('show-gold-gift', store.config.showGoldGift)"
      >
        显示付费礼物
      </UCheckBox>
      <UCheckBox
        v-model="store.config.pushGiftIntoHighlight"
        @update:model-value="settingChanged('push-gift-into-highlight', store.config.pushGiftIntoHighlight)"
      >
        付费礼物加入高能榜
      </UCheckBox>
    </USettingsBox>

    <USettingsBox title="样式">
      <UColorPicker
        v-model="store.config.textColor"
        @update:model-value="settingChanged('text-color-changed', store.config.textColor)"
      >
        文字颜色
      </UColorPicker>
      <div flex space-x-2>
        <UCheckBox
          v-model="store.config.enableTextShadow"
          @update:model-value="settingChanged('enable-text-shadow', store.config.enableTextShadow)"
        >
          文字阴影
        </UCheckBox>
        <UColorPicker
          v-model="store.config.textShadowColor"
          :disabled="!store.config.enableTextShadow"
          @update:model-value="settingChanged('text-shadow-color-changed', store.config.textShadowColor)"
        >
          颜色
        </UColorPicker>
      </div>
      <div flex space-x-1 items-center>
        <div>
          字体
        </div>
        <div flex-1>
          <input
            v-model="store.config.fontFamily"
            w-full
            m-input rounded text-sm
            autocorrect="off"
            autocapitalize="off"
            autocomplete="off"
            spellcheck="false"
            :style="{ fontFamily: store.config.fontFamily }"
            @input="settingChanged('font-changed', store.config.fontFamily)"
          >
        </div>
      </div>
      <UColorPicker
        v-model="store.config.bgColor"
        @update:model-value="settingChanged('bg-color-changed', store.config.bgColor)"
      >
        背景颜色
      </UColorPicker>
      <div flex space-x-2 leading-relaxed>
        <USlider
          v-model="store.config.bgOpacity" :min-value="0" :max-value="255" w-100px
          @update:model-value="settingChanged('bg-opacity-changed', store.config.bgOpacity)"
        />
        <span>背景不透明度</span>
      </div>
      <UCheckBox
        v-model="store.config.blur"
        @update:model-value="settingChanged('blur', store.config.blur)"
      >
        毛玻璃效果(不稳定)
      </UCheckBox>
    </USettingsBox>
    <UBlackList @settings-changed="settingChanged('blacklist', store.getConfig.blackList)" />
    <USettingsBox :title="store.getUserInfo.mid ? '弹幕扩展' : '弹幕扩展(需要登录)'">
      <UCheckBox
        v-model="store.config.canSendMessage"
        :disabled="!store.getUserInfo.mid || store.clickThrough"
        @update:model-value="setCanSend"
      >
        通过弹幕窗格发送弹幕
      </UCheckBox>
      <UCheckBox
        v-model="store.config.autoReply"
        :disabled="!store.getUserInfo.mid"
        @update:model-value="setAutoReply"
      >
        自动回复
      </UCheckBox>
    </USettingsBox>
    <UMultiList
      v-if="store.config.autoReply"
      ml-2
      @settings-changed="store.settingsSaved = false"
    />
  </div>
</template>


================================================
FILE: src/pages/show.vue
================================================
<script setup lang="ts">
import UWidget from '~/components/UWidget.vue'
</script>

<template>
  <UWidget />
</template>

<route lang="yaml">
meta:
  layout: none
</route>


================================================
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
================================================
/// <reference types="vite/client" />

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<String, String> {
  
  // 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<String, String> {
    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<Wry>) {
    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<Wry>) {
    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<Wry>, enable: bool) -> Result<bool, String> {
  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<Wry>) -> Result<PosProps, String> {
  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<Wry>, conf: PosProps) -> Result<bool, String> {
  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(),
  ],
})
Download .txt
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
Download .txt
SYMBOL INDEX (99 symbols across 29 files)

FILE: src-tauri/build.rs
  function main (line 1) | fn main() {

FILE: src-tauri/src/fetch_img.rs
  function fetch_image (line 4) | pub async fn fetch_image(img_url: String, file_path: String) -> Result<S...

FILE: src-tauri/src/load_local_img.rs
  function load_local_image (line 2) | pub async fn load_local_image(uid_path: String) -> Result<String, String> {

FILE: src-tauri/src/main.rs
  function main (line 24) | fn main() {

FILE: src-tauri/src/new_sender.rs
  function create_sender_window (line 4) | pub async fn create_sender_window(app_handle: tauri::AppHandle<Wry>) {

FILE: src-tauri/src/new_view.rs
  function create_new_danmaku_view (line 4) | pub async fn create_new_danmaku_view(app_handle: tauri::AppHandle<Wry>) {
  function set_click_through (line 30) | pub fn set_click_through(app_handle: tauri::AppHandle<Wry>, enable: bool...
  type PosProps (line 47) | pub struct PosProps {
  function get_viewer_pos_and_size (line 55) | pub fn get_viewer_pos_and_size(app_handle: tauri::AppHandle<Wry>) -> Res...
  function set_viewer_pos_and_size (line 69) | pub fn set_viewer_pos_and_size(app_handle: tauri::AppHandle<Wry>, conf: ...

FILE: src-tauri/src/open_app_dir.rs
  function open_app_img_dir (line 4) | pub async fn open_app_img_dir(dir: String) -> Result<(), String> {

FILE: src-tauri/src/send_msg.rs
  type Payload (line 2) | struct Payload {
  function send_message (line 12) | pub async fn send_message(msg: String, cookie: String, csrf: String, roo...

FILE: src/composables/autoSendMsg.ts
  type Answer (line 4) | interface Answer {
  function addFAQ (line 12) | function addFAQ(ans: Omit<Answer, 'ts'>) {
  function removeFAQ (line 19) | function removeFAQ(index: number) {
  function enqueueAnswerTs (line 25) | function enqueueAnswerTs(ts: number) {
  function autoSendByIndex (line 33) | function autoSendByIndex(index: number) {
  function autoSendByWord (line 50) | function autoSendByWord(word: string) {

FILE: src/composables/components.ts
  type DanmakuProps (line 1) | interface DanmakuProps {
  function isDanmakuProps (line 15) | function isDanmakuProps(obj: any): obj is DanmakuProps {
  type GiftProps (line 19) | interface GiftProps {
  function isGiftProps (line 41) | function isGiftProps(obj: any): obj is GiftProps {
  type PropsType (line 45) | type PropsType = 'text' | 'gift'
  type SuperChatProps (line 47) | interface SuperChatProps {
  function isSuperChatProps (line 61) | function isSuperChatProps(obj: any): obj is SuperChatProps {
  type GuardBuyProps (line 65) | interface GuardBuyProps {
  function isGuardBuyProps (line 76) | function isGuardBuyProps(obj: any): obj is GuardBuyProps {
  type InteractProps (line 80) | interface InteractProps {
  function isInteractProps (line 89) | function isInteractProps(obj: any): obj is InteractProps {

FILE: src/composables/eventEmitter.ts
  function eventEmitter (line 3) | function eventEmitter(event: string, payload: any) {

FILE: src/composables/fetchImgFromBackend.ts
  function getAbsolutePathFromUrl (line 8) | async function getAbsolutePathFromUrl(url: string, fileName: string) {
  function abPath2Blob (line 18) | async function abPath2Blob(path: string) {
  function processImgUrl2 (line 24) | async function processImgUrl2(imgUrl: string, uid?: number) {

FILE: src/composables/getAvatar.ts
  constant MAX_REQUEST_BLOCK_TIMES (line 10) | const MAX_REQUEST_BLOCK_TIMES = 10
  function getAvatar2 (line 15) | async function getAvatar2(uid: number): Promise<{ url: string; isBlob: b...

FILE: src/composables/getCookies.ts
  function getCookies (line 5) | function getCookies() {

FILE: src/composables/getInfoFromUid.ts
  function getSpaceInfo (line 5) | async function getSpaceInfo(uid: number) {
  function getCardInfo (line 14) | async function getCardInfo(uid: number) {

FILE: src/composables/getLiverInfo.ts
  function getLiveRoomInfoFromRoomId (line 8) | async function getLiveRoomInfoFromRoomId(roomId: number) {
  function getLiverInfo (line 23) | async function getLiverInfo(roomId: number) {
  function getLiveRoomInfoFromUid (line 39) | async function getLiveRoomInfoFromUid(uid: number) {
  function getLiveStatusFromUid (line 47) | async function getLiveStatusFromUid(uid: number) {

FILE: src/composables/load_pos.ts
  function loadPos (line 4) | async function loadPos(conf: PositionConfig) {

FILE: src/composables/loginLoop.ts
  function createLoginLoop (line 32) | async function createLoginLoop(oauthKey: string): Promise<boolean> {

FILE: src/composables/logout.ts
  function logout (line 14) | async function logout() {

FILE: src/composables/msgSend.ts
  function sendSingleMsg (line 10) | function sendSingleMsg(msg: string) {
  function sendMsg (line 27) | function sendMsg(msg: string) {

FILE: src/composables/openLive.ts
  function getAreaInfoList (line 12) | async function getAreaInfoList() {
  function updateLiveTitle (line 20) | async function updateLiveTitle(roomId: string, title: string) {
  function startLive (line 40) | async function startLive(roomId: string, area_v2: number, platform: stri...
  function stopLive (line 68) | async function stopLive(roomId: string) {

FILE: src/composables/priceToSeconds.ts
  function priceToSeconds (line 1) | function priceToSeconds(price: number) {

FILE: src/composables/randomColor.ts
  function hslToRgb (line 1) | function hslToRgb(h: number, s: number, l: number) {
  function randomColor (line 11) | function randomColor() {
  function rgbToHex (line 19) | function rgbToHex(r: number, g: number, b: number) {
  function randomColorPair (line 27) | function randomColorPair() {
  function rgbAppendAlpha (line 37) | function rgbAppendAlpha(color: string) {
  function getLightnessFromHex (line 41) | function getLightnessFromHex(hex: string) {
  function getLightnessFromRgb (line 46) | function getLightnessFromRgb(rgb: string) {
  function hex2rgb (line 51) | function hex2rgb(hex: string, opacity: string) {
  constant LIGHTNESS_LIMIT (line 56) | const LIGHTNESS_LIMIT = 120

FILE: src/composables/shortIdToLong.ts
  function shortToLongResponse (line 4) | async function shortToLongResponse(id: number) {
  function shortToLong (line 9) | async function shortToLong(id: number) {

FILE: src/composables/tooLongSymbols.ts
  function processTooLongSymbols (line 1) | function processTooLongSymbols(content: string) {

FILE: src/composables/types.ts
  type MsgCommand (line 1) | type MsgCommand = 'INTERACT_WORD'
  type MessageType (line 17) | interface MessageType {
  type DanmakuMessage (line 21) | interface DanmakuMessage extends MessageType {
  type WatchedMessage (line 60) | interface WatchedMessage extends MessageType {
  type SubscriberMessage (line 67) | interface SubscriberMessage extends MessageType {
  type SendGiftMessage (line 77) | interface SendGiftMessage extends MessageType {
  type GuardBuyMessage (line 101) | interface GuardBuyMessage extends MessageType {
  type SuperChatMessage (line 114) | interface SuperChatMessage extends MessageType {
  type WelcomeGuardMessage (line 132) | interface WelcomeGuardMessage extends MessageType {
  type InteractiveWordMessage (line 141) | interface InteractiveWordMessage extends MessageType {
  type ComboSendMessage (line 159) | interface ComboSendMessage extends MessageType {
  type SendMessageProps (line 177) | interface SendMessageProps {
  type GiftInfo (line 189) | interface GiftInfo {
  type LiveAreaInfo (line 194) | interface LiveAreaInfo {
  type StartLiveResponse (line 203) | interface StartLiveResponse {
  type SpaceApiResponse (line 216) | interface SpaceApiResponse {
  type CardInfoResponse (line 229) | interface CardInfoResponse {

FILE: src/stores/position.ts
  type PositionConfig (line 4) | interface PositionConfig {
  method getConfig (line 19) | getConfig() {
  method storeConfig (line 30) | async storeConfig() {

FILE: src/stores/store.ts
  type UserInfo (line 6) | interface UserInfo {
  type ConfigProps (line 19) | interface ConfigProps {
  type liveConfig (line 86) | interface liveConfig {
  method getUserInfo (line 120) | getUserInfo(): UserInfo {
  method getConfig (line 138) | getConfig(): ConfigProps {
  method getRoomId (line 157) | getRoomId(): string {
  method getFaqs (line 161) | getFaqs(): Answer[] {
  method storeUserInfo (line 167) | storeUserInfo() {
  method removeUserInfo (line 170) | removeUserInfo() {
  method storeConfig (line 174) | storeConfig() {
  method removeConfig (line 181) | removeConfig() {
  method setRoomId (line 186) | setRoomId(id: string) {

FILE: src/types.ts
  type MessageProvider (line 1) | interface MessageProvider {
  type MessageProviderOptions (line 5) | interface MessageProviderOptions {
Condensed preview — 98 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (191K chars).
[
  {
    "path": ".eslintignore",
    "chars": 38,
    "preview": "dist\npublic\nsrc-tauri\n.vscode\n.github\n"
  },
  {
    "path": ".eslintrc",
    "chars": 26,
    "preview": "{\n  \"extends\": \"@antfu\"\n}\n"
  },
  {
    "path": ".github/workflows/release.yml",
    "chars": 2833,
    "preview": "# 可选,将显示在 GitHub 存储库的“操作”选项卡中的工作流名称\nname: Release CI\n\n# 指定此工作流的触发器\non:\n  push:\n    # 匹配特定标签 (refs/tags)\n    tags:\n      "
  },
  {
    "path": ".gitignore",
    "chars": 353,
    "preview": "# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\npnpm-debug.log*\nlerna-debug.log*\n\nnode_modules\ndist\ndis"
  },
  {
    "path": ".vscode/extensions.json",
    "chars": 39,
    "preview": "{\n  \"recommendations\": [\"Vue.volar\"]\n}\n"
  },
  {
    "path": ".vscode/settings.json",
    "chars": 176,
    "preview": "{\n    \"editor.codeActionsOnSave\": {\n        \"source.fixAll.eslint\": true\n    },\n    \"files.associations\": {\n        \"*.c"
  },
  {
    "path": "LICENSE",
    "chars": 34523,
    "preview": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C)"
  },
  {
    "path": "README.md",
    "chars": 2545,
    "preview": "# D4nm4ku\n\n![](https://img.shields.io/github/workflow/status/widcardw/D4nm4ku/Release%20CI) ![](https://img.shields.io/g"
  },
  {
    "path": "index.html",
    "chars": 469,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <link rel=\"icon\" type=\"image/svg+xml\" href=\"/"
  },
  {
    "path": "package.json",
    "chars": 1078,
    "preview": "{\n  \"name\": \"D4nm4ku\",\n  \"type\": \"module\",\n  \"version\": \"0.0.0\",\n  \"private\": true,\n  \"scripts\": {\n    \"dev\": \"vite\",\n  "
  },
  {
    "path": "src/App.vue",
    "chars": 468,
    "preview": "<script setup lang=\"ts\">\nimport { provide, ref } from 'vue'\nimport UMessageProvider from './components/ui/UMessageProvid"
  },
  {
    "path": "src/components/DarkMode.vue",
    "chars": 238,
    "preview": "<script setup lang=\"ts\">\nimport { isDark, toggleDark } from '~/composables/dark'\n</script>\n\n<template>\n  <div icon-btn @"
  },
  {
    "path": "src/components/SideBar.vue",
    "chars": 967,
    "preview": "<script setup lang=\"ts\">\nimport { ref } from 'vue'\nimport { useRouter } from 'vue-router'\nimport DarkMode from './DarkMo"
  },
  {
    "path": "src/components/UWidget.vue",
    "chars": 6646,
    "preview": "<script setup lang=\"ts\">\nimport { listen } from '@tauri-apps/api/event'\nimport { tryOnBeforeUnmount, useStorage } from '"
  },
  {
    "path": "src/components/danmaku/UDanmaku.vue",
    "chars": 5052,
    "preview": "<script setup lang=\"ts\">\nimport { confirm } from '@tauri-apps/api/dialog'\nimport { WebviewWindow } from '@tauri-apps/api"
  },
  {
    "path": "src/components/danmaku/UGift.vue",
    "chars": 1635,
    "preview": "<script setup lang=\"ts\">\nimport Avatar from '~/components/img/Avatar.vue'\nimport MyImg from '~/components/img/MyImg.vue'"
  },
  {
    "path": "src/components/danmaku/UGuardTag.vue",
    "chars": 501,
    "preview": "<script setup lang=\"ts\">\nconst props = defineProps<{\n  level: number\n  label: string\n  perhapsGuard: 0 | 1 | 2 | 3\n  tag"
  },
  {
    "path": "src/components/danmaku/UInteraction.vue",
    "chars": 1227,
    "preview": "<script setup lang=\"ts\">\nimport { inject, ref } from 'vue'\nimport { getAvatar2 } from '../../composables/getAvatar'\nimpo"
  },
  {
    "path": "src/components/danmaku/URenderer.vue",
    "chars": 1963,
    "preview": "<script setup lang=\"ts\">\nimport UInteraction from './UInteraction.vue'\nimport UDanmaku from '~/components/danmaku/UDanma"
  },
  {
    "path": "src/components/danmaku/UWatch.vue",
    "chars": 267,
    "preview": "<script setup lang=\"ts\">\ndefineProps<{\n  population: string\n  fans: string\n}>()\n</script>\n\n<template>\n  <div\n    flex\n  "
  },
  {
    "path": "src/components/img/Avatar.vue",
    "chars": 256,
    "preview": "<script setup lang=\"ts\">\nimport MyImg from './MyImg.vue'\ndefineProps<{\n  src: string\n  uid?: number\n  isBlob?: boolean\n}"
  },
  {
    "path": "src/components/img/MyImg.vue",
    "chars": 815,
    "preview": "<script setup lang=\"ts\">\n// import { readBinaryFile } from '@tauri-apps/api/fs'\nimport { ref, watch } from 'vue'\nimport "
  },
  {
    "path": "src/components/img/MyQrCode.vue",
    "chars": 469,
    "preview": "<script setup lang=\"ts\">\nimport { useQRCode } from '@vueuse/integrations/useQRCode'\n\nconst props = defineProps<{\n  url: "
  },
  {
    "path": "src/components/send/UMessageSender.vue",
    "chars": 1056,
    "preview": "<script setup lang=\"ts\">\nimport { inject, ref } from 'vue'\nimport { sendMsg } from '~/composables/msgSend'\nimport UInput"
  },
  {
    "path": "src/components/settings/Login.vue",
    "chars": 3047,
    "preview": "<script setup lang=\"ts\">\nimport { fetch } from '@tauri-apps/api/http'\nimport { confirm } from '@tauri-apps/api/dialog'\ni"
  },
  {
    "path": "src/components/superchat/UScDanmaku.vue",
    "chars": 2057,
    "preview": "<script setup lang=\"ts\">\nimport { computed, inject, ref } from 'vue'\nimport Avatar from '~/components/img/Avatar.vue'\nim"
  },
  {
    "path": "src/components/superchat/USuperChatFloat.vue",
    "chars": 2090,
    "preview": "<script setup lang=\"ts\">\nimport { computed, inject, ref } from 'vue'\nimport Avatar from '~/components/img/Avatar.vue'\nim"
  },
  {
    "path": "src/components/superchat/USuperChatPool.vue",
    "chars": 1399,
    "preview": "<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport USuperChat from './USuperChatFloat.vue'\nimport "
  },
  {
    "path": "src/components/superchat/USuperChatTag.vue",
    "chars": 1638,
    "preview": "<script setup lang=\"ts\">\nimport { useIntervalFn } from '@vueuse/core'\nimport { inject, ref, watchEffect } from 'vue'\nimp"
  },
  {
    "path": "src/components/ui/UBlackList.vue",
    "chars": 1523,
    "preview": "<script setup lang=\"ts\">\nimport { inject } from 'vue'\nimport UTag from './UTag.vue'\nimport { useStore } from '~/stores/s"
  },
  {
    "path": "src/components/ui/UCheckBox.vue",
    "chars": 980,
    "preview": "<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\n\nconst props = withDefaults(defineProps<{\n  modelValue"
  },
  {
    "path": "src/components/ui/UColorPicker.vue",
    "chars": 771,
    "preview": "<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\n\nconst props = withDefaults(defineProps<{\n  modelValue"
  },
  {
    "path": "src/components/ui/UInputBtn.vue",
    "chars": 1120,
    "preview": "<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\n\nconst props = withDefaults(defineProps<{\n  modelValue"
  },
  {
    "path": "src/components/ui/UMdInput.vue",
    "chars": 1169,
    "preview": "<script setup lang=\"ts\">\nimport { useFocus, useVModel } from '@vueuse/core'\nimport { computed, ref } from 'vue'\n\nconst p"
  },
  {
    "path": "src/components/ui/UMessageProvider.vue",
    "chars": 1608,
    "preview": "<script setup lang=\"ts\">\nimport { ref } from 'vue'\nimport type { MessageProviderOptions } from '~/types'\n\ninterface PopM"
  },
  {
    "path": "src/components/ui/UMultiList.vue",
    "chars": 3054,
    "preview": "<script setup lang=\"ts\">\nimport { confirm } from '@tauri-apps/api/dialog'\nimport { inject } from 'vue'\nimport type { Ans"
  },
  {
    "path": "src/components/ui/URadio.vue",
    "chars": 991,
    "preview": "<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\n\nconst props = withDefaults(defineProps<{\n  modelValue"
  },
  {
    "path": "src/components/ui/USelector.vue",
    "chars": 882,
    "preview": "<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nconst props = withDefaults(defineProps<{\n  options?: A"
  },
  {
    "path": "src/components/ui/USettingsBox.vue",
    "chars": 242,
    "preview": "<script setup lang=\"ts\">\ndefineProps<{ title: string }>()\n</script>\n\n<template>\n  <div>\n    <div font-bold>\n      {{ tit"
  },
  {
    "path": "src/components/ui/USlider.vue",
    "chars": 1192,
    "preview": "<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\n\nconst props = withDefaults(defineProps<{\n  modelValue"
  },
  {
    "path": "src/components/ui/USwitch.vue",
    "chars": 1060,
    "preview": "<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\n\nconst props = withDefaults(defineProps<{\n  modelValue"
  },
  {
    "path": "src/components/ui/UTabSelector.vue",
    "chars": 2385,
    "preview": "<script setup lang=\"ts\">\nimport { onClickOutside, useVModels } from '@vueuse/core'\nimport { ref } from 'vue'\nimport { us"
  },
  {
    "path": "src/components/ui/UTag.vue",
    "chars": 383,
    "preview": "<script setup lang=\"ts\">\ndefineProps<{\n  content: string\n}>()\n\nconst emits = defineEmits(['close'])\n</script>\n\n<template"
  },
  {
    "path": "src/composables/api.ts",
    "chars": 1304,
    "preview": "const spaceInfo = 'https://api.bilibili.com/x/space/app/index?mid='\nconst cardInfo = 'http://api.bilibili.com/x/web-inte"
  },
  {
    "path": "src/composables/autoSendMsg.ts",
    "chars": 1191,
    "preview": "import { sendMsg } from './msgSend'\nimport { useStore } from '~/stores/store'\n\ninterface Answer {\n  ts: number\n  keyword"
  },
  {
    "path": "src/composables/components.ts",
    "chars": 1926,
    "preview": "interface DanmakuProps {\n  type: 'text'\n  content: string\n  uname: string\n  color: string\n  tagColor: number\n  fang: num"
  },
  {
    "path": "src/composables/dark.ts",
    "chars": 243,
    "preview": "import { useDark, usePreferredDark, useToggle } from '@vueuse/core'\n\n// these APIs are auto-imported from @vueuse/core\ne"
  },
  {
    "path": "src/composables/data.ts",
    "chars": 749,
    "preview": "const guardType = {\n  1: {\n    type: 'member',\n    bgColor: '#fae4ab',\n    bgBottomColor: '#e3704d',\n    second: 60,\n   "
  },
  {
    "path": "src/composables/eventEmitter.ts",
    "chars": 358,
    "preview": "import { WebviewWindow } from '@tauri-apps/api/window'\n\nexport function eventEmitter(event: string, payload: any) {\n  co"
  },
  {
    "path": "src/composables/fetchImgFromBackend.ts",
    "chars": 1731,
    "preview": "import { appDir, join } from '@tauri-apps/api/path'\nimport { invoke } from '@tauri-apps/api/tauri'\nimport { readBinaryFi"
  },
  {
    "path": "src/composables/getAvatar.ts",
    "chars": 2120,
    "preview": "import { invoke } from '@tauri-apps/api/tauri'\nimport { appDir, join } from '@tauri-apps/api/path'\nimport { getCardInfo,"
  },
  {
    "path": "src/composables/getCookies.ts",
    "chars": 463,
    "preview": "import { useStore } from '~/stores/store'\n\nconst store = useStore()\n\nexport default function getCookies() {\n  if (!store"
  },
  {
    "path": "src/composables/getInfoFromUid.ts",
    "chars": 572,
    "preview": "import { fetch } from '@tauri-apps/api/http'\nimport { cardInfo, spaceInfo } from './api'\nimport type { CardInfoResponse,"
  },
  {
    "path": "src/composables/getLastMatchedGift.ts",
    "chars": 628,
    "preview": "import type { GiftProps } from '~/composables/components'\n\nconst getLastMatchedGift = (\n  danmakuPool: Array<any>,\n  una"
  },
  {
    "path": "src/composables/getLiverInfo.ts",
    "chars": 1471,
    "preview": "import { fetch } from '@tauri-apps/api/http'\nimport { getRoomInfoOldApi, roomInfo } from './api'\nimport { getCardInfo, g"
  },
  {
    "path": "src/composables/injectionKeys.ts",
    "chars": 196,
    "preview": "import type { InjectionKey, Ref } from 'vue'\nimport type UMessageProvider from '~/components/ui/UMessageProvider.vue'\n\ne"
  },
  {
    "path": "src/composables/load_pos.ts",
    "chars": 253,
    "preview": "import { invoke } from '@tauri-apps/api/tauri'\nimport type { PositionConfig } from '~/stores/position'\n\nasync function l"
  },
  {
    "path": "src/composables/loginLoop.ts",
    "chars": 2467,
    "preview": "import { Body, fetch } from '@tauri-apps/api/http'\nimport { ref } from 'vue'\nimport { qrcodeLogin } from './api'\nimport "
  },
  {
    "path": "src/composables/logout.ts",
    "chars": 670,
    "preview": "import { Body, fetch } from '@tauri-apps/api/http'\nimport getCookies from './getCookies'\nimport { logOutApi } from './ap"
  },
  {
    "path": "src/composables/msgSend.ts",
    "chars": 833,
    "preview": "import { invoke } from '@tauri-apps/api/tauri'\nimport getCookies from './getCookies'\nimport { useStore } from '~/stores/"
  },
  {
    "path": "src/composables/openLive.ts",
    "chars": 2413,
    "preview": "import { Body, fetch } from '@tauri-apps/api/http'\nimport { useStorage } from '@vueuse/core'\nimport { liveAreaInfoListAp"
  },
  {
    "path": "src/composables/parseFanNumbers.ts",
    "chars": 184,
    "preview": "export default function (num: number) {\n  if (num >= 1e8)\n    return `${(num / 1e8).toFixed(1)} 亿`\n\n  if (num >= 10000)\n"
  },
  {
    "path": "src/composables/priceToSeconds.ts",
    "chars": 267,
    "preview": "function priceToSeconds(price: number) {\n  if (price <= 2000)\n    return 5\n  if (price <= 10000)\n    return 10\n  if (pri"
  },
  {
    "path": "src/composables/randomColor.ts",
    "chars": 1958,
    "preview": "function hslToRgb(h: number, s: number, l: number) {\n  s /= 100\n  l /= 100\n  const k = (n: number) => (n + h / 30) % 12\n"
  },
  {
    "path": "src/composables/server.ts",
    "chars": 8073,
    "preview": "import { KeepLiveWS } from 'bilibili-live-ws'\nimport { fetch } from '@tauri-apps/api/http'\nimport { useStorage } from '@"
  },
  {
    "path": "src/composables/shortIdToLong.ts",
    "chars": 402,
    "preview": "import { fetch } from '@tauri-apps/api/http'\nimport { shortIdToLongApi } from './api'\n\nasync function shortToLongRespons"
  },
  {
    "path": "src/composables/tooLongSymbols.ts",
    "chars": 205,
    "preview": "function processTooLongSymbols(content: string) {\n  const match = content.match(/^(.)\\1{6,20}$/)\n  if (match)\n    return"
  },
  {
    "path": "src/composables/types.ts",
    "chars": 4833,
    "preview": "type MsgCommand = 'INTERACT_WORD'\n| 'DANMU_MSG' // 弹幕信息\n| 'ROOM_REAL_TIME_MESSAGE_UPDATA' // 有关注人数\n| 'WATCHED_CHANGE' //"
  },
  {
    "path": "src/layouts/default.vue",
    "chars": 759,
    "preview": "<script setup lang=\"ts\">\nimport { listen } from '@tauri-apps/api/event'\nimport { tryOnBeforeUnmount } from '@vueuse/core"
  },
  {
    "path": "src/layouts/none.vue",
    "chars": 77,
    "preview": "<script setup lang=\"ts\">\n\n</script>\n\n<template>\n  <RouterView />\n</template>\n"
  },
  {
    "path": "src/main.ts",
    "chars": 1197,
    "preview": "import { createApp } from 'vue'\nimport { createRouter, createWebHistory } from 'vue-router'\nimport generatedRoutes from "
  },
  {
    "path": "src/pages/index.vue",
    "chars": 6862,
    "preview": "<script setup lang=\"ts\">\nimport { WebviewWindow } from '@tauri-apps/api/window'\nimport { invoke } from '@tauri-apps/api/"
  },
  {
    "path": "src/pages/live.vue",
    "chars": 7714,
    "preview": "<script setup lang=\"ts\">\nimport { useClipboard, useStorage } from '@vueuse/core'\nimport type { Ref } from 'vue'\nimport {"
  },
  {
    "path": "src/pages/sender.vue",
    "chars": 1971,
    "preview": "<script setup lang=\"ts\">\nimport { listen } from '@tauri-apps/api/event'\nimport { tryOnBeforeUnmount } from '@vueuse/core"
  },
  {
    "path": "src/pages/settings.vue",
    "chars": 8400,
    "preview": "<script setup lang=\"ts\">\nimport { inject } from 'vue'\nimport { confirm } from '@tauri-apps/api/dialog'\nimport { invoke }"
  },
  {
    "path": "src/pages/show.vue",
    "chars": 171,
    "preview": "<script setup lang=\"ts\">\nimport UWidget from '~/components/UWidget.vue'\n</script>\n\n<template>\n  <UWidget />\n</template>\n"
  },
  {
    "path": "src/stores/index.ts",
    "chars": 72,
    "preview": "import { createPinia } from 'pinia'\n\nexport const pinia = createPinia()\n"
  },
  {
    "path": "src/stores/position.ts",
    "chars": 937,
    "preview": "import { defineStore } from 'pinia'\nimport { invoke } from '@tauri-apps/api/tauri'\n\nexport interface PositionConfig {\n  "
  },
  {
    "path": "src/stores/store.ts",
    "chars": 5029,
    "preview": "import { defineStore } from 'pinia'\nimport type { GiftInfo, LiveAreaInfo } from '../composables/types'\nimport type { Ans"
  },
  {
    "path": "src/styles/main.css",
    "chars": 597,
    "preview": ":root {\n  font-family: Inter, Avenir, Helvetica, Arial, sans-serif;\n  font-size: 16px;\n  line-height: 24px;\n  font-weigh"
  },
  {
    "path": "src/types.ts",
    "chars": 209,
    "preview": "export interface MessageProvider {\n  pushMsg(msg: string, config?: MessageProviderOptions): void\n}\n\nexport interface Mes"
  },
  {
    "path": "src/vite-env.d.ts",
    "chars": 186,
    "preview": "/// <reference types=\"vite/client\" />\n\ndeclare module '*.vue' {\n  import type { DefineComponent } from 'vue'\n  const com"
  },
  {
    "path": "src-tauri/.gitignore",
    "chars": 73,
    "preview": "# Generated by Cargo\n# will have compiled files and executables\n/target/\n"
  },
  {
    "path": "src-tauri/Cargo.toml",
    "chars": 1035,
    "preview": "[package]\nname = \"app\"\nversion = \"0.1.0\"\ndescription = \"A Tauri App\"\nauthors = [\"you\"]\nlicense = \"\"\nrepository = \"\"\ndefa"
  },
  {
    "path": "src-tauri/build.rs",
    "chars": 37,
    "preview": "fn main() {\n  tauri_build::build()\n}\n"
  },
  {
    "path": "src-tauri/src/fetch_img.rs",
    "chars": 782,
    "preview": "use std::io::Write;\n\n#[tauri::command]\npub async fn fetch_image(img_url: String, file_path: String) -> Result<String, St"
  },
  {
    "path": "src-tauri/src/load_local_img.rs",
    "chars": 218,
    "preview": "#[tauri::command]\npub async fn load_local_image(uid_path: String) -> Result<String, String> {\n    if std::path::Path::ne"
  },
  {
    "path": "src-tauri/src/main.rs",
    "chars": 1046,
    "preview": "#![cfg_attr(\n  all(not(debug_assertions), target_os = \"windows\"),\n  windows_subsystem = \"windows\"\n)]\n\nmod send_msg;\nmod "
  },
  {
    "path": "src-tauri/src/new_sender.rs",
    "chars": 827,
    "preview": "use tauri::Wry;\n\n#[tauri::command]\npub async fn create_sender_window(app_handle: tauri::AppHandle<Wry>) {\n    let viewer"
  },
  {
    "path": "src-tauri/src/new_view.rs",
    "chars": 2392,
    "preview": "use tauri::{Manager, Wry};\n\n#[tauri::command]\npub async fn create_new_danmaku_view(app_handle: tauri::AppHandle<Wry>) {\n"
  },
  {
    "path": "src-tauri/src/open_app_dir.rs",
    "chars": 549,
    "preview": "use std::process::Command;\n\n#[tauri::command]\npub async fn open_app_img_dir(dir: String) -> Result<(), String> {\n    // "
  },
  {
    "path": "src-tauri/src/send_msg.rs",
    "chars": 1063,
    "preview": "#[derive(Clone, serde::Serialize, serde::Deserialize, Debug)]\nstruct Payload {\n  msg: String,\n  cookie: String,\n  csrf: "
  },
  {
    "path": "src-tauri/tauri.conf.json",
    "chars": 1738,
    "preview": "{\n  \"$schema\": \"../node_modules/@tauri-apps/cli/schema.json\",\n  \"build\": {\n    \"beforeBuildCommand\": \"pnpm build\",\n    \""
  },
  {
    "path": "tsconfig.json",
    "chars": 776,
    "preview": "{\n  \"compilerOptions\": {\n    \"baseUrl\": \".\",\n    \"target\": \"ESNext\",\n    \"useDefineForClassFields\": true,\n    \"module\": "
  },
  {
    "path": "tsconfig.node.json",
    "chars": 184,
    "preview": "{\n  \"compilerOptions\": {\n    \"composite\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Node\",\n    \"allowSynthe"
  },
  {
    "path": "unocss.config.ts",
    "chars": 1380,
    "preview": "import {\n  defineConfig,\n  presetAttributify,\n  presetIcons,\n  presetUno,\n  presetWebFonts,\n  // transformerDirectives,\n"
  },
  {
    "path": "vite.config.ts",
    "chars": 439,
    "preview": "import path from 'path'\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport Unocss from 'uno"
  }
]

// ... and 1 more files (download for full content)

About this extraction

This page contains the full source code of the widcardw/D4nm4ku GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 98 files (169.4 KB), approximately 49.5k tokens, and a symbol index with 99 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!