Spaces:
Sleeping
Sleeping
Upload 84 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- CODE_OF_CONDUCT.md +128 -0
- Dockerfile +29 -7
- LICENSE +373 -0
- bun.lock +0 -0
- docker-compose.yml +28 -0
- eslint.config.js +41 -0
- generate_spotify_totp.py +225 -0
- package-lock.json +0 -0
- package.json +55 -0
- src/app.css +481 -0
- src/app.d.ts +32 -0
- src/app.html +18 -0
- src/lib/api.ts +2568 -0
- src/lib/assets/favicon.svg +1 -0
- src/lib/components/AudioPlayer.svelte +1975 -0
- src/lib/components/DynamicBackground.svelte +904 -0
- src/lib/components/DynamicBackgroundWebGL.svelte +573 -0
- src/lib/components/LyricsPopup.svelte +830 -0
- src/lib/components/QualitySelector.svelte +98 -0
- src/lib/components/SearchInterface.svelte +1760 -0
- src/lib/components/ShareButton.svelte +170 -0
- src/lib/components/TopTracksGrid.svelte +298 -0
- src/lib/components/TrackList.svelte +572 -0
- src/lib/config.ts +578 -0
- src/lib/downloads.ts +538 -0
- src/lib/ffmpegClient.ts +212 -0
- src/lib/index.ts +29 -0
- src/lib/server/redis.ts +67 -0
- src/lib/stores/downloadPreferences.ts +56 -0
- src/lib/stores/downloadUi.ts +381 -0
- src/lib/stores/lyrics.ts +91 -0
- src/lib/stores/performance.ts +52 -0
- src/lib/stores/player.ts +473 -0
- src/lib/stores/region.ts +50 -0
- src/lib/stores/searchStore.svelte.ts +77 -0
- src/lib/stores/userPreferences.ts +181 -0
- src/lib/types.ts +237 -0
- src/lib/utils.ts +45 -0
- src/lib/utils/audioQuality.ts +107 -0
- src/lib/utils/colorExtraction.ts +305 -0
- src/lib/utils/colorPalette.ts +411 -0
- src/lib/utils/performance.ts +642 -0
- src/lib/utils/songlink.ts +242 -0
- src/lib/utils/urlParser.ts +120 -0
- src/lib/utils/webglShaders.ts +271 -0
- src/lib/version.ts +1 -0
- src/routes/+layout.server.ts +8 -0
- src/routes/+layout.svelte +1362 -0
- src/routes/+page.server.ts +9 -0
- src/routes/+page.svelte +140 -0
CODE_OF_CONDUCT.md
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Contributor Covenant Code of Conduct
|
| 2 |
+
|
| 3 |
+
## Our Pledge
|
| 4 |
+
|
| 5 |
+
We as members, contributors, and leaders pledge to make participation in our
|
| 6 |
+
community a harassment-free experience for everyone, regardless of age, body
|
| 7 |
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
| 8 |
+
identity and expression, level of experience, education, socio-economic status,
|
| 9 |
+
nationality, personal appearance, race, religion, or sexual identity
|
| 10 |
+
and orientation.
|
| 11 |
+
|
| 12 |
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
| 13 |
+
diverse, inclusive, and healthy community.
|
| 14 |
+
|
| 15 |
+
## Our Standards
|
| 16 |
+
|
| 17 |
+
Examples of behavior that contributes to a positive environment for our
|
| 18 |
+
community include:
|
| 19 |
+
|
| 20 |
+
* Demonstrating empathy and kindness toward other people
|
| 21 |
+
* Being respectful of differing opinions, viewpoints, and experiences
|
| 22 |
+
* Giving and gracefully accepting constructive feedback
|
| 23 |
+
* Accepting responsibility and apologizing to those affected by our mistakes,
|
| 24 |
+
and learning from the experience
|
| 25 |
+
* Focusing on what is best not just for us as individuals, but for the
|
| 26 |
+
overall community
|
| 27 |
+
|
| 28 |
+
Examples of unacceptable behavior include:
|
| 29 |
+
|
| 30 |
+
* The use of sexualized language or imagery, and sexual attention or
|
| 31 |
+
advances of any kind
|
| 32 |
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
| 33 |
+
* Public or private harassment
|
| 34 |
+
* Publishing others' private information, such as a physical or email
|
| 35 |
+
address, without their explicit permission
|
| 36 |
+
* Other conduct which could reasonably be considered inappropriate in a
|
| 37 |
+
professional setting
|
| 38 |
+
|
| 39 |
+
## Enforcement Responsibilities
|
| 40 |
+
|
| 41 |
+
Community leaders are responsible for clarifying and enforcing our standards of
|
| 42 |
+
acceptable behavior and will take appropriate and fair corrective action in
|
| 43 |
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
| 44 |
+
or harmful.
|
| 45 |
+
|
| 46 |
+
Community leaders have the right and responsibility to remove, edit, or reject
|
| 47 |
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
| 48 |
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
| 49 |
+
decisions when appropriate.
|
| 50 |
+
|
| 51 |
+
## Scope
|
| 52 |
+
|
| 53 |
+
This Code of Conduct applies within all community spaces, and also applies when
|
| 54 |
+
an individual is officially representing the community in public spaces.
|
| 55 |
+
Examples of representing our community include using an official e-mail address,
|
| 56 |
+
posting via an official social media account, or acting as an appointed
|
| 57 |
+
representative at an online or offline event.
|
| 58 |
+
|
| 59 |
+
## Enforcement
|
| 60 |
+
|
| 61 |
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
| 62 |
+
reported to the community leaders responsible for enforcement at
|
| 63 |
+
max@binimum.org.
|
| 64 |
+
All complaints will be reviewed and investigated promptly and fairly.
|
| 65 |
+
|
| 66 |
+
All community leaders are obligated to respect the privacy and security of the
|
| 67 |
+
reporter of any incident.
|
| 68 |
+
|
| 69 |
+
## Enforcement Guidelines
|
| 70 |
+
|
| 71 |
+
Community leaders will follow these Community Impact Guidelines in determining
|
| 72 |
+
the consequences for any action they deem in violation of this Code of Conduct:
|
| 73 |
+
|
| 74 |
+
### 1. Correction
|
| 75 |
+
|
| 76 |
+
**Community Impact**: Use of inappropriate language or other behavior deemed
|
| 77 |
+
unprofessional or unwelcome in the community.
|
| 78 |
+
|
| 79 |
+
**Consequence**: A private, written warning from community leaders, providing
|
| 80 |
+
clarity around the nature of the violation and an explanation of why the
|
| 81 |
+
behavior was inappropriate. A public apology may be requested.
|
| 82 |
+
|
| 83 |
+
### 2. Warning
|
| 84 |
+
|
| 85 |
+
**Community Impact**: A violation through a single incident or series
|
| 86 |
+
of actions.
|
| 87 |
+
|
| 88 |
+
**Consequence**: A warning with consequences for continued behavior. No
|
| 89 |
+
interaction with the people involved, including unsolicited interaction with
|
| 90 |
+
those enforcing the Code of Conduct, for a specified period of time. This
|
| 91 |
+
includes avoiding interactions in community spaces as well as external channels
|
| 92 |
+
like social media. Violating these terms may lead to a temporary or
|
| 93 |
+
permanent ban.
|
| 94 |
+
|
| 95 |
+
### 3. Temporary Ban
|
| 96 |
+
|
| 97 |
+
**Community Impact**: A serious violation of community standards, including
|
| 98 |
+
sustained inappropriate behavior.
|
| 99 |
+
|
| 100 |
+
**Consequence**: A temporary ban from any sort of interaction or public
|
| 101 |
+
communication with the community for a specified period of time. No public or
|
| 102 |
+
private interaction with the people involved, including unsolicited interaction
|
| 103 |
+
with those enforcing the Code of Conduct, is allowed during this period.
|
| 104 |
+
Violating these terms may lead to a permanent ban.
|
| 105 |
+
|
| 106 |
+
### 4. Permanent Ban
|
| 107 |
+
|
| 108 |
+
**Community Impact**: Demonstrating a pattern of violation of community
|
| 109 |
+
standards, including sustained inappropriate behavior, harassment of an
|
| 110 |
+
individual, or aggression toward or disparagement of classes of individuals.
|
| 111 |
+
|
| 112 |
+
**Consequence**: A permanent ban from any sort of public interaction within
|
| 113 |
+
the community.
|
| 114 |
+
|
| 115 |
+
## Attribution
|
| 116 |
+
|
| 117 |
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
| 118 |
+
version 2.0, available at
|
| 119 |
+
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
| 120 |
+
|
| 121 |
+
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
| 122 |
+
enforcement ladder](https://github.com/mozilla/diversity).
|
| 123 |
+
|
| 124 |
+
[homepage]: https://www.contributor-covenant.org
|
| 125 |
+
|
| 126 |
+
For answers to common questions about this code of conduct, see the FAQ at
|
| 127 |
+
https://www.contributor-covenant.org/faq. Translations are available at
|
| 128 |
+
https://www.contributor-covenant.org/translations.
|
Dockerfile
CHANGED
|
@@ -1,14 +1,36 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
RUN apt-get update && apt-get install -y ffmpeg && rm -rf /var/lib/apt/lists/*
|
| 4 |
|
|
|
|
| 5 |
WORKDIR /app
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
|
|
|
|
| 11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
EXPOSE 7860
|
| 13 |
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Use a Node.js Slim image for the builder stage
|
| 2 |
+
FROM node:24.0.1-slim AS builder
|
|
|
|
| 3 |
|
| 4 |
+
# Set the working directory
|
| 5 |
WORKDIR /app
|
| 6 |
|
| 7 |
+
# Copy package files and install dependencies
|
| 8 |
+
COPY package*.json ./
|
| 9 |
+
RUN npm ci
|
| 10 |
+
|
| 11 |
+
# Copy the rest of the source files and build the SvelteKit app
|
| 12 |
+
COPY . .
|
| 13 |
+
RUN npm run build
|
| 14 |
|
| 15 |
+
# Prune dependencies to production-only
|
| 16 |
+
RUN npm prune --production
|
| 17 |
|
| 18 |
+
# Use another Node.js Slim image for the final stage
|
| 19 |
+
FROM node:24.0.1-slim AS runner
|
| 20 |
+
|
| 21 |
+
# Set the working directory
|
| 22 |
+
WORKDIR /app
|
| 23 |
+
|
| 24 |
+
# Copy the built app and production node_modules from the builder stage
|
| 25 |
+
COPY --from=builder /app/build build/
|
| 26 |
+
COPY --from=builder /app/node_modules node_modules/
|
| 27 |
+
COPY package.json .
|
| 28 |
+
|
| 29 |
+
# Expose the port the app runs on
|
| 30 |
EXPOSE 7860
|
| 31 |
|
| 32 |
+
# Set the environment to production
|
| 33 |
+
ENV NODE_ENV=production
|
| 34 |
+
|
| 35 |
+
# Specify the command to run the app
|
| 36 |
+
CMD ["node", "build"]
|
LICENSE
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 7 |
+
1.1. "Contributor"
|
| 8 |
+
means each individual or legal entity that creates, contributes to
|
| 9 |
+
the creation of, or owns Covered Software.
|
| 10 |
+
|
| 11 |
+
1.2. "Contributor Version"
|
| 12 |
+
means the combination of the Contributions of others (if any) used
|
| 13 |
+
by a Contributor and that particular Contributor's Contribution.
|
| 14 |
+
|
| 15 |
+
1.3. "Contribution"
|
| 16 |
+
means Covered Software of a particular Contributor.
|
| 17 |
+
|
| 18 |
+
1.4. "Covered Software"
|
| 19 |
+
means Source Code Form to which the initial Contributor has attached
|
| 20 |
+
the notice in Exhibit A, the Executable Form of such Source Code
|
| 21 |
+
Form, and Modifications of such Source Code Form, in each case
|
| 22 |
+
including portions thereof.
|
| 23 |
+
|
| 24 |
+
1.5. "Incompatible With Secondary Licenses"
|
| 25 |
+
means
|
| 26 |
+
|
| 27 |
+
(a) that the initial Contributor has attached the notice described
|
| 28 |
+
in Exhibit B to the Covered Software; or
|
| 29 |
+
|
| 30 |
+
(b) that the Covered Software was made available under the terms of
|
| 31 |
+
version 1.1 or earlier of the License, but not also under the
|
| 32 |
+
terms of a Secondary License.
|
| 33 |
+
|
| 34 |
+
1.6. "Executable Form"
|
| 35 |
+
means any form of the work other than Source Code Form.
|
| 36 |
+
|
| 37 |
+
1.7. "Larger Work"
|
| 38 |
+
means a work that combines Covered Software with other material, in
|
| 39 |
+
a separate file or files, that is not Covered Software.
|
| 40 |
+
|
| 41 |
+
1.8. "License"
|
| 42 |
+
means this document.
|
| 43 |
+
|
| 44 |
+
1.9. "Licensable"
|
| 45 |
+
means having the right to grant, to the maximum extent possible,
|
| 46 |
+
whether at the time of the initial grant or subsequently, any and
|
| 47 |
+
all of the rights conveyed by this License.
|
| 48 |
+
|
| 49 |
+
1.10. "Modifications"
|
| 50 |
+
means any of the following:
|
| 51 |
+
|
| 52 |
+
(a) any file in Source Code Form that results from an addition to,
|
| 53 |
+
deletion from, or modification of the contents of Covered
|
| 54 |
+
Software; or
|
| 55 |
+
|
| 56 |
+
(b) any new file in Source Code Form that contains any Covered
|
| 57 |
+
Software.
|
| 58 |
+
|
| 59 |
+
1.11. "Patent Claims" of a Contributor
|
| 60 |
+
means any patent claim(s), including without limitation, method,
|
| 61 |
+
process, and apparatus claims, in any patent Licensable by such
|
| 62 |
+
Contributor that would be infringed, but for the grant of the
|
| 63 |
+
License, by the making, using, selling, offering for sale, having
|
| 64 |
+
made, import, or transfer of either its Contributions or its
|
| 65 |
+
Contributor Version.
|
| 66 |
+
|
| 67 |
+
1.12. "Secondary License"
|
| 68 |
+
means either the GNU General Public License, Version 2.0, the GNU
|
| 69 |
+
Lesser General Public License, Version 2.1, the GNU Affero General
|
| 70 |
+
Public License, Version 3.0, or any later versions of those
|
| 71 |
+
licenses.
|
| 72 |
+
|
| 73 |
+
1.13. "Source Code Form"
|
| 74 |
+
means the form of the work preferred for making modifications.
|
| 75 |
+
|
| 76 |
+
1.14. "You" (or "Your")
|
| 77 |
+
means an individual or a legal entity exercising rights under this
|
| 78 |
+
License. For legal entities, "You" includes any entity that
|
| 79 |
+
controls, is controlled by, or is under common control with You. For
|
| 80 |
+
purposes of this definition, "control" means (a) the power, direct
|
| 81 |
+
or indirect, to cause the direction or management of such entity,
|
| 82 |
+
whether by contract or otherwise, or (b) ownership of more than
|
| 83 |
+
fifty percent (50%) of the outstanding shares or beneficial
|
| 84 |
+
ownership of such entity.
|
| 85 |
+
|
| 86 |
+
2. License Grants and Conditions
|
| 87 |
+
--------------------------------
|
| 88 |
+
|
| 89 |
+
2.1. Grants
|
| 90 |
+
|
| 91 |
+
Each Contributor hereby grants You a world-wide, royalty-free,
|
| 92 |
+
non-exclusive license:
|
| 93 |
+
|
| 94 |
+
(a) under intellectual property rights (other than patent or trademark)
|
| 95 |
+
Licensable by such Contributor to use, reproduce, make available,
|
| 96 |
+
modify, display, perform, distribute, and otherwise exploit its
|
| 97 |
+
Contributions, either on an unmodified basis, with Modifications, or
|
| 98 |
+
as part of a Larger Work; and
|
| 99 |
+
|
| 100 |
+
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
| 101 |
+
for sale, have made, import, and otherwise transfer either its
|
| 102 |
+
Contributions or its Contributor Version.
|
| 103 |
+
|
| 104 |
+
2.2. Effective Date
|
| 105 |
+
|
| 106 |
+
The licenses granted in Section 2.1 with respect to any Contribution
|
| 107 |
+
become effective for each Contribution on the date the Contributor first
|
| 108 |
+
distributes such Contribution.
|
| 109 |
+
|
| 110 |
+
2.3. Limitations on Grant Scope
|
| 111 |
+
|
| 112 |
+
The licenses granted in this Section 2 are the only rights granted under
|
| 113 |
+
this License. No additional rights or licenses will be implied from the
|
| 114 |
+
distribution or licensing of Covered Software under this License.
|
| 115 |
+
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
| 116 |
+
Contributor:
|
| 117 |
+
|
| 118 |
+
(a) for any code that a Contributor has removed from Covered Software;
|
| 119 |
+
or
|
| 120 |
+
|
| 121 |
+
(b) for infringements caused by: (i) Your and any other third party's
|
| 122 |
+
modifications of Covered Software, or (ii) the combination of its
|
| 123 |
+
Contributions with other software (except as part of its Contributor
|
| 124 |
+
Version); or
|
| 125 |
+
|
| 126 |
+
(c) under Patent Claims infringed by Covered Software in the absence of
|
| 127 |
+
its Contributions.
|
| 128 |
+
|
| 129 |
+
This License does not grant any rights in the trademarks, service marks,
|
| 130 |
+
or logos of any Contributor (except as may be necessary to comply with
|
| 131 |
+
the notice requirements in Section 3.4).
|
| 132 |
+
|
| 133 |
+
2.4. Subsequent Licenses
|
| 134 |
+
|
| 135 |
+
No Contributor makes additional grants as a result of Your choice to
|
| 136 |
+
distribute the Covered Software under a subsequent version of this
|
| 137 |
+
License (see Section 10.2) or under the terms of a Secondary License (if
|
| 138 |
+
permitted under the terms of Section 3.3).
|
| 139 |
+
|
| 140 |
+
2.5. Representation
|
| 141 |
+
|
| 142 |
+
Each Contributor represents that the Contributor believes its
|
| 143 |
+
Contributions are its original creation(s) or it has sufficient rights
|
| 144 |
+
to grant the rights to its Contributions conveyed by this License.
|
| 145 |
+
|
| 146 |
+
2.6. Fair Use
|
| 147 |
+
|
| 148 |
+
This License is not intended to limit any rights You have under
|
| 149 |
+
applicable copyright doctrines of fair use, fair dealing, or other
|
| 150 |
+
equivalents.
|
| 151 |
+
|
| 152 |
+
2.7. Conditions
|
| 153 |
+
|
| 154 |
+
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
| 155 |
+
in Section 2.1.
|
| 156 |
+
|
| 157 |
+
3. Responsibilities
|
| 158 |
+
-------------------
|
| 159 |
+
|
| 160 |
+
3.1. Distribution of Source Form
|
| 161 |
+
|
| 162 |
+
All distribution of Covered Software in Source Code Form, including any
|
| 163 |
+
Modifications that You create or to which You contribute, must be under
|
| 164 |
+
the terms of this License. You must inform recipients that the Source
|
| 165 |
+
Code Form of the Covered Software is governed by the terms of this
|
| 166 |
+
License, and how they can obtain a copy of this License. You may not
|
| 167 |
+
attempt to alter or restrict the recipients' rights in the Source Code
|
| 168 |
+
Form.
|
| 169 |
+
|
| 170 |
+
3.2. Distribution of Executable Form
|
| 171 |
+
|
| 172 |
+
If You distribute Covered Software in Executable Form then:
|
| 173 |
+
|
| 174 |
+
(a) such Covered Software must also be made available in Source Code
|
| 175 |
+
Form, as described in Section 3.1, and You must inform recipients of
|
| 176 |
+
the Executable Form how they can obtain a copy of such Source Code
|
| 177 |
+
Form by reasonable means in a timely manner, at a charge no more
|
| 178 |
+
than the cost of distribution to the recipient; and
|
| 179 |
+
|
| 180 |
+
(b) You may distribute such Executable Form under the terms of this
|
| 181 |
+
License, or sublicense it under different terms, provided that the
|
| 182 |
+
license for the Executable Form does not attempt to limit or alter
|
| 183 |
+
the recipients' rights in the Source Code Form under this License.
|
| 184 |
+
|
| 185 |
+
3.3. Distribution of a Larger Work
|
| 186 |
+
|
| 187 |
+
You may create and distribute a Larger Work under terms of Your choice,
|
| 188 |
+
provided that You also comply with the requirements of this License for
|
| 189 |
+
the Covered Software. If the Larger Work is a combination of Covered
|
| 190 |
+
Software with a work governed by one or more Secondary Licenses, and the
|
| 191 |
+
Covered Software is not Incompatible With Secondary Licenses, this
|
| 192 |
+
License permits You to additionally distribute such Covered Software
|
| 193 |
+
under the terms of such Secondary License(s), so that the recipient of
|
| 194 |
+
the Larger Work may, at their option, further distribute the Covered
|
| 195 |
+
Software under the terms of either this License or such Secondary
|
| 196 |
+
License(s).
|
| 197 |
+
|
| 198 |
+
3.4. Notices
|
| 199 |
+
|
| 200 |
+
You may not remove or alter the substance of any license notices
|
| 201 |
+
(including copyright notices, patent notices, disclaimers of warranty,
|
| 202 |
+
or limitations of liability) contained within the Source Code Form of
|
| 203 |
+
the Covered Software, except that You may alter any license notices to
|
| 204 |
+
the extent required to remedy known factual inaccuracies.
|
| 205 |
+
|
| 206 |
+
3.5. Application of Additional Terms
|
| 207 |
+
|
| 208 |
+
You may choose to offer, and to charge a fee for, warranty, support,
|
| 209 |
+
indemnity or liability obligations to one or more recipients of Covered
|
| 210 |
+
Software. However, You may do so only on Your own behalf, and not on
|
| 211 |
+
behalf of any Contributor. You must make it absolutely clear that any
|
| 212 |
+
such warranty, support, indemnity, or liability obligation is offered by
|
| 213 |
+
You alone, and You hereby agree to indemnify every Contributor for any
|
| 214 |
+
liability incurred by such Contributor as a result of warranty, support,
|
| 215 |
+
indemnity or liability terms You offer. You may include additional
|
| 216 |
+
disclaimers of warranty and limitations of liability specific to any
|
| 217 |
+
jurisdiction.
|
| 218 |
+
|
| 219 |
+
4. Inability to Comply Due to Statute or Regulation
|
| 220 |
+
---------------------------------------------------
|
| 221 |
+
|
| 222 |
+
If it is impossible for You to comply with any of the terms of this
|
| 223 |
+
License with respect to some or all of the Covered Software due to
|
| 224 |
+
statute, judicial order, or regulation then You must: (a) comply with
|
| 225 |
+
the terms of this License to the maximum extent possible; and (b)
|
| 226 |
+
describe the limitations and the code they affect. Such description must
|
| 227 |
+
be placed in a text file included with all distributions of the Covered
|
| 228 |
+
Software under this License. Except to the extent prohibited by statute
|
| 229 |
+
or regulation, such description must be sufficiently detailed for a
|
| 230 |
+
recipient of ordinary skill to be able to understand it.
|
| 231 |
+
|
| 232 |
+
5. Termination
|
| 233 |
+
--------------
|
| 234 |
+
|
| 235 |
+
5.1. The rights granted under this License will terminate automatically
|
| 236 |
+
if You fail to comply with any of its terms. However, if You become
|
| 237 |
+
compliant, then the rights granted under this License from a particular
|
| 238 |
+
Contributor are reinstated (a) provisionally, unless and until such
|
| 239 |
+
Contributor explicitly and finally terminates Your grants, and (b) on an
|
| 240 |
+
ongoing basis, if such Contributor fails to notify You of the
|
| 241 |
+
non-compliance by some reasonable means prior to 60 days after You have
|
| 242 |
+
come back into compliance. Moreover, Your grants from a particular
|
| 243 |
+
Contributor are reinstated on an ongoing basis if such Contributor
|
| 244 |
+
notifies You of the non-compliance by some reasonable means, this is the
|
| 245 |
+
first time You have received notice of non-compliance with this License
|
| 246 |
+
from such Contributor, and You become compliant prior to 30 days after
|
| 247 |
+
Your receipt of the notice.
|
| 248 |
+
|
| 249 |
+
5.2. If You initiate litigation against any entity by asserting a patent
|
| 250 |
+
infringement claim (excluding declaratory judgment actions,
|
| 251 |
+
counter-claims, and cross-claims) alleging that a Contributor Version
|
| 252 |
+
directly or indirectly infringes any patent, then the rights granted to
|
| 253 |
+
You by any and all Contributors for the Covered Software under Section
|
| 254 |
+
2.1 of this License shall terminate.
|
| 255 |
+
|
| 256 |
+
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
| 257 |
+
end user license agreements (excluding distributors and resellers) which
|
| 258 |
+
have been validly granted by You or Your distributors under this License
|
| 259 |
+
prior to termination shall survive termination.
|
| 260 |
+
|
| 261 |
+
************************************************************************
|
| 262 |
+
* *
|
| 263 |
+
* 6. Disclaimer of Warranty *
|
| 264 |
+
* ------------------------- *
|
| 265 |
+
* *
|
| 266 |
+
* Covered Software is provided under this License on an "as is" *
|
| 267 |
+
* basis, without warranty of any kind, either expressed, implied, or *
|
| 268 |
+
* statutory, including, without limitation, warranties that the *
|
| 269 |
+
* Covered Software is free of defects, merchantable, fit for a *
|
| 270 |
+
* particular purpose or non-infringing. The entire risk as to the *
|
| 271 |
+
* quality and performance of the Covered Software is with You. *
|
| 272 |
+
* Should any Covered Software prove defective in any respect, You *
|
| 273 |
+
* (not any Contributor) assume the cost of any necessary servicing, *
|
| 274 |
+
* repair, or correction. This disclaimer of warranty constitutes an *
|
| 275 |
+
* essential part of this License. No use of any Covered Software is *
|
| 276 |
+
* authorized under this License except under this disclaimer. *
|
| 277 |
+
* *
|
| 278 |
+
************************************************************************
|
| 279 |
+
|
| 280 |
+
************************************************************************
|
| 281 |
+
* *
|
| 282 |
+
* 7. Limitation of Liability *
|
| 283 |
+
* -------------------------- *
|
| 284 |
+
* *
|
| 285 |
+
* Under no circumstances and under no legal theory, whether tort *
|
| 286 |
+
* (including negligence), contract, or otherwise, shall any *
|
| 287 |
+
* Contributor, or anyone who distributes Covered Software as *
|
| 288 |
+
* permitted above, be liable to You for any direct, indirect, *
|
| 289 |
+
* special, incidental, or consequential damages of any character *
|
| 290 |
+
* including, without limitation, damages for lost profits, loss of *
|
| 291 |
+
* goodwill, work stoppage, computer failure or malfunction, or any *
|
| 292 |
+
* and all other commercial damages or losses, even if such party *
|
| 293 |
+
* shall have been informed of the possibility of such damages. This *
|
| 294 |
+
* limitation of liability shall not apply to liability for death or *
|
| 295 |
+
* personal injury resulting from such party's negligence to the *
|
| 296 |
+
* extent applicable law prohibits such limitation. Some *
|
| 297 |
+
* jurisdictions do not allow the exclusion or limitation of *
|
| 298 |
+
* incidental or consequential damages, so this exclusion and *
|
| 299 |
+
* limitation may not apply to You. *
|
| 300 |
+
* *
|
| 301 |
+
************************************************************************
|
| 302 |
+
|
| 303 |
+
8. Litigation
|
| 304 |
+
-------------
|
| 305 |
+
|
| 306 |
+
Any litigation relating to this License may be brought only in the
|
| 307 |
+
courts of a jurisdiction where the defendant maintains its principal
|
| 308 |
+
place of business and such litigation shall be governed by laws of that
|
| 309 |
+
jurisdiction, without reference to its conflict-of-law provisions.
|
| 310 |
+
Nothing in this Section shall prevent a party's ability to bring
|
| 311 |
+
cross-claims or counter-claims.
|
| 312 |
+
|
| 313 |
+
9. Miscellaneous
|
| 314 |
+
----------------
|
| 315 |
+
|
| 316 |
+
This License represents the complete agreement concerning the subject
|
| 317 |
+
matter hereof. If any provision of this License is held to be
|
| 318 |
+
unenforceable, such provision shall be reformed only to the extent
|
| 319 |
+
necessary to make it enforceable. Any law or regulation which provides
|
| 320 |
+
that the language of a contract shall be construed against the drafter
|
| 321 |
+
shall not be used to construe this License against a Contributor.
|
| 322 |
+
|
| 323 |
+
10. Versions of the License
|
| 324 |
+
---------------------------
|
| 325 |
+
|
| 326 |
+
10.1. New Versions
|
| 327 |
+
|
| 328 |
+
Mozilla Foundation is the license steward. Except as provided in Section
|
| 329 |
+
10.3, no one other than the license steward has the right to modify or
|
| 330 |
+
publish new versions of this License. Each version will be given a
|
| 331 |
+
distinguishing version number.
|
| 332 |
+
|
| 333 |
+
10.2. Effect of New Versions
|
| 334 |
+
|
| 335 |
+
You may distribute the Covered Software under the terms of the version
|
| 336 |
+
of the License under which You originally received the Covered Software,
|
| 337 |
+
or under the terms of any subsequent version published by the license
|
| 338 |
+
steward.
|
| 339 |
+
|
| 340 |
+
10.3. Modified Versions
|
| 341 |
+
|
| 342 |
+
If you create software not governed by this License, and you want to
|
| 343 |
+
create a new license for such software, you may create and use a
|
| 344 |
+
modified version of this License if you rename the license and remove
|
| 345 |
+
any references to the name of the license steward (except to note that
|
| 346 |
+
such modified license differs from this License).
|
| 347 |
+
|
| 348 |
+
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
| 349 |
+
Licenses
|
| 350 |
+
|
| 351 |
+
If You choose to distribute Source Code Form that is Incompatible With
|
| 352 |
+
Secondary Licenses under the terms of this version of the License, the
|
| 353 |
+
notice described in Exhibit B of this License must be attached.
|
| 354 |
+
|
| 355 |
+
Exhibit A - Source Code Form License Notice
|
| 356 |
+
-------------------------------------------
|
| 357 |
+
|
| 358 |
+
This Source Code Form is subject to the terms of the Mozilla Public
|
| 359 |
+
License, v. 2.0. If a copy of the MPL was not distributed with this
|
| 360 |
+
file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
| 361 |
+
|
| 362 |
+
If it is not possible or desirable to put the notice in a particular
|
| 363 |
+
file, then You may include the notice in a location (such as a LICENSE
|
| 364 |
+
file in a relevant directory) where a recipient would be likely to look
|
| 365 |
+
for such a notice.
|
| 366 |
+
|
| 367 |
+
You may add additional accurate notices of copyright ownership.
|
| 368 |
+
|
| 369 |
+
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
| 370 |
+
---------------------------------------------------------
|
| 371 |
+
|
| 372 |
+
This Source Code Form is "Incompatible With Secondary Licenses", as
|
| 373 |
+
defined by the Mozilla Public License, v. 2.0.
|
bun.lock
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
docker-compose.yml
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version: '3'
|
| 2 |
+
|
| 3 |
+
services:
|
| 4 |
+
svelte-prod:
|
| 5 |
+
build:
|
| 6 |
+
context: .
|
| 7 |
+
dockerfile: ./Dockerfile
|
| 8 |
+
ports:
|
| 9 |
+
- '7860:7860'
|
| 10 |
+
restart: unless-stopped
|
| 11 |
+
environment:
|
| 12 |
+
- NODE_ENV=production
|
| 13 |
+
- TITLE=${TITLE}
|
| 14 |
+
- REDIS_URL=${REDIS_URL}
|
| 15 |
+
- REDIS_HOST=${REDIS_HOST}
|
| 16 |
+
- REDIS_PORT=${REDIS_PORT}
|
| 17 |
+
- REDIS_USERNAME=${REDIS_USERNAME}
|
| 18 |
+
- REDIS_PASSWORD=${REDIS_PASSWORD}
|
| 19 |
+
- REDIS_TLS=${REDIS_TLS}
|
| 20 |
+
- REDIS_CACHE_TTL_SECONDS=${REDIS_CACHE_TTL_SECONDS}
|
| 21 |
+
- REDIS_CACHE_TTL_SEARCH_SECONDS=${REDIS_CACHE_TTL_SEARCH_SECONDS}
|
| 22 |
+
- REDIS_CACHE_TTL_TRACK_SECONDS=${REDIS_CACHE_TTL_TRACK_SECONDS}
|
| 23 |
+
- REDIS_CACHE_MAX_BODY_BYTES=${REDIS_CACHE_MAX_BODY_BYTES}
|
| 24 |
+
- PORT=7860
|
| 25 |
+
|
| 26 |
+
networks:
|
| 27 |
+
default:
|
| 28 |
+
driver: bridge
|
eslint.config.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import prettier from 'eslint-config-prettier';
|
| 2 |
+
import { fileURLToPath } from 'node:url';
|
| 3 |
+
import { includeIgnoreFile } from '@eslint/compat';
|
| 4 |
+
import js from '@eslint/js';
|
| 5 |
+
import svelte from 'eslint-plugin-svelte';
|
| 6 |
+
import { defineConfig } from 'eslint/config';
|
| 7 |
+
import globals from 'globals';
|
| 8 |
+
import ts from 'typescript-eslint';
|
| 9 |
+
import svelteConfig from './svelte.config.js';
|
| 10 |
+
|
| 11 |
+
const gitignorePath = fileURLToPath(new URL('./.gitignore', import.meta.url));
|
| 12 |
+
|
| 13 |
+
export default defineConfig(
|
| 14 |
+
includeIgnoreFile(gitignorePath),
|
| 15 |
+
js.configs.recommended,
|
| 16 |
+
...ts.configs.recommended,
|
| 17 |
+
...svelte.configs.recommended,
|
| 18 |
+
prettier,
|
| 19 |
+
...svelte.configs.prettier,
|
| 20 |
+
{
|
| 21 |
+
languageOptions: {
|
| 22 |
+
globals: { ...globals.browser, ...globals.node }
|
| 23 |
+
},
|
| 24 |
+
rules: {
|
| 25 |
+
// typescript-eslint strongly recommend that you do not use the no-undef lint rule on TypeScript projects.
|
| 26 |
+
// see: https://typescript-eslint.io/troubleshooting/faqs/eslint/#i-get-errors-from-the-no-undef-rule-about-global-variables-not-being-defined-even-though-there-are-no-typescript-errors
|
| 27 |
+
'no-undef': 'off'
|
| 28 |
+
}
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
files: ['**/*.svelte', '**/*.svelte.ts', '**/*.svelte.js'],
|
| 32 |
+
languageOptions: {
|
| 33 |
+
parserOptions: {
|
| 34 |
+
projectService: true,
|
| 35 |
+
extraFileExtensions: ['.svelte'],
|
| 36 |
+
parser: ts.parser,
|
| 37 |
+
svelteConfig
|
| 38 |
+
}
|
| 39 |
+
}
|
| 40 |
+
}
|
| 41 |
+
);
|
generate_spotify_totp.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 5 |
+
|
| 6 |
+
Automatic extractor for secret keys used for TOTP generation in Spotify Web Player JavaScript bundles
|
| 7 |
+
https://github.com/misiektoja/spotify_monitor#debugging-tools
|
| 8 |
+
|
| 9 |
+
Python pip3 requirements:
|
| 10 |
+
|
| 11 |
+
playwright
|
| 12 |
+
|
| 13 |
+
Install:
|
| 14 |
+
|
| 15 |
+
pip install playwright
|
| 16 |
+
playwright install
|
| 17 |
+
|
| 18 |
+
---------------
|
| 19 |
+
|
| 20 |
+
Change log:
|
| 21 |
+
|
| 22 |
+
v1.2 (12 Oct 25):
|
| 23 |
+
- Added CLI output modes (--secret, --secretbytes and --secretdict CLI flags, see -h for help)
|
| 24 |
+
- Added --all mode writing all secret formats to files (secrets.json, secretBytes.json, secretDict.json) (thx @tomballgithub)
|
| 25 |
+
|
| 26 |
+
v1.1 (12 Jul 25):
|
| 27 |
+
- Added JSON array output for plain secrets and secret bytes
|
| 28 |
+
|
| 29 |
+
v1.0 (09 Jul 25):
|
| 30 |
+
- Initial proof-of-concept, confirmed to extract v10, v11 and v12 secrets
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
import asyncio
|
| 35 |
+
import re
|
| 36 |
+
from datetime import datetime
|
| 37 |
+
import json
|
| 38 |
+
from typing import List, Dict, Any
|
| 39 |
+
from playwright.async_api import async_playwright
|
| 40 |
+
import argparse
|
| 41 |
+
import sys
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
BUNDLE_RE = re.compile(r"""(?x)(?:vendor~web-player|encore~web-player|web-player)\.[0-9a-f]{4,}\.(?:js|mjs)""")
|
| 45 |
+
TIMEOUT = 45000 # 45s
|
| 46 |
+
VERBOSE = True
|
| 47 |
+
|
| 48 |
+
OUTPUT_FILES = {
|
| 49 |
+
'plain_json': 'secrets.json',
|
| 50 |
+
'bytes_json_array': 'secretBytes.json',
|
| 51 |
+
'bytes_json_dict': 'secretDict.json',
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _inline_int_array(nums):
|
| 56 |
+
return '[ ' + ', '.join(str(n) for n in nums) + ' ]'
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _write_secretbytes_compact(fp, items):
|
| 60 |
+
fp.write('[\n')
|
| 61 |
+
last = len(items) - 1
|
| 62 |
+
for i, itm in enumerate(items):
|
| 63 |
+
comma = ',' if i < last else ''
|
| 64 |
+
fp.write(f' {{ "version": {itm["version"]}, "secret": {_inline_int_array(itm["secret"])} }}{comma}\n')
|
| 65 |
+
fp.write(']\n')
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _write_secretdict_compact(fp, mapping):
|
| 69 |
+
keys = sorted(mapping.keys(), key=lambda k: int(k))
|
| 70 |
+
fp.write('{\n')
|
| 71 |
+
for i, v in enumerate(keys):
|
| 72 |
+
comma = ',' if i < len(keys) - 1 else ''
|
| 73 |
+
fp.write(f' "{v}": {_inline_int_array(mapping[v])}{comma}\n')
|
| 74 |
+
fp.write('}\n')
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def log(m):
|
| 78 |
+
if VERBOSE:
|
| 79 |
+
print(f"[{datetime.now().strftime('%H:%M:%S')}] {m}")
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def summarise(caps: List[Dict[str, Any]], mode=None):
|
| 83 |
+
real = {}
|
| 84 |
+
|
| 85 |
+
for cap in caps:
|
| 86 |
+
sec = cap.get('secret')
|
| 87 |
+
if not isinstance(sec, str):
|
| 88 |
+
continue
|
| 89 |
+
ver = cap.get('version') or (isinstance(cap.get('obj'), dict) and cap['obj'].get('version'))
|
| 90 |
+
if ver is None:
|
| 91 |
+
continue
|
| 92 |
+
real[str(ver)] = sec
|
| 93 |
+
|
| 94 |
+
if not real:
|
| 95 |
+
log('No real secrets with version.')
|
| 96 |
+
return
|
| 97 |
+
|
| 98 |
+
sorted_items = sorted(real.items(), key=lambda kv: int(kv[0]))
|
| 99 |
+
formatted_data = [{"version": int(v), "secret": s} for v, s in sorted_items]
|
| 100 |
+
secret_bytes = [{"version": int(v), "secret": [ord(c) for c in s]} for v, s in sorted_items]
|
| 101 |
+
secret_dict = {v: [ord(c) for c in s] for v, s in sorted_items}
|
| 102 |
+
|
| 103 |
+
if mode is None:
|
| 104 |
+
print("\n--- List of extracted secrets ---\n")
|
| 105 |
+
for v, s in sorted(real.items(), key=lambda kv: int(kv[0])):
|
| 106 |
+
print(f"v{v}: '{s}'")
|
| 107 |
+
|
| 108 |
+
print("\n--- Plain secrets (JSON array) ---\n")
|
| 109 |
+
print(json.dumps(formatted_data, indent=2))
|
| 110 |
+
|
| 111 |
+
print("\n--- Secret bytes (JSON array) ---\n")
|
| 112 |
+
print('[')
|
| 113 |
+
for idx, itm in enumerate(secret_bytes):
|
| 114 |
+
comma = ',' if idx < len(secret_bytes) - 1 else ''
|
| 115 |
+
print(' {')
|
| 116 |
+
print(f' "version": {itm["version"]},')
|
| 117 |
+
print(f' "secret": {_inline_int_array(itm["secret"])}')
|
| 118 |
+
print(f' }}{comma}')
|
| 119 |
+
print(']')
|
| 120 |
+
|
| 121 |
+
print("\n--- Secret bytes (JSON object/dict): version -> byte list mapping ---\n")
|
| 122 |
+
print('{')
|
| 123 |
+
last = len(real) - 1
|
| 124 |
+
for idx, (v, s) in enumerate(sorted(real.items(), key=lambda kv: int(kv[0]))):
|
| 125 |
+
arr = [ord(c) for c in s]
|
| 126 |
+
comma = ',' if idx < last else ''
|
| 127 |
+
print(f' "{v}": {_inline_int_array(arr)}{comma}')
|
| 128 |
+
print('}')
|
| 129 |
+
|
| 130 |
+
elif mode == 'secret':
|
| 131 |
+
print(json.dumps(formatted_data, indent=2))
|
| 132 |
+
|
| 133 |
+
elif mode == 'secretbytes':
|
| 134 |
+
print('[')
|
| 135 |
+
for idx, itm in enumerate(secret_bytes):
|
| 136 |
+
comma = ',' if idx < len(secret_bytes) - 1 else ''
|
| 137 |
+
print(f' {{ "version": {itm["version"]}, "secret": {_inline_int_array(itm["secret"])} }}{comma}')
|
| 138 |
+
print(']')
|
| 139 |
+
|
| 140 |
+
elif mode == 'secretdict':
|
| 141 |
+
print('{')
|
| 142 |
+
last = len(real) - 1
|
| 143 |
+
for idx, (v, s) in enumerate(sorted(real.items(), key=lambda kv: int(kv[0]))):
|
| 144 |
+
arr = [ord(c) for c in s]
|
| 145 |
+
comma = ',' if idx < last else ''
|
| 146 |
+
print(f' "{v}": {_inline_int_array(arr)}{comma}')
|
| 147 |
+
print('}')
|
| 148 |
+
|
| 149 |
+
elif mode == 'all':
|
| 150 |
+
try:
|
| 151 |
+
with open(OUTPUT_FILES['plain_json'], 'w') as f:
|
| 152 |
+
json.dump(formatted_data, f, indent=2)
|
| 153 |
+
f.write('\n')
|
| 154 |
+
with open(OUTPUT_FILES['bytes_json_array'], 'w') as f:
|
| 155 |
+
_write_secretbytes_compact(f, secret_bytes)
|
| 156 |
+
with open(OUTPUT_FILES['bytes_json_dict'], 'w') as f:
|
| 157 |
+
_write_secretdict_compact(f, secret_dict)
|
| 158 |
+
if VERBOSE:
|
| 159 |
+
print(f"[+] Wrote plain secrets to {OUTPUT_FILES['plain_json']}")
|
| 160 |
+
print(f"[+] Wrote secret bytes array to {OUTPUT_FILES['bytes_json_array']}")
|
| 161 |
+
print(f"[+] Wrote secret bytes dict to {OUTPUT_FILES['bytes_json_dict']}")
|
| 162 |
+
except Exception as e:
|
| 163 |
+
print(f"Error writing output files: {e}", file=sys.stderr)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
async def grab_live():
|
| 167 |
+
hook = """(()=>{if(globalThis.__secretHookInstalled)return;globalThis.__secretHookInstalled=true;globalThis.__captures=[];
|
| 168 |
+
Object.defineProperty(Object.prototype,'secret',{configurable:true,set:function(v){try{__captures.push({secret:v,version:this.version,obj:this});}catch(e){}
|
| 169 |
+
Object.defineProperty(this,'secret',{value:v,writable:true,configurable:true,enumerable:true});}});})();"""
|
| 170 |
+
|
| 171 |
+
async with async_playwright() as p:
|
| 172 |
+
b = await p.chromium.launch(headless=True)
|
| 173 |
+
ctx = await b.new_context()
|
| 174 |
+
await ctx.add_init_script(hook)
|
| 175 |
+
pg = await ctx.new_page()
|
| 176 |
+
pg.on('response', lambda resp: BUNDLE_RE.fullmatch(resp.url.split('/')[-1]) and log(f"↓ {resp.url.split('/')[-1]} ({resp.status})"))
|
| 177 |
+
log('→ opening open.spotify.com ...')
|
| 178 |
+
await pg.goto('https://open.spotify.com', timeout=TIMEOUT)
|
| 179 |
+
await pg.wait_for_load_state('networkidle', timeout=TIMEOUT)
|
| 180 |
+
await pg.wait_for_timeout(3000)
|
| 181 |
+
caps = await pg.evaluate('__captures')
|
| 182 |
+
|
| 183 |
+
if caps:
|
| 184 |
+
for c in caps:
|
| 185 |
+
if isinstance(c.get('secret'), str) and c.get('version') is not None:
|
| 186 |
+
log(f"✔ secret({c.get('version')}) → {c.get('secret')}")
|
| 187 |
+
|
| 188 |
+
await b.close()
|
| 189 |
+
return caps or []
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def main():
|
| 193 |
+
parser = argparse.ArgumentParser(description='Extract Spotify web-player TOTP secrets')
|
| 194 |
+
parser.add_argument('--secret', action='store_true', help='Output plain secrets JSON only')
|
| 195 |
+
parser.add_argument('--secretbytes', action='store_true', help='Output secret-bytes JSON only')
|
| 196 |
+
parser.add_argument('--secretdict', action='store_true', help='Output version->byte-list dict JSON only')
|
| 197 |
+
parser.add_argument('--all', action='store_true', help='Write plain, bytes array and bytes dict JSON files')
|
| 198 |
+
args = parser.parse_args()
|
| 199 |
+
|
| 200 |
+
mode = None
|
| 201 |
+
if args.secret:
|
| 202 |
+
mode = 'secret'
|
| 203 |
+
elif args.secretbytes:
|
| 204 |
+
mode = 'secretbytes'
|
| 205 |
+
elif args.secretdict:
|
| 206 |
+
mode = 'secretdict'
|
| 207 |
+
elif args.all:
|
| 208 |
+
mode = 'all'
|
| 209 |
+
|
| 210 |
+
global VERBOSE
|
| 211 |
+
if mode and mode != 'all':
|
| 212 |
+
VERBOSE = False
|
| 213 |
+
elif mode == 'all':
|
| 214 |
+
VERBOSE = True
|
| 215 |
+
|
| 216 |
+
try:
|
| 217 |
+
caps = asyncio.run(grab_live())
|
| 218 |
+
summarise(caps, mode)
|
| 219 |
+
except Exception as e:
|
| 220 |
+
print(f"Error: {e}", file=sys.stderr)
|
| 221 |
+
sys.exit(1)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
if __name__ == '__main__':
|
| 225 |
+
main()
|
package-lock.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
package.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "tidal-ui",
|
| 3 |
+
"private": true,
|
| 4 |
+
"version": "3.0.0",
|
| 5 |
+
"license": "MPL-2.0",
|
| 6 |
+
"type": "module",
|
| 7 |
+
"scripts": {
|
| 8 |
+
"dev": "vite dev",
|
| 9 |
+
"build": "vite build",
|
| 10 |
+
"preview": "vite preview",
|
| 11 |
+
"prepare": "svelte-kit sync || echo ''",
|
| 12 |
+
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
| 13 |
+
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
|
| 14 |
+
"format": "prettier --write .",
|
| 15 |
+
"lint": "prettier --check . && eslint ."
|
| 16 |
+
},
|
| 17 |
+
"devDependencies": {
|
| 18 |
+
"@eslint/compat": "^1.2.5",
|
| 19 |
+
"@eslint/js": "^9.22.0",
|
| 20 |
+
"@sveltejs/adapter-auto": "^6.0.0",
|
| 21 |
+
"@sveltejs/adapter-cloudflare": "^7.2.4",
|
| 22 |
+
"@sveltejs/adapter-node": "^5.3.3",
|
| 23 |
+
"@sveltejs/adapter-vercel": "^5.10.3",
|
| 24 |
+
"@sveltejs/kit": "^2.22.0",
|
| 25 |
+
"@sveltejs/vite-plugin-svelte": "^6.0.0",
|
| 26 |
+
"@tailwindcss/forms": "^0.5.9",
|
| 27 |
+
"@tailwindcss/typography": "^0.5.15",
|
| 28 |
+
"@tailwindcss/vite": "^4.0.0",
|
| 29 |
+
"@types/colorthief": "^2.6.0",
|
| 30 |
+
"@types/node": "^20",
|
| 31 |
+
"eslint": "^9.22.0",
|
| 32 |
+
"eslint-config-prettier": "^10.0.1",
|
| 33 |
+
"eslint-plugin-svelte": "^3.0.0",
|
| 34 |
+
"globals": "^16.0.0",
|
| 35 |
+
"prettier": "^3.4.2",
|
| 36 |
+
"prettier-plugin-svelte": "^3.3.3",
|
| 37 |
+
"prettier-plugin-tailwindcss": "^0.6.11",
|
| 38 |
+
"svelte": "^5.0.0",
|
| 39 |
+
"svelte-check": "^4.0.0",
|
| 40 |
+
"tailwindcss": "^4.0.0",
|
| 41 |
+
"typescript": "^5.0.0",
|
| 42 |
+
"typescript-eslint": "^8.20.0",
|
| 43 |
+
"vite": "^7.0.4",
|
| 44 |
+
"vite-plugin-devtools-json": "^1.0.0"
|
| 45 |
+
},
|
| 46 |
+
"dependencies": {
|
| 47 |
+
"@ffmpeg/ffmpeg": "^0.12.6",
|
| 48 |
+
"@ffmpeg/util": "^0.12.1",
|
| 49 |
+
"colorthief": "^2.6.0",
|
| 50 |
+
"ioredis": "^5.4.1",
|
| 51 |
+
"jszip": "^3.10.1",
|
| 52 |
+
"lucide-svelte": "^0.544.0",
|
| 53 |
+
"shaka-player": "^4.11.7"
|
| 54 |
+
}
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 8 |
+
[type='reset'],
|
| 9 |
+
a,
|
| 10 |
+
[role='button'],
|
| 11 |
+
summary {
|
| 12 |
+
cursor: pointer;
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
button:disabled,
|
| 16 |
+
[type='button']:disabled,
|
| 17 |
+
[type='submit']:disabled,
|
| 18 |
+
[type='reset']:disabled,
|
| 19 |
+
[role='button'][aria-disabled='true'],
|
| 20 |
+
a[aria-disabled='true'] {
|
| 21 |
+
cursor: not-allowed;
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
/* ============================================
|
| 25 |
+
DESIGN SYSTEM TOKENS
|
| 26 |
+
============================================ */
|
| 27 |
+
|
| 28 |
+
/* Performance-optimized blur and effects */
|
| 29 |
+
:root[data-performance='medium'] {
|
| 30 |
+
--perf-blur-high: 22px;
|
| 31 |
+
--perf-blur-medium: 18px;
|
| 32 |
+
--perf-blur-low: 14px;
|
| 33 |
+
--perf-saturate: 125%;
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
:root[data-performance='low'] {
|
| 37 |
+
--perf-blur-high: 0px;
|
| 38 |
+
--perf-blur-medium: 0px;
|
| 39 |
+
--perf-blur-low: 0px;
|
| 40 |
+
--perf-saturate: 100%;
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
:root[data-performance='low'] * {
|
| 44 |
+
backdrop-filter: none !important;
|
| 45 |
+
-webkit-backdrop-filter: none !important;
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
:root[data-performance='low'] .glass-panel,
|
| 49 |
+
:root[data-performance='low'] .glass-toolbar,
|
| 50 |
+
:root[data-performance='low'] .settings-menu,
|
| 51 |
+
:root[data-performance='low'] .toolbar-button,
|
| 52 |
+
:root[data-performance='low'] .glass-option,
|
| 53 |
+
:root[data-performance='low'] .glass-action,
|
| 54 |
+
:root[data-performance='low'] .glass-option__chip,
|
| 55 |
+
:root[data-performance='low'] .glass-panel__footer,
|
| 56 |
+
:root[data-performance='low'] .navigation-overlay,
|
| 57 |
+
:root[data-performance='low'] .navigation-overlay__progress {
|
| 58 |
+
background-color: rgba(15, 23, 42, 0.92) !important;
|
| 59 |
+
border-color: rgba(148, 163, 184, 0.2) !important;
|
| 60 |
+
box-shadow: none !important;
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
:root[data-performance='low'] .toolbar-button,
|
| 64 |
+
:root[data-performance='low'] .glass-option,
|
| 65 |
+
:root[data-performance='low'] .glass-action {
|
| 66 |
+
transition: none;
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
:root:not([data-performance='medium']):not([data-performance='low']) {
|
| 70 |
+
--perf-blur-high: 32px;
|
| 71 |
+
--perf-blur-medium: 28px;
|
| 72 |
+
--perf-blur-low: 24px;
|
| 73 |
+
--perf-saturate: 160%;
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
/* Enhanced Color Palette */
|
| 77 |
+
:root {
|
| 78 |
+
/* Primary Blues */
|
| 79 |
+
--color-primary-50: #eff6ff;
|
| 80 |
+
--color-primary-100: #dbeafe;
|
| 81 |
+
--color-primary-200: #bfdbfe;
|
| 82 |
+
--color-primary-300: #93c5fd;
|
| 83 |
+
--color-primary-400: #60a5fa;
|
| 84 |
+
--color-primary-500: #3b82f6;
|
| 85 |
+
--color-primary-600: #2563eb;
|
| 86 |
+
--color-primary-700: #1d4ed8;
|
| 87 |
+
--color-primary-800: #1e40af;
|
| 88 |
+
--color-primary-900: #1e3a8a;
|
| 89 |
+
|
| 90 |
+
/* Accent Purples */
|
| 91 |
+
--color-accent-400: #a78bfa;
|
| 92 |
+
--color-accent-500: #8b5cf6;
|
| 93 |
+
--color-accent-600: #7c3aed;
|
| 94 |
+
|
| 95 |
+
/* Neutrals (Slate) */
|
| 96 |
+
--color-neutral-50: #f8fafc;
|
| 97 |
+
--color-neutral-100: #f1f5f9;
|
| 98 |
+
--color-neutral-200: #e2e8f0;
|
| 99 |
+
--color-neutral-300: #cbd5e1;
|
| 100 |
+
--color-neutral-400: #94a3b8;
|
| 101 |
+
--color-neutral-500: #64748b;
|
| 102 |
+
--color-neutral-600: #475569;
|
| 103 |
+
--color-neutral-700: #334155;
|
| 104 |
+
--color-neutral-800: #1e293b;
|
| 105 |
+
--color-neutral-900: #0f172a;
|
| 106 |
+
--color-neutral-950: #020617;
|
| 107 |
+
|
| 108 |
+
/* Semantic Colors */
|
| 109 |
+
--color-success-500: #22c55e;
|
| 110 |
+
--color-warning-500: #f59e0b;
|
| 111 |
+
--color-error-500: #ef4444;
|
| 112 |
+
|
| 113 |
+
/* Spacing Scale */
|
| 114 |
+
--space-1: 0.25rem;
|
| 115 |
+
--space-2: 0.5rem;
|
| 116 |
+
--space-3: 0.75rem;
|
| 117 |
+
--space-4: 1rem;
|
| 118 |
+
--space-5: 1.25rem;
|
| 119 |
+
--space-6: 1.5rem;
|
| 120 |
+
--space-8: 2rem;
|
| 121 |
+
--space-10: 2.5rem;
|
| 122 |
+
--space-12: 3rem;
|
| 123 |
+
--space-16: 4rem;
|
| 124 |
+
|
| 125 |
+
/* Border Radius */
|
| 126 |
+
--radius-sm: 0.375rem;
|
| 127 |
+
--radius-md: 0.5rem;
|
| 128 |
+
--radius-lg: 0.75rem;
|
| 129 |
+
--radius-xl: 1rem;
|
| 130 |
+
--radius-2xl: 1.25rem;
|
| 131 |
+
--radius-full: 9999px;
|
| 132 |
+
|
| 133 |
+
/* Shadows */
|
| 134 |
+
--shadow-glow-sm: 0 0 10px rgba(59, 130, 246, 0.15);
|
| 135 |
+
--shadow-glow-md: 0 0 20px rgba(59, 130, 246, 0.2);
|
| 136 |
+
--shadow-glow-lg: 0 0 40px rgba(59, 130, 246, 0.25);
|
| 137 |
+
|
| 138 |
+
/* Transitions */
|
| 139 |
+
--transition-fast: 150ms cubic-bezier(0.4, 0, 0.2, 1);
|
| 140 |
+
--transition-base: 200ms cubic-bezier(0.4, 0, 0.2, 1);
|
| 141 |
+
--transition-slow: 300ms cubic-bezier(0.4, 0, 0.2, 1);
|
| 142 |
+
--transition-spring: 500ms cubic-bezier(0.34, 1.56, 0.64, 1);
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
/* Gradient Definitions */
|
| 146 |
+
.gradient-primary {
|
| 147 |
+
background: linear-gradient(135deg, var(--color-primary-500) 0%, var(--color-accent-500) 100%);
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
.gradient-text-primary {
|
| 151 |
+
background: linear-gradient(135deg, var(--color-primary-400) 0%, var(--color-accent-400) 100%);
|
| 152 |
+
-webkit-background-clip: text;
|
| 153 |
+
background-clip: text;
|
| 154 |
+
color: transparent;
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
.gradient-text-hero {
|
| 158 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
|
| 159 |
+
background-size: 200% 200%;
|
| 160 |
+
-webkit-background-clip: text;
|
| 161 |
+
background-clip: text;
|
| 162 |
+
color: transparent;
|
| 163 |
+
animation: gradient-shift 8s ease infinite;
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
@keyframes gradient-shift {
|
| 167 |
+
0%, 100% { background-position: 0% 50%; }
|
| 168 |
+
50% { background-position: 100% 50%; }
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
/* Glass Effect Utilities */
|
| 172 |
+
.glass-subtle {
|
| 173 |
+
background: rgba(15, 23, 42, 0.4);
|
| 174 |
+
backdrop-filter: blur(var(--perf-blur-low, 24px)) saturate(var(--perf-saturate, 160%));
|
| 175 |
+
-webkit-backdrop-filter: blur(var(--perf-blur-low, 24px)) saturate(var(--perf-saturate, 160%));
|
| 176 |
+
border: 1px solid rgba(148, 163, 184, 0.12);
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
.glass-medium {
|
| 180 |
+
background: rgba(15, 23, 42, 0.55);
|
| 181 |
+
backdrop-filter: blur(var(--perf-blur-medium, 28px)) saturate(var(--perf-saturate, 160%));
|
| 182 |
+
-webkit-backdrop-filter: blur(var(--perf-blur-medium, 28px)) saturate(var(--perf-saturate, 160%));
|
| 183 |
+
border: 1px solid rgba(148, 163, 184, 0.15);
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
.glass-strong {
|
| 187 |
+
background: rgba(15, 23, 42, 0.7);
|
| 188 |
+
backdrop-filter: blur(var(--perf-blur-high, 32px)) saturate(var(--perf-saturate, 160%));
|
| 189 |
+
-webkit-backdrop-filter: blur(var(--perf-blur-high, 32px)) saturate(var(--perf-saturate, 160%));
|
| 190 |
+
border: 1px solid rgba(148, 163, 184, 0.18);
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
/* Hover Lift Effect */
|
| 194 |
+
.hover-lift {
|
| 195 |
+
transition: transform var(--transition-base), box-shadow var(--transition-base);
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
.hover-lift:hover {
|
| 199 |
+
transform: translateY(-2px);
|
| 200 |
+
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
/* Glow on Focus/Hover */
|
| 204 |
+
.glow-on-hover {
|
| 205 |
+
transition: box-shadow var(--transition-base);
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
.glow-on-hover:hover {
|
| 209 |
+
box-shadow: var(--shadow-glow-md);
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
/* Card Styles */
|
| 213 |
+
.card-interactive {
|
| 214 |
+
transition:
|
| 215 |
+
transform var(--transition-base),
|
| 216 |
+
box-shadow var(--transition-base),
|
| 217 |
+
border-color var(--transition-slow);
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
.card-interactive:hover {
|
| 221 |
+
transform: translateY(-2px) scale(1.01);
|
| 222 |
+
box-shadow:
|
| 223 |
+
0 20px 50px rgba(2, 6, 23, 0.4),
|
| 224 |
+
var(--shadow-glow-sm);
|
| 225 |
+
border-color: rgba(148, 163, 184, 0.25);
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
/* ============================================
|
| 229 |
+
MOBILE PERFORMANCE OPTIMIZATIONS
|
| 230 |
+
============================================ */
|
| 231 |
+
|
| 232 |
+
/* Mobile-specific blur reduction (major GPU savings) */
|
| 233 |
+
@media (max-width: 768px) {
|
| 234 |
+
:root:not([data-performance='low']) {
|
| 235 |
+
--perf-blur-high: 16px;
|
| 236 |
+
--perf-blur-medium: 12px;
|
| 237 |
+
--perf-blur-low: 8px;
|
| 238 |
+
--perf-saturate: 130%;
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
:root[data-performance='medium'] {
|
| 242 |
+
--perf-blur-high: 12px;
|
| 243 |
+
--perf-blur-medium: 8px;
|
| 244 |
+
--perf-blur-low: 6px;
|
| 245 |
+
--perf-saturate: 120%;
|
| 246 |
+
}
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
/* Touch device optimizations */
|
| 250 |
+
@media (pointer: coarse) {
|
| 251 |
+
/* Disable hover effects that cause sticky states on touch */
|
| 252 |
+
.hover-lift:hover {
|
| 253 |
+
transform: none;
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
/* Active state for touch feedback */
|
| 257 |
+
.hover-lift:active {
|
| 258 |
+
transform: scale(0.98);
|
| 259 |
+
}
|
| 260 |
+
|
| 261 |
+
.card-interactive:hover {
|
| 262 |
+
transform: none;
|
| 263 |
+
box-shadow: none;
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
.card-interactive:active {
|
| 267 |
+
transform: scale(0.99);
|
| 268 |
+
background: rgba(148, 163, 184, 0.08);
|
| 269 |
+
}
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
/* GPU acceleration for animated elements */
|
| 273 |
+
.gpu-accelerated {
|
| 274 |
+
transform: translateZ(0);
|
| 275 |
+
will-change: transform;
|
| 276 |
+
backface-visibility: hidden;
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
/* CSS Containment for performance */
|
| 280 |
+
.contain-layout {
|
| 281 |
+
contain: layout;
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
.contain-paint {
|
| 285 |
+
contain: paint;
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
.contain-strict {
|
| 289 |
+
contain: strict;
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
.contain-content {
|
| 293 |
+
contain: content;
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
/* Off-screen content optimization */
|
| 297 |
+
.content-visibility-auto {
|
| 298 |
+
content-visibility: auto;
|
| 299 |
+
contain-intrinsic-size: auto 300px;
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
/* ============================================
|
| 303 |
+
TOUCH-FRIENDLY DEFAULTS
|
| 304 |
+
============================================ */
|
| 305 |
+
|
| 306 |
+
/* Minimum touch target size (44px as per Apple/Google guidelines) */
|
| 307 |
+
.touch-target {
|
| 308 |
+
min-height: 44px;
|
| 309 |
+
min-width: 44px;
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
.touch-target-lg {
|
| 313 |
+
min-height: 48px;
|
| 314 |
+
min-width: 48px;
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
/* Remove tap highlight on mobile */
|
| 318 |
+
* {
|
| 319 |
+
-webkit-tap-highlight-color: transparent;
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
/* Safe area padding for notched devices */
|
| 323 |
+
.safe-area-top {
|
| 324 |
+
padding-top: env(safe-area-inset-top, 0);
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
.safe-area-bottom {
|
| 328 |
+
padding-bottom: env(safe-area-inset-bottom, 0);
|
| 329 |
+
}
|
| 330 |
+
|
| 331 |
+
.safe-area-left {
|
| 332 |
+
padding-left: env(safe-area-inset-left, 0);
|
| 333 |
+
}
|
| 334 |
+
|
| 335 |
+
.safe-area-right {
|
| 336 |
+
padding-right: env(safe-area-inset-right, 0);
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
.safe-area-x {
|
| 340 |
+
padding-left: env(safe-area-inset-left, 0);
|
| 341 |
+
padding-right: env(safe-area-inset-right, 0);
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
.safe-area-y {
|
| 345 |
+
padding-top: env(safe-area-inset-top, 0);
|
| 346 |
+
padding-bottom: env(safe-area-inset-bottom, 0);
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
/* ============================================
|
| 350 |
+
REDUCED MOTION PREFERENCES
|
| 351 |
+
============================================ */
|
| 352 |
+
|
| 353 |
+
@media (prefers-reduced-motion: reduce) {
|
| 354 |
+
*,
|
| 355 |
+
*::before,
|
| 356 |
+
*::after {
|
| 357 |
+
animation-duration: 0.01ms !important;
|
| 358 |
+
animation-iteration-count: 1 !important;
|
| 359 |
+
transition-duration: 0.01ms !important;
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
.gradient-text-hero {
|
| 363 |
+
animation: none;
|
| 364 |
+
background-size: 100% 100%;
|
| 365 |
+
}
|
| 366 |
+
}
|
| 367 |
+
|
| 368 |
+
/* ============================================
|
| 369 |
+
EFFICIENT MOBILE ANIMATIONS
|
| 370 |
+
============================================ */
|
| 371 |
+
|
| 372 |
+
/* Simple fade for mobile (no transforms = cheaper) */
|
| 373 |
+
@keyframes fade-in {
|
| 374 |
+
from { opacity: 0; }
|
| 375 |
+
to { opacity: 1; }
|
| 376 |
+
}
|
| 377 |
+
|
| 378 |
+
@keyframes fade-out {
|
| 379 |
+
from { opacity: 1; }
|
| 380 |
+
to { opacity: 0; }
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
/* Slide animations using transform (GPU-accelerated) */
|
| 384 |
+
@keyframes slide-up {
|
| 385 |
+
from {
|
| 386 |
+
opacity: 0;
|
| 387 |
+
transform: translateY(10px);
|
| 388 |
+
}
|
| 389 |
+
to {
|
| 390 |
+
opacity: 1;
|
| 391 |
+
transform: translateY(0);
|
| 392 |
+
}
|
| 393 |
+
}
|
| 394 |
+
|
| 395 |
+
@keyframes slide-down {
|
| 396 |
+
from {
|
| 397 |
+
opacity: 0;
|
| 398 |
+
transform: translateY(-10px);
|
| 399 |
+
}
|
| 400 |
+
to {
|
| 401 |
+
opacity: 1;
|
| 402 |
+
transform: translateY(0);
|
| 403 |
+
}
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
/* Pulse for loading states */
|
| 407 |
+
@keyframes pulse-subtle {
|
| 408 |
+
0%, 100% { opacity: 1; }
|
| 409 |
+
50% { opacity: 0.6; }
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
.animate-pulse-subtle {
|
| 413 |
+
animation: pulse-subtle 2s ease-in-out infinite;
|
| 414 |
+
}
|
| 415 |
+
|
| 416 |
+
/* ============================================
|
| 417 |
+
SCROLLBAR STYLING
|
| 418 |
+
============================================ */
|
| 419 |
+
|
| 420 |
+
/* Custom scrollbar for webkit browsers */
|
| 421 |
+
::-webkit-scrollbar {
|
| 422 |
+
width: 8px;
|
| 423 |
+
height: 8px;
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
+
::-webkit-scrollbar-track {
|
| 427 |
+
background: rgba(15, 23, 42, 0.3);
|
| 428 |
+
border-radius: 4px;
|
| 429 |
+
}
|
| 430 |
+
|
| 431 |
+
::-webkit-scrollbar-thumb {
|
| 432 |
+
background: rgba(148, 163, 184, 0.3);
|
| 433 |
+
border-radius: 4px;
|
| 434 |
+
}
|
| 435 |
+
|
| 436 |
+
::-webkit-scrollbar-thumb:hover {
|
| 437 |
+
background: rgba(148, 163, 184, 0.5);
|
| 438 |
+
}
|
| 439 |
+
|
| 440 |
+
/* Firefox scrollbar */
|
| 441 |
+
* {
|
| 442 |
+
scrollbar-width: thin;
|
| 443 |
+
scrollbar-color: rgba(148, 163, 184, 0.3) rgba(15, 23, 42, 0.3);
|
| 444 |
+
}
|
| 445 |
+
|
| 446 |
+
/* figtree-regular - latin_latin-ext */
|
| 447 |
+
@font-face {
|
| 448 |
+
font-display: swap; /* Check https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display for other options. */
|
| 449 |
+
font-family: 'Figtree';
|
| 450 |
+
font-style: normal;
|
| 451 |
+
font-weight: 400;
|
| 452 |
+
src: url('/fonts/figtree-v9-latin_latin-ext-regular.woff2') format('woff2'), /* Chrome 36+, Opera 23+, Firefox 39+, Safari 12+, iOS 10+ */
|
| 453 |
+
url('/fonts/figtree-v9-latin_latin-ext-regular.ttf') format('truetype'); /* Chrome 4+, Firefox 3.5+, IE 9+, Safari 3.1+, iOS 4.2+, Android Browser 2.2+ */
|
| 454 |
+
}
|
| 455 |
+
/* figtree-italic - latin_latin-ext */
|
| 456 |
+
@font-face {
|
| 457 |
+
font-display: swap; /* Check https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display for other options. */
|
| 458 |
+
font-family: 'Figtree';
|
| 459 |
+
font-style: italic;
|
| 460 |
+
font-weight: 400;
|
| 461 |
+
src: url('/fonts/figtree-v9-latin_latin-ext-italic.woff2') format('woff2'), /* Chrome 36+, Opera 23+, Firefox 39+, Safari 12+, iOS 10+ */
|
| 462 |
+
url('/fonts/figtree-v9-latin_latin-ext-italic.ttf') format('truetype'); /* Chrome 4+, Firefox 3.5+, IE 9+, Safari 3.1+, iOS 4.2+, Android Browser 2.2+ */
|
| 463 |
+
}
|
| 464 |
+
/* figtree-700 - latin_latin-ext */
|
| 465 |
+
@font-face {
|
| 466 |
+
font-display: swap; /* Check https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display for other options. */
|
| 467 |
+
font-family: 'Figtree';
|
| 468 |
+
font-style: normal;
|
| 469 |
+
font-weight: 700;
|
| 470 |
+
src: url('/fonts/figtree-v9-latin_latin-ext-700.woff2') format('woff2'), /* Chrome 36+, Opera 23+, Firefox 39+, Safari 12+, iOS 10+ */
|
| 471 |
+
url('/fonts/figtree-v9-latin_latin-ext-700.ttf') format('truetype'); /* Chrome 4+, Firefox 3.5+, IE 9+, Safari 3.1+, iOS 4.2+, Android Browser 2.2+ */
|
| 472 |
+
}
|
| 473 |
+
/* figtree-700italic - latin_latin-ext */
|
| 474 |
+
@font-face {
|
| 475 |
+
font-display: swap; /* Check https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display for other options. */
|
| 476 |
+
font-family: 'Figtree';
|
| 477 |
+
font-style: italic;
|
| 478 |
+
font-weight: 700;
|
| 479 |
+
src: url('/fonts/figtree-v9-latin_latin-ext-700italic.woff2') format('woff2'), /* Chrome 36+, Opera 23+, Firefox 39+, Safari 12+, iOS 10+ */
|
| 480 |
+
url('/fonts/figtree-v9-latin_latin-ext-700italic.ttf') format('truetype'); /* Chrome 4+, Firefox 3.5+, IE 9+, Safari 3.1+, iOS 4.2+, Android Browser 2.2+ */
|
| 481 |
+
}
|
src/app.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// See https://svelte.dev/docs/kit/types#app.d.ts
|
| 2 |
+
// for information about these interfaces
|
| 3 |
+
declare global {
|
| 4 |
+
namespace App {
|
| 5 |
+
// interface Error {}
|
| 6 |
+
// interface Locals {}
|
| 7 |
+
// interface PageData {}
|
| 8 |
+
// interface PageState {}
|
| 9 |
+
// interface Platform {}
|
| 10 |
+
}
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
declare module 'shaka-player/dist/shaka-player.compiled.js' {
|
| 14 |
+
const shaka: {
|
| 15 |
+
Player: new (mediaElement: HTMLMediaElement) => {
|
| 16 |
+
load(uri: string): Promise<void>;
|
| 17 |
+
unload(): Promise<void>;
|
| 18 |
+
destroy(): Promise<void>;
|
| 19 |
+
getNetworkingEngine?: () => {
|
| 20 |
+
registerRequestFilter: (
|
| 21 |
+
callback: (type: unknown, request: { method: string; uris: string[] }) => void
|
| 22 |
+
) => void;
|
| 23 |
+
};
|
| 24 |
+
};
|
| 25 |
+
polyfill?: {
|
| 26 |
+
installAll?: () => void;
|
| 27 |
+
};
|
| 28 |
+
};
|
| 29 |
+
export default shaka;
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
export {};
|
src/app.html
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8" />
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
| 6 |
+
<link rel="icon" type="image/png" href="/icons/favicon-96x96.png" sizes="96x96" />
|
| 7 |
+
<link rel="icon" type="image/svg+xml" href="/icons/favicon.svg" />
|
| 8 |
+
<link rel="shortcut icon" href="/icons/favicon.ico" />
|
| 9 |
+
<link rel="apple-touch-icon" sizes="180x180" href="/icons/apple-touch-icon.png" />
|
| 10 |
+
<meta name="apple-mobile-web-app-title" content="BiniLossless" />
|
| 11 |
+
<link rel="manifest" href="/site.webmanifest" />
|
| 12 |
+
<script defer src="https://u.binimum.org/script.js" data-website-id="a722aa59-e529-475b-b21d-0835ff659a93"></script>
|
| 13 |
+
%sveltekit.head%
|
| 14 |
+
</head>
|
| 15 |
+
<body data-sveltekit-preload-data="hover">
|
| 16 |
+
<div style="display: contents">%sveltekit.body%</div>
|
| 17 |
+
</body>
|
| 18 |
+
</html>
|
src/lib/api.ts
ADDED
|
@@ -0,0 +1,2568 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
import { deriveTrackQuality } from '$lib/utils/audioQuality';
|
| 5 |
+
import { parseTidalUrl, type TidalUrlParseResult } from '$lib/utils/urlParser';
|
| 6 |
+
import { formatArtistsForMetadata } from '$lib/utils';
|
| 7 |
+
import type {
|
| 8 |
+
Track,
|
| 9 |
+
Artist,
|
| 10 |
+
Album,
|
| 11 |
+
Playlist,
|
| 12 |
+
SearchResponse,
|
| 13 |
+
AudioQuality,
|
| 14 |
+
StreamData,
|
| 15 |
+
CoverImage,
|
| 16 |
+
Lyrics,
|
| 17 |
+
TrackInfo,
|
| 18 |
+
TrackLookup,
|
| 19 |
+
ArtistDetails,
|
| 20 |
+
TrackRecommendationsResponse
|
| 21 |
+
} from './types';
|
| 22 |
+
|
| 23 |
+
const API_BASE = API_CONFIG.baseUrl;
|
| 24 |
+
const RATE_LIMIT_ERROR_MESSAGE = 'Too Many Requests. Please wait a moment and try again.';
|
| 25 |
+
export const DASH_MANIFEST_UNAVAILABLE_CODE = 'DASH_MANIFEST_UNAVAILABLE';
|
| 26 |
+
|
| 27 |
+
type CodedError = Error & { code?: string };
|
| 28 |
+
|
| 29 |
+
export type TrackDownloadProgress =
|
| 30 |
+
| { stage: 'downloading'; receivedBytes: number; totalBytes?: number }
|
| 31 |
+
| { stage: 'embedding'; progress: number };
|
| 32 |
+
|
| 33 |
+
export type DashManifestResult =
|
| 34 |
+
| {
|
| 35 |
+
kind: 'dash';
|
| 36 |
+
manifest: string;
|
| 37 |
+
contentType: string | null;
|
| 38 |
+
}
|
| 39 |
+
| {
|
| 40 |
+
kind: 'flac';
|
| 41 |
+
manifestText: string;
|
| 42 |
+
urls: string[];
|
| 43 |
+
contentType: string | null;
|
| 44 |
+
};
|
| 45 |
+
|
| 46 |
+
export interface DashManifestWithMetadata {
|
| 47 |
+
result: DashManifestResult;
|
| 48 |
+
trackInfo: {
|
| 49 |
+
sampleRate: number | null;
|
| 50 |
+
bitDepth: number | null;
|
| 51 |
+
replayGain: number | null;
|
| 52 |
+
};
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
export interface DownloadTrackOptions {
|
| 56 |
+
signal?: AbortSignal;
|
| 57 |
+
onProgress?: (progress: TrackDownloadProgress) => void;
|
| 58 |
+
onFfmpegCountdown?: (options: { totalBytes?: number; autoTriggered: boolean }) => void;
|
| 59 |
+
onFfmpegStart?: () => void;
|
| 60 |
+
onFfmpegProgress?: (progress: number) => void;
|
| 61 |
+
onFfmpegComplete?: () => void;
|
| 62 |
+
onFfmpegError?: (error: unknown) => void;
|
| 63 |
+
ffmpegAutoTriggered?: boolean;
|
| 64 |
+
convertAacToMp3?: boolean;
|
| 65 |
+
downloadCoverSeperately?: boolean;
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
class LosslessAPI {
|
| 69 |
+
public baseUrl: string;
|
| 70 |
+
private metadataQueue: Promise<void> = Promise.resolve();
|
| 71 |
+
|
| 72 |
+
constructor(baseUrl: string = API_BASE) {
|
| 73 |
+
this.baseUrl = baseUrl;
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
private resolveRegionalBase(region: RegionOption = 'auto'): string {
|
| 77 |
+
try {
|
| 78 |
+
const target = selectApiTargetForRegion(region);
|
| 79 |
+
if (target?.baseUrl) {
|
| 80 |
+
return target.baseUrl;
|
| 81 |
+
}
|
| 82 |
+
} catch (error) {
|
| 83 |
+
console.warn('Falling back to default API base URL for region selection', { region, error });
|
| 84 |
+
}
|
| 85 |
+
return this.baseUrl;
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
private buildRegionalUrl(path: string, region: RegionOption = 'auto'): string {
|
| 89 |
+
const base = this.resolveRegionalBase(region).replace(/\/+$/, '');
|
| 90 |
+
const normalizedPath = path.startsWith('/') ? path : `/${path}`;
|
| 91 |
+
return `${base}${normalizedPath}`;
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
private normalizeSearchResponse<T>(
|
| 95 |
+
data: unknown,
|
| 96 |
+
key: 'tracks' | 'albums' | 'artists' | 'playlists'
|
| 97 |
+
): SearchResponse<T> {
|
| 98 |
+
const section = this.findSearchSection<T>(data, key, new Set());
|
| 99 |
+
return this.buildSearchResponse<T>(section);
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
private buildSearchResponse<T>(
|
| 103 |
+
section: Partial<SearchResponse<T>> | undefined
|
| 104 |
+
): SearchResponse<T> {
|
| 105 |
+
const items = section?.items;
|
| 106 |
+
const list = Array.isArray(items) ? (items as T[]) : [];
|
| 107 |
+
const limit = typeof section?.limit === 'number' ? section.limit : list.length;
|
| 108 |
+
const offset = typeof section?.offset === 'number' ? section.offset : 0;
|
| 109 |
+
const total =
|
| 110 |
+
typeof section?.totalNumberOfItems === 'number' ? section.totalNumberOfItems : list.length;
|
| 111 |
+
|
| 112 |
+
return {
|
| 113 |
+
items: list,
|
| 114 |
+
limit,
|
| 115 |
+
offset,
|
| 116 |
+
totalNumberOfItems: total
|
| 117 |
+
};
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
private findSearchSection<T>(
|
| 121 |
+
source: unknown,
|
| 122 |
+
key: 'tracks' | 'albums' | 'artists' | 'playlists',
|
| 123 |
+
visited: Set<object>
|
| 124 |
+
): Partial<SearchResponse<T>> | undefined {
|
| 125 |
+
if (!source) {
|
| 126 |
+
return undefined;
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
if (Array.isArray(source)) {
|
| 130 |
+
for (const entry of source) {
|
| 131 |
+
const found = this.findSearchSection<T>(entry, key, visited);
|
| 132 |
+
if (found) {
|
| 133 |
+
return found;
|
| 134 |
+
}
|
| 135 |
+
}
|
| 136 |
+
return undefined;
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
if (typeof source !== 'object') {
|
| 140 |
+
return undefined;
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
const objectRef = source as Record<string, unknown>;
|
| 144 |
+
if (visited.has(objectRef)) {
|
| 145 |
+
return undefined;
|
| 146 |
+
}
|
| 147 |
+
visited.add(objectRef);
|
| 148 |
+
|
| 149 |
+
if (!Array.isArray(source) && 'items' in objectRef && Array.isArray(objectRef.items)) {
|
| 150 |
+
return objectRef as Partial<SearchResponse<T>>;
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
if (key in objectRef) {
|
| 154 |
+
const nested = objectRef[key];
|
| 155 |
+
const fromKey = this.findSearchSection<T>(nested, key, visited);
|
| 156 |
+
if (fromKey) {
|
| 157 |
+
return fromKey;
|
| 158 |
+
}
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
for (const value of Object.values(objectRef)) {
|
| 162 |
+
const found = this.findSearchSection<T>(value, key, visited);
|
| 163 |
+
if (found) {
|
| 164 |
+
return found;
|
| 165 |
+
}
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
return undefined;
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
private prepareTrack(track: Track): Track {
|
| 172 |
+
let normalized = track;
|
| 173 |
+
if (!track.artist && Array.isArray(track.artists) && track.artists.length > 0) {
|
| 174 |
+
normalized = { ...track, artist: track.artists[0]! };
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
const derivedQuality = deriveTrackQuality(normalized);
|
| 178 |
+
if (derivedQuality && normalized.audioQuality !== derivedQuality) {
|
| 179 |
+
normalized = { ...normalized, audioQuality: derivedQuality };
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
return normalized;
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
private prepareAlbum(album: Album): Album {
|
| 186 |
+
if (!album.artist && Array.isArray(album.artists) && album.artists.length > 0) {
|
| 187 |
+
return { ...album, artist: album.artists[0]! };
|
| 188 |
+
}
|
| 189 |
+
return album;
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
private prepareArtist(artist: Artist): Artist {
|
| 193 |
+
if (!artist.type && Array.isArray(artist.artistTypes) && artist.artistTypes.length > 0) {
|
| 194 |
+
return { ...artist, type: artist.artistTypes[0]! } as Artist;
|
| 195 |
+
}
|
| 196 |
+
return artist;
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
private ensureNotRateLimited(response: Response): void {
|
| 200 |
+
if (response.status === 429) {
|
| 201 |
+
throw new Error(RATE_LIMIT_ERROR_MESSAGE);
|
| 202 |
+
}
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
private async delay(ms: number): Promise<void> {
|
| 206 |
+
await new Promise((resolve) => setTimeout(resolve, ms));
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
private parseTrackLookup(data: unknown): TrackLookup {
|
| 210 |
+
const entries = Array.isArray(data) ? data : [data];
|
| 211 |
+
let track: Track | undefined;
|
| 212 |
+
let info: TrackInfo | undefined;
|
| 213 |
+
let originalTrackUrl: string | undefined;
|
| 214 |
+
|
| 215 |
+
for (const entry of entries) {
|
| 216 |
+
if (!entry || typeof entry !== 'object') continue;
|
| 217 |
+
if (!track && 'album' in entry && 'artist' in entry && 'duration' in entry) {
|
| 218 |
+
track = entry as Track;
|
| 219 |
+
continue;
|
| 220 |
+
}
|
| 221 |
+
if (!info && 'manifest' in entry) {
|
| 222 |
+
info = entry as TrackInfo;
|
| 223 |
+
continue;
|
| 224 |
+
}
|
| 225 |
+
if (!originalTrackUrl && 'OriginalTrackUrl' in entry) {
|
| 226 |
+
const candidate = (entry as { OriginalTrackUrl?: unknown }).OriginalTrackUrl;
|
| 227 |
+
if (typeof candidate === 'string') {
|
| 228 |
+
originalTrackUrl = candidate;
|
| 229 |
+
}
|
| 230 |
+
}
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
if (!track || !info) {
|
| 234 |
+
throw new Error('Malformed track response');
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
return { track, info, originalTrackUrl };
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
private extractStreamUrlFromManifest(manifest: string): string | null {
|
| 241 |
+
try {
|
| 242 |
+
const decoded = this.decodeBase64Manifest(manifest);
|
| 243 |
+
try {
|
| 244 |
+
const parsed = JSON.parse(decoded) as { urls?: string[] };
|
| 245 |
+
if (parsed && Array.isArray(parsed.urls) && parsed.urls.length > 0) {
|
| 246 |
+
return parsed.urls[0] ?? null;
|
| 247 |
+
}
|
| 248 |
+
} catch (jsonError) {
|
| 249 |
+
// Ignore JSON parse failure and fall back to regex/XML search
|
| 250 |
+
console.debug('Manifest JSON parse failed, falling back to pattern match', jsonError);
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
// If this is a segmented DASH manifest, don't extract a URL - let it fall through to segment download
|
| 254 |
+
if (this.isSegmentedDashManifest(decoded)) {
|
| 255 |
+
return null;
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
const mpdUrl = this.parseFlacUrlFromMpd(decoded);
|
| 259 |
+
if (mpdUrl) {
|
| 260 |
+
return mpdUrl;
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
// Match all URLs and filter out schema/namespace URLs and segment URLs
|
| 264 |
+
const urlRegex = /https?:\/\/[\w\-.~:?#[\]@!$&'()*+,;=%/]+/g;
|
| 265 |
+
let match: RegExpExecArray | null;
|
| 266 |
+
while ((match = urlRegex.exec(decoded)) !== null) {
|
| 267 |
+
const url = match[0];
|
| 268 |
+
// Skip segment template URLs and initialization segments
|
| 269 |
+
if (url.includes('$Number$')) continue;
|
| 270 |
+
if (/\/\d+\.mp4/.test(url)) continue; // Skip segment files like /0.mp4, /1.mp4, etc.
|
| 271 |
+
if (this.isValidMediaUrl(url)) {
|
| 272 |
+
return url;
|
| 273 |
+
}
|
| 274 |
+
}
|
| 275 |
+
return null;
|
| 276 |
+
} catch (error) {
|
| 277 |
+
console.error('Failed to decode manifest:', error);
|
| 278 |
+
return null;
|
| 279 |
+
}
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
private isSegmentedDashManifest(decoded: string): boolean {
|
| 283 |
+
// Check if manifest contains SegmentTemplate which indicates segmented content
|
| 284 |
+
return /<SegmentTemplate/i.test(decoded);
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
private isDashManifestPayload(payload: string, contentType: string | null): boolean {
|
| 288 |
+
const trimmed = payload.trim();
|
| 289 |
+
if (!trimmed) {
|
| 290 |
+
return false;
|
| 291 |
+
}
|
| 292 |
+
if (contentType && contentType.toLowerCase().includes('xml')) {
|
| 293 |
+
return trimmed.startsWith('<');
|
| 294 |
+
}
|
| 295 |
+
return /^<\?xml/i.test(trimmed) || /^<MPD[\s>]/i.test(trimmed) || /^<\w+/i.test(trimmed);
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
private parseJsonSafely<T>(payload: string): T | null {
|
| 299 |
+
try {
|
| 300 |
+
return JSON.parse(payload) as T;
|
| 301 |
+
} catch (error) {
|
| 302 |
+
console.debug('Failed to parse JSON payload from DASH response', error);
|
| 303 |
+
return null;
|
| 304 |
+
}
|
| 305 |
+
}
|
| 306 |
+
|
| 307 |
+
private createDashUnavailableError(message: string): CodedError {
|
| 308 |
+
const error = new Error(message) as CodedError;
|
| 309 |
+
error.code = DASH_MANIFEST_UNAVAILABLE_CODE;
|
| 310 |
+
return error;
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
private isXmlContentType(contentType: string | null): boolean {
|
| 314 |
+
if (!contentType) return false;
|
| 315 |
+
return (
|
| 316 |
+
/(application|text)\/(?:.+\+)?xml/i.test(contentType) || /dash\+xml|mpd/i.test(contentType)
|
| 317 |
+
);
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
private isJsonContentType(contentType: string | null): boolean {
|
| 321 |
+
if (!contentType) return false;
|
| 322 |
+
return /json/i.test(contentType) || /application\/vnd\.tidal\.bts/i.test(contentType);
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
+
private extractUrlsFromDashJsonPayload(payload: unknown): string[] {
|
| 326 |
+
if (!payload || typeof payload !== 'object') {
|
| 327 |
+
return [];
|
| 328 |
+
}
|
| 329 |
+
|
| 330 |
+
const candidate = (payload as { urls?: unknown }).urls;
|
| 331 |
+
if (!Array.isArray(candidate)) {
|
| 332 |
+
return [];
|
| 333 |
+
}
|
| 334 |
+
|
| 335 |
+
return candidate
|
| 336 |
+
.map((entry) => (typeof entry === 'string' ? entry.trim() : ''))
|
| 337 |
+
.filter((entry) => entry.length > 0);
|
| 338 |
+
}
|
| 339 |
+
|
| 340 |
+
private isHiResQuality(quality: AudioQuality | string): boolean {
|
| 341 |
+
return String(quality).toUpperCase() === 'HI_RES_LOSSLESS';
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
private isV2ApiContainer(payload: unknown): payload is { version?: unknown; data?: unknown } {
|
| 345 |
+
return Boolean(
|
| 346 |
+
payload &&
|
| 347 |
+
typeof payload === 'object' &&
|
| 348 |
+
'version' in (payload as Record<string, unknown>) &&
|
| 349 |
+
String((payload as { version?: unknown }).version).startsWith('2.')
|
| 350 |
+
);
|
| 351 |
+
}
|
| 352 |
+
|
| 353 |
+
private decodeBase64Manifest(manifest: string): string {
|
| 354 |
+
if (typeof manifest !== 'string') return '';
|
| 355 |
+
const trimmed = manifest.trim();
|
| 356 |
+
if (!trimmed) return '';
|
| 357 |
+
try {
|
| 358 |
+
// Support URL-safe base64 and missing padding
|
| 359 |
+
const normalized = (() => {
|
| 360 |
+
let value = trimmed.replace(/-/g, '+').replace(/_/g, '/');
|
| 361 |
+
const pad = value.length % 4;
|
| 362 |
+
if (pad === 2) value += '==';
|
| 363 |
+
if (pad === 3) value += '=';
|
| 364 |
+
return value;
|
| 365 |
+
})();
|
| 366 |
+
const decoded = atob(normalized);
|
| 367 |
+
return decoded || trimmed;
|
| 368 |
+
} catch {
|
| 369 |
+
return trimmed;
|
| 370 |
+
}
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
private extractTrackFromPayload(payload: unknown): Track | undefined {
|
| 374 |
+
const candidates: unknown[] = [];
|
| 375 |
+
if (!payload) return undefined;
|
| 376 |
+
if (Array.isArray(payload)) {
|
| 377 |
+
candidates.push(...payload);
|
| 378 |
+
} else if (typeof payload === 'object') {
|
| 379 |
+
candidates.push(payload);
|
| 380 |
+
for (const value of Object.values(payload as Record<string, unknown>)) {
|
| 381 |
+
if (value && (typeof value === 'object' || Array.isArray(value))) {
|
| 382 |
+
candidates.push(value);
|
| 383 |
+
}
|
| 384 |
+
}
|
| 385 |
+
}
|
| 386 |
+
|
| 387 |
+
const isTrackLike = (entry: unknown): entry is Track => {
|
| 388 |
+
if (!entry || typeof entry !== 'object') return false;
|
| 389 |
+
const record = entry as Record<string, unknown>;
|
| 390 |
+
return (
|
| 391 |
+
typeof record.id === 'number' &&
|
| 392 |
+
typeof record.title === 'string' &&
|
| 393 |
+
typeof record.duration === 'number'
|
| 394 |
+
);
|
| 395 |
+
};
|
| 396 |
+
|
| 397 |
+
for (const candidate of candidates) {
|
| 398 |
+
if (isTrackLike(candidate)) {
|
| 399 |
+
return candidate as Track;
|
| 400 |
+
}
|
| 401 |
+
}
|
| 402 |
+
return undefined;
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
private async fetchTrackMetadata(
|
| 406 |
+
trackId: number,
|
| 407 |
+
apiVersion: 'v1' | 'v2' = 'v2'
|
| 408 |
+
): Promise<Track> {
|
| 409 |
+
const response = await this.fetch(`${this.baseUrl}/info/?id=${trackId}`, { apiVersion });
|
| 410 |
+
this.ensureNotRateLimited(response);
|
| 411 |
+
if (!response.ok) {
|
| 412 |
+
throw new Error('Failed to fetch track metadata');
|
| 413 |
+
}
|
| 414 |
+
const payload = await response.json();
|
| 415 |
+
const data = this.isV2ApiContainer(payload) ? payload.data : payload;
|
| 416 |
+
const track = this.extractTrackFromPayload(data);
|
| 417 |
+
if (!track) {
|
| 418 |
+
throw new Error('Track metadata not found');
|
| 419 |
+
}
|
| 420 |
+
return this.prepareTrack(track);
|
| 421 |
+
}
|
| 422 |
+
|
| 423 |
+
private buildTrackInfoFromV2(data: Record<string, unknown>, fallbackTrackId: number): TrackInfo {
|
| 424 |
+
const manifestMimeType =
|
| 425 |
+
typeof data.manifestMimeType === 'string' && data.manifestMimeType.trim().length > 0
|
| 426 |
+
? data.manifestMimeType
|
| 427 |
+
: 'application/dash+xml';
|
| 428 |
+
|
| 429 |
+
return {
|
| 430 |
+
trackId: typeof data.trackId === 'number' ? data.trackId : fallbackTrackId,
|
| 431 |
+
audioMode: typeof data.audioMode === 'string' ? data.audioMode : 'STEREO',
|
| 432 |
+
audioQuality: typeof data.audioQuality === 'string' ? data.audioQuality : 'LOSSLESS',
|
| 433 |
+
manifest: typeof data.manifest === 'string' ? data.manifest : '',
|
| 434 |
+
manifestMimeType,
|
| 435 |
+
manifestHash: typeof data.manifestHash === 'string' ? data.manifestHash : undefined,
|
| 436 |
+
assetPresentation:
|
| 437 |
+
typeof data.assetPresentation === 'string' ? data.assetPresentation : 'FULL',
|
| 438 |
+
albumReplayGain: typeof data.albumReplayGain === 'number' ? data.albumReplayGain : undefined,
|
| 439 |
+
albumPeakAmplitude:
|
| 440 |
+
typeof data.albumPeakAmplitude === 'number' ? data.albumPeakAmplitude : undefined,
|
| 441 |
+
trackReplayGain: typeof data.trackReplayGain === 'number' ? data.trackReplayGain : undefined,
|
| 442 |
+
trackPeakAmplitude:
|
| 443 |
+
typeof data.trackPeakAmplitude === 'number' ? data.trackPeakAmplitude : undefined,
|
| 444 |
+
bitDepth: typeof data.bitDepth === 'number' ? data.bitDepth : undefined,
|
| 445 |
+
sampleRate: typeof data.sampleRate === 'number' ? data.sampleRate : undefined
|
| 446 |
+
};
|
| 447 |
+
}
|
| 448 |
+
|
| 449 |
+
private extractOriginalTrackUrl(payload: Record<string, unknown>): string | undefined {
|
| 450 |
+
const originalUrl =
|
| 451 |
+
typeof payload.OriginalTrackUrl === 'string'
|
| 452 |
+
? payload.OriginalTrackUrl
|
| 453 |
+
: typeof payload.originalTrackUrl === 'string'
|
| 454 |
+
? payload.originalTrackUrl
|
| 455 |
+
: undefined;
|
| 456 |
+
return originalUrl;
|
| 457 |
+
}
|
| 458 |
+
|
| 459 |
+
private async parseTrackLookupV2(
|
| 460 |
+
trackId: number,
|
| 461 |
+
payload: { data?: unknown },
|
| 462 |
+
apiVersion: 'v1' | 'v2' = 'v2'
|
| 463 |
+
): Promise<TrackLookup> {
|
| 464 |
+
const container = (payload?.data ?? payload) as Record<string, unknown>;
|
| 465 |
+
const trackInfo = this.buildTrackInfoFromV2(container, trackId);
|
| 466 |
+
let track = this.extractTrackFromPayload(container) ?? null;
|
| 467 |
+
if (!track) {
|
| 468 |
+
track = await this.fetchTrackMetadata(trackId, apiVersion);
|
| 469 |
+
}
|
| 470 |
+
|
| 471 |
+
return {
|
| 472 |
+
track: this.prepareTrack(track),
|
| 473 |
+
info: trackInfo,
|
| 474 |
+
originalTrackUrl: this.extractOriginalTrackUrl(container)
|
| 475 |
+
};
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
private buildDashManifestResult(payload: string, contentType: string | null): DashManifestResult {
|
| 479 |
+
const manifestText = this.decodeBase64Manifest(payload);
|
| 480 |
+
|
| 481 |
+
if (
|
| 482 |
+
this.isXmlContentType(contentType) ||
|
| 483 |
+
this.isDashManifestPayload(manifestText, contentType)
|
| 484 |
+
) {
|
| 485 |
+
return { kind: 'dash', manifest: manifestText, contentType };
|
| 486 |
+
}
|
| 487 |
+
|
| 488 |
+
const trimmed = manifestText.trim();
|
| 489 |
+
if (this.isJsonContentType(contentType) || trimmed.startsWith('{') || trimmed.startsWith('[')) {
|
| 490 |
+
const parsed = this.parseJsonSafely<{ detail?: unknown; urls?: unknown }>(manifestText);
|
| 491 |
+
if (
|
| 492 |
+
parsed &&
|
| 493 |
+
typeof parsed === 'object' &&
|
| 494 |
+
parsed.detail &&
|
| 495 |
+
typeof parsed.detail === 'string' &&
|
| 496 |
+
parsed.detail.toLowerCase() === 'not found'
|
| 497 |
+
) {
|
| 498 |
+
throw this.createDashUnavailableError('Dash manifest not found for track');
|
| 499 |
+
}
|
| 500 |
+
const urls = this.extractUrlsFromDashJsonPayload(parsed);
|
| 501 |
+
if (urls.length > 0) {
|
| 502 |
+
return { kind: 'flac', manifestText, urls, contentType };
|
| 503 |
+
}
|
| 504 |
+
}
|
| 505 |
+
|
| 506 |
+
if (this.isDashManifestPayload(manifestText, contentType)) {
|
| 507 |
+
return { kind: 'dash', manifest: manifestText, contentType };
|
| 508 |
+
}
|
| 509 |
+
|
| 510 |
+
const parsed = this.parseJsonSafely(manifestText);
|
| 511 |
+
const urls = this.extractUrlsFromDashJsonPayload(parsed);
|
| 512 |
+
if (urls.length > 0) {
|
| 513 |
+
return { kind: 'flac', manifestText, urls, contentType };
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
throw this.createDashUnavailableError('Received unexpected payload from dash endpoint.');
|
| 517 |
+
}
|
| 518 |
+
|
| 519 |
+
private isValidMediaUrl(url: string): boolean {
|
| 520 |
+
if (!url) return false;
|
| 521 |
+
const normalized = url.toLowerCase();
|
| 522 |
+
// Filter out XML schema/namespace URLs
|
| 523 |
+
if (normalized.includes('w3.org')) return false;
|
| 524 |
+
if (normalized.includes('xmlschema')) return false;
|
| 525 |
+
if (normalized.includes('xmlns')) return false;
|
| 526 |
+
// Must look like a media URL (has extension or query params suggesting media)
|
| 527 |
+
if (
|
| 528 |
+
normalized.includes('.flac') ||
|
| 529 |
+
normalized.includes('.mp4') ||
|
| 530 |
+
normalized.includes('.m4a') ||
|
| 531 |
+
normalized.includes('.aac') ||
|
| 532 |
+
normalized.includes('token=') ||
|
| 533 |
+
normalized.includes('/audio/')
|
| 534 |
+
) {
|
| 535 |
+
return true;
|
| 536 |
+
}
|
| 537 |
+
// If it has a file-like path segment, it's likely valid
|
| 538 |
+
if (/\/[^/]+\.[a-z0-9]{2,5}(\?|$)/i.test(url)) return true;
|
| 539 |
+
// If it's a relative path starting with a segment name, likely valid
|
| 540 |
+
if (/^[a-z0-9_-]+\//i.test(url)) return true;
|
| 541 |
+
// If it ends with a path segment that could be a file
|
| 542 |
+
if (/\/[a-z0-9_-]+$/i.test(url)) return true;
|
| 543 |
+
return false;
|
| 544 |
+
}
|
| 545 |
+
|
| 546 |
+
private parseFlacUrlFromMpd(manifestText: string): string | null {
|
| 547 |
+
const trimmed = manifestText.trim();
|
| 548 |
+
if (!trimmed) return null;
|
| 549 |
+
|
| 550 |
+
const isValidMediaUrl = this.isValidMediaUrl.bind(this);
|
| 551 |
+
|
| 552 |
+
const scoreUrl = (url: string | undefined | null): number => {
|
| 553 |
+
if (!url) return -1;
|
| 554 |
+
const normalized = url.toLowerCase();
|
| 555 |
+
let score = 0;
|
| 556 |
+
if (normalized.includes('flac')) score += 3;
|
| 557 |
+
if (normalized.includes('hires')) score += 1;
|
| 558 |
+
if (normalized.endsWith('.flac')) score += 4;
|
| 559 |
+
if (normalized.includes('token=')) score += 1;
|
| 560 |
+
return score;
|
| 561 |
+
};
|
| 562 |
+
|
| 563 |
+
const pickBest = (urls: Array<string | undefined | null>): string | null => {
|
| 564 |
+
const candidates = urls
|
| 565 |
+
.map((u) => (typeof u === 'string' ? u.trim() : ''))
|
| 566 |
+
.filter((u) => u.length > 0 && isValidMediaUrl(u));
|
| 567 |
+
if (candidates.length === 0) return null;
|
| 568 |
+
return candidates.sort((a, b) => scoreUrl(b) - scoreUrl(a))[0] ?? null;
|
| 569 |
+
};
|
| 570 |
+
|
| 571 |
+
// Prefer DOMParser when available (browser side)
|
| 572 |
+
if (typeof DOMParser !== 'undefined') {
|
| 573 |
+
try {
|
| 574 |
+
const doc = new DOMParser().parseFromString(trimmed, 'application/xml');
|
| 575 |
+
const baseUrls = Array.from(doc.getElementsByTagName('BaseURL')).map(
|
| 576 |
+
(n) => n.textContent?.trim() ?? ''
|
| 577 |
+
);
|
| 578 |
+
if (baseUrls.length > 0) {
|
| 579 |
+
const best = pickBest(baseUrls);
|
| 580 |
+
if (best) return best;
|
| 581 |
+
}
|
| 582 |
+
|
| 583 |
+
const reps = Array.from(doc.getElementsByTagName('Representation'));
|
| 584 |
+
for (const rep of reps) {
|
| 585 |
+
const codecs = rep.getAttribute('codecs')?.toLowerCase() ?? '';
|
| 586 |
+
const base = Array.from(rep.getElementsByTagName('BaseURL')).map(
|
| 587 |
+
(n) => n.textContent?.trim() ?? ''
|
| 588 |
+
);
|
| 589 |
+
if (base.length > 0 && codecs.includes('flac')) {
|
| 590 |
+
const best = pickBest(base);
|
| 591 |
+
if (best) return best;
|
| 592 |
+
}
|
| 593 |
+
}
|
| 594 |
+
} catch (error) {
|
| 595 |
+
console.debug('Failed to parse MPD manifest via DOMParser', error);
|
| 596 |
+
}
|
| 597 |
+
}
|
| 598 |
+
|
| 599 |
+
// Regex fallback for SSR / non-browser
|
| 600 |
+
const baseUrlMatch = trimmed.match(/<BaseURL[^>]*>([^<]+)<\/BaseURL>/i);
|
| 601 |
+
if (baseUrlMatch?.[1]) {
|
| 602 |
+
const candidate = baseUrlMatch[1].trim();
|
| 603 |
+
if (isValidMediaUrl(candidate)) {
|
| 604 |
+
return candidate;
|
| 605 |
+
}
|
| 606 |
+
}
|
| 607 |
+
|
| 608 |
+
return null;
|
| 609 |
+
}
|
| 610 |
+
|
| 611 |
+
private parseMpdSegmentTemplate(manifestText: string): {
|
| 612 |
+
initializationUrl: string;
|
| 613 |
+
mediaUrlTemplate: string;
|
| 614 |
+
startNumber: number;
|
| 615 |
+
segmentTimeline: Array<{ duration: number; repeat: number }>;
|
| 616 |
+
baseUrl?: string;
|
| 617 |
+
codec?: string;
|
| 618 |
+
} | null {
|
| 619 |
+
const trimmed = manifestText.trim();
|
| 620 |
+
if (!trimmed) return null;
|
| 621 |
+
|
| 622 |
+
const parseWithDom = () => {
|
| 623 |
+
if (typeof DOMParser === 'undefined') return null;
|
| 624 |
+
try {
|
| 625 |
+
const doc = new DOMParser().parseFromString(trimmed, 'application/xml');
|
| 626 |
+
const rawBaseUrl = doc.getElementsByTagName('BaseURL')[0]?.textContent?.trim();
|
| 627 |
+
// Filter out schema/namespace URLs
|
| 628 |
+
const baseUrl = rawBaseUrl && this.isValidMediaUrl(rawBaseUrl) ? rawBaseUrl : undefined;
|
| 629 |
+
|
| 630 |
+
let template: Element | null = null;
|
| 631 |
+
let codec: string | undefined;
|
| 632 |
+
|
| 633 |
+
const representations = Array.from(doc.getElementsByTagName('Representation'));
|
| 634 |
+
for (const rep of representations) {
|
| 635 |
+
const candidateTemplate = rep.getElementsByTagName('SegmentTemplate')[0];
|
| 636 |
+
if (!candidateTemplate) continue;
|
| 637 |
+
const codecsAttr = rep.getAttribute('codecs')?.toLowerCase() ?? '';
|
| 638 |
+
if (!template || codecsAttr.includes('flac')) {
|
| 639 |
+
template = candidateTemplate;
|
| 640 |
+
codec = codecsAttr || undefined;
|
| 641 |
+
if (codecsAttr.includes('flac')) break;
|
| 642 |
+
}
|
| 643 |
+
}
|
| 644 |
+
|
| 645 |
+
if (!template) {
|
| 646 |
+
template = doc.getElementsByTagName('SegmentTemplate')[0] ?? null;
|
| 647 |
+
}
|
| 648 |
+
|
| 649 |
+
if (!template) return null;
|
| 650 |
+
|
| 651 |
+
const initializationUrl = template.getAttribute('initialization')?.trim();
|
| 652 |
+
const mediaUrlTemplate = template.getAttribute('media')?.trim();
|
| 653 |
+
if (!initializationUrl || !mediaUrlTemplate) return null;
|
| 654 |
+
|
| 655 |
+
const startNumber = Number.parseInt(template.getAttribute('startNumber') ?? '1', 10);
|
| 656 |
+
const timelineParent = template.getElementsByTagName('SegmentTimeline')[0];
|
| 657 |
+
const segmentTimeline: Array<{ duration: number; repeat: number }> = [];
|
| 658 |
+
if (timelineParent) {
|
| 659 |
+
const segments = timelineParent.getElementsByTagName('S');
|
| 660 |
+
for (const seg of Array.from(segments)) {
|
| 661 |
+
const duration = Number.parseInt(seg.getAttribute('d') ?? '0', 10);
|
| 662 |
+
if (!Number.isFinite(duration) || duration <= 0) continue;
|
| 663 |
+
const repeat = Number.parseInt(seg.getAttribute('r') ?? '0', 10);
|
| 664 |
+
segmentTimeline.push({ duration, repeat: Number.isFinite(repeat) ? repeat : 0 });
|
| 665 |
+
}
|
| 666 |
+
}
|
| 667 |
+
|
| 668 |
+
return {
|
| 669 |
+
initializationUrl,
|
| 670 |
+
mediaUrlTemplate,
|
| 671 |
+
startNumber: Number.isFinite(startNumber) && startNumber > 0 ? startNumber : 1,
|
| 672 |
+
segmentTimeline,
|
| 673 |
+
baseUrl,
|
| 674 |
+
codec
|
| 675 |
+
};
|
| 676 |
+
} catch (error) {
|
| 677 |
+
console.debug('Failed to parse MPD manifest with DOMParser', error);
|
| 678 |
+
return null;
|
| 679 |
+
}
|
| 680 |
+
};
|
| 681 |
+
|
| 682 |
+
const parseWithRegex = () => {
|
| 683 |
+
const initializationUrl = /initialization="([^"]+)"/i.exec(trimmed)?.[1]?.trim();
|
| 684 |
+
const mediaUrlTemplate = /media="([^"]+)"/i.exec(trimmed)?.[1]?.trim();
|
| 685 |
+
if (!initializationUrl || !mediaUrlTemplate) return null;
|
| 686 |
+
const startNumberMatch = /startNumber="(\d+)"/i.exec(trimmed);
|
| 687 |
+
const startNumber = startNumberMatch ? Number.parseInt(startNumberMatch[1]!, 10) : 1;
|
| 688 |
+
const segmentTimeline: Array<{ duration: number; repeat: number }> = [];
|
| 689 |
+
// Match <S> elements with d attribute, r attribute is optional
|
| 690 |
+
const timelineRegex = /<S[^>]*\sd="(\d+)"(?:[^>]*\sr="(-?\d+)")?[^>]*\/?>/gi;
|
| 691 |
+
let match: RegExpExecArray | null;
|
| 692 |
+
while ((match = timelineRegex.exec(trimmed)) !== null) {
|
| 693 |
+
const duration = Number.parseInt(match[1]!, 10);
|
| 694 |
+
const repeat = match[2] ? Number.parseInt(match[2], 10) : 0;
|
| 695 |
+
if (Number.isFinite(duration) && duration > 0) {
|
| 696 |
+
segmentTimeline.push({ duration, repeat: Number.isFinite(repeat) ? repeat : 0 });
|
| 697 |
+
}
|
| 698 |
+
}
|
| 699 |
+
|
| 700 |
+
return {
|
| 701 |
+
initializationUrl,
|
| 702 |
+
mediaUrlTemplate,
|
| 703 |
+
startNumber: Number.isFinite(startNumber) && startNumber > 0 ? startNumber : 1,
|
| 704 |
+
segmentTimeline
|
| 705 |
+
};
|
| 706 |
+
};
|
| 707 |
+
|
| 708 |
+
return parseWithDom() ?? parseWithRegex();
|
| 709 |
+
}
|
| 710 |
+
|
| 711 |
+
private buildMpdSegmentUrls(
|
| 712 |
+
template: {
|
| 713 |
+
initializationUrl: string;
|
| 714 |
+
mediaUrlTemplate: string;
|
| 715 |
+
startNumber: number;
|
| 716 |
+
segmentTimeline: Array<{ duration: number; repeat: number }>;
|
| 717 |
+
baseUrl?: string;
|
| 718 |
+
codec?: string;
|
| 719 |
+
} | null
|
| 720 |
+
): { initializationUrl: string; segmentUrls: string[] } | null {
|
| 721 |
+
if (!template) return null;
|
| 722 |
+
|
| 723 |
+
const resolveUrl = (url: string): string => {
|
| 724 |
+
if (/^https?:\/\//i.test(url)) return url;
|
| 725 |
+
if (template.baseUrl) {
|
| 726 |
+
try {
|
| 727 |
+
return new URL(url, template.baseUrl).toString();
|
| 728 |
+
} catch {
|
| 729 |
+
return `${template.baseUrl.replace(/\/+$/, '')}/${url.replace(/^\/+/, '')}`;
|
| 730 |
+
}
|
| 731 |
+
}
|
| 732 |
+
return url;
|
| 733 |
+
};
|
| 734 |
+
|
| 735 |
+
const initializationUrl = resolveUrl(template.initializationUrl);
|
| 736 |
+
const segmentUrls: string[] = [];
|
| 737 |
+
let segmentNumber = template.startNumber;
|
| 738 |
+
const timeline =
|
| 739 |
+
template.segmentTimeline.length > 0 ? template.segmentTimeline : [{ duration: 0, repeat: 0 }];
|
| 740 |
+
|
| 741 |
+
for (const entry of timeline) {
|
| 742 |
+
const repeat = Number.isFinite(entry.repeat) ? entry.repeat : 0;
|
| 743 |
+
const count = Math.max(1, repeat + 1);
|
| 744 |
+
for (let i = 0; i < count; i += 1) {
|
| 745 |
+
const url = template.mediaUrlTemplate.replace('$Number$', `${segmentNumber}`);
|
| 746 |
+
segmentUrls.push(resolveUrl(url));
|
| 747 |
+
segmentNumber += 1;
|
| 748 |
+
}
|
| 749 |
+
}
|
| 750 |
+
|
| 751 |
+
return { initializationUrl, segmentUrls };
|
| 752 |
+
}
|
| 753 |
+
|
| 754 |
+
private async downloadFlacFromMpd(
|
| 755 |
+
manifestText: string,
|
| 756 |
+
options?: DownloadTrackOptions
|
| 757 |
+
): Promise<{ blob: Blob; mimeType: string } | null> {
|
| 758 |
+
const template = this.parseMpdSegmentTemplate(manifestText);
|
| 759 |
+
const segments = this.buildMpdSegmentUrls(template);
|
| 760 |
+
if (!segments) return null;
|
| 761 |
+
|
| 762 |
+
const urls = [segments.initializationUrl, ...segments.segmentUrls];
|
| 763 |
+
const chunks: Uint8Array[] = [];
|
| 764 |
+
let receivedBytes = 0;
|
| 765 |
+
|
| 766 |
+
for (const url of urls) {
|
| 767 |
+
const response = await this.fetch(url, { signal: options?.signal });
|
| 768 |
+
if (!response.ok) {
|
| 769 |
+
throw new Error(`Failed to fetch DASH segment (status ${response.status})`);
|
| 770 |
+
}
|
| 771 |
+
const buffer = await response.arrayBuffer();
|
| 772 |
+
const chunk = new Uint8Array(buffer);
|
| 773 |
+
receivedBytes += chunk.byteLength;
|
| 774 |
+
chunks.push(chunk);
|
| 775 |
+
options?.onProgress?.({ stage: 'downloading', receivedBytes, totalBytes: undefined });
|
| 776 |
+
}
|
| 777 |
+
|
| 778 |
+
const totalBytes = chunks.reduce((total, current) => total + current.byteLength, 0);
|
| 779 |
+
const merged = new Uint8Array(totalBytes);
|
| 780 |
+
let offset = 0;
|
| 781 |
+
for (const chunk of chunks) {
|
| 782 |
+
merged.set(chunk, offset);
|
| 783 |
+
offset += chunk.byteLength;
|
| 784 |
+
}
|
| 785 |
+
|
| 786 |
+
return { blob: new Blob([merged], { type: 'audio/flac' }), mimeType: 'audio/flac' };
|
| 787 |
+
}
|
| 788 |
+
|
| 789 |
+
private async resolveHiResStreamFromDash(trackId: number): Promise<string> {
|
| 790 |
+
const manifest = await this.getDashManifest(trackId, 'HI_RES_LOSSLESS');
|
| 791 |
+
if (manifest.kind === 'flac') {
|
| 792 |
+
const url = manifest.urls.find(
|
| 793 |
+
(candidate) => typeof candidate === 'string' && candidate.length > 0
|
| 794 |
+
);
|
| 795 |
+
if (url) {
|
| 796 |
+
return url;
|
| 797 |
+
}
|
| 798 |
+
throw new Error('DASH manifest did not include any FLAC URLs.');
|
| 799 |
+
}
|
| 800 |
+
const directUrl = this.parseFlacUrlFromMpd(manifest.manifest);
|
| 801 |
+
if (directUrl) {
|
| 802 |
+
return directUrl;
|
| 803 |
+
}
|
| 804 |
+
throw new Error('Hi-res DASH manifest does not expose a direct FLAC URL.');
|
| 805 |
+
}
|
| 806 |
+
|
| 807 |
+
/**
|
| 808 |
+
* Fetch wrapper with CORS handling
|
| 809 |
+
*/
|
| 810 |
+
private async fetch(
|
| 811 |
+
url: string,
|
| 812 |
+
options?: RequestInit & {
|
| 813 |
+
apiVersion?: 'v1' | 'v2';
|
| 814 |
+
preferredQuality?: string;
|
| 815 |
+
validateResponse?: (res: Response) => Promise<boolean>;
|
| 816 |
+
}
|
| 817 |
+
): Promise<Response> {
|
| 818 |
+
return fetchWithCORS(url, options);
|
| 819 |
+
}
|
| 820 |
+
|
| 821 |
+
/**
|
| 822 |
+
* Search for tracks
|
| 823 |
+
*/
|
| 824 |
+
async searchTracks(query: string, region: RegionOption = 'auto'): Promise<SearchResponse<Track>> {
|
| 825 |
+
const response = await this.fetch(
|
| 826 |
+
this.buildRegionalUrl(`/search/?s=${encodeURIComponent(query)}`, region)
|
| 827 |
+
);
|
| 828 |
+
this.ensureNotRateLimited(response);
|
| 829 |
+
if (!response.ok) throw new Error('Failed to search tracks');
|
| 830 |
+
const data = await response.json();
|
| 831 |
+
const normalized = this.normalizeSearchResponse<Track>(data, 'tracks');
|
| 832 |
+
return {
|
| 833 |
+
...normalized,
|
| 834 |
+
items: normalized.items.map((track) => this.prepareTrack(track))
|
| 835 |
+
};
|
| 836 |
+
}
|
| 837 |
+
|
| 838 |
+
/**
|
| 839 |
+
* Search for artists
|
| 840 |
+
*/
|
| 841 |
+
async searchArtists(
|
| 842 |
+
query: string,
|
| 843 |
+
region: RegionOption = 'auto'
|
| 844 |
+
): Promise<SearchResponse<Artist>> {
|
| 845 |
+
const response = await this.fetch(
|
| 846 |
+
this.buildRegionalUrl(`/search/?a=${encodeURIComponent(query)}`, region)
|
| 847 |
+
);
|
| 848 |
+
this.ensureNotRateLimited(response);
|
| 849 |
+
if (!response.ok) throw new Error('Failed to search artists');
|
| 850 |
+
const data = await response.json();
|
| 851 |
+
const normalized = this.normalizeSearchResponse<Artist>(data, 'artists');
|
| 852 |
+
return {
|
| 853 |
+
...normalized,
|
| 854 |
+
items: normalized.items.map((artist) => this.prepareArtist(artist))
|
| 855 |
+
};
|
| 856 |
+
}
|
| 857 |
+
|
| 858 |
+
/**
|
| 859 |
+
* Search for albums
|
| 860 |
+
*/
|
| 861 |
+
async searchAlbums(query: string, region: RegionOption = 'auto'): Promise<SearchResponse<Album>> {
|
| 862 |
+
const response = await this.fetch(
|
| 863 |
+
this.buildRegionalUrl(`/search/?al=${encodeURIComponent(query)}`, region)
|
| 864 |
+
);
|
| 865 |
+
this.ensureNotRateLimited(response);
|
| 866 |
+
if (!response.ok) throw new Error('Failed to search albums');
|
| 867 |
+
const data = await response.json();
|
| 868 |
+
const normalized = this.normalizeSearchResponse<Album>(data, 'albums');
|
| 869 |
+
return {
|
| 870 |
+
...normalized,
|
| 871 |
+
items: normalized.items.map((album) => this.prepareAlbum(album))
|
| 872 |
+
};
|
| 873 |
+
}
|
| 874 |
+
|
| 875 |
+
/**
|
| 876 |
+
* Search for playlists
|
| 877 |
+
*/
|
| 878 |
+
async searchPlaylists(
|
| 879 |
+
query: string,
|
| 880 |
+
region: RegionOption = 'auto'
|
| 881 |
+
): Promise<SearchResponse<Playlist>> {
|
| 882 |
+
const response = await this.fetch(
|
| 883 |
+
this.buildRegionalUrl(`/search/?p=${encodeURIComponent(query)}`, region)
|
| 884 |
+
);
|
| 885 |
+
this.ensureNotRateLimited(response);
|
| 886 |
+
if (!response.ok) throw new Error('Failed to search playlists');
|
| 887 |
+
const data = await response.json();
|
| 888 |
+
return this.normalizeSearchResponse<Playlist>(data, 'playlists');
|
| 889 |
+
}
|
| 890 |
+
|
| 891 |
+
/**
|
| 892 |
+
* Import content from a Tidal URL
|
| 893 |
+
* Supports track, album, artist, and playlist URLs
|
| 894 |
+
*/
|
| 895 |
+
async importFromUrl(url: string): Promise<{
|
| 896 |
+
type: 'track' | 'album' | 'artist' | 'playlist';
|
| 897 |
+
data: Track | Album | Artist | { playlist: Playlist; tracks: Track[] };
|
| 898 |
+
}> {
|
| 899 |
+
const parsed = parseTidalUrl(url);
|
| 900 |
+
|
| 901 |
+
if (parsed.type === 'unknown') {
|
| 902 |
+
throw new Error(
|
| 903 |
+
'Invalid Tidal URL. Please provide a valid track, album, artist, or playlist URL.'
|
| 904 |
+
);
|
| 905 |
+
}
|
| 906 |
+
|
| 907 |
+
switch (parsed.type) {
|
| 908 |
+
case 'track': {
|
| 909 |
+
if (!parsed.trackId) {
|
| 910 |
+
throw new Error('Could not extract track ID from URL');
|
| 911 |
+
}
|
| 912 |
+
const lookup = await this.getTrack(parsed.trackId);
|
| 913 |
+
return {
|
| 914 |
+
type: 'track',
|
| 915 |
+
data: this.prepareTrack(lookup.track)
|
| 916 |
+
};
|
| 917 |
+
}
|
| 918 |
+
|
| 919 |
+
case 'album': {
|
| 920 |
+
if (!parsed.albumId) {
|
| 921 |
+
throw new Error('Could not extract album ID from URL');
|
| 922 |
+
}
|
| 923 |
+
const { album } = await this.getAlbum(parsed.albumId);
|
| 924 |
+
return {
|
| 925 |
+
type: 'album',
|
| 926 |
+
data: this.prepareAlbum(album)
|
| 927 |
+
};
|
| 928 |
+
}
|
| 929 |
+
|
| 930 |
+
case 'artist': {
|
| 931 |
+
if (!parsed.artistId) {
|
| 932 |
+
throw new Error('Could not extract artist ID from URL');
|
| 933 |
+
}
|
| 934 |
+
const artist = await this.getArtist(parsed.artistId);
|
| 935 |
+
return {
|
| 936 |
+
type: 'artist',
|
| 937 |
+
data: this.prepareArtist(artist)
|
| 938 |
+
};
|
| 939 |
+
}
|
| 940 |
+
|
| 941 |
+
case 'playlist': {
|
| 942 |
+
if (!parsed.playlistId) {
|
| 943 |
+
throw new Error('Could not extract playlist ID from URL');
|
| 944 |
+
}
|
| 945 |
+
const { playlist, items } = await this.getPlaylist(parsed.playlistId);
|
| 946 |
+
const tracks = items.map((item) => this.prepareTrack(item.item));
|
| 947 |
+
return {
|
| 948 |
+
type: 'playlist',
|
| 949 |
+
data: { playlist, tracks }
|
| 950 |
+
};
|
| 951 |
+
}
|
| 952 |
+
|
| 953 |
+
default:
|
| 954 |
+
throw new Error('Unsupported URL type');
|
| 955 |
+
}
|
| 956 |
+
}
|
| 957 |
+
|
| 958 |
+
/**
|
| 959 |
+
* Get track info and stream URL (with retries for quality fallback)
|
| 960 |
+
*/
|
| 961 |
+
async getTrack(id: number, quality: AudioQuality = 'LOSSLESS'): Promise<TrackLookup> {
|
| 962 |
+
const url = `${this.baseUrl}/track/?id=${id}&quality=${quality}`;
|
| 963 |
+
let lastError: Error | null = null;
|
| 964 |
+
|
| 965 |
+
for (let attempt = 1; attempt <= 3; attempt += 1) {
|
| 966 |
+
const response = await this.fetch(url, {
|
| 967 |
+
apiVersion: 'v2',
|
| 968 |
+
validateResponse: async (res) => {
|
| 969 |
+
try {
|
| 970 |
+
const data = await res.json();
|
| 971 |
+
const container = (data?.data ?? data) as Record<string, unknown>;
|
| 972 |
+
return container?.assetPresentation !== 'PREVIEW';
|
| 973 |
+
} catch {
|
| 974 |
+
return true;
|
| 975 |
+
}
|
| 976 |
+
}
|
| 977 |
+
});
|
| 978 |
+
this.ensureNotRateLimited(response);
|
| 979 |
+
if (response.ok) {
|
| 980 |
+
const data = await response.json();
|
| 981 |
+
if (this.isV2ApiContainer(data)) {
|
| 982 |
+
return await this.parseTrackLookupV2(id, data, 'v2');
|
| 983 |
+
}
|
| 984 |
+
return this.parseTrackLookup(data);
|
| 985 |
+
}
|
| 986 |
+
|
| 987 |
+
let detail: string | undefined;
|
| 988 |
+
let userMessage: string | undefined;
|
| 989 |
+
let subStatus: number | undefined;
|
| 990 |
+
try {
|
| 991 |
+
const errorData = (await response.json()) as {
|
| 992 |
+
detail?: unknown;
|
| 993 |
+
subStatus?: unknown;
|
| 994 |
+
userMessage?: unknown;
|
| 995 |
+
};
|
| 996 |
+
if (typeof errorData?.detail === 'string') {
|
| 997 |
+
detail = errorData.detail;
|
| 998 |
+
}
|
| 999 |
+
if (typeof errorData?.userMessage === 'string') {
|
| 1000 |
+
userMessage = errorData.userMessage;
|
| 1001 |
+
if (!detail) {
|
| 1002 |
+
detail = errorData.userMessage;
|
| 1003 |
+
}
|
| 1004 |
+
}
|
| 1005 |
+
if (typeof errorData?.subStatus === 'number') {
|
| 1006 |
+
subStatus = errorData.subStatus;
|
| 1007 |
+
}
|
| 1008 |
+
} catch {
|
| 1009 |
+
// Ignore JSON parse errors
|
| 1010 |
+
}
|
| 1011 |
+
|
| 1012 |
+
const isTokenRetry = response.status === 401 && subStatus === 11002;
|
| 1013 |
+
const message = detail ?? `Failed to get track (status ${response.status})`;
|
| 1014 |
+
lastError = new Error(isTokenRetry ? (userMessage ?? message) : message);
|
| 1015 |
+
const shouldRetry =
|
| 1016 |
+
isTokenRetry || (detail ? /quality not found/i.test(detail) : response.status >= 500);
|
| 1017 |
+
|
| 1018 |
+
if (attempt === 3 || !shouldRetry) {
|
| 1019 |
+
throw lastError;
|
| 1020 |
+
}
|
| 1021 |
+
|
| 1022 |
+
await this.delay(200 * attempt);
|
| 1023 |
+
}
|
| 1024 |
+
|
| 1025 |
+
throw lastError ?? new Error('Failed to get track');
|
| 1026 |
+
}
|
| 1027 |
+
|
| 1028 |
+
async getRecommendations(trackId: number): Promise<Track[]> {
|
| 1029 |
+
const response = await this.fetch(`${this.baseUrl}/recommendations/?id=${trackId}`);
|
| 1030 |
+
this.ensureNotRateLimited(response);
|
| 1031 |
+
if (!response.ok) {
|
| 1032 |
+
throw new Error('Failed to fetch track recommendations');
|
| 1033 |
+
}
|
| 1034 |
+
const payload: TrackRecommendationsResponse = await response.json();
|
| 1035 |
+
if (!payload.data.items) {
|
| 1036 |
+
throw new Error('No recommendations found');
|
| 1037 |
+
}
|
| 1038 |
+
return payload.data.items.map(item => item.track);
|
| 1039 |
+
}
|
| 1040 |
+
|
| 1041 |
+
async getDashManifest(
|
| 1042 |
+
trackId: number,
|
| 1043 |
+
quality: AudioQuality = 'HI_RES_LOSSLESS'
|
| 1044 |
+
): Promise<DashManifestResult> {
|
| 1045 |
+
const { result } = await this.getDashManifestWithMetadata(trackId, quality);
|
| 1046 |
+
return result;
|
| 1047 |
+
}
|
| 1048 |
+
|
| 1049 |
+
async getDashManifestWithMetadata(
|
| 1050 |
+
trackId: number,
|
| 1051 |
+
quality: AudioQuality = 'HI_RES_LOSSLESS'
|
| 1052 |
+
): Promise<DashManifestWithMetadata> {
|
| 1053 |
+
let lastError: Error | null = null;
|
| 1054 |
+
|
| 1055 |
+
for (let attempt = 1; attempt <= 3; attempt += 1) {
|
| 1056 |
+
try {
|
| 1057 |
+
const lookup = await this.getTrack(trackId, quality);
|
| 1058 |
+
const manifestPayload = lookup.info?.manifest ?? '';
|
| 1059 |
+
const contentType = lookup.info?.manifestMimeType ?? null;
|
| 1060 |
+
const result = this.buildDashManifestResult(manifestPayload, contentType);
|
| 1061 |
+
const trackInfo = {
|
| 1062 |
+
sampleRate: lookup.info?.sampleRate ?? null,
|
| 1063 |
+
bitDepth: lookup.info?.bitDepth ?? null,
|
| 1064 |
+
replayGain: lookup.info?.trackReplayGain ?? null
|
| 1065 |
+
};
|
| 1066 |
+
return { result, trackInfo };
|
| 1067 |
+
} catch (error) {
|
| 1068 |
+
lastError = error instanceof Error ? error : new Error(String(error));
|
| 1069 |
+
}
|
| 1070 |
+
|
| 1071 |
+
if (attempt < 3) {
|
| 1072 |
+
await this.delay(200 * attempt);
|
| 1073 |
+
}
|
| 1074 |
+
}
|
| 1075 |
+
|
| 1076 |
+
throw lastError ?? this.createDashUnavailableError('Unable to load dash manifest for track');
|
| 1077 |
+
}
|
| 1078 |
+
|
| 1079 |
+
/**
|
| 1080 |
+
* Get song with stream info
|
| 1081 |
+
*/
|
| 1082 |
+
async getSong(query: string, quality: AudioQuality = 'LOSSLESS'): Promise<StreamData> {
|
| 1083 |
+
const response = await this.fetch(
|
| 1084 |
+
`${this.baseUrl}/song/?q=${encodeURIComponent(query)}&quality=${quality}`
|
| 1085 |
+
);
|
| 1086 |
+
this.ensureNotRateLimited(response);
|
| 1087 |
+
if (!response.ok) throw new Error('Failed to get song');
|
| 1088 |
+
return response.json();
|
| 1089 |
+
}
|
| 1090 |
+
|
| 1091 |
+
/**
|
| 1092 |
+
* Get album details with track listing
|
| 1093 |
+
*/
|
| 1094 |
+
async getAlbum(id: number): Promise<{ album: Album; tracks: Track[] }> {
|
| 1095 |
+
const response = await this.fetch(`${this.baseUrl}/album/?id=${id}`);
|
| 1096 |
+
this.ensureNotRateLimited(response);
|
| 1097 |
+
if (!response.ok) throw new Error('Failed to get album');
|
| 1098 |
+
const data = await response.json();
|
| 1099 |
+
|
| 1100 |
+
// Handle v2/new API structure where response is { version, data: { items: [...] } }
|
| 1101 |
+
if (data && typeof data === 'object' && 'data' in data && 'items' in data.data) {
|
| 1102 |
+
const items = data.data.items;
|
| 1103 |
+
if (Array.isArray(items) && items.length > 0) {
|
| 1104 |
+
const firstItem = items[0];
|
| 1105 |
+
const firstTrack = firstItem.item || firstItem;
|
| 1106 |
+
|
| 1107 |
+
if (firstTrack && firstTrack.album) {
|
| 1108 |
+
let albumEntry = this.prepareAlbum(firstTrack.album);
|
| 1109 |
+
|
| 1110 |
+
// If album doesn't have artist info, try to get it from the track
|
| 1111 |
+
if (!albumEntry.artist && firstTrack.artist) {
|
| 1112 |
+
albumEntry = { ...albumEntry, artist: firstTrack.artist };
|
| 1113 |
+
}
|
| 1114 |
+
|
| 1115 |
+
const tracks = items
|
| 1116 |
+
.map((i: unknown) => {
|
| 1117 |
+
if (!i || typeof i !== 'object') return null;
|
| 1118 |
+
const itemObj = i as { item?: unknown };
|
| 1119 |
+
const t = (itemObj.item || itemObj) as Track;
|
| 1120 |
+
|
| 1121 |
+
if (!t) return null;
|
| 1122 |
+
// Ensure track has album reference
|
| 1123 |
+
return this.prepareTrack({ ...t, album: albumEntry });
|
| 1124 |
+
})
|
| 1125 |
+
.filter((t): t is Track => t !== null);
|
| 1126 |
+
|
| 1127 |
+
return { album: albumEntry, tracks };
|
| 1128 |
+
}
|
| 1129 |
+
}
|
| 1130 |
+
}
|
| 1131 |
+
|
| 1132 |
+
const entries = Array.isArray(data) ? data : [data];
|
| 1133 |
+
|
| 1134 |
+
let albumEntry: Album | undefined;
|
| 1135 |
+
let trackCollection: { items?: unknown[] } | undefined;
|
| 1136 |
+
|
| 1137 |
+
for (const entry of entries) {
|
| 1138 |
+
if (!entry || typeof entry !== 'object') continue;
|
| 1139 |
+
|
| 1140 |
+
if (!albumEntry && 'title' in entry && 'id' in entry && 'cover' in entry) {
|
| 1141 |
+
albumEntry = this.prepareAlbum(entry as Album);
|
| 1142 |
+
continue;
|
| 1143 |
+
}
|
| 1144 |
+
|
| 1145 |
+
if (
|
| 1146 |
+
!trackCollection &&
|
| 1147 |
+
'items' in entry &&
|
| 1148 |
+
Array.isArray((entry as { items?: unknown[] }).items)
|
| 1149 |
+
) {
|
| 1150 |
+
trackCollection = entry as { items?: unknown[] };
|
| 1151 |
+
}
|
| 1152 |
+
}
|
| 1153 |
+
|
| 1154 |
+
if (!albumEntry) {
|
| 1155 |
+
throw new Error('Album not found');
|
| 1156 |
+
}
|
| 1157 |
+
|
| 1158 |
+
const tracks: Track[] = [];
|
| 1159 |
+
if (trackCollection?.items) {
|
| 1160 |
+
for (const rawItem of trackCollection.items) {
|
| 1161 |
+
if (!rawItem || typeof rawItem !== 'object') continue;
|
| 1162 |
+
|
| 1163 |
+
let trackCandidate: Track | undefined;
|
| 1164 |
+
if ('item' in rawItem && rawItem.item && typeof rawItem.item === 'object') {
|
| 1165 |
+
trackCandidate = rawItem.item as Track;
|
| 1166 |
+
} else {
|
| 1167 |
+
trackCandidate = rawItem as Track;
|
| 1168 |
+
}
|
| 1169 |
+
|
| 1170 |
+
if (!trackCandidate) continue;
|
| 1171 |
+
|
| 1172 |
+
const candidateWithAlbum = trackCandidate.album
|
| 1173 |
+
? trackCandidate
|
| 1174 |
+
: ({ ...trackCandidate, album: albumEntry } as Track);
|
| 1175 |
+
tracks.push(this.prepareTrack(candidateWithAlbum));
|
| 1176 |
+
}
|
| 1177 |
+
}
|
| 1178 |
+
|
| 1179 |
+
return { album: albumEntry, tracks };
|
| 1180 |
+
}
|
| 1181 |
+
|
| 1182 |
+
/**
|
| 1183 |
+
* Get playlist details
|
| 1184 |
+
*/
|
| 1185 |
+
async getPlaylist(uuid: string): Promise<{ playlist: Playlist; items: Array<{ item: Track }> }> {
|
| 1186 |
+
const response = await this.fetch(`${this.baseUrl}/playlist/?id=${uuid}`);
|
| 1187 |
+
this.ensureNotRateLimited(response);
|
| 1188 |
+
if (!response.ok) throw new Error('Failed to get playlist');
|
| 1189 |
+
const data = await response.json();
|
| 1190 |
+
|
| 1191 |
+
// Handle v2 structure (object with playlist and items keys)
|
| 1192 |
+
if (data && typeof data === 'object' && 'playlist' in data && 'items' in data) {
|
| 1193 |
+
return {
|
| 1194 |
+
playlist: data.playlist,
|
| 1195 |
+
items: data.items
|
| 1196 |
+
};
|
| 1197 |
+
}
|
| 1198 |
+
|
| 1199 |
+
return {
|
| 1200 |
+
playlist: Array.isArray(data) ? data[0] : data,
|
| 1201 |
+
items: Array.isArray(data) && data[1] ? data[1].items : []
|
| 1202 |
+
};
|
| 1203 |
+
}
|
| 1204 |
+
|
| 1205 |
+
/**
|
| 1206 |
+
* Get artist overview, including discography modules and top tracks
|
| 1207 |
+
*/
|
| 1208 |
+
async getArtist(id: number): Promise<ArtistDetails> {
|
| 1209 |
+
const response = await this.fetch(`${this.baseUrl}/artist/?f=${id}`);
|
| 1210 |
+
this.ensureNotRateLimited(response);
|
| 1211 |
+
if (!response.ok) throw new Error('Failed to get artist');
|
| 1212 |
+
const data = await response.json();
|
| 1213 |
+
const entries = Array.isArray(data) ? data : [data];
|
| 1214 |
+
|
| 1215 |
+
const visited = new Set<object>();
|
| 1216 |
+
const albumMap = new Map<number, Album>();
|
| 1217 |
+
const trackMap = new Map<number, Track>();
|
| 1218 |
+
let artist: Artist | undefined;
|
| 1219 |
+
|
| 1220 |
+
const isTrackLike = (value: unknown): value is Track => {
|
| 1221 |
+
if (!value || typeof value !== 'object') return false;
|
| 1222 |
+
const candidate = value as Record<string, unknown>;
|
| 1223 |
+
const albumCandidate = candidate.album as unknown;
|
| 1224 |
+
return (
|
| 1225 |
+
typeof candidate.id === 'number' &&
|
| 1226 |
+
typeof candidate.title === 'string' &&
|
| 1227 |
+
typeof candidate.duration === 'number' &&
|
| 1228 |
+
'trackNumber' in candidate &&
|
| 1229 |
+
albumCandidate !== undefined &&
|
| 1230 |
+
albumCandidate !== null &&
|
| 1231 |
+
typeof albumCandidate === 'object'
|
| 1232 |
+
);
|
| 1233 |
+
};
|
| 1234 |
+
|
| 1235 |
+
const isAlbumLike = (value: unknown): value is Album => {
|
| 1236 |
+
if (!value || typeof value !== 'object') return false;
|
| 1237 |
+
const candidate = value as Record<string, unknown>;
|
| 1238 |
+
return (
|
| 1239 |
+
typeof candidate.id === 'number' &&
|
| 1240 |
+
typeof candidate.title === 'string' &&
|
| 1241 |
+
'cover' in candidate
|
| 1242 |
+
);
|
| 1243 |
+
};
|
| 1244 |
+
|
| 1245 |
+
const isArtistLike = (value: unknown): value is Artist => {
|
| 1246 |
+
if (!value || typeof value !== 'object') return false;
|
| 1247 |
+
const candidate = value as Record<string, unknown>;
|
| 1248 |
+
return (
|
| 1249 |
+
typeof candidate.id === 'number' &&
|
| 1250 |
+
typeof candidate.name === 'string' &&
|
| 1251 |
+
typeof candidate.type === 'string' &&
|
| 1252 |
+
('artistRoles' in candidate || 'artistTypes' in candidate || 'url' in candidate)
|
| 1253 |
+
);
|
| 1254 |
+
};
|
| 1255 |
+
|
| 1256 |
+
const recordArtist = (candidate: Artist | undefined) => {
|
| 1257 |
+
if (!candidate) return;
|
| 1258 |
+
const normalized = this.prepareArtist(candidate);
|
| 1259 |
+
if (!artist || artist.id === normalized.id) {
|
| 1260 |
+
artist = normalized;
|
| 1261 |
+
}
|
| 1262 |
+
};
|
| 1263 |
+
|
| 1264 |
+
const addAlbum = (candidate: Album | undefined) => {
|
| 1265 |
+
if (!candidate || typeof candidate.id !== 'number') return;
|
| 1266 |
+
const normalized = this.prepareAlbum({ ...candidate });
|
| 1267 |
+
albumMap.set(normalized.id, normalized);
|
| 1268 |
+
recordArtist(normalized.artist ?? normalized.artists?.[0]);
|
| 1269 |
+
};
|
| 1270 |
+
|
| 1271 |
+
const addTrack = (candidate: Track | undefined) => {
|
| 1272 |
+
if (!candidate || typeof candidate.id !== 'number') return;
|
| 1273 |
+
const normalized = this.prepareTrack({ ...candidate });
|
| 1274 |
+
if (!normalized.album) {
|
| 1275 |
+
return;
|
| 1276 |
+
}
|
| 1277 |
+
addAlbum(normalized.album);
|
| 1278 |
+
const knownAlbum = albumMap.get(normalized.album.id);
|
| 1279 |
+
if (knownAlbum) {
|
| 1280 |
+
normalized.album = knownAlbum;
|
| 1281 |
+
}
|
| 1282 |
+
trackMap.set(normalized.id, normalized);
|
| 1283 |
+
recordArtist(normalized.artist);
|
| 1284 |
+
};
|
| 1285 |
+
|
| 1286 |
+
const parseModuleItems = (items: unknown) => {
|
| 1287 |
+
if (!Array.isArray(items)) return;
|
| 1288 |
+
for (const entry of items) {
|
| 1289 |
+
if (!entry || typeof entry !== 'object') {
|
| 1290 |
+
continue;
|
| 1291 |
+
}
|
| 1292 |
+
|
| 1293 |
+
const candidate = 'item' in entry ? (entry as { item?: unknown }).item : entry;
|
| 1294 |
+
if (isAlbumLike(candidate)) {
|
| 1295 |
+
addAlbum(candidate as Album);
|
| 1296 |
+
const normalizedAlbum = albumMap.get((candidate as Album).id);
|
| 1297 |
+
recordArtist(normalizedAlbum?.artist ?? normalizedAlbum?.artists?.[0]);
|
| 1298 |
+
continue;
|
| 1299 |
+
}
|
| 1300 |
+
if (isTrackLike(candidate)) {
|
| 1301 |
+
addTrack(candidate as Track);
|
| 1302 |
+
continue;
|
| 1303 |
+
}
|
| 1304 |
+
|
| 1305 |
+
scanValue(candidate);
|
| 1306 |
+
}
|
| 1307 |
+
};
|
| 1308 |
+
|
| 1309 |
+
const scanValue = (value: unknown) => {
|
| 1310 |
+
if (!value) return;
|
| 1311 |
+
if (Array.isArray(value)) {
|
| 1312 |
+
const trackCandidates = value.filter(isTrackLike);
|
| 1313 |
+
if (trackCandidates.length > 0) {
|
| 1314 |
+
for (const track of trackCandidates) {
|
| 1315 |
+
addTrack(track);
|
| 1316 |
+
}
|
| 1317 |
+
return;
|
| 1318 |
+
}
|
| 1319 |
+
for (const entry of value) {
|
| 1320 |
+
scanValue(entry);
|
| 1321 |
+
}
|
| 1322 |
+
return;
|
| 1323 |
+
}
|
| 1324 |
+
|
| 1325 |
+
if (typeof value !== 'object') {
|
| 1326 |
+
return;
|
| 1327 |
+
}
|
| 1328 |
+
|
| 1329 |
+
const objectRef = value as Record<string, unknown>;
|
| 1330 |
+
if (visited.has(objectRef)) {
|
| 1331 |
+
return;
|
| 1332 |
+
}
|
| 1333 |
+
visited.add(objectRef);
|
| 1334 |
+
|
| 1335 |
+
if (isArtistLike(objectRef)) {
|
| 1336 |
+
recordArtist(objectRef as Artist);
|
| 1337 |
+
}
|
| 1338 |
+
|
| 1339 |
+
if ('modules' in objectRef && Array.isArray(objectRef.modules)) {
|
| 1340 |
+
for (const moduleEntry of objectRef.modules) {
|
| 1341 |
+
scanValue(moduleEntry);
|
| 1342 |
+
}
|
| 1343 |
+
}
|
| 1344 |
+
|
| 1345 |
+
if (
|
| 1346 |
+
'pagedList' in objectRef &&
|
| 1347 |
+
objectRef.pagedList &&
|
| 1348 |
+
typeof objectRef.pagedList === 'object'
|
| 1349 |
+
) {
|
| 1350 |
+
const pagedList = objectRef.pagedList as { items?: unknown };
|
| 1351 |
+
parseModuleItems(pagedList.items);
|
| 1352 |
+
}
|
| 1353 |
+
|
| 1354 |
+
if ('items' in objectRef && Array.isArray(objectRef.items)) {
|
| 1355 |
+
parseModuleItems(objectRef.items);
|
| 1356 |
+
}
|
| 1357 |
+
|
| 1358 |
+
if ('rows' in objectRef && Array.isArray(objectRef.rows)) {
|
| 1359 |
+
parseModuleItems(objectRef.rows);
|
| 1360 |
+
}
|
| 1361 |
+
|
| 1362 |
+
if ('listItems' in objectRef && Array.isArray(objectRef.listItems)) {
|
| 1363 |
+
parseModuleItems(objectRef.listItems);
|
| 1364 |
+
}
|
| 1365 |
+
|
| 1366 |
+
for (const nested of Object.values(objectRef)) {
|
| 1367 |
+
scanValue(nested);
|
| 1368 |
+
}
|
| 1369 |
+
};
|
| 1370 |
+
|
| 1371 |
+
for (const entry of entries) {
|
| 1372 |
+
scanValue(entry);
|
| 1373 |
+
}
|
| 1374 |
+
|
| 1375 |
+
if (!artist) {
|
| 1376 |
+
const trackPrimaryArtist = Array.from(trackMap.values())
|
| 1377 |
+
.map((track) => track.artist ?? track.artists?.[0])
|
| 1378 |
+
.find(Boolean);
|
| 1379 |
+
const albumPrimaryArtist = Array.from(albumMap.values())
|
| 1380 |
+
.map((album) => album.artist ?? album.artists?.[0])
|
| 1381 |
+
.find(Boolean);
|
| 1382 |
+
recordArtist(trackPrimaryArtist ?? albumPrimaryArtist);
|
| 1383 |
+
}
|
| 1384 |
+
|
| 1385 |
+
if (!artist) {
|
| 1386 |
+
try {
|
| 1387 |
+
const fallbackResponse = await this.fetch(`${this.baseUrl}/artist/?id=${id}`);
|
| 1388 |
+
this.ensureNotRateLimited(fallbackResponse);
|
| 1389 |
+
if (fallbackResponse.ok) {
|
| 1390 |
+
const fallbackData = await fallbackResponse.json();
|
| 1391 |
+
const baseArtist = Array.isArray(fallbackData) ? fallbackData[0] : fallbackData;
|
| 1392 |
+
if (baseArtist && typeof baseArtist === 'object') {
|
| 1393 |
+
recordArtist(baseArtist as Artist);
|
| 1394 |
+
}
|
| 1395 |
+
}
|
| 1396 |
+
} catch (fallbackError) {
|
| 1397 |
+
console.warn('Failed to fetch base artist details:', fallbackError);
|
| 1398 |
+
}
|
| 1399 |
+
}
|
| 1400 |
+
|
| 1401 |
+
if (!artist) {
|
| 1402 |
+
throw new Error('Artist not found');
|
| 1403 |
+
}
|
| 1404 |
+
|
| 1405 |
+
const albums = Array.from(albumMap.values()).map((album) => {
|
| 1406 |
+
if (!album.artist && artist) {
|
| 1407 |
+
return { ...album, artist };
|
| 1408 |
+
}
|
| 1409 |
+
return album;
|
| 1410 |
+
});
|
| 1411 |
+
|
| 1412 |
+
const albumById = new Map(albums.map((album) => [album.id, album] as const));
|
| 1413 |
+
|
| 1414 |
+
const tracks = Array.from(trackMap.values()).map((track) => {
|
| 1415 |
+
const enrichedArtist = track.artist ?? artist;
|
| 1416 |
+
const album = track.album;
|
| 1417 |
+
const enrichedAlbum = album
|
| 1418 |
+
? (albumById.get(album.id) ?? (artist && !album.artist ? { ...album, artist } : album))
|
| 1419 |
+
: undefined;
|
| 1420 |
+
return {
|
| 1421 |
+
...track,
|
| 1422 |
+
artist: enrichedArtist ?? track.artist,
|
| 1423 |
+
album: enrichedAlbum ?? album
|
| 1424 |
+
};
|
| 1425 |
+
});
|
| 1426 |
+
|
| 1427 |
+
const parseDate = (value?: string): number => {
|
| 1428 |
+
if (!value) return Number.NaN;
|
| 1429 |
+
const timestamp = Date.parse(value);
|
| 1430 |
+
return Number.isFinite(timestamp) ? timestamp : Number.NaN;
|
| 1431 |
+
};
|
| 1432 |
+
|
| 1433 |
+
const sortedAlbums = albums.sort((a, b) => {
|
| 1434 |
+
const timeA = parseDate(a.releaseDate);
|
| 1435 |
+
const timeB = parseDate(b.releaseDate);
|
| 1436 |
+
if (Number.isNaN(timeA) && Number.isNaN(timeB)) {
|
| 1437 |
+
return (b.popularity ?? 0) - (a.popularity ?? 0);
|
| 1438 |
+
}
|
| 1439 |
+
if (Number.isNaN(timeA)) return 1;
|
| 1440 |
+
if (Number.isNaN(timeB)) return -1;
|
| 1441 |
+
return timeB - timeA;
|
| 1442 |
+
});
|
| 1443 |
+
|
| 1444 |
+
const sortedTracks = tracks
|
| 1445 |
+
.sort((a, b) => (b.popularity ?? 0) - (a.popularity ?? 0))
|
| 1446 |
+
.slice(0, 100);
|
| 1447 |
+
|
| 1448 |
+
return {
|
| 1449 |
+
...artist,
|
| 1450 |
+
albums: sortedAlbums,
|
| 1451 |
+
tracks: sortedTracks
|
| 1452 |
+
};
|
| 1453 |
+
}
|
| 1454 |
+
|
| 1455 |
+
/**
|
| 1456 |
+
* Get cover image
|
| 1457 |
+
*/
|
| 1458 |
+
async getCover(id?: number, query?: string): Promise<CoverImage[]> {
|
| 1459 |
+
let url = `${this.baseUrl}/cover/?`;
|
| 1460 |
+
if (id) url += `id=${id}`;
|
| 1461 |
+
if (query) url += `q=${encodeURIComponent(query)}`;
|
| 1462 |
+
const response = await this.fetch(url);
|
| 1463 |
+
this.ensureNotRateLimited(response);
|
| 1464 |
+
if (!response.ok) throw new Error('Failed to get cover');
|
| 1465 |
+
return response.json();
|
| 1466 |
+
}
|
| 1467 |
+
|
| 1468 |
+
/**
|
| 1469 |
+
* Get lyrics for a track
|
| 1470 |
+
*/
|
| 1471 |
+
async getLyrics(id: number): Promise<Lyrics> {
|
| 1472 |
+
const response = await this.fetch(`${this.baseUrl}/lyrics/?id=${id}`);
|
| 1473 |
+
this.ensureNotRateLimited(response);
|
| 1474 |
+
if (!response.ok) throw new Error('Failed to get lyrics');
|
| 1475 |
+
const data = await response.json();
|
| 1476 |
+
return Array.isArray(data) ? data[0] : data;
|
| 1477 |
+
}
|
| 1478 |
+
|
| 1479 |
+
/**
|
| 1480 |
+
* Get stream data including URL and replay gain
|
| 1481 |
+
*/
|
| 1482 |
+
async getStreamData(
|
| 1483 |
+
trackId: number,
|
| 1484 |
+
quality: AudioQuality = 'LOSSLESS'
|
| 1485 |
+
): Promise<{
|
| 1486 |
+
url: string;
|
| 1487 |
+
replayGain: number | null;
|
| 1488 |
+
sampleRate: number | null;
|
| 1489 |
+
bitDepth: number | null;
|
| 1490 |
+
}> {
|
| 1491 |
+
let replayGain: number | null = null;
|
| 1492 |
+
let sampleRate: number | null = null;
|
| 1493 |
+
let bitDepth: number | null = null;
|
| 1494 |
+
|
| 1495 |
+
if (this.isHiResQuality(quality)) {
|
| 1496 |
+
try {
|
| 1497 |
+
// Try to fetch metadata for replay gain, but don't fail if it fails
|
| 1498 |
+
try {
|
| 1499 |
+
const lookup = await this.getTrack(trackId, quality);
|
| 1500 |
+
replayGain = lookup.info.trackReplayGain ?? null;
|
| 1501 |
+
sampleRate = lookup.info.sampleRate ?? null;
|
| 1502 |
+
bitDepth = lookup.info.bitDepth ?? null;
|
| 1503 |
+
} catch {
|
| 1504 |
+
// Ignore metadata fetch failure for HiRes
|
| 1505 |
+
}
|
| 1506 |
+
|
| 1507 |
+
const url = await this.resolveHiResStreamFromDash(trackId);
|
| 1508 |
+
return { url, replayGain, sampleRate, bitDepth };
|
| 1509 |
+
} catch (error) {
|
| 1510 |
+
console.warn('Failed to resolve hi-res stream via DASH manifest', error);
|
| 1511 |
+
quality = 'LOSSLESS';
|
| 1512 |
+
}
|
| 1513 |
+
}
|
| 1514 |
+
|
| 1515 |
+
let lastError: Error | null = null;
|
| 1516 |
+
|
| 1517 |
+
for (let attempt = 1; attempt <= 3; attempt += 1) {
|
| 1518 |
+
try {
|
| 1519 |
+
const lookup = await this.getTrack(trackId, quality);
|
| 1520 |
+
replayGain = lookup.info.trackReplayGain ?? null;
|
| 1521 |
+
sampleRate = lookup.info.sampleRate ?? null;
|
| 1522 |
+
bitDepth = lookup.info.bitDepth ?? null;
|
| 1523 |
+
|
| 1524 |
+
if (lookup.originalTrackUrl) {
|
| 1525 |
+
return { url: lookup.originalTrackUrl, replayGain, sampleRate, bitDepth };
|
| 1526 |
+
}
|
| 1527 |
+
|
| 1528 |
+
const manifestUrl = this.extractStreamUrlFromManifest(lookup.info.manifest);
|
| 1529 |
+
if (manifestUrl) {
|
| 1530 |
+
return { url: manifestUrl, replayGain, sampleRate, bitDepth };
|
| 1531 |
+
}
|
| 1532 |
+
|
| 1533 |
+
lastError = new Error('Unable to resolve stream URL for track');
|
| 1534 |
+
} catch (error) {
|
| 1535 |
+
lastError = error instanceof Error ? error : new Error(String(error));
|
| 1536 |
+
}
|
| 1537 |
+
|
| 1538 |
+
if (attempt < 3) {
|
| 1539 |
+
await this.delay(200 * attempt);
|
| 1540 |
+
}
|
| 1541 |
+
}
|
| 1542 |
+
|
| 1543 |
+
throw lastError ?? new Error('Unable to resolve stream URL for track');
|
| 1544 |
+
}
|
| 1545 |
+
|
| 1546 |
+
/**
|
| 1547 |
+
* Get stream URL for a track
|
| 1548 |
+
*/
|
| 1549 |
+
async getStreamUrl(trackId: number, quality: AudioQuality = 'LOSSLESS'): Promise<string> {
|
| 1550 |
+
const data = await this.getStreamData(trackId, quality);
|
| 1551 |
+
return data.url;
|
| 1552 |
+
}
|
| 1553 |
+
|
| 1554 |
+
/**
|
| 1555 |
+
* Attempt to embed metadata into a downloaded track using FFmpeg WASM
|
| 1556 |
+
*/
|
| 1557 |
+
private async embedMetadataIntoBlob(
|
| 1558 |
+
blob: Blob,
|
| 1559 |
+
lookup: TrackLookup,
|
| 1560 |
+
filename: string,
|
| 1561 |
+
contentType: string | null,
|
| 1562 |
+
options: DownloadTrackOptions | undefined,
|
| 1563 |
+
quality: AudioQuality,
|
| 1564 |
+
convertToMp3: boolean
|
| 1565 |
+
): Promise<Blob | null> {
|
| 1566 |
+
const job = this.metadataQueue.then(() =>
|
| 1567 |
+
this.runMetadataEmbedding(
|
| 1568 |
+
blob,
|
| 1569 |
+
lookup,
|
| 1570 |
+
filename,
|
| 1571 |
+
contentType ?? undefined,
|
| 1572 |
+
options,
|
| 1573 |
+
quality,
|
| 1574 |
+
convertToMp3
|
| 1575 |
+
)
|
| 1576 |
+
);
|
| 1577 |
+
this.metadataQueue = job.then(
|
| 1578 |
+
() => undefined,
|
| 1579 |
+
() => undefined
|
| 1580 |
+
);
|
| 1581 |
+
|
| 1582 |
+
try {
|
| 1583 |
+
return await job;
|
| 1584 |
+
} catch (error) {
|
| 1585 |
+
console.warn('Metadata embedding failed', error);
|
| 1586 |
+
return null;
|
| 1587 |
+
}
|
| 1588 |
+
}
|
| 1589 |
+
|
| 1590 |
+
private inferExtensionFromFilename(filename: string): string | null {
|
| 1591 |
+
const match = /\.([a-z0-9]+)(?:\?.*)?$/i.exec(filename);
|
| 1592 |
+
return match ? match[1]!.toLowerCase() : null;
|
| 1593 |
+
}
|
| 1594 |
+
|
| 1595 |
+
private inferExtensionFromMime(mime?: string | null): string | null {
|
| 1596 |
+
if (!mime) return null;
|
| 1597 |
+
const normalized = mime.split(';')[0]?.trim().toLowerCase();
|
| 1598 |
+
switch (normalized) {
|
| 1599 |
+
case 'audio/flac':
|
| 1600 |
+
return 'flac';
|
| 1601 |
+
case 'audio/x-flac':
|
| 1602 |
+
return 'flac';
|
| 1603 |
+
case 'audio/mpeg':
|
| 1604 |
+
return 'mp3';
|
| 1605 |
+
case 'audio/mp3':
|
| 1606 |
+
return 'mp3';
|
| 1607 |
+
case 'audio/mp4':
|
| 1608 |
+
case 'audio/aac':
|
| 1609 |
+
case 'audio/x-m4a':
|
| 1610 |
+
return 'm4a';
|
| 1611 |
+
case 'audio/wav':
|
| 1612 |
+
case 'audio/x-wav':
|
| 1613 |
+
return 'wav';
|
| 1614 |
+
case 'audio/ogg':
|
| 1615 |
+
return 'ogg';
|
| 1616 |
+
default:
|
| 1617 |
+
return null;
|
| 1618 |
+
}
|
| 1619 |
+
}
|
| 1620 |
+
|
| 1621 |
+
private inferMimeFromExtension(
|
| 1622 |
+
ext: string | null | undefined,
|
| 1623 |
+
fallbackType?: string
|
| 1624 |
+
): string | undefined {
|
| 1625 |
+
switch (ext) {
|
| 1626 |
+
case 'flac':
|
| 1627 |
+
return 'audio/flac';
|
| 1628 |
+
case 'mp3':
|
| 1629 |
+
return 'audio/mpeg';
|
| 1630 |
+
case 'm4a':
|
| 1631 |
+
case 'aac':
|
| 1632 |
+
return 'audio/mp4';
|
| 1633 |
+
case 'wav':
|
| 1634 |
+
return 'audio/wav';
|
| 1635 |
+
case 'ogg':
|
| 1636 |
+
return 'audio/ogg';
|
| 1637 |
+
default:
|
| 1638 |
+
return fallbackType;
|
| 1639 |
+
}
|
| 1640 |
+
}
|
| 1641 |
+
|
| 1642 |
+
private validateImageData(data: Uint8Array): boolean {
|
| 1643 |
+
// Check if data is long enough to contain magic bytes
|
| 1644 |
+
if (!data || data.length < 4) {
|
| 1645 |
+
return false;
|
| 1646 |
+
}
|
| 1647 |
+
|
| 1648 |
+
// Check for JPEG magic bytes (FF D8 FF)
|
| 1649 |
+
if (data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) {
|
| 1650 |
+
return true;
|
| 1651 |
+
}
|
| 1652 |
+
|
| 1653 |
+
// Check for PNG magic bytes (89 50 4E 47)
|
| 1654 |
+
if (data[0] === 0x89 && data[1] === 0x50 && data[2] === 0x4e && data[3] === 0x47) {
|
| 1655 |
+
return true;
|
| 1656 |
+
}
|
| 1657 |
+
|
| 1658 |
+
// Check for WebP magic bytes (52 49 46 46 ... 57 45 42 50)
|
| 1659 |
+
if (
|
| 1660 |
+
data.length >= 12 &&
|
| 1661 |
+
data[0] === 0x52 &&
|
| 1662 |
+
data[1] === 0x49 &&
|
| 1663 |
+
data[2] === 0x46 &&
|
| 1664 |
+
data[3] === 0x46 &&
|
| 1665 |
+
data[8] === 0x57 &&
|
| 1666 |
+
data[9] === 0x45 &&
|
| 1667 |
+
data[10] === 0x42 &&
|
| 1668 |
+
data[11] === 0x50
|
| 1669 |
+
) {
|
| 1670 |
+
return true;
|
| 1671 |
+
}
|
| 1672 |
+
|
| 1673 |
+
return false;
|
| 1674 |
+
}
|
| 1675 |
+
|
| 1676 |
+
private detectImageFormat(data: Uint8Array): { extension: string; mimeType: string } | null {
|
| 1677 |
+
if (!data || data.length < 4) {
|
| 1678 |
+
return null;
|
| 1679 |
+
}
|
| 1680 |
+
|
| 1681 |
+
// Check for JPEG magic bytes (FF D8 FF)
|
| 1682 |
+
if (data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) {
|
| 1683 |
+
return { extension: 'jpg', mimeType: 'image/jpeg' };
|
| 1684 |
+
}
|
| 1685 |
+
|
| 1686 |
+
// Check for PNG magic bytes (89 50 4E 47)
|
| 1687 |
+
if (data[0] === 0x89 && data[1] === 0x50 && data[2] === 0x4e && data[3] === 0x47) {
|
| 1688 |
+
return { extension: 'png', mimeType: 'image/png' };
|
| 1689 |
+
}
|
| 1690 |
+
|
| 1691 |
+
// Check for WebP magic bytes (52 49 46 46 ... 57 45 42 50)
|
| 1692 |
+
if (
|
| 1693 |
+
data.length >= 12 &&
|
| 1694 |
+
data[0] === 0x52 &&
|
| 1695 |
+
data[1] === 0x49 &&
|
| 1696 |
+
data[2] === 0x46 &&
|
| 1697 |
+
data[3] === 0x46 &&
|
| 1698 |
+
data[8] === 0x57 &&
|
| 1699 |
+
data[9] === 0x45 &&
|
| 1700 |
+
data[10] === 0x42 &&
|
| 1701 |
+
data[11] === 0x50
|
| 1702 |
+
) {
|
| 1703 |
+
return { extension: 'webp', mimeType: 'image/webp' };
|
| 1704 |
+
}
|
| 1705 |
+
|
| 1706 |
+
return null;
|
| 1707 |
+
}
|
| 1708 |
+
|
| 1709 |
+
private buildMetadataEntries(lookup: TrackLookup): Array<[string, string]> {
|
| 1710 |
+
const entries: Array<[string, string]> = [];
|
| 1711 |
+
const { track } = lookup;
|
| 1712 |
+
const album = track.album;
|
| 1713 |
+
const mainArtist = formatArtistsForMetadata(track.artists);
|
| 1714 |
+
const albumArtist =
|
| 1715 |
+
album?.artist?.name ??
|
| 1716 |
+
(album?.artists && album.artists.length > 0 ? album.artists[0]?.name : undefined) ??
|
| 1717 |
+
track.artists?.[0]?.name;
|
| 1718 |
+
|
| 1719 |
+
if (track.title) entries.push(['title', track.title]);
|
| 1720 |
+
if (mainArtist) entries.push(['artist', mainArtist]);
|
| 1721 |
+
if (albumArtist) entries.push(['album_artist', albumArtist]);
|
| 1722 |
+
if (album?.title) entries.push(['album', album.title]);
|
| 1723 |
+
|
| 1724 |
+
const trackNumber = Number(track.trackNumber);
|
| 1725 |
+
const totalTracks = Number(album?.numberOfTracks);
|
| 1726 |
+
if (Number.isFinite(trackNumber) && trackNumber > 0) {
|
| 1727 |
+
const value =
|
| 1728 |
+
Number.isFinite(totalTracks) && totalTracks > 0
|
| 1729 |
+
? `${trackNumber}/${totalTracks}`
|
| 1730 |
+
: `${trackNumber}`;
|
| 1731 |
+
entries.push(['track', value]);
|
| 1732 |
+
}
|
| 1733 |
+
|
| 1734 |
+
const discNumber = Number(track.volumeNumber);
|
| 1735 |
+
const totalDiscs = Number(album?.numberOfVolumes);
|
| 1736 |
+
if (Number.isFinite(discNumber) && discNumber > 0) {
|
| 1737 |
+
const value =
|
| 1738 |
+
Number.isFinite(totalDiscs) && totalDiscs > 0
|
| 1739 |
+
? `${discNumber}/${totalDiscs}`
|
| 1740 |
+
: `${discNumber}`;
|
| 1741 |
+
entries.push(['disc', value]);
|
| 1742 |
+
}
|
| 1743 |
+
|
| 1744 |
+
const releaseDate = album?.releaseDate ?? track.streamStartDate;
|
| 1745 |
+
if (releaseDate) {
|
| 1746 |
+
const yearMatch = /^(\d{4})/.exec(releaseDate);
|
| 1747 |
+
if (yearMatch?.[1]) {
|
| 1748 |
+
entries.push(['date', yearMatch[1]]);
|
| 1749 |
+
entries.push(['year', yearMatch[1]]);
|
| 1750 |
+
}
|
| 1751 |
+
}
|
| 1752 |
+
|
| 1753 |
+
// API does not include genre
|
| 1754 |
+
/*
|
| 1755 |
+
const tags = track.mediaMetadata?.tags ?? album?.mediaMetadata?.tags;
|
| 1756 |
+
if (tags && tags.length > 0) {
|
| 1757 |
+
entries.push(['genre', tags.join('; ')]);
|
| 1758 |
+
}
|
| 1759 |
+
*/
|
| 1760 |
+
|
| 1761 |
+
if (track.isrc) {
|
| 1762 |
+
entries.push(['ISRC', track.isrc]);
|
| 1763 |
+
}
|
| 1764 |
+
|
| 1765 |
+
if (album?.copyright) {
|
| 1766 |
+
entries.push(['copyright', album.copyright]);
|
| 1767 |
+
}
|
| 1768 |
+
|
| 1769 |
+
// ReplayGain
|
| 1770 |
+
if (lookup.info) {
|
| 1771 |
+
const { trackReplayGain, trackPeakAmplitude, albumReplayGain, albumPeakAmplitude } =
|
| 1772 |
+
lookup.info;
|
| 1773 |
+
|
| 1774 |
+
if (trackReplayGain !== undefined && trackReplayGain !== null) {
|
| 1775 |
+
entries.push(['REPLAYGAIN_TRACK_GAIN', `${trackReplayGain} dB`]);
|
| 1776 |
+
}
|
| 1777 |
+
if (trackPeakAmplitude !== undefined && trackPeakAmplitude !== null) {
|
| 1778 |
+
entries.push(['REPLAYGAIN_TRACK_PEAK', `${trackPeakAmplitude}`]);
|
| 1779 |
+
}
|
| 1780 |
+
if (albumReplayGain !== undefined && albumReplayGain !== null) {
|
| 1781 |
+
entries.push(['REPLAYGAIN_ALBUM_GAIN', `${albumReplayGain} dB`]);
|
| 1782 |
+
}
|
| 1783 |
+
if (albumPeakAmplitude !== undefined && albumPeakAmplitude !== null) {
|
| 1784 |
+
entries.push(['REPLAYGAIN_ALBUM_PEAK', `${albumPeakAmplitude}`]);
|
| 1785 |
+
}
|
| 1786 |
+
} else if (track.replayGain) {
|
| 1787 |
+
entries.push(['REPLAYGAIN_TRACK_GAIN', `${track.replayGain} dB`]);
|
| 1788 |
+
if (track.peak) {
|
| 1789 |
+
entries.push(['REPLAYGAIN_TRACK_PEAK', `${track.peak}`]);
|
| 1790 |
+
}
|
| 1791 |
+
}
|
| 1792 |
+
|
| 1793 |
+
entries.push(['comment', 'Downloaded from music.binimum.org/tidal.squid.wtf']);
|
| 1794 |
+
|
| 1795 |
+
return entries;
|
| 1796 |
+
}
|
| 1797 |
+
|
| 1798 |
+
private async runMetadataEmbedding(
|
| 1799 |
+
blob: Blob,
|
| 1800 |
+
lookup: TrackLookup,
|
| 1801 |
+
filename: string,
|
| 1802 |
+
contentType: string | undefined,
|
| 1803 |
+
options: DownloadTrackOptions | undefined,
|
| 1804 |
+
quality: AudioQuality,
|
| 1805 |
+
convertToMp3: boolean
|
| 1806 |
+
): Promise<Blob | null> {
|
| 1807 |
+
if (typeof window === 'undefined') {
|
| 1808 |
+
return null;
|
| 1809 |
+
}
|
| 1810 |
+
|
| 1811 |
+
const extensionFromMime = this.inferExtensionFromMime(contentType);
|
| 1812 |
+
const extensionFromFilename = this.inferExtensionFromFilename(filename);
|
| 1813 |
+
const extension = extensionFromMime ?? extensionFromFilename;
|
| 1814 |
+
|
| 1815 |
+
if (!extension) {
|
| 1816 |
+
return null;
|
| 1817 |
+
}
|
| 1818 |
+
|
| 1819 |
+
const supportedExtensions = new Set(['flac', 'mp3', 'm4a', 'aac', 'wav', 'ogg']);
|
| 1820 |
+
if (!supportedExtensions.has(extension)) {
|
| 1821 |
+
return null;
|
| 1822 |
+
}
|
| 1823 |
+
|
| 1824 |
+
const convertibleExtensions = new Set(['m4a', 'aac', 'mp4']);
|
| 1825 |
+
const shouldConvertToMp3 = convertToMp3 && convertibleExtensions.has(extension);
|
| 1826 |
+
const outputExtension = shouldConvertToMp3 ? 'mp3' : extension;
|
| 1827 |
+
const targetBitrate = quality === 'LOW' ? '96k' : '320k';
|
| 1828 |
+
|
| 1829 |
+
let ffmpegModule: typeof import('./ffmpegClient') | null = null;
|
| 1830 |
+
try {
|
| 1831 |
+
ffmpegModule = await import('./ffmpegClient');
|
| 1832 |
+
} catch (error) {
|
| 1833 |
+
console.warn('Unable to load FFmpeg client module', error);
|
| 1834 |
+
options?.onFfmpegError?.(error);
|
| 1835 |
+
return null;
|
| 1836 |
+
}
|
| 1837 |
+
|
| 1838 |
+
if (!ffmpegModule.isFFmpegSupported()) {
|
| 1839 |
+
return null;
|
| 1840 |
+
}
|
| 1841 |
+
|
| 1842 |
+
if (options?.onFfmpegCountdown) {
|
| 1843 |
+
try {
|
| 1844 |
+
const estimatedBytes = await ffmpegModule.estimateFfmpegDownloadSize?.();
|
| 1845 |
+
options.onFfmpegCountdown({
|
| 1846 |
+
totalBytes: estimatedBytes,
|
| 1847 |
+
autoTriggered: options.ffmpegAutoTriggered ?? false
|
| 1848 |
+
});
|
| 1849 |
+
} catch (estimateError) {
|
| 1850 |
+
console.debug('Failed to estimate FFmpeg size', estimateError);
|
| 1851 |
+
options.onFfmpegCountdown({
|
| 1852 |
+
totalBytes: undefined,
|
| 1853 |
+
autoTriggered: options.ffmpegAutoTriggered ?? false
|
| 1854 |
+
});
|
| 1855 |
+
}
|
| 1856 |
+
}
|
| 1857 |
+
|
| 1858 |
+
options?.onFfmpegStart?.();
|
| 1859 |
+
|
| 1860 |
+
let ffmpeg: Awaited<ReturnType<typeof ffmpegModule.getFFmpeg>>;
|
| 1861 |
+
let progressHandler: ((data: { progress: number }) => void) | null = null;
|
| 1862 |
+
|
| 1863 |
+
try {
|
| 1864 |
+
const loadOptions: Parameters<typeof ffmpegModule.getFFmpeg>[0] = {
|
| 1865 |
+
signal: options?.signal,
|
| 1866 |
+
onProgress: ({
|
| 1867 |
+
receivedBytes,
|
| 1868 |
+
totalBytes
|
| 1869 |
+
}: {
|
| 1870 |
+
receivedBytes: number;
|
| 1871 |
+
totalBytes?: number;
|
| 1872 |
+
}) => {
|
| 1873 |
+
if (totalBytes && totalBytes > 0) {
|
| 1874 |
+
options?.onFfmpegProgress?.(Math.max(0, Math.min(1, receivedBytes / totalBytes)));
|
| 1875 |
+
} else if (receivedBytes > 0) {
|
| 1876 |
+
options?.onFfmpegProgress?.(0);
|
| 1877 |
+
}
|
| 1878 |
+
}
|
| 1879 |
+
};
|
| 1880 |
+
ffmpeg = await ffmpegModule.getFFmpeg(loadOptions);
|
| 1881 |
+
|
| 1882 |
+
// Set up progress tracking for this specific job
|
| 1883 |
+
progressHandler = ({ progress }: { progress: number }) => {
|
| 1884 |
+
if (options?.onProgress && progress >= 0) {
|
| 1885 |
+
options.onProgress({ stage: 'embedding', progress: Math.min(1, progress) });
|
| 1886 |
+
}
|
| 1887 |
+
};
|
| 1888 |
+
ffmpeg.on('progress', progressHandler);
|
| 1889 |
+
|
| 1890 |
+
options?.onFfmpegProgress?.(1);
|
| 1891 |
+
options?.onFfmpegComplete?.();
|
| 1892 |
+
} catch (loadError) {
|
| 1893 |
+
options?.onFfmpegError?.(loadError);
|
| 1894 |
+
throw loadError;
|
| 1895 |
+
}
|
| 1896 |
+
const uniqueSuffix =
|
| 1897 |
+
typeof crypto !== 'undefined' && 'randomUUID' in crypto
|
| 1898 |
+
? crypto.randomUUID()
|
| 1899 |
+
: `${Date.now()}-${Math.random().toString(16).slice(2, 10)}`;
|
| 1900 |
+
const inputName = `source-${uniqueSuffix}.${extension}`;
|
| 1901 |
+
const outputName = `output-${uniqueSuffix}.${outputExtension}`;
|
| 1902 |
+
|
| 1903 |
+
let coverWritten = false;
|
| 1904 |
+
let coverExtension = 'jpg';
|
| 1905 |
+
|
| 1906 |
+
try {
|
| 1907 |
+
if (options?.onProgress) {
|
| 1908 |
+
options.onProgress({ stage: 'embedding', progress: 0 });
|
| 1909 |
+
}
|
| 1910 |
+
|
| 1911 |
+
// Convert blob to Uint8Array to ensure proper memory handling
|
| 1912 |
+
const arrayBuffer = await blob.arrayBuffer();
|
| 1913 |
+
const uint8Array = new Uint8Array(arrayBuffer);
|
| 1914 |
+
|
| 1915 |
+
await ffmpeg.writeFile(inputName, uint8Array);
|
| 1916 |
+
|
| 1917 |
+
const artworkId = lookup.track.album?.cover;
|
| 1918 |
+
|
| 1919 |
+
if (artworkId) {
|
| 1920 |
+
// Try multiple sizes as fallback
|
| 1921 |
+
const coverSizes: Array<'1280' | '640' | '320'> = ['1280', '640', '320'];
|
| 1922 |
+
let coverFetchSuccess = false;
|
| 1923 |
+
|
| 1924 |
+
for (const size of coverSizes) {
|
| 1925 |
+
if (coverFetchSuccess) break;
|
| 1926 |
+
|
| 1927 |
+
const coverUrl = this.getCoverUrl(artworkId, size);
|
| 1928 |
+
|
| 1929 |
+
// Try two fetch strategies: with headers, then without
|
| 1930 |
+
const fetchStrategies = [
|
| 1931 |
+
{
|
| 1932 |
+
name: 'with-headers',
|
| 1933 |
+
options: {
|
| 1934 |
+
method: 'GET' as const,
|
| 1935 |
+
headers: {
|
| 1936 |
+
Accept: 'image/jpeg,image/jpg,image/png,image/*',
|
| 1937 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
| 1938 |
+
},
|
| 1939 |
+
signal: AbortSignal.timeout(10000)
|
| 1940 |
+
}
|
| 1941 |
+
},
|
| 1942 |
+
{
|
| 1943 |
+
name: 'simple',
|
| 1944 |
+
options: {
|
| 1945 |
+
method: 'GET' as const,
|
| 1946 |
+
signal: AbortSignal.timeout(10000)
|
| 1947 |
+
}
|
| 1948 |
+
}
|
| 1949 |
+
];
|
| 1950 |
+
|
| 1951 |
+
for (const strategy of fetchStrategies) {
|
| 1952 |
+
if (coverFetchSuccess) break;
|
| 1953 |
+
|
| 1954 |
+
try {
|
| 1955 |
+
const coverResponse = await fetch(coverUrl, strategy.options);
|
| 1956 |
+
|
| 1957 |
+
if (!coverResponse.ok) {
|
| 1958 |
+
continue; // Try next size
|
| 1959 |
+
}
|
| 1960 |
+
|
| 1961 |
+
const contentType = coverResponse.headers.get('Content-Type');
|
| 1962 |
+
const contentLength = coverResponse.headers.get('Content-Length');
|
| 1963 |
+
|
| 1964 |
+
// Check if Content-Length indicates empty response
|
| 1965 |
+
if (contentLength && parseInt(contentLength, 10) === 0) {
|
| 1966 |
+
continue; // Try next size
|
| 1967 |
+
}
|
| 1968 |
+
|
| 1969 |
+
if (contentType && !contentType.startsWith('image/')) {
|
| 1970 |
+
continue; // Try next size
|
| 1971 |
+
}
|
| 1972 |
+
|
| 1973 |
+
// Try arrayBuffer directly instead of blob first (more reliable)
|
| 1974 |
+
let coverArrayBuffer: ArrayBuffer;
|
| 1975 |
+
|
| 1976 |
+
try {
|
| 1977 |
+
coverArrayBuffer = await coverResponse.arrayBuffer();
|
| 1978 |
+
} catch {
|
| 1979 |
+
continue; // Try next size
|
| 1980 |
+
}
|
| 1981 |
+
|
| 1982 |
+
if (!coverArrayBuffer || coverArrayBuffer.byteLength === 0) {
|
| 1983 |
+
continue; // Try next size
|
| 1984 |
+
}
|
| 1985 |
+
|
| 1986 |
+
const coverUint8Array = new Uint8Array(coverArrayBuffer);
|
| 1987 |
+
|
| 1988 |
+
// Detect image format from magic bytes
|
| 1989 |
+
const imageFormat = this.detectImageFormat(coverUint8Array);
|
| 1990 |
+
if (!imageFormat) {
|
| 1991 |
+
continue; // Try next size
|
| 1992 |
+
}
|
| 1993 |
+
|
| 1994 |
+
coverExtension = imageFormat.extension;
|
| 1995 |
+
const finalCoverName = `cover-${uniqueSuffix}.${coverExtension}`;
|
| 1996 |
+
|
| 1997 |
+
await ffmpeg.writeFile(finalCoverName, coverUint8Array);
|
| 1998 |
+
coverWritten = true;
|
| 1999 |
+
coverFetchSuccess = true;
|
| 2000 |
+
break; // Success, exit strategy loop
|
| 2001 |
+
} catch {
|
| 2002 |
+
// Continue to next strategy
|
| 2003 |
+
}
|
| 2004 |
+
} // End strategy loop
|
| 2005 |
+
} // End size loop
|
| 2006 |
+
}
|
| 2007 |
+
|
| 2008 |
+
const args: string[] = ['-i', inputName];
|
| 2009 |
+
if (coverWritten) {
|
| 2010 |
+
const finalCoverName = `cover-${uniqueSuffix}.${coverExtension}`;
|
| 2011 |
+
args.push('-i', finalCoverName);
|
| 2012 |
+
}
|
| 2013 |
+
|
| 2014 |
+
// Map streams FIRST (matching working command pattern)
|
| 2015 |
+
// Working command: -map 0:a -map 1 -codec copy
|
| 2016 |
+
if (coverWritten) {
|
| 2017 |
+
args.push('-map', '0:a'); // Map audio stream from first input
|
| 2018 |
+
args.push('-map', '1'); // Map entire second input (cover image)
|
| 2019 |
+
} else {
|
| 2020 |
+
args.push('-map', '0:a');
|
| 2021 |
+
}
|
| 2022 |
+
|
| 2023 |
+
// Codec settings
|
| 2024 |
+
if (shouldConvertToMp3) {
|
| 2025 |
+
args.push('-codec:a', 'libmp3lame');
|
| 2026 |
+
args.push('-b:a', targetBitrate);
|
| 2027 |
+
} else {
|
| 2028 |
+
args.push('-codec', 'copy');
|
| 2029 |
+
}
|
| 2030 |
+
|
| 2031 |
+
// Track metadata (title, artist, album, etc.)
|
| 2032 |
+
for (const [key, value] of this.buildMetadataEntries(lookup)) {
|
| 2033 |
+
args.push('-metadata', `${key}=${value}`);
|
| 2034 |
+
}
|
| 2035 |
+
|
| 2036 |
+
// Cover-specific metadata and disposition (matching working command)
|
| 2037 |
+
if (coverWritten) {
|
| 2038 |
+
args.push('-metadata:s:v', 'title=Album cover');
|
| 2039 |
+
args.push('-metadata:s:v', 'comment=Cover (front)');
|
| 2040 |
+
args.push('-disposition:v', 'attached_pic');
|
| 2041 |
+
}
|
| 2042 |
+
|
| 2043 |
+
// MP3-specific settings
|
| 2044 |
+
if (shouldConvertToMp3) {
|
| 2045 |
+
args.push('-id3v2_version', '3');
|
| 2046 |
+
args.push('-write_xing', '0');
|
| 2047 |
+
}
|
| 2048 |
+
|
| 2049 |
+
args.push(outputName);
|
| 2050 |
+
|
| 2051 |
+
// Execute FFmpeg with timeout protection (3 minutes for large files)
|
| 2052 |
+
const timeoutMs = 180000; // 3 minutes
|
| 2053 |
+
const execPromise = ffmpeg.exec(args);
|
| 2054 |
+
const timeoutPromise = new Promise<never>((_, reject) => {
|
| 2055 |
+
setTimeout(() => {
|
| 2056 |
+
reject(
|
| 2057 |
+
new Error(
|
| 2058 |
+
`FFmpeg execution timeout - processing took longer than 3 minutes. Try using "Download covers separately" option instead.`
|
| 2059 |
+
)
|
| 2060 |
+
);
|
| 2061 |
+
}, timeoutMs);
|
| 2062 |
+
});
|
| 2063 |
+
|
| 2064 |
+
try {
|
| 2065 |
+
await Promise.race([execPromise, timeoutPromise]);
|
| 2066 |
+
} catch (execError) {
|
| 2067 |
+
// Check if it's a timeout
|
| 2068 |
+
const errorMessage = execError instanceof Error ? execError.message : String(execError);
|
| 2069 |
+
if (errorMessage.includes('timeout')) {
|
| 2070 |
+
throw new Error(
|
| 2071 |
+
'FFmpeg timeout: Processing took too long. Enable "Download covers separately" option for FLAC files.'
|
| 2072 |
+
);
|
| 2073 |
+
}
|
| 2074 |
+
|
| 2075 |
+
// Check if it's a memory error
|
| 2076 |
+
if (
|
| 2077 |
+
errorMessage.includes('memory access out of bounds') ||
|
| 2078 |
+
errorMessage.includes('RuntimeError') ||
|
| 2079 |
+
errorMessage.includes('out of memory')
|
| 2080 |
+
) {
|
| 2081 |
+
throw new Error(
|
| 2082 |
+
'FFmpeg memory error: File may be too large for browser processing. Try a smaller file or download without metadata embedding.'
|
| 2083 |
+
);
|
| 2084 |
+
}
|
| 2085 |
+
|
| 2086 |
+
throw execError;
|
| 2087 |
+
}
|
| 2088 |
+
|
| 2089 |
+
const outputData = await ffmpeg.readFile(outputName);
|
| 2090 |
+
if (options?.onProgress) {
|
| 2091 |
+
options.onProgress({ stage: 'embedding', progress: 1 });
|
| 2092 |
+
}
|
| 2093 |
+
let outputArray: Uint8Array;
|
| 2094 |
+
if (outputData instanceof Uint8Array) {
|
| 2095 |
+
outputArray = outputData;
|
| 2096 |
+
} else if (typeof outputData === 'string') {
|
| 2097 |
+
outputArray = new TextEncoder().encode(outputData);
|
| 2098 |
+
} else {
|
| 2099 |
+
outputArray = new Uint8Array((outputData as unknown as ArrayBuffer) ?? new ArrayBuffer(0));
|
| 2100 |
+
}
|
| 2101 |
+
const blobArray = new Uint8Array(outputArray);
|
| 2102 |
+
const mimeType = this.inferMimeFromExtension(
|
| 2103 |
+
outputExtension,
|
| 2104 |
+
contentType ?? (blob.type && blob.type.length > 0 ? blob.type : undefined)
|
| 2105 |
+
);
|
| 2106 |
+
const resultBlob = new Blob([blobArray], { type: mimeType });
|
| 2107 |
+
return resultBlob;
|
| 2108 |
+
} catch (error) {
|
| 2109 |
+
// Check if it's a memory error and provide helpful message
|
| 2110 |
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
| 2111 |
+
if (
|
| 2112 |
+
errorMessage.includes('memory access out of bounds') ||
|
| 2113 |
+
errorMessage.includes('RuntimeError') ||
|
| 2114 |
+
errorMessage.includes('out of memory') ||
|
| 2115 |
+
errorMessage.includes('memory error')
|
| 2116 |
+
) {
|
| 2117 |
+
options?.onFfmpegError?.(
|
| 2118 |
+
new Error('Memory error: File processed without metadata due to browser limitations')
|
| 2119 |
+
);
|
| 2120 |
+
} else {
|
| 2121 |
+
options?.onFfmpegError?.(error);
|
| 2122 |
+
}
|
| 2123 |
+
|
| 2124 |
+
// Return null to fallback to original blob (handled by caller)
|
| 2125 |
+
return null;
|
| 2126 |
+
} finally {
|
| 2127 |
+
// Remove progress handler
|
| 2128 |
+
if (progressHandler && ffmpeg) {
|
| 2129 |
+
ffmpeg.off('progress', progressHandler);
|
| 2130 |
+
}
|
| 2131 |
+
|
| 2132 |
+
// Clean up temporary files
|
| 2133 |
+
if (ffmpeg) {
|
| 2134 |
+
try {
|
| 2135 |
+
await ffmpeg.deleteFile(inputName);
|
| 2136 |
+
} catch (cleanupErr) {
|
| 2137 |
+
console.debug('Failed to delete FFmpeg input file', cleanupErr);
|
| 2138 |
+
}
|
| 2139 |
+
try {
|
| 2140 |
+
await ffmpeg.deleteFile(outputName);
|
| 2141 |
+
} catch (cleanupErr) {
|
| 2142 |
+
console.debug('Failed to delete FFmpeg output file', cleanupErr);
|
| 2143 |
+
}
|
| 2144 |
+
if (coverWritten) {
|
| 2145 |
+
try {
|
| 2146 |
+
const finalCoverName = `cover-${uniqueSuffix}.${coverExtension}`;
|
| 2147 |
+
await ffmpeg.deleteFile(finalCoverName);
|
| 2148 |
+
} catch (cleanupErr) {
|
| 2149 |
+
console.debug('Failed to delete FFmpeg cover file', cleanupErr);
|
| 2150 |
+
}
|
| 2151 |
+
}
|
| 2152 |
+
}
|
| 2153 |
+
}
|
| 2154 |
+
}
|
| 2155 |
+
|
| 2156 |
+
private async resolveTrackLookups(
|
| 2157 |
+
trackId: number,
|
| 2158 |
+
quality: AudioQuality
|
| 2159 |
+
): Promise<{
|
| 2160 |
+
manifestLookup: TrackLookup;
|
| 2161 |
+
metadataLookup: TrackLookup;
|
| 2162 |
+
manifestQuality: AudioQuality;
|
| 2163 |
+
}> {
|
| 2164 |
+
const manifestLookup = await this.getTrack(trackId, quality);
|
| 2165 |
+
const metadataLookup = manifestLookup;
|
| 2166 |
+
return { manifestLookup, metadataLookup, manifestQuality: quality };
|
| 2167 |
+
}
|
| 2168 |
+
|
| 2169 |
+
async getPreferredTrackMetadata(
|
| 2170 |
+
trackId: number,
|
| 2171 |
+
quality: AudioQuality = 'LOSSLESS'
|
| 2172 |
+
): Promise<TrackLookup> {
|
| 2173 |
+
const { metadataLookup } = await this.resolveTrackLookups(trackId, quality);
|
| 2174 |
+
return metadataLookup;
|
| 2175 |
+
}
|
| 2176 |
+
|
| 2177 |
+
async fetchTrackBlob(
|
| 2178 |
+
trackId: number,
|
| 2179 |
+
quality: AudioQuality = 'LOSSLESS',
|
| 2180 |
+
filename: string,
|
| 2181 |
+
options?: DownloadTrackOptions
|
| 2182 |
+
): Promise<{ blob: Blob; mimeType?: string }> {
|
| 2183 |
+
try {
|
| 2184 |
+
const {
|
| 2185 |
+
manifestLookup,
|
| 2186 |
+
metadataLookup: initialMetadataLookup,
|
| 2187 |
+
manifestQuality
|
| 2188 |
+
} = await this.resolveTrackLookups(trackId, quality);
|
| 2189 |
+
let metadataLookup = initialMetadataLookup;
|
| 2190 |
+
let response: Response | null = null;
|
| 2191 |
+
let streamUrl: string | null = null;
|
| 2192 |
+
let downloadBlob: Blob | null = null;
|
| 2193 |
+
let contentType: string | null = null;
|
| 2194 |
+
let receivedBytes = 0;
|
| 2195 |
+
let totalBytes: number | undefined;
|
| 2196 |
+
|
| 2197 |
+
streamUrl = manifestLookup.originalTrackUrl || null;
|
| 2198 |
+
if (streamUrl) {
|
| 2199 |
+
response = await fetch(streamUrl, { signal: options?.signal });
|
| 2200 |
+
if (response.status === 429) {
|
| 2201 |
+
throw new Error(RATE_LIMIT_ERROR_MESSAGE);
|
| 2202 |
+
}
|
| 2203 |
+
if (!response.ok) {
|
| 2204 |
+
console.warn('OriginalTrackUrl download failed, falling back to manifest', {
|
| 2205 |
+
status: response.status
|
| 2206 |
+
});
|
| 2207 |
+
response = null;
|
| 2208 |
+
}
|
| 2209 |
+
}
|
| 2210 |
+
|
| 2211 |
+
if (!response) {
|
| 2212 |
+
let manifestSource = manifestLookup;
|
| 2213 |
+
const decodedManifest = this.decodeBase64Manifest(manifestSource.info.manifest);
|
| 2214 |
+
|
| 2215 |
+
// For segmented DASH manifests, go directly to segment download
|
| 2216 |
+
if (this.isSegmentedDashManifest(decodedManifest)) {
|
| 2217 |
+
try {
|
| 2218 |
+
const mpdResult = await this.downloadFlacFromMpd(decodedManifest, options);
|
| 2219 |
+
if (mpdResult) {
|
| 2220 |
+
downloadBlob = mpdResult.blob;
|
| 2221 |
+
contentType = mpdResult.mimeType;
|
| 2222 |
+
receivedBytes = downloadBlob.size;
|
| 2223 |
+
totalBytes = downloadBlob.size;
|
| 2224 |
+
metadataLookup = manifestSource;
|
| 2225 |
+
}
|
| 2226 |
+
} catch (mpdError) {
|
| 2227 |
+
console.warn('Failed to download FLAC from MPD manifest', mpdError);
|
| 2228 |
+
}
|
| 2229 |
+
|
| 2230 |
+
if (!downloadBlob) {
|
| 2231 |
+
throw new Error('Could not download segmented DASH content');
|
| 2232 |
+
}
|
| 2233 |
+
} else {
|
| 2234 |
+
// Try to extract a direct stream URL
|
| 2235 |
+
let fallbackUrl = this.extractStreamUrlFromManifest(manifestSource.info.manifest);
|
| 2236 |
+
if (!fallbackUrl && manifestQuality !== 'LOSSLESS') {
|
| 2237 |
+
try {
|
| 2238 |
+
const losslessLookup = await this.getTrack(trackId, 'LOSSLESS');
|
| 2239 |
+
const candidateUrl = this.extractStreamUrlFromManifest(losslessLookup.info.manifest);
|
| 2240 |
+
if (candidateUrl) {
|
| 2241 |
+
fallbackUrl = candidateUrl;
|
| 2242 |
+
manifestSource = losslessLookup;
|
| 2243 |
+
}
|
| 2244 |
+
} catch (manifestError) {
|
| 2245 |
+
console.warn(
|
| 2246 |
+
'Failed to fetch lossless manifest for download fallback',
|
| 2247 |
+
manifestError
|
| 2248 |
+
);
|
| 2249 |
+
}
|
| 2250 |
+
}
|
| 2251 |
+
|
| 2252 |
+
if (fallbackUrl) {
|
| 2253 |
+
streamUrl = fallbackUrl;
|
| 2254 |
+
response = await fetch(fallbackUrl, { signal: options?.signal });
|
| 2255 |
+
if (response.status === 429) {
|
| 2256 |
+
throw new Error(RATE_LIMIT_ERROR_MESSAGE);
|
| 2257 |
+
}
|
| 2258 |
+
if (!response.ok) {
|
| 2259 |
+
throw new Error('Failed to fetch audio stream');
|
| 2260 |
+
}
|
| 2261 |
+
metadataLookup = manifestSource;
|
| 2262 |
+
} else {
|
| 2263 |
+
throw new Error('Could not extract stream URL from manifest');
|
| 2264 |
+
}
|
| 2265 |
+
}
|
| 2266 |
+
}
|
| 2267 |
+
|
| 2268 |
+
if (response) {
|
| 2269 |
+
const totalHeader = Number(response.headers.get('Content-Length') ?? '0');
|
| 2270 |
+
totalBytes = Number.isFinite(totalHeader) && totalHeader > 0 ? totalHeader : undefined;
|
| 2271 |
+
|
| 2272 |
+
if (!response.body) {
|
| 2273 |
+
downloadBlob = await response.blob();
|
| 2274 |
+
receivedBytes = downloadBlob.size;
|
| 2275 |
+
if (!totalBytes && receivedBytes > 0) {
|
| 2276 |
+
options?.onProgress?.({
|
| 2277 |
+
stage: 'downloading',
|
| 2278 |
+
receivedBytes,
|
| 2279 |
+
totalBytes: receivedBytes
|
| 2280 |
+
});
|
| 2281 |
+
}
|
| 2282 |
+
} else {
|
| 2283 |
+
const reader = response.body.getReader();
|
| 2284 |
+
const chunks: Uint8Array[] = [];
|
| 2285 |
+
while (true) {
|
| 2286 |
+
const { done, value } = await reader.read();
|
| 2287 |
+
if (done) break;
|
| 2288 |
+
if (value) {
|
| 2289 |
+
receivedBytes += value.byteLength;
|
| 2290 |
+
chunks.push(value);
|
| 2291 |
+
options?.onProgress?.({
|
| 2292 |
+
stage: 'downloading',
|
| 2293 |
+
receivedBytes,
|
| 2294 |
+
totalBytes
|
| 2295 |
+
});
|
| 2296 |
+
}
|
| 2297 |
+
}
|
| 2298 |
+
downloadBlob = new Blob(chunks as BlobPart[], {
|
| 2299 |
+
type: response.headers.get('Content-Type') ?? 'application/octet-stream'
|
| 2300 |
+
});
|
| 2301 |
+
if (receivedBytes === 0) {
|
| 2302 |
+
receivedBytes = downloadBlob.size;
|
| 2303 |
+
}
|
| 2304 |
+
}
|
| 2305 |
+
|
| 2306 |
+
contentType = response.headers.get('Content-Type');
|
| 2307 |
+
}
|
| 2308 |
+
|
| 2309 |
+
options?.onProgress?.({
|
| 2310 |
+
stage: 'downloading',
|
| 2311 |
+
receivedBytes,
|
| 2312 |
+
totalBytes: totalBytes ?? downloadBlob?.size
|
| 2313 |
+
});
|
| 2314 |
+
|
| 2315 |
+
if (!downloadBlob) {
|
| 2316 |
+
throw new Error('Download failed to produce audio payload');
|
| 2317 |
+
}
|
| 2318 |
+
|
| 2319 |
+
const shouldConvertToMp3 =
|
| 2320 |
+
options?.convertAacToMp3 === true && (quality === 'HIGH' || quality === 'LOW');
|
| 2321 |
+
const processedBlob = await this.embedMetadataIntoBlob(
|
| 2322 |
+
downloadBlob,
|
| 2323 |
+
metadataLookup,
|
| 2324 |
+
filename,
|
| 2325 |
+
contentType,
|
| 2326 |
+
options,
|
| 2327 |
+
quality,
|
| 2328 |
+
shouldConvertToMp3
|
| 2329 |
+
);
|
| 2330 |
+
const finalBlob = processedBlob ?? downloadBlob;
|
| 2331 |
+
return { blob: finalBlob, mimeType: contentType ?? undefined };
|
| 2332 |
+
} catch (error) {
|
| 2333 |
+
if (error instanceof DOMException && error.name === 'AbortError') {
|
| 2334 |
+
throw error;
|
| 2335 |
+
}
|
| 2336 |
+
if (error instanceof Error && error.message === RATE_LIMIT_ERROR_MESSAGE) {
|
| 2337 |
+
throw error;
|
| 2338 |
+
}
|
| 2339 |
+
throw new Error(
|
| 2340 |
+
'Download failed. The stream URL may require a proxy. Please try streaming instead.'
|
| 2341 |
+
);
|
| 2342 |
+
}
|
| 2343 |
+
}
|
| 2344 |
+
|
| 2345 |
+
async getTrackStreamUrl(trackId: number, quality: AudioQuality = 'LOSSLESS'): Promise<string> {
|
| 2346 |
+
if (this.isHiResQuality(quality)) {
|
| 2347 |
+
quality = 'LOSSLESS';
|
| 2348 |
+
}
|
| 2349 |
+
|
| 2350 |
+
const lookup = await this.getTrack(trackId, quality);
|
| 2351 |
+
if (lookup.originalTrackUrl) {
|
| 2352 |
+
return lookup.originalTrackUrl;
|
| 2353 |
+
}
|
| 2354 |
+
const fallback = this.extractStreamUrlFromManifest(lookup.info.manifest);
|
| 2355 |
+
if (!fallback) {
|
| 2356 |
+
throw new Error('Could not resolve stream URL for track');
|
| 2357 |
+
}
|
| 2358 |
+
return fallback;
|
| 2359 |
+
}
|
| 2360 |
+
|
| 2361 |
+
/**
|
| 2362 |
+
* Download a track
|
| 2363 |
+
* Fetches the audio stream and triggers a download
|
| 2364 |
+
*/
|
| 2365 |
+
async downloadTrack(
|
| 2366 |
+
trackId: number,
|
| 2367 |
+
quality: AudioQuality = 'LOSSLESS',
|
| 2368 |
+
filename: string,
|
| 2369 |
+
options?: DownloadTrackOptions
|
| 2370 |
+
): Promise<void> {
|
| 2371 |
+
try {
|
| 2372 |
+
const { blob } = await this.fetchTrackBlob(trackId, quality, filename, options);
|
| 2373 |
+
const url = URL.createObjectURL(blob);
|
| 2374 |
+
|
| 2375 |
+
// Trigger download
|
| 2376 |
+
const a = document.createElement('a');
|
| 2377 |
+
a.href = url;
|
| 2378 |
+
a.download = filename;
|
| 2379 |
+
document.body.appendChild(a);
|
| 2380 |
+
a.click();
|
| 2381 |
+
document.body.removeChild(a);
|
| 2382 |
+
URL.revokeObjectURL(url);
|
| 2383 |
+
|
| 2384 |
+
// Download cover separately if enabled
|
| 2385 |
+
if (options?.downloadCoverSeperately) {
|
| 2386 |
+
try {
|
| 2387 |
+
const metadata = await this.getPreferredTrackMetadata(trackId, quality);
|
| 2388 |
+
const coverId = metadata.track.album?.cover;
|
| 2389 |
+
if (coverId) {
|
| 2390 |
+
console.log('[Cover Download] Fetching cover for separate download...');
|
| 2391 |
+
|
| 2392 |
+
// Try multiple sizes as fallback
|
| 2393 |
+
const coverSizes: Array<'1280' | '640' | '320'> = ['1280', '640', '320'];
|
| 2394 |
+
let coverDownloadSuccess = false;
|
| 2395 |
+
|
| 2396 |
+
for (const size of coverSizes) {
|
| 2397 |
+
if (coverDownloadSuccess) break;
|
| 2398 |
+
|
| 2399 |
+
const coverUrl = this.getCoverUrl(coverId, size);
|
| 2400 |
+
console.log(`[Cover Download] Attempting size ${size}:`, coverUrl);
|
| 2401 |
+
|
| 2402 |
+
// Try two fetch strategies: with headers, then without
|
| 2403 |
+
const fetchStrategies = [
|
| 2404 |
+
{
|
| 2405 |
+
name: 'with-headers',
|
| 2406 |
+
options: {
|
| 2407 |
+
method: 'GET' as const,
|
| 2408 |
+
headers: {
|
| 2409 |
+
Accept: 'image/jpeg,image/jpg,image/png,image/*',
|
| 2410 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
| 2411 |
+
},
|
| 2412 |
+
signal: AbortSignal.timeout(10000)
|
| 2413 |
+
}
|
| 2414 |
+
},
|
| 2415 |
+
{
|
| 2416 |
+
name: 'simple',
|
| 2417 |
+
options: {
|
| 2418 |
+
method: 'GET' as const,
|
| 2419 |
+
signal: AbortSignal.timeout(10000)
|
| 2420 |
+
}
|
| 2421 |
+
}
|
| 2422 |
+
];
|
| 2423 |
+
|
| 2424 |
+
for (const strategy of fetchStrategies) {
|
| 2425 |
+
if (coverDownloadSuccess) break;
|
| 2426 |
+
|
| 2427 |
+
console.log(`[Cover Download] Trying strategy: ${strategy.name}`);
|
| 2428 |
+
|
| 2429 |
+
try {
|
| 2430 |
+
const coverResponse = await fetch(coverUrl, strategy.options);
|
| 2431 |
+
|
| 2432 |
+
console.log(
|
| 2433 |
+
`[Cover Download] Response status: ${coverResponse.status}, Content-Length: ${coverResponse.headers.get('Content-Length')}`
|
| 2434 |
+
);
|
| 2435 |
+
|
| 2436 |
+
if (!coverResponse.ok) {
|
| 2437 |
+
console.warn(
|
| 2438 |
+
`[Cover Download] Failed with status ${coverResponse.status} for size ${size}`
|
| 2439 |
+
);
|
| 2440 |
+
continue;
|
| 2441 |
+
}
|
| 2442 |
+
|
| 2443 |
+
const contentType = coverResponse.headers.get('Content-Type');
|
| 2444 |
+
const contentLength = coverResponse.headers.get('Content-Length');
|
| 2445 |
+
|
| 2446 |
+
if (contentLength && parseInt(contentLength, 10) === 0) {
|
| 2447 |
+
console.warn(`[Cover Download] Content-Length is 0 for size ${size}`);
|
| 2448 |
+
continue;
|
| 2449 |
+
}
|
| 2450 |
+
|
| 2451 |
+
if (contentType && !contentType.startsWith('image/')) {
|
| 2452 |
+
console.warn(`[Cover Download] Invalid content type: ${contentType}`);
|
| 2453 |
+
continue;
|
| 2454 |
+
}
|
| 2455 |
+
|
| 2456 |
+
// Use arrayBuffer directly for more reliable data retrieval
|
| 2457 |
+
const arrayBuffer = await coverResponse.arrayBuffer();
|
| 2458 |
+
|
| 2459 |
+
if (!arrayBuffer || arrayBuffer.byteLength === 0) {
|
| 2460 |
+
console.warn(`[Cover Download] Empty array buffer for size ${size}`);
|
| 2461 |
+
continue;
|
| 2462 |
+
}
|
| 2463 |
+
|
| 2464 |
+
const uint8Array = new Uint8Array(arrayBuffer);
|
| 2465 |
+
console.log(`[Cover Download] Received ${uint8Array.length} bytes`);
|
| 2466 |
+
console.log(
|
| 2467 |
+
`[Cover Download] First 16 bytes:`,
|
| 2468 |
+
Array.from(uint8Array.slice(0, 16))
|
| 2469 |
+
.map((b) => b.toString(16).padStart(2, '0'))
|
| 2470 |
+
.join(' ')
|
| 2471 |
+
);
|
| 2472 |
+
|
| 2473 |
+
// Validate image data
|
| 2474 |
+
if (!this.validateImageData(uint8Array)) {
|
| 2475 |
+
console.warn(`[Cover Download] Invalid image data for size ${size}`);
|
| 2476 |
+
continue;
|
| 2477 |
+
}
|
| 2478 |
+
|
| 2479 |
+
// Detect image format
|
| 2480 |
+
const imageFormat = this.detectImageFormat(uint8Array);
|
| 2481 |
+
if (!imageFormat) {
|
| 2482 |
+
console.warn(`[Cover Download] Unknown image format for size ${size}`);
|
| 2483 |
+
continue;
|
| 2484 |
+
}
|
| 2485 |
+
|
| 2486 |
+
// Create blob with correct MIME type
|
| 2487 |
+
const coverBlob = new Blob([uint8Array], { type: imageFormat.mimeType });
|
| 2488 |
+
|
| 2489 |
+
const coverObjectUrl = URL.createObjectURL(coverBlob);
|
| 2490 |
+
const coverLink = document.createElement('a');
|
| 2491 |
+
coverLink.href = coverObjectUrl;
|
| 2492 |
+
coverLink.download = `cover.${imageFormat.extension}`;
|
| 2493 |
+
document.body.appendChild(coverLink);
|
| 2494 |
+
coverLink.click();
|
| 2495 |
+
document.body.removeChild(coverLink);
|
| 2496 |
+
URL.revokeObjectURL(coverObjectUrl);
|
| 2497 |
+
|
| 2498 |
+
coverDownloadSuccess = true;
|
| 2499 |
+
console.log(
|
| 2500 |
+
`[Cover Download] Successfully downloaded (${size}x${size}, format: ${imageFormat.extension}, strategy: ${strategy.name})`
|
| 2501 |
+
);
|
| 2502 |
+
break;
|
| 2503 |
+
} catch (sizeError) {
|
| 2504 |
+
console.warn(
|
| 2505 |
+
`[Cover Download] Failed at size ${size} with strategy ${strategy.name}:`,
|
| 2506 |
+
sizeError
|
| 2507 |
+
);
|
| 2508 |
+
}
|
| 2509 |
+
} // End strategy loop
|
| 2510 |
+
} // End size loop
|
| 2511 |
+
|
| 2512 |
+
if (!coverDownloadSuccess) {
|
| 2513 |
+
console.warn('[Cover Download] All attempts failed');
|
| 2514 |
+
}
|
| 2515 |
+
}
|
| 2516 |
+
} catch (coverError) {
|
| 2517 |
+
console.warn('Failed to download cover separately:', coverError);
|
| 2518 |
+
}
|
| 2519 |
+
}
|
| 2520 |
+
} catch (error) {
|
| 2521 |
+
if (error instanceof DOMException && error.name === 'AbortError') {
|
| 2522 |
+
throw error;
|
| 2523 |
+
}
|
| 2524 |
+
console.error('Download failed:', error);
|
| 2525 |
+
if (error instanceof Error && error.message === RATE_LIMIT_ERROR_MESSAGE) {
|
| 2526 |
+
throw error;
|
| 2527 |
+
}
|
| 2528 |
+
throw new Error(
|
| 2529 |
+
'Download failed. The stream URL may require a proxy. Please try streaming instead.'
|
| 2530 |
+
);
|
| 2531 |
+
}
|
| 2532 |
+
}
|
| 2533 |
+
|
| 2534 |
+
/**
|
| 2535 |
+
* Format duration from seconds to MM:SS
|
| 2536 |
+
*/
|
| 2537 |
+
formatDuration(seconds: number): string {
|
| 2538 |
+
const mins = Math.floor(seconds / 60);
|
| 2539 |
+
const secs = seconds % 60;
|
| 2540 |
+
return `${mins}:${secs.toString().padStart(2, '0')}`;
|
| 2541 |
+
}
|
| 2542 |
+
|
| 2543 |
+
/**
|
| 2544 |
+
* Get cover URL
|
| 2545 |
+
*/
|
| 2546 |
+
getCoverUrl(coverId: string, size: '1280' | '640' | '320' | '160' | '80' = '640'): string {
|
| 2547 |
+
return `https://resources.tidal.com/images/${coverId.replace(/-/g, '/')}/${size}x${size}.jpg`;
|
| 2548 |
+
}
|
| 2549 |
+
|
| 2550 |
+
/**
|
| 2551 |
+
* Get video cover URL
|
| 2552 |
+
*/
|
| 2553 |
+
getVideoCoverUrl(
|
| 2554 |
+
videoCoverId: string,
|
| 2555 |
+
size: '1280' | '640' | '320' | '160' | '80' = '640'
|
| 2556 |
+
): string {
|
| 2557 |
+
return `https://resources.tidal.com/videos/${videoCoverId.replace(/-/g, '/')}/${size}x${size}.mp4`;
|
| 2558 |
+
}
|
| 2559 |
+
|
| 2560 |
+
/**
|
| 2561 |
+
* Get artist picture URL
|
| 2562 |
+
*/
|
| 2563 |
+
getArtistPictureUrl(pictureId: string, size: '750' = '750'): string {
|
| 2564 |
+
return `https://resources.tidal.com/images/${pictureId.replace(/-/g, '/')}/${size}x${size}.jpg`;
|
| 2565 |
+
}
|
| 2566 |
+
}
|
| 2567 |
+
|
| 2568 |
+
export const losslessAPI = new LosslessAPI();
|
src/lib/assets/favicon.svg
ADDED
|
|
src/lib/components/AudioPlayer.svelte
ADDED
|
@@ -0,0 +1,1975 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<script lang="ts">
|
| 2 |
+
import { onMount } from 'svelte';
|
| 3 |
+
import { get } from 'svelte/store';
|
| 4 |
+
import { playerStore } from '$lib/stores/player';
|
| 5 |
+
import { lyricsStore } from '$lib/stores/lyrics';
|
| 6 |
+
import { losslessAPI, DASH_MANIFEST_UNAVAILABLE_CODE, type TrackDownloadProgress } from '$lib/api';
|
| 7 |
+
import type { DashManifestResult, DashManifestWithMetadata } from '$lib/api';
|
| 8 |
+
import { getProxiedUrl } from '$lib/config';
|
| 9 |
+
import { downloadUiStore, ffmpegBanner, activeTrackDownloads } from '$lib/stores/downloadUi';
|
| 10 |
+
import { userPreferencesStore } from '$lib/stores/userPreferences';
|
| 11 |
+
import { sanitizeForFilename, getExtensionForQuality, buildTrackFilename } from '$lib/downloads';
|
| 12 |
+
import { formatArtists } from '$lib/utils';
|
| 13 |
+
import { deriveTrackQuality } from '$lib/utils/audioQuality';
|
| 14 |
+
import type { Track, AudioQuality, SonglinkTrack, PlayableTrack } from '$lib/types';
|
| 15 |
+
import { isSonglinkTrack } from '$lib/types';
|
| 16 |
+
import { convertToTidal, extractTidalInfo } from '$lib/utils/songlink';
|
| 17 |
+
import { slide } from 'svelte/transition';
|
| 18 |
+
import { cubicOut } from 'svelte/easing';
|
| 19 |
+
import {
|
| 20 |
+
Play,
|
| 21 |
+
Pause,
|
| 22 |
+
SkipForward,
|
| 23 |
+
SkipBack,
|
| 24 |
+
Volume2,
|
| 25 |
+
VolumeX,
|
| 26 |
+
ListMusic,
|
| 27 |
+
Trash2,
|
| 28 |
+
X,
|
| 29 |
+
Shuffle,
|
| 30 |
+
ScrollText,
|
| 31 |
+
Download,
|
| 32 |
+
LoaderCircle
|
| 33 |
+
} from 'lucide-svelte';
|
| 34 |
+
|
| 35 |
+
type ShakaPlayerInstance = {
|
| 36 |
+
load: (uri: string) => Promise<void>;
|
| 37 |
+
unload: () => Promise<void>;
|
| 38 |
+
destroy: () => Promise<void>;
|
| 39 |
+
getNetworkingEngine?: () => {
|
| 40 |
+
registerRequestFilter: (
|
| 41 |
+
callback: (type: unknown, request: { method: string; uris: string[] }) => void
|
| 42 |
+
) => void;
|
| 43 |
+
};
|
| 44 |
+
};
|
| 45 |
+
|
| 46 |
+
type ShakaNamespace = {
|
| 47 |
+
Player: new (mediaElement: HTMLMediaElement) => ShakaPlayerInstance;
|
| 48 |
+
polyfill?: {
|
| 49 |
+
installAll?: () => void;
|
| 50 |
+
};
|
| 51 |
+
};
|
| 52 |
+
|
| 53 |
+
type ShakaModule = { default: ShakaNamespace };
|
| 54 |
+
|
| 55 |
+
let audioElement: HTMLAudioElement;
|
| 56 |
+
let streamUrl = $state('');
|
| 57 |
+
let isMuted = $state(false);
|
| 58 |
+
let previousVolume = 0.8;
|
| 59 |
+
let currentTrackId: number | null = null;
|
| 60 |
+
let loadSequence = 0;
|
| 61 |
+
let bufferedPercent = $state(0);
|
| 62 |
+
let lastQualityTrackId: number | string | null = null;
|
| 63 |
+
let lastQualityForTrack: AudioQuality | null = null;
|
| 64 |
+
let currentPlaybackQuality = $state<AudioQuality | null>(null);
|
| 65 |
+
let isDownloadingCurrentTrack = $state(false);
|
| 66 |
+
let downloadTaskIdForCurrentTrack: string | null = null;
|
| 67 |
+
const { onHeightChange = () => {}, headless = false } = $props<{ onHeightChange?: (height: number) => void, headless?: boolean }>();
|
| 68 |
+
|
| 69 |
+
let containerElement: HTMLDivElement | null = null;
|
| 70 |
+
let resizeObserver: ResizeObserver | null = null;
|
| 71 |
+
let showQueuePanel = $state(false);
|
| 72 |
+
const streamCache = new Map<
|
| 73 |
+
string,
|
| 74 |
+
{ url: string; replayGain: number | null; sampleRate: number | null; bitDepth: number | null }
|
| 75 |
+
>();
|
| 76 |
+
let preloadingCacheKey: string | null = null;
|
| 77 |
+
const PRELOAD_THRESHOLD_SECONDS = 12;
|
| 78 |
+
const hiResQualities = new Set<AudioQuality>(['HI_RES_LOSSLESS']);
|
| 79 |
+
const dashManifestCache = new Map<string, DashManifestWithMetadata>();
|
| 80 |
+
let shakaNamespace: ShakaNamespace | null = null;
|
| 81 |
+
let shakaPlayer: ShakaPlayerInstance | null = null;
|
| 82 |
+
let hiResObjectUrl: string | null = null;
|
| 83 |
+
let shakaNetworkingConfigured = false;
|
| 84 |
+
const sampleRateLabel = $derived(formatSampleRate($playerStore.sampleRate));
|
| 85 |
+
const bitDepthLabel = $derived(formatBitDepth($playerStore.bitDepth));
|
| 86 |
+
const isFirefox = typeof navigator !== 'undefined' && /firefox/i.test(navigator.userAgent);
|
| 87 |
+
let dashPlaybackActive = false;
|
| 88 |
+
let dashFallbackAttemptedTrackId: number | string | null = null;
|
| 89 |
+
let dashFallbackInFlight = false;
|
| 90 |
+
|
| 91 |
+
const canUseMediaSession = typeof navigator !== 'undefined' && 'mediaSession' in navigator;
|
| 92 |
+
let mediaSessionTrackId: number | string | null = null;
|
| 93 |
+
let cleanupMediaSessionHandlers: (() => void) | null = null;
|
| 94 |
+
let lastKnownPlaybackState: 'none' | 'paused' | 'playing' = 'none';
|
| 95 |
+
let isSeeking = false;
|
| 96 |
+
let seekBarElement = $state<HTMLButtonElement | null>(null);
|
| 97 |
+
|
| 98 |
+
function getCacheKey(trackId: number, quality: AudioQuality) {
|
| 99 |
+
return `${trackId}:${quality}`;
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
function isHiResQuality(quality: AudioQuality | undefined): boolean {
|
| 103 |
+
return quality ? hiResQualities.has(quality) : false;
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
function revokeHiResObjectUrl() {
|
| 107 |
+
if (hiResObjectUrl) {
|
| 108 |
+
URL.revokeObjectURL(hiResObjectUrl);
|
| 109 |
+
hiResObjectUrl = null;
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
async function destroyShakaPlayer() {
|
| 114 |
+
revokeHiResObjectUrl();
|
| 115 |
+
if (shakaPlayer) {
|
| 116 |
+
try {
|
| 117 |
+
await shakaPlayer.destroy();
|
| 118 |
+
} catch (error) {
|
| 119 |
+
console.debug('Failed to destroy Shaka player', error);
|
| 120 |
+
}
|
| 121 |
+
shakaPlayer = null;
|
| 122 |
+
}
|
| 123 |
+
shakaNetworkingConfigured = false;
|
| 124 |
+
dashPlaybackActive = false;
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
async function ensureShakaPlayer(): Promise<ShakaPlayerInstance> {
|
| 128 |
+
if (!audioElement) {
|
| 129 |
+
throw new Error('Audio element not ready for Shaka initialization');
|
| 130 |
+
}
|
| 131 |
+
if (!shakaNamespace) {
|
| 132 |
+
// @ts-expect-error Shaka Player's compiled bundle does not expose module typings.
|
| 133 |
+
const module = await import('shaka-player/dist/shaka-player.compiled.js');
|
| 134 |
+
const resolved =
|
| 135 |
+
(module as ShakaModule | { default: ShakaNamespace }).default ??
|
| 136 |
+
(module as unknown as ShakaNamespace);
|
| 137 |
+
shakaNamespace = resolved;
|
| 138 |
+
if (shakaNamespace?.polyfill?.installAll) {
|
| 139 |
+
try {
|
| 140 |
+
shakaNamespace.polyfill.installAll();
|
| 141 |
+
} catch (error) {
|
| 142 |
+
console.debug('Shaka polyfill installation failed', error);
|
| 143 |
+
}
|
| 144 |
+
}
|
| 145 |
+
}
|
| 146 |
+
if (!shakaNamespace) {
|
| 147 |
+
throw new Error('Shaka namespace unavailable');
|
| 148 |
+
}
|
| 149 |
+
if (!shakaPlayer) {
|
| 150 |
+
shakaPlayer = new shakaNamespace.Player(audioElement);
|
| 151 |
+
const networking = shakaPlayer.getNetworkingEngine?.();
|
| 152 |
+
if (networking && !shakaNetworkingConfigured) {
|
| 153 |
+
networking.registerRequestFilter((type, request) => {
|
| 154 |
+
if (request.method === 'HEAD') {
|
| 155 |
+
request.method = 'GET';
|
| 156 |
+
}
|
| 157 |
+
if (Array.isArray(request.uris)) {
|
| 158 |
+
request.uris = request.uris.map((uri) => getProxiedUrl(uri));
|
| 159 |
+
}
|
| 160 |
+
});
|
| 161 |
+
shakaNetworkingConfigured = true;
|
| 162 |
+
}
|
| 163 |
+
}
|
| 164 |
+
audioElement.crossOrigin = 'anonymous';
|
| 165 |
+
return shakaPlayer!;
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
function pruneDashManifestCache() {
|
| 169 |
+
const keepKeys = new Set<string>();
|
| 170 |
+
const dashQuality: AudioQuality = 'HI_RES_LOSSLESS';
|
| 171 |
+
const current = $playerStore.currentTrack;
|
| 172 |
+
if (current && !isSonglinkTrack(current)) {
|
| 173 |
+
keepKeys.add(getCacheKey(current.id, dashQuality));
|
| 174 |
+
}
|
| 175 |
+
const { queue, queueIndex } = $playerStore;
|
| 176 |
+
const nextTrack = queue[queueIndex + 1];
|
| 177 |
+
if (nextTrack && !isSonglinkTrack(nextTrack)) {
|
| 178 |
+
keepKeys.add(getCacheKey(nextTrack.id, dashQuality));
|
| 179 |
+
}
|
| 180 |
+
for (const key of dashManifestCache.keys()) {
|
| 181 |
+
if (!keepKeys.has(key)) {
|
| 182 |
+
dashManifestCache.delete(key);
|
| 183 |
+
}
|
| 184 |
+
}
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
function cacheFlacFallback(trackId: number, result: DashManifestResult | DashManifestWithMetadata) {
|
| 188 |
+
const manifestResult = 'result' in result ? result.result : result;
|
| 189 |
+
const trackInfo = 'trackInfo' in result ? result.trackInfo : null;
|
| 190 |
+
|
| 191 |
+
if (manifestResult.kind !== 'flac') {
|
| 192 |
+
return;
|
| 193 |
+
}
|
| 194 |
+
const fallbackUrl = manifestResult.urls.find(
|
| 195 |
+
(candidate) => typeof candidate === 'string' && candidate.length > 0
|
| 196 |
+
);
|
| 197 |
+
if (!fallbackUrl) {
|
| 198 |
+
return;
|
| 199 |
+
}
|
| 200 |
+
const proxied = getProxiedUrl(fallbackUrl);
|
| 201 |
+
streamCache.set(getCacheKey(trackId, 'LOSSLESS'), {
|
| 202 |
+
url: proxied,
|
| 203 |
+
replayGain: trackInfo?.replayGain ?? null,
|
| 204 |
+
sampleRate: trackInfo?.sampleRate ?? null,
|
| 205 |
+
bitDepth: trackInfo?.bitDepth ?? null
|
| 206 |
+
});
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
async function resolveStream(
|
| 210 |
+
track: Track,
|
| 211 |
+
overrideQuality?: AudioQuality
|
| 212 |
+
): Promise<{
|
| 213 |
+
url: string;
|
| 214 |
+
replayGain: number | null;
|
| 215 |
+
sampleRate: number | null;
|
| 216 |
+
bitDepth: number | null;
|
| 217 |
+
}> {
|
| 218 |
+
const quality = overrideQuality ?? $playerStore.quality;
|
| 219 |
+
if (isHiResQuality(quality)) {
|
| 220 |
+
throw new Error('Attempted to resolve hi-res stream via standard resolver');
|
| 221 |
+
}
|
| 222 |
+
const cacheKey = getCacheKey(track.id, quality);
|
| 223 |
+
const cached = streamCache.get(cacheKey);
|
| 224 |
+
if (cached) {
|
| 225 |
+
return cached;
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
const data = await losslessAPI.getStreamData(track.id, quality);
|
| 229 |
+
const proxied = getProxiedUrl(data.url);
|
| 230 |
+
const entry = {
|
| 231 |
+
url: proxied,
|
| 232 |
+
replayGain: data.replayGain,
|
| 233 |
+
sampleRate: data.sampleRate,
|
| 234 |
+
bitDepth: data.bitDepth
|
| 235 |
+
};
|
| 236 |
+
streamCache.set(cacheKey, entry);
|
| 237 |
+
return entry;
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
function pruneStreamCache() {
|
| 241 |
+
const quality = $playerStore.quality;
|
| 242 |
+
const keepKeys = new Set<string>();
|
| 243 |
+
const baseQualities: AudioQuality[] = isHiResQuality(quality) ? ['LOSSLESS'] : [quality];
|
| 244 |
+
const current = $playerStore.currentTrack;
|
| 245 |
+
if (current && !isSonglinkTrack(current)) {
|
| 246 |
+
for (const base of baseQualities) {
|
| 247 |
+
keepKeys.add(getCacheKey(current.id, base));
|
| 248 |
+
}
|
| 249 |
+
}
|
| 250 |
+
const { queue, queueIndex } = $playerStore;
|
| 251 |
+
const nextTrack = queue[queueIndex + 1];
|
| 252 |
+
if (nextTrack && !isSonglinkTrack(nextTrack)) {
|
| 253 |
+
for (const base of baseQualities) {
|
| 254 |
+
keepKeys.add(getCacheKey(nextTrack.id, base));
|
| 255 |
+
}
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
for (const key of streamCache.keys()) {
|
| 259 |
+
if (!keepKeys.has(key)) {
|
| 260 |
+
streamCache.delete(key);
|
| 261 |
+
}
|
| 262 |
+
}
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
async function preloadDashManifest(track: Track) {
|
| 266 |
+
const cacheKey = getCacheKey(track.id, 'HI_RES_LOSSLESS');
|
| 267 |
+
if (dashManifestCache.has(cacheKey) || preloadingCacheKey === cacheKey) {
|
| 268 |
+
const cached = dashManifestCache.get(cacheKey);
|
| 269 |
+
if (cached) {
|
| 270 |
+
cacheFlacFallback(track.id, cached.result);
|
| 271 |
+
}
|
| 272 |
+
return;
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
preloadingCacheKey = cacheKey;
|
| 276 |
+
try {
|
| 277 |
+
const result = await losslessAPI.getDashManifestWithMetadata(track.id, 'HI_RES_LOSSLESS');
|
| 278 |
+
dashManifestCache.set(cacheKey, result);
|
| 279 |
+
cacheFlacFallback(track.id, result.result);
|
| 280 |
+
pruneDashManifestCache();
|
| 281 |
+
} catch (error) {
|
| 282 |
+
console.warn('Failed to preload dash manifest:', error);
|
| 283 |
+
} finally {
|
| 284 |
+
if (preloadingCacheKey === cacheKey) {
|
| 285 |
+
preloadingCacheKey = null;
|
| 286 |
+
}
|
| 287 |
+
}
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
async function preloadNextTrack(track: Track) {
|
| 291 |
+
const cacheKey = getCacheKey(track.id, 'HI_RES_LOSSLESS');
|
| 292 |
+
if (dashManifestCache.has(cacheKey) || preloadingCacheKey === cacheKey) {
|
| 293 |
+
return;
|
| 294 |
+
}
|
| 295 |
+
await preloadDashManifest(track);
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
/**
|
| 299 |
+
* Convert a SonglinkTrack to a full TIDAL Track
|
| 300 |
+
* This is called when a Songlink track is about to be played
|
| 301 |
+
*/
|
| 302 |
+
async function convertSonglinkTrackToTidal(songlinkTrack: SonglinkTrack): Promise<Track> {
|
| 303 |
+
console.log('Converting SonglinkTrack to TIDAL:', songlinkTrack.title);
|
| 304 |
+
|
| 305 |
+
// Optimization: Use pre-calculated tidalId if available
|
| 306 |
+
if (songlinkTrack.tidalId) {
|
| 307 |
+
try {
|
| 308 |
+
const trackLookup = await losslessAPI.getTrack(songlinkTrack.tidalId);
|
| 309 |
+
if (trackLookup?.track) {
|
| 310 |
+
return trackLookup.track;
|
| 311 |
+
}
|
| 312 |
+
} catch (e) {
|
| 313 |
+
console.warn('Failed to fetch track using pre-calculated tidalId, falling back to extraction', e);
|
| 314 |
+
}
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
// Use the stored Songlink data to find the TIDAL URL
|
| 318 |
+
const tidalInfo = extractTidalInfo(songlinkTrack.songlinkData);
|
| 319 |
+
|
| 320 |
+
if (!tidalInfo || tidalInfo.type !== 'track') {
|
| 321 |
+
// Fallback: try converting from the source URL
|
| 322 |
+
console.warn('No TIDAL track in Songlink data, attempting conversion...');
|
| 323 |
+
const fallbackTidalInfo = await convertToTidal(songlinkTrack.sourceUrl, {
|
| 324 |
+
userCountry: 'US',
|
| 325 |
+
songIfSingle: true
|
| 326 |
+
});
|
| 327 |
+
|
| 328 |
+
if (!fallbackTidalInfo || fallbackTidalInfo.type !== 'track') {
|
| 329 |
+
throw new Error(`Could not find TIDAL equivalent for: ${songlinkTrack.title}`);
|
| 330 |
+
}
|
| 331 |
+
|
| 332 |
+
// Validate that the ID is numeric (TIDAL tracks have numeric IDs)
|
| 333 |
+
const trackId = Number(fallbackTidalInfo.id);
|
| 334 |
+
if (!Number.isFinite(trackId) || trackId <= 0) {
|
| 335 |
+
throw new Error(`Invalid TIDAL track ID for: ${songlinkTrack.title} (got: ${fallbackTidalInfo.id})`);
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
const trackLookup = await losslessAPI.getTrack(trackId);
|
| 339 |
+
if (!trackLookup?.track) {
|
| 340 |
+
throw new Error(`Failed to fetch TIDAL track for: ${songlinkTrack.title}`);
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
return trackLookup.track;
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
// Validate that we have a numeric TIDAL ID
|
| 347 |
+
const trackId = Number(tidalInfo.id);
|
| 348 |
+
if (!Number.isFinite(trackId) || trackId <= 0) {
|
| 349 |
+
// The ID is not numeric, try fallback conversion
|
| 350 |
+
console.warn(`Non-numeric TIDAL ID (${tidalInfo.id}), attempting fallback conversion...`);
|
| 351 |
+
const fallbackTidalInfo = await convertToTidal(songlinkTrack.sourceUrl, {
|
| 352 |
+
userCountry: 'US',
|
| 353 |
+
songIfSingle: true
|
| 354 |
+
});
|
| 355 |
+
|
| 356 |
+
if (!fallbackTidalInfo || fallbackTidalInfo.type !== 'track') {
|
| 357 |
+
throw new Error(`Could not find TIDAL equivalent for: ${songlinkTrack.title}`);
|
| 358 |
+
}
|
| 359 |
+
|
| 360 |
+
const fallbackId = Number(fallbackTidalInfo.id);
|
| 361 |
+
if (!Number.isFinite(fallbackId) || fallbackId <= 0) {
|
| 362 |
+
throw new Error(`No valid TIDAL track found for: ${songlinkTrack.title}`);
|
| 363 |
+
}
|
| 364 |
+
|
| 365 |
+
const trackLookup = await losslessAPI.getTrack(fallbackId);
|
| 366 |
+
if (!trackLookup?.track) {
|
| 367 |
+
throw new Error(`Failed to fetch TIDAL track for: ${songlinkTrack.title}`);
|
| 368 |
+
}
|
| 369 |
+
|
| 370 |
+
return trackLookup.track;
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
// We found TIDAL info in the Songlink data, fetch the full track
|
| 374 |
+
const trackLookup = await losslessAPI.getTrack(trackId);
|
| 375 |
+
if (!trackLookup?.track) {
|
| 376 |
+
throw new Error(`Failed to fetch TIDAL track for: ${songlinkTrack.title}`);
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
+
console.log('Successfully converted to TIDAL track:', trackLookup.track.title);
|
| 380 |
+
return trackLookup.track;
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
function maybePreloadNextTrack(remainingSeconds: number) {
|
| 384 |
+
if (remainingSeconds > PRELOAD_THRESHOLD_SECONDS) {
|
| 385 |
+
return;
|
| 386 |
+
}
|
| 387 |
+
const { queue, queueIndex } = $playerStore;
|
| 388 |
+
const nextTrack = queue[queueIndex + 1];
|
| 389 |
+
if (!nextTrack || isSonglinkTrack(nextTrack)) {
|
| 390 |
+
return; // Don't preload Songlink tracks
|
| 391 |
+
}
|
| 392 |
+
const dashKey = getCacheKey(nextTrack.id, 'HI_RES_LOSSLESS');
|
| 393 |
+
if (dashManifestCache.has(dashKey) || preloadingCacheKey === dashKey) {
|
| 394 |
+
return;
|
| 395 |
+
}
|
| 396 |
+
preloadNextTrack(nextTrack);
|
| 397 |
+
}
|
| 398 |
+
|
| 399 |
+
// Track which Songlink tracks are currently being converted to prevent duplicates
|
| 400 |
+
const convertingTracks = new Set<string>();
|
| 401 |
+
|
| 402 |
+
// Effect to convert SonglinkTrack to Track when needed
|
| 403 |
+
$effect(() => {
|
| 404 |
+
const current = $playerStore.currentTrack;
|
| 405 |
+
if (current && isSonglinkTrack(current)) {
|
| 406 |
+
console.log('[Conversion Effect] Detected SonglinkTrack:', current.title, 'ID:', current.id);
|
| 407 |
+
|
| 408 |
+
// Check if this track is already being converted
|
| 409 |
+
if (convertingTracks.has(current.id)) {
|
| 410 |
+
console.log('[Conversion Effect] Track already being converted, skipping');
|
| 411 |
+
return;
|
| 412 |
+
}
|
| 413 |
+
|
| 414 |
+
// Mark this track as being converted
|
| 415 |
+
convertingTracks.add(current.id);
|
| 416 |
+
console.log('[Conversion Effect] Starting conversion for:', current.title);
|
| 417 |
+
|
| 418 |
+
// Convert the Songlink track to a TIDAL track and update the store
|
| 419 |
+
convertSonglinkTrackToTidal(current)
|
| 420 |
+
.then((tidalTrack) => {
|
| 421 |
+
console.log('[Conversion Effect] Conversion SUCCESS:', tidalTrack.title, 'TIDAL ID:', tidalTrack.id);
|
| 422 |
+
// Only update if this is still the current track
|
| 423 |
+
const state = get(playerStore);
|
| 424 |
+
if (state.currentTrack && isSonglinkTrack(state.currentTrack) && state.currentTrack.id === current.id) {
|
| 425 |
+
console.log('[Conversion Effect] Updating player with converted track');
|
| 426 |
+
playerStore.setTrack(tidalTrack);
|
| 427 |
+
} else {
|
| 428 |
+
console.log('[Conversion Effect] Track changed during conversion, not updating');
|
| 429 |
+
}
|
| 430 |
+
})
|
| 431 |
+
.catch((error) => {
|
| 432 |
+
console.error('[Conversion Effect] Conversion FAILED:', error);
|
| 433 |
+
alert(`Failed to play track: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
| 434 |
+
})
|
| 435 |
+
.finally(() => {
|
| 436 |
+
// Remove from converting set when done
|
| 437 |
+
convertingTracks.delete(current.id);
|
| 438 |
+
console.log('[Conversion Effect] Finished conversion attempt for:', current.title);
|
| 439 |
+
});
|
| 440 |
+
}
|
| 441 |
+
});
|
| 442 |
+
|
| 443 |
+
$effect(() => {
|
| 444 |
+
const current = $playerStore.currentTrack;
|
| 445 |
+
if (!audioElement || !current) {
|
| 446 |
+
if (!current) {
|
| 447 |
+
currentTrackId = null;
|
| 448 |
+
streamUrl = '';
|
| 449 |
+
bufferedPercent = 0;
|
| 450 |
+
dashPlaybackActive = false;
|
| 451 |
+
dashFallbackAttemptedTrackId = null;
|
| 452 |
+
dashFallbackInFlight = false;
|
| 453 |
+
lastQualityTrackId = null;
|
| 454 |
+
lastQualityForTrack = null;
|
| 455 |
+
currentPlaybackQuality = null;
|
| 456 |
+
}
|
| 457 |
+
} else if (current.id !== currentTrackId) {
|
| 458 |
+
// Don't load SonglinkTracks - wait for them to be converted first
|
| 459 |
+
if (isSonglinkTrack(current)) {
|
| 460 |
+
return;
|
| 461 |
+
}
|
| 462 |
+
|
| 463 |
+
currentTrackId = current.id;
|
| 464 |
+
streamUrl = '';
|
| 465 |
+
bufferedPercent = 0;
|
| 466 |
+
dashPlaybackActive = false;
|
| 467 |
+
dashFallbackAttemptedTrackId = null;
|
| 468 |
+
dashFallbackInFlight = false;
|
| 469 |
+
lastQualityTrackId = current.id;
|
| 470 |
+
lastQualityForTrack = $playerStore.quality;
|
| 471 |
+
currentPlaybackQuality = null;
|
| 472 |
+
loadTrack(current);
|
| 473 |
+
}
|
| 474 |
+
});
|
| 475 |
+
|
| 476 |
+
$effect(() => {
|
| 477 |
+
const track = $playerStore.currentTrack;
|
| 478 |
+
if (!audioElement || !track) {
|
| 479 |
+
return;
|
| 480 |
+
}
|
| 481 |
+
const quality = $playerStore.quality;
|
| 482 |
+
if (lastQualityTrackId === track.id && lastQualityForTrack === quality) {
|
| 483 |
+
return;
|
| 484 |
+
}
|
| 485 |
+
lastQualityTrackId = track.id;
|
| 486 |
+
lastQualityForTrack = quality;
|
| 487 |
+
loadTrack(track);
|
| 488 |
+
});
|
| 489 |
+
|
| 490 |
+
$effect(() => {
|
| 491 |
+
if (showQueuePanel && $playerStore.queue.length === 0) {
|
| 492 |
+
showQueuePanel = false;
|
| 493 |
+
}
|
| 494 |
+
});
|
| 495 |
+
|
| 496 |
+
$effect(() => {
|
| 497 |
+
if (canUseMediaSession) {
|
| 498 |
+
updateMediaSessionMetadata($playerStore.currentTrack);
|
| 499 |
+
}
|
| 500 |
+
});
|
| 501 |
+
|
| 502 |
+
$effect(() => {
|
| 503 |
+
if (canUseMediaSession) {
|
| 504 |
+
const hasTrack = Boolean($playerStore.currentTrack);
|
| 505 |
+
updateMediaSessionPlaybackState(
|
| 506 |
+
hasTrack ? ($playerStore.isPlaying ? 'playing' : 'paused') : 'none'
|
| 507 |
+
);
|
| 508 |
+
}
|
| 509 |
+
});
|
| 510 |
+
|
| 511 |
+
function toggleQueuePanel() {
|
| 512 |
+
showQueuePanel = !showQueuePanel;
|
| 513 |
+
}
|
| 514 |
+
|
| 515 |
+
function closeQueuePanel() {
|
| 516 |
+
showQueuePanel = false;
|
| 517 |
+
}
|
| 518 |
+
|
| 519 |
+
function playFromQueue(index: number) {
|
| 520 |
+
playerStore.playAtIndex(index);
|
| 521 |
+
}
|
| 522 |
+
|
| 523 |
+
function removeFromQueue(index: number, event?: MouseEvent) {
|
| 524 |
+
if (event) {
|
| 525 |
+
event.stopPropagation();
|
| 526 |
+
}
|
| 527 |
+
playerStore.removeFromQueue(index);
|
| 528 |
+
}
|
| 529 |
+
|
| 530 |
+
function clearQueue() {
|
| 531 |
+
playerStore.clearQueue();
|
| 532 |
+
}
|
| 533 |
+
|
| 534 |
+
function handleShuffleQueue() {
|
| 535 |
+
playerStore.shuffleQueue();
|
| 536 |
+
}
|
| 537 |
+
|
| 538 |
+
$effect(() => {
|
| 539 |
+
if (audioElement) {
|
| 540 |
+
const baseVolume = $playerStore.volume;
|
| 541 |
+
const replayGain = $playerStore.replayGain;
|
| 542 |
+
|
| 543 |
+
if (replayGain !== null && typeof replayGain === 'number') {
|
| 544 |
+
// Apply replay gain: volume * 10^(gain / 20)
|
| 545 |
+
const gainFactor = Math.pow(10, replayGain / 20);
|
| 546 |
+
const adjusted = baseVolume * gainFactor;
|
| 547 |
+
audioElement.volume = Math.min(1, Math.max(0, adjusted));
|
| 548 |
+
} else {
|
| 549 |
+
audioElement.volume = baseVolume;
|
| 550 |
+
}
|
| 551 |
+
}
|
| 552 |
+
});
|
| 553 |
+
|
| 554 |
+
$effect(() => {
|
| 555 |
+
if ($playerStore.isPlaying && audioElement) {
|
| 556 |
+
audioElement.play().catch(console.error);
|
| 557 |
+
} else if (!$playerStore.isPlaying && audioElement) {
|
| 558 |
+
audioElement.pause();
|
| 559 |
+
}
|
| 560 |
+
});
|
| 561 |
+
|
| 562 |
+
async function loadStandardTrack(track: Track, quality: AudioQuality, sequence: number) {
|
| 563 |
+
await destroyShakaPlayer();
|
| 564 |
+
dashPlaybackActive = false;
|
| 565 |
+
const { url, replayGain, sampleRate, bitDepth } = await resolveStream(track, quality);
|
| 566 |
+
if (sequence !== loadSequence) {
|
| 567 |
+
return;
|
| 568 |
+
}
|
| 569 |
+
streamUrl = url;
|
| 570 |
+
currentPlaybackQuality = quality;
|
| 571 |
+
playerStore.setReplayGain(replayGain);
|
| 572 |
+
playerStore.setSampleRate(sampleRate);
|
| 573 |
+
playerStore.setBitDepth(bitDepth);
|
| 574 |
+
pruneStreamCache();
|
| 575 |
+
if (audioElement) {
|
| 576 |
+
audioElement.crossOrigin = 'anonymous';
|
| 577 |
+
audioElement.load();
|
| 578 |
+
}
|
| 579 |
+
}
|
| 580 |
+
|
| 581 |
+
async function loadDashTrack(
|
| 582 |
+
track: Track,
|
| 583 |
+
quality: AudioQuality,
|
| 584 |
+
sequence: number
|
| 585 |
+
): Promise<DashManifestWithMetadata> {
|
| 586 |
+
const cacheKey = getCacheKey(track.id, quality);
|
| 587 |
+
let cached = dashManifestCache.get(cacheKey);
|
| 588 |
+
if (!cached) {
|
| 589 |
+
cached = await losslessAPI.getDashManifestWithMetadata(track.id, quality);
|
| 590 |
+
dashManifestCache.set(cacheKey, cached);
|
| 591 |
+
}
|
| 592 |
+
const { result: manifestResult, trackInfo } = cached;
|
| 593 |
+
cacheFlacFallback(track.id, manifestResult);
|
| 594 |
+
if (manifestResult.kind === 'flac') {
|
| 595 |
+
dashPlaybackActive = false;
|
| 596 |
+
return cached;
|
| 597 |
+
}
|
| 598 |
+
revokeHiResObjectUrl();
|
| 599 |
+
const blob = new Blob([manifestResult.manifest], {
|
| 600 |
+
type: manifestResult.contentType ?? 'application/dash+xml'
|
| 601 |
+
});
|
| 602 |
+
hiResObjectUrl = URL.createObjectURL(blob);
|
| 603 |
+
const player = await ensureShakaPlayer();
|
| 604 |
+
if (sequence !== loadSequence) {
|
| 605 |
+
return cached;
|
| 606 |
+
}
|
| 607 |
+
if (audioElement) {
|
| 608 |
+
audioElement.pause();
|
| 609 |
+
audioElement.removeAttribute('src');
|
| 610 |
+
audioElement.load();
|
| 611 |
+
}
|
| 612 |
+
await player.unload();
|
| 613 |
+
await player.load(hiResObjectUrl);
|
| 614 |
+
dashPlaybackActive = true;
|
| 615 |
+
streamUrl = '';
|
| 616 |
+
currentPlaybackQuality = 'HI_RES_LOSSLESS';
|
| 617 |
+
|
| 618 |
+
// Apply metadata directly from the API response - no second API call needed
|
| 619 |
+
if (sequence === loadSequence && currentTrackId === track.id) {
|
| 620 |
+
playerStore.setSampleRate(trackInfo.sampleRate);
|
| 621 |
+
playerStore.setBitDepth(trackInfo.bitDepth);
|
| 622 |
+
if (trackInfo.replayGain !== null) {
|
| 623 |
+
playerStore.setReplayGain(trackInfo.replayGain);
|
| 624 |
+
}
|
| 625 |
+
}
|
| 626 |
+
|
| 627 |
+
pruneDashManifestCache();
|
| 628 |
+
return cached;
|
| 629 |
+
}
|
| 630 |
+
|
| 631 |
+
async function loadTrack(track: PlayableTrack) {
|
| 632 |
+
// CRITICAL: Never try to load a SonglinkTrack - it must be converted first
|
| 633 |
+
if (isSonglinkTrack(track)) {
|
| 634 |
+
console.error('Attempted to load SonglinkTrack directly - this should not happen!', track);
|
| 635 |
+
return;
|
| 636 |
+
}
|
| 637 |
+
const tidalTrack = track as Track;
|
| 638 |
+
|
| 639 |
+
// Validate that we have a numeric track ID
|
| 640 |
+
const trackId = Number(tidalTrack.id);
|
| 641 |
+
if (!Number.isFinite(trackId) || trackId <= 0) {
|
| 642 |
+
console.error('Invalid track ID - must be numeric:', tidalTrack.id);
|
| 643 |
+
return;
|
| 644 |
+
}
|
| 645 |
+
|
| 646 |
+
const sequence = ++loadSequence;
|
| 647 |
+
playerStore.setLoading(true);
|
| 648 |
+
bufferedPercent = 0;
|
| 649 |
+
currentPlaybackQuality = null;
|
| 650 |
+
let requestedQuality = $playerStore.quality;
|
| 651 |
+
|
| 652 |
+
const trackBestQuality = deriveTrackQuality(tidalTrack);
|
| 653 |
+
if (isHiResQuality(requestedQuality) && trackBestQuality && !isHiResQuality(trackBestQuality)) {
|
| 654 |
+
requestedQuality = trackBestQuality;
|
| 655 |
+
}
|
| 656 |
+
|
| 657 |
+
if (dashFallbackAttemptedTrackId && dashFallbackAttemptedTrackId !== tidalTrack.id) {
|
| 658 |
+
dashFallbackAttemptedTrackId = null;
|
| 659 |
+
}
|
| 660 |
+
|
| 661 |
+
try {
|
| 662 |
+
if (isHiResQuality(requestedQuality)) {
|
| 663 |
+
try {
|
| 664 |
+
const hiResQuality: AudioQuality = 'HI_RES_LOSSLESS';
|
| 665 |
+
const dashResult = await loadDashTrack(tidalTrack, hiResQuality, sequence);
|
| 666 |
+
if (dashResult.result.kind === 'dash') {
|
| 667 |
+
// Metadata already applied in loadDashTrack - no second API call needed
|
| 668 |
+
return;
|
| 669 |
+
}
|
| 670 |
+
console.info('Dash endpoint returned FLAC fallback. Using lossless stream.');
|
| 671 |
+
} catch (dashError) {
|
| 672 |
+
const coded = dashError as { code?: string };
|
| 673 |
+
if (coded?.code === DASH_MANIFEST_UNAVAILABLE_CODE) {
|
| 674 |
+
dashManifestCache.delete(getCacheKey(tidalTrack.id, 'HI_RES_LOSSLESS'));
|
| 675 |
+
}
|
| 676 |
+
console.warn('DASH playback failed, falling back to lossless stream.', dashError);
|
| 677 |
+
}
|
| 678 |
+
await loadStandardTrack(tidalTrack, 'LOSSLESS', sequence);
|
| 679 |
+
return;
|
| 680 |
+
}
|
| 681 |
+
|
| 682 |
+
await loadStandardTrack(tidalTrack, requestedQuality, sequence);
|
| 683 |
+
} catch (error) {
|
| 684 |
+
console.error('Failed to load track:', error);
|
| 685 |
+
if (
|
| 686 |
+
sequence === loadSequence &&
|
| 687 |
+
requestedQuality !== 'LOSSLESS' &&
|
| 688 |
+
!isHiResQuality(requestedQuality)
|
| 689 |
+
) {
|
| 690 |
+
try {
|
| 691 |
+
await loadStandardTrack(tidalTrack, 'LOSSLESS', sequence);
|
| 692 |
+
} catch (fallbackError) {
|
| 693 |
+
console.error('Secondary lossless fallback failed:', fallbackError);
|
| 694 |
+
}
|
| 695 |
+
}
|
| 696 |
+
} finally {
|
| 697 |
+
if (sequence === loadSequence) {
|
| 698 |
+
playerStore.setLoading(false);
|
| 699 |
+
}
|
| 700 |
+
}
|
| 701 |
+
}
|
| 702 |
+
|
| 703 |
+
function handleTimeUpdate() {
|
| 704 |
+
if (audioElement) {
|
| 705 |
+
playerStore.setCurrentTime(audioElement.currentTime);
|
| 706 |
+
updateBufferedPercent();
|
| 707 |
+
const remaining = ($playerStore.duration ?? 0) - audioElement.currentTime;
|
| 708 |
+
maybePreloadNextTrack(remaining);
|
| 709 |
+
updateMediaSessionPositionState();
|
| 710 |
+
}
|
| 711 |
+
}
|
| 712 |
+
|
| 713 |
+
async function fallbackToLosslessAfterDashError(reason: string) {
|
| 714 |
+
if (dashFallbackInFlight) {
|
| 715 |
+
return;
|
| 716 |
+
}
|
| 717 |
+
const track = $playerStore.currentTrack;
|
| 718 |
+
if (!track) {
|
| 719 |
+
return;
|
| 720 |
+
}
|
| 721 |
+
if (dashFallbackAttemptedTrackId === track.id) {
|
| 722 |
+
return;
|
| 723 |
+
}
|
| 724 |
+
dashFallbackInFlight = true;
|
| 725 |
+
dashFallbackAttemptedTrackId = track.id;
|
| 726 |
+
const sequence = ++loadSequence;
|
| 727 |
+
console.warn(`Attempting lossless fallback after DASH playback error (${reason}).`);
|
| 728 |
+
try {
|
| 729 |
+
dashPlaybackActive = false;
|
| 730 |
+
playerStore.setLoading(true);
|
| 731 |
+
bufferedPercent = 0;
|
| 732 |
+
await loadStandardTrack(track as Track, 'LOSSLESS', sequence);
|
| 733 |
+
} catch (fallbackError) {
|
| 734 |
+
console.error('Lossless fallback after DASH playback error failed', fallbackError);
|
| 735 |
+
if (sequence === loadSequence) {
|
| 736 |
+
playerStore.setLoading(false);
|
| 737 |
+
}
|
| 738 |
+
} finally {
|
| 739 |
+
dashFallbackInFlight = false;
|
| 740 |
+
}
|
| 741 |
+
}
|
| 742 |
+
|
| 743 |
+
function handleAudioError(event: Event) {
|
| 744 |
+
if (!dashPlaybackActive || !isFirefox) {
|
| 745 |
+
return;
|
| 746 |
+
}
|
| 747 |
+
const element = event.currentTarget as HTMLAudioElement | null;
|
| 748 |
+
const mediaError = element?.error ?? null;
|
| 749 |
+
const code = mediaError?.code;
|
| 750 |
+
const decodeConstant = mediaError?.MEDIA_ERR_DECODE;
|
| 751 |
+
const isDecodeError =
|
| 752 |
+
typeof code === 'number' && typeof decodeConstant === 'number'
|
| 753 |
+
? code === decodeConstant
|
| 754 |
+
: false;
|
| 755 |
+
const reason = isDecodeError ? 'decode error' : code ? `code ${code}` : 'unknown error';
|
| 756 |
+
void fallbackToLosslessAfterDashError(reason);
|
| 757 |
+
}
|
| 758 |
+
|
| 759 |
+
function handleDurationChange() {
|
| 760 |
+
if (audioElement) {
|
| 761 |
+
playerStore.setDuration(audioElement.duration);
|
| 762 |
+
updateBufferedPercent();
|
| 763 |
+
updateMediaSessionPositionState();
|
| 764 |
+
}
|
| 765 |
+
}
|
| 766 |
+
|
| 767 |
+
function updateBufferedPercent() {
|
| 768 |
+
if (!audioElement) {
|
| 769 |
+
bufferedPercent = 0;
|
| 770 |
+
return;
|
| 771 |
+
}
|
| 772 |
+
|
| 773 |
+
const { duration, buffered, currentTime } = audioElement;
|
| 774 |
+
if (!Number.isFinite(duration) || duration <= 0 || buffered.length === 0) {
|
| 775 |
+
bufferedPercent = 0;
|
| 776 |
+
return;
|
| 777 |
+
}
|
| 778 |
+
|
| 779 |
+
let bufferedEnd = 0;
|
| 780 |
+
for (let i = 0; i < buffered.length; i += 1) {
|
| 781 |
+
const start = buffered.start(i);
|
| 782 |
+
const end = buffered.end(i);
|
| 783 |
+
if (start <= currentTime && end >= currentTime) {
|
| 784 |
+
bufferedEnd = end;
|
| 785 |
+
break;
|
| 786 |
+
}
|
| 787 |
+
bufferedEnd = Math.max(bufferedEnd, end);
|
| 788 |
+
}
|
| 789 |
+
|
| 790 |
+
bufferedPercent = Math.max(0, Math.min(100, (bufferedEnd / duration) * 100));
|
| 791 |
+
}
|
| 792 |
+
|
| 793 |
+
function handleProgress() {
|
| 794 |
+
updateBufferedPercent();
|
| 795 |
+
}
|
| 796 |
+
|
| 797 |
+
function handleLoadedData() {
|
| 798 |
+
playerStore.setLoading(false);
|
| 799 |
+
updateBufferedPercent();
|
| 800 |
+
|
| 801 |
+
// Resume playback position if needed (e.g. after quality switch or page reload)
|
| 802 |
+
const state = get(playerStore);
|
| 803 |
+
if (audioElement && state.currentTime > 0 && Math.abs(audioElement.currentTime - state.currentTime) > 1) {
|
| 804 |
+
audioElement.currentTime = state.currentTime;
|
| 805 |
+
}
|
| 806 |
+
|
| 807 |
+
updateMediaSessionPositionState();
|
| 808 |
+
}
|
| 809 |
+
|
| 810 |
+
function getPercent(current: number, total: number): number {
|
| 811 |
+
if (!Number.isFinite(total) || total <= 0) {
|
| 812 |
+
return 0;
|
| 813 |
+
}
|
| 814 |
+
return Math.max(0, Math.min(100, (current / total) * 100));
|
| 815 |
+
}
|
| 816 |
+
|
| 817 |
+
function handlePrevious() {
|
| 818 |
+
if (audioElement && (audioElement.currentTime > 5 || $playerStore.queueIndex <= 0)) {
|
| 819 |
+
audioElement.currentTime = 0;
|
| 820 |
+
playerStore.setCurrentTime(0);
|
| 821 |
+
updateMediaSessionPositionState();
|
| 822 |
+
} else {
|
| 823 |
+
playerStore.previous();
|
| 824 |
+
}
|
| 825 |
+
}
|
| 826 |
+
|
| 827 |
+
function handleEnded() {
|
| 828 |
+
playerStore.next();
|
| 829 |
+
updateMediaSessionPositionState();
|
| 830 |
+
}
|
| 831 |
+
|
| 832 |
+
function handleSeek(event: MouseEvent | TouchEvent) {
|
| 833 |
+
if (!seekBarElement) return;
|
| 834 |
+
|
| 835 |
+
const rect = seekBarElement.getBoundingClientRect();
|
| 836 |
+
const clientX = 'touches' in event ? event.touches[0].clientX : event.clientX;
|
| 837 |
+
const percent = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));
|
| 838 |
+
const newTime = percent * $playerStore.duration;
|
| 839 |
+
|
| 840 |
+
if (audioElement) {
|
| 841 |
+
audioElement.currentTime = newTime;
|
| 842 |
+
playerStore.setCurrentTime(newTime);
|
| 843 |
+
updateMediaSessionPositionState();
|
| 844 |
+
}
|
| 845 |
+
}
|
| 846 |
+
|
| 847 |
+
function handleSeekStart(event: MouseEvent | TouchEvent) {
|
| 848 |
+
event.preventDefault();
|
| 849 |
+
isSeeking = true;
|
| 850 |
+
handleSeek(event);
|
| 851 |
+
|
| 852 |
+
const handleMove = (e: MouseEvent | TouchEvent) => {
|
| 853 |
+
if (isSeeking) {
|
| 854 |
+
handleSeek(e);
|
| 855 |
+
}
|
| 856 |
+
};
|
| 857 |
+
|
| 858 |
+
const handleEnd = () => {
|
| 859 |
+
isSeeking = false;
|
| 860 |
+
document.removeEventListener('mousemove', handleMove as EventListener);
|
| 861 |
+
document.removeEventListener('mouseup', handleEnd);
|
| 862 |
+
document.removeEventListener('touchmove', handleMove as EventListener);
|
| 863 |
+
document.removeEventListener('touchend', handleEnd);
|
| 864 |
+
};
|
| 865 |
+
|
| 866 |
+
document.addEventListener('mousemove', handleMove as EventListener);
|
| 867 |
+
document.addEventListener('mouseup', handleEnd);
|
| 868 |
+
document.addEventListener('touchmove', handleMove as EventListener);
|
| 869 |
+
document.addEventListener('touchend', handleEnd);
|
| 870 |
+
}
|
| 871 |
+
|
| 872 |
+
function handleVolumeChange(event: Event) {
|
| 873 |
+
const target = event.target as HTMLInputElement;
|
| 874 |
+
const newVolume = parseFloat(target.value);
|
| 875 |
+
playerStore.setVolume(newVolume);
|
| 876 |
+
if (newVolume > 0 && isMuted) {
|
| 877 |
+
isMuted = false;
|
| 878 |
+
}
|
| 879 |
+
}
|
| 880 |
+
|
| 881 |
+
function handleLyricsSeekEvent(event: Event) {
|
| 882 |
+
const customEvent = event as CustomEvent<{ timeSeconds?: number }>;
|
| 883 |
+
const targetSeconds = customEvent.detail?.timeSeconds;
|
| 884 |
+
if (typeof targetSeconds !== 'number' || !audioElement) {
|
| 885 |
+
return;
|
| 886 |
+
}
|
| 887 |
+
|
| 888 |
+
const seekSeconds = Math.max(0, targetSeconds);
|
| 889 |
+
audioElement.currentTime = seekSeconds;
|
| 890 |
+
playerStore.setCurrentTime(seekSeconds);
|
| 891 |
+
updateMediaSessionPositionState();
|
| 892 |
+
|
| 893 |
+
const state = get(playerStore);
|
| 894 |
+
if (!state.isPlaying) {
|
| 895 |
+
playerStore.play();
|
| 896 |
+
}
|
| 897 |
+
|
| 898 |
+
audioElement.play().catch(() => {});
|
| 899 |
+
}
|
| 900 |
+
|
| 901 |
+
async function handleDownloadCurrentTrack() {
|
| 902 |
+
const track = $playerStore.currentTrack;
|
| 903 |
+
if (!track || isDownloadingCurrentTrack || isSonglinkTrack(track)) {
|
| 904 |
+
return;
|
| 905 |
+
}
|
| 906 |
+
|
| 907 |
+
const quality = $playerStore.quality;
|
| 908 |
+
const convertAacToMp3 = $userPreferencesStore.convertAacToMp3;
|
| 909 |
+
const downloadCoverSeperately = $userPreferencesStore.downloadCoversSeperately;
|
| 910 |
+
const filename = buildTrackFilename(
|
| 911 |
+
track.album,
|
| 912 |
+
track,
|
| 913 |
+
quality,
|
| 914 |
+
formatArtists(track.artists),
|
| 915 |
+
convertAacToMp3
|
| 916 |
+
);
|
| 917 |
+
|
| 918 |
+
const { taskId, controller } = downloadUiStore.beginTrackDownload(track, filename, {
|
| 919 |
+
subtitle: track.album?.title ?? track.artist?.name
|
| 920 |
+
});
|
| 921 |
+
|
| 922 |
+
downloadTaskIdForCurrentTrack = taskId;
|
| 923 |
+
isDownloadingCurrentTrack = true;
|
| 924 |
+
downloadUiStore.skipFfmpegCountdown();
|
| 925 |
+
|
| 926 |
+
try {
|
| 927 |
+
await losslessAPI.downloadTrack(track.id, quality, filename, {
|
| 928 |
+
signal: controller.signal,
|
| 929 |
+
onProgress: (progress: TrackDownloadProgress) => {
|
| 930 |
+
if (progress.stage === 'downloading') {
|
| 931 |
+
downloadUiStore.updateTrackProgress(
|
| 932 |
+
taskId,
|
| 933 |
+
progress.receivedBytes,
|
| 934 |
+
progress.totalBytes
|
| 935 |
+
);
|
| 936 |
+
} else {
|
| 937 |
+
downloadUiStore.updateTrackStage(taskId, progress.progress);
|
| 938 |
+
}
|
| 939 |
+
},
|
| 940 |
+
onFfmpegCountdown: ({ totalBytes }) => {
|
| 941 |
+
if (typeof totalBytes === 'number') {
|
| 942 |
+
downloadUiStore.startFfmpegCountdown(totalBytes, { autoTriggered: false });
|
| 943 |
+
} else {
|
| 944 |
+
downloadUiStore.startFfmpegCountdown(0, { autoTriggered: false });
|
| 945 |
+
}
|
| 946 |
+
},
|
| 947 |
+
onFfmpegStart: () => downloadUiStore.startFfmpegLoading(),
|
| 948 |
+
onFfmpegProgress: (value) => downloadUiStore.updateFfmpegProgress(value),
|
| 949 |
+
onFfmpegComplete: () => downloadUiStore.completeFfmpeg(),
|
| 950 |
+
onFfmpegError: (error) => downloadUiStore.errorFfmpeg(error),
|
| 951 |
+
ffmpegAutoTriggered: false,
|
| 952 |
+
convertAacToMp3,
|
| 953 |
+
downloadCoverSeperately
|
| 954 |
+
});
|
| 955 |
+
downloadUiStore.completeTrackDownload(taskId);
|
| 956 |
+
} catch (error) {
|
| 957 |
+
if (error instanceof DOMException && error.name === 'AbortError') {
|
| 958 |
+
downloadUiStore.completeTrackDownload(taskId);
|
| 959 |
+
} else {
|
| 960 |
+
console.error('Failed to download track:', error);
|
| 961 |
+
const fallbackMessage = 'Failed to download track. Please try again.';
|
| 962 |
+
const message = error instanceof Error && error.message ? error.message : fallbackMessage;
|
| 963 |
+
downloadUiStore.errorTrackDownload(taskId, message);
|
| 964 |
+
alert(message);
|
| 965 |
+
}
|
| 966 |
+
} finally {
|
| 967 |
+
isDownloadingCurrentTrack = false;
|
| 968 |
+
downloadTaskIdForCurrentTrack = null;
|
| 969 |
+
}
|
| 970 |
+
}
|
| 971 |
+
|
| 972 |
+
function toggleMute() {
|
| 973 |
+
if (isMuted) {
|
| 974 |
+
playerStore.setVolume(previousVolume);
|
| 975 |
+
isMuted = false;
|
| 976 |
+
} else {
|
| 977 |
+
previousVolume = $playerStore.volume;
|
| 978 |
+
playerStore.setVolume(0);
|
| 979 |
+
isMuted = true;
|
| 980 |
+
}
|
| 981 |
+
}
|
| 982 |
+
|
| 983 |
+
function formatTime(seconds: number): string {
|
| 984 |
+
if (isNaN(seconds)) return '0:00';
|
| 985 |
+
const mins = Math.floor(seconds / 60);
|
| 986 |
+
const secs = Math.floor(seconds % 60);
|
| 987 |
+
return `${mins}:${secs.toString().padStart(2, '0')}`;
|
| 988 |
+
}
|
| 989 |
+
|
| 990 |
+
function formatQualityLabel(quality?: string): string {
|
| 991 |
+
if (!quality) return '—';
|
| 992 |
+
const normalized = quality.toUpperCase();
|
| 993 |
+
if (normalized === 'LOSSLESS') {
|
| 994 |
+
return 'CD';
|
| 995 |
+
}
|
| 996 |
+
if (normalized === 'HI_RES_LOSSLESS') {
|
| 997 |
+
return 'Hi-Res';
|
| 998 |
+
}
|
| 999 |
+
return quality;
|
| 1000 |
+
}
|
| 1001 |
+
|
| 1002 |
+
function formatSampleRate(value?: number | null): string | null {
|
| 1003 |
+
if (!Number.isFinite(value ?? NaN) || !value || value <= 0) {
|
| 1004 |
+
return null;
|
| 1005 |
+
}
|
| 1006 |
+
const kilohertz = value / 1000;
|
| 1007 |
+
const precision =
|
| 1008 |
+
kilohertz >= 100 || Math.abs(kilohertz - Math.round(kilohertz)) < 0.05 ? 0 : 1;
|
| 1009 |
+
const formatted = kilohertz.toFixed(precision).replace(/\.0$/, '');
|
| 1010 |
+
return `${formatted} kHz`;
|
| 1011 |
+
}
|
| 1012 |
+
|
| 1013 |
+
function formatBitDepth(value?: number | null): string | null {
|
| 1014 |
+
if (!Number.isFinite(value ?? NaN) || !value || value <= 0) {
|
| 1015 |
+
return null;
|
| 1016 |
+
}
|
| 1017 |
+
return `${value}-bit`;
|
| 1018 |
+
}
|
| 1019 |
+
|
| 1020 |
+
function formatMegabytes(bytes?: number | null): string | null {
|
| 1021 |
+
if (!Number.isFinite(bytes ?? NaN) || !bytes || bytes <= 0) {
|
| 1022 |
+
return null;
|
| 1023 |
+
}
|
| 1024 |
+
const value = bytes / (1024 * 1024);
|
| 1025 |
+
const digits = value >= 100 ? 0 : value >= 10 ? 1 : 2;
|
| 1026 |
+
return `${value.toFixed(digits)} MB`;
|
| 1027 |
+
}
|
| 1028 |
+
|
| 1029 |
+
function formatPercent(value: number | null | undefined): string {
|
| 1030 |
+
if (!Number.isFinite(value ?? NaN)) {
|
| 1031 |
+
return '0%';
|
| 1032 |
+
}
|
| 1033 |
+
const percent = Math.max(0, Math.min(100, Math.round((value ?? 0) * 100)));
|
| 1034 |
+
return `${percent}%`;
|
| 1035 |
+
}
|
| 1036 |
+
|
| 1037 |
+
function formatTransferStatus(received: number, total?: number): string {
|
| 1038 |
+
const receivedLabel = formatMegabytes(received) ?? '0 MB';
|
| 1039 |
+
const totalLabel = formatMegabytes(total) ?? null;
|
| 1040 |
+
return totalLabel ? `${receivedLabel} / ${totalLabel}` : receivedLabel;
|
| 1041 |
+
}
|
| 1042 |
+
|
| 1043 |
+
$effect(() => {
|
| 1044 |
+
if ($ffmpegBanner.phase === 'ready') {
|
| 1045 |
+
const timeout = setTimeout(() => {
|
| 1046 |
+
downloadUiStore.dismissFfmpeg();
|
| 1047 |
+
}, 3200);
|
| 1048 |
+
return () => clearTimeout(timeout);
|
| 1049 |
+
}
|
| 1050 |
+
});
|
| 1051 |
+
|
| 1052 |
+
function getMediaSessionArtwork(track: PlayableTrack): MediaImage[] {
|
| 1053 |
+
if (isSonglinkTrack(track)) {
|
| 1054 |
+
if (track.thumbnailUrl) {
|
| 1055 |
+
return [{
|
| 1056 |
+
src: track.thumbnailUrl,
|
| 1057 |
+
sizes: '640x640',
|
| 1058 |
+
type: 'image/jpeg'
|
| 1059 |
+
}];
|
| 1060 |
+
}
|
| 1061 |
+
return [];
|
| 1062 |
+
}
|
| 1063 |
+
|
| 1064 |
+
if (!track.album?.cover) {
|
| 1065 |
+
return [];
|
| 1066 |
+
}
|
| 1067 |
+
|
| 1068 |
+
const sizes = ['80', '160', '320', '640', '1280'] as const;
|
| 1069 |
+
const artwork: MediaImage[] = [];
|
| 1070 |
+
|
| 1071 |
+
for (const size of sizes) {
|
| 1072 |
+
const src = losslessAPI.getCoverUrl(track.album.cover, size);
|
| 1073 |
+
if (src) {
|
| 1074 |
+
artwork.push({
|
| 1075 |
+
src,
|
| 1076 |
+
sizes: `${size}x${size}`,
|
| 1077 |
+
type: 'image/jpeg'
|
| 1078 |
+
});
|
| 1079 |
+
}
|
| 1080 |
+
}
|
| 1081 |
+
|
| 1082 |
+
return artwork;
|
| 1083 |
+
}
|
| 1084 |
+
|
| 1085 |
+
function updateMediaSessionMetadata(track: PlayableTrack | null) {
|
| 1086 |
+
if (!canUseMediaSession) {
|
| 1087 |
+
return;
|
| 1088 |
+
}
|
| 1089 |
+
|
| 1090 |
+
if (!track) {
|
| 1091 |
+
mediaSessionTrackId = null;
|
| 1092 |
+
lastKnownPlaybackState = 'none';
|
| 1093 |
+
try {
|
| 1094 |
+
navigator.mediaSession.metadata = null;
|
| 1095 |
+
navigator.mediaSession.playbackState = 'none';
|
| 1096 |
+
} catch (error) {
|
| 1097 |
+
console.debug('Media Session reset failed', error);
|
| 1098 |
+
}
|
| 1099 |
+
return;
|
| 1100 |
+
}
|
| 1101 |
+
|
| 1102 |
+
if (mediaSessionTrackId === track.id) {
|
| 1103 |
+
return;
|
| 1104 |
+
}
|
| 1105 |
+
|
| 1106 |
+
mediaSessionTrackId = track.id;
|
| 1107 |
+
|
| 1108 |
+
try {
|
| 1109 |
+
navigator.mediaSession.metadata = new MediaMetadata({
|
| 1110 |
+
title: track.title,
|
| 1111 |
+
artist: isSonglinkTrack(track) ? track.artistName : formatArtists(track.artists),
|
| 1112 |
+
album: isSonglinkTrack(track) ? '' : (track.album?.title ?? ''),
|
| 1113 |
+
artwork: getMediaSessionArtwork(track)
|
| 1114 |
+
});
|
| 1115 |
+
} catch (error) {
|
| 1116 |
+
console.debug('Unable to set Media Session metadata', error);
|
| 1117 |
+
}
|
| 1118 |
+
|
| 1119 |
+
updateMediaSessionPositionState();
|
| 1120 |
+
}
|
| 1121 |
+
|
| 1122 |
+
function updateMediaSessionPlaybackState(state: 'playing' | 'paused' | 'none') {
|
| 1123 |
+
if (!canUseMediaSession) {
|
| 1124 |
+
return;
|
| 1125 |
+
}
|
| 1126 |
+
|
| 1127 |
+
if (lastKnownPlaybackState === state) {
|
| 1128 |
+
return;
|
| 1129 |
+
}
|
| 1130 |
+
lastKnownPlaybackState = state;
|
| 1131 |
+
|
| 1132 |
+
try {
|
| 1133 |
+
navigator.mediaSession.playbackState = state;
|
| 1134 |
+
} catch (error) {
|
| 1135 |
+
console.debug('Unable to set Media Session playback state', error);
|
| 1136 |
+
}
|
| 1137 |
+
}
|
| 1138 |
+
|
| 1139 |
+
function updateMediaSessionPositionState() {
|
| 1140 |
+
if (
|
| 1141 |
+
!canUseMediaSession ||
|
| 1142 |
+
!audioElement ||
|
| 1143 |
+
typeof navigator.mediaSession.setPositionState !== 'function'
|
| 1144 |
+
) {
|
| 1145 |
+
return;
|
| 1146 |
+
}
|
| 1147 |
+
|
| 1148 |
+
const durationFromAudio = audioElement.duration;
|
| 1149 |
+
const storeState = get(playerStore);
|
| 1150 |
+
const duration = Number.isFinite(durationFromAudio) ? durationFromAudio : storeState.duration;
|
| 1151 |
+
|
| 1152 |
+
try {
|
| 1153 |
+
navigator.mediaSession.setPositionState({
|
| 1154 |
+
duration: Number.isFinite(duration) ? duration : 0,
|
| 1155 |
+
playbackRate: audioElement.playbackRate ?? 1,
|
| 1156 |
+
position: audioElement.currentTime
|
| 1157 |
+
});
|
| 1158 |
+
} catch (error) {
|
| 1159 |
+
console.debug('Unable to set Media Session position state', error);
|
| 1160 |
+
}
|
| 1161 |
+
}
|
| 1162 |
+
|
| 1163 |
+
function registerMediaSessionHandlers() {
|
| 1164 |
+
if (!canUseMediaSession) {
|
| 1165 |
+
return;
|
| 1166 |
+
}
|
| 1167 |
+
|
| 1168 |
+
const safeSetActionHandler = (
|
| 1169 |
+
action: MediaSessionAction,
|
| 1170 |
+
handler: MediaSessionActionHandler | null
|
| 1171 |
+
) => {
|
| 1172 |
+
try {
|
| 1173 |
+
navigator.mediaSession.setActionHandler(action, handler);
|
| 1174 |
+
} catch (error) {
|
| 1175 |
+
console.debug(`Media Session action ${action} unsupported`, error);
|
| 1176 |
+
}
|
| 1177 |
+
};
|
| 1178 |
+
|
| 1179 |
+
safeSetActionHandler('play', async () => {
|
| 1180 |
+
playerStore.play();
|
| 1181 |
+
if (!audioElement) return;
|
| 1182 |
+
try {
|
| 1183 |
+
await audioElement.play();
|
| 1184 |
+
} catch (error) {
|
| 1185 |
+
console.debug('Media Session play failed', error);
|
| 1186 |
+
}
|
| 1187 |
+
updateMediaSessionPlaybackState('playing');
|
| 1188 |
+
updateMediaSessionPositionState();
|
| 1189 |
+
});
|
| 1190 |
+
|
| 1191 |
+
safeSetActionHandler('pause', () => {
|
| 1192 |
+
playerStore.pause();
|
| 1193 |
+
audioElement?.pause();
|
| 1194 |
+
updateMediaSessionPlaybackState('paused');
|
| 1195 |
+
updateMediaSessionPositionState();
|
| 1196 |
+
});
|
| 1197 |
+
|
| 1198 |
+
safeSetActionHandler('previoustrack', () => {
|
| 1199 |
+
handlePrevious();
|
| 1200 |
+
});
|
| 1201 |
+
|
| 1202 |
+
safeSetActionHandler('nexttrack', () => {
|
| 1203 |
+
playerStore.next();
|
| 1204 |
+
});
|
| 1205 |
+
|
| 1206 |
+
const handleSeekDelta =
|
| 1207 |
+
(direction: 'forward' | 'backward') => (details: MediaSessionActionDetails) => {
|
| 1208 |
+
if (!audioElement) return;
|
| 1209 |
+
const offset = details.seekOffset ?? 10;
|
| 1210 |
+
const delta = direction === 'forward' ? offset : -offset;
|
| 1211 |
+
const tentative = audioElement.currentTime + delta;
|
| 1212 |
+
const duration = audioElement.duration;
|
| 1213 |
+
const bounded = Number.isFinite(duration)
|
| 1214 |
+
? Math.min(Math.max(0, tentative), Math.max(duration, 0))
|
| 1215 |
+
: Math.max(0, tentative);
|
| 1216 |
+
audioElement.currentTime = bounded;
|
| 1217 |
+
playerStore.setCurrentTime(bounded);
|
| 1218 |
+
updateMediaSessionPositionState();
|
| 1219 |
+
};
|
| 1220 |
+
|
| 1221 |
+
safeSetActionHandler('seekforward', handleSeekDelta('forward'));
|
| 1222 |
+
safeSetActionHandler('seekbackward', handleSeekDelta('backward'));
|
| 1223 |
+
|
| 1224 |
+
safeSetActionHandler('seekto', (details) => {
|
| 1225 |
+
if (!audioElement || details.seekTime === undefined) return;
|
| 1226 |
+
const nextTime = Math.max(0, details.seekTime);
|
| 1227 |
+
audioElement.currentTime = nextTime;
|
| 1228 |
+
playerStore.setCurrentTime(nextTime);
|
| 1229 |
+
updateMediaSessionPositionState();
|
| 1230 |
+
});
|
| 1231 |
+
|
| 1232 |
+
safeSetActionHandler('stop', () => {
|
| 1233 |
+
playerStore.pause();
|
| 1234 |
+
if (audioElement) {
|
| 1235 |
+
audioElement.pause();
|
| 1236 |
+
audioElement.currentTime = 0;
|
| 1237 |
+
}
|
| 1238 |
+
playerStore.setCurrentTime(0);
|
| 1239 |
+
updateMediaSessionPlaybackState('paused');
|
| 1240 |
+
updateMediaSessionPositionState();
|
| 1241 |
+
});
|
| 1242 |
+
|
| 1243 |
+
cleanupMediaSessionHandlers = () => {
|
| 1244 |
+
const actions: MediaSessionAction[] = [
|
| 1245 |
+
'play',
|
| 1246 |
+
'pause',
|
| 1247 |
+
'previoustrack',
|
| 1248 |
+
'nexttrack',
|
| 1249 |
+
'seekforward',
|
| 1250 |
+
'seekbackward',
|
| 1251 |
+
'seekto',
|
| 1252 |
+
'stop'
|
| 1253 |
+
];
|
| 1254 |
+
for (const action of actions) {
|
| 1255 |
+
safeSetActionHandler(action, null);
|
| 1256 |
+
}
|
| 1257 |
+
mediaSessionTrackId = null;
|
| 1258 |
+
lastKnownPlaybackState = 'none';
|
| 1259 |
+
};
|
| 1260 |
+
}
|
| 1261 |
+
|
| 1262 |
+
onMount(() => {
|
| 1263 |
+
let detachLyricsSeek: (() => void) | null = null;
|
| 1264 |
+
|
| 1265 |
+
if (audioElement) {
|
| 1266 |
+
audioElement.volume = $playerStore.volume;
|
| 1267 |
+
}
|
| 1268 |
+
|
| 1269 |
+
if (containerElement) {
|
| 1270 |
+
notifyContainerHeight();
|
| 1271 |
+
resizeObserver = new ResizeObserver(() => {
|
| 1272 |
+
notifyContainerHeight();
|
| 1273 |
+
});
|
| 1274 |
+
resizeObserver.observe(containerElement);
|
| 1275 |
+
}
|
| 1276 |
+
|
| 1277 |
+
if (canUseMediaSession) {
|
| 1278 |
+
registerMediaSessionHandlers();
|
| 1279 |
+
const state = get(playerStore);
|
| 1280 |
+
updateMediaSessionMetadata(state.currentTrack);
|
| 1281 |
+
updateMediaSessionPlaybackState(
|
| 1282 |
+
state.currentTrack ? (state.isPlaying ? 'playing' : 'paused') : 'none'
|
| 1283 |
+
);
|
| 1284 |
+
updateMediaSessionPositionState();
|
| 1285 |
+
}
|
| 1286 |
+
|
| 1287 |
+
if (typeof window !== 'undefined') {
|
| 1288 |
+
const listener = (event: Event) => handleLyricsSeekEvent(event);
|
| 1289 |
+
window.addEventListener('lyrics:seek', listener as EventListener);
|
| 1290 |
+
detachLyricsSeek = () => {
|
| 1291 |
+
window.removeEventListener('lyrics:seek', listener as EventListener);
|
| 1292 |
+
};
|
| 1293 |
+
}
|
| 1294 |
+
|
| 1295 |
+
return () => {
|
| 1296 |
+
resizeObserver?.disconnect();
|
| 1297 |
+
cleanupMediaSessionHandlers?.();
|
| 1298 |
+
cleanupMediaSessionHandlers = null;
|
| 1299 |
+
detachLyricsSeek?.();
|
| 1300 |
+
destroyShakaPlayer().catch((error) => {
|
| 1301 |
+
console.debug('Shaka cleanup failed', error);
|
| 1302 |
+
});
|
| 1303 |
+
if (canUseMediaSession) {
|
| 1304 |
+
try {
|
| 1305 |
+
navigator.mediaSession.metadata = null;
|
| 1306 |
+
navigator.mediaSession.playbackState = 'none';
|
| 1307 |
+
} catch (error) {
|
| 1308 |
+
console.debug('Failed to clean up Media Session', error);
|
| 1309 |
+
}
|
| 1310 |
+
}
|
| 1311 |
+
};
|
| 1312 |
+
});
|
| 1313 |
+
|
| 1314 |
+
function notifyContainerHeight() {
|
| 1315 |
+
if (typeof onHeightChange === 'function' && containerElement) {
|
| 1316 |
+
const height = containerElement.offsetHeight ?? 0;
|
| 1317 |
+
onHeightChange(height);
|
| 1318 |
+
// Set CSS variable for other components (like lyrics popup)
|
| 1319 |
+
if (typeof document !== 'undefined') {
|
| 1320 |
+
document.documentElement.style.setProperty('--player-height', `${height}px`);
|
| 1321 |
+
}
|
| 1322 |
+
}
|
| 1323 |
+
}
|
| 1324 |
+
|
| 1325 |
+
function asTrack(track: PlayableTrack): Track {
|
| 1326 |
+
return track as Track;
|
| 1327 |
+
}
|
| 1328 |
+
</script>
|
| 1329 |
+
|
| 1330 |
+
<audio
|
| 1331 |
+
bind:this={audioElement}
|
| 1332 |
+
src={streamUrl}
|
| 1333 |
+
ontimeupdate={handleTimeUpdate}
|
| 1334 |
+
ondurationchange={handleDurationChange}
|
| 1335 |
+
onended={handleEnded}
|
| 1336 |
+
onloadeddata={handleLoadedData}
|
| 1337 |
+
onloadedmetadata={updateBufferedPercent}
|
| 1338 |
+
onprogress={handleProgress}
|
| 1339 |
+
onerror={handleAudioError}
|
| 1340 |
+
class="hidden"
|
| 1341 |
+
></audio>
|
| 1342 |
+
|
| 1343 |
+
{#if !headless}
|
| 1344 |
+
<div
|
| 1345 |
+
class="audio-player-backdrop fixed inset-x-0 bottom-0 z-50 px-4 pt-16 pb-5 sm:px-6 sm:pt-16 sm:pb-6"
|
| 1346 |
+
bind:this={containerElement}
|
| 1347 |
+
>
|
| 1348 |
+
<div class="relative mx-auto w-full max-w-screen-2xl">
|
| 1349 |
+
{#if $ffmpegBanner.phase !== 'idle' || $activeTrackDownloads.length > 0}
|
| 1350 |
+
<div
|
| 1351 |
+
class="pointer-events-none absolute top-0 right-0 left-0 -translate-y-full transform pb-4"
|
| 1352 |
+
>
|
| 1353 |
+
<div class="mx-auto flex w-full max-w-2xl flex-col gap-2 px-4">
|
| 1354 |
+
{#if $ffmpegBanner.phase !== 'idle'}
|
| 1355 |
+
<div
|
| 1356 |
+
class="ffmpeg-banner pointer-events-auto rounded-2xl border px-4 py-3 text-sm text-blue-100 shadow-xl"
|
| 1357 |
+
>
|
| 1358 |
+
<div class="flex items-start gap-3">
|
| 1359 |
+
<div class="min-w-0 flex-1">
|
| 1360 |
+
<p class="leading-5 font-semibold text-blue-50">
|
| 1361 |
+
Downloading FFmpeg
|
| 1362 |
+
{#if formatMegabytes($ffmpegBanner.totalBytes)}
|
| 1363 |
+
<span class="text-blue-100/80">
|
| 1364 |
+
({formatMegabytes($ffmpegBanner.totalBytes)})</span
|
| 1365 |
+
>
|
| 1366 |
+
{/if}
|
| 1367 |
+
</p>
|
| 1368 |
+
{#if $ffmpegBanner.phase === 'countdown'}
|
| 1369 |
+
<p class="mt-1 text-xs text-blue-100/80">
|
| 1370 |
+
Starting in {$ffmpegBanner.countdownSeconds} seconds…
|
| 1371 |
+
</p>
|
| 1372 |
+
{:else if $ffmpegBanner.phase === 'loading'}
|
| 1373 |
+
<p class="mt-1 text-xs text-blue-100/80">
|
| 1374 |
+
Preparing encoder… {formatPercent($ffmpegBanner.progress)}
|
| 1375 |
+
</p>
|
| 1376 |
+
{:else if $ffmpegBanner.phase === 'ready'}
|
| 1377 |
+
<p class="mt-1 text-xs text-blue-100/80">FFmpeg is ready to use.</p>
|
| 1378 |
+
{:else if $ffmpegBanner.phase === 'error'}
|
| 1379 |
+
<p class="mt-1 text-xs text-red-200">
|
| 1380 |
+
{$ffmpegBanner.error ?? 'Failed to load FFmpeg.'}
|
| 1381 |
+
</p>
|
| 1382 |
+
{/if}
|
| 1383 |
+
</div>
|
| 1384 |
+
{#if $ffmpegBanner.dismissible}
|
| 1385 |
+
<button
|
| 1386 |
+
onclick={() => downloadUiStore.dismissFfmpeg()}
|
| 1387 |
+
class="rounded-full p-1 text-blue-100/70 transition-colors hover:bg-blue-500/20 hover:text-blue-50"
|
| 1388 |
+
aria-label="Dismiss FFmpeg download"
|
| 1389 |
+
>
|
| 1390 |
+
<X size={16} />
|
| 1391 |
+
</button>
|
| 1392 |
+
{/if}
|
| 1393 |
+
</div>
|
| 1394 |
+
{#if $ffmpegBanner.phase === 'loading'}
|
| 1395 |
+
<div class="mt-3 h-1.5 overflow-hidden rounded-full bg-blue-500/20">
|
| 1396 |
+
<div
|
| 1397 |
+
class="h-full rounded-full bg-blue-400 transition-all duration-200"
|
| 1398 |
+
style="width: {Math.min(Math.max($ffmpegBanner.progress * 100, 6), 100)}%"
|
| 1399 |
+
></div>
|
| 1400 |
+
</div>
|
| 1401 |
+
{/if}
|
| 1402 |
+
</div>
|
| 1403 |
+
{/if}
|
| 1404 |
+
|
| 1405 |
+
{#each $activeTrackDownloads as task (task.id)}
|
| 1406 |
+
<div
|
| 1407 |
+
class="download-popup pointer-events-auto rounded-2xl border px-4 py-3 text-sm text-gray-100 shadow-xl"
|
| 1408 |
+
>
|
| 1409 |
+
<div class="flex items-start gap-3">
|
| 1410 |
+
<div class="flex min-w-0 flex-1 flex-col gap-1">
|
| 1411 |
+
<p class="flex items-center gap-2 text-sm font-semibold text-gray-50">
|
| 1412 |
+
{#if task.progress < 0.02}
|
| 1413 |
+
<LoaderCircle size={16} class="animate-spin text-blue-300" />
|
| 1414 |
+
{:else}
|
| 1415 |
+
<Download size={16} class="text-blue-300" />
|
| 1416 |
+
{/if}
|
| 1417 |
+
<span class="truncate">{task.title}</span>
|
| 1418 |
+
</p>
|
| 1419 |
+
{#if task.subtitle}
|
| 1420 |
+
<p class="truncate text-xs text-gray-400">{task.subtitle}</p>
|
| 1421 |
+
{/if}
|
| 1422 |
+
<div class="flex flex-wrap items-center gap-2 text-xs text-gray-400">
|
| 1423 |
+
<span>{formatTransferStatus(task.receivedBytes, task.totalBytes)}</span>
|
| 1424 |
+
<span aria-hidden="true">•</span>
|
| 1425 |
+
<span>{formatPercent(task.progress)}</span>
|
| 1426 |
+
</div>
|
| 1427 |
+
</div>
|
| 1428 |
+
<button
|
| 1429 |
+
onclick={() =>
|
| 1430 |
+
task.cancellable
|
| 1431 |
+
? downloadUiStore.cancelTrackDownload(task.id)
|
| 1432 |
+
: downloadUiStore.dismissTrackTask(task.id)}
|
| 1433 |
+
class="rounded-full p-1 text-gray-400 transition-colors hover:bg-gray-800 hover:text-white"
|
| 1434 |
+
aria-label={task.cancellable
|
| 1435 |
+
? `Cancel download for ${task.title}`
|
| 1436 |
+
: `Dismiss download for ${task.title}`}
|
| 1437 |
+
>
|
| 1438 |
+
<X size={16} />
|
| 1439 |
+
</button>
|
| 1440 |
+
</div>
|
| 1441 |
+
<div class="mt-3 h-1.5 overflow-hidden rounded-full bg-gray-800">
|
| 1442 |
+
<div
|
| 1443 |
+
class="h-full rounded-full bg-blue-500 transition-all duration-200"
|
| 1444 |
+
style="width: {Math.min(Math.max(task.progress * 100, 4), 100)}%"
|
| 1445 |
+
></div>
|
| 1446 |
+
</div>
|
| 1447 |
+
</div>
|
| 1448 |
+
{/each}
|
| 1449 |
+
</div>
|
| 1450 |
+
</div>
|
| 1451 |
+
{/if}
|
| 1452 |
+
<div class="audio-player-glass overflow-hidden rounded-2xl border shadow-2xl">
|
| 1453 |
+
<div class="relative px-4 py-3">
|
| 1454 |
+
{#if $playerStore.currentTrack}
|
| 1455 |
+
<!-- Progress Bar -->
|
| 1456 |
+
<div class="mb-3">
|
| 1457 |
+
<button
|
| 1458 |
+
bind:this={seekBarElement}
|
| 1459 |
+
onmousedown={handleSeekStart}
|
| 1460 |
+
ontouchstart={handleSeekStart}
|
| 1461 |
+
class="group relative h-1 w-full cursor-pointer overflow-hidden rounded-full bg-gray-700"
|
| 1462 |
+
type="button"
|
| 1463 |
+
aria-label="Seek position"
|
| 1464 |
+
>
|
| 1465 |
+
<div
|
| 1466 |
+
class="pointer-events-none absolute inset-y-0 left-0 bg-blue-400/30 transition-all"
|
| 1467 |
+
style="width: {bufferedPercent}%"
|
| 1468 |
+
aria-hidden="true"
|
| 1469 |
+
></div>
|
| 1470 |
+
<div
|
| 1471 |
+
class="pointer-events-none absolute inset-y-0 left-0 bg-blue-500 transition-all"
|
| 1472 |
+
style="width: {getPercent($playerStore.currentTime, $playerStore.duration)}%"
|
| 1473 |
+
aria-hidden="true"
|
| 1474 |
+
></div>
|
| 1475 |
+
<div
|
| 1476 |
+
class="pointer-events-none absolute top-1/2 h-3 w-3 -translate-y-1/2 rounded-full bg-blue-500 opacity-0 transition-opacity group-hover:opacity-100"
|
| 1477 |
+
style="left: {getPercent($playerStore.currentTime, $playerStore.duration)}%"
|
| 1478 |
+
aria-hidden="true"
|
| 1479 |
+
></div>
|
| 1480 |
+
</button>
|
| 1481 |
+
<div class="mt-1 flex justify-between text-xs text-gray-400">
|
| 1482 |
+
<span>{formatTime($playerStore.currentTime)}</span>
|
| 1483 |
+
<span>{formatTime($playerStore.duration)}</span>
|
| 1484 |
+
</div>
|
| 1485 |
+
</div>
|
| 1486 |
+
|
| 1487 |
+
<div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
| 1488 |
+
<!-- Track Info -->
|
| 1489 |
+
{#if $playerStore.currentTrack}
|
| 1490 |
+
<div class="flex min-w-0 items-center gap-3 sm:flex-1">
|
| 1491 |
+
{#if !isSonglinkTrack($playerStore.currentTrack)}
|
| 1492 |
+
<!-- Only show album cover for regular tracks -->
|
| 1493 |
+
{#if asTrack($playerStore.currentTrack).album.videoCover}
|
| 1494 |
+
<video
|
| 1495 |
+
src={losslessAPI.getVideoCoverUrl(asTrack($playerStore.currentTrack).album.videoCover!, '640')}
|
| 1496 |
+
autoplay
|
| 1497 |
+
loop
|
| 1498 |
+
muted
|
| 1499 |
+
playsinline
|
| 1500 |
+
class="h-16 w-16 flex-shrink-0 rounded-md object-cover"
|
| 1501 |
+
></video>
|
| 1502 |
+
{:else if asTrack($playerStore.currentTrack).album.cover}
|
| 1503 |
+
<img
|
| 1504 |
+
src={losslessAPI.getCoverUrl(asTrack($playerStore.currentTrack).album.cover!, '640')}
|
| 1505 |
+
alt={$playerStore.currentTrack.title}
|
| 1506 |
+
class="h-16 w-16 flex-shrink-0 rounded-md object-cover"
|
| 1507 |
+
/>
|
| 1508 |
+
{/if}
|
| 1509 |
+
{/if}
|
| 1510 |
+
<div class="min-w-0 flex-1">
|
| 1511 |
+
<h3 class="truncate font-semibold text-white w-full">
|
| 1512 |
+
{$playerStore.currentTrack.title}{!isSonglinkTrack($playerStore.currentTrack) && asTrack($playerStore.currentTrack).version ? ` (${asTrack($playerStore.currentTrack).version})` : ''}
|
| 1513 |
+
</h3>
|
| 1514 |
+
{#if isSonglinkTrack($playerStore.currentTrack)}
|
| 1515 |
+
<!-- Display for SonglinkTrack -->
|
| 1516 |
+
<p class="truncate text-sm text-gray-400 w-full">
|
| 1517 |
+
{$playerStore.currentTrack.artistName}
|
| 1518 |
+
</p>
|
| 1519 |
+
{:else}
|
| 1520 |
+
<!-- Display for regular Track -->
|
| 1521 |
+
<a
|
| 1522 |
+
href={`/artist/${asTrack($playerStore.currentTrack).artist.id}`}
|
| 1523 |
+
class="truncate text-sm text-gray-400 hover:text-blue-400 hover:underline inline-block w-full"
|
| 1524 |
+
data-sveltekit-preload-data
|
| 1525 |
+
>
|
| 1526 |
+
{formatArtists(asTrack($playerStore.currentTrack).artists)}
|
| 1527 |
+
</a>
|
| 1528 |
+
<p class="truncate text-xs text-gray-500 w-full">
|
| 1529 |
+
<a
|
| 1530 |
+
href={`/album/${asTrack($playerStore.currentTrack).album.id}`}
|
| 1531 |
+
class="hover:text-blue-400 hover:underline"
|
| 1532 |
+
data-sveltekit-preload-data
|
| 1533 |
+
>
|
| 1534 |
+
{asTrack($playerStore.currentTrack).album.title}
|
| 1535 |
+
</a>
|
| 1536 |
+
{#if currentPlaybackQuality}
|
| 1537 |
+
<span class="mx-1" aria-hidden="true">•</span>
|
| 1538 |
+
<span>{formatQualityLabel(currentPlaybackQuality)}</span>
|
| 1539 |
+
{/if}
|
| 1540 |
+
{#if currentPlaybackQuality && asTrack($playerStore.currentTrack).audioQuality && currentPlaybackQuality !== asTrack($playerStore.currentTrack).audioQuality}
|
| 1541 |
+
<span class="mx-1 text-gray-600" aria-hidden="true">•</span>
|
| 1542 |
+
<span class="text-gray-500">
|
| 1543 |
+
({formatQualityLabel(asTrack($playerStore.currentTrack).audioQuality)} available)
|
| 1544 |
+
</span>
|
| 1545 |
+
{/if}
|
| 1546 |
+
{#if bitDepthLabel}
|
| 1547 |
+
<span class="mx-1 text-gray-600" aria-hidden="true">•</span>
|
| 1548 |
+
<span>{bitDepthLabel}</span>
|
| 1549 |
+
{/if}
|
| 1550 |
+
{#if sampleRateLabel}
|
| 1551 |
+
<span class="mx-1 text-gray-600" aria-hidden="true">•</span>
|
| 1552 |
+
<span>{sampleRateLabel}</span>
|
| 1553 |
+
{/if}
|
| 1554 |
+
</p>
|
| 1555 |
+
{/if}
|
| 1556 |
+
</div>
|
| 1557 |
+
</div>
|
| 1558 |
+
{/if}
|
| 1559 |
+
|
| 1560 |
+
<div class="flex flex-nowrap items-center justify-between gap-2 sm:gap-4">
|
| 1561 |
+
<!-- Controls -->
|
| 1562 |
+
<div class="flex items-center justify-center gap-1 sm:gap-2">
|
| 1563 |
+
<button
|
| 1564 |
+
onclick={handlePrevious}
|
| 1565 |
+
class="p-1.5 sm:p-2 text-gray-400 transition-colors hover:text-white disabled:opacity-50"
|
| 1566 |
+
disabled={false}
|
| 1567 |
+
aria-label="Previous track"
|
| 1568 |
+
>
|
| 1569 |
+
<SkipBack size={18} class="sm:w-5 sm:h-5" />
|
| 1570 |
+
</button>
|
| 1571 |
+
|
| 1572 |
+
<button
|
| 1573 |
+
onclick={() => playerStore.togglePlay()}
|
| 1574 |
+
class="rounded-full bg-white p-2.5 sm:p-3 text-gray-900 transition-transform hover:scale-105"
|
| 1575 |
+
aria-label={$playerStore.isPlaying ? 'Pause' : 'Play'}
|
| 1576 |
+
>
|
| 1577 |
+
{#if $playerStore.isPlaying}
|
| 1578 |
+
<Pause size={20} class="sm:w-6 sm:h-6" fill="currentColor" />
|
| 1579 |
+
{:else}
|
| 1580 |
+
<Play size={20} class="sm:w-6 sm:h-6" fill="currentColor" />
|
| 1581 |
+
{/if}
|
| 1582 |
+
</button>
|
| 1583 |
+
|
| 1584 |
+
<button
|
| 1585 |
+
onclick={() => playerStore.next()}
|
| 1586 |
+
class="p-1.5 sm:p-2 text-gray-400 transition-colors hover:text-white disabled:opacity-50"
|
| 1587 |
+
disabled={$playerStore.queueIndex >= $playerStore.queue.length - 1}
|
| 1588 |
+
aria-label="Next track"
|
| 1589 |
+
>
|
| 1590 |
+
<SkipForward size={18} class="sm:w-5 sm:h-5" />
|
| 1591 |
+
</button>
|
| 1592 |
+
</div>
|
| 1593 |
+
|
| 1594 |
+
<!-- Queue Toggle -->
|
| 1595 |
+
<div class="flex items-center gap-1 sm:gap-2">
|
| 1596 |
+
<button
|
| 1597 |
+
onclick={handleDownloadCurrentTrack}
|
| 1598 |
+
class="player-toggle-button p-1.5 sm:p-2"
|
| 1599 |
+
aria-label="Download current track"
|
| 1600 |
+
type="button"
|
| 1601 |
+
disabled={!$playerStore.currentTrack || isDownloadingCurrentTrack}
|
| 1602 |
+
>
|
| 1603 |
+
{#if isDownloadingCurrentTrack}
|
| 1604 |
+
<LoaderCircle size={16} class="sm:w-[18px] sm:h-[18px] animate-spin" />
|
| 1605 |
+
{:else}
|
| 1606 |
+
<Download size={16} class="sm:w-[18px] sm:h-[18px]" />
|
| 1607 |
+
{/if}
|
| 1608 |
+
<span class="hidden sm:inline">Download</span>
|
| 1609 |
+
</button>
|
| 1610 |
+
<button
|
| 1611 |
+
onclick={() => lyricsStore.toggle()}
|
| 1612 |
+
class="player-toggle-button p-1.5 sm:p-2 {$lyricsStore.open
|
| 1613 |
+
? 'player-toggle-button--active'
|
| 1614 |
+
: ''}"
|
| 1615 |
+
aria-label={$lyricsStore.open ? 'Hide lyrics popup' : 'Show lyrics popup'}
|
| 1616 |
+
aria-expanded={$lyricsStore.open}
|
| 1617 |
+
type="button"
|
| 1618 |
+
>
|
| 1619 |
+
<ScrollText size={16} class="sm:w-[18px] sm:h-[18px]" />
|
| 1620 |
+
<span class="hidden sm:inline">Lyrics</span>
|
| 1621 |
+
</button>
|
| 1622 |
+
<button
|
| 1623 |
+
onclick={toggleQueuePanel}
|
| 1624 |
+
class="player-toggle-button p-1.5 sm:p-2 {showQueuePanel
|
| 1625 |
+
? 'player-toggle-button--active'
|
| 1626 |
+
: ''}"
|
| 1627 |
+
aria-label="Toggle queue panel"
|
| 1628 |
+
aria-expanded={showQueuePanel}
|
| 1629 |
+
type="button"
|
| 1630 |
+
>
|
| 1631 |
+
<ListMusic size={16} class="sm:w-[18px] sm:h-[18px]" />
|
| 1632 |
+
<span class="hidden sm:inline">Queue ({$playerStore.queue.length})</span>
|
| 1633 |
+
</button>
|
| 1634 |
+
</div>
|
| 1635 |
+
|
| 1636 |
+
<!-- Volume Control -->
|
| 1637 |
+
<div class="hidden sm:flex items-center gap-2">
|
| 1638 |
+
<button
|
| 1639 |
+
onclick={toggleMute}
|
| 1640 |
+
class="p-2 text-gray-400 transition-colors hover:text-white"
|
| 1641 |
+
aria-label={isMuted ? 'Unmute' : 'Mute'}
|
| 1642 |
+
>
|
| 1643 |
+
{#if isMuted || $playerStore.volume === 0}
|
| 1644 |
+
<VolumeX size={20} />
|
| 1645 |
+
{:else}
|
| 1646 |
+
<Volume2 size={20} />
|
| 1647 |
+
{/if}
|
| 1648 |
+
</button>
|
| 1649 |
+
<input
|
| 1650 |
+
type="range"
|
| 1651 |
+
min="0"
|
| 1652 |
+
max="1"
|
| 1653 |
+
step="0.01"
|
| 1654 |
+
value={$playerStore.volume}
|
| 1655 |
+
oninput={handleVolumeChange}
|
| 1656 |
+
class="h-1 w-24 cursor-pointer appearance-none rounded-lg bg-gray-700 accent-white"
|
| 1657 |
+
aria-label="Volume"
|
| 1658 |
+
/>
|
| 1659 |
+
</div>
|
| 1660 |
+
</div>
|
| 1661 |
+
</div>
|
| 1662 |
+
|
| 1663 |
+
{#if showQueuePanel}
|
| 1664 |
+
<div
|
| 1665 |
+
class="queue-panel mt-4 space-y-3 rounded-2xl border p-4 text-sm shadow-inner"
|
| 1666 |
+
transition:slide={{ duration: 220, easing: cubicOut }}
|
| 1667 |
+
>
|
| 1668 |
+
<div class="flex items-center justify-between gap-2">
|
| 1669 |
+
<div class="flex items-center gap-2 text-gray-300">
|
| 1670 |
+
<ListMusic size={18} />
|
| 1671 |
+
<span class="font-medium">Playback Queue</span>
|
| 1672 |
+
<span class="rounded-full bg-gray-800 px-2 py-0.5 text-xs text-gray-400">
|
| 1673 |
+
{$playerStore.queue.length}
|
| 1674 |
+
</span>
|
| 1675 |
+
</div>
|
| 1676 |
+
<div class="flex items-center gap-2">
|
| 1677 |
+
<button
|
| 1678 |
+
onclick={handleShuffleQueue}
|
| 1679 |
+
class="flex items-center gap-1 rounded-full border border-transparent px-3 py-1 text-xs tracking-wide text-gray-400 uppercase transition-colors hover:border-blue-500 hover:text-blue-200 disabled:opacity-40"
|
| 1680 |
+
type="button"
|
| 1681 |
+
disabled={$playerStore.queue.length <= 1}
|
| 1682 |
+
>
|
| 1683 |
+
<Shuffle size={14} />
|
| 1684 |
+
Shuffle
|
| 1685 |
+
</button>
|
| 1686 |
+
<button
|
| 1687 |
+
onclick={clearQueue}
|
| 1688 |
+
class="flex items-center gap-1 rounded-full border border-transparent px-3 py-1 text-xs tracking-wide text-gray-400 uppercase transition-colors hover:border-red-500 hover:text-red-400"
|
| 1689 |
+
type="button"
|
| 1690 |
+
disabled={$playerStore.queue.length === 0}
|
| 1691 |
+
>
|
| 1692 |
+
<Trash2 size={14} />
|
| 1693 |
+
Clear
|
| 1694 |
+
</button>
|
| 1695 |
+
<button
|
| 1696 |
+
onclick={closeQueuePanel}
|
| 1697 |
+
class="rounded-full p-1 text-gray-400 transition-colors hover:text-white"
|
| 1698 |
+
aria-label="Close queue panel"
|
| 1699 |
+
>
|
| 1700 |
+
<X size={16} />
|
| 1701 |
+
</button>
|
| 1702 |
+
</div>
|
| 1703 |
+
</div>
|
| 1704 |
+
|
| 1705 |
+
{#if $playerStore.queue.length > 0}
|
| 1706 |
+
<ul class="max-h-60 space-y-2 overflow-y-auto pr-1">
|
| 1707 |
+
{#each $playerStore.queue as queuedTrack, index}
|
| 1708 |
+
<li>
|
| 1709 |
+
<div
|
| 1710 |
+
onclick={() => playFromQueue(index)}
|
| 1711 |
+
onkeydown={(event) => {
|
| 1712 |
+
if (event.key === 'Enter' || event.key === ' ') {
|
| 1713 |
+
event.preventDefault();
|
| 1714 |
+
playFromQueue(index);
|
| 1715 |
+
}
|
| 1716 |
+
}}
|
| 1717 |
+
tabindex="0"
|
| 1718 |
+
role="button"
|
| 1719 |
+
class="group flex w-full cursor-pointer items-center gap-3 rounded-xl px-3 py-2 text-left transition-colors {index ===
|
| 1720 |
+
$playerStore.queueIndex
|
| 1721 |
+
? 'bg-blue-500/10 text-white'
|
| 1722 |
+
: 'text-gray-200 hover:bg-gray-800/70'}"
|
| 1723 |
+
>
|
| 1724 |
+
<span
|
| 1725 |
+
class="w-6 text-xs font-semibold text-gray-500 group-hover:text-gray-300"
|
| 1726 |
+
>
|
| 1727 |
+
{index + 1}
|
| 1728 |
+
</span>
|
| 1729 |
+
<div class="min-w-0 flex-1">
|
| 1730 |
+
<p class="truncate text-sm font-medium">
|
| 1731 |
+
{queuedTrack.title}{!isSonglinkTrack(queuedTrack) && asTrack(queuedTrack).version ? ` (${asTrack(queuedTrack).version})` : ''}
|
| 1732 |
+
</p>
|
| 1733 |
+
{#if isSonglinkTrack(queuedTrack)}
|
| 1734 |
+
<p class="truncate text-xs text-gray-400">
|
| 1735 |
+
{queuedTrack.artistName}
|
| 1736 |
+
</p>
|
| 1737 |
+
{:else}
|
| 1738 |
+
<a
|
| 1739 |
+
href={`/artist/${asTrack(queuedTrack).artist.id}`}
|
| 1740 |
+
onclick={(e) => e.stopPropagation()}
|
| 1741 |
+
class="truncate text-xs text-gray-400 hover:text-blue-400 hover:underline inline-block"
|
| 1742 |
+
data-sveltekit-preload-data
|
| 1743 |
+
>
|
| 1744 |
+
{formatArtists(asTrack(queuedTrack).artists)}
|
| 1745 |
+
</a>
|
| 1746 |
+
{/if}
|
| 1747 |
+
</div>
|
| 1748 |
+
<button
|
| 1749 |
+
onclick={(event) => removeFromQueue(index, event)}
|
| 1750 |
+
class="rounded-full p-1 text-gray-500 transition-colors hover:text-red-400"
|
| 1751 |
+
aria-label={`Remove ${queuedTrack.title} from queue`}
|
| 1752 |
+
type="button"
|
| 1753 |
+
>
|
| 1754 |
+
<X size={14} />
|
| 1755 |
+
</button>
|
| 1756 |
+
</div>
|
| 1757 |
+
</li>
|
| 1758 |
+
{/each}
|
| 1759 |
+
</ul>
|
| 1760 |
+
{:else}
|
| 1761 |
+
<p
|
| 1762 |
+
class="rounded-lg border border-dashed border-gray-700 bg-gray-900/70 px-3 py-8 text-center text-gray-400"
|
| 1763 |
+
>
|
| 1764 |
+
Queue is empty
|
| 1765 |
+
</p>
|
| 1766 |
+
{/if}
|
| 1767 |
+
</div>
|
| 1768 |
+
{/if}
|
| 1769 |
+
|
| 1770 |
+
{#if $playerStore.currentTrack && $playerStore.isLoading}
|
| 1771 |
+
<div class="loading-overlay">
|
| 1772 |
+
<div class="loading-equalizer" aria-hidden="true">
|
| 1773 |
+
<span class="bar" style="animation-delay: 0ms"></span>
|
| 1774 |
+
<span class="bar" style="animation-delay: 150ms"></span>
|
| 1775 |
+
<span class="bar" style="animation-delay: 300ms"></span>
|
| 1776 |
+
<span class="bar" style="animation-delay: 450ms"></span>
|
| 1777 |
+
</div>
|
| 1778 |
+
<p class="text-sm font-medium text-gray-200">Loading track…</p>
|
| 1779 |
+
</div>
|
| 1780 |
+
{/if}
|
| 1781 |
+
{:else}
|
| 1782 |
+
<div class="flex h-20 items-center justify-center text-sm text-gray-400">
|
| 1783 |
+
Nothing is playing
|
| 1784 |
+
</div>
|
| 1785 |
+
{/if}
|
| 1786 |
+
</div>
|
| 1787 |
+
</div>
|
| 1788 |
+
</div>
|
| 1789 |
+
</div>
|
| 1790 |
+
{/if}
|
| 1791 |
+
|
| 1792 |
+
<style>
|
| 1793 |
+
.audio-player-glass {
|
| 1794 |
+
background: transparent;
|
| 1795 |
+
border-color: rgba(148, 163, 184, 0.2);
|
| 1796 |
+
backdrop-filter: blur(var(--perf-blur-high, 32px)) saturate(var(--perf-saturate, 160%));
|
| 1797 |
+
-webkit-backdrop-filter: blur(var(--perf-blur-high, 32px)) saturate(var(--perf-saturate, 160%));
|
| 1798 |
+
box-shadow:
|
| 1799 |
+
0 30px 80px rgba(2, 6, 23, 0.6),
|
| 1800 |
+
0 4px 18px rgba(15, 23, 42, 0.45),
|
| 1801 |
+
inset 0 1px 0 rgba(255, 255, 255, 0.06);
|
| 1802 |
+
transition:
|
| 1803 |
+
border-color 1.2s cubic-bezier(0.4, 0, 0.2, 1),
|
| 1804 |
+
box-shadow 0.3s ease;
|
| 1805 |
+
}
|
| 1806 |
+
|
| 1807 |
+
.queue-panel {
|
| 1808 |
+
background: transparent;
|
| 1809 |
+
border-color: rgba(148, 163, 184, 0.2);
|
| 1810 |
+
backdrop-filter: blur(var(--perf-blur-medium, 28px)) saturate(var(--perf-saturate, 160%));
|
| 1811 |
+
-webkit-backdrop-filter: blur(var(--perf-blur-medium, 28px))
|
| 1812 |
+
saturate(var(--perf-saturate, 160%));
|
| 1813 |
+
box-shadow:
|
| 1814 |
+
0 8px 24px rgba(2, 6, 23, 0.4),
|
| 1815 |
+
inset 0 1px 0 rgba(255, 255, 255, 0.05);
|
| 1816 |
+
transition:
|
| 1817 |
+
border-color 1.2s cubic-bezier(0.4, 0, 0.2, 1),
|
| 1818 |
+
box-shadow 0.3s ease;
|
| 1819 |
+
}
|
| 1820 |
+
|
| 1821 |
+
.ffmpeg-banner {
|
| 1822 |
+
background: transparent;
|
| 1823 |
+
border-color: var(--bloom-accent, rgba(59, 130, 246, 0.7));
|
| 1824 |
+
backdrop-filter: blur(var(--perf-blur-high, 32px)) saturate(var(--perf-saturate, 160%));
|
| 1825 |
+
-webkit-backdrop-filter: blur(var(--perf-blur-high, 32px)) saturate(var(--perf-saturate, 160%));
|
| 1826 |
+
box-shadow:
|
| 1827 |
+
0 12px 32px rgba(2, 6, 23, 0.5),
|
| 1828 |
+
0 2px 8px rgba(59, 130, 246, 0.2),
|
| 1829 |
+
inset 0 1px 0 rgba(255, 255, 255, 0.08),
|
| 1830 |
+
inset 0 0 30px rgba(59, 130, 246, 0.08);
|
| 1831 |
+
transition:
|
| 1832 |
+
border-color 1.2s cubic-bezier(0.4, 0, 0.2, 1),
|
| 1833 |
+
box-shadow 0.3s ease;
|
| 1834 |
+
}
|
| 1835 |
+
|
| 1836 |
+
.download-popup {
|
| 1837 |
+
background: transparent;
|
| 1838 |
+
border-color: rgba(148, 163, 184, 0.2);
|
| 1839 |
+
backdrop-filter: blur(var(--perf-blur-high, 32px)) saturate(var(--perf-saturate, 160%));
|
| 1840 |
+
-webkit-backdrop-filter: blur(var(--perf-blur-high, 32px)) saturate(var(--perf-saturate, 160%));
|
| 1841 |
+
box-shadow:
|
| 1842 |
+
0 12px 32px rgba(2, 6, 23, 0.5),
|
| 1843 |
+
0 2px 8px rgba(15, 23, 42, 0.35),
|
| 1844 |
+
inset 0 1px 0 rgba(255, 255, 255, 0.06);
|
| 1845 |
+
transition:
|
| 1846 |
+
border-color 1.2s cubic-bezier(0.4, 0, 0.2, 1),
|
| 1847 |
+
box-shadow 0.3s ease;
|
| 1848 |
+
}
|
| 1849 |
+
|
| 1850 |
+
.audio-player-backdrop {
|
| 1851 |
+
isolation: isolate;
|
| 1852 |
+
}
|
| 1853 |
+
|
| 1854 |
+
.audio-player-backdrop::before {
|
| 1855 |
+
content: '';
|
| 1856 |
+
position: absolute;
|
| 1857 |
+
inset: 0;
|
| 1858 |
+
pointer-events: none;
|
| 1859 |
+
z-index: 0;
|
| 1860 |
+
backdrop-filter: blur(20px);
|
| 1861 |
+
-webkit-backdrop-filter: blur(20px);
|
| 1862 |
+
mask: linear-gradient(to bottom, transparent 0%, black 25%);
|
| 1863 |
+
}
|
| 1864 |
+
|
| 1865 |
+
.audio-player-backdrop > * {
|
| 1866 |
+
position: relative;
|
| 1867 |
+
z-index: 1;
|
| 1868 |
+
}
|
| 1869 |
+
|
| 1870 |
+
input[type='range']::-webkit-slider-thumb {
|
| 1871 |
+
appearance: none;
|
| 1872 |
+
width: 12px;
|
| 1873 |
+
height: 12px;
|
| 1874 |
+
background: white;
|
| 1875 |
+
border-radius: 50%;
|
| 1876 |
+
cursor: pointer;
|
| 1877 |
+
}
|
| 1878 |
+
|
| 1879 |
+
input[type='range']::-moz-range-thumb {
|
| 1880 |
+
width: 12px;
|
| 1881 |
+
height: 12px;
|
| 1882 |
+
background: white;
|
| 1883 |
+
border-radius: 50%;
|
| 1884 |
+
cursor: pointer;
|
| 1885 |
+
border: none;
|
| 1886 |
+
}
|
| 1887 |
+
|
| 1888 |
+
.loading-overlay {
|
| 1889 |
+
position: absolute;
|
| 1890 |
+
inset: 0;
|
| 1891 |
+
display: flex;
|
| 1892 |
+
flex-direction: column;
|
| 1893 |
+
align-items: center;
|
| 1894 |
+
justify-content: center;
|
| 1895 |
+
gap: 0.75rem;
|
| 1896 |
+
background: rgba(17, 24, 39, 0.65);
|
| 1897 |
+
backdrop-filter: blur(6px);
|
| 1898 |
+
}
|
| 1899 |
+
|
| 1900 |
+
.loading-equalizer {
|
| 1901 |
+
display: flex;
|
| 1902 |
+
align-items: flex-end;
|
| 1903 |
+
gap: 0.4rem;
|
| 1904 |
+
height: 1.75rem;
|
| 1905 |
+
}
|
| 1906 |
+
|
| 1907 |
+
.loading-equalizer .bar {
|
| 1908 |
+
width: 0.3rem;
|
| 1909 |
+
height: 0.6rem;
|
| 1910 |
+
border-radius: 9999px;
|
| 1911 |
+
background: rgba(255, 255, 255, 0.85);
|
| 1912 |
+
animation: equalize 1s ease-in-out infinite;
|
| 1913 |
+
}
|
| 1914 |
+
|
| 1915 |
+
@keyframes equalize {
|
| 1916 |
+
0% {
|
| 1917 |
+
opacity: 0.4;
|
| 1918 |
+
height: 0.5rem;
|
| 1919 |
+
}
|
| 1920 |
+
40% {
|
| 1921 |
+
opacity: 1;
|
| 1922 |
+
height: 1.7rem;
|
| 1923 |
+
}
|
| 1924 |
+
80% {
|
| 1925 |
+
opacity: 0.6;
|
| 1926 |
+
height: 0.8rem;
|
| 1927 |
+
}
|
| 1928 |
+
100% {
|
| 1929 |
+
opacity: 0.4;
|
| 1930 |
+
height: 0.5rem;
|
| 1931 |
+
}
|
| 1932 |
+
}
|
| 1933 |
+
|
| 1934 |
+
/* Dynamic button styles */
|
| 1935 |
+
button.rounded-full {
|
| 1936 |
+
transition:
|
| 1937 |
+
border-color 1.2s cubic-bezier(0.4, 0, 0.2, 1),
|
| 1938 |
+
color 0.2s ease,
|
| 1939 |
+
background 0.2s ease;
|
| 1940 |
+
}
|
| 1941 |
+
|
| 1942 |
+
button.rounded-full:hover {
|
| 1943 |
+
border-color: var(--bloom-accent, rgba(59, 130, 246, 0.7)) !important;
|
| 1944 |
+
}
|
| 1945 |
+
|
| 1946 |
+
/* Player toggle buttons (Lyrics, Queue) */
|
| 1947 |
+
.player-toggle-button {
|
| 1948 |
+
display: flex;
|
| 1949 |
+
align-items: center;
|
| 1950 |
+
gap: 0.5rem;
|
| 1951 |
+
border-radius: 9999px;
|
| 1952 |
+
border: 1px solid rgba(148, 163, 184, 0.25);
|
| 1953 |
+
background: transparent;
|
| 1954 |
+
backdrop-filter: blur(16px) saturate(140%);
|
| 1955 |
+
-webkit-backdrop-filter: blur(16px) saturate(140%);
|
| 1956 |
+
padding: 0.5rem 0.75rem;
|
| 1957 |
+
font-size: 0.875rem;
|
| 1958 |
+
color: rgba(209, 213, 219, 0.85);
|
| 1959 |
+
transition:
|
| 1960 |
+
border-color 200ms ease,
|
| 1961 |
+
color 200ms ease,
|
| 1962 |
+
box-shadow 200ms ease;
|
| 1963 |
+
}
|
| 1964 |
+
|
| 1965 |
+
.player-toggle-button:hover {
|
| 1966 |
+
border-color: var(--bloom-accent, rgba(96, 165, 250, 0.6));
|
| 1967 |
+
color: rgba(255, 255, 255, 0.95);
|
| 1968 |
+
}
|
| 1969 |
+
|
| 1970 |
+
.player-toggle-button--active {
|
| 1971 |
+
border-color: var(--bloom-accent, rgba(96, 165, 250, 0.7));
|
| 1972 |
+
color: rgba(255, 255, 255, 0.98);
|
| 1973 |
+
box-shadow: inset 0 0 20px rgba(96, 165, 250, 0.15);
|
| 1974 |
+
}
|
| 1975 |
+
</style>
|
src/lib/components/DynamicBackground.svelte
ADDED
|
@@ -0,0 +1,904 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<script lang="ts">
|
| 2 |
+
import { onDestroy, onMount } from 'svelte';
|
| 3 |
+
import { get } from 'svelte/store';
|
| 4 |
+
import { browser } from '$app/environment';
|
| 5 |
+
import { playerStore } from '$lib/stores/player';
|
| 6 |
+
import { effectivePerformanceLevel, animationsEnabled } from '$lib/stores/performance';
|
| 7 |
+
import { losslessAPI } from '$lib/api';
|
| 8 |
+
import {
|
| 9 |
+
extractPaletteFromImageWebGL,
|
| 10 |
+
type RGBColor
|
| 11 |
+
} from '$lib/utils/colorPalette';
|
| 12 |
+
|
| 13 |
+
// WebGL constants
|
| 14 |
+
const MASTER_PALETTE_SIZE = 40;
|
| 15 |
+
const MASTER_PALETTE_TEX_WIDTH = 8;
|
| 16 |
+
const MASTER_PALETTE_TEX_HEIGHT = 5;
|
| 17 |
+
const DISPLAY_GRID_WIDTH = 8;
|
| 18 |
+
const DISPLAY_GRID_HEIGHT = 5;
|
| 19 |
+
const STRETCHED_GRID_WIDTH = 32;
|
| 20 |
+
const STRETCHED_GRID_HEIGHT = 18;
|
| 21 |
+
const BLUR_DOWNSAMPLE_FACTOR = 26;
|
| 22 |
+
const SONG_PALETTE_TRANSITION_SPEED = 0.003;
|
| 23 |
+
const SCROLL_SPEED = 0.0005;
|
| 24 |
+
|
| 25 |
+
// Mobile performance settings
|
| 26 |
+
const MOBILE_BREAKPOINT = 768;
|
| 27 |
+
const MOBILE_TARGET_FPS = 30;
|
| 28 |
+
const DESKTOP_TARGET_FPS = 60;
|
| 29 |
+
const MOBILE_CANVAS_SIZE = 256;
|
| 30 |
+
const DESKTOP_CANVAS_SIZE = 512;
|
| 31 |
+
|
| 32 |
+
// Detect mobile viewport
|
| 33 |
+
const isMobileViewport = (): boolean => {
|
| 34 |
+
if (!browser) return false;
|
| 35 |
+
return window.innerWidth <= MOBILE_BREAKPOINT;
|
| 36 |
+
};
|
| 37 |
+
|
| 38 |
+
// Get appropriate canvas size based on device
|
| 39 |
+
const getCanvasSize = (): number => {
|
| 40 |
+
return isMobileViewport() ? MOBILE_CANVAS_SIZE : DESKTOP_CANVAS_SIZE;
|
| 41 |
+
};
|
| 42 |
+
|
| 43 |
+
// Frame rate limiter
|
| 44 |
+
let lastRenderTime = 0;
|
| 45 |
+
const getFrameInterval = (): number => {
|
| 46 |
+
const targetFps = isMobileViewport() ? MOBILE_TARGET_FPS : DESKTOP_TARGET_FPS;
|
| 47 |
+
return 1000 / targetFps;
|
| 48 |
+
};
|
| 49 |
+
|
| 50 |
+
// WebGL state
|
| 51 |
+
let webglCanvas: HTMLCanvasElement;
|
| 52 |
+
let gl: WebGLRenderingContext | null = null;
|
| 53 |
+
let glProgram: WebGLProgram | null = null;
|
| 54 |
+
let updateStateProgram: WebGLProgram | null = null;
|
| 55 |
+
let blurProgram: WebGLProgram | null = null;
|
| 56 |
+
|
| 57 |
+
let currentTargetMasterPalette = $state<RGBColor[]>([]);
|
| 58 |
+
let previousMasterPalette: RGBColor[] = [];
|
| 59 |
+
let songPaletteTransitionProgress = 1.0;
|
| 60 |
+
let scrollOffset = 0;
|
| 61 |
+
let globalAnimationId: number | null = null;
|
| 62 |
+
let lastFrameTime = 0;
|
| 63 |
+
|
| 64 |
+
// Textures and framebuffers
|
| 65 |
+
let cellStateTexture: WebGLTexture | null = null;
|
| 66 |
+
let cellStateFramebuffer: WebGLFramebuffer | null = null;
|
| 67 |
+
let paletteTexture: WebGLTexture | null = null;
|
| 68 |
+
let colorRenderTexture: WebGLTexture | null = null;
|
| 69 |
+
let colorRenderFramebuffer: WebGLFramebuffer | null = null;
|
| 70 |
+
let blurTexture1: WebGLTexture | null = null;
|
| 71 |
+
let blurFramebuffer1: WebGLFramebuffer | null = null;
|
| 72 |
+
let blurTexture2: WebGLTexture | null = null;
|
| 73 |
+
let blurFramebuffer2: WebGLFramebuffer | null = null;
|
| 74 |
+
|
| 75 |
+
let isPlaying = $state(false);
|
| 76 |
+
let enableAnimations = $state(true);
|
| 77 |
+
let performanceLevel = $state<'high' | 'medium' | 'low'>(get(effectivePerformanceLevel));
|
| 78 |
+
let backgroundEnabled = $state(performanceLevel !== 'low');
|
| 79 |
+
let requestToken = 0;
|
| 80 |
+
let latestState: PlayerStateShape = { currentTrack: null, isPlaying: false };
|
| 81 |
+
let currentCoverUrl: string | null = null;
|
| 82 |
+
let retryAttempts = 0;
|
| 83 |
+
let canvasVisible = $state(false);
|
| 84 |
+
let webglListenersAttached = false;
|
| 85 |
+
|
| 86 |
+
const MAX_RETRY_ATTEMPTS = 3;
|
| 87 |
+
const RETRY_DELAY_MS = 600;
|
| 88 |
+
|
| 89 |
+
const setCssVariables = (mostVibrantColor: RGBColor) => {
|
| 90 |
+
if (!browser) return;
|
| 91 |
+
const target = document.documentElement;
|
| 92 |
+
|
| 93 |
+
// Set lyrics palette color with boosted saturation
|
| 94 |
+
const [h, s, l] = rgbToHsl(mostVibrantColor.red, mostVibrantColor.green, mostVibrantColor.blue);
|
| 95 |
+
const boostedSat = Math.min(1.0, s * 1.2);
|
| 96 |
+
const [r, g, b] = hslToRgb(h, boostedSat, l);
|
| 97 |
+
|
| 98 |
+
target.style.setProperty('--lyplus-lyrics-palette', `rgb(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)})`);
|
| 99 |
+
};
|
| 100 |
+
|
| 101 |
+
const rgbToHsl = (r: number, g: number, b: number): [number, number, number] => {
|
| 102 |
+
r /= 255;
|
| 103 |
+
g /= 255;
|
| 104 |
+
b /= 255;
|
| 105 |
+
const max = Math.max(r, g, b);
|
| 106 |
+
const min = Math.min(r, g, b);
|
| 107 |
+
let h = 0;
|
| 108 |
+
let s = 0;
|
| 109 |
+
const l = (max + min) / 2;
|
| 110 |
+
|
| 111 |
+
if (max !== min) {
|
| 112 |
+
const d = max - min;
|
| 113 |
+
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
| 114 |
+
switch (max) {
|
| 115 |
+
case r: h = ((g - b) / d + (g < b ? 6 : 0)) / 6; break;
|
| 116 |
+
case g: h = ((b - r) / d + 2) / 6; break;
|
| 117 |
+
case b: h = ((r - g) / d + 4) / 6; break;
|
| 118 |
+
}
|
| 119 |
+
}
|
| 120 |
+
return [h, s, l];
|
| 121 |
+
};
|
| 122 |
+
|
| 123 |
+
const hslToRgb = (h: number, s: number, l: number): [number, number, number] => {
|
| 124 |
+
let r: number, g: number, b: number;
|
| 125 |
+
if (s === 0) {
|
| 126 |
+
r = g = b = l;
|
| 127 |
+
} else {
|
| 128 |
+
const hue2rgb = (p: number, q: number, t: number) => {
|
| 129 |
+
if (t < 0) t += 1;
|
| 130 |
+
if (t > 1) t -= 1;
|
| 131 |
+
if (t < 1/6) return p + (q - p) * 6 * t;
|
| 132 |
+
if (t < 1/2) return q;
|
| 133 |
+
if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
|
| 134 |
+
return p;
|
| 135 |
+
};
|
| 136 |
+
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
|
| 137 |
+
const p = 2 * l - q;
|
| 138 |
+
r = hue2rgb(p, q, h + 1/3);
|
| 139 |
+
g = hue2rgb(p, q, h);
|
| 140 |
+
b = hue2rgb(p, q, h - 1/3);
|
| 141 |
+
}
|
| 142 |
+
return [r * 255, g * 255, b * 255];
|
| 143 |
+
};
|
| 144 |
+
|
| 145 |
+
// WebGL Shader Sources
|
| 146 |
+
const vertexShaderSource = `
|
| 147 |
+
attribute vec2 a_position;
|
| 148 |
+
varying vec2 v_uv;
|
| 149 |
+
void main() {
|
| 150 |
+
v_uv = a_position * 0.5 + 0.5;
|
| 151 |
+
gl_Position = vec4(a_position, 0.0, 1.0);
|
| 152 |
+
}
|
| 153 |
+
`;
|
| 154 |
+
|
| 155 |
+
const updateStateShaderSource = `
|
| 156 |
+
precision mediump float;
|
| 157 |
+
uniform sampler2D u_currentStateTexture;
|
| 158 |
+
uniform float u_deltaTime;
|
| 159 |
+
uniform float u_time;
|
| 160 |
+
varying vec2 v_uv;
|
| 161 |
+
|
| 162 |
+
float random(vec2 st) {
|
| 163 |
+
return fract(sin(dot(st.xy, vec2(12.9898, 78.233))) * 43758.5453123);
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
void main() {
|
| 167 |
+
vec4 currentState = texture2D(u_currentStateTexture, v_uv);
|
| 168 |
+
float sourceIdx_norm = currentState.r;
|
| 169 |
+
float targetIdx_norm = currentState.g;
|
| 170 |
+
float progress = currentState.b;
|
| 171 |
+
float speed = currentState.a * 10.0;
|
| 172 |
+
|
| 173 |
+
progress += speed * u_deltaTime;
|
| 174 |
+
|
| 175 |
+
if (progress >= 1.0) {
|
| 176 |
+
progress = fract(progress);
|
| 177 |
+
sourceIdx_norm = targetIdx_norm;
|
| 178 |
+
vec2 seed = v_uv + vec2(u_time, progress);
|
| 179 |
+
float newTargetIdx = floor(random(seed) * 40.0);
|
| 180 |
+
targetIdx_norm = newTargetIdx / 39.0;
|
| 181 |
+
// Much slower cell transitions: 0.08-0.20 range (was 0.15-0.35)
|
| 182 |
+
speed = (random(seed + vec2(1.0)) * 0.12 + 0.08) * 0.48;
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
gl_FragColor = vec4(sourceIdx_norm, targetIdx_norm, progress, speed / 10.0);
|
| 186 |
+
}
|
| 187 |
+
`;
|
| 188 |
+
|
| 189 |
+
const fragmentShaderSource = `
|
| 190 |
+
precision mediump float;
|
| 191 |
+
uniform sampler2D u_paletteTexture;
|
| 192 |
+
uniform sampler2D u_cellStateTexture;
|
| 193 |
+
uniform float u_songPaletteTransitionProgress;
|
| 194 |
+
uniform float u_scrollOffset;
|
| 195 |
+
varying vec2 v_uv;
|
| 196 |
+
|
| 197 |
+
vec4 getColorFromMasterPalette(int index, float y_offset) {
|
| 198 |
+
float texY_row = floor(float(index) / 8.0);
|
| 199 |
+
float texX_col = mod(float(index), 8.0);
|
| 200 |
+
float u = (texX_col + 0.5) / 8.0;
|
| 201 |
+
float v = (texY_row + y_offset + 0.5) / 10.0;
|
| 202 |
+
return texture2D(u_paletteTexture, vec2(u, v));
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
vec4 getCellColor(vec2 uv) {
|
| 206 |
+
vec4 cellState = texture2D(u_cellStateTexture, uv);
|
| 207 |
+
int sourceColorIndex = int(cellState.r * 39.0 + 0.5);
|
| 208 |
+
int targetColorIndex = int(cellState.g * 39.0 + 0.5);
|
| 209 |
+
float fadeProgress = cellState.b;
|
| 210 |
+
|
| 211 |
+
vec4 prevPalette_source = getColorFromMasterPalette(sourceColorIndex, 0.0);
|
| 212 |
+
vec4 targetPalette_source = getColorFromMasterPalette(sourceColorIndex, 5.0);
|
| 213 |
+
vec4 colorA = mix(prevPalette_source, targetPalette_source, u_songPaletteTransitionProgress);
|
| 214 |
+
|
| 215 |
+
vec4 prevPalette_target = getColorFromMasterPalette(targetColorIndex, 0.0);
|
| 216 |
+
vec4 targetPalette_target = getColorFromMasterPalette(targetColorIndex, 5.0);
|
| 217 |
+
vec4 colorB = mix(prevPalette_target, targetPalette_target, u_songPaletteTransitionProgress);
|
| 218 |
+
|
| 219 |
+
return mix(colorA, colorB, fadeProgress);
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
void main() {
|
| 223 |
+
float scrolledX = v_uv.x - u_scrollOffset;
|
| 224 |
+
float cellX = scrolledX * 8.0;
|
| 225 |
+
float cellXFrac = fract(cellX);
|
| 226 |
+
|
| 227 |
+
vec4 color1 = getCellColor(vec2(fract(scrolledX), v_uv.y));
|
| 228 |
+
vec4 color2 = getCellColor(vec2(fract(scrolledX + 1.0/8.0), v_uv.y));
|
| 229 |
+
vec4 finalColor = mix(color1, color2, cellXFrac);
|
| 230 |
+
|
| 231 |
+
// Very aggressively tone down brightness for better contrast
|
| 232 |
+
float luminance = dot(finalColor.rgb, vec3(0.2126, 0.7152, 0.0722));
|
| 233 |
+
if (luminance > 0.25) {
|
| 234 |
+
// Reduce by up to 70% for very bright colors
|
| 235 |
+
float reduction = (luminance - 0.25) * 0.93;
|
| 236 |
+
finalColor.rgb *= (1.0 - reduction);
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
gl_FragColor = finalColor;
|
| 240 |
+
}
|
| 241 |
+
`;
|
| 242 |
+
|
| 243 |
+
const blurFragmentShaderSource = `
|
| 244 |
+
precision mediump float;
|
| 245 |
+
uniform sampler2D u_image;
|
| 246 |
+
uniform vec2 u_resolution;
|
| 247 |
+
uniform vec2 u_direction;
|
| 248 |
+
varying vec2 v_uv;
|
| 249 |
+
|
| 250 |
+
void main() {
|
| 251 |
+
vec2 texelSize = 1.0 / u_resolution;
|
| 252 |
+
vec3 result = texture2D(u_image, v_uv).rgb * 0.227027;
|
| 253 |
+
|
| 254 |
+
result += texture2D(u_image, v_uv + texelSize * u_direction * 1.0).rgb * 0.1945946;
|
| 255 |
+
result += texture2D(u_image, v_uv - texelSize * u_direction * 1.0).rgb * 0.1945946;
|
| 256 |
+
result += texture2D(u_image, v_uv + texelSize * u_direction * 2.0).rgb * 0.1216216;
|
| 257 |
+
result += texture2D(u_image, v_uv - texelSize * u_direction * 2.0).rgb * 0.1216216;
|
| 258 |
+
result += texture2D(u_image, v_uv + texelSize * u_direction * 3.0).rgb * 0.05405405;
|
| 259 |
+
result += texture2D(u_image, v_uv - texelSize * u_direction * 3.0).rgb * 0.05405405;
|
| 260 |
+
result += texture2D(u_image, v_uv + texelSize * u_direction * 4.0).rgb * 0.01621621;
|
| 261 |
+
result += texture2D(u_image, v_uv - texelSize * u_direction * 4.0).rgb * 0.01621621;
|
| 262 |
+
|
| 263 |
+
gl_FragColor = vec4(result, 1.0);
|
| 264 |
+
}
|
| 265 |
+
`;
|
| 266 |
+
|
| 267 |
+
const createShader = (gl: WebGLRenderingContext, type: number, source: string): WebGLShader | null => {
|
| 268 |
+
const shader = gl.createShader(type);
|
| 269 |
+
if (!shader) return null;
|
| 270 |
+
gl.shaderSource(shader, source);
|
| 271 |
+
gl.compileShader(shader);
|
| 272 |
+
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
|
| 273 |
+
console.error('Shader compilation error:', gl.getShaderInfoLog(shader));
|
| 274 |
+
gl.deleteShader(shader);
|
| 275 |
+
return null;
|
| 276 |
+
}
|
| 277 |
+
return shader;
|
| 278 |
+
};
|
| 279 |
+
|
| 280 |
+
const createProgram = (gl: WebGLRenderingContext, vertexShader: WebGLShader, fragmentShader: WebGLShader): WebGLProgram | null => {
|
| 281 |
+
const program = gl.createProgram();
|
| 282 |
+
if (!program) return null;
|
| 283 |
+
gl.attachShader(program, vertexShader);
|
| 284 |
+
gl.attachShader(program, fragmentShader);
|
| 285 |
+
gl.linkProgram(program);
|
| 286 |
+
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
|
| 287 |
+
console.error('Program linking error:', gl.getProgramInfoLog(program));
|
| 288 |
+
gl.deleteProgram(program);
|
| 289 |
+
return null;
|
| 290 |
+
}
|
| 291 |
+
return program;
|
| 292 |
+
};
|
| 293 |
+
|
| 294 |
+
const setupQuadBuffer = (gl: WebGLRenderingContext) => {
|
| 295 |
+
const buffer = gl.createBuffer();
|
| 296 |
+
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
|
| 297 |
+
const positions = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]);
|
| 298 |
+
gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);
|
| 299 |
+
return buffer;
|
| 300 |
+
};
|
| 301 |
+
|
| 302 |
+
const createTexture = (gl: WebGLRenderingContext, width: number, height: number): WebGLTexture | null => {
|
| 303 |
+
const texture = gl.createTexture();
|
| 304 |
+
gl.bindTexture(gl.TEXTURE_2D, texture);
|
| 305 |
+
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
|
| 306 |
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
|
| 307 |
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
|
| 308 |
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
| 309 |
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
| 310 |
+
return texture;
|
| 311 |
+
};
|
| 312 |
+
|
| 313 |
+
const createFramebuffer = (gl: WebGLRenderingContext, texture: WebGLTexture | null): WebGLFramebuffer | null => {
|
| 314 |
+
const framebuffer = gl.createFramebuffer();
|
| 315 |
+
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
|
| 316 |
+
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
|
| 317 |
+
return framebuffer;
|
| 318 |
+
};
|
| 319 |
+
|
| 320 |
+
const initializeCellStates = (gl: WebGLRenderingContext) => {
|
| 321 |
+
const data = new Uint8Array(DISPLAY_GRID_WIDTH * DISPLAY_GRID_HEIGHT * 4);
|
| 322 |
+
for (let i = 0; i < DISPLAY_GRID_WIDTH * DISPLAY_GRID_HEIGHT; i++) {
|
| 323 |
+
const idx = i * 4;
|
| 324 |
+
data[idx] = Math.floor(Math.random() * 40) * (255 / 39); // source color
|
| 325 |
+
data[idx + 1] = Math.floor(Math.random() * 40) * (255 / 39); // target color
|
| 326 |
+
data[idx + 2] = Math.floor(Math.random() * 255); // progress
|
| 327 |
+
// Much slower initial speed: 0.08-0.20 range (was 0.15-0.35)
|
| 328 |
+
data[idx + 3] = Math.floor((Math.random() * 0.12 + 0.08) * 0.48 * 10 * 255 / 10); // speed
|
| 329 |
+
}
|
| 330 |
+
gl.bindTexture(gl.TEXTURE_2D, cellStateTexture);
|
| 331 |
+
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, DISPLAY_GRID_WIDTH, DISPLAY_GRID_HEIGHT, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
|
| 332 |
+
};
|
| 333 |
+
|
| 334 |
+
const initWebGL = () => {
|
| 335 |
+
if (!browser || !webglCanvas) return false;
|
| 336 |
+
|
| 337 |
+
const context = webglCanvas.getContext('webgl', {
|
| 338 |
+
alpha: true,
|
| 339 |
+
premultipliedAlpha: false,
|
| 340 |
+
antialias: false,
|
| 341 |
+
preserveDrawingBuffer: false
|
| 342 |
+
});
|
| 343 |
+
|
| 344 |
+
if (!context) {
|
| 345 |
+
console.warn('WebGL not supported');
|
| 346 |
+
return false;
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
gl = context;
|
| 350 |
+
|
| 351 |
+
// Set canvas size based on device
|
| 352 |
+
const canvasSize = getCanvasSize();
|
| 353 |
+
webglCanvas.width = canvasSize;
|
| 354 |
+
webglCanvas.height = canvasSize;
|
| 355 |
+
|
| 356 |
+
// Create shaders and programs
|
| 357 |
+
const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
|
| 358 |
+
if (!vertexShader) return false;
|
| 359 |
+
|
| 360 |
+
// Update state program
|
| 361 |
+
const updateStateFragShader = createShader(gl, gl.FRAGMENT_SHADER, updateStateShaderSource);
|
| 362 |
+
if (!updateStateFragShader) return false;
|
| 363 |
+
updateStateProgram = createProgram(gl, vertexShader, updateStateFragShader);
|
| 364 |
+
if (!updateStateProgram) return false;
|
| 365 |
+
|
| 366 |
+
// Main render program
|
| 367 |
+
const fragShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
|
| 368 |
+
if (!fragShader) return false;
|
| 369 |
+
glProgram = createProgram(gl, vertexShader, fragShader);
|
| 370 |
+
if (!glProgram) return false;
|
| 371 |
+
|
| 372 |
+
// Blur program
|
| 373 |
+
const blurFragShader = createShader(gl, gl.FRAGMENT_SHADER, blurFragmentShaderSource);
|
| 374 |
+
if (!blurFragShader) return false;
|
| 375 |
+
blurProgram = createProgram(gl, vertexShader, blurFragShader);
|
| 376 |
+
if (!blurProgram) return false;
|
| 377 |
+
|
| 378 |
+
// Setup quad buffer
|
| 379 |
+
setupQuadBuffer(gl);
|
| 380 |
+
|
| 381 |
+
// Create textures and framebuffers
|
| 382 |
+
cellStateTexture = createTexture(gl, DISPLAY_GRID_WIDTH, DISPLAY_GRID_HEIGHT);
|
| 383 |
+
cellStateFramebuffer = createFramebuffer(gl, cellStateTexture);
|
| 384 |
+
|
| 385 |
+
paletteTexture = createTexture(gl, MASTER_PALETTE_TEX_WIDTH, MASTER_PALETTE_TEX_HEIGHT * 2);
|
| 386 |
+
|
| 387 |
+
colorRenderTexture = createTexture(gl, STRETCHED_GRID_WIDTH, STRETCHED_GRID_HEIGHT);
|
| 388 |
+
colorRenderFramebuffer = createFramebuffer(gl, colorRenderTexture);
|
| 389 |
+
|
| 390 |
+
const blurWidth = Math.round(canvasSize / BLUR_DOWNSAMPLE_FACTOR);
|
| 391 |
+
const blurHeight = Math.round(canvasSize / BLUR_DOWNSAMPLE_FACTOR);
|
| 392 |
+
blurTexture1 = createTexture(gl, blurWidth, blurHeight);
|
| 393 |
+
blurFramebuffer1 = createFramebuffer(gl, blurTexture1);
|
| 394 |
+
blurTexture2 = createTexture(gl, blurWidth, blurHeight);
|
| 395 |
+
blurFramebuffer2 = createFramebuffer(gl, blurTexture2);
|
| 396 |
+
|
| 397 |
+
// Initialize cell states with random values
|
| 398 |
+
initializeCellStates(gl);
|
| 399 |
+
|
| 400 |
+
// Setup context loss handlers
|
| 401 |
+
if (!webglListenersAttached) {
|
| 402 |
+
webglCanvas.addEventListener('webglcontextlost', (event) => {
|
| 403 |
+
event.preventDefault();
|
| 404 |
+
if (globalAnimationId !== null) {
|
| 405 |
+
cancelAnimationFrame(globalAnimationId);
|
| 406 |
+
globalAnimationId = null;
|
| 407 |
+
}
|
| 408 |
+
gl = null;
|
| 409 |
+
glProgram = null;
|
| 410 |
+
updateStateProgram = null;
|
| 411 |
+
blurProgram = null;
|
| 412 |
+
});
|
| 413 |
+
|
| 414 |
+
webglCanvas.addEventListener('webglcontextrestored', () => {
|
| 415 |
+
initWebGL();
|
| 416 |
+
if (currentTargetMasterPalette.length > 0) {
|
| 417 |
+
updatePaletteTexture(previousMasterPalette, currentTargetMasterPalette);
|
| 418 |
+
}
|
| 419 |
+
});
|
| 420 |
+
|
| 421 |
+
webglListenersAttached = true;
|
| 422 |
+
}
|
| 423 |
+
|
| 424 |
+
return true;
|
| 425 |
+
};
|
| 426 |
+
|
| 427 |
+
const updatePaletteTexture = (previous: RGBColor[], target: RGBColor[]) => {
|
| 428 |
+
if (!gl || !paletteTexture) return;
|
| 429 |
+
|
| 430 |
+
const data = new Uint8Array(MASTER_PALETTE_TEX_WIDTH * MASTER_PALETTE_TEX_HEIGHT * 2 * 4);
|
| 431 |
+
|
| 432 |
+
// Write previous palette to top 5 rows
|
| 433 |
+
for (let i = 0; i < MASTER_PALETTE_SIZE; i++) {
|
| 434 |
+
const color = previous[i] || { red: 0, green: 0, blue: 0 };
|
| 435 |
+
const idx = i * 4;
|
| 436 |
+
data[idx] = color.red;
|
| 437 |
+
data[idx + 1] = color.green;
|
| 438 |
+
data[idx + 2] = color.blue;
|
| 439 |
+
data[idx + 3] = 255;
|
| 440 |
+
}
|
| 441 |
+
|
| 442 |
+
// Write target palette to bottom 5 rows
|
| 443 |
+
const offset = MASTER_PALETTE_SIZE * 4;
|
| 444 |
+
for (let i = 0; i < MASTER_PALETTE_SIZE; i++) {
|
| 445 |
+
const color = target[i] || { red: 0, green: 0, blue: 0 };
|
| 446 |
+
const idx = offset + i * 4;
|
| 447 |
+
data[idx] = color.red;
|
| 448 |
+
data[idx + 1] = color.green;
|
| 449 |
+
data[idx + 2] = color.blue;
|
| 450 |
+
data[idx + 3] = 255;
|
| 451 |
+
}
|
| 452 |
+
|
| 453 |
+
gl.bindTexture(gl.TEXTURE_2D, paletteTexture);
|
| 454 |
+
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, MASTER_PALETTE_TEX_WIDTH, MASTER_PALETTE_TEX_HEIGHT * 2, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
|
| 455 |
+
};
|
| 456 |
+
|
| 457 |
+
const animateWebGLBackground = (timestamp: number) => {
|
| 458 |
+
if (!gl || !glProgram || !updateStateProgram || !blurProgram) return;
|
| 459 |
+
|
| 460 |
+
// Frame rate limiting for mobile performance
|
| 461 |
+
const frameInterval = getFrameInterval();
|
| 462 |
+
const elapsed = timestamp - lastRenderTime;
|
| 463 |
+
|
| 464 |
+
if (elapsed < frameInterval) {
|
| 465 |
+
// Skip this frame, schedule next
|
| 466 |
+
if (canvasVisible && backgroundEnabled) {
|
| 467 |
+
globalAnimationId = requestAnimationFrame(animateWebGLBackground);
|
| 468 |
+
}
|
| 469 |
+
return;
|
| 470 |
+
}
|
| 471 |
+
|
| 472 |
+
lastRenderTime = timestamp - (elapsed % frameInterval);
|
| 473 |
+
|
| 474 |
+
const deltaTime = lastFrameTime > 0 ? (timestamp - lastFrameTime) / 1000 : 0.016;
|
| 475 |
+
lastFrameTime = timestamp;
|
| 476 |
+
|
| 477 |
+
// Update scroll offset
|
| 478 |
+
scrollOffset += SCROLL_SPEED * deltaTime;
|
| 479 |
+
if (scrollOffset >= 1.0) scrollOffset -= 1.0;
|
| 480 |
+
|
| 481 |
+
// Update palette transition
|
| 482 |
+
if (songPaletteTransitionProgress < 1.0) {
|
| 483 |
+
songPaletteTransitionProgress = Math.min(1.0, songPaletteTransitionProgress + SONG_PALETTE_TRANSITION_SPEED);
|
| 484 |
+
}
|
| 485 |
+
|
| 486 |
+
// Pass 1: Update cell states (lightweight mode skips this when not transitioning)
|
| 487 |
+
if (performanceLevel !== 'low' || songPaletteTransitionProgress < 1.0) {
|
| 488 |
+
gl.bindFramebuffer(gl.FRAMEBUFFER, cellStateFramebuffer);
|
| 489 |
+
gl.viewport(0, 0, DISPLAY_GRID_WIDTH, DISPLAY_GRID_HEIGHT);
|
| 490 |
+
gl.useProgram(updateStateProgram);
|
| 491 |
+
|
| 492 |
+
const positionLocation = gl.getAttribLocation(updateStateProgram, 'a_position');
|
| 493 |
+
gl.enableVertexAttribArray(positionLocation);
|
| 494 |
+
gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
|
| 495 |
+
|
| 496 |
+
gl.activeTexture(gl.TEXTURE0);
|
| 497 |
+
gl.bindTexture(gl.TEXTURE_2D, cellStateTexture);
|
| 498 |
+
gl.uniform1i(gl.getUniformLocation(updateStateProgram, 'u_currentStateTexture'), 0);
|
| 499 |
+
gl.uniform1f(gl.getUniformLocation(updateStateProgram, 'u_deltaTime'), deltaTime);
|
| 500 |
+
gl.uniform1f(gl.getUniformLocation(updateStateProgram, 'u_time'), timestamp / 1000);
|
| 501 |
+
|
| 502 |
+
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
|
| 503 |
+
|
| 504 |
+
// Copy result back to cellStateTexture
|
| 505 |
+
gl.bindTexture(gl.TEXTURE_2D, cellStateTexture);
|
| 506 |
+
gl.copyTexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 0, 0, DISPLAY_GRID_WIDTH, DISPLAY_GRID_HEIGHT, 0);
|
| 507 |
+
}
|
| 508 |
+
|
| 509 |
+
// Pass 2: Render colors
|
| 510 |
+
gl.bindFramebuffer(gl.FRAMEBUFFER, colorRenderFramebuffer);
|
| 511 |
+
gl.viewport(0, 0, STRETCHED_GRID_WIDTH, STRETCHED_GRID_HEIGHT);
|
| 512 |
+
gl.useProgram(glProgram);
|
| 513 |
+
|
| 514 |
+
const positionLocation2 = gl.getAttribLocation(glProgram, 'a_position');
|
| 515 |
+
gl.enableVertexAttribArray(positionLocation2);
|
| 516 |
+
gl.vertexAttribPointer(positionLocation2, 2, gl.FLOAT, false, 0, 0);
|
| 517 |
+
|
| 518 |
+
gl.activeTexture(gl.TEXTURE0);
|
| 519 |
+
gl.bindTexture(gl.TEXTURE_2D, paletteTexture);
|
| 520 |
+
gl.uniform1i(gl.getUniformLocation(glProgram, 'u_paletteTexture'), 0);
|
| 521 |
+
|
| 522 |
+
gl.activeTexture(gl.TEXTURE1);
|
| 523 |
+
gl.bindTexture(gl.TEXTURE_2D, cellStateTexture);
|
| 524 |
+
gl.uniform1i(gl.getUniformLocation(glProgram, 'u_cellStateTexture'), 1);
|
| 525 |
+
|
| 526 |
+
gl.uniform1f(gl.getUniformLocation(glProgram, 'u_songPaletteTransitionProgress'), songPaletteTransitionProgress);
|
| 527 |
+
gl.uniform1f(gl.getUniformLocation(glProgram, 'u_scrollOffset'), scrollOffset);
|
| 528 |
+
|
| 529 |
+
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
|
| 530 |
+
|
| 531 |
+
// Pass 3: Horizontal blur
|
| 532 |
+
const canvasSize = getCanvasSize();
|
| 533 |
+
const blurWidth = Math.round(canvasSize / BLUR_DOWNSAMPLE_FACTOR);
|
| 534 |
+
const blurHeight = Math.round(canvasSize / BLUR_DOWNSAMPLE_FACTOR);
|
| 535 |
+
|
| 536 |
+
gl.bindFramebuffer(gl.FRAMEBUFFER, blurFramebuffer1);
|
| 537 |
+
gl.viewport(0, 0, blurWidth, blurHeight);
|
| 538 |
+
gl.useProgram(blurProgram);
|
| 539 |
+
|
| 540 |
+
const positionLocation3 = gl.getAttribLocation(blurProgram, 'a_position');
|
| 541 |
+
gl.enableVertexAttribArray(positionLocation3);
|
| 542 |
+
gl.vertexAttribPointer(positionLocation3, 2, gl.FLOAT, false, 0, 0);
|
| 543 |
+
|
| 544 |
+
gl.activeTexture(gl.TEXTURE0);
|
| 545 |
+
gl.bindTexture(gl.TEXTURE_2D, colorRenderTexture);
|
| 546 |
+
gl.uniform1i(gl.getUniformLocation(blurProgram, 'u_image'), 0);
|
| 547 |
+
gl.uniform2f(gl.getUniformLocation(blurProgram, 'u_resolution'), STRETCHED_GRID_WIDTH, STRETCHED_GRID_HEIGHT);
|
| 548 |
+
gl.uniform2f(gl.getUniformLocation(blurProgram, 'u_direction'), 1.0, 0.0);
|
| 549 |
+
|
| 550 |
+
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
|
| 551 |
+
|
| 552 |
+
// Pass 4: Vertical blur & display
|
| 553 |
+
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
| 554 |
+
gl.viewport(0, 0, canvasSize, canvasSize);
|
| 555 |
+
gl.useProgram(blurProgram);
|
| 556 |
+
|
| 557 |
+
gl.enableVertexAttribArray(positionLocation3);
|
| 558 |
+
gl.vertexAttribPointer(positionLocation3, 2, gl.FLOAT, false, 0, 0);
|
| 559 |
+
|
| 560 |
+
gl.activeTexture(gl.TEXTURE0);
|
| 561 |
+
gl.bindTexture(gl.TEXTURE_2D, blurTexture1);
|
| 562 |
+
gl.uniform1i(gl.getUniformLocation(blurProgram, 'u_image'), 0);
|
| 563 |
+
gl.uniform2f(gl.getUniformLocation(blurProgram, 'u_resolution'), blurWidth, blurHeight);
|
| 564 |
+
gl.uniform2f(gl.getUniformLocation(blurProgram, 'u_direction'), 0.0, 1.0);
|
| 565 |
+
|
| 566 |
+
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
|
| 567 |
+
|
| 568 |
+
// Continue animation if needed
|
| 569 |
+
if (canvasVisible && backgroundEnabled && (performanceLevel !== 'low' || songPaletteTransitionProgress < 1.0)) {
|
| 570 |
+
globalAnimationId = requestAnimationFrame(animateWebGLBackground);
|
| 571 |
+
} else {
|
| 572 |
+
globalAnimationId = null;
|
| 573 |
+
}
|
| 574 |
+
};
|
| 575 |
+
|
| 576 |
+
const startAnimation = () => {
|
| 577 |
+
if (globalAnimationId === null && gl) {
|
| 578 |
+
lastFrameTime = 0;
|
| 579 |
+
globalAnimationId = requestAnimationFrame(animateWebGLBackground);
|
| 580 |
+
}
|
| 581 |
+
};
|
| 582 |
+
|
| 583 |
+
const stopAnimation = () => {
|
| 584 |
+
if (globalAnimationId !== null) {
|
| 585 |
+
cancelAnimationFrame(globalAnimationId);
|
| 586 |
+
globalAnimationId = null;
|
| 587 |
+
}
|
| 588 |
+
};
|
| 589 |
+
|
| 590 |
+
const resolveArtworkUrl = (track: PlayerStateShape['currentTrack']): string | null => {
|
| 591 |
+
if (!track) return null;
|
| 592 |
+
|
| 593 |
+
if (track.thumbnailUrl) {
|
| 594 |
+
return track.thumbnailUrl;
|
| 595 |
+
}
|
| 596 |
+
|
| 597 |
+
const albumCover = track.album?.cover ?? null;
|
| 598 |
+
if (albumCover) {
|
| 599 |
+
const imageSize = performanceLevel === 'low' ? '320' : performanceLevel === 'medium' ? '640' : '1280';
|
| 600 |
+
return losslessAPI.getCoverUrl(albumCover, imageSize);
|
| 601 |
+
}
|
| 602 |
+
|
| 603 |
+
const artistPicture = track.artist?.picture ?? track.artists?.find((artist) => Boolean(artist?.picture))?.picture ?? null;
|
| 604 |
+
if (artistPicture) {
|
| 605 |
+
return losslessAPI.getArtistPictureUrl(artistPicture, '750');
|
| 606 |
+
}
|
| 607 |
+
|
| 608 |
+
return null;
|
| 609 |
+
};
|
| 610 |
+
|
| 611 |
+
const updateFromTrack = async (state: PlayerStateShape | null = null) => {
|
| 612 |
+
if (performanceLevel === 'low') {
|
| 613 |
+
currentCoverUrl = null;
|
| 614 |
+
retryAttempts = 0;
|
| 615 |
+
return;
|
| 616 |
+
}
|
| 617 |
+
|
| 618 |
+
const snapshot = state ?? latestState;
|
| 619 |
+
const token = ++requestToken;
|
| 620 |
+
|
| 621 |
+
if (!snapshot?.currentTrack) {
|
| 622 |
+
currentCoverUrl = null;
|
| 623 |
+
retryAttempts = 0;
|
| 624 |
+
return;
|
| 625 |
+
}
|
| 626 |
+
|
| 627 |
+
const coverUrl = resolveArtworkUrl(snapshot.currentTrack);
|
| 628 |
+
|
| 629 |
+
if (!coverUrl) {
|
| 630 |
+
currentCoverUrl = null;
|
| 631 |
+
retryAttempts = 0;
|
| 632 |
+
return;
|
| 633 |
+
}
|
| 634 |
+
|
| 635 |
+
if (coverUrl === currentCoverUrl) {
|
| 636 |
+
return;
|
| 637 |
+
}
|
| 638 |
+
|
| 639 |
+
currentCoverUrl = coverUrl;
|
| 640 |
+
retryAttempts = 0;
|
| 641 |
+
|
| 642 |
+
try {
|
| 643 |
+
const { palette, mostVibrant } = await extractPaletteFromImageWebGL(coverUrl);
|
| 644 |
+
if (token === requestToken && palette.length === MASTER_PALETTE_SIZE) {
|
| 645 |
+
// Update palette for WebGL
|
| 646 |
+
previousMasterPalette = [...currentTargetMasterPalette];
|
| 647 |
+
currentTargetMasterPalette = palette;
|
| 648 |
+
songPaletteTransitionProgress = 0.0;
|
| 649 |
+
|
| 650 |
+
updatePaletteTexture(previousMasterPalette, currentTargetMasterPalette);
|
| 651 |
+
|
| 652 |
+
// Update CSS variable for lyrics color
|
| 653 |
+
if (mostVibrant) {
|
| 654 |
+
setCssVariables(mostVibrant);
|
| 655 |
+
}
|
| 656 |
+
|
| 657 |
+
// Start animation
|
| 658 |
+
startAnimation();
|
| 659 |
+
}
|
| 660 |
+
} catch (error) {
|
| 661 |
+
console.warn('Failed to extract palette from cover art', error);
|
| 662 |
+
if (token === requestToken) {
|
| 663 |
+
currentCoverUrl = null;
|
| 664 |
+
retryAttempts += 1;
|
| 665 |
+
if (retryAttempts <= MAX_RETRY_ATTEMPTS) {
|
| 666 |
+
setTimeout(() => {
|
| 667 |
+
updateFromTrack();
|
| 668 |
+
}, RETRY_DELAY_MS);
|
| 669 |
+
} else {
|
| 670 |
+
retryAttempts = 0;
|
| 671 |
+
}
|
| 672 |
+
}
|
| 673 |
+
}
|
| 674 |
+
};
|
| 675 |
+
|
| 676 |
+
let unsubscribe: () => void = () => {};
|
| 677 |
+
let lastProcessedCover: string | null = null;
|
| 678 |
+
|
| 679 |
+
const handlePlayerChange = (state: PlayerStateShape) => {
|
| 680 |
+
latestState = state;
|
| 681 |
+
isPlaying = state.isPlaying && Boolean(state.currentTrack);
|
| 682 |
+
|
| 683 |
+
const coverUrl = state.currentTrack ? resolveArtworkUrl(state.currentTrack) : null;
|
| 684 |
+
|
| 685 |
+
if (backgroundEnabled && coverUrl === lastProcessedCover) {
|
| 686 |
+
return;
|
| 687 |
+
}
|
| 688 |
+
|
| 689 |
+
lastProcessedCover = backgroundEnabled ? coverUrl : null;
|
| 690 |
+
updateFromTrack(state);
|
| 691 |
+
};
|
| 692 |
+
|
| 693 |
+
type PlayerStateShape = {
|
| 694 |
+
currentTrack: {
|
| 695 |
+
thumbnailUrl?: string | null;
|
| 696 |
+
album?: {
|
| 697 |
+
cover?: string | null;
|
| 698 |
+
videoCover?: string | null;
|
| 699 |
+
};
|
| 700 |
+
artist?: {
|
| 701 |
+
picture?: string | null;
|
| 702 |
+
} | null;
|
| 703 |
+
artists?: Array<{
|
| 704 |
+
picture?: string | null;
|
| 705 |
+
}> | null;
|
| 706 |
+
} | null;
|
| 707 |
+
isPlaying: boolean;
|
| 708 |
+
};
|
| 709 |
+
|
| 710 |
+
const subscribeToPlayer = () => {
|
| 711 |
+
unsubscribe = playerStore.subscribe(($state) => {
|
| 712 |
+
const snapshot: PlayerStateShape = {
|
| 713 |
+
currentTrack: $state.currentTrack
|
| 714 |
+
? {
|
| 715 |
+
thumbnailUrl: 'thumbnailUrl' in $state.currentTrack ? $state.currentTrack.thumbnailUrl : null,
|
| 716 |
+
album: 'album' in $state.currentTrack ? {
|
| 717 |
+
cover: $state.currentTrack.album?.cover ?? null,
|
| 718 |
+
videoCover: $state.currentTrack.album?.videoCover ?? null
|
| 719 |
+
} : undefined,
|
| 720 |
+
artist: 'artist' in $state.currentTrack && $state.currentTrack.artist
|
| 721 |
+
? {
|
| 722 |
+
picture: $state.currentTrack.artist.picture ?? null
|
| 723 |
+
}
|
| 724 |
+
: null,
|
| 725 |
+
artists: 'artists' in $state.currentTrack ? $state.currentTrack.artists?.map((artist) => ({
|
| 726 |
+
picture: artist.picture ?? null
|
| 727 |
+
})) ?? null : null
|
| 728 |
+
}
|
| 729 |
+
: null,
|
| 730 |
+
isPlaying: $state.isPlaying
|
| 731 |
+
};
|
| 732 |
+
handlePlayerChange(snapshot);
|
| 733 |
+
});
|
| 734 |
+
};
|
| 735 |
+
|
| 736 |
+
onMount(() => {
|
| 737 |
+
if (!browser) return;
|
| 738 |
+
|
| 739 |
+
// Initialize WebGL only if not in low performance mode
|
| 740 |
+
if (performanceLevel !== 'low') {
|
| 741 |
+
if (!initWebGL()) {
|
| 742 |
+
console.warn('Failed to initialize WebGL');
|
| 743 |
+
backgroundEnabled = false;
|
| 744 |
+
// Don't return here, continue setup
|
| 745 |
+
}
|
| 746 |
+
}
|
| 747 |
+
|
| 748 |
+
// Setup intersection observer for visibility
|
| 749 |
+
const observer = new IntersectionObserver((entries) => {
|
| 750 |
+
entries.forEach((entry) => {
|
| 751 |
+
canvasVisible = entry.isIntersecting;
|
| 752 |
+
if (entry.isIntersecting && backgroundEnabled) {
|
| 753 |
+
startAnimation();
|
| 754 |
+
} else {
|
| 755 |
+
stopAnimation();
|
| 756 |
+
}
|
| 757 |
+
});
|
| 758 |
+
}, { threshold: 0.01 });
|
| 759 |
+
|
| 760 |
+
if (webglCanvas) {
|
| 761 |
+
observer.observe(webglCanvas);
|
| 762 |
+
}
|
| 763 |
+
|
| 764 |
+
// Subscribe to performance settings
|
| 765 |
+
const unsubPerf = effectivePerformanceLevel.subscribe((level) => {
|
| 766 |
+
const previousLevel = performanceLevel;
|
| 767 |
+
if (level === previousLevel) {
|
| 768 |
+
return;
|
| 769 |
+
}
|
| 770 |
+
|
| 771 |
+
performanceLevel = level;
|
| 772 |
+
backgroundEnabled = level !== 'low';
|
| 773 |
+
|
| 774 |
+
if (level === 'low') {
|
| 775 |
+
requestToken += 1;
|
| 776 |
+
lastProcessedCover = null;
|
| 777 |
+
currentCoverUrl = null;
|
| 778 |
+
retryAttempts = 0;
|
| 779 |
+
stopAnimation();
|
| 780 |
+
|
| 781 |
+
// Release WebGL context to free resources
|
| 782 |
+
if (gl) {
|
| 783 |
+
gl.getExtension('WEBGL_lose_context')?.loseContext();
|
| 784 |
+
}
|
| 785 |
+
} else if (previousLevel === 'low') {
|
| 786 |
+
// Re-initialize WebGL if needed
|
| 787 |
+
if (!gl) {
|
| 788 |
+
initWebGL();
|
| 789 |
+
}
|
| 790 |
+
|
| 791 |
+
if (latestState?.currentTrack) {
|
| 792 |
+
lastProcessedCover = null;
|
| 793 |
+
currentCoverUrl = null;
|
| 794 |
+
retryAttempts = 0;
|
| 795 |
+
updateFromTrack(latestState);
|
| 796 |
+
}
|
| 797 |
+
}
|
| 798 |
+
});
|
| 799 |
+
|
| 800 |
+
const unsubAnim = animationsEnabled.subscribe((enabled) => {
|
| 801 |
+
enableAnimations = enabled;
|
| 802 |
+
});
|
| 803 |
+
|
| 804 |
+
// Get current state before subscribing
|
| 805 |
+
const currentState = get(playerStore);
|
| 806 |
+
if (currentState.currentTrack) {
|
| 807 |
+
const snapshot: PlayerStateShape = {
|
| 808 |
+
currentTrack: {
|
| 809 |
+
thumbnailUrl: 'thumbnailUrl' in currentState.currentTrack ? currentState.currentTrack.thumbnailUrl : null,
|
| 810 |
+
album: 'album' in currentState.currentTrack ? {
|
| 811 |
+
cover: currentState.currentTrack.album?.cover ?? null,
|
| 812 |
+
videoCover: currentState.currentTrack.album?.videoCover ?? null
|
| 813 |
+
} : undefined,
|
| 814 |
+
artist: 'artist' in currentState.currentTrack && currentState.currentTrack.artist
|
| 815 |
+
? {
|
| 816 |
+
picture: currentState.currentTrack.artist.picture ?? null
|
| 817 |
+
}
|
| 818 |
+
: null,
|
| 819 |
+
artists: 'artists' in currentState.currentTrack ? currentState.currentTrack.artists?.map((artist) => ({
|
| 820 |
+
picture: artist.picture ?? null
|
| 821 |
+
})) ?? null : null
|
| 822 |
+
},
|
| 823 |
+
isPlaying: currentState.isPlaying
|
| 824 |
+
};
|
| 825 |
+
|
| 826 |
+
const coverUrl = resolveArtworkUrl(snapshot.currentTrack);
|
| 827 |
+
backgroundEnabled = performanceLevel !== 'low';
|
| 828 |
+
lastProcessedCover = backgroundEnabled ? coverUrl : null;
|
| 829 |
+
latestState = snapshot;
|
| 830 |
+
isPlaying = snapshot.isPlaying && Boolean(snapshot.currentTrack);
|
| 831 |
+
updateFromTrack(snapshot);
|
| 832 |
+
}
|
| 833 |
+
|
| 834 |
+
// Subscribe after handling initial state
|
| 835 |
+
subscribeToPlayer();
|
| 836 |
+
|
| 837 |
+
return () => {
|
| 838 |
+
unsubPerf();
|
| 839 |
+
unsubAnim();
|
| 840 |
+
observer.disconnect();
|
| 841 |
+
stopAnimation();
|
| 842 |
+
};
|
| 843 |
+
});
|
| 844 |
+
|
| 845 |
+
onDestroy(() => {
|
| 846 |
+
unsubscribe?.();
|
| 847 |
+
stopAnimation();
|
| 848 |
+
});
|
| 849 |
+
</script>
|
| 850 |
+
|
| 851 |
+
<div class="webgl-background" aria-hidden="true" data-performance={performanceLevel}>
|
| 852 |
+
{#if (!currentTargetMasterPalette.length && !isPlaying) || performanceLevel === 'low'}
|
| 853 |
+
<div class="default-background"></div>
|
| 854 |
+
{/if}
|
| 855 |
+
<canvas
|
| 856 |
+
bind:this={webglCanvas}
|
| 857 |
+
class="webgl-background__canvas"
|
| 858 |
+
style="width: 100%; height: 100%; opacity: {currentTargetMasterPalette.length && isPlaying ? 1 : 0};"
|
| 859 |
+
></canvas>
|
| 860 |
+
</div>
|
| 861 |
+
|
| 862 |
+
<style>
|
| 863 |
+
.webgl-background {
|
| 864 |
+
position: fixed;
|
| 865 |
+
inset: 0;
|
| 866 |
+
z-index: 0;
|
| 867 |
+
pointer-events: none;
|
| 868 |
+
overflow: hidden;
|
| 869 |
+
background: #0a0e1a;
|
| 870 |
+
}
|
| 871 |
+
|
| 872 |
+
.default-background {
|
| 873 |
+
position: absolute;
|
| 874 |
+
inset: 0;
|
| 875 |
+
background:
|
| 876 |
+
radial-gradient(ellipse at 20% 30%, rgba(59, 130, 246, 0.15) 0%, transparent 50%),
|
| 877 |
+
radial-gradient(ellipse at 80% 70%, rgba(99, 102, 241, 0.12) 0%, transparent 50%),
|
| 878 |
+
radial-gradient(ellipse at 50% 50%, rgba(139, 92, 246, 0.08) 0%, transparent 60%),
|
| 879 |
+
linear-gradient(135deg, #0a0e1a 0%, #0f172a 50%, #1e293b 100%);
|
| 880 |
+
animation: ambient-float 20s ease-in-out infinite;
|
| 881 |
+
}
|
| 882 |
+
|
| 883 |
+
@keyframes ambient-float {
|
| 884 |
+
0%, 100% {
|
| 885 |
+
transform: scale(1) rotate(0deg);
|
| 886 |
+
opacity: 1;
|
| 887 |
+
}
|
| 888 |
+
33% {
|
| 889 |
+
transform: scale(1.05) rotate(1deg);
|
| 890 |
+
opacity: 0.95;
|
| 891 |
+
}
|
| 892 |
+
66% {
|
| 893 |
+
transform: scale(0.98) rotate(-1deg);
|
| 894 |
+
opacity: 0.98;
|
| 895 |
+
}
|
| 896 |
+
}
|
| 897 |
+
|
| 898 |
+
.webgl-background__canvas {
|
| 899 |
+
width: 100%;
|
| 900 |
+
height: 100%;
|
| 901 |
+
object-fit: cover;
|
| 902 |
+
transition: opacity 1.2s ease-in-out;
|
| 903 |
+
}
|
| 904 |
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<script lang="ts">
|
| 2 |
+
import { onMount, onDestroy } from 'svelte';
|
| 3 |
+
import { playerStore } from '$lib/stores/player';
|
| 4 |
+
import { effectivePerformanceLevel } from '$lib/stores/performance';
|
| 5 |
+
import { losslessAPI } from '$lib/api';
|
| 6 |
+
import {
|
| 7 |
+
extractPaletteFromImage,
|
| 8 |
+
getMostVibrantColor,
|
| 9 |
+
type Color
|
| 10 |
+
} from '$lib/utils/colorExtraction';
|
| 11 |
+
import {
|
| 12 |
+
vertexShaderSource,
|
| 13 |
+
updateStateShaderSource,
|
| 14 |
+
colorRenderShaderSource,
|
| 15 |
+
blurFragmentShaderSource,
|
| 16 |
+
createShader,
|
| 17 |
+
createProgram,
|
| 18 |
+
setupQuad,
|
| 19 |
+
createTexture,
|
| 20 |
+
createFramebuffer
|
| 21 |
+
} from '$lib/utils/webglShaders';
|
| 22 |
+
|
| 23 |
+
// Constants
|
| 24 |
+
const DISPLAY_CANVAS_SIZE = 512;
|
| 25 |
+
const MASTER_PALETTE_SIZE = 40;
|
| 26 |
+
const DISPLAY_GRID_WIDTH = 8;
|
| 27 |
+
const DISPLAY_GRID_HEIGHT = 5;
|
| 28 |
+
const STRETCHED_GRID_WIDTH = 32;
|
| 29 |
+
const STRETCHED_GRID_HEIGHT = 18;
|
| 30 |
+
const BLUR_DOWNSAMPLE_FACTOR = 26;
|
| 31 |
+
const SONG_PALETTE_TRANSITION_SPEED = 0.015;
|
| 32 |
+
const SCROLL_SPEED = 0.008;
|
| 33 |
+
|
| 34 |
+
// Canvas and WebGL context
|
| 35 |
+
let canvasElement: HTMLCanvasElement;
|
| 36 |
+
let gl: WebGLRenderingContext | null = null;
|
| 37 |
+
|
| 38 |
+
// Shader programs
|
| 39 |
+
let updateStateProgram: WebGLProgram | null = null;
|
| 40 |
+
let colorRenderProgram: WebGLProgram | null = null;
|
| 41 |
+
let blurProgram: WebGLProgram | null = null;
|
| 42 |
+
|
| 43 |
+
// Textures and framebuffers
|
| 44 |
+
let paletteTexture: WebGLTexture | null = null;
|
| 45 |
+
let cellStateTexture: WebGLTexture | null = null;
|
| 46 |
+
let cellStateTexture2: WebGLTexture | null = null;
|
| 47 |
+
let colorRenderTexture: WebGLTexture | null = null;
|
| 48 |
+
let blurTexture1: WebGLTexture | null = null;
|
| 49 |
+
let blurTexture2: WebGLTexture | null = null;
|
| 50 |
+
|
| 51 |
+
let stateFramebuffer1: WebGLFramebuffer | null = null;
|
| 52 |
+
let stateFramebuffer2: WebGLFramebuffer | null = null;
|
| 53 |
+
let colorRenderFramebuffer: WebGLFramebuffer | null = null;
|
| 54 |
+
let blurFramebuffer1: WebGLFramebuffer | null = null;
|
| 55 |
+
let blurFramebuffer2: WebGLFramebuffer | null = null;
|
| 56 |
+
|
| 57 |
+
// Animation state
|
| 58 |
+
let previousPalette: Color[] = [];
|
| 59 |
+
let targetPalette: Color[] = [];
|
| 60 |
+
let songPaletteTransitionProgress = 1.0;
|
| 61 |
+
let scrollOffset = 0.0;
|
| 62 |
+
let lastFrameTime = performance.now();
|
| 63 |
+
let animationFrameId: number | null = null;
|
| 64 |
+
let currentStateTexture = 0; // 0 or 1 for ping-pong
|
| 65 |
+
|
| 66 |
+
// Performance flags
|
| 67 |
+
let isLightweight = false;
|
| 68 |
+
let isVisible = true;
|
| 69 |
+
|
| 70 |
+
// Track current song
|
| 71 |
+
let currentTrackId: number | string | null = null;
|
| 72 |
+
|
| 73 |
+
onMount(() => {
|
| 74 |
+
initializeWebGL();
|
| 75 |
+
setupIntersectionObserver();
|
| 76 |
+
|
| 77 |
+
// Subscribe to performance level changes
|
| 78 |
+
const unsubscribePerf = effectivePerformanceLevel.subscribe((level) => {
|
| 79 |
+
isLightweight = level === 'low';
|
| 80 |
+
});
|
| 81 |
+
|
| 82 |
+
// Subscribe to player changes
|
| 83 |
+
const unsubscribePlayer = playerStore.subscribe(async (state) => {
|
| 84 |
+
if (state.currentTrack && state.currentTrack.id !== currentTrackId) {
|
| 85 |
+
currentTrackId = state.currentTrack.id;
|
| 86 |
+
let coverUrl = '';
|
| 87 |
+
if ('thumbnailUrl' in state.currentTrack && state.currentTrack.thumbnailUrl) {
|
| 88 |
+
coverUrl = state.currentTrack.thumbnailUrl;
|
| 89 |
+
} else if ('album' in state.currentTrack && state.currentTrack.album?.cover) {
|
| 90 |
+
coverUrl = state.currentTrack.album.cover;
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
if (coverUrl) {
|
| 94 |
+
await updateFromTrack(coverUrl);
|
| 95 |
+
}
|
| 96 |
+
}
|
| 97 |
+
});
|
| 98 |
+
|
| 99 |
+
return () => {
|
| 100 |
+
unsubscribePerf();
|
| 101 |
+
unsubscribePlayer();
|
| 102 |
+
};
|
| 103 |
+
});
|
| 104 |
+
|
| 105 |
+
onDestroy(() => {
|
| 106 |
+
if (animationFrameId !== null) {
|
| 107 |
+
cancelAnimationFrame(animationFrameId);
|
| 108 |
+
}
|
| 109 |
+
cleanupWebGL();
|
| 110 |
+
});
|
| 111 |
+
|
| 112 |
+
function initializeWebGL() {
|
| 113 |
+
if (!canvasElement) return;
|
| 114 |
+
|
| 115 |
+
// Set canvas size
|
| 116 |
+
canvasElement.width = DISPLAY_CANVAS_SIZE;
|
| 117 |
+
canvasElement.height = DISPLAY_CANVAS_SIZE;
|
| 118 |
+
|
| 119 |
+
// Get WebGL context
|
| 120 |
+
gl = canvasElement.getContext('webgl', {
|
| 121 |
+
alpha: false,
|
| 122 |
+
antialias: false,
|
| 123 |
+
depth: false,
|
| 124 |
+
premultipliedAlpha: false,
|
| 125 |
+
preserveDrawingBuffer: false
|
| 126 |
+
});
|
| 127 |
+
|
| 128 |
+
if (!gl) {
|
| 129 |
+
console.error('WebGL not supported');
|
| 130 |
+
return;
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
// Handle context loss
|
| 134 |
+
canvasElement.addEventListener('webglcontextlost', handleContextLost, false);
|
| 135 |
+
canvasElement.addEventListener('webglcontextrestored', handleContextRestored, false);
|
| 136 |
+
|
| 137 |
+
setupShaders();
|
| 138 |
+
setupTextures();
|
| 139 |
+
setupFramebuffers();
|
| 140 |
+
initializeCellStates();
|
| 141 |
+
startAnimation();
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
function setupShaders() {
|
| 145 |
+
if (!gl) return;
|
| 146 |
+
|
| 147 |
+
// Create vertex shader
|
| 148 |
+
const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
|
| 149 |
+
if (!vertexShader) return;
|
| 150 |
+
|
| 151 |
+
// Create update state program
|
| 152 |
+
const updateStateFragShader = createShader(gl, gl.FRAGMENT_SHADER, updateStateShaderSource);
|
| 153 |
+
if (updateStateFragShader) {
|
| 154 |
+
updateStateProgram = createProgram(gl, vertexShader, updateStateFragShader);
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
// Create color render program
|
| 158 |
+
const colorRenderFragShader = createShader(gl, gl.FRAGMENT_SHADER, colorRenderShaderSource);
|
| 159 |
+
if (colorRenderFragShader) {
|
| 160 |
+
colorRenderProgram = createProgram(gl, vertexShader, colorRenderFragShader);
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
// Create blur program
|
| 164 |
+
const blurFragShader = createShader(gl, gl.FRAGMENT_SHADER, blurFragmentShaderSource);
|
| 165 |
+
if (blurFragShader) {
|
| 166 |
+
blurProgram = createProgram(gl, vertexShader, blurFragShader);
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
setupQuad(gl);
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
function setupTextures() {
|
| 173 |
+
if (!gl) return;
|
| 174 |
+
|
| 175 |
+
const blurWidth = Math.round(DISPLAY_CANVAS_SIZE / BLUR_DOWNSAMPLE_FACTOR);
|
| 176 |
+
const blurHeight = Math.round(DISPLAY_CANVAS_SIZE / BLUR_DOWNSAMPLE_FACTOR);
|
| 177 |
+
|
| 178 |
+
// Palette texture (8x10 - double-buffered palette)
|
| 179 |
+
paletteTexture = createTexture(gl, DISPLAY_GRID_WIDTH, DISPLAY_GRID_HEIGHT * 2);
|
| 180 |
+
|
| 181 |
+
// Cell state textures (8x5 - ping-pong for state updates)
|
| 182 |
+
cellStateTexture = createTexture(gl, DISPLAY_GRID_WIDTH, DISPLAY_GRID_HEIGHT);
|
| 183 |
+
cellStateTexture2 = createTexture(gl, DISPLAY_GRID_WIDTH, DISPLAY_GRID_HEIGHT);
|
| 184 |
+
|
| 185 |
+
// Color render texture (32x18)
|
| 186 |
+
colorRenderTexture = createTexture(gl, STRETCHED_GRID_WIDTH, STRETCHED_GRID_HEIGHT);
|
| 187 |
+
|
| 188 |
+
// Blur textures
|
| 189 |
+
blurTexture1 = createTexture(gl, blurWidth, blurHeight);
|
| 190 |
+
blurTexture2 = createTexture(gl, blurWidth, blurHeight);
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
function setupFramebuffers() {
|
| 194 |
+
if (!gl || !cellStateTexture || !cellStateTexture2 || !colorRenderTexture || !blurTexture1 || !blurTexture2) return;
|
| 195 |
+
|
| 196 |
+
stateFramebuffer1 = createFramebuffer(gl, cellStateTexture);
|
| 197 |
+
stateFramebuffer2 = createFramebuffer(gl, cellStateTexture2);
|
| 198 |
+
colorRenderFramebuffer = createFramebuffer(gl, colorRenderTexture);
|
| 199 |
+
blurFramebuffer1 = createFramebuffer(gl, blurTexture1);
|
| 200 |
+
blurFramebuffer2 = createFramebuffer(gl, blurTexture2);
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
function initializeCellStates() {
|
| 204 |
+
if (!gl || !cellStateTexture) return;
|
| 205 |
+
|
| 206 |
+
// Initialize with random states
|
| 207 |
+
const stateData = new Uint8Array(DISPLAY_GRID_WIDTH * DISPLAY_GRID_HEIGHT * 4);
|
| 208 |
+
|
| 209 |
+
for (let i = 0; i < MASTER_PALETTE_SIZE; i++) {
|
| 210 |
+
const idx = i * 4;
|
| 211 |
+
const sourceIdx = Math.floor(Math.random() * MASTER_PALETTE_SIZE);
|
| 212 |
+
const targetIdx = Math.floor(Math.random() * MASTER_PALETTE_SIZE);
|
| 213 |
+
const progress = Math.random();
|
| 214 |
+
const speed = (Math.random() * 0.5 + 0.5) * 0.48;
|
| 215 |
+
|
| 216 |
+
stateData[idx] = Math.round((sourceIdx / 39) * 255);
|
| 217 |
+
stateData[idx + 1] = Math.round((targetIdx / 39) * 255);
|
| 218 |
+
stateData[idx + 2] = Math.round(progress * 255);
|
| 219 |
+
stateData[idx + 3] = Math.round((speed / 10.0) * 255);
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
gl.bindTexture(gl.TEXTURE_2D, cellStateTexture);
|
| 223 |
+
gl.texImage2D(
|
| 224 |
+
gl.TEXTURE_2D,
|
| 225 |
+
0,
|
| 226 |
+
gl.RGBA,
|
| 227 |
+
DISPLAY_GRID_WIDTH,
|
| 228 |
+
DISPLAY_GRID_HEIGHT,
|
| 229 |
+
0,
|
| 230 |
+
gl.RGBA,
|
| 231 |
+
gl.UNSIGNED_BYTE,
|
| 232 |
+
stateData
|
| 233 |
+
);
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
async function updateFromTrack(coverUrl: string) {
|
| 237 |
+
try {
|
| 238 |
+
const fullCoverUrl = coverUrl.startsWith('http') ? coverUrl : losslessAPI.getCoverUrl(coverUrl, '640');
|
| 239 |
+
const palette = await extractPaletteFromImage(
|
| 240 |
+
fullCoverUrl,
|
| 241 |
+
DISPLAY_GRID_WIDTH,
|
| 242 |
+
DISPLAY_GRID_HEIGHT,
|
| 243 |
+
STRETCHED_GRID_WIDTH,
|
| 244 |
+
STRETCHED_GRID_HEIGHT
|
| 245 |
+
);
|
| 246 |
+
|
| 247 |
+
// Shift current target to previous
|
| 248 |
+
previousPalette = targetPalette.length > 0 ? targetPalette : palette;
|
| 249 |
+
targetPalette = palette;
|
| 250 |
+
|
| 251 |
+
// Update palette texture
|
| 252 |
+
updatePaletteTexture();
|
| 253 |
+
|
| 254 |
+
// Reset transition
|
| 255 |
+
songPaletteTransitionProgress = 0.0;
|
| 256 |
+
|
| 257 |
+
// Get vibrant color for lyrics (could be exposed via a store)
|
| 258 |
+
const vibrantColor = getMostVibrantColor(palette);
|
| 259 |
+
document.documentElement.style.setProperty(
|
| 260 |
+
'--dynamic-bg-vibrant',
|
| 261 |
+
`rgb(${vibrantColor.r}, ${vibrantColor.g}, ${vibrantColor.b})`
|
| 262 |
+
);
|
| 263 |
+
} catch (error) {
|
| 264 |
+
console.error('Failed to update background from track:', error);
|
| 265 |
+
}
|
| 266 |
+
}
|
| 267 |
+
|
| 268 |
+
function updatePaletteTexture() {
|
| 269 |
+
if (!gl || !paletteTexture) return;
|
| 270 |
+
|
| 271 |
+
const textureData = new Uint8Array(DISPLAY_GRID_WIDTH * DISPLAY_GRID_HEIGHT * 2 * 4);
|
| 272 |
+
|
| 273 |
+
// Write previous palette to rows 0-4
|
| 274 |
+
for (let i = 0; i < MASTER_PALETTE_SIZE; i++) {
|
| 275 |
+
const color = previousPalette[i] || { r: 0, g: 0, b: 0, a: 255 };
|
| 276 |
+
const idx = i * 4;
|
| 277 |
+
textureData[idx] = color.r;
|
| 278 |
+
textureData[idx + 1] = color.g;
|
| 279 |
+
textureData[idx + 2] = color.b;
|
| 280 |
+
textureData[idx + 3] = color.a;
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
// Write target palette to rows 5-9
|
| 284 |
+
for (let i = 0; i < MASTER_PALETTE_SIZE; i++) {
|
| 285 |
+
const color = targetPalette[i] || { r: 0, g: 0, b: 0, a: 255 };
|
| 286 |
+
const idx = (MASTER_PALETTE_SIZE + i) * 4;
|
| 287 |
+
textureData[idx] = color.r;
|
| 288 |
+
textureData[idx + 1] = color.g;
|
| 289 |
+
textureData[idx + 2] = color.b;
|
| 290 |
+
textureData[idx + 3] = color.a;
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
gl.bindTexture(gl.TEXTURE_2D, paletteTexture);
|
| 294 |
+
gl.texImage2D(
|
| 295 |
+
gl.TEXTURE_2D,
|
| 296 |
+
0,
|
| 297 |
+
gl.RGBA,
|
| 298 |
+
DISPLAY_GRID_WIDTH,
|
| 299 |
+
DISPLAY_GRID_HEIGHT * 2,
|
| 300 |
+
0,
|
| 301 |
+
gl.RGBA,
|
| 302 |
+
gl.UNSIGNED_BYTE,
|
| 303 |
+
textureData
|
| 304 |
+
);
|
| 305 |
+
}
|
| 306 |
+
|
| 307 |
+
function startAnimation() {
|
| 308 |
+
if (animationFrameId !== null) return;
|
| 309 |
+
lastFrameTime = performance.now();
|
| 310 |
+
animationFrameId = requestAnimationFrame(animate);
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
function stopAnimation() {
|
| 314 |
+
if (animationFrameId !== null) {
|
| 315 |
+
cancelAnimationFrame(animationFrameId);
|
| 316 |
+
animationFrameId = null;
|
| 317 |
+
}
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
function animate(currentTime: number) {
|
| 321 |
+
if (!gl || !isVisible) {
|
| 322 |
+
animationFrameId = requestAnimationFrame(animate);
|
| 323 |
+
return;
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
const deltaTime = Math.min((currentTime - lastFrameTime) / 1000, 0.1); // Cap at 100ms
|
| 327 |
+
lastFrameTime = currentTime;
|
| 328 |
+
|
| 329 |
+
// Update animation state
|
| 330 |
+
if (songPaletteTransitionProgress < 1.0) {
|
| 331 |
+
songPaletteTransitionProgress = Math.min(1.0, songPaletteTransitionProgress + SONG_PALETTE_TRANSITION_SPEED);
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
scrollOffset += SCROLL_SPEED * deltaTime;
|
| 335 |
+
if (scrollOffset >= 1.0) scrollOffset -= 1.0;
|
| 336 |
+
|
| 337 |
+
// Render pipeline
|
| 338 |
+
renderPipeline(deltaTime, currentTime);
|
| 339 |
+
|
| 340 |
+
animationFrameId = requestAnimationFrame(animate);
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
function renderPipeline(deltaTime: number, currentTime: number) {
|
| 344 |
+
if (!gl) return;
|
| 345 |
+
|
| 346 |
+
// Pass 1: Update cell states (skip in lightweight mode unless transitioning)
|
| 347 |
+
if (!isLightweight || songPaletteTransitionProgress < 1.0) {
|
| 348 |
+
updateCellStates(deltaTime, currentTime);
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
// Pass 2: Render colors with current states
|
| 352 |
+
renderColors();
|
| 353 |
+
|
| 354 |
+
// Pass 3: Horizontal blur
|
| 355 |
+
renderHorizontalBlur();
|
| 356 |
+
|
| 357 |
+
// Pass 4: Vertical blur and display
|
| 358 |
+
renderVerticalBlur();
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
function updateCellStates(deltaTime: number, currentTime: number) {
|
| 362 |
+
if (!gl || !updateStateProgram || !stateFramebuffer1 || !stateFramebuffer2) return;
|
| 363 |
+
|
| 364 |
+
gl.useProgram(updateStateProgram);
|
| 365 |
+
|
| 366 |
+
// Bind source state texture
|
| 367 |
+
const sourceTexture = currentStateTexture === 0 ? cellStateTexture : cellStateTexture2;
|
| 368 |
+
const targetFramebuffer = currentStateTexture === 0 ? stateFramebuffer2 : stateFramebuffer1;
|
| 369 |
+
|
| 370 |
+
gl.activeTexture(gl.TEXTURE0);
|
| 371 |
+
gl.bindTexture(gl.TEXTURE_2D, sourceTexture);
|
| 372 |
+
gl.uniform1i(gl.getUniformLocation(updateStateProgram, 'u_currentStateTexture'), 0);
|
| 373 |
+
gl.uniform1f(gl.getUniformLocation(updateStateProgram, 'u_deltaTime'), deltaTime);
|
| 374 |
+
gl.uniform1f(gl.getUniformLocation(updateStateProgram, 'u_time'), currentTime);
|
| 375 |
+
|
| 376 |
+
// Set up attributes
|
| 377 |
+
setupAttributes(updateStateProgram);
|
| 378 |
+
|
| 379 |
+
// Render to target framebuffer
|
| 380 |
+
gl.bindFramebuffer(gl.FRAMEBUFFER, targetFramebuffer);
|
| 381 |
+
gl.viewport(0, 0, DISPLAY_GRID_WIDTH, DISPLAY_GRID_HEIGHT);
|
| 382 |
+
gl.drawArrays(gl.TRIANGLES, 0, 6);
|
| 383 |
+
|
| 384 |
+
// Swap state textures
|
| 385 |
+
currentStateTexture = 1 - currentStateTexture;
|
| 386 |
+
}
|
| 387 |
+
|
| 388 |
+
function renderColors() {
|
| 389 |
+
if (!gl || !colorRenderProgram || !colorRenderFramebuffer) return;
|
| 390 |
+
|
| 391 |
+
gl.useProgram(colorRenderProgram);
|
| 392 |
+
|
| 393 |
+
// Bind palette texture
|
| 394 |
+
gl.activeTexture(gl.TEXTURE0);
|
| 395 |
+
gl.bindTexture(gl.TEXTURE_2D, paletteTexture);
|
| 396 |
+
gl.uniform1i(gl.getUniformLocation(colorRenderProgram, 'u_paletteTexture'), 0);
|
| 397 |
+
|
| 398 |
+
// Bind cell state texture
|
| 399 |
+
const currentTexture = currentStateTexture === 0 ? cellStateTexture : cellStateTexture2;
|
| 400 |
+
gl.activeTexture(gl.TEXTURE1);
|
| 401 |
+
gl.bindTexture(gl.TEXTURE_2D, currentTexture);
|
| 402 |
+
gl.uniform1i(gl.getUniformLocation(colorRenderProgram, 'u_cellStateTexture'), 1);
|
| 403 |
+
|
| 404 |
+
// Set uniforms
|
| 405 |
+
gl.uniform1f(
|
| 406 |
+
gl.getUniformLocation(colorRenderProgram, 'u_songPaletteTransitionProgress'),
|
| 407 |
+
songPaletteTransitionProgress
|
| 408 |
+
);
|
| 409 |
+
gl.uniform1f(gl.getUniformLocation(colorRenderProgram, 'u_scrollOffset'), scrollOffset);
|
| 410 |
+
|
| 411 |
+
// Set up attributes
|
| 412 |
+
setupAttributes(colorRenderProgram);
|
| 413 |
+
|
| 414 |
+
// Render to color framebuffer
|
| 415 |
+
gl.bindFramebuffer(gl.FRAMEBUFFER, colorRenderFramebuffer);
|
| 416 |
+
gl.viewport(0, 0, STRETCHED_GRID_WIDTH, STRETCHED_GRID_HEIGHT);
|
| 417 |
+
gl.drawArrays(gl.TRIANGLES, 0, 6);
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
function renderHorizontalBlur() {
|
| 421 |
+
if (!gl || !blurProgram || !blurFramebuffer1) return;
|
| 422 |
+
|
| 423 |
+
gl.useProgram(blurProgram);
|
| 424 |
+
|
| 425 |
+
// Bind color render texture
|
| 426 |
+
gl.activeTexture(gl.TEXTURE0);
|
| 427 |
+
gl.bindTexture(gl.TEXTURE_2D, colorRenderTexture);
|
| 428 |
+
gl.uniform1i(gl.getUniformLocation(blurProgram, 'u_image'), 0);
|
| 429 |
+
|
| 430 |
+
const blurWidth = Math.round(DISPLAY_CANVAS_SIZE / BLUR_DOWNSAMPLE_FACTOR);
|
| 431 |
+
const blurHeight = Math.round(DISPLAY_CANVAS_SIZE / BLUR_DOWNSAMPLE_FACTOR);
|
| 432 |
+
|
| 433 |
+
gl.uniform2f(gl.getUniformLocation(blurProgram, 'u_resolution'), blurWidth, blurHeight);
|
| 434 |
+
gl.uniform2f(gl.getUniformLocation(blurProgram, 'u_direction'), 1.0, 0.0); // Horizontal
|
| 435 |
+
|
| 436 |
+
// Set up attributes
|
| 437 |
+
setupAttributes(blurProgram);
|
| 438 |
+
|
| 439 |
+
// Render to blur framebuffer
|
| 440 |
+
gl.bindFramebuffer(gl.FRAMEBUFFER, blurFramebuffer1);
|
| 441 |
+
gl.viewport(0, 0, blurWidth, blurHeight);
|
| 442 |
+
gl.drawArrays(gl.TRIANGLES, 0, 6);
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
+
function renderVerticalBlur() {
|
| 446 |
+
if (!gl || !blurProgram) return;
|
| 447 |
+
|
| 448 |
+
gl.useProgram(blurProgram);
|
| 449 |
+
|
| 450 |
+
// Bind horizontal blur result
|
| 451 |
+
gl.activeTexture(gl.TEXTURE0);
|
| 452 |
+
gl.bindTexture(gl.TEXTURE_2D, blurTexture1);
|
| 453 |
+
gl.uniform1i(gl.getUniformLocation(blurProgram, 'u_image'), 0);
|
| 454 |
+
|
| 455 |
+
const blurWidth = Math.round(DISPLAY_CANVAS_SIZE / BLUR_DOWNSAMPLE_FACTOR);
|
| 456 |
+
const blurHeight = Math.round(DISPLAY_CANVAS_SIZE / BLUR_DOWNSAMPLE_FACTOR);
|
| 457 |
+
|
| 458 |
+
gl.uniform2f(gl.getUniformLocation(blurProgram, 'u_resolution'), blurWidth, blurHeight);
|
| 459 |
+
gl.uniform2f(gl.getUniformLocation(blurProgram, 'u_direction'), 0.0, 1.0); // Vertical
|
| 460 |
+
|
| 461 |
+
// Set up attributes
|
| 462 |
+
setupAttributes(blurProgram);
|
| 463 |
+
|
| 464 |
+
// Render to canvas
|
| 465 |
+
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
| 466 |
+
gl.viewport(0, 0, DISPLAY_CANVAS_SIZE, DISPLAY_CANVAS_SIZE);
|
| 467 |
+
gl.drawArrays(gl.TRIANGLES, 0, 6);
|
| 468 |
+
}
|
| 469 |
+
|
| 470 |
+
function setupAttributes(program: WebGLProgram) {
|
| 471 |
+
if (!gl) return;
|
| 472 |
+
|
| 473 |
+
const positionLocation = gl.getAttribLocation(program, 'a_position');
|
| 474 |
+
const texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
|
| 475 |
+
|
| 476 |
+
// Position attribute
|
| 477 |
+
const positions = new Float32Array([
|
| 478 |
+
-1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0
|
| 479 |
+
]);
|
| 480 |
+
const positionBuffer = gl.createBuffer();
|
| 481 |
+
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
|
| 482 |
+
gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);
|
| 483 |
+
gl.enableVertexAttribArray(positionLocation);
|
| 484 |
+
gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
|
| 485 |
+
|
| 486 |
+
// TexCoord attribute
|
| 487 |
+
const texCoords = new Float32Array([0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0]);
|
| 488 |
+
const texCoordBuffer = gl.createBuffer();
|
| 489 |
+
gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
|
| 490 |
+
gl.bufferData(gl.ARRAY_BUFFER, texCoords, gl.STATIC_DRAW);
|
| 491 |
+
gl.enableVertexAttribArray(texCoordLocation);
|
| 492 |
+
gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
|
| 493 |
+
}
|
| 494 |
+
|
| 495 |
+
function setupIntersectionObserver() {
|
| 496 |
+
if (!canvasElement || typeof IntersectionObserver === 'undefined') return;
|
| 497 |
+
|
| 498 |
+
const observer = new IntersectionObserver(
|
| 499 |
+
(entries) => {
|
| 500 |
+
for (const entry of entries) {
|
| 501 |
+
isVisible = entry.isIntersecting;
|
| 502 |
+
if (entry.isIntersecting) {
|
| 503 |
+
startAnimation();
|
| 504 |
+
} else {
|
| 505 |
+
stopAnimation();
|
| 506 |
+
}
|
| 507 |
+
}
|
| 508 |
+
},
|
| 509 |
+
{ threshold: 0.01 }
|
| 510 |
+
);
|
| 511 |
+
|
| 512 |
+
observer.observe(canvasElement);
|
| 513 |
+
}
|
| 514 |
+
|
| 515 |
+
function handleContextLost(event: Event) {
|
| 516 |
+
event.preventDefault();
|
| 517 |
+
stopAnimation();
|
| 518 |
+
console.warn('WebGL context lost');
|
| 519 |
+
}
|
| 520 |
+
|
| 521 |
+
function handleContextRestored() {
|
| 522 |
+
console.log('WebGL context restored');
|
| 523 |
+
initializeWebGL();
|
| 524 |
+
}
|
| 525 |
+
|
| 526 |
+
function cleanupWebGL() {
|
| 527 |
+
if (!gl) return;
|
| 528 |
+
|
| 529 |
+
// Delete textures
|
| 530 |
+
if (paletteTexture) gl.deleteTexture(paletteTexture);
|
| 531 |
+
if (cellStateTexture) gl.deleteTexture(cellStateTexture);
|
| 532 |
+
if (cellStateTexture2) gl.deleteTexture(cellStateTexture2);
|
| 533 |
+
if (colorRenderTexture) gl.deleteTexture(colorRenderTexture);
|
| 534 |
+
if (blurTexture1) gl.deleteTexture(blurTexture1);
|
| 535 |
+
if (blurTexture2) gl.deleteTexture(blurTexture2);
|
| 536 |
+
|
| 537 |
+
// Delete framebuffers
|
| 538 |
+
if (stateFramebuffer1) gl.deleteFramebuffer(stateFramebuffer1);
|
| 539 |
+
if (stateFramebuffer2) gl.deleteFramebuffer(stateFramebuffer2);
|
| 540 |
+
if (colorRenderFramebuffer) gl.deleteFramebuffer(colorRenderFramebuffer);
|
| 541 |
+
if (blurFramebuffer1) gl.deleteFramebuffer(blurFramebuffer1);
|
| 542 |
+
if (blurFramebuffer2) gl.deleteFramebuffer(blurFramebuffer2);
|
| 543 |
+
|
| 544 |
+
// Delete programs
|
| 545 |
+
if (updateStateProgram) gl.deleteProgram(updateStateProgram);
|
| 546 |
+
if (colorRenderProgram) gl.deleteProgram(colorRenderProgram);
|
| 547 |
+
if (blurProgram) gl.deleteProgram(blurProgram);
|
| 548 |
+
}
|
| 549 |
+
</script>
|
| 550 |
+
|
| 551 |
+
<div class="dynamic-background-container">
|
| 552 |
+
<canvas bind:this={canvasElement} class="dynamic-background-canvas"></canvas>
|
| 553 |
+
</div>
|
| 554 |
+
|
| 555 |
+
<style>
|
| 556 |
+
.dynamic-background-container {
|
| 557 |
+
position: fixed;
|
| 558 |
+
top: 0;
|
| 559 |
+
left: 0;
|
| 560 |
+
width: 100%;
|
| 561 |
+
height: 100%;
|
| 562 |
+
z-index: -1;
|
| 563 |
+
overflow: hidden;
|
| 564 |
+
pointer-events: none;
|
| 565 |
+
}
|
| 566 |
+
|
| 567 |
+
.dynamic-background-canvas {
|
| 568 |
+
width: 100%;
|
| 569 |
+
height: 100%;
|
| 570 |
+
object-fit: cover;
|
| 571 |
+
filter: blur(0px);
|
| 572 |
+
}
|
| 573 |
+
</style>
|
src/lib/components/LyricsPopup.svelte
ADDED
|
@@ -0,0 +1,830 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<script lang="ts">
|
| 2 |
+
import { browser } from '$app/environment';
|
| 3 |
+
import { onDestroy } from 'svelte';
|
| 4 |
+
import { currentTime, playerStore } from '$lib/stores/player';
|
| 5 |
+
import { lyricsStore } from '$lib/stores/lyrics';
|
| 6 |
+
import { formatArtists } from '$lib/utils';
|
| 7 |
+
import { isSonglinkTrack } from '$lib/types';
|
| 8 |
+
import { Maximize2, Minimize2, RefreshCw, X } from 'lucide-svelte';
|
| 9 |
+
|
| 10 |
+
const COMPONENT_MODULE_URL =
|
| 11 |
+
'https://cdn.jsdelivr.net/npm/@uimaxbai/am-lyrics/dist/src/am-lyrics.min.js';
|
| 12 |
+
const SEEK_FORCE_THRESHOLD_MS = 220;
|
| 13 |
+
|
| 14 |
+
type LyricsMetadata = {
|
| 15 |
+
title: string;
|
| 16 |
+
artist: string;
|
| 17 |
+
album?: string;
|
| 18 |
+
query: string;
|
| 19 |
+
durationMs?: number;
|
| 20 |
+
isrc?: string;
|
| 21 |
+
};
|
| 22 |
+
|
| 23 |
+
type AmLyricsElement = HTMLElement & {
|
| 24 |
+
currentTime: number;
|
| 25 |
+
scrollToActiveLine?: () => void;
|
| 26 |
+
scrollToInstrumental?: (index: number) => void;
|
| 27 |
+
activeLineIndices?: number[];
|
| 28 |
+
shadowRoot: ShadowRoot | null;
|
| 29 |
+
updateComplete?: Promise<unknown>;
|
| 30 |
+
__tidalScrollPatched?: boolean;
|
| 31 |
+
};
|
| 32 |
+
|
| 33 |
+
let amLyricsElement = $state<AmLyricsElement | null>(null);
|
| 34 |
+
let scriptStatus = $state<'idle' | 'loading' | 'ready' | 'error'>('idle');
|
| 35 |
+
let scriptError = $state<string | null>(null);
|
| 36 |
+
let pendingLoad: Promise<void> | null = null;
|
| 37 |
+
let hasEscapeListener = false;
|
| 38 |
+
|
| 39 |
+
let baseTimeMs = $state(0);
|
| 40 |
+
let lyricsKey = $state('0:none');
|
| 41 |
+
let metadata = $state<LyricsMetadata | null>(null);
|
| 42 |
+
let animationFrameId: number | null = null;
|
| 43 |
+
let lastBaseTimestamp = 0;
|
| 44 |
+
let scrollPatchFrame: number | null = null;
|
| 45 |
+
let lastRefreshedTrackId = $state<number | string | null>(null);
|
| 46 |
+
|
| 47 |
+
$effect(() => {
|
| 48 |
+
const seconds = $currentTime ?? 0;
|
| 49 |
+
const playing = $playerStore.isPlaying;
|
| 50 |
+
const nextMs = Number.isFinite(seconds) ? Math.max(0, seconds * 1000) : 0;
|
| 51 |
+
baseTimeMs = nextMs;
|
| 52 |
+
if (browser) {
|
| 53 |
+
lastBaseTimestamp = performance.now();
|
| 54 |
+
}
|
| 55 |
+
if (scriptStatus === 'ready' && amLyricsElement) {
|
| 56 |
+
const current = Number(amLyricsElement.currentTime ?? 0);
|
| 57 |
+
const delta = Math.abs(current - nextMs);
|
| 58 |
+
if (!playing || delta > SEEK_FORCE_THRESHOLD_MS) {
|
| 59 |
+
amLyricsElement.currentTime = nextMs;
|
| 60 |
+
}
|
| 61 |
+
}
|
| 62 |
+
});
|
| 63 |
+
|
| 64 |
+
$effect(() => {
|
| 65 |
+
lyricsKey = `${$lyricsStore.refreshToken}:${$lyricsStore.track?.id ?? 'none'}`;
|
| 66 |
+
});
|
| 67 |
+
|
| 68 |
+
$effect(() => {
|
| 69 |
+
if ($lyricsStore.open && browser) {
|
| 70 |
+
void ensureComponentLoaded();
|
| 71 |
+
}
|
| 72 |
+
attachEscapeListener($lyricsStore.open);
|
| 73 |
+
});
|
| 74 |
+
|
| 75 |
+
onDestroy(() => {
|
| 76 |
+
attachEscapeListener(false);
|
| 77 |
+
});
|
| 78 |
+
|
| 79 |
+
async function ensureComponentLoaded() {
|
| 80 |
+
if (scriptStatus === 'ready') {
|
| 81 |
+
return;
|
| 82 |
+
}
|
| 83 |
+
if (typeof customElements !== 'undefined' && customElements.get('am-lyrics')) {
|
| 84 |
+
scriptStatus = 'ready';
|
| 85 |
+
scriptError = null;
|
| 86 |
+
return;
|
| 87 |
+
}
|
| 88 |
+
if (pendingLoad) {
|
| 89 |
+
scriptStatus = 'loading';
|
| 90 |
+
try {
|
| 91 |
+
await pendingLoad;
|
| 92 |
+
} catch {
|
| 93 |
+
// handled when the original promise settles
|
| 94 |
+
}
|
| 95 |
+
return;
|
| 96 |
+
}
|
| 97 |
+
if (!browser) return;
|
| 98 |
+
|
| 99 |
+
scriptStatus = 'loading';
|
| 100 |
+
scriptError = null;
|
| 101 |
+
|
| 102 |
+
pendingLoad = loadComponentScript()
|
| 103 |
+
.then(() => {
|
| 104 |
+
scriptStatus = 'ready';
|
| 105 |
+
scriptError = null;
|
| 106 |
+
if (amLyricsElement) {
|
| 107 |
+
amLyricsElement.currentTime = baseTimeMs;
|
| 108 |
+
}
|
| 109 |
+
})
|
| 110 |
+
.catch((error) => {
|
| 111 |
+
console.error('Failed to load Apple Music lyrics component', error);
|
| 112 |
+
scriptStatus = 'error';
|
| 113 |
+
scriptError = error instanceof Error ? error.message : 'Unable to load lyrics component.';
|
| 114 |
+
})
|
| 115 |
+
.finally(() => {
|
| 116 |
+
pendingLoad = null;
|
| 117 |
+
});
|
| 118 |
+
|
| 119 |
+
await pendingLoad;
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
function loadComponentScript(): Promise<void> {
|
| 123 |
+
return new Promise((resolve, reject) => {
|
| 124 |
+
if (!browser) {
|
| 125 |
+
resolve();
|
| 126 |
+
return;
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
const waitForDefinition = () => {
|
| 130 |
+
if (typeof customElements !== 'undefined' && 'whenDefined' in customElements) {
|
| 131 |
+
customElements
|
| 132 |
+
.whenDefined('am-lyrics')
|
| 133 |
+
.then(() => resolve())
|
| 134 |
+
.catch(reject);
|
| 135 |
+
} else {
|
| 136 |
+
resolve();
|
| 137 |
+
}
|
| 138 |
+
};
|
| 139 |
+
|
| 140 |
+
if (typeof customElements !== 'undefined' && customElements.get('am-lyrics')) {
|
| 141 |
+
resolve();
|
| 142 |
+
return;
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
const existing = document.querySelector<HTMLScriptElement>('script[data-am-lyrics]');
|
| 146 |
+
if (existing) {
|
| 147 |
+
if (existing.dataset.loaded === 'true') {
|
| 148 |
+
waitForDefinition();
|
| 149 |
+
return;
|
| 150 |
+
}
|
| 151 |
+
const handleLoad = () => {
|
| 152 |
+
existing.dataset.loaded = 'true';
|
| 153 |
+
waitForDefinition();
|
| 154 |
+
};
|
| 155 |
+
const handleError = () => {
|
| 156 |
+
existing.removeEventListener('load', handleLoad);
|
| 157 |
+
existing.removeEventListener('error', handleError);
|
| 158 |
+
existing.remove();
|
| 159 |
+
reject(new Error('Failed to load lyrics component.'));
|
| 160 |
+
};
|
| 161 |
+
existing.addEventListener('load', handleLoad, { once: true });
|
| 162 |
+
existing.addEventListener('error', handleError, { once: true });
|
| 163 |
+
return;
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
const script = document.createElement('script');
|
| 167 |
+
script.type = 'module';
|
| 168 |
+
script.src = COMPONENT_MODULE_URL;
|
| 169 |
+
script.dataset.amLyrics = 'true';
|
| 170 |
+
|
| 171 |
+
const handleLoad = () => {
|
| 172 |
+
script.dataset.loaded = 'true';
|
| 173 |
+
waitForDefinition();
|
| 174 |
+
};
|
| 175 |
+
|
| 176 |
+
const handleError = () => {
|
| 177 |
+
script.removeEventListener('load', handleLoad);
|
| 178 |
+
script.removeEventListener('error', handleError);
|
| 179 |
+
script.remove();
|
| 180 |
+
reject(new Error('Failed to load lyrics component.'));
|
| 181 |
+
};
|
| 182 |
+
|
| 183 |
+
script.addEventListener('load', handleLoad, { once: true });
|
| 184 |
+
script.addEventListener('error', handleError, { once: true });
|
| 185 |
+
document.head.append(script);
|
| 186 |
+
});
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
function handleOverlayClick(event: MouseEvent) {
|
| 190 |
+
if (event.target === event.currentTarget) {
|
| 191 |
+
lyricsStore.close();
|
| 192 |
+
}
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
function handleOverlayKeydown(event: KeyboardEvent) {
|
| 196 |
+
if (event.target !== event.currentTarget) return;
|
| 197 |
+
if (event.key === 'Enter' || event.key === ' ') {
|
| 198 |
+
event.preventDefault();
|
| 199 |
+
lyricsStore.close();
|
| 200 |
+
}
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
function handleEscape(event: KeyboardEvent) {
|
| 204 |
+
if (event.key === 'Escape' && $lyricsStore.open) {
|
| 205 |
+
event.preventDefault();
|
| 206 |
+
lyricsStore.close();
|
| 207 |
+
}
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
function attachEscapeListener(open: boolean) {
|
| 211 |
+
if (!browser) return;
|
| 212 |
+
if (open && !hasEscapeListener) {
|
| 213 |
+
window.addEventListener('keydown', handleEscape);
|
| 214 |
+
hasEscapeListener = true;
|
| 215 |
+
} else if (!open && hasEscapeListener) {
|
| 216 |
+
window.removeEventListener('keydown', handleEscape);
|
| 217 |
+
hasEscapeListener = false;
|
| 218 |
+
}
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
function stopAnimation() {
|
| 222 |
+
if (animationFrameId !== null) {
|
| 223 |
+
cancelAnimationFrame(animationFrameId);
|
| 224 |
+
animationFrameId = null;
|
| 225 |
+
}
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
function handleRefresh() {
|
| 229 |
+
if ($lyricsStore.track) {
|
| 230 |
+
lyricsStore.refresh();
|
| 231 |
+
}
|
| 232 |
+
if (scriptStatus !== 'ready' && browser) {
|
| 233 |
+
scriptStatus = 'idle';
|
| 234 |
+
scriptError = null;
|
| 235 |
+
void ensureComponentLoaded();
|
| 236 |
+
}
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
function handleRetry() {
|
| 240 |
+
scriptStatus = 'idle';
|
| 241 |
+
scriptError = null;
|
| 242 |
+
if (browser) {
|
| 243 |
+
void ensureComponentLoaded();
|
| 244 |
+
}
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
function handleLineClick(event: Event) {
|
| 248 |
+
const detail = (event as CustomEvent<{ timestamp: number }>).detail;
|
| 249 |
+
if (!detail) return;
|
| 250 |
+
const timeSeconds = detail.timestamp / 1000;
|
| 251 |
+
playerStore.play();
|
| 252 |
+
window.dispatchEvent(new CustomEvent('lyrics:seek', { detail: { timeSeconds } }));
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
function patchLyricsAutoscroll(element: AmLyricsElement, attempt = 0) {
|
| 256 |
+
if (!browser || !element || element.__tidalScrollPatched) {
|
| 257 |
+
return;
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
const container = element.shadowRoot?.querySelector<HTMLElement>('.lyrics-container');
|
| 261 |
+
if (!container) {
|
| 262 |
+
if (attempt > 8) return;
|
| 263 |
+
if (scrollPatchFrame !== null) {
|
| 264 |
+
cancelAnimationFrame(scrollPatchFrame);
|
| 265 |
+
}
|
| 266 |
+
scrollPatchFrame = requestAnimationFrame(() => {
|
| 267 |
+
patchLyricsAutoscroll(element, attempt + 1);
|
| 268 |
+
});
|
| 269 |
+
return;
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
scrollPatchFrame = null;
|
| 273 |
+
|
| 274 |
+
element.__tidalScrollPatched = true;
|
| 275 |
+
|
| 276 |
+
const styles = getComputedStyle(container);
|
| 277 |
+
const parsedPaddingTop = parseFloat(styles.paddingTop || '0');
|
| 278 |
+
const parsedPaddingBottom = parseFloat(styles.paddingBottom || '0');
|
| 279 |
+
const preferredFraction = 0.32;
|
| 280 |
+
const comfortTopFraction = 0.18;
|
| 281 |
+
const comfortBottomFraction = 0.22;
|
| 282 |
+
|
| 283 |
+
const computeScrollTarget = (line: HTMLElement) => {
|
| 284 |
+
const containerRect = container.getBoundingClientRect();
|
| 285 |
+
const lineRect = line.getBoundingClientRect();
|
| 286 |
+
const lineTop = lineRect.top - containerRect.top + container.scrollTop;
|
| 287 |
+
const lineBottom = lineTop + lineRect.height;
|
| 288 |
+
const viewportStart = container.scrollTop;
|
| 289 |
+
const viewportEnd = viewportStart + container.clientHeight;
|
| 290 |
+
const comfortStart = viewportStart + parsedPaddingTop + container.clientHeight * comfortTopFraction;
|
| 291 |
+
const comfortEnd = viewportEnd - parsedPaddingBottom - container.clientHeight * comfortBottomFraction;
|
| 292 |
+
|
| 293 |
+
if (lineTop >= comfortStart && lineBottom <= comfortEnd) {
|
| 294 |
+
return null;
|
| 295 |
+
}
|
| 296 |
+
|
| 297 |
+
const backgroundBefore = line.querySelector<HTMLElement>('.background-text.before');
|
| 298 |
+
const backgroundOffset = backgroundBefore
|
| 299 |
+
? Math.min(backgroundBefore.clientHeight / 2, lineRect.height * 0.6)
|
| 300 |
+
: 0;
|
| 301 |
+
|
| 302 |
+
const desiredTop =
|
| 303 |
+
lineTop - parsedPaddingTop - container.clientHeight * preferredFraction - backgroundOffset;
|
| 304 |
+
const maxScroll = container.scrollHeight - container.clientHeight;
|
| 305 |
+
|
| 306 |
+
return Math.max(0, Math.min(maxScroll, desiredTop));
|
| 307 |
+
};
|
| 308 |
+
|
| 309 |
+
const applyScroll = (target: number | null) => {
|
| 310 |
+
if (target === null) return;
|
| 311 |
+
const delta = Math.abs(container.scrollTop - target);
|
| 312 |
+
if (delta < 1) return;
|
| 313 |
+
container.scrollTo({ top: target, behavior: 'smooth' });
|
| 314 |
+
};
|
| 315 |
+
|
| 316 |
+
const originalActiveScroll = element.scrollToActiveLine?.bind(element);
|
| 317 |
+
element.scrollToActiveLine = function () {
|
| 318 |
+
const indices = Array.isArray(element.activeLineIndices)
|
| 319 |
+
? (element.activeLineIndices as number[])
|
| 320 |
+
: [];
|
| 321 |
+
if (!indices.length) {
|
| 322 |
+
originalActiveScroll?.();
|
| 323 |
+
return;
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
const targetIndex = Math.min(...indices);
|
| 327 |
+
const line = container.querySelector<HTMLElement>(
|
| 328 |
+
`.lyrics-line:nth-child(${targetIndex + 1})`
|
| 329 |
+
);
|
| 330 |
+
if (!line) {
|
| 331 |
+
originalActiveScroll?.();
|
| 332 |
+
return;
|
| 333 |
+
}
|
| 334 |
+
|
| 335 |
+
const target = computeScrollTarget(line);
|
| 336 |
+
if (target === null) return;
|
| 337 |
+
applyScroll(target);
|
| 338 |
+
};
|
| 339 |
+
|
| 340 |
+
const originalInstrumentalScroll = element.scrollToInstrumental?.bind(element);
|
| 341 |
+
element.scrollToInstrumental = function (index: number) {
|
| 342 |
+
const line = container.querySelector<HTMLElement>(`.lyrics-line:nth-child(${index + 1})`);
|
| 343 |
+
if (!line) {
|
| 344 |
+
originalInstrumentalScroll?.(index);
|
| 345 |
+
return;
|
| 346 |
+
}
|
| 347 |
+
|
| 348 |
+
const target = computeScrollTarget(line);
|
| 349 |
+
if (target === null) return;
|
| 350 |
+
applyScroll(target);
|
| 351 |
+
};
|
| 352 |
+
}
|
| 353 |
+
|
| 354 |
+
$effect(() => {
|
| 355 |
+
if (!amLyricsElement) {
|
| 356 |
+
return;
|
| 357 |
+
}
|
| 358 |
+
|
| 359 |
+
const listener = (event: Event) => handleLineClick(event);
|
| 360 |
+
amLyricsElement.addEventListener('line-click', listener as EventListener);
|
| 361 |
+
return () => {
|
| 362 |
+
amLyricsElement?.removeEventListener('line-click', listener as EventListener);
|
| 363 |
+
};
|
| 364 |
+
});
|
| 365 |
+
|
| 366 |
+
$effect(() => {
|
| 367 |
+
if (!browser) return;
|
| 368 |
+
const element = amLyricsElement as AmLyricsElement | null;
|
| 369 |
+
if (!element || scriptStatus !== 'ready') return;
|
| 370 |
+
patchLyricsAutoscroll(element);
|
| 371 |
+
});
|
| 372 |
+
|
| 373 |
+
$effect(() => {
|
| 374 |
+
const open = $lyricsStore.open;
|
| 375 |
+
const trackId = $lyricsStore.track?.id ?? null;
|
| 376 |
+
|
| 377 |
+
if (!open || !trackId) {
|
| 378 |
+
lastRefreshedTrackId = open ? trackId : null;
|
| 379 |
+
return;
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
if (trackId !== lastRefreshedTrackId) {
|
| 383 |
+
lastRefreshedTrackId = trackId;
|
| 384 |
+
lyricsStore.refresh();
|
| 385 |
+
}
|
| 386 |
+
});
|
| 387 |
+
|
| 388 |
+
$effect(() => {
|
| 389 |
+
if (!browser || !amLyricsElement) {
|
| 390 |
+
stopAnimation();
|
| 391 |
+
return;
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
+
if (scriptStatus !== 'ready' || !$lyricsStore.open) {
|
| 395 |
+
stopAnimation();
|
| 396 |
+
amLyricsElement.currentTime = baseTimeMs;
|
| 397 |
+
return;
|
| 398 |
+
}
|
| 399 |
+
|
| 400 |
+
if (!$playerStore.isPlaying) {
|
| 401 |
+
stopAnimation();
|
| 402 |
+
amLyricsElement.currentTime = baseTimeMs;
|
| 403 |
+
return;
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
const element = amLyricsElement;
|
| 407 |
+
const originBase = baseTimeMs;
|
| 408 |
+
const nowTimestamp = performance.now();
|
| 409 |
+
const originTimestamp =
|
| 410 |
+
lastBaseTimestamp && Math.abs(nowTimestamp - lastBaseTimestamp) < 1200
|
| 411 |
+
? lastBaseTimestamp
|
| 412 |
+
: nowTimestamp;
|
| 413 |
+
|
| 414 |
+
const tick = (now: number) => {
|
| 415 |
+
const elapsed = now - originTimestamp;
|
| 416 |
+
const nextMs = originBase + elapsed;
|
| 417 |
+
element.currentTime = nextMs;
|
| 418 |
+
animationFrameId = requestAnimationFrame(tick);
|
| 419 |
+
};
|
| 420 |
+
|
| 421 |
+
animationFrameId = requestAnimationFrame(tick);
|
| 422 |
+
return () => {
|
| 423 |
+
stopAnimation();
|
| 424 |
+
};
|
| 425 |
+
});
|
| 426 |
+
|
| 427 |
+
$effect(() => {
|
| 428 |
+
const track = $lyricsStore.track;
|
| 429 |
+
if (!track) {
|
| 430 |
+
metadata = null;
|
| 431 |
+
return;
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
let title: string;
|
| 435 |
+
let artist: string;
|
| 436 |
+
let album: string | undefined;
|
| 437 |
+
let isrc: string | undefined;
|
| 438 |
+
|
| 439 |
+
if (isSonglinkTrack(track)) {
|
| 440 |
+
title = track.title;
|
| 441 |
+
artist = track.artistName;
|
| 442 |
+
album = undefined;
|
| 443 |
+
isrc = undefined;
|
| 444 |
+
} else {
|
| 445 |
+
title = track.title;
|
| 446 |
+
artist = formatArtists(track.artists);
|
| 447 |
+
album = track.album?.title;
|
| 448 |
+
isrc = track.isrc;
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
const durationMs =
|
| 452 |
+
typeof track.duration === 'number'
|
| 453 |
+
? Math.max(0, Math.round(track.duration * 1000))
|
| 454 |
+
: undefined;
|
| 455 |
+
|
| 456 |
+
metadata = {
|
| 457 |
+
title,
|
| 458 |
+
artist,
|
| 459 |
+
album,
|
| 460 |
+
query: `${title} ${artist}`.trim(),
|
| 461 |
+
durationMs,
|
| 462 |
+
isrc: isrc ?? ''
|
| 463 |
+
};
|
| 464 |
+
});
|
| 465 |
+
</script>
|
| 466 |
+
|
| 467 |
+
{#if $lyricsStore.open}
|
| 468 |
+
<div
|
| 469 |
+
class="lyrics-overlay"
|
| 470 |
+
role="presentation"
|
| 471 |
+
onclick={handleOverlayClick}
|
| 472 |
+
onkeydown={handleOverlayKeydown}
|
| 473 |
+
tabindex="-1"
|
| 474 |
+
>
|
| 475 |
+
<div
|
| 476 |
+
class={`lyrics-panel ${$lyricsStore.maximized ? 'lyrics-panel--maximized' : ''}`}
|
| 477 |
+
role="dialog"
|
| 478 |
+
aria-modal="true"
|
| 479 |
+
aria-label="Lyrics"
|
| 480 |
+
>
|
| 481 |
+
<header class="lyrics-header">
|
| 482 |
+
<div class="lyrics-heading">
|
| 483 |
+
<h2 class="lyrics-title">Lyrics</h2>
|
| 484 |
+
{#if metadata}
|
| 485 |
+
<p class="lyrics-subtitle">{metadata.title} • {metadata.artist}</p>
|
| 486 |
+
{#if metadata.album}
|
| 487 |
+
<p class="lyrics-album">{metadata.album}</p>
|
| 488 |
+
{/if}
|
| 489 |
+
{:else}
|
| 490 |
+
<p class="lyrics-subtitle">Start playback to load synced lyrics.</p>
|
| 491 |
+
{/if}
|
| 492 |
+
</div>
|
| 493 |
+
<div class="lyrics-header-actions">
|
| 494 |
+
<button
|
| 495 |
+
type="button"
|
| 496 |
+
class="lyrics-icon-button"
|
| 497 |
+
onclick={handleRefresh}
|
| 498 |
+
aria-label="Refresh lyrics"
|
| 499 |
+
title="Refresh lyrics"
|
| 500 |
+
disabled={!metadata || scriptStatus === 'loading'}
|
| 501 |
+
>
|
| 502 |
+
<RefreshCw size={18} class={scriptStatus === 'loading' ? 'animate-spin' : ''} />
|
| 503 |
+
</button>
|
| 504 |
+
<button
|
| 505 |
+
type="button"
|
| 506 |
+
class="lyrics-icon-button lyrics-maximize-button"
|
| 507 |
+
onclick={() => lyricsStore.toggleMaximize()}
|
| 508 |
+
aria-label={$lyricsStore.maximized ? 'Restore window' : 'Maximize window'}
|
| 509 |
+
title={$lyricsStore.maximized ? 'Restore window' : 'Maximize window'}
|
| 510 |
+
>
|
| 511 |
+
{#if $lyricsStore.maximized}
|
| 512 |
+
<Minimize2 size={18} />
|
| 513 |
+
{:else}
|
| 514 |
+
<Maximize2 size={18} />
|
| 515 |
+
{/if}
|
| 516 |
+
</button>
|
| 517 |
+
<button
|
| 518 |
+
type="button"
|
| 519 |
+
class="lyrics-icon-button"
|
| 520 |
+
onclick={() => lyricsStore.close()}
|
| 521 |
+
aria-label="Close lyrics"
|
| 522 |
+
title="Close lyrics"
|
| 523 |
+
>
|
| 524 |
+
<X size={18} />
|
| 525 |
+
</button>
|
| 526 |
+
</div>
|
| 527 |
+
</header>
|
| 528 |
+
|
| 529 |
+
<div class="lyrics-body">
|
| 530 |
+
{#if scriptStatus === 'error'}
|
| 531 |
+
<div class="lyrics-placeholder">
|
| 532 |
+
<p class="lyrics-message">{scriptError ?? 'Unable to load lyrics right now.'}</p>
|
| 533 |
+
<button type="button" class="lyrics-retry" onclick={handleRetry}> Try again </button>
|
| 534 |
+
</div>
|
| 535 |
+
{:else if !metadata}
|
| 536 |
+
<div class="lyrics-placeholder">
|
| 537 |
+
<p class="lyrics-message">Press play to fetch lyrics.</p>
|
| 538 |
+
</div>
|
| 539 |
+
{:else if scriptStatus === 'loading' || scriptStatus === 'idle'}
|
| 540 |
+
<div class="lyrics-placeholder">
|
| 541 |
+
<span class="spinner" aria-hidden="true"></span>
|
| 542 |
+
Loading lyrics…
|
| 543 |
+
</div>
|
| 544 |
+
{:else}
|
| 545 |
+
<div class="lyrics-component-wrapper">
|
| 546 |
+
{#key lyricsKey}
|
| 547 |
+
<am-lyrics
|
| 548 |
+
bind:this={amLyricsElement}
|
| 549 |
+
class="am-lyrics-element"
|
| 550 |
+
song-title={metadata.title}
|
| 551 |
+
song-artist={metadata.artist}
|
| 552 |
+
song-album={metadata.album || undefined}
|
| 553 |
+
song-duration={metadata.durationMs}
|
| 554 |
+
query={metadata.query}
|
| 555 |
+
isrc={metadata.isrc || undefined}
|
| 556 |
+
highlight-color="#fff"
|
| 557 |
+
hover-background-color="rgba(59, 130, 246, 0.14)"
|
| 558 |
+
font-family="'Figtree', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif"
|
| 559 |
+
autoscroll
|
| 560 |
+
interpolate
|
| 561 |
+
></am-lyrics>
|
| 562 |
+
{/key}
|
| 563 |
+
</div>
|
| 564 |
+
{/if}
|
| 565 |
+
</div>
|
| 566 |
+
</div>
|
| 567 |
+
</div>
|
| 568 |
+
{/if}
|
| 569 |
+
|
| 570 |
+
<style>
|
| 571 |
+
.lyrics-overlay {
|
| 572 |
+
position: fixed;
|
| 573 |
+
inset: 0;
|
| 574 |
+
bottom: var(--player-height, 120px);
|
| 575 |
+
display: flex;
|
| 576 |
+
align-items: center;
|
| 577 |
+
justify-content: center;
|
| 578 |
+
padding: 1rem;
|
| 579 |
+
padding-bottom: 0.5rem;
|
| 580 |
+
background: transparent;
|
| 581 |
+
backdrop-filter: blur(var(--perf-blur-low, 12px)) saturate(120%);
|
| 582 |
+
-webkit-backdrop-filter: blur(var(--perf-blur-low, 12px)) saturate(120%);
|
| 583 |
+
z-index: 60;
|
| 584 |
+
pointer-events: none;
|
| 585 |
+
}
|
| 586 |
+
|
| 587 |
+
.lyrics-panel {
|
| 588 |
+
width: min(960px, 100%);
|
| 589 |
+
height: clamp(380px, 72vh, 780px);
|
| 590 |
+
display: flex;
|
| 591 |
+
flex-direction: column;
|
| 592 |
+
border-radius: 1.25rem;
|
| 593 |
+
background: transparent;
|
| 594 |
+
border: 1px solid rgba(148, 163, 184, 0.25);
|
| 595 |
+
backdrop-filter: blur(var(--perf-blur-high, 32px)) saturate(var(--perf-saturate, 160%));
|
| 596 |
+
-webkit-backdrop-filter: blur(var(--perf-blur-high, 32px)) saturate(var(--perf-saturate, 160%));
|
| 597 |
+
box-shadow:
|
| 598 |
+
0 30px 80px rgba(2, 6, 23, 0.6),
|
| 599 |
+
0 4px 18px rgba(15, 23, 42, 0.45),
|
| 600 |
+
inset 0 1px 0 rgba(255, 255, 255, 0.06);
|
| 601 |
+
overflow: hidden;
|
| 602 |
+
pointer-events: auto;
|
| 603 |
+
transition:
|
| 604 |
+
border-color 1.2s cubic-bezier(0.4, 0, 0.2, 1),
|
| 605 |
+
box-shadow 0.3s ease;
|
| 606 |
+
}
|
| 607 |
+
|
| 608 |
+
.lyrics-header {
|
| 609 |
+
display: flex;
|
| 610 |
+
align-items: flex-start;
|
| 611 |
+
justify-content: space-between;
|
| 612 |
+
gap: 1rem;
|
| 613 |
+
padding: 1.25rem 1.5rem 1rem;
|
| 614 |
+
border-bottom: 1px solid rgba(71, 85, 105, 0.45);
|
| 615 |
+
}
|
| 616 |
+
|
| 617 |
+
.lyrics-heading {
|
| 618 |
+
flex: 1;
|
| 619 |
+
}
|
| 620 |
+
|
| 621 |
+
.lyrics-title {
|
| 622 |
+
margin: 0;
|
| 623 |
+
font-size: 1.25rem;
|
| 624 |
+
font-weight: 600;
|
| 625 |
+
color: #f8fafc;
|
| 626 |
+
}
|
| 627 |
+
|
| 628 |
+
.lyrics-subtitle {
|
| 629 |
+
margin: 0.35rem 0 0;
|
| 630 |
+
font-size: 0.95rem;
|
| 631 |
+
color: #cbd5f5;
|
| 632 |
+
}
|
| 633 |
+
|
| 634 |
+
.lyrics-album {
|
| 635 |
+
margin: 0.2rem 0 0;
|
| 636 |
+
font-size: 0.8rem;
|
| 637 |
+
color: #94a3b8;
|
| 638 |
+
}
|
| 639 |
+
|
| 640 |
+
.lyrics-header-actions {
|
| 641 |
+
display: flex;
|
| 642 |
+
align-items: center;
|
| 643 |
+
gap: 0.5rem;
|
| 644 |
+
}
|
| 645 |
+
|
| 646 |
+
.lyrics-icon-button {
|
| 647 |
+
display: inline-flex;
|
| 648 |
+
align-items: center;
|
| 649 |
+
justify-content: center;
|
| 650 |
+
padding: 0.4rem;
|
| 651 |
+
border-radius: 9999px;
|
| 652 |
+
border: 1px solid rgba(148, 163, 184, 0.3);
|
| 653 |
+
background: transparent;
|
| 654 |
+
backdrop-filter: blur(16px) saturate(140%);
|
| 655 |
+
-webkit-backdrop-filter: blur(16px) saturate(140%);
|
| 656 |
+
color: #e2e8f0;
|
| 657 |
+
transition:
|
| 658 |
+
background 160ms ease,
|
| 659 |
+
border-color 160ms ease,
|
| 660 |
+
transform 160ms ease,
|
| 661 |
+
box-shadow 160ms ease;
|
| 662 |
+
}
|
| 663 |
+
|
| 664 |
+
.lyrics-icon-button[disabled] {
|
| 665 |
+
opacity: 0.5;
|
| 666 |
+
cursor: not-allowed;
|
| 667 |
+
}
|
| 668 |
+
|
| 669 |
+
.lyrics-icon-button:not([disabled]):hover {
|
| 670 |
+
border-color: var(--bloom-accent, rgba(96, 165, 250, 0.7));
|
| 671 |
+
box-shadow: inset 0 0 20px rgba(96, 165, 250, 0.12);
|
| 672 |
+
transform: translateY(-1px);
|
| 673 |
+
}
|
| 674 |
+
|
| 675 |
+
.animate-spin {
|
| 676 |
+
animation: spin 0.8s linear infinite;
|
| 677 |
+
}
|
| 678 |
+
|
| 679 |
+
@keyframes spin {
|
| 680 |
+
0% {
|
| 681 |
+
transform: rotate(0deg);
|
| 682 |
+
}
|
| 683 |
+
100% {
|
| 684 |
+
transform: rotate(360deg);
|
| 685 |
+
}
|
| 686 |
+
}
|
| 687 |
+
|
| 688 |
+
.lyrics-body {
|
| 689 |
+
flex: 1;
|
| 690 |
+
padding: 1rem 1.5rem 1.5rem;
|
| 691 |
+
display: flex;
|
| 692 |
+
overflow: hidden;
|
| 693 |
+
}
|
| 694 |
+
|
| 695 |
+
.lyrics-component-wrapper {
|
| 696 |
+
flex: 1;
|
| 697 |
+
display: flex;
|
| 698 |
+
align-items: stretch;
|
| 699 |
+
justify-content: stretch;
|
| 700 |
+
border-radius: 1rem;
|
| 701 |
+
background: rgba(15, 23, 42, 0.65);
|
| 702 |
+
border: 1px solid rgba(59, 73, 99, 0.5);
|
| 703 |
+
overflow: hidden;
|
| 704 |
+
}
|
| 705 |
+
|
| 706 |
+
.am-lyrics-element {
|
| 707 |
+
flex: 1;
|
| 708 |
+
display: block;
|
| 709 |
+
width: 100%;
|
| 710 |
+
height: 100%;
|
| 711 |
+
overflow-y: auto;
|
| 712 |
+
overflow-x: hidden;
|
| 713 |
+
overscroll-behavior: contain;
|
| 714 |
+
color: inherit;
|
| 715 |
+
}
|
| 716 |
+
|
| 717 |
+
.am-lyrics-element::part(container) {
|
| 718 |
+
padding: 1.25rem;
|
| 719 |
+
padding-block: 2rem;
|
| 720 |
+
box-sizing: border-box;
|
| 721 |
+
}
|
| 722 |
+
|
| 723 |
+
.am-lyrics-element::part(line) {
|
| 724 |
+
scroll-margin-block-start: min(32vh, 9rem);
|
| 725 |
+
scroll-margin-block-end: min(28vh, 7rem);
|
| 726 |
+
}
|
| 727 |
+
|
| 728 |
+
@media (min-width: 640px) {
|
| 729 |
+
.lyrics-panel--maximized .am-lyrics-element {
|
| 730 |
+
font-size: clamp(1.05rem, 0.85rem + 1.2vw, 1.85rem);
|
| 731 |
+
line-height: 1.6;
|
| 732 |
+
letter-spacing: 0.01em;
|
| 733 |
+
}
|
| 734 |
+
|
| 735 |
+
.lyrics-panel--maximized .am-lyrics-element::part(line) {
|
| 736 |
+
padding-block: clamp(0.65rem, 0.45rem + 0.8vw, 1.2rem);
|
| 737 |
+
}
|
| 738 |
+
}
|
| 739 |
+
|
| 740 |
+
.lyrics-placeholder {
|
| 741 |
+
flex: 1;
|
| 742 |
+
display: flex;
|
| 743 |
+
flex-direction: column;
|
| 744 |
+
align-items: center;
|
| 745 |
+
justify-content: center;
|
| 746 |
+
gap: 1rem;
|
| 747 |
+
text-align: center;
|
| 748 |
+
color: #cbd5f5;
|
| 749 |
+
padding: 1.5rem;
|
| 750 |
+
}
|
| 751 |
+
|
| 752 |
+
.lyrics-message {
|
| 753 |
+
margin: 0;
|
| 754 |
+
font-size: 0.95rem;
|
| 755 |
+
}
|
| 756 |
+
|
| 757 |
+
.lyrics-retry {
|
| 758 |
+
border: 1px solid var(--bloom-accent, rgba(96, 165, 250, 0.7));
|
| 759 |
+
background: transparent;
|
| 760 |
+
backdrop-filter: blur(16px) saturate(140%);
|
| 761 |
+
-webkit-backdrop-filter: blur(16px) saturate(140%);
|
| 762 |
+
color: #f0f9ff;
|
| 763 |
+
border-radius: 9999px;
|
| 764 |
+
padding: 0.45rem 1.25rem;
|
| 765 |
+
font-size: 0.85rem;
|
| 766 |
+
font-weight: 500;
|
| 767 |
+
box-shadow: inset 0 0 20px rgba(96, 165, 250, 0.1);
|
| 768 |
+
transition:
|
| 769 |
+
border-color 160ms ease,
|
| 770 |
+
box-shadow 160ms ease;
|
| 771 |
+
}
|
| 772 |
+
|
| 773 |
+
.lyrics-retry:hover {
|
| 774 |
+
border-color: var(--bloom-accent, rgba(191, 219, 254, 0.9));
|
| 775 |
+
box-shadow: inset 0 0 30px rgba(96, 165, 250, 0.18);
|
| 776 |
+
}
|
| 777 |
+
|
| 778 |
+
.spinner {
|
| 779 |
+
width: 1.25rem;
|
| 780 |
+
height: 1.25rem;
|
| 781 |
+
border-radius: 9999px;
|
| 782 |
+
border: 2px solid rgba(148, 163, 184, 0.35);
|
| 783 |
+
border-top-color: rgba(148, 163, 184, 0.95);
|
| 784 |
+
animation: spin 0.85s linear infinite;
|
| 785 |
+
}
|
| 786 |
+
|
| 787 |
+
@media (max-width: 640px) {
|
| 788 |
+
.lyrics-overlay {
|
| 789 |
+
padding: 0;
|
| 790 |
+
align-items: stretch;
|
| 791 |
+
justify-content: stretch;
|
| 792 |
+
bottom: 0; /* Override player height on mobile for full screen */
|
| 793 |
+
}
|
| 794 |
+
|
| 795 |
+
.lyrics-panel {
|
| 796 |
+
border-radius: 0;
|
| 797 |
+
border: none;
|
| 798 |
+
width: 100vw;
|
| 799 |
+
height: 100vh;
|
| 800 |
+
max-height: 100vh;
|
| 801 |
+
}
|
| 802 |
+
|
| 803 |
+
.lyrics-header {
|
| 804 |
+
flex-direction: column;
|
| 805 |
+
align-items: flex-start;
|
| 806 |
+
}
|
| 807 |
+
|
| 808 |
+
.lyrics-header-actions {
|
| 809 |
+
align-self: flex-end;
|
| 810 |
+
}
|
| 811 |
+
|
| 812 |
+
.lyrics-body {
|
| 813 |
+
padding: 1rem;
|
| 814 |
+
}
|
| 815 |
+
|
| 816 |
+
.lyrics-maximize-button {
|
| 817 |
+
display: none;
|
| 818 |
+
}
|
| 819 |
+
|
| 820 |
+
.am-lyrics-element::part(container) {
|
| 821 |
+
padding: 1.5rem;
|
| 822 |
+
padding-block: 2.5rem;
|
| 823 |
+
}
|
| 824 |
+
|
| 825 |
+
.am-lyrics-element::part(line) {
|
| 826 |
+
scroll-margin-block-start: min(40vh, 9rem);
|
| 827 |
+
scroll-margin-block-end: min(28vh, 6.5rem);
|
| 828 |
+
}
|
| 829 |
+
}
|
| 830 |
+
</style>
|
src/lib/components/QualitySelector.svelte
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!-- Literally unused because it doesn't work -->
|
| 2 |
+
|
| 3 |
+
<script lang="ts">
|
| 4 |
+
import type { AudioQuality } from '$lib/types';
|
| 5 |
+
import { playerStore } from '$lib/stores/player';
|
| 6 |
+
import { Settings, Check } from 'lucide-svelte';
|
| 7 |
+
|
| 8 |
+
let isOpen = $state(false);
|
| 9 |
+
const disabledQualities = new Set<AudioQuality>();
|
| 10 |
+
|
| 11 |
+
const qualities: { value: AudioQuality; label: string; description: string }[] = [
|
| 12 |
+
{
|
| 13 |
+
value: 'HI_RES_LOSSLESS',
|
| 14 |
+
label: 'Hi-Res',
|
| 15 |
+
description: '24-bit FLAC up to 192 kHz'
|
| 16 |
+
},
|
| 17 |
+
{ value: 'LOSSLESS', label: 'Lossless', description: '16-bit/44.1 kHz FLAC' },
|
| 18 |
+
{ value: 'HIGH', label: 'High', description: '320k AAC' },
|
| 19 |
+
{ value: 'LOW', label: 'Low', description: '96k AAC' }
|
| 20 |
+
];
|
| 21 |
+
|
| 22 |
+
function isQualityDisabled(quality: AudioQuality): boolean {
|
| 23 |
+
return disabledQualities.has(quality);
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
function selectQuality(quality: AudioQuality) {
|
| 27 |
+
if (isQualityDisabled(quality)) {
|
| 28 |
+
return;
|
| 29 |
+
}
|
| 30 |
+
playerStore.setQuality(quality);
|
| 31 |
+
isOpen = false;
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
function toggleDropdown() {
|
| 35 |
+
isOpen = !isOpen;
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
function handleClickOutside(event: MouseEvent) {
|
| 39 |
+
if (isOpen && !(event.target as Element).closest('.quality-selector')) {
|
| 40 |
+
isOpen = false;
|
| 41 |
+
}
|
| 42 |
+
}
|
| 43 |
+
</script>
|
| 44 |
+
|
| 45 |
+
<svelte:window onclick={handleClickOutside} />
|
| 46 |
+
|
| 47 |
+
<div class="quality-selector relative">
|
| 48 |
+
<button
|
| 49 |
+
onclick={toggleDropdown}
|
| 50 |
+
class="flex items-center gap-2 rounded-lg bg-gray-800 px-4 py-2 text-white transition-colors hover:bg-gray-700"
|
| 51 |
+
aria-label="Select audio quality"
|
| 52 |
+
>
|
| 53 |
+
<Settings size={18} />
|
| 54 |
+
<span class="text-sm">
|
| 55 |
+
{qualities.find((q) => q.value === $playerStore.quality)?.label || 'Quality'}
|
| 56 |
+
</span>
|
| 57 |
+
</button>
|
| 58 |
+
|
| 59 |
+
{#if isOpen}
|
| 60 |
+
<div
|
| 61 |
+
class="absolute right-0 z-50 mt-2 w-64 overflow-hidden rounded-lg border border-gray-700 bg-gray-800 shadow-lg"
|
| 62 |
+
>
|
| 63 |
+
<div class="border-b border-gray-700 p-2">
|
| 64 |
+
<h3 class="text-sm font-semibold text-white">Audio Quality</h3>
|
| 65 |
+
</div>
|
| 66 |
+
<div class="py-1">
|
| 67 |
+
{#each qualities as quality}
|
| 68 |
+
<button
|
| 69 |
+
onclick={() => selectQuality(quality.value)}
|
| 70 |
+
class="flex w-full items-start gap-3 px-4 py-3 text-left transition-colors hover:bg-gray-700 disabled:cursor-not-allowed disabled:text-gray-500 disabled:opacity-60 disabled:hover:bg-gray-800"
|
| 71 |
+
disabled={isQualityDisabled(quality.value)}
|
| 72 |
+
aria-disabled={isQualityDisabled(quality.value)}
|
| 73 |
+
title={isQualityDisabled(quality.value) ? 'Not available in this build' : undefined}
|
| 74 |
+
>
|
| 75 |
+
<div class="mt-0.5 flex h-5 w-5 flex-shrink-0 items-center justify-center">
|
| 76 |
+
{#if $playerStore.quality === quality.value}
|
| 77 |
+
<Check size={18} class="text-blue-500" />
|
| 78 |
+
{/if}
|
| 79 |
+
</div>
|
| 80 |
+
<div class="flex-1">
|
| 81 |
+
<div class="text-sm font-medium text-white">{quality.label}</div>
|
| 82 |
+
<div
|
| 83 |
+
class={`text-xs ${isQualityDisabled(quality.value) ? 'text-gray-500' : 'text-gray-400'}`}
|
| 84 |
+
>
|
| 85 |
+
{quality.description}
|
| 86 |
+
{#if isQualityDisabled(quality.value)}
|
| 87 |
+
<span class="ml-1 text-[10px] tracking-wide text-gray-500 uppercase"
|
| 88 |
+
>Unavailable</span
|
| 89 |
+
>
|
| 90 |
+
{/if}
|
| 91 |
+
</div>
|
| 92 |
+
</div>
|
| 93 |
+
</button>
|
| 94 |
+
{/each}
|
| 95 |
+
</div>
|
| 96 |
+
</div>
|
| 97 |
+
{/if}
|
| 98 |
+
</div>
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<script lang="ts">
|
| 2 |
+
import { onDestroy, onMount } from 'svelte';
|
| 3 |
+
import { losslessAPI, type TrackDownloadProgress } from '$lib/api';
|
| 4 |
+
import { hasRegionTargets } from '$lib/config';
|
| 5 |
+
import { downloadAlbum, getExtensionForQuality } from '$lib/downloads';
|
| 6 |
+
import { formatArtists } from '$lib/utils';
|
| 7 |
+
import { playerStore } from '$lib/stores/player';
|
| 8 |
+
import { downloadUiStore } from '$lib/stores/downloadUi';
|
| 9 |
+
import { downloadPreferencesStore } from '$lib/stores/downloadPreferences';
|
| 10 |
+
import { userPreferencesStore } from '$lib/stores/userPreferences';
|
| 11 |
+
import { regionStore, type RegionOption } from '$lib/stores/region';
|
| 12 |
+
import { isTidalUrl } from '$lib/utils/urlParser';
|
| 13 |
+
import {
|
| 14 |
+
isSupportedStreamingUrl,
|
| 15 |
+
convertToTidal,
|
| 16 |
+
getPlatformName,
|
| 17 |
+
isSpotifyPlaylistUrl,
|
| 18 |
+
convertSpotifyPlaylist,
|
| 19 |
+
fetchSonglinkData,
|
| 20 |
+
extractTidalSongEntity
|
| 21 |
+
} from '$lib/utils/songlink';
|
| 22 |
+
import type { Track, Album, Artist, Playlist, AudioQuality, SonglinkTrack, PlayableTrack } from '$lib/types';
|
| 23 |
+
import { isSonglinkTrack } from '$lib/types';
|
| 24 |
+
import {
|
| 25 |
+
Search,
|
| 26 |
+
ChevronDown,
|
| 27 |
+
Music,
|
| 28 |
+
User,
|
| 29 |
+
Disc,
|
| 30 |
+
Download,
|
| 31 |
+
Newspaper,
|
| 32 |
+
ListPlus,
|
| 33 |
+
ListVideo,
|
| 34 |
+
LoaderCircle,
|
| 35 |
+
X,
|
| 36 |
+
Earth,
|
| 37 |
+
Ban,
|
| 38 |
+
Link2,
|
| 39 |
+
MoreVertical,
|
| 40 |
+
List,
|
| 41 |
+
Play,
|
| 42 |
+
Shuffle,
|
| 43 |
+
Copy,
|
| 44 |
+
Code
|
| 45 |
+
} from 'lucide-svelte';
|
| 46 |
+
|
| 47 |
+
import { searchStore, type SearchTab } from '$lib/stores/searchStore.svelte';
|
| 48 |
+
import { page } from '$app/stores';
|
| 49 |
+
|
| 50 |
+
function getLongLink(type: 'track' | 'album' | 'artist' | 'playlist', id: string | number) {
|
| 51 |
+
return `${$page.url.protocol}://${$page.url.host}/${type}/${id}`;
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
function getShortLink(type: 'track' | 'album' | 'artist' | 'playlist', id: string | number) {
|
| 55 |
+
const prefixMap = {
|
| 56 |
+
track: 't',
|
| 57 |
+
album: 'al',
|
| 58 |
+
artist: 'ar',
|
| 59 |
+
playlist: 'p'
|
| 60 |
+
};
|
| 61 |
+
return `https://okiw.me/${prefixMap[type]}/${id}`;
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
function getEmbedCode(type: 'track' | 'album' | 'artist' | 'playlist', id: string | number) {
|
| 65 |
+
if (type === "track") return `<iframe src="https://music.binimum.org/embed/${type}/${id}" width="100%" height="150" style="border:none; overflow:hidden; border-radius: 0.5em;" allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture"></iframe>`;
|
| 66 |
+
return `<iframe src="https://music.binimum.org/embed/${type}/${id}" width="100%" height="450" style="border:none; overflow:hidden; border-radius: 0.5em;" allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture"></iframe>`;
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
async function copyToClipboard(text: string) {
|
| 70 |
+
try {
|
| 71 |
+
if (navigator.clipboard && navigator.clipboard.writeText) {
|
| 72 |
+
await navigator.clipboard.writeText(text);
|
| 73 |
+
} else {
|
| 74 |
+
// Fallback for non-secure contexts
|
| 75 |
+
const textArea = document.createElement('textarea');
|
| 76 |
+
textArea.value = text;
|
| 77 |
+
textArea.style.position = 'fixed';
|
| 78 |
+
textArea.style.left = '-9999px';
|
| 79 |
+
textArea.style.top = '0';
|
| 80 |
+
document.body.appendChild(textArea);
|
| 81 |
+
textArea.focus();
|
| 82 |
+
textArea.select();
|
| 83 |
+
try {
|
| 84 |
+
document.execCommand('copy');
|
| 85 |
+
} catch (err) {
|
| 86 |
+
console.error('Fallback: Oops, unable to copy', err);
|
| 87 |
+
throw err;
|
| 88 |
+
}
|
| 89 |
+
document.body.removeChild(textArea);
|
| 90 |
+
}
|
| 91 |
+
} catch (err) {
|
| 92 |
+
console.error('Failed to copy:', err);
|
| 93 |
+
}
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
let downloadingIds = $state(new Set<number | string>());
|
| 97 |
+
let downloadTaskIds = $state(new Map<number | string, string>());
|
| 98 |
+
let cancelledIds = $state(new Set<number | string>());
|
| 99 |
+
let activeMenuId = $state<number | string | null>(null);
|
| 100 |
+
|
| 101 |
+
const albumDownloadQuality = $derived($userPreferencesStore.playbackQuality as AudioQuality);
|
| 102 |
+
const albumDownloadMode = $derived($downloadPreferencesStore.mode);
|
| 103 |
+
const convertAacToMp3Preference = $derived($userPreferencesStore.convertAacToMp3);
|
| 104 |
+
const downloadCoverSeperatelyPreference = $derived(
|
| 105 |
+
$userPreferencesStore.downloadCoversSeperately
|
| 106 |
+
);
|
| 107 |
+
let selectedRegion = $state<RegionOption>('auto');
|
| 108 |
+
let isRegionSelectorOpen = $state(false);
|
| 109 |
+
// Playlist state moved to searchStore
|
| 110 |
+
|
| 111 |
+
const regionAvailability: Record<RegionOption, boolean> = {
|
| 112 |
+
auto: hasRegionTargets('auto'),
|
| 113 |
+
us: hasRegionTargets('us'),
|
| 114 |
+
eu: hasRegionTargets('eu')
|
| 115 |
+
};
|
| 116 |
+
|
| 117 |
+
const ensureSupportedRegion = (value: RegionOption): RegionOption => {
|
| 118 |
+
if (value !== 'auto' && !regionAvailability[value]) {
|
| 119 |
+
return 'auto';
|
| 120 |
+
}
|
| 121 |
+
return value;
|
| 122 |
+
};
|
| 123 |
+
|
| 124 |
+
const unsubscribeRegion = regionStore.subscribe((value) => {
|
| 125 |
+
const nextRegion = ensureSupportedRegion(value);
|
| 126 |
+
if (nextRegion !== value) {
|
| 127 |
+
regionStore.setRegion(nextRegion);
|
| 128 |
+
}
|
| 129 |
+
selectedRegion = nextRegion;
|
| 130 |
+
});
|
| 131 |
+
|
| 132 |
+
onDestroy(unsubscribeRegion);
|
| 133 |
+
|
| 134 |
+
// Computed property to check if current query is a Tidal URL
|
| 135 |
+
const isQueryATidalUrl = $derived(searchStore.query.trim().length > 0 && isTidalUrl(searchStore.query.trim()));
|
| 136 |
+
|
| 137 |
+
// Computed property to check if current query is a supported streaming platform URL
|
| 138 |
+
const isQueryAStreamingUrl = $derived(
|
| 139 |
+
searchStore.query.trim().length > 0 && isSupportedStreamingUrl(searchStore.query.trim())
|
| 140 |
+
);
|
| 141 |
+
|
| 142 |
+
// Computed property to check if current query is a Spotify playlist URL
|
| 143 |
+
const isQueryASpotifyPlaylist = $derived(
|
| 144 |
+
searchStore.query.trim().length > 0 && isSpotifyPlaylistUrl(searchStore.query.trim())
|
| 145 |
+
);
|
| 146 |
+
|
| 147 |
+
// Combined URL check
|
| 148 |
+
const isQueryAUrl = $derived(isQueryATidalUrl || isQueryAStreamingUrl);
|
| 149 |
+
|
| 150 |
+
type AlbumDownloadState = {
|
| 151 |
+
downloading: boolean;
|
| 152 |
+
completed: number;
|
| 153 |
+
total: number;
|
| 154 |
+
error: string | null;
|
| 155 |
+
};
|
| 156 |
+
|
| 157 |
+
let albumDownloadStates = $state<Record<number, AlbumDownloadState>>({});
|
| 158 |
+
|
| 159 |
+
const newsItems = [
|
| 160 |
+
{
|
| 161 |
+
title: 'Hi-Res downloading!!!',
|
| 162 |
+
description:
|
| 163 |
+
"You can finally download and stream in Hi-Res again because of a much better API. It should also be much faster - try it out for yourself!"
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
title: 'Links support + QOLs!',
|
| 167 |
+
description:
|
| 168 |
+
"You can now paste links from supported streaming platforms (Spotify, YouTube, Apple Music, etc.) and the app will try to convert them to TIDAL equivalents for you to play or download. Only Spotify playlists work right now, but I'm working on fixing it."
|
| 169 |
+
},
|
| 170 |
+
{
|
| 171 |
+
title: 'Redesign + QQDL',
|
| 172 |
+
description:
|
| 173 |
+
'Hi-Res downloading still a WIP but a cool redesign that I inspired off a very cool library called Color Thief is here - and the site is also now up at QQDL!'
|
| 174 |
+
},
|
| 175 |
+
{
|
| 176 |
+
title: 'Hi-Res Audio',
|
| 177 |
+
description:
|
| 178 |
+
"Streaming for Hi-Res is now here. Stay tuned for Hi-Res downloading - I haven't gotten that one figured out yet. And video covers/lower quality streaming. Pretty cool."
|
| 179 |
+
},
|
| 180 |
+
{
|
| 181 |
+
title: 'Even more changes!',
|
| 182 |
+
description:
|
| 183 |
+
"LYRICS!!! I've stabilised the API a bit and added a few more features such as ZIP download of albums, better error handling, etc. Stay tuned for word by word lyrics!"
|
| 184 |
+
},
|
| 185 |
+
{
|
| 186 |
+
title: 'QOL changes',
|
| 187 |
+
description:
|
| 188 |
+
'This website is still very much in beta, but queue management and album/artist pages/downloads have been added as well as some bug squashing/QOL changes such as bigger album covers and download all for albums.'
|
| 189 |
+
},
|
| 190 |
+
{
|
| 191 |
+
title: 'Initial release!',
|
| 192 |
+
description:
|
| 193 |
+
"Two APIs fetch lossless CD-quality 16/44.1kHz FLACs. No support for Hi-Res yet but I'm working on it haha. No playlist saving or logging in either but downloading and streaming work."
|
| 194 |
+
}
|
| 195 |
+
];
|
| 196 |
+
|
| 197 |
+
const trackSkeletons = Array.from({ length: 6 }, (_, index) => index);
|
| 198 |
+
const gridSkeletons = Array.from({ length: 8 }, (_, index) => index);
|
| 199 |
+
|
| 200 |
+
interface Props {
|
| 201 |
+
onTrackSelect?: (track: PlayableTrack) => void;
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
let { onTrackSelect }: Props = $props();
|
| 205 |
+
|
| 206 |
+
// Close track menus when clicking outside
|
| 207 |
+
onMount(() => {
|
| 208 |
+
const handleClickOutside = (event: MouseEvent) => {
|
| 209 |
+
const target = event.target as HTMLElement;
|
| 210 |
+
// Check if click is outside any menu
|
| 211 |
+
if (
|
| 212 |
+
!target.closest('.track-menu-container') &&
|
| 213 |
+
!target.closest('button[title="Queue actions"]')
|
| 214 |
+
) {
|
| 215 |
+
activeMenuId = null;
|
| 216 |
+
}
|
| 217 |
+
};
|
| 218 |
+
|
| 219 |
+
document.addEventListener('click', handleClickOutside);
|
| 220 |
+
|
| 221 |
+
return () => {
|
| 222 |
+
document.removeEventListener('click', handleClickOutside);
|
| 223 |
+
};
|
| 224 |
+
});
|
| 225 |
+
|
| 226 |
+
async function fetchWithRetry<T>(
|
| 227 |
+
action: () => Promise<T>,
|
| 228 |
+
attempts = 3,
|
| 229 |
+
delayMs = 250
|
| 230 |
+
): Promise<T> {
|
| 231 |
+
let lastError: unknown = null;
|
| 232 |
+
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
| 233 |
+
try {
|
| 234 |
+
return await action();
|
| 235 |
+
} catch (err) {
|
| 236 |
+
lastError = err;
|
| 237 |
+
if (attempt < attempts) {
|
| 238 |
+
await new Promise((resolve) => setTimeout(resolve, delayMs * attempt));
|
| 239 |
+
}
|
| 240 |
+
}
|
| 241 |
+
}
|
| 242 |
+
throw lastError instanceof Error ? lastError : new Error('Request failed');
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
function markCancelled(trackId: number | string) {
|
| 246 |
+
const next = new Set(cancelledIds);
|
| 247 |
+
next.add(trackId);
|
| 248 |
+
cancelledIds = next;
|
| 249 |
+
setTimeout(() => {
|
| 250 |
+
const updated = new Set(cancelledIds);
|
| 251 |
+
updated.delete(trackId);
|
| 252 |
+
cancelledIds = updated;
|
| 253 |
+
}, 1500);
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
function handleCancelDownload(trackId: number | string, event: MouseEvent) {
|
| 257 |
+
event.stopPropagation();
|
| 258 |
+
const taskId = downloadTaskIds.get(trackId);
|
| 259 |
+
if (taskId) {
|
| 260 |
+
downloadUiStore.cancelTrackDownload(taskId);
|
| 261 |
+
}
|
| 262 |
+
const next = new Set(downloadingIds);
|
| 263 |
+
next.delete(trackId);
|
| 264 |
+
downloadingIds = next;
|
| 265 |
+
const taskMap = new Map(downloadTaskIds);
|
| 266 |
+
taskMap.delete(trackId);
|
| 267 |
+
downloadTaskIds = taskMap;
|
| 268 |
+
markCancelled(trackId);
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
async function handleDownload(track: PlayableTrack, event?: MouseEvent) {
|
| 272 |
+
if (event) {
|
| 273 |
+
event.stopPropagation();
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
let trackId: number;
|
| 277 |
+
let artistName: string;
|
| 278 |
+
let albumTitle: string | undefined;
|
| 279 |
+
|
| 280 |
+
// Handle SonglinkTracks
|
| 281 |
+
if (isSonglinkTrack(track)) {
|
| 282 |
+
if (track.tidalId) {
|
| 283 |
+
trackId = track.tidalId;
|
| 284 |
+
artistName = track.artistName;
|
| 285 |
+
albumTitle = undefined;
|
| 286 |
+
} else {
|
| 287 |
+
console.warn('Cannot download SonglinkTrack directly - play it first to convert to TIDAL');
|
| 288 |
+
alert('This track needs to be played first before it can be downloaded. Click to play it, then download.');
|
| 289 |
+
return;
|
| 290 |
+
}
|
| 291 |
+
} else {
|
| 292 |
+
trackId = track.id;
|
| 293 |
+
artistName = formatArtists(track.artists);
|
| 294 |
+
albumTitle = track.album?.title;
|
| 295 |
+
}
|
| 296 |
+
|
| 297 |
+
// Guard against non-numeric IDs
|
| 298 |
+
if (!Number.isFinite(trackId) || trackId <= 0) {
|
| 299 |
+
console.error('Cannot download track with invalid ID:', track.id);
|
| 300 |
+
alert('Cannot download this track - invalid track ID');
|
| 301 |
+
return;
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
// Use the original ID for tracking active downloads in the UI to avoid confusion
|
| 305 |
+
// (since the UI list might still be using the string ID)
|
| 306 |
+
const uiTrackId = track.id;
|
| 307 |
+
|
| 308 |
+
if (downloadingIds.has(uiTrackId)) {
|
| 309 |
+
return;
|
| 310 |
+
}
|
| 311 |
+
const next = new Set(downloadingIds);
|
| 312 |
+
next.add(uiTrackId);
|
| 313 |
+
downloadingIds = next;
|
| 314 |
+
|
| 315 |
+
const quality = $userPreferencesStore.playbackQuality;
|
| 316 |
+
const extension = getExtensionForQuality(quality, convertAacToMp3Preference);
|
| 317 |
+
|
| 318 |
+
// Format title with version if present
|
| 319 |
+
let title = track.title;
|
| 320 |
+
if ('version' in track && track.version) {
|
| 321 |
+
title = `${title} (${track.version})`;
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
const filename = `${artistName} - ${title}.${extension}`;
|
| 325 |
+
const { taskId, controller } = downloadUiStore.beginTrackDownload(track, filename, {
|
| 326 |
+
subtitle: albumTitle ?? artistName
|
| 327 |
+
});
|
| 328 |
+
const taskMap = new Map(downloadTaskIds);
|
| 329 |
+
taskMap.set(uiTrackId, taskId);
|
| 330 |
+
downloadTaskIds = taskMap;
|
| 331 |
+
downloadUiStore.skipFfmpegCountdown();
|
| 332 |
+
|
| 333 |
+
try {
|
| 334 |
+
await losslessAPI.downloadTrack(trackId, quality, filename, {
|
| 335 |
+
signal: controller.signal,
|
| 336 |
+
onProgress: (progress: TrackDownloadProgress) => {
|
| 337 |
+
if (progress.stage === 'downloading') {
|
| 338 |
+
downloadUiStore.updateTrackProgress(
|
| 339 |
+
taskId,
|
| 340 |
+
progress.receivedBytes,
|
| 341 |
+
progress.totalBytes
|
| 342 |
+
);
|
| 343 |
+
} else {
|
| 344 |
+
downloadUiStore.updateTrackStage(taskId, progress.progress);
|
| 345 |
+
}
|
| 346 |
+
},
|
| 347 |
+
onFfmpegCountdown: ({ totalBytes }) => {
|
| 348 |
+
if (typeof totalBytes === 'number') {
|
| 349 |
+
downloadUiStore.startFfmpegCountdown(totalBytes, { autoTriggered: false });
|
| 350 |
+
} else {
|
| 351 |
+
downloadUiStore.startFfmpegCountdown(0, { autoTriggered: false });
|
| 352 |
+
}
|
| 353 |
+
},
|
| 354 |
+
onFfmpegStart: () => downloadUiStore.startFfmpegLoading(),
|
| 355 |
+
onFfmpegProgress: (value) => downloadUiStore.updateFfmpegProgress(value),
|
| 356 |
+
onFfmpegComplete: () => downloadUiStore.completeFfmpeg(),
|
| 357 |
+
onFfmpegError: (error) => downloadUiStore.errorFfmpeg(error),
|
| 358 |
+
ffmpegAutoTriggered: false,
|
| 359 |
+
convertAacToMp3: convertAacToMp3Preference,
|
| 360 |
+
downloadCoverSeperately: downloadCoverSeperatelyPreference
|
| 361 |
+
});
|
| 362 |
+
|
| 363 |
+
downloadUiStore.completeTrackDownload(taskId);
|
| 364 |
+
} catch (error) {
|
| 365 |
+
if (error instanceof DOMException && error.name === 'AbortError') {
|
| 366 |
+
downloadUiStore.completeTrackDownload(taskId);
|
| 367 |
+
} else {
|
| 368 |
+
console.error('Failed to download track:', error);
|
| 369 |
+
const fallbackMessage = 'Failed to download track. Please try again.';
|
| 370 |
+
const message = error instanceof Error && error.message ? error.message : fallbackMessage;
|
| 371 |
+
downloadUiStore.errorTrackDownload(taskId, message);
|
| 372 |
+
alert(message);
|
| 373 |
+
}
|
| 374 |
+
} finally {
|
| 375 |
+
const next = new Set(downloadingIds);
|
| 376 |
+
next.delete(uiTrackId);
|
| 377 |
+
downloadingIds = next;
|
| 378 |
+
const taskMap = new Map(downloadTaskIds);
|
| 379 |
+
taskMap.delete(uiTrackId);
|
| 380 |
+
downloadTaskIds = taskMap;
|
| 381 |
+
}
|
| 382 |
+
}
|
| 383 |
+
|
| 384 |
+
function patchAlbumDownloadState(albumId: number, patch: Partial<AlbumDownloadState>) {
|
| 385 |
+
const previous = albumDownloadStates[albumId] ?? {
|
| 386 |
+
downloading: false,
|
| 387 |
+
completed: 0,
|
| 388 |
+
total: 0,
|
| 389 |
+
error: null
|
| 390 |
+
};
|
| 391 |
+
albumDownloadStates = {
|
| 392 |
+
...albumDownloadStates,
|
| 393 |
+
[albumId]: { ...previous, ...patch }
|
| 394 |
+
};
|
| 395 |
+
}
|
| 396 |
+
|
| 397 |
+
async function handleAlbumDownloadClick(album: Album, event: MouseEvent) {
|
| 398 |
+
event.preventDefault();
|
| 399 |
+
event.stopPropagation();
|
| 400 |
+
|
| 401 |
+
if (albumDownloadStates[album.id]?.downloading) {
|
| 402 |
+
return;
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
patchAlbumDownloadState(album.id, {
|
| 406 |
+
downloading: true,
|
| 407 |
+
completed: 0,
|
| 408 |
+
total: album.numberOfTracks ?? 0,
|
| 409 |
+
error: null
|
| 410 |
+
});
|
| 411 |
+
|
| 412 |
+
const quality = albumDownloadQuality;
|
| 413 |
+
|
| 414 |
+
try {
|
| 415 |
+
await downloadAlbum(
|
| 416 |
+
album,
|
| 417 |
+
quality,
|
| 418 |
+
{
|
| 419 |
+
onTotalResolved: (total) => {
|
| 420 |
+
patchAlbumDownloadState(album.id, { total });
|
| 421 |
+
},
|
| 422 |
+
onTrackDownloaded: (completed, total) => {
|
| 423 |
+
patchAlbumDownloadState(album.id, { completed, total });
|
| 424 |
+
}
|
| 425 |
+
},
|
| 426 |
+
album.artist?.name,
|
| 427 |
+
{
|
| 428 |
+
mode: albumDownloadMode,
|
| 429 |
+
convertAacToMp3: convertAacToMp3Preference,
|
| 430 |
+
downloadCoverSeperately: downloadCoverSeperatelyPreference
|
| 431 |
+
}
|
| 432 |
+
);
|
| 433 |
+
const finalState = albumDownloadStates[album.id];
|
| 434 |
+
patchAlbumDownloadState(album.id, {
|
| 435 |
+
downloading: false,
|
| 436 |
+
completed: finalState?.total ?? finalState?.completed ?? 0,
|
| 437 |
+
error: null
|
| 438 |
+
});
|
| 439 |
+
} catch (err) {
|
| 440 |
+
console.error('Failed to download album:', err);
|
| 441 |
+
const message =
|
| 442 |
+
err instanceof Error && err.message
|
| 443 |
+
? err.message
|
| 444 |
+
: 'Failed to download album. Please try again.';
|
| 445 |
+
patchAlbumDownloadState(album.id, { downloading: false, error: message });
|
| 446 |
+
}
|
| 447 |
+
}
|
| 448 |
+
|
| 449 |
+
function handleTrackActivation(track: PlayableTrack) {
|
| 450 |
+
onTrackSelect?.(track);
|
| 451 |
+
}
|
| 452 |
+
|
| 453 |
+
function handleAddToQueue(track: PlayableTrack, event: MouseEvent) {
|
| 454 |
+
event.stopPropagation();
|
| 455 |
+
playerStore.enqueue(track);
|
| 456 |
+
}
|
| 457 |
+
|
| 458 |
+
function handlePlayNext(track: PlayableTrack, event: MouseEvent) {
|
| 459 |
+
event.stopPropagation();
|
| 460 |
+
playerStore.enqueueNext(track);
|
| 461 |
+
}
|
| 462 |
+
|
| 463 |
+
function handleTrackKeydown(event: KeyboardEvent, track: PlayableTrack) {
|
| 464 |
+
if (event.key === 'Enter' || event.key === ' ') {
|
| 465 |
+
event.preventDefault();
|
| 466 |
+
handleTrackActivation(track);
|
| 467 |
+
}
|
| 468 |
+
}
|
| 469 |
+
|
| 470 |
+
$effect(() => {
|
| 471 |
+
const activeIds = new Set(searchStore.albums.map((album) => album.id));
|
| 472 |
+
let mutated = false;
|
| 473 |
+
const nextState: Record<number, AlbumDownloadState> = {};
|
| 474 |
+
for (const [albumId, state] of Object.entries(albumDownloadStates)) {
|
| 475 |
+
const numericId = Number(albumId);
|
| 476 |
+
if (activeIds.has(numericId)) {
|
| 477 |
+
nextState[numericId] = state;
|
| 478 |
+
} else {
|
| 479 |
+
mutated = true;
|
| 480 |
+
}
|
| 481 |
+
}
|
| 482 |
+
if (mutated) {
|
| 483 |
+
albumDownloadStates = nextState;
|
| 484 |
+
}
|
| 485 |
+
});
|
| 486 |
+
|
| 487 |
+
async function handleUrlImport() {
|
| 488 |
+
if (!searchStore.query.trim()) return;
|
| 489 |
+
|
| 490 |
+
searchStore.isLoading = true;
|
| 491 |
+
searchStore.error = null;
|
| 492 |
+
|
| 493 |
+
try {
|
| 494 |
+
const result = await losslessAPI.importFromUrl(searchStore.query);
|
| 495 |
+
|
| 496 |
+
// Clear previous results
|
| 497 |
+
searchStore.tracks = [];
|
| 498 |
+
searchStore.albums = [];
|
| 499 |
+
searchStore.artists = [];
|
| 500 |
+
searchStore.playlists = [];
|
| 501 |
+
|
| 502 |
+
// Set results based on type
|
| 503 |
+
switch (result.type) {
|
| 504 |
+
case 'track':
|
| 505 |
+
searchStore.tracks = [result.data as Track];
|
| 506 |
+
searchStore.activeTab = 'tracks';
|
| 507 |
+
break;
|
| 508 |
+
case 'album':
|
| 509 |
+
searchStore.albums = [result.data as Album];
|
| 510 |
+
searchStore.activeTab = 'albums';
|
| 511 |
+
break;
|
| 512 |
+
case 'artist':
|
| 513 |
+
searchStore.artists = [result.data as Artist];
|
| 514 |
+
searchStore.activeTab = 'artists';
|
| 515 |
+
break;
|
| 516 |
+
case 'playlist': {
|
| 517 |
+
const playlistData = result.data as { playlist: Playlist; tracks: Track[] };
|
| 518 |
+
searchStore.playlists = [playlistData.playlist];
|
| 519 |
+
searchStore.tracks = playlistData.tracks;
|
| 520 |
+
searchStore.activeTab = 'playlists';
|
| 521 |
+
break;
|
| 522 |
+
}
|
| 523 |
+
}
|
| 524 |
+
} catch (err) {
|
| 525 |
+
searchStore.error = err instanceof Error ? err.message : 'Failed to import from URL';
|
| 526 |
+
console.error('URL import error:', err);
|
| 527 |
+
} finally {
|
| 528 |
+
searchStore.isLoading = false;
|
| 529 |
+
}
|
| 530 |
+
}
|
| 531 |
+
|
| 532 |
+
async function handleSearch() {
|
| 533 |
+
if (!searchStore.query.trim()) return;
|
| 534 |
+
|
| 535 |
+
// Auto-detect: if query is a Tidal URL, import it directly
|
| 536 |
+
if (isQueryATidalUrl) {
|
| 537 |
+
await handleUrlImport();
|
| 538 |
+
return;
|
| 539 |
+
}
|
| 540 |
+
|
| 541 |
+
// Auto-detect: if query is a Spotify playlist, convert it
|
| 542 |
+
if (isQueryASpotifyPlaylist) {
|
| 543 |
+
await handleSpotifyPlaylistConversion();
|
| 544 |
+
return;
|
| 545 |
+
}
|
| 546 |
+
|
| 547 |
+
// Auto-detect: if query is a streaming platform URL, convert it first
|
| 548 |
+
if (isQueryAStreamingUrl) {
|
| 549 |
+
await handleStreamingUrlConversion();
|
| 550 |
+
return;
|
| 551 |
+
}
|
| 552 |
+
|
| 553 |
+
searchStore.isLoading = true;
|
| 554 |
+
searchStore.error = null;
|
| 555 |
+
|
| 556 |
+
try {
|
| 557 |
+
switch (searchStore.activeTab) {
|
| 558 |
+
case 'tracks': {
|
| 559 |
+
const response = await fetchWithRetry(() =>
|
| 560 |
+
losslessAPI.searchTracks(searchStore.query, selectedRegion)
|
| 561 |
+
);
|
| 562 |
+
searchStore.tracks = Array.isArray(response?.items) ? response.items : [];
|
| 563 |
+
break;
|
| 564 |
+
}
|
| 565 |
+
case 'albums': {
|
| 566 |
+
const response = await losslessAPI.searchAlbums(searchStore.query, selectedRegion);
|
| 567 |
+
searchStore.albums = Array.isArray(response?.items) ? response.items : [];
|
| 568 |
+
break;
|
| 569 |
+
}
|
| 570 |
+
case 'artists': {
|
| 571 |
+
const response = await losslessAPI.searchArtists(searchStore.query, selectedRegion);
|
| 572 |
+
searchStore.artists = Array.isArray(response?.items) ? response.items : [];
|
| 573 |
+
break;
|
| 574 |
+
}
|
| 575 |
+
case 'playlists': {
|
| 576 |
+
const response = await losslessAPI.searchPlaylists(searchStore.query, selectedRegion);
|
| 577 |
+
searchStore.playlists = Array.isArray(response?.items) ? response.items : [];
|
| 578 |
+
break;
|
| 579 |
+
}
|
| 580 |
+
}
|
| 581 |
+
} catch (err) {
|
| 582 |
+
searchStore.error = err instanceof Error ? err.message : 'Search failed';
|
| 583 |
+
console.error('Search error:', err);
|
| 584 |
+
} finally {
|
| 585 |
+
searchStore.isLoading = false;
|
| 586 |
+
}
|
| 587 |
+
}
|
| 588 |
+
|
| 589 |
+
async function handleStreamingUrlConversion() {
|
| 590 |
+
if (!searchStore.query.trim()) {
|
| 591 |
+
return;
|
| 592 |
+
}
|
| 593 |
+
|
| 594 |
+
searchStore.isLoading = true;
|
| 595 |
+
searchStore.error = null;
|
| 596 |
+
|
| 597 |
+
try {
|
| 598 |
+
const platformName = getPlatformName(searchStore.query.trim());
|
| 599 |
+
console.log(`Converting ${platformName || 'streaming'} URL to TIDAL...`);
|
| 600 |
+
|
| 601 |
+
const tidalInfo = await convertToTidal(searchStore.query.trim(), {
|
| 602 |
+
userCountry: 'US',
|
| 603 |
+
songIfSingle: true
|
| 604 |
+
});
|
| 605 |
+
|
| 606 |
+
if (!tidalInfo) {
|
| 607 |
+
searchStore.error = `Could not find TIDAL equivalent for this ${platformName || 'streaming platform'} link. The content might not be available on TIDAL.`;
|
| 608 |
+
searchStore.isLoading = false;
|
| 609 |
+
return;
|
| 610 |
+
}
|
| 611 |
+
|
| 612 |
+
console.log('Converted to TIDAL:', tidalInfo);
|
| 613 |
+
|
| 614 |
+
// Load the TIDAL content based on type
|
| 615 |
+
switch (tidalInfo.type) {
|
| 616 |
+
case 'track': {
|
| 617 |
+
const trackLookup = await losslessAPI.getTrack(Number(tidalInfo.id));
|
| 618 |
+
if (trackLookup?.track) {
|
| 619 |
+
// Pre-cache the stream URL for this track
|
| 620 |
+
try {
|
| 621 |
+
const quality = $playerStore.quality;
|
| 622 |
+
await losslessAPI.getStreamUrl(trackLookup.track.id, quality);
|
| 623 |
+
console.log(`Cached stream for track ${trackLookup.track.id}`);
|
| 624 |
+
} catch (cacheErr) {
|
| 625 |
+
console.warn(`Failed to cache stream for track ${trackLookup.track.id}:`, cacheErr);
|
| 626 |
+
}
|
| 627 |
+
|
| 628 |
+
playerStore.setTrack(trackLookup.track);
|
| 629 |
+
playerStore.play();
|
| 630 |
+
searchStore.query = '';
|
| 631 |
+
}
|
| 632 |
+
break;
|
| 633 |
+
}
|
| 634 |
+
case 'album': {
|
| 635 |
+
const albumData = await losslessAPI.getAlbum(Number(tidalInfo.id));
|
| 636 |
+
if (albumData?.album) {
|
| 637 |
+
searchStore.activeTab = 'albums';
|
| 638 |
+
searchStore.albums = [albumData.album];
|
| 639 |
+
searchStore.query = '';
|
| 640 |
+
}
|
| 641 |
+
break;
|
| 642 |
+
}
|
| 643 |
+
case 'playlist': {
|
| 644 |
+
const playlistData = await losslessAPI.getPlaylist(tidalInfo.id);
|
| 645 |
+
if (playlistData?.playlist) {
|
| 646 |
+
searchStore.activeTab = 'playlists';
|
| 647 |
+
searchStore.playlists = [playlistData.playlist];
|
| 648 |
+
searchStore.query = '';
|
| 649 |
+
}
|
| 650 |
+
break;
|
| 651 |
+
}
|
| 652 |
+
}
|
| 653 |
+
} catch (err) {
|
| 654 |
+
searchStore.error = err instanceof Error ? err.message : 'Failed to convert URL';
|
| 655 |
+
console.error('Streaming URL conversion error:', err);
|
| 656 |
+
} finally {
|
| 657 |
+
searchStore.isLoading = false;
|
| 658 |
+
}
|
| 659 |
+
}
|
| 660 |
+
|
| 661 |
+
async function handleSpotifyPlaylistConversion() {
|
| 662 |
+
if (!searchStore.query.trim()) {
|
| 663 |
+
return;
|
| 664 |
+
}
|
| 665 |
+
|
| 666 |
+
searchStore.error = null;
|
| 667 |
+
searchStore.playlistLoadingMessage = 'Loading playlist...';
|
| 668 |
+
searchStore.isPlaylistConversionMode = true;
|
| 669 |
+
searchStore.isLoading = true;
|
| 670 |
+
|
| 671 |
+
try {
|
| 672 |
+
console.log('Fetching Spotify playlist tracks...');
|
| 673 |
+
|
| 674 |
+
// Step 1: Get all Spotify track URLs from the playlist
|
| 675 |
+
const spotifyTrackUrls = await convertSpotifyPlaylist(searchStore.query.trim());
|
| 676 |
+
|
| 677 |
+
if (!spotifyTrackUrls || spotifyTrackUrls.length === 0) {
|
| 678 |
+
searchStore.error =
|
| 679 |
+
'Could not fetch tracks from Spotify playlist. The playlist might be empty or private.';
|
| 680 |
+
searchStore.playlistLoadingMessage = null;
|
| 681 |
+
searchStore.isLoading = false;
|
| 682 |
+
searchStore.isPlaylistConversionMode = false;
|
| 683 |
+
return;
|
| 684 |
+
}
|
| 685 |
+
|
| 686 |
+
console.log(`Found ${spotifyTrackUrls.length} tracks in playlist`);
|
| 687 |
+
searchStore.playlistConversionTotal = spotifyTrackUrls.length;
|
| 688 |
+
searchStore.playlistLoadingMessage = `Loading ${spotifyTrackUrls.length} tracks...`;
|
| 689 |
+
|
| 690 |
+
// Clear previous results and switch to tracks tab
|
| 691 |
+
searchStore.activeTab = 'tracks';
|
| 692 |
+
searchStore.tracks = [];
|
| 693 |
+
|
| 694 |
+
// Set loading to false so tracks can be displayed as they're added
|
| 695 |
+
searchStore.isLoading = false;
|
| 696 |
+
|
| 697 |
+
// Step 2: Fetch Songlink data for all tracks (no TIDAL conversion yet!)
|
| 698 |
+
const conversionPromises = spotifyTrackUrls.map(async (trackUrl, index) => {
|
| 699 |
+
try {
|
| 700 |
+
const songlinkData = await fetchSonglinkData(trackUrl, {
|
| 701 |
+
userCountry: 'US',
|
| 702 |
+
songIfSingle: true
|
| 703 |
+
});
|
| 704 |
+
|
| 705 |
+
// Extract TIDAL entity for display
|
| 706 |
+
const tidalEntity = extractTidalSongEntity(songlinkData);
|
| 707 |
+
|
| 708 |
+
if (tidalEntity) {
|
| 709 |
+
// Create a SonglinkTrack object (no TIDAL API call!)
|
| 710 |
+
const songlinkTrack: SonglinkTrack = {
|
| 711 |
+
id: songlinkData.entityUniqueId,
|
| 712 |
+
title: tidalEntity.title || 'Unknown Track',
|
| 713 |
+
artistName: tidalEntity.artistName || 'Unknown Artist',
|
| 714 |
+
duration: 180, // Placeholder duration (3 minutes)
|
| 715 |
+
thumbnailUrl: tidalEntity.thumbnailUrl || '',
|
| 716 |
+
sourceUrl: trackUrl,
|
| 717 |
+
songlinkData,
|
| 718 |
+
isSonglinkTrack: true,
|
| 719 |
+
tidalId: tidalEntity.id ? Number(tidalEntity.id) : undefined,
|
| 720 |
+
audioQuality: 'LOSSLESS'
|
| 721 |
+
};
|
| 722 |
+
|
| 723 |
+
return { success: true, track: songlinkTrack, url: trackUrl };
|
| 724 |
+
}
|
| 725 |
+
|
| 726 |
+
return { success: false, url: trackUrl };
|
| 727 |
+
} catch (err) {
|
| 728 |
+
console.warn(`Failed to fetch Songlink data for track ${index + 1}:`, err);
|
| 729 |
+
return { success: false, url: trackUrl };
|
| 730 |
+
}
|
| 731 |
+
});
|
| 732 |
+
|
| 733 |
+
// Wait for all Songlink fetches to complete
|
| 734 |
+
const results = await Promise.allSettled(conversionPromises);
|
| 735 |
+
|
| 736 |
+
// Process results and update UI
|
| 737 |
+
const successfulTracks: SonglinkTrack[] = [];
|
| 738 |
+
const failedTracks: string[] = [];
|
| 739 |
+
|
| 740 |
+
results.forEach((result, index) => {
|
| 741 |
+
if (result.status === 'fulfilled' && result.value.success && result.value.track) {
|
| 742 |
+
successfulTracks.push(result.value.track);
|
| 743 |
+
} else {
|
| 744 |
+
failedTracks.push(spotifyTrackUrls[index]);
|
| 745 |
+
}
|
| 746 |
+
|
| 747 |
+
// Update progress message
|
| 748 |
+
searchStore.playlistLoadingMessage = `Loaded ${index + 1}/${spotifyTrackUrls.length} tracks...`;
|
| 749 |
+
});
|
| 750 |
+
|
| 751 |
+
// Update tracks all at once for better performance
|
| 752 |
+
searchStore.tracks = successfulTracks;
|
| 753 |
+
|
| 754 |
+
console.log(`Successfully loaded ${searchStore.tracks.length}/${spotifyTrackUrls.length} tracks`);
|
| 755 |
+
|
| 756 |
+
if (searchStore.tracks.length === 0) {
|
| 757 |
+
searchStore.error = 'Could not find TIDAL equivalents for any tracks in this playlist.';
|
| 758 |
+
searchStore.playlistLoadingMessage = null;
|
| 759 |
+
searchStore.isPlaylistConversionMode = false;
|
| 760 |
+
return;
|
| 761 |
+
}
|
| 762 |
+
|
| 763 |
+
// Show a message if some tracks failed
|
| 764 |
+
if (failedTracks.length > 0) {
|
| 765 |
+
console.warn(`${failedTracks.length} tracks could not be loaded`);
|
| 766 |
+
searchStore.playlistLoadingMessage = `Loaded ${searchStore.tracks.length} tracks (${failedTracks.length} failed)`;
|
| 767 |
+
} else {
|
| 768 |
+
searchStore.playlistLoadingMessage = `Successfully loaded ${searchStore.tracks.length} tracks!`;
|
| 769 |
+
}
|
| 770 |
+
|
| 771 |
+
// Clear the query and hide loading message after a brief delay
|
| 772 |
+
searchStore.query = '';
|
| 773 |
+
setTimeout(() => {
|
| 774 |
+
searchStore.playlistLoadingMessage = null;
|
| 775 |
+
}, 3000);
|
| 776 |
+
} catch (err) {
|
| 777 |
+
searchStore.error = err instanceof Error ? err.message : 'Failed to load Spotify playlist';
|
| 778 |
+
console.error('Spotify playlist loading error:', err);
|
| 779 |
+
searchStore.playlistLoadingMessage = null;
|
| 780 |
+
searchStore.isPlaylistConversionMode = false;
|
| 781 |
+
}
|
| 782 |
+
}
|
| 783 |
+
|
| 784 |
+
function handlePlayAll() {
|
| 785 |
+
if (searchStore.tracks.length > 0) {
|
| 786 |
+
playerStore.setQueue(searchStore.tracks, 0);
|
| 787 |
+
playerStore.play();
|
| 788 |
+
}
|
| 789 |
+
}
|
| 790 |
+
|
| 791 |
+
function handleShuffleAll() {
|
| 792 |
+
if (searchStore.tracks.length > 0) {
|
| 793 |
+
// Shuffle the tracks
|
| 794 |
+
const shuffled = [...searchStore.tracks].sort(() => Math.random() - 0.5);
|
| 795 |
+
playerStore.setQueue(shuffled, 0);
|
| 796 |
+
playerStore.play();
|
| 797 |
+
}
|
| 798 |
+
}
|
| 799 |
+
|
| 800 |
+
async function handleDownloadAll() {
|
| 801 |
+
if (searchStore.tracks.length === 0) return;
|
| 802 |
+
|
| 803 |
+
const quality = $playerStore.quality;
|
| 804 |
+
const convertAacToMp3Preference = $userPreferencesStore.convertAacToMp3;
|
| 805 |
+
const downloadCoverSeperatelyPreference = $userPreferencesStore.downloadCoversSeperately;
|
| 806 |
+
|
| 807 |
+
for (const track of searchStore.tracks) {
|
| 808 |
+
try {
|
| 809 |
+
// Use tidalId if available (for Songlink tracks), otherwise use id
|
| 810 |
+
const trackId = 'tidalId' in track && track.tidalId ? track.tidalId : track.id;
|
| 811 |
+
|
| 812 |
+
// Skip if we don't have a valid numeric ID (e.g. unconverted Songlink track)
|
| 813 |
+
if (typeof trackId !== 'number') {
|
| 814 |
+
console.warn(`Skipping download for track ${track.title}: No valid TIDAL ID`);
|
| 815 |
+
continue;
|
| 816 |
+
}
|
| 817 |
+
|
| 818 |
+
const artistName = 'artistName' in track ? track.artistName : formatArtists(track.artists);
|
| 819 |
+
const albumTitle = 'album' in track ? track.album?.title : undefined;
|
| 820 |
+
|
| 821 |
+
let title = track.title;
|
| 822 |
+
if ('version' in track && track.version) {
|
| 823 |
+
title = `${title} (${track.version})`;
|
| 824 |
+
}
|
| 825 |
+
|
| 826 |
+
const filename = `${artistName} - ${title}.${getExtensionForQuality(quality)}`;
|
| 827 |
+
|
| 828 |
+
const { taskId, controller } = downloadUiStore.beginTrackDownload(track, filename, {
|
| 829 |
+
subtitle: albumTitle ?? artistName
|
| 830 |
+
});
|
| 831 |
+
|
| 832 |
+
await losslessAPI.downloadTrack(trackId, quality, filename, {
|
| 833 |
+
signal: controller.signal,
|
| 834 |
+
onProgress: (progress: TrackDownloadProgress) => {
|
| 835 |
+
if (progress.stage === 'downloading') {
|
| 836 |
+
downloadUiStore.updateTrackProgress(
|
| 837 |
+
taskId,
|
| 838 |
+
progress.receivedBytes,
|
| 839 |
+
progress.totalBytes
|
| 840 |
+
);
|
| 841 |
+
} else {
|
| 842 |
+
downloadUiStore.updateTrackStage(taskId, progress.progress);
|
| 843 |
+
}
|
| 844 |
+
},
|
| 845 |
+
onFfmpegCountdown: ({ totalBytes }) => {
|
| 846 |
+
if (typeof totalBytes === 'number') {
|
| 847 |
+
downloadUiStore.startFfmpegCountdown(totalBytes, { autoTriggered: false });
|
| 848 |
+
} else {
|
| 849 |
+
downloadUiStore.startFfmpegCountdown(0, { autoTriggered: false });
|
| 850 |
+
}
|
| 851 |
+
},
|
| 852 |
+
onFfmpegStart: () => downloadUiStore.startFfmpegLoading(),
|
| 853 |
+
onFfmpegProgress: (value) => downloadUiStore.updateFfmpegProgress(value),
|
| 854 |
+
onFfmpegComplete: () => downloadUiStore.completeFfmpeg(),
|
| 855 |
+
onFfmpegError: (error) => downloadUiStore.errorFfmpeg(error),
|
| 856 |
+
ffmpegAutoTriggered: false,
|
| 857 |
+
convertAacToMp3: convertAacToMp3Preference,
|
| 858 |
+
downloadCoverSeperately: downloadCoverSeperatelyPreference
|
| 859 |
+
});
|
| 860 |
+
|
| 861 |
+
downloadUiStore.completeTrackDownload(taskId);
|
| 862 |
+
} catch (error) {
|
| 863 |
+
console.error(`Failed to download track ${track.title}:`, error);
|
| 864 |
+
}
|
| 865 |
+
}
|
| 866 |
+
}
|
| 867 |
+
|
| 868 |
+
function handleKeyPress(event: KeyboardEvent) {
|
| 869 |
+
if (event.key === 'Enter') {
|
| 870 |
+
handleSearch();
|
| 871 |
+
}
|
| 872 |
+
}
|
| 873 |
+
|
| 874 |
+
function handleTabChange(tab: SearchTab) {
|
| 875 |
+
searchStore.activeTab = tab;
|
| 876 |
+
// Only trigger search if we have a query and it's not a URL
|
| 877 |
+
if (searchStore.query.trim() && !isQueryAUrl) {
|
| 878 |
+
handleSearch();
|
| 879 |
+
}
|
| 880 |
+
}
|
| 881 |
+
|
| 882 |
+
function handleRegionChange(event: Event) {
|
| 883 |
+
const target = event.currentTarget as HTMLSelectElement | null;
|
| 884 |
+
if (!target) return;
|
| 885 |
+
const value = ensureSupportedRegion(target.value as RegionOption);
|
| 886 |
+
if (value !== selectedRegion) {
|
| 887 |
+
regionStore.setRegion(value);
|
| 888 |
+
// Only trigger search if we have a query and it's not a URL
|
| 889 |
+
if (searchStore.query.trim() && !isQueryAUrl) {
|
| 890 |
+
handleSearch();
|
| 891 |
+
}
|
| 892 |
+
}
|
| 893 |
+
// Close the selector after selection
|
| 894 |
+
isRegionSelectorOpen = false;
|
| 895 |
+
}
|
| 896 |
+
|
| 897 |
+
function handleRegionClick(event: MouseEvent) {
|
| 898 |
+
const target = event.currentTarget as HTMLSelectElement | null;
|
| 899 |
+
if (!target) return;
|
| 900 |
+
// Toggle the open state when clicking
|
| 901 |
+
isRegionSelectorOpen = !isRegionSelectorOpen;
|
| 902 |
+
}
|
| 903 |
+
|
| 904 |
+
function displayTrackTotal(total?: number | null): number {
|
| 905 |
+
if (!Number.isFinite(total)) return 0;
|
| 906 |
+
return total && total > 0 ? total : (total ?? 0);
|
| 907 |
+
}
|
| 908 |
+
|
| 909 |
+
function formatQualityLabel(quality?: string | null): string {
|
| 910 |
+
if (!quality) return '—';
|
| 911 |
+
const normalized = quality.toUpperCase();
|
| 912 |
+
if (normalized === 'LOSSLESS') {
|
| 913 |
+
return 'CD • 16-bit/44.1 kHz FLAC';
|
| 914 |
+
}
|
| 915 |
+
if (normalized === 'HI_RES_LOSSLESS') {
|
| 916 |
+
return 'Hi-Res • up to 24-bit/192 kHz FLAC';
|
| 917 |
+
}
|
| 918 |
+
return quality;
|
| 919 |
+
}
|
| 920 |
+
|
| 921 |
+
function asTrack(track: PlayableTrack): Track {
|
| 922 |
+
return track as Track;
|
| 923 |
+
}
|
| 924 |
+
</script>
|
| 925 |
+
|
| 926 |
+
<div class="w-full">
|
| 927 |
+
<!-- Search Input -->
|
| 928 |
+
<div class="mb-6">
|
| 929 |
+
<div
|
| 930 |
+
class="search-glass rounded-lg border px-3 py-2 pr-2 shadow-sm transition-colors focus-within:border-blue-500"
|
| 931 |
+
>
|
| 932 |
+
<div class="flex flex-row gap-2 sm:items-center sm:justify-between">
|
| 933 |
+
<div class="flex min-w-0 flex-1 items-center gap-2">
|
| 934 |
+
<input
|
| 935 |
+
type="text"
|
| 936 |
+
bind:value={searchStore.query}
|
| 937 |
+
onkeypress={handleKeyPress}
|
| 938 |
+
placeholder={isQueryATidalUrl
|
| 939 |
+
? 'Tidal URL detected - press Enter to import'
|
| 940 |
+
: isQueryASpotifyPlaylist
|
| 941 |
+
? 'Spotify playlist detected - press Enter to convert'
|
| 942 |
+
: isQueryAStreamingUrl
|
| 943 |
+
? `${getPlatformName(searchStore.query)} URL detected - press Enter to convert`
|
| 944 |
+
: 'Search for tracks, albums, artists... or paste a URL'}
|
| 945 |
+
class="w-full min-w-0 flex-1 border-none bg-transparent p-0 pl-1 text-white ring-0 placeholder:text-gray-400 focus:outline-none"
|
| 946 |
+
/>
|
| 947 |
+
</div>
|
| 948 |
+
<div class="flex w-auto flex-row items-center gap-2">
|
| 949 |
+
{#if false} <!-- hide the region selector that doesn't even work lol -->
|
| 950 |
+
<div class="relative w-auto">
|
| 951 |
+
<label class="sr-only" for="region-select">Region</label>
|
| 952 |
+
<Earth
|
| 953 |
+
size={18}
|
| 954 |
+
color="#ffffff"
|
| 955 |
+
class="text0white pointer-events-none absolute top-1/2 left-3 -translate-y-1/2"
|
| 956 |
+
style="color: #ffffff; z-index: 99;"
|
| 957 |
+
/>
|
| 958 |
+
<select
|
| 959 |
+
id="region-select"
|
| 960 |
+
class="region-selector w-[52px] cursor-pointer appearance-none rounded-md border py-2 pr-9 pl-9 text-sm font-medium text-white ring-0 transition-colors focus:outline-none sm:w-auto"
|
| 961 |
+
value={selectedRegion}
|
| 962 |
+
onchange={handleRegionChange}
|
| 963 |
+
onmousedown={handleRegionClick}
|
| 964 |
+
onblur={() => (isRegionSelectorOpen = false)}
|
| 965 |
+
title="Change search region"
|
| 966 |
+
>
|
| 967 |
+
<option value="auto">Auto</option>
|
| 968 |
+
<option
|
| 969 |
+
value="us"
|
| 970 |
+
disabled={!regionAvailability.us}
|
| 971 |
+
class:opacity-50={!regionAvailability.us}
|
| 972 |
+
>
|
| 973 |
+
US
|
| 974 |
+
</option>
|
| 975 |
+
<option
|
| 976 |
+
value="eu"
|
| 977 |
+
disabled={!regionAvailability.eu}
|
| 978 |
+
class:opacity-50={!regionAvailability.eu}
|
| 979 |
+
>
|
| 980 |
+
EU
|
| 981 |
+
</option>
|
| 982 |
+
</select>
|
| 983 |
+
<span
|
| 984 |
+
class={`region-chevron pointer-events-none absolute top-1/2 right-3 text-gray-400 ${isRegionSelectorOpen ? 'rotate-180' : ''}`}
|
| 985 |
+
>
|
| 986 |
+
<ChevronDown size={16} />
|
| 987 |
+
</span>
|
| 988 |
+
</div>
|
| 989 |
+
{/if}
|
| 990 |
+
<button
|
| 991 |
+
onclick={handleSearch}
|
| 992 |
+
disabled={searchStore.isLoading || !searchStore.query.trim()}
|
| 993 |
+
class="search-button flex h-full items-center justify-center gap-2 rounded-md px-3 py-2 text-sm font-semibold text-white transition-colors disabled:cursor-not-allowed disabled:opacity-60 sm:w-auto"
|
| 994 |
+
>
|
| 995 |
+
{#if isQueryASpotifyPlaylist}
|
| 996 |
+
<Link2 size={16} class="text-white" />
|
| 997 |
+
<span class="hidden sm:inline">{searchStore.isLoading ? 'Converting…' : 'Convert Playlist'}</span>
|
| 998 |
+
{:else if isQueryAStreamingUrl}
|
| 999 |
+
<Link2 size={16} class="text-white" />
|
| 1000 |
+
<span class="hidden sm:inline">{searchStore.isLoading ? 'Converting…' : 'Convert & Play'}</span>
|
| 1001 |
+
{:else if isQueryATidalUrl}
|
| 1002 |
+
<Link2 size={16} class="text-white" />
|
| 1003 |
+
<span class="hidden sm:inline">{searchStore.isLoading ? 'Importing…' : 'Import'}</span>
|
| 1004 |
+
{:else}
|
| 1005 |
+
<Search size={16} class="text-white" />
|
| 1006 |
+
<span class="hidden sm:inline">{searchStore.isLoading ? 'Searching…' : 'Search'}</span>
|
| 1007 |
+
{/if}
|
| 1008 |
+
</button>
|
| 1009 |
+
</div>
|
| 1010 |
+
</div>
|
| 1011 |
+
</div>
|
| 1012 |
+
</div>
|
| 1013 |
+
|
| 1014 |
+
<!-- Tabs (hidden when URL is detected) -->
|
| 1015 |
+
{#if !isQueryAUrl}
|
| 1016 |
+
<div class="scrollbar-hide mb-6 flex gap-2 overflow-x-auto border-b border-gray-700">
|
| 1017 |
+
<button
|
| 1018 |
+
onclick={() => handleTabChange('tracks')}
|
| 1019 |
+
class="flex cursor-pointer items-center gap-2 border-b-2 px-3 py-2 whitespace-nowrap transition-colors sm:px-4 {searchStore.activeTab ===
|
| 1020 |
+
'tracks'
|
| 1021 |
+
? 'border-blue-500 text-blue-500'
|
| 1022 |
+
: 'border-transparent text-gray-300 hover:text-white'}"
|
| 1023 |
+
>
|
| 1024 |
+
<Music size={18} />
|
| 1025 |
+
<span class="text-sm sm:text-base">Tracks</span>
|
| 1026 |
+
</button>
|
| 1027 |
+
<button
|
| 1028 |
+
onclick={() => handleTabChange('albums')}
|
| 1029 |
+
class="flex cursor-pointer items-center gap-2 border-b-2 px-3 py-2 whitespace-nowrap transition-colors sm:px-4 {searchStore.activeTab ===
|
| 1030 |
+
'albums'
|
| 1031 |
+
? 'border-blue-500 text-blue-500'
|
| 1032 |
+
: 'border-transparent text-gray-300 hover:text-white'}"
|
| 1033 |
+
>
|
| 1034 |
+
<Disc size={18} />
|
| 1035 |
+
<span class="text-sm sm:text-base">Albums</span>
|
| 1036 |
+
</button>
|
| 1037 |
+
<button
|
| 1038 |
+
onclick={() => handleTabChange('artists')}
|
| 1039 |
+
class="flex cursor-pointer items-center gap-2 border-b-2 px-3 py-2 whitespace-nowrap transition-colors sm:px-4 {searchStore.activeTab ===
|
| 1040 |
+
'artists'
|
| 1041 |
+
? 'border-blue-500 text-blue-500'
|
| 1042 |
+
: 'border-transparent text-gray-300 hover:text-white'}"
|
| 1043 |
+
>
|
| 1044 |
+
<User size={18} />
|
| 1045 |
+
<span class="text-sm sm:text-base">Artists</span>
|
| 1046 |
+
</button>
|
| 1047 |
+
<button
|
| 1048 |
+
onclick={() => handleTabChange('playlists')}
|
| 1049 |
+
class="flex cursor-pointer items-center gap-2 border-b-2 px-3 py-2 whitespace-nowrap transition-colors sm:px-4 {searchStore.activeTab ===
|
| 1050 |
+
'playlists'
|
| 1051 |
+
? 'border-blue-500 text-blue-500'
|
| 1052 |
+
: 'border-transparent text-gray-300 hover:text-white'}"
|
| 1053 |
+
>
|
| 1054 |
+
<List size={18} />
|
| 1055 |
+
<span class="text-sm sm:text-base">Playlists</span>
|
| 1056 |
+
</button>
|
| 1057 |
+
</div>
|
| 1058 |
+
{/if}
|
| 1059 |
+
|
| 1060 |
+
<!-- Loading State -->
|
| 1061 |
+
{#if searchStore.isLoading}
|
| 1062 |
+
{#if searchStore.activeTab === 'tracks'}
|
| 1063 |
+
<div class="space-y-2">
|
| 1064 |
+
{#each trackSkeletons as _}
|
| 1065 |
+
<div class="flex w-full items-center gap-3 rounded-lg bg-gray-800/70 p-3">
|
| 1066 |
+
<div class="h-12 w-12 flex-shrink-0 animate-pulse rounded bg-gray-700/80"></div>
|
| 1067 |
+
<div class="flex-1 space-y-2">
|
| 1068 |
+
<div class="h-4 w-2/3 animate-pulse rounded bg-gray-700/80"></div>
|
| 1069 |
+
<div class="h-3 w-1/3 animate-pulse rounded bg-gray-700/60"></div>
|
| 1070 |
+
<div class="h-3 w-1/4 animate-pulse rounded bg-gray-700/40"></div>
|
| 1071 |
+
</div>
|
| 1072 |
+
<div class="h-6 w-12 animate-pulse rounded-full bg-gray-700/80"></div>
|
| 1073 |
+
</div>
|
| 1074 |
+
{/each}
|
| 1075 |
+
</div>
|
| 1076 |
+
{:else if searchStore.activeTab === 'albums' || searchStore.activeTab === 'playlists'}
|
| 1077 |
+
<div class="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
|
| 1078 |
+
{#each gridSkeletons as _}
|
| 1079 |
+
<div class="space-y-3">
|
| 1080 |
+
<div class="aspect-square w-full animate-pulse rounded-lg bg-gray-800/70"></div>
|
| 1081 |
+
<div class="h-4 w-3/4 animate-pulse rounded bg-gray-700/80"></div>
|
| 1082 |
+
<div class="h-3 w-1/2 animate-pulse rounded bg-gray-700/60"></div>
|
| 1083 |
+
</div>
|
| 1084 |
+
{/each}
|
| 1085 |
+
</div>
|
| 1086 |
+
{:else if searchStore.activeTab === 'artists'}
|
| 1087 |
+
<div class="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6">
|
| 1088 |
+
{#each gridSkeletons as _}
|
| 1089 |
+
<div class="flex flex-col items-center gap-3">
|
| 1090 |
+
<div class="aspect-square w-full animate-pulse rounded-full bg-gray-800/70"></div>
|
| 1091 |
+
<div class="h-4 w-3/4 animate-pulse rounded bg-gray-700/80"></div>
|
| 1092 |
+
<div class="h-3 w-1/2 animate-pulse rounded bg-gray-700/60"></div>
|
| 1093 |
+
</div>
|
| 1094 |
+
{/each}
|
| 1095 |
+
</div>
|
| 1096 |
+
{:else}
|
| 1097 |
+
<div class="flex items-center justify-center py-12">
|
| 1098 |
+
<div class="h-10 w-10 animate-spin rounded-full border-b-2 border-blue-500"></div>
|
| 1099 |
+
</div>
|
| 1100 |
+
{/if}
|
| 1101 |
+
{/if}
|
| 1102 |
+
|
| 1103 |
+
<!-- Error State -->
|
| 1104 |
+
{#if searchStore.error}
|
| 1105 |
+
<div class="rounded-lg border border-red-900 bg-red-900/20 p-4 text-red-400">
|
| 1106 |
+
{searchStore.error}
|
| 1107 |
+
</div>
|
| 1108 |
+
{/if}
|
| 1109 |
+
|
| 1110 |
+
<!-- Playlist Loading Progress -->
|
| 1111 |
+
{#if searchStore.playlistLoadingMessage}
|
| 1112 |
+
<div
|
| 1113 |
+
class="mb-4 flex items-center gap-3 rounded-lg border border-blue-900 bg-blue-900/20 p-4 text-blue-400"
|
| 1114 |
+
>
|
| 1115 |
+
<LoaderCircle class="animate-spin" size={20} />
|
| 1116 |
+
<span>{searchStore.playlistLoadingMessage}</span>
|
| 1117 |
+
</div>
|
| 1118 |
+
{/if}
|
| 1119 |
+
|
| 1120 |
+
<!-- Results -->
|
| 1121 |
+
{#if (!searchStore.isLoading && !searchStore.error) || (searchStore.isPlaylistConversionMode && searchStore.tracks.length > 0)}
|
| 1122 |
+
{#if searchStore.activeTab === 'tracks' && searchStore.tracks.length > 0}
|
| 1123 |
+
<!-- Playlist Controls (shown when in playlist conversion mode) -->
|
| 1124 |
+
{#if searchStore.isPlaylistConversionMode}
|
| 1125 |
+
<div class="mb-6 flex flex-wrap items-center gap-3">
|
| 1126 |
+
<button
|
| 1127 |
+
onclick={handlePlayAll}
|
| 1128 |
+
class="flex items-center gap-2 rounded-full bg-blue-600 px-6 py-3 font-semibold transition-colors hover:bg-blue-700"
|
| 1129 |
+
>
|
| 1130 |
+
<Play size={20} fill="currentColor" />
|
| 1131 |
+
Play All
|
| 1132 |
+
</button>
|
| 1133 |
+
<button
|
| 1134 |
+
onclick={handleShuffleAll}
|
| 1135 |
+
class="flex items-center gap-2 rounded-full bg-purple-600 px-6 py-3 font-semibold transition-colors hover:bg-purple-700"
|
| 1136 |
+
>
|
| 1137 |
+
<Shuffle size={20} />
|
| 1138 |
+
Shuffle All
|
| 1139 |
+
</button>
|
| 1140 |
+
<button
|
| 1141 |
+
onclick={handleDownloadAll}
|
| 1142 |
+
class="flex items-center gap-2 rounded-full bg-green-600 px-6 py-3 font-semibold transition-colors hover:bg-green-700"
|
| 1143 |
+
>
|
| 1144 |
+
<Download size={20} />
|
| 1145 |
+
Download All
|
| 1146 |
+
</button>
|
| 1147 |
+
<div class="ml-auto text-sm text-gray-400">
|
| 1148 |
+
{searchStore.tracks.length} of {searchStore.playlistConversionTotal} tracks
|
| 1149 |
+
</div>
|
| 1150 |
+
</div>
|
| 1151 |
+
{/if}
|
| 1152 |
+
|
| 1153 |
+
<div class="space-y-2">
|
| 1154 |
+
{#each searchStore.tracks as track}
|
| 1155 |
+
<div
|
| 1156 |
+
role="button"
|
| 1157 |
+
tabindex="0"
|
| 1158 |
+
onclick={(e) => {
|
| 1159 |
+
if (e.target instanceof Element && (e.target.closest('a') || e.target.closest('button'))) return;
|
| 1160 |
+
handleTrackActivation(track);
|
| 1161 |
+
}}
|
| 1162 |
+
onkeydown={(event) => handleTrackKeydown(event, track)}
|
| 1163 |
+
class="track-glass group flex w-full cursor-pointer items-center gap-3 rounded-lg p-3 transition-colors hover:brightness-110 focus:ring-2 focus:ring-blue-500 focus:outline-none {activeMenuId === track.id ? 'z-20 relative' : ''}"
|
| 1164 |
+
>
|
| 1165 |
+
{#if isSonglinkTrack(track)}
|
| 1166 |
+
<!-- Display for SonglinkTrack -->
|
| 1167 |
+
<img
|
| 1168 |
+
src={track.thumbnailUrl || '/placeholder-album.jpg'}
|
| 1169 |
+
alt={`${track.title} by ${track.artistName}`}
|
| 1170 |
+
class="h-12 w-12 flex-shrink-0 rounded object-cover"
|
| 1171 |
+
/>
|
| 1172 |
+
<div class="min-w-0 flex-1">
|
| 1173 |
+
<h3 class="truncate font-semibold text-white group-hover:text-blue-400 w-full">
|
| 1174 |
+
{track.title}
|
| 1175 |
+
</h3>
|
| 1176 |
+
<p class="truncate text-sm text-gray-400 w-full">
|
| 1177 |
+
{track.artistName}
|
| 1178 |
+
</p>
|
| 1179 |
+
<p class="text-xs text-gray-500">
|
| 1180 |
+
{formatQualityLabel(track.audioQuality)}
|
| 1181 |
+
</p>
|
| 1182 |
+
</div>
|
| 1183 |
+
<!-- Queue actions for Songlink tracks -->
|
| 1184 |
+
<div class="flex items-center gap-2 text-sm text-gray-400">
|
| 1185 |
+
<div class="relative">
|
| 1186 |
+
<button
|
| 1187 |
+
onclick={(event) => {
|
| 1188 |
+
event.stopPropagation();
|
| 1189 |
+
activeMenuId = activeMenuId === track.id ? null : track.id;
|
| 1190 |
+
}}
|
| 1191 |
+
class="rounded-full p-2 text-gray-400 transition-colors hover:text-white"
|
| 1192 |
+
title="Queue actions"
|
| 1193 |
+
aria-label="Queue actions for {track.title}"
|
| 1194 |
+
>
|
| 1195 |
+
<MoreVertical size={18} />
|
| 1196 |
+
</button>
|
| 1197 |
+
<!-- Dropdown menu for queue actions -->
|
| 1198 |
+
{#if activeMenuId === track.id}
|
| 1199 |
+
<div
|
| 1200 |
+
class="track-menu-container absolute right-0 top-full z-10 mt-1 w-48 rounded-lg border border-gray-700 bg-gray-800 shadow-lg"
|
| 1201 |
+
>
|
| 1202 |
+
<button
|
| 1203 |
+
onclick={(event) => {
|
| 1204 |
+
handlePlayNext(track, event);
|
| 1205 |
+
activeMenuId = null;
|
| 1206 |
+
}}
|
| 1207 |
+
class="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-gray-300 hover:bg-gray-700"
|
| 1208 |
+
>
|
| 1209 |
+
<ListVideo size={16} />
|
| 1210 |
+
Play Next
|
| 1211 |
+
</button>
|
| 1212 |
+
<button
|
| 1213 |
+
onclick={(event) => {
|
| 1214 |
+
handleAddToQueue(track, event);
|
| 1215 |
+
activeMenuId = null;
|
| 1216 |
+
}}
|
| 1217 |
+
class="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-gray-300 hover:bg-gray-700"
|
| 1218 |
+
>
|
| 1219 |
+
<ListPlus size={16} />
|
| 1220 |
+
Add to Queue
|
| 1221 |
+
</button>
|
| 1222 |
+
<div class="my-1 border-t border-gray-700"></div>
|
| 1223 |
+
<button
|
| 1224 |
+
onclick={(event) => {
|
| 1225 |
+
event.stopPropagation();
|
| 1226 |
+
copyToClipboard(getLongLink('track', track.id));
|
| 1227 |
+
activeMenuId = null;
|
| 1228 |
+
}}
|
| 1229 |
+
class="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-gray-300 hover:bg-gray-700"
|
| 1230 |
+
>
|
| 1231 |
+
<Link2 size={16} />
|
| 1232 |
+
Share Link
|
| 1233 |
+
</button>
|
| 1234 |
+
<button
|
| 1235 |
+
onclick={(event) => {
|
| 1236 |
+
event.stopPropagation();
|
| 1237 |
+
copyToClipboard(getShortLink('track', track.id));
|
| 1238 |
+
activeMenuId = null;
|
| 1239 |
+
}}
|
| 1240 |
+
class="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-gray-300 hover:bg-gray-700"
|
| 1241 |
+
>
|
| 1242 |
+
<Copy size={16} />
|
| 1243 |
+
Share Short Link
|
| 1244 |
+
</button>
|
| 1245 |
+
<button
|
| 1246 |
+
onclick={(event) => {
|
| 1247 |
+
event.stopPropagation();
|
| 1248 |
+
copyToClipboard(getEmbedCode('track', track.id));
|
| 1249 |
+
activeMenuId = null;
|
| 1250 |
+
}}
|
| 1251 |
+
class="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-gray-300 hover:bg-gray-700"
|
| 1252 |
+
>
|
| 1253 |
+
<Code size={16} />
|
| 1254 |
+
Copy Embed Code
|
| 1255 |
+
</button>
|
| 1256 |
+
</div>
|
| 1257 |
+
{/if}
|
| 1258 |
+
</div>
|
| 1259 |
+
</div>
|
| 1260 |
+
{:else}
|
| 1261 |
+
<!-- Display for regular Track -->
|
| 1262 |
+
{#if asTrack(track).album.cover}
|
| 1263 |
+
<img
|
| 1264 |
+
src={losslessAPI.getCoverUrl(asTrack(track).album.cover, '160')}
|
| 1265 |
+
alt={track.title}
|
| 1266 |
+
class="h-12 w-12 rounded object-cover"
|
| 1267 |
+
/>
|
| 1268 |
+
{/if}
|
| 1269 |
+
<div class="min-w-0 flex-1">
|
| 1270 |
+
<h3 class="truncate font-semibold text-white group-hover:text-blue-400 w-full">
|
| 1271 |
+
{track.title}{asTrack(track).version ? ` (${asTrack(track).version})` : ''}
|
| 1272 |
+
{#if asTrack(track).explicit}
|
| 1273 |
+
<svg
|
| 1274 |
+
class="inline h-4 w-4 flex-shrink-0 align-middle"
|
| 1275 |
+
xmlns="http://www.w3.org/2000/svg"
|
| 1276 |
+
fill="currentColor"
|
| 1277 |
+
height="24"
|
| 1278 |
+
viewBox="0 0 24 24"
|
| 1279 |
+
width="24"
|
| 1280 |
+
focusable="false"
|
| 1281 |
+
aria-hidden="true"
|
| 1282 |
+
><path
|
| 1283 |
+
d="M20 2H4a2 2 0 00-2 2v16a2 2 0 002 2h16a2 2 0 002-2V4a2 2 0 00-2-2ZM8 6h8a1 1 0 110 2H9v3h5a1 1 0 010 2H9v3h7a1 1 0 010 2H8a1 1 0 01-1-1V7a1 1 0 011-1Z"
|
| 1284 |
+
></path></svg
|
| 1285 |
+
>
|
| 1286 |
+
{/if}
|
| 1287 |
+
</h3>
|
| 1288 |
+
<a
|
| 1289 |
+
href={`/artist/${asTrack(track).artist.id}`}
|
| 1290 |
+
class="inline-block truncate text-sm text-gray-400 hover:text-blue-400 hover:underline w-full"
|
| 1291 |
+
data-sveltekit-preload-data
|
| 1292 |
+
>
|
| 1293 |
+
{formatArtists(asTrack(track).artists)}
|
| 1294 |
+
</a>
|
| 1295 |
+
<p class="text-xs text-gray-500">
|
| 1296 |
+
<a
|
| 1297 |
+
href={`/album/${asTrack(track).album.id}`}
|
| 1298 |
+
class="hover:text-blue-400 hover:underline"
|
| 1299 |
+
data-sveltekit-preload-data
|
| 1300 |
+
>
|
| 1301 |
+
{asTrack(track).album.title}
|
| 1302 |
+
</a>
|
| 1303 |
+
• {formatQualityLabel(track.audioQuality)}
|
| 1304 |
+
</p>
|
| 1305 |
+
</div>
|
| 1306 |
+
<div class="flex items-center gap-2 text-sm text-gray-400">
|
| 1307 |
+
<button
|
| 1308 |
+
onclick={(event) =>
|
| 1309 |
+
downloadingIds.has(track.id)
|
| 1310 |
+
? handleCancelDownload(track.id, event)
|
| 1311 |
+
: handleDownload(track, event)}
|
| 1312 |
+
class="rounded-full p-2 text-gray-400 transition-colors hover:text-white"
|
| 1313 |
+
title={downloadingIds.has(track.id) ? 'Cancel download' : 'Download track'}
|
| 1314 |
+
aria-label={downloadingIds.has(track.id)
|
| 1315 |
+
? `Cancel download for ${track.title}`
|
| 1316 |
+
: `Download ${track.title}`}
|
| 1317 |
+
aria-busy={downloadingIds.has(track.id)}
|
| 1318 |
+
aria-pressed={downloadingIds.has(track.id)}
|
| 1319 |
+
>
|
| 1320 |
+
{#if downloadingIds.has(track.id)}
|
| 1321 |
+
<span class="flex h-4 w-4 items-center justify-center">
|
| 1322 |
+
{#if cancelledIds.has(track.id)}
|
| 1323 |
+
<X size={14} />
|
| 1324 |
+
{:else}
|
| 1325 |
+
<span
|
| 1326 |
+
class="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"
|
| 1327 |
+
></span>
|
| 1328 |
+
{/if}
|
| 1329 |
+
</span>
|
| 1330 |
+
{:else if cancelledIds.has(track.id)}
|
| 1331 |
+
<X size={18} />
|
| 1332 |
+
{:else}
|
| 1333 |
+
<Download size={18} />
|
| 1334 |
+
{/if}
|
| 1335 |
+
</button>
|
| 1336 |
+
<div class="relative">
|
| 1337 |
+
<button
|
| 1338 |
+
onclick={(event) => {
|
| 1339 |
+
event.stopPropagation();
|
| 1340 |
+
activeMenuId = activeMenuId === track.id ? null : track.id;
|
| 1341 |
+
}}
|
| 1342 |
+
class="rounded-full p-2 text-gray-400 transition-colors hover:text-white"
|
| 1343 |
+
title="Queue actions"
|
| 1344 |
+
aria-label="Queue actions for {track.title}"
|
| 1345 |
+
>
|
| 1346 |
+
<MoreVertical size={18} />
|
| 1347 |
+
</button>
|
| 1348 |
+
{#if activeMenuId === track.id}
|
| 1349 |
+
<div
|
| 1350 |
+
class="track-menu-container absolute right-0 top-full z-10 mt-1 w-48 rounded-lg border border-gray-700 bg-gray-800 shadow-lg"
|
| 1351 |
+
>
|
| 1352 |
+
<button
|
| 1353 |
+
onclick={(event) => {
|
| 1354 |
+
handlePlayNext(track, event);
|
| 1355 |
+
activeMenuId = null;
|
| 1356 |
+
}}
|
| 1357 |
+
class="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-gray-300 hover:bg-gray-700"
|
| 1358 |
+
>
|
| 1359 |
+
<ListVideo size={16} />
|
| 1360 |
+
Play Next
|
| 1361 |
+
</button>
|
| 1362 |
+
<button
|
| 1363 |
+
onclick={(event) => {
|
| 1364 |
+
handleAddToQueue(track, event);
|
| 1365 |
+
activeMenuId = null;
|
| 1366 |
+
}}
|
| 1367 |
+
class="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-gray-300 hover:bg-gray-700"
|
| 1368 |
+
>
|
| 1369 |
+
<ListPlus size={16} />
|
| 1370 |
+
Add to Queue
|
| 1371 |
+
</button>
|
| 1372 |
+
<div class="my-1 border-t border-gray-700"></div>
|
| 1373 |
+
<button
|
| 1374 |
+
onclick={(event) => {
|
| 1375 |
+
event.stopPropagation();
|
| 1376 |
+
copyToClipboard(getLongLink('track', track.id));
|
| 1377 |
+
activeMenuId = null;
|
| 1378 |
+
}}
|
| 1379 |
+
class="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-gray-300 hover:bg-gray-700"
|
| 1380 |
+
>
|
| 1381 |
+
<Link2 size={16} />
|
| 1382 |
+
Share Link
|
| 1383 |
+
</button>
|
| 1384 |
+
<button
|
| 1385 |
+
onclick={(event) => {
|
| 1386 |
+
event.stopPropagation();
|
| 1387 |
+
copyToClipboard(getShortLink('track', track.id));
|
| 1388 |
+
activeMenuId = null;
|
| 1389 |
+
}}
|
| 1390 |
+
class="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-gray-300 hover:bg-gray-700"
|
| 1391 |
+
>
|
| 1392 |
+
<Copy size={16} />
|
| 1393 |
+
Share Short Link
|
| 1394 |
+
</button>
|
| 1395 |
+
<button
|
| 1396 |
+
onclick={(event) => {
|
| 1397 |
+
event.stopPropagation();
|
| 1398 |
+
copyToClipboard(getEmbedCode('track', track.id));
|
| 1399 |
+
activeMenuId = null;
|
| 1400 |
+
}}
|
| 1401 |
+
class="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-gray-300 hover:bg-gray-700"
|
| 1402 |
+
>
|
| 1403 |
+
<Code size={16} />
|
| 1404 |
+
Copy Embed Code
|
| 1405 |
+
</button>
|
| 1406 |
+
</div>
|
| 1407 |
+
{/if}
|
| 1408 |
+
</div>
|
| 1409 |
+
</div>
|
| 1410 |
+
{/if}
|
| 1411 |
+
{#if !('isSonglinkTrack' in track && track.isSonglinkTrack)}
|
| 1412 |
+
<span>{losslessAPI.formatDuration(track.duration)}</span>
|
| 1413 |
+
{/if}
|
| 1414 |
+
</div>
|
| 1415 |
+
{/each}
|
| 1416 |
+
</div>
|
| 1417 |
+
{:else if searchStore.activeTab === 'albums' && searchStore.albums.length > 0}
|
| 1418 |
+
<div class="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
|
| 1419 |
+
{#each searchStore.albums as album}
|
| 1420 |
+
<div class="group relative text-left">
|
| 1421 |
+
<button
|
| 1422 |
+
onclick={(event) => handleAlbumDownloadClick(album, event)}
|
| 1423 |
+
type="button"
|
| 1424 |
+
class="absolute top-3 right-3 z-40 flex items-center justify-center rounded-full bg-black/50 p-2 text-gray-200 backdrop-blur-md transition-colors hover:bg-blue-600/80 hover:text-white disabled:cursor-not-allowed disabled:opacity-60"
|
| 1425 |
+
disabled={albumDownloadStates[album.id]?.downloading}
|
| 1426 |
+
aria-label={`Download ${album.title}`}
|
| 1427 |
+
>
|
| 1428 |
+
{#if albumDownloadStates[album.id]?.downloading}
|
| 1429 |
+
<LoaderCircle size={16} class="animate-spin" />
|
| 1430 |
+
{:else}
|
| 1431 |
+
<Download size={16} />
|
| 1432 |
+
{/if}
|
| 1433 |
+
</button>
|
| 1434 |
+
<a
|
| 1435 |
+
href={`/album/${album.id}`}
|
| 1436 |
+
class="flex w-full flex-col text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 focus-visible:ring-offset-neutral-900"
|
| 1437 |
+
data-sveltekit-preload-data
|
| 1438 |
+
>
|
| 1439 |
+
<div class="relative mb-2 aspect-square overflow-hidden rounded-lg">
|
| 1440 |
+
{#if album.videoCover}
|
| 1441 |
+
<video
|
| 1442 |
+
src={losslessAPI.getVideoCoverUrl(album.videoCover, '640')}
|
| 1443 |
+
poster={album.cover ? losslessAPI.getCoverUrl(album.cover, '640') : undefined}
|
| 1444 |
+
aria-label={album.title}
|
| 1445 |
+
class="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
|
| 1446 |
+
autoplay
|
| 1447 |
+
loop
|
| 1448 |
+
muted
|
| 1449 |
+
playsinline
|
| 1450 |
+
preload="metadata"
|
| 1451 |
+
></video>
|
| 1452 |
+
{:else if album.cover}
|
| 1453 |
+
<img
|
| 1454 |
+
src={losslessAPI.getCoverUrl(album.cover, '640')}
|
| 1455 |
+
alt={album.title}
|
| 1456 |
+
class="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
|
| 1457 |
+
/>
|
| 1458 |
+
{:else}
|
| 1459 |
+
<div
|
| 1460 |
+
class="flex h-full w-full items-center justify-center bg-gray-800 text-sm text-gray-500"
|
| 1461 |
+
>
|
| 1462 |
+
No artwork
|
| 1463 |
+
</div>
|
| 1464 |
+
{/if}
|
| 1465 |
+
</div>
|
| 1466 |
+
<h3 class="truncate font-semibold text-white group-hover:text-blue-400 w-full">
|
| 1467 |
+
{album.title}
|
| 1468 |
+
{#if album.explicit}
|
| 1469 |
+
<svg
|
| 1470 |
+
class="inline h-4 w-4 flex-shrink-0 align-middle"
|
| 1471 |
+
xmlns="http://www.w3.org/2000/svg"
|
| 1472 |
+
fill="currentColor"
|
| 1473 |
+
height="24"
|
| 1474 |
+
viewBox="0 0 24 24"
|
| 1475 |
+
width="24"
|
| 1476 |
+
focusable="false"
|
| 1477 |
+
aria-hidden="true"
|
| 1478 |
+
><path
|
| 1479 |
+
d="M20 2H4a2 2 0 00-2 2v16a2 2 0 002 2h16a2 2 0 002-2V4a2 2 0 00-2-2ZM8 6h8a1 1 0 110 2H9v3h5a1 1 0 010 2H9v3h7a1 1 0 010 2H8a1 1 0 01-1-1V7a1 1 0 011-1Z"
|
| 1480 |
+
></path></svg
|
| 1481 |
+
>
|
| 1482 |
+
{/if}
|
| 1483 |
+
</h3>
|
| 1484 |
+
{#if album.artist}
|
| 1485 |
+
<p class="truncate text-sm text-gray-400 w-full">{album.artist.name}</p>
|
| 1486 |
+
{/if}
|
| 1487 |
+
{#if album.releaseDate}
|
| 1488 |
+
<p class="text-xs text-gray-500">{album.releaseDate.split('-')[0]}</p>
|
| 1489 |
+
{/if}
|
| 1490 |
+
</a>
|
| 1491 |
+
{#if albumDownloadStates[album.id]?.downloading}
|
| 1492 |
+
<p class="mt-2 text-xs text-blue-300">
|
| 1493 |
+
Downloading
|
| 1494 |
+
{#if albumDownloadStates[album.id]?.total}
|
| 1495 |
+
{albumDownloadStates[album.id]?.completed ?? 0}/{displayTrackTotal(
|
| 1496 |
+
albumDownloadStates[album.id]?.total ?? 0
|
| 1497 |
+
)}
|
| 1498 |
+
{:else}
|
| 1499 |
+
{albumDownloadStates[album.id]?.completed ?? 0}
|
| 1500 |
+
{/if}
|
| 1501 |
+
tracks…
|
| 1502 |
+
</p>
|
| 1503 |
+
{:else if albumDownloadStates[album.id]?.error}
|
| 1504 |
+
<p class="mt-2 text-xs text-red-400" role="alert">
|
| 1505 |
+
{albumDownloadStates[album.id]?.error}
|
| 1506 |
+
</p>
|
| 1507 |
+
{/if}
|
| 1508 |
+
</div>
|
| 1509 |
+
{/each}
|
| 1510 |
+
</div>
|
| 1511 |
+
{:else if searchStore.activeTab === 'artists' && searchStore.artists.length > 0}
|
| 1512 |
+
<div class="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6">
|
| 1513 |
+
{#each searchStore.artists as artist}
|
| 1514 |
+
<a href={`/artist/${artist.id}`} class="group text-center" data-sveltekit-preload-data>
|
| 1515 |
+
<div class="relative mb-2 aspect-square overflow-hidden rounded-full">
|
| 1516 |
+
{#if artist.picture}
|
| 1517 |
+
<img
|
| 1518 |
+
src={losslessAPI.getArtistPictureUrl(artist.picture)}
|
| 1519 |
+
alt={artist.name}
|
| 1520 |
+
class="h-full w-full object-cover transition-transform group-hover:scale-105"
|
| 1521 |
+
/>
|
| 1522 |
+
{:else}
|
| 1523 |
+
<div class="flex h-full w-full items-center justify-center bg-gray-800">
|
| 1524 |
+
<User size={48} class="text-gray-600" />
|
| 1525 |
+
</div>
|
| 1526 |
+
{/if}
|
| 1527 |
+
</div>
|
| 1528 |
+
<h3 class="truncate font-semibold text-white group-hover:text-blue-400 w-full">
|
| 1529 |
+
{artist.name}
|
| 1530 |
+
</h3>
|
| 1531 |
+
<p class="text-xs text-gray-500">Artist</p>
|
| 1532 |
+
</a>
|
| 1533 |
+
{/each}
|
| 1534 |
+
</div>
|
| 1535 |
+
{:else if searchStore.activeTab === 'playlists' && searchStore.playlists.length > 0}
|
| 1536 |
+
<div class="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
|
| 1537 |
+
{#each searchStore.playlists as playlist}
|
| 1538 |
+
<a
|
| 1539 |
+
href={`/playlist/${playlist.uuid}`}
|
| 1540 |
+
class="group text-left"
|
| 1541 |
+
data-sveltekit-preload-data
|
| 1542 |
+
>
|
| 1543 |
+
<div class="relative mb-2 aspect-square overflow-hidden rounded-lg">
|
| 1544 |
+
{#if playlist.squareImage || playlist.image}
|
| 1545 |
+
<img
|
| 1546 |
+
src={losslessAPI.getCoverUrl(playlist.squareImage || playlist.image, '640')}
|
| 1547 |
+
alt={playlist.title}
|
| 1548 |
+
class="h-full w-full object-cover transition-transform group-hover:scale-105"
|
| 1549 |
+
/>
|
| 1550 |
+
{/if}
|
| 1551 |
+
</div>
|
| 1552 |
+
<h3 class="truncate font-semibold text-white group-hover:text-blue-400 w-full">
|
| 1553 |
+
{playlist.title}
|
| 1554 |
+
</h3>
|
| 1555 |
+
<p class="truncate text-sm text-gray-400 w-full">{playlist.creator.name}</p>
|
| 1556 |
+
<p class="text-xs text-gray-500">{playlist.numberOfTracks} tracks</p>
|
| 1557 |
+
</a>
|
| 1558 |
+
{/each}
|
| 1559 |
+
</div>
|
| 1560 |
+
<!-- News Section -->
|
| 1561 |
+
{:else if !searchStore.query.trim()}
|
| 1562 |
+
<div class="news-container rounded-lg border p-4">
|
| 1563 |
+
<h2 class="mb-4 text-3xl font-bold">News</h2>
|
| 1564 |
+
<section class="grid gap-4 text-left shadow-lg sm:grid-cols-2">
|
| 1565 |
+
{#each newsItems as item}
|
| 1566 |
+
<article
|
| 1567 |
+
class="news-card flex flex-col gap-3 rounded-lg border p-4 transition-transform hover:-translate-y-0.5"
|
| 1568 |
+
>
|
| 1569 |
+
<div class="flex items-center gap-3">
|
| 1570 |
+
<div
|
| 1571 |
+
class="flex h-10 w-10 items-center justify-center rounded-full bg-blue-900/40 text-blue-300"
|
| 1572 |
+
>
|
| 1573 |
+
<Newspaper size={20} />
|
| 1574 |
+
</div>
|
| 1575 |
+
<h3 class="text-lg font-semibold text-white">{item.title}</h3>
|
| 1576 |
+
</div>
|
| 1577 |
+
<p class="text-sm text-gray-300">{item.description}</p>
|
| 1578 |
+
</article>
|
| 1579 |
+
{/each}
|
| 1580 |
+
</section>
|
| 1581 |
+
</div>
|
| 1582 |
+
{:else if isQueryATidalUrl && !searchStore.isLoading}
|
| 1583 |
+
<div class="py-12 text-center text-gray-400">
|
| 1584 |
+
<div class="flex flex-col items-center gap-4">
|
| 1585 |
+
<Link2 size={48} class="text-blue-400" />
|
| 1586 |
+
<p class="text-lg text-white">Tidal URL detected</p>
|
| 1587 |
+
<p class="text-sm">Press Enter or click Import to load this content</p>
|
| 1588 |
+
</div>
|
| 1589 |
+
</div>
|
| 1590 |
+
{:else if searchStore.query.trim() && !searchStore.isLoading && !isQueryATidalUrl}
|
| 1591 |
+
<div class="py-12 text-center text-gray-400">
|
| 1592 |
+
<p>No results found...</p>
|
| 1593 |
+
</div>
|
| 1594 |
+
{/if}
|
| 1595 |
+
{/if}
|
| 1596 |
+
</div>
|
| 1597 |
+
|
| 1598 |
+
<style>
|
| 1599 |
+
.search-glass {
|
| 1600 |
+
background: transparent;
|
| 1601 |
+
border-color: rgba(148, 163, 184, 0.2);
|
| 1602 |
+
backdrop-filter: blur(var(--perf-blur-high, 32px)) saturate(var(--perf-saturate, 160%));
|
| 1603 |
+
-webkit-backdrop-filter: blur(var(--perf-blur-high, 32px)) saturate(var(--perf-saturate, 160%));
|
| 1604 |
+
box-shadow:
|
| 1605 |
+
0 10px 30px rgba(2, 6, 23, 0.4),
|
| 1606 |
+
0 2px 8px rgba(15, 23, 42, 0.35),
|
| 1607 |
+
inset 0 1px 0 rgba(255, 255, 255, 0.06);
|
| 1608 |
+
transition:
|
| 1609 |
+
border-color 1.2s cubic-bezier(0.4, 0, 0.2, 1),
|
| 1610 |
+
box-shadow 0.3s ease;
|
| 1611 |
+
}
|
| 1612 |
+
|
| 1613 |
+
.track-glass {
|
| 1614 |
+
background: transparent;
|
| 1615 |
+
border: 1px solid rgba(148, 163, 184, 0.15);
|
| 1616 |
+
backdrop-filter: blur(var(--perf-blur-medium, 28px)) saturate(var(--perf-saturate, 160%));
|
| 1617 |
+
-webkit-backdrop-filter: blur(var(--perf-blur-medium, 28px))
|
| 1618 |
+
saturate(var(--perf-saturate, 160%));
|
| 1619 |
+
box-shadow:
|
| 1620 |
+
0 4px 12px rgba(2, 6, 23, 0.3),
|
| 1621 |
+
inset 0 1px 0 rgba(255, 255, 255, 0.04);
|
| 1622 |
+
transition:
|
| 1623 |
+
border-color 1.2s cubic-bezier(0.4, 0, 0.2, 1),
|
| 1624 |
+
box-shadow 0.3s ease,
|
| 1625 |
+
filter 0.2s ease;
|
| 1626 |
+
}
|
| 1627 |
+
|
| 1628 |
+
.region-selector {
|
| 1629 |
+
background: transparent;
|
| 1630 |
+
border-color: rgba(148, 163, 184, 0.2);
|
| 1631 |
+
backdrop-filter: blur(var(--perf-blur-high, 32px)) saturate(var(--perf-saturate, 160%));
|
| 1632 |
+
-webkit-backdrop-filter: blur(var(--perf-blur-high, 32px)) saturate(var(--perf-saturate, 160%));
|
| 1633 |
+
transition:
|
| 1634 |
+
border-color 1.2s cubic-bezier(0.4, 0, 0.2, 1),
|
| 1635 |
+
box-shadow 0.3s ease;
|
| 1636 |
+
}
|
| 1637 |
+
|
| 1638 |
+
.region-selector:hover {
|
| 1639 |
+
border-color: var(--bloom-accent, rgba(148, 163, 184, 0.3));
|
| 1640 |
+
box-shadow:
|
| 1641 |
+
0 6px 20px rgba(2, 6, 23, 0.4),
|
| 1642 |
+
0 2px 8px rgba(15, 23, 42, 0.3),
|
| 1643 |
+
inset 0 1px 0 rgba(255, 255, 255, 0.08);
|
| 1644 |
+
}
|
| 1645 |
+
|
| 1646 |
+
.region-selector:focus {
|
| 1647 |
+
border-color: var(--bloom-accent, #3b82f6);
|
| 1648 |
+
box-shadow:
|
| 1649 |
+
0 6px 20px rgba(2, 6, 23, 0.4),
|
| 1650 |
+
0 2px 8px rgba(15, 23, 42, 0.3),
|
| 1651 |
+
0 0 0 3px color-mix(in srgb, var(--bloom-accent, #3b82f6) 15%, transparent),
|
| 1652 |
+
inset 0 1px 0 rgba(255, 255, 255, 0.08);
|
| 1653 |
+
}
|
| 1654 |
+
|
| 1655 |
+
.region-chevron {
|
| 1656 |
+
transition: transform 200ms ease;
|
| 1657 |
+
display: inline-flex;
|
| 1658 |
+
align-items: center;
|
| 1659 |
+
justify-content: center;
|
| 1660 |
+
transform: translateY(-50%);
|
| 1661 |
+
}
|
| 1662 |
+
|
| 1663 |
+
.region-chevron.rotate-180 {
|
| 1664 |
+
transform: translateY(-50%) rotate(180deg);
|
| 1665 |
+
}
|
| 1666 |
+
|
| 1667 |
+
/* Tab buttons dynamic styling */
|
| 1668 |
+
button.border-blue-500 {
|
| 1669 |
+
border-color: rgb(96, 165, 250) !important;
|
| 1670 |
+
color: rgb(96, 165, 250);
|
| 1671 |
+
transition:
|
| 1672 |
+
border-color 0.2s ease,
|
| 1673 |
+
color 0.2s ease;
|
| 1674 |
+
}
|
| 1675 |
+
|
| 1676 |
+
/* Search button acrylic styling */
|
| 1677 |
+
.search-button {
|
| 1678 |
+
background: rgba(59, 130, 246, 0.85);
|
| 1679 |
+
border: 1px solid rgba(59, 130, 246, 0.4);
|
| 1680 |
+
backdrop-filter: blur(16px) saturate(140%);
|
| 1681 |
+
-webkit-backdrop-filter: blur(16px) saturate(140%);
|
| 1682 |
+
box-shadow:
|
| 1683 |
+
0 4px 12px rgba(59, 130, 246, 0.35),
|
| 1684 |
+
inset 0 1px 0 rgba(255, 255, 255, 0.1);
|
| 1685 |
+
transition:
|
| 1686 |
+
background 0.3s ease,
|
| 1687 |
+
border-color 0.3s ease,
|
| 1688 |
+
box-shadow 0.3s ease,
|
| 1689 |
+
opacity 0.2s ease;
|
| 1690 |
+
}
|
| 1691 |
+
|
| 1692 |
+
.search-button:hover:not(:disabled) {
|
| 1693 |
+
background: rgba(59, 130, 246, 0.95);
|
| 1694 |
+
box-shadow:
|
| 1695 |
+
0 6px 18px rgba(59, 130, 246, 0.45),
|
| 1696 |
+
inset 0 1px 0 rgba(255, 255, 255, 0.15);
|
| 1697 |
+
}
|
| 1698 |
+
|
| 1699 |
+
/* News container acrylic styling */
|
| 1700 |
+
.news-container {
|
| 1701 |
+
background: transparent;
|
| 1702 |
+
border-color: rgba(148, 163, 184, 0.2);
|
| 1703 |
+
backdrop-filter: blur(var(--perf-blur-medium, 28px)) saturate(var(--perf-saturate, 160%));
|
| 1704 |
+
-webkit-backdrop-filter: blur(var(--perf-blur-medium, 28px))
|
| 1705 |
+
saturate(var(--perf-saturate, 160%));
|
| 1706 |
+
box-shadow:
|
| 1707 |
+
0 8px 24px rgba(2, 6, 23, 0.35),
|
| 1708 |
+
inset 0 1px 0 rgba(255, 255, 255, 0.05);
|
| 1709 |
+
transition:
|
| 1710 |
+
border-color 1.2s cubic-bezier(0.4, 0, 0.2, 1),
|
| 1711 |
+
box-shadow 0.3s ease;
|
| 1712 |
+
}
|
| 1713 |
+
|
| 1714 |
+
/* News card acrylic styling */
|
| 1715 |
+
.news-card {
|
| 1716 |
+
background: transparent;
|
| 1717 |
+
border-color: rgba(148, 163, 184, 0.18);
|
| 1718 |
+
backdrop-filter: blur(var(--perf-blur-low, 24px)) saturate(var(--perf-saturate, 160%));
|
| 1719 |
+
-webkit-backdrop-filter: blur(var(--perf-blur-low, 24px)) saturate(var(--perf-saturate, 160%));
|
| 1720 |
+
box-shadow:
|
| 1721 |
+
0 4px 12px rgba(2, 6, 23, 0.3),
|
| 1722 |
+
inset 0 1px 0 rgba(255, 255, 255, 0.04);
|
| 1723 |
+
transition:
|
| 1724 |
+
border-color 1.2s cubic-bezier(0.4, 0, 0.2, 1),
|
| 1725 |
+
box-shadow 0.3s ease,
|
| 1726 |
+
transform 0.2s ease;
|
| 1727 |
+
}
|
| 1728 |
+
|
| 1729 |
+
.news-card:hover {
|
| 1730 |
+
border-color: rgba(148, 163, 184, 0.3);
|
| 1731 |
+
box-shadow:
|
| 1732 |
+
0 6px 18px rgba(2, 6, 23, 0.4),
|
| 1733 |
+
inset 0 1px 0 rgba(255, 255, 255, 0.06);
|
| 1734 |
+
}
|
| 1735 |
+
|
| 1736 |
+
/* Improved contrast for grey text */
|
| 1737 |
+
:global(.text-gray-400) {
|
| 1738 |
+
color: rgb(156, 163, 175) !important;
|
| 1739 |
+
}
|
| 1740 |
+
|
| 1741 |
+
:global(.text-gray-500) {
|
| 1742 |
+
color: rgb(115, 125, 140) !important;
|
| 1743 |
+
}
|
| 1744 |
+
|
| 1745 |
+
/* Better placeholder contrast */
|
| 1746 |
+
input::placeholder {
|
| 1747 |
+
color: rgb(156, 163, 175) !important;
|
| 1748 |
+
opacity: 1;
|
| 1749 |
+
}
|
| 1750 |
+
|
| 1751 |
+
/* Hide scrollbar for mobile tabs */
|
| 1752 |
+
.scrollbar-hide {
|
| 1753 |
+
-ms-overflow-style: none;
|
| 1754 |
+
scrollbar-width: none;
|
| 1755 |
+
}
|
| 1756 |
+
|
| 1757 |
+
.scrollbar-hide::-webkit-scrollbar {
|
| 1758 |
+
display: none;
|
| 1759 |
+
}
|
| 1760 |
+
</style>
|
src/lib/components/ShareButton.svelte
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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Copy, Check, Code } from 'lucide-svelte';
|
| 3 |
+
import { fade, scale } from 'svelte/transition';
|
| 4 |
+
import { onMount } from 'svelte';
|
| 5 |
+
import { page } from '$app/stores';
|
| 6 |
+
|
| 7 |
+
interface Props {
|
| 8 |
+
type: 'track' | 'album' | 'artist' | 'playlist';
|
| 9 |
+
id: string | number;
|
| 10 |
+
title?: string;
|
| 11 |
+
size?: number;
|
| 12 |
+
iconOnly?: boolean;
|
| 13 |
+
variant?: 'ghost' | 'primary' | 'secondary';
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
let {
|
| 17 |
+
type,
|
| 18 |
+
id,
|
| 19 |
+
title = 'Share',
|
| 20 |
+
size = 20,
|
| 21 |
+
iconOnly = false,
|
| 22 |
+
variant = 'ghost'
|
| 23 |
+
}: Props = $props();
|
| 24 |
+
|
| 25 |
+
let showMenu = $state(false);
|
| 26 |
+
let copied = $state(false);
|
| 27 |
+
let menuRef: HTMLDivElement | null = null;
|
| 28 |
+
let buttonRef: HTMLButtonElement | null = null;
|
| 29 |
+
|
| 30 |
+
function getLongLink() {
|
| 31 |
+
return `${$page.url.protocol}://${$page.url.host}/${type}/${id}`;
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
function getEmbedUrl() {
|
| 35 |
+
return `${$page.url.protocol}://${$page.url.host}/embed/${type}/${id}`;
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
function getShortLink() {
|
| 39 |
+
const prefixMap = {
|
| 40 |
+
track: 't',
|
| 41 |
+
album: 'al',
|
| 42 |
+
artist: 'ar',
|
| 43 |
+
playlist: 'p'
|
| 44 |
+
};
|
| 45 |
+
return `https://okiw.me/${prefixMap[type]}/${id}`;
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
function getEmbedCode() {
|
| 49 |
+
if (type === "track") return `<iframe src="${getEmbedUrl()}" width="100%" height="150" style="border:none; overflow:hidden; border-radius: 0.5em;" allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture"></iframe>`;
|
| 50 |
+
return `<iframe src="${getEmbedUrl()}" width="100%" height="450" style="border:none; overflow:hidden; border-radius: 0.5em;" allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture"></iframe>`;
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
async function copyToClipboard(text: string) {
|
| 54 |
+
try {
|
| 55 |
+
if (navigator.clipboard && navigator.clipboard.writeText) {
|
| 56 |
+
await navigator.clipboard.writeText(text);
|
| 57 |
+
} else {
|
| 58 |
+
// Fallback for non-secure contexts
|
| 59 |
+
const textArea = document.createElement('textarea');
|
| 60 |
+
textArea.value = text;
|
| 61 |
+
textArea.style.position = 'fixed';
|
| 62 |
+
textArea.style.left = '-9999px';
|
| 63 |
+
textArea.style.top = '0';
|
| 64 |
+
document.body.appendChild(textArea);
|
| 65 |
+
textArea.focus();
|
| 66 |
+
textArea.select();
|
| 67 |
+
try {
|
| 68 |
+
document.execCommand('copy');
|
| 69 |
+
} catch (err) {
|
| 70 |
+
console.error('Fallback: Oops, unable to copy', err);
|
| 71 |
+
throw err;
|
| 72 |
+
}
|
| 73 |
+
document.body.removeChild(textArea);
|
| 74 |
+
}
|
| 75 |
+
copied = true;
|
| 76 |
+
showMenu = false;
|
| 77 |
+
setTimeout(() => {
|
| 78 |
+
copied = false;
|
| 79 |
+
}, 2000);
|
| 80 |
+
} catch (err) {
|
| 81 |
+
console.error('Failed to copy:', err);
|
| 82 |
+
}
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
function handleClickOutside(event: MouseEvent) {
|
| 86 |
+
if (showMenu &&
|
| 87 |
+
menuRef &&
|
| 88 |
+
!menuRef.contains(event.target as Node) &&
|
| 89 |
+
buttonRef &&
|
| 90 |
+
!buttonRef.contains(event.target as Node)) {
|
| 91 |
+
showMenu = false;
|
| 92 |
+
}
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
onMount(() => {
|
| 96 |
+
document.addEventListener('click', handleClickOutside);
|
| 97 |
+
return () => {
|
| 98 |
+
document.removeEventListener('click', handleClickOutside);
|
| 99 |
+
};
|
| 100 |
+
});
|
| 101 |
+
|
| 102 |
+
const variantClasses = {
|
| 103 |
+
ghost: 'text-gray-400 hover:text-white hover:bg-white/10',
|
| 104 |
+
primary: 'bg-blue-600 text-white hover:bg-blue-700',
|
| 105 |
+
secondary: 'bg-gray-800 text-white hover:bg-gray-700'
|
| 106 |
+
};
|
| 107 |
+
</script>
|
| 108 |
+
|
| 109 |
+
<div class="relative inline-block">
|
| 110 |
+
<button
|
| 111 |
+
bind:this={buttonRef}
|
| 112 |
+
class="flex items-center gap-2 rounded-full transition-colors {variantClasses[variant]} {iconOnly ? 'p-2' : 'px-4 py-2'}"
|
| 113 |
+
onclick={(e) => {
|
| 114 |
+
e.stopPropagation();
|
| 115 |
+
showMenu = !showMenu;
|
| 116 |
+
}}
|
| 117 |
+
{title}
|
| 118 |
+
aria-label={title}
|
| 119 |
+
aria-haspopup="true"
|
| 120 |
+
aria-expanded={showMenu}
|
| 121 |
+
>
|
| 122 |
+
{#if copied && iconOnly}
|
| 123 |
+
<Check size={size} class="text-green-500" />
|
| 124 |
+
{:else}
|
| 125 |
+
<Share2 size={size} />
|
| 126 |
+
{/if}
|
| 127 |
+
{#if !iconOnly}
|
| 128 |
+
<span>{copied ? 'Copied!' : 'Share'}</span>
|
| 129 |
+
{/if}
|
| 130 |
+
</button>
|
| 131 |
+
|
| 132 |
+
{#if showMenu}
|
| 133 |
+
<div
|
| 134 |
+
bind:this={menuRef}
|
| 135 |
+
transition:scale={{ duration: 100, start: 0.95 }}
|
| 136 |
+
class="absolute right-0 top-full z-50 mt-2 w-48 origin-top-right rounded-lg border border-white/10 bg-gray-900 p-1 shadow-xl backdrop-blur-xl"
|
| 137 |
+
>
|
| 138 |
+
<button
|
| 139 |
+
class="flex w-full items-center gap-2 rounded px-3 py-2 text-sm text-gray-300 hover:bg-white/10 hover:text-white"
|
| 140 |
+
onclick={(e) => {
|
| 141 |
+
e.stopPropagation();
|
| 142 |
+
copyToClipboard(getLongLink());
|
| 143 |
+
}}
|
| 144 |
+
>
|
| 145 |
+
<Link size={16} />
|
| 146 |
+
Copy Link
|
| 147 |
+
</button>
|
| 148 |
+
<button
|
| 149 |
+
class="flex w-full items-center gap-2 rounded px-3 py-2 text-sm text-gray-300 hover:bg-white/10 hover:text-white"
|
| 150 |
+
onclick={(e) => {
|
| 151 |
+
e.stopPropagation();
|
| 152 |
+
copyToClipboard(getShortLink());
|
| 153 |
+
}}
|
| 154 |
+
>
|
| 155 |
+
<Copy size={16} />
|
| 156 |
+
Copy Short Link
|
| 157 |
+
</button>
|
| 158 |
+
<button
|
| 159 |
+
class="flex w-full items-center gap-2 rounded px-3 py-2 text-sm text-gray-300 hover:bg-white/10 hover:text-white"
|
| 160 |
+
onclick={(e) => {
|
| 161 |
+
e.stopPropagation();
|
| 162 |
+
copyToClipboard(getEmbedCode());
|
| 163 |
+
}}
|
| 164 |
+
>
|
| 165 |
+
<Code size={16} />
|
| 166 |
+
Copy Embed Code
|
| 167 |
+
</button>
|
| 168 |
+
</div>
|
| 169 |
+
{/if}
|
| 170 |
+
</div>
|
src/lib/components/TopTracksGrid.svelte
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<script lang="ts">
|
| 2 |
+
import type { Track } from '$lib/types';
|
| 3 |
+
import { losslessAPI, type TrackDownloadProgress } from '$lib/api';
|
| 4 |
+
import { getExtensionForQuality, buildTrackFilename } from '$lib/downloads';
|
| 5 |
+
import { playerStore } from '$lib/stores/player';
|
| 6 |
+
import { downloadUiStore } from '$lib/stores/downloadUi';
|
| 7 |
+
import { userPreferencesStore } from '$lib/stores/userPreferences';
|
| 8 |
+
import { formatArtists } from '$lib/utils';
|
| 9 |
+
import { Play, Pause, Download, ListPlus, Plus, Clock, X } from 'lucide-svelte';
|
| 10 |
+
|
| 11 |
+
interface Props {
|
| 12 |
+
tracks: Track[];
|
| 13 |
+
maxTracks?: number;
|
| 14 |
+
columns?: number;
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
function getColumnClass(columns: number): string {
|
| 18 |
+
if (columns >= 3) {
|
| 19 |
+
return 'grid-cols-1 sm:grid-cols-2 xl:grid-cols-3';
|
| 20 |
+
}
|
| 21 |
+
if (columns === 2) {
|
| 22 |
+
return 'grid-cols-1 sm:grid-cols-2';
|
| 23 |
+
}
|
| 24 |
+
return 'grid-cols-1';
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
let { tracks, maxTracks = 6, columns = 3 }: Props = $props();
|
| 28 |
+
|
| 29 |
+
const columnClass = $derived(getColumnClass(columns));
|
| 30 |
+
const displayedTracks = $derived(maxTracks ? tracks.slice(0, maxTracks) : tracks);
|
| 31 |
+
|
| 32 |
+
let downloadingIds = $state(new Set<number>());
|
| 33 |
+
let downloadTaskIds = $state(new Map<number, string>());
|
| 34 |
+
let cancelledIds = $state(new Set<number>());
|
| 35 |
+
const convertAacToMp3Preference = $derived($userPreferencesStore.convertAacToMp3);
|
| 36 |
+
const downloadCoverSeperatelyPreference = $derived(
|
| 37 |
+
$userPreferencesStore.downloadCoversSeperately
|
| 38 |
+
);
|
| 39 |
+
|
| 40 |
+
const IGNORED_TAGS = new Set(['HI_RES_LOSSLESS']);
|
| 41 |
+
|
| 42 |
+
function getDisplayTags(tags?: string[] | null): string[] {
|
| 43 |
+
if (!tags) return [];
|
| 44 |
+
return tags.filter((tag) => tag && !IGNORED_TAGS.has(tag));
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
function handlePlayTrack(track: Track, index: number) {
|
| 48 |
+
playerStore.setQueue(displayedTracks, index);
|
| 49 |
+
playerStore.play();
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
function handleAddToQueue(track: Track, event: MouseEvent) {
|
| 53 |
+
event.stopPropagation();
|
| 54 |
+
playerStore.enqueue(track);
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
function handlePlayNext(track: Track, event: MouseEvent) {
|
| 58 |
+
event.stopPropagation();
|
| 59 |
+
playerStore.enqueueNext(track);
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
function handleCardKeydown(event: KeyboardEvent, track: Track, index: number) {
|
| 63 |
+
if (event.key === 'Enter' || event.key === ' ') {
|
| 64 |
+
event.preventDefault();
|
| 65 |
+
handlePlayTrack(track, index);
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
function isCurrentTrack(track: Track): boolean {
|
| 70 |
+
return $playerStore.currentTrack?.id === track.id;
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
function isPlaying(track: Track): boolean {
|
| 74 |
+
return isCurrentTrack(track) && $playerStore.isPlaying;
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
function markCancelled(trackId: number) {
|
| 78 |
+
const next = new Set(cancelledIds);
|
| 79 |
+
next.add(trackId);
|
| 80 |
+
cancelledIds = next;
|
| 81 |
+
setTimeout(() => {
|
| 82 |
+
const updated = new Set(cancelledIds);
|
| 83 |
+
updated.delete(trackId);
|
| 84 |
+
cancelledIds = updated;
|
| 85 |
+
}, 1500);
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
function handleCancelDownload(trackId: number, event: MouseEvent) {
|
| 89 |
+
event.stopPropagation();
|
| 90 |
+
const taskId = downloadTaskIds.get(trackId);
|
| 91 |
+
if (taskId) {
|
| 92 |
+
downloadUiStore.cancelTrackDownload(taskId);
|
| 93 |
+
}
|
| 94 |
+
const next = new Set(downloadingIds);
|
| 95 |
+
next.delete(trackId);
|
| 96 |
+
downloadingIds = next;
|
| 97 |
+
const taskMap = new Map(downloadTaskIds);
|
| 98 |
+
taskMap.delete(trackId);
|
| 99 |
+
downloadTaskIds = taskMap;
|
| 100 |
+
markCancelled(trackId);
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
async function handleDownload(track: Track, event: MouseEvent) {
|
| 104 |
+
event.stopPropagation();
|
| 105 |
+
const next = new Set(downloadingIds);
|
| 106 |
+
next.add(track.id);
|
| 107 |
+
downloadingIds = next;
|
| 108 |
+
|
| 109 |
+
const quality = $playerStore.quality;
|
| 110 |
+
const filename = buildTrackFilename(
|
| 111 |
+
track.album,
|
| 112 |
+
track,
|
| 113 |
+
quality,
|
| 114 |
+
formatArtists(track.artists),
|
| 115 |
+
convertAacToMp3Preference
|
| 116 |
+
);
|
| 117 |
+
const { taskId, controller } = downloadUiStore.beginTrackDownload(track, filename, {
|
| 118 |
+
subtitle: track.album?.title ?? track.artist?.name
|
| 119 |
+
});
|
| 120 |
+
const taskMap = new Map(downloadTaskIds);
|
| 121 |
+
taskMap.set(track.id, taskId);
|
| 122 |
+
downloadTaskIds = taskMap;
|
| 123 |
+
downloadUiStore.skipFfmpegCountdown();
|
| 124 |
+
|
| 125 |
+
try {
|
| 126 |
+
await losslessAPI.downloadTrack(track.id, quality, filename, {
|
| 127 |
+
signal: controller.signal,
|
| 128 |
+
onProgress: (progress: TrackDownloadProgress) => {
|
| 129 |
+
if (progress.stage === 'downloading') {
|
| 130 |
+
downloadUiStore.updateTrackProgress(
|
| 131 |
+
taskId,
|
| 132 |
+
progress.receivedBytes,
|
| 133 |
+
progress.totalBytes
|
| 134 |
+
);
|
| 135 |
+
} else {
|
| 136 |
+
downloadUiStore.updateTrackStage(taskId, progress.progress);
|
| 137 |
+
}
|
| 138 |
+
},
|
| 139 |
+
onFfmpegCountdown: ({ totalBytes }) => {
|
| 140 |
+
if (typeof totalBytes === 'number') {
|
| 141 |
+
downloadUiStore.startFfmpegCountdown(totalBytes, { autoTriggered: false });
|
| 142 |
+
} else {
|
| 143 |
+
downloadUiStore.startFfmpegCountdown(0, { autoTriggered: false });
|
| 144 |
+
}
|
| 145 |
+
},
|
| 146 |
+
onFfmpegStart: () => downloadUiStore.startFfmpegLoading(),
|
| 147 |
+
onFfmpegProgress: (value) => downloadUiStore.updateFfmpegProgress(value),
|
| 148 |
+
onFfmpegComplete: () => downloadUiStore.completeFfmpeg(),
|
| 149 |
+
onFfmpegError: (error) => downloadUiStore.errorFfmpeg(error),
|
| 150 |
+
ffmpegAutoTriggered: false,
|
| 151 |
+
convertAacToMp3: convertAacToMp3Preference,
|
| 152 |
+
downloadCoverSeperately: downloadCoverSeperatelyPreference
|
| 153 |
+
});
|
| 154 |
+
downloadUiStore.completeTrackDownload(taskId);
|
| 155 |
+
} catch (error) {
|
| 156 |
+
if (error instanceof DOMException && error.name === 'AbortError') {
|
| 157 |
+
downloadUiStore.completeTrackDownload(taskId);
|
| 158 |
+
markCancelled(track.id);
|
| 159 |
+
} else {
|
| 160 |
+
console.error('Failed to download track:', error);
|
| 161 |
+
const fallbackMessage = 'Failed to download track. Please try again.';
|
| 162 |
+
const message = error instanceof Error && error.message ? error.message : fallbackMessage;
|
| 163 |
+
downloadUiStore.errorTrackDownload(taskId, message);
|
| 164 |
+
alert(message);
|
| 165 |
+
}
|
| 166 |
+
} finally {
|
| 167 |
+
const updated = new Set(downloadingIds);
|
| 168 |
+
updated.delete(track.id);
|
| 169 |
+
downloadingIds = updated;
|
| 170 |
+
const ids = new Map(downloadTaskIds);
|
| 171 |
+
ids.delete(track.id);
|
| 172 |
+
downloadTaskIds = ids;
|
| 173 |
+
}
|
| 174 |
+
}
|
| 175 |
+
</script>
|
| 176 |
+
|
| 177 |
+
<div class={`grid gap-4 ${columnClass}`}>
|
| 178 |
+
{#if displayedTracks.length === 0}
|
| 179 |
+
<div class="col-span-full py-12 text-center text-gray-400">
|
| 180 |
+
<p>No tracks available</p>
|
| 181 |
+
</div>
|
| 182 |
+
{:else}
|
| 183 |
+
{#each displayedTracks as track, index (track.id)}
|
| 184 |
+
<div
|
| 185 |
+
role="button"
|
| 186 |
+
tabindex="0"
|
| 187 |
+
onclick={() => handlePlayTrack(track, index)}
|
| 188 |
+
onkeydown={(event) => handleCardKeydown(event, track, index)}
|
| 189 |
+
class="group flex h-full cursor-pointer flex-col gap-4 rounded-xl border border-gray-800 bg-gray-900/50 p-4 transition-colors hover:border-blue-700 hover:bg-gray-900/70 focus:ring-2 focus:ring-blue-500 focus:outline-none"
|
| 190 |
+
>
|
| 191 |
+
<div class="flex items-start gap-4">
|
| 192 |
+
<button
|
| 193 |
+
onclick={(event) => {
|
| 194 |
+
event.stopPropagation();
|
| 195 |
+
handlePlayTrack(track, index);
|
| 196 |
+
}}
|
| 197 |
+
class="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full bg-gray-800 transition-transform hover:scale-110"
|
| 198 |
+
aria-label={isPlaying(track) ? 'Pause' : 'Play'}
|
| 199 |
+
>
|
| 200 |
+
{#if isPlaying(track)}
|
| 201 |
+
<Pause size={18} class="text-blue-500" />
|
| 202 |
+
{:else if isCurrentTrack(track)}
|
| 203 |
+
<Play size={18} class="text-blue-500" />
|
| 204 |
+
{:else}
|
| 205 |
+
<span class="text-sm font-semibold text-gray-300">{index + 1}</span>
|
| 206 |
+
{/if}
|
| 207 |
+
</button>
|
| 208 |
+
|
| 209 |
+
{#if track.album?.cover}
|
| 210 |
+
<img
|
| 211 |
+
src={losslessAPI.getCoverUrl(track.album.cover, '320')}
|
| 212 |
+
alt={track.title}
|
| 213 |
+
class="h-20 w-20 flex-shrink-0 rounded-lg object-cover shadow-lg"
|
| 214 |
+
/>
|
| 215 |
+
{/if}
|
| 216 |
+
|
| 217 |
+
<div class="min-w-0 flex-1">
|
| 218 |
+
<h3
|
| 219 |
+
class="truncate text-lg font-semibold {isCurrentTrack(track)
|
| 220 |
+
? 'text-blue-500'
|
| 221 |
+
: 'text-white group-hover:text-blue-400'}"
|
| 222 |
+
>
|
| 223 |
+
{track.title}
|
| 224 |
+
{#if track.explicit}
|
| 225 |
+
<span class="ml-1 text-xs text-gray-500">[E]</span>
|
| 226 |
+
{/if}
|
| 227 |
+
</h3>
|
| 228 |
+
<div class="mt-1 space-y-1 text-sm text-gray-400">
|
| 229 |
+
<p class="truncate">{formatArtists(track.artists)}</p>
|
| 230 |
+
{#if track.album}
|
| 231 |
+
<p class="truncate text-xs text-gray-500">{track.album.title}</p>
|
| 232 |
+
{/if}
|
| 233 |
+
</div>
|
| 234 |
+
{#if getDisplayTags(track.mediaMetadata?.tags).length > 0}
|
| 235 |
+
<p class="mt-2 text-xs text-gray-500">
|
| 236 |
+
{getDisplayTags(track.mediaMetadata?.tags).join(', ')}
|
| 237 |
+
</p>
|
| 238 |
+
{/if}
|
| 239 |
+
</div>
|
| 240 |
+
</div>
|
| 241 |
+
|
| 242 |
+
<div
|
| 243 |
+
class="mt-auto flex flex-wrap items-center justify-between gap-3 text-sm text-gray-400"
|
| 244 |
+
>
|
| 245 |
+
<div class="flex items-center gap-2">
|
| 246 |
+
<button
|
| 247 |
+
onclick={(event) => handlePlayNext(track, event)}
|
| 248 |
+
class="rounded-full p-2 transition-colors hover:bg-gray-800 hover:text-white"
|
| 249 |
+
title="Play next"
|
| 250 |
+
aria-label={`Play ${track.title} next`}
|
| 251 |
+
>
|
| 252 |
+
<ListPlus size={18} />
|
| 253 |
+
</button>
|
| 254 |
+
<button
|
| 255 |
+
onclick={(event) => handleAddToQueue(track, event)}
|
| 256 |
+
class="rounded-full p-2 transition-colors hover:bg-gray-800 hover:text-white"
|
| 257 |
+
title="Add to queue"
|
| 258 |
+
aria-label={`Add ${track.title} to queue`}
|
| 259 |
+
>
|
| 260 |
+
<Plus size={18} />
|
| 261 |
+
</button>
|
| 262 |
+
<button
|
| 263 |
+
onclick={(event) =>
|
| 264 |
+
downloadingIds.has(track.id)
|
| 265 |
+
? handleCancelDownload(track.id, event)
|
| 266 |
+
: handleDownload(track, event)}
|
| 267 |
+
class="rounded-full p-2 transition-colors hover:bg-gray-800 hover:text-white"
|
| 268 |
+
title={downloadingIds.has(track.id) ? 'Cancel download' : 'Download track'}
|
| 269 |
+
aria-label={downloadingIds.has(track.id) ? 'Cancel download' : 'Download track'}
|
| 270 |
+
aria-busy={downloadingIds.has(track.id)}
|
| 271 |
+
aria-pressed={downloadingIds.has(track.id)}
|
| 272 |
+
>
|
| 273 |
+
{#if downloadingIds.has(track.id)}
|
| 274 |
+
<span class="flex h-4 w-4 items-center justify-center">
|
| 275 |
+
{#if cancelledIds.has(track.id)}
|
| 276 |
+
<X size={14} />
|
| 277 |
+
{:else}
|
| 278 |
+
<span
|
| 279 |
+
class="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"
|
| 280 |
+
></span>
|
| 281 |
+
{/if}
|
| 282 |
+
</span>
|
| 283 |
+
{:else if cancelledIds.has(track.id)}
|
| 284 |
+
<X size={18} />
|
| 285 |
+
{:else}
|
| 286 |
+
<Download size={18} />
|
| 287 |
+
{/if}
|
| 288 |
+
</button>
|
| 289 |
+
</div>
|
| 290 |
+
<div class="flex items-center gap-1 text-xs text-gray-400">
|
| 291 |
+
<Clock size={14} />
|
| 292 |
+
<span>{losslessAPI.formatDuration(track.duration)}</span>
|
| 293 |
+
</div>
|
| 294 |
+
</div>
|
| 295 |
+
</div>
|
| 296 |
+
{/each}
|
| 297 |
+
{/if}
|
| 298 |
+
</div>
|
src/lib/components/TrackList.svelte
ADDED
|
@@ -0,0 +1,572 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<script lang="ts">
|
| 2 |
+
import type { Track } from '$lib/types';
|
| 3 |
+
import { losslessAPI, type TrackDownloadProgress } from '$lib/api';
|
| 4 |
+
import { getExtensionForQuality, buildTrackFilename } from '$lib/downloads';
|
| 5 |
+
import { playerStore } from '$lib/stores/player';
|
| 6 |
+
import { downloadUiStore } from '$lib/stores/downloadUi';
|
| 7 |
+
import { userPreferencesStore } from '$lib/stores/userPreferences';
|
| 8 |
+
import { formatArtists } from '$lib/utils';
|
| 9 |
+
import ShareButton from '$lib/components/ShareButton.svelte';
|
| 10 |
+
import { Play, Pause, Download, Clock, Plus, ListPlus, X } from 'lucide-svelte';
|
| 11 |
+
|
| 12 |
+
interface Props {
|
| 13 |
+
tracks: Track[];
|
| 14 |
+
showAlbum?: boolean;
|
| 15 |
+
showArtist?: boolean;
|
| 16 |
+
showCover?: boolean;
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
let { tracks, showAlbum = true, showArtist = true, showCover = true }: Props = $props();
|
| 20 |
+
let downloadingIds = $state(new Set<number>());
|
| 21 |
+
let downloadTaskIds = $state(new Map<number, string>());
|
| 22 |
+
let cancelledIds = $state(new Set<number>());
|
| 23 |
+
const IGNORED_TAGS = new Set(['HI_RES_LOSSLESS']);
|
| 24 |
+
const convertAacToMp3Preference = $derived($userPreferencesStore.convertAacToMp3);
|
| 25 |
+
const downloadCoverSeperatelyPreference = $derived($userPreferencesStore.downloadCoversSeperately);
|
| 26 |
+
|
| 27 |
+
function getDisplayTags(tags?: string[] | null): string[] {
|
| 28 |
+
if (!tags) return [];
|
| 29 |
+
return tags.filter((tag) => tag && !IGNORED_TAGS.has(tag));
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
function formatTrackNumber(track: Track): string {
|
| 33 |
+
const volumeNumber = Number(track.volumeNumber);
|
| 34 |
+
const trackNumber = Number(track.trackNumber);
|
| 35 |
+
|
| 36 |
+
// Check if this is a multi-volume album by checking:
|
| 37 |
+
// 1. numberOfVolumes > 1, or
|
| 38 |
+
// 2. volumeNumber is set and finite (indicating multi-volume structure)
|
| 39 |
+
const isMultiVolume = (track.album?.numberOfVolumes && track.album.numberOfVolumes > 1) ||
|
| 40 |
+
Number.isFinite(volumeNumber);
|
| 41 |
+
|
| 42 |
+
if (isMultiVolume) {
|
| 43 |
+
const volumePadded = Number.isFinite(volumeNumber) && volumeNumber > 0 ? volumeNumber.toString() : '1';
|
| 44 |
+
const trackPadded = Number.isFinite(trackNumber) && trackNumber > 0 ? trackNumber.toString() : '0';
|
| 45 |
+
return `${volumePadded}-${trackPadded}`;
|
| 46 |
+
} else {
|
| 47 |
+
const trackPadded = Number.isFinite(trackNumber) && trackNumber > 0 ? trackNumber.toString() : '0';
|
| 48 |
+
return trackPadded;
|
| 49 |
+
}
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
function handlePlayTrack(track: Track, index: number) {
|
| 53 |
+
playerStore.setQueue(tracks, index);
|
| 54 |
+
playerStore.play();
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
function handleAddToQueue(track: Track, event: MouseEvent) {
|
| 58 |
+
event.stopPropagation();
|
| 59 |
+
playerStore.enqueue(track);
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
function handlePlayNext(track: Track, event: MouseEvent) {
|
| 63 |
+
event.stopPropagation();
|
| 64 |
+
playerStore.enqueueNext(track);
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
function markCancelled(trackId: number) {
|
| 68 |
+
const next = new Set(cancelledIds);
|
| 69 |
+
next.add(trackId);
|
| 70 |
+
cancelledIds = next;
|
| 71 |
+
setTimeout(() => {
|
| 72 |
+
const updated = new Set(cancelledIds);
|
| 73 |
+
updated.delete(trackId);
|
| 74 |
+
cancelledIds = updated;
|
| 75 |
+
}, 1500);
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
function handleCancelDownload(trackId: number, event: MouseEvent) {
|
| 79 |
+
event.stopPropagation();
|
| 80 |
+
const taskId = downloadTaskIds.get(trackId);
|
| 81 |
+
if (taskId) {
|
| 82 |
+
downloadUiStore.cancelTrackDownload(taskId);
|
| 83 |
+
}
|
| 84 |
+
const next = new Set(downloadingIds);
|
| 85 |
+
next.delete(trackId);
|
| 86 |
+
downloadingIds = next;
|
| 87 |
+
const nextTasks = new Map(downloadTaskIds);
|
| 88 |
+
nextTasks.delete(trackId);
|
| 89 |
+
downloadTaskIds = nextTasks;
|
| 90 |
+
markCancelled(trackId);
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
async function handleDownload(track: Track, event: MouseEvent) {
|
| 94 |
+
event.stopPropagation();
|
| 95 |
+
const next = new Set(downloadingIds);
|
| 96 |
+
next.add(track.id);
|
| 97 |
+
downloadingIds = next;
|
| 98 |
+
|
| 99 |
+
const quality = $playerStore.quality;
|
| 100 |
+
const filename = buildTrackFilename(
|
| 101 |
+
track.album,
|
| 102 |
+
track,
|
| 103 |
+
quality,
|
| 104 |
+
formatArtists(track.artists),
|
| 105 |
+
convertAacToMp3Preference
|
| 106 |
+
);
|
| 107 |
+
const { taskId, controller } = downloadUiStore.beginTrackDownload(track, filename, {
|
| 108 |
+
subtitle: showAlbum ? (track.album?.title ?? track.artist?.name) : track.artist?.name
|
| 109 |
+
});
|
| 110 |
+
const taskMap = new Map(downloadTaskIds);
|
| 111 |
+
taskMap.set(track.id, taskId);
|
| 112 |
+
downloadTaskIds = taskMap;
|
| 113 |
+
downloadUiStore.skipFfmpegCountdown();
|
| 114 |
+
|
| 115 |
+
try {
|
| 116 |
+
await losslessAPI.downloadTrack(track.id, quality, filename, {
|
| 117 |
+
signal: controller.signal,
|
| 118 |
+
onProgress: (progress: TrackDownloadProgress) => {
|
| 119 |
+
if (progress.stage === 'downloading') {
|
| 120 |
+
downloadUiStore.updateTrackProgress(
|
| 121 |
+
taskId,
|
| 122 |
+
progress.receivedBytes,
|
| 123 |
+
progress.totalBytes
|
| 124 |
+
);
|
| 125 |
+
} else {
|
| 126 |
+
downloadUiStore.updateTrackStage(taskId, progress.progress);
|
| 127 |
+
}
|
| 128 |
+
},
|
| 129 |
+
onFfmpegCountdown: ({ totalBytes }) => {
|
| 130 |
+
if (typeof totalBytes === 'number') {
|
| 131 |
+
downloadUiStore.startFfmpegCountdown(totalBytes, { autoTriggered: false });
|
| 132 |
+
} else {
|
| 133 |
+
downloadUiStore.startFfmpegCountdown(0, { autoTriggered: false });
|
| 134 |
+
}
|
| 135 |
+
},
|
| 136 |
+
onFfmpegStart: () => downloadUiStore.startFfmpegLoading(),
|
| 137 |
+
onFfmpegProgress: (value) => downloadUiStore.updateFfmpegProgress(value),
|
| 138 |
+
onFfmpegComplete: () => downloadUiStore.completeFfmpeg(),
|
| 139 |
+
onFfmpegError: (error) => downloadUiStore.errorFfmpeg(error),
|
| 140 |
+
ffmpegAutoTriggered: false,
|
| 141 |
+
convertAacToMp3: convertAacToMp3Preference,
|
| 142 |
+
downloadCoverSeperately: downloadCoverSeperatelyPreference
|
| 143 |
+
});
|
| 144 |
+
downloadUiStore.completeTrackDownload(taskId);
|
| 145 |
+
} catch (error) {
|
| 146 |
+
if (error instanceof DOMException && error.name === 'AbortError') {
|
| 147 |
+
downloadUiStore.completeTrackDownload(taskId);
|
| 148 |
+
markCancelled(track.id);
|
| 149 |
+
} else {
|
| 150 |
+
console.error('Failed to download track:', error);
|
| 151 |
+
const fallbackMessage = 'Failed to download track. Please try again.';
|
| 152 |
+
const message = error instanceof Error && error.message ? error.message : fallbackMessage;
|
| 153 |
+
downloadUiStore.errorTrackDownload(taskId, message);
|
| 154 |
+
alert(message);
|
| 155 |
+
}
|
| 156 |
+
} finally {
|
| 157 |
+
const updated = new Set(downloadingIds);
|
| 158 |
+
updated.delete(track.id);
|
| 159 |
+
downloadingIds = updated;
|
| 160 |
+
const ids = new Map(downloadTaskIds);
|
| 161 |
+
ids.delete(track.id);
|
| 162 |
+
downloadTaskIds = ids;
|
| 163 |
+
}
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
function isCurrentTrack(track: Track): boolean {
|
| 167 |
+
return $playerStore.currentTrack?.id === track.id;
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
function isPlaying(track: Track): boolean {
|
| 171 |
+
return isCurrentTrack(track) && $playerStore.isPlaying;
|
| 172 |
+
}
|
| 173 |
+
</script>
|
| 174 |
+
|
| 175 |
+
<div class="track-list">
|
| 176 |
+
{#if tracks.length === 0}
|
| 177 |
+
<div class="track-list__empty">
|
| 178 |
+
<p>No tracks available</p>
|
| 179 |
+
</div>
|
| 180 |
+
{:else}
|
| 181 |
+
<div class="track-list__items">
|
| 182 |
+
{#each tracks as track, index}
|
| 183 |
+
<div
|
| 184 |
+
class="track-row {isCurrentTrack(track) ? 'track-row--active' : ''}"
|
| 185 |
+
>
|
| 186 |
+
<!-- Track Number / Play Button -->
|
| 187 |
+
<button
|
| 188 |
+
onclick={() => handlePlayTrack(track, index)}
|
| 189 |
+
class="track-row__play-btn touch-target"
|
| 190 |
+
aria-label={isPlaying(track) ? 'Pause' : 'Play'}
|
| 191 |
+
>
|
| 192 |
+
{#if isPlaying(track)}
|
| 193 |
+
<Pause size={18} class="track-row__icon--active" />
|
| 194 |
+
{:else if isCurrentTrack(track)}
|
| 195 |
+
<Play size={18} class="track-row__icon--active" />
|
| 196 |
+
{:else}
|
| 197 |
+
<span class="track-row__number">{formatTrackNumber(track)}</span>
|
| 198 |
+
<Play size={18} class="track-row__icon--hover" />
|
| 199 |
+
{/if}
|
| 200 |
+
</button>
|
| 201 |
+
|
| 202 |
+
<!-- Cover -->
|
| 203 |
+
{#if showCover && track.album.cover}
|
| 204 |
+
<img
|
| 205 |
+
src={losslessAPI.getCoverUrl(track.album.cover, '320')}
|
| 206 |
+
alt={track.title}
|
| 207 |
+
class="track-row__cover"
|
| 208 |
+
loading="lazy"
|
| 209 |
+
/>
|
| 210 |
+
{/if}
|
| 211 |
+
|
| 212 |
+
<!-- Track Info -->
|
| 213 |
+
<div class="track-row__info">
|
| 214 |
+
<button
|
| 215 |
+
onclick={() => handlePlayTrack(track, index)}
|
| 216 |
+
class="track-row__title {isCurrentTrack(track) ? 'track-row__title--active' : ''}"
|
| 217 |
+
>
|
| 218 |
+
{track.title}
|
| 219 |
+
{#if track.explicit}
|
| 220 |
+
<svg
|
| 221 |
+
class="track-row__explicit"
|
| 222 |
+
xmlns="http://www.w3.org/2000/svg"
|
| 223 |
+
fill="currentColor"
|
| 224 |
+
height="24"
|
| 225 |
+
viewBox="0 0 24 24"
|
| 226 |
+
width="24"
|
| 227 |
+
focusable="false"
|
| 228 |
+
aria-hidden="true"
|
| 229 |
+
><path
|
| 230 |
+
d="M20 2H4a2 2 0 00-2 2v16a2 2 0 002 2h16a2 2 0 002-2V4a2 2 0 00-2-2ZM8 6h8a1 1 0 110 2H9v3h5a1 1 0 010 2H9v3h7a1 1 0 010 2H8a1 1 0 01-1-1V7a1 1 0 011-1Z"
|
| 231 |
+
></path></svg
|
| 232 |
+
>
|
| 233 |
+
{/if}
|
| 234 |
+
</button>
|
| 235 |
+
<div class="track-row__meta">
|
| 236 |
+
{#if showArtist}
|
| 237 |
+
<span class="track-row__artist">{formatArtists(track.artists)}</span>
|
| 238 |
+
{/if}
|
| 239 |
+
{#if showAlbum && showArtist}
|
| 240 |
+
<span class="track-row__sep">•</span>
|
| 241 |
+
{/if}
|
| 242 |
+
{#if showAlbum}
|
| 243 |
+
<span class="track-row__album">{track.album.title}</span>
|
| 244 |
+
{/if}
|
| 245 |
+
</div>
|
| 246 |
+
{#if getDisplayTags(track.mediaMetadata?.tags).length > 0}
|
| 247 |
+
<div class="track-row__tags">
|
| 248 |
+
• {getDisplayTags(track.mediaMetadata?.tags).join(', ')}
|
| 249 |
+
</div>
|
| 250 |
+
{/if}
|
| 251 |
+
</div>
|
| 252 |
+
|
| 253 |
+
<!-- Actions -->
|
| 254 |
+
<div class="track-row__actions">
|
| 255 |
+
<button
|
| 256 |
+
onclick={(event) => handlePlayNext(track, event)}
|
| 257 |
+
class="track-row__action-btn touch-target"
|
| 258 |
+
title="Play next"
|
| 259 |
+
aria-label={`Play ${track.title} next`}
|
| 260 |
+
>
|
| 261 |
+
<ListPlus size={20} />
|
| 262 |
+
</button>
|
| 263 |
+
<button
|
| 264 |
+
onclick={(event) => handleAddToQueue(track, event)}
|
| 265 |
+
class="track-row__action-btn touch-target"
|
| 266 |
+
title="Add to queue"
|
| 267 |
+
aria-label={`Add ${track.title} to queue`}
|
| 268 |
+
>
|
| 269 |
+
<Plus size={20} />
|
| 270 |
+
</button>
|
| 271 |
+
|
| 272 |
+
<div class="track-row__action-btn">
|
| 273 |
+
<ShareButton type="track" id={track.id} iconOnly size={20} title="Share track" />
|
| 274 |
+
</div>
|
| 275 |
+
|
| 276 |
+
<button
|
| 277 |
+
onclick={(e) =>
|
| 278 |
+
downloadingIds.has(track.id)
|
| 279 |
+
? handleCancelDownload(track.id, e)
|
| 280 |
+
: handleDownload(track, e)}
|
| 281 |
+
class="track-row__action-btn touch-target"
|
| 282 |
+
aria-label={downloadingIds.has(track.id) ? 'Cancel download' : 'Download track'}
|
| 283 |
+
title={downloadingIds.has(track.id) ? 'Cancel download' : 'Download track'}
|
| 284 |
+
aria-busy={downloadingIds.has(track.id)}
|
| 285 |
+
>
|
| 286 |
+
{#if downloadingIds.has(track.id)}
|
| 287 |
+
<span class="track-row__spinner">
|
| 288 |
+
{#if cancelledIds.has(track.id)}
|
| 289 |
+
<X size={16} />
|
| 290 |
+
{:else}
|
| 291 |
+
<span class="track-row__loading"></span>
|
| 292 |
+
{/if}
|
| 293 |
+
</span>
|
| 294 |
+
{:else if cancelledIds.has(track.id)}
|
| 295 |
+
<X size={20} />
|
| 296 |
+
{:else}
|
| 297 |
+
<Download size={20} />
|
| 298 |
+
{/if}
|
| 299 |
+
</button>
|
| 300 |
+
|
| 301 |
+
<!-- Duration -->
|
| 302 |
+
<div class="track-row__duration">
|
| 303 |
+
<Clock size={14} />
|
| 304 |
+
{losslessAPI.formatDuration(track.duration)}
|
| 305 |
+
</div>
|
| 306 |
+
</div>
|
| 307 |
+
</div>
|
| 308 |
+
{/each}
|
| 309 |
+
</div>
|
| 310 |
+
{/if}
|
| 311 |
+
</div>
|
| 312 |
+
|
| 313 |
+
<style>
|
| 314 |
+
.track-list {
|
| 315 |
+
width: 100%;
|
| 316 |
+
contain: content;
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
.track-list__empty {
|
| 320 |
+
padding: var(--space-12, 3rem) 0;
|
| 321 |
+
text-align: center;
|
| 322 |
+
color: rgba(148, 163, 184, 0.8);
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
+
.track-list__items {
|
| 326 |
+
display: flex;
|
| 327 |
+
flex-direction: column;
|
| 328 |
+
gap: var(--space-1, 0.25rem);
|
| 329 |
+
}
|
| 330 |
+
|
| 331 |
+
/* Track Row - Performance optimized (no backdrop-filter) */
|
| 332 |
+
.track-row {
|
| 333 |
+
display: flex;
|
| 334 |
+
align-items: center;
|
| 335 |
+
gap: var(--space-3, 0.75rem);
|
| 336 |
+
padding: var(--space-3, 0.75rem);
|
| 337 |
+
border-radius: var(--radius-lg, 0.75rem);
|
| 338 |
+
background: rgba(15, 23, 42, 0.4);
|
| 339 |
+
border: 1px solid rgba(148, 163, 184, 0.08);
|
| 340 |
+
transition:
|
| 341 |
+
background var(--transition-fast, 150ms ease),
|
| 342 |
+
border-color var(--transition-fast, 150ms ease);
|
| 343 |
+
contain: layout style;
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
.track-row:hover {
|
| 347 |
+
background: rgba(30, 41, 59, 0.6);
|
| 348 |
+
border-color: rgba(148, 163, 184, 0.15);
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
.track-row--active {
|
| 352 |
+
background: rgba(59, 130, 246, 0.12);
|
| 353 |
+
border-color: rgba(59, 130, 246, 0.25);
|
| 354 |
+
border-left: 3px solid rgba(59, 130, 246, 0.8);
|
| 355 |
+
}
|
| 356 |
+
|
| 357 |
+
/* Play Button */
|
| 358 |
+
.track-row__play-btn {
|
| 359 |
+
display: flex;
|
| 360 |
+
align-items: center;
|
| 361 |
+
justify-content: center;
|
| 362 |
+
width: 2.5rem;
|
| 363 |
+
height: 2.5rem;
|
| 364 |
+
flex-shrink: 0;
|
| 365 |
+
background: none;
|
| 366 |
+
border: none;
|
| 367 |
+
color: inherit;
|
| 368 |
+
border-radius: var(--radius-md, 0.5rem);
|
| 369 |
+
transition: background var(--transition-fast, 150ms ease);
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
.track-row__play-btn:hover {
|
| 373 |
+
background: rgba(148, 163, 184, 0.1);
|
| 374 |
+
}
|
| 375 |
+
|
| 376 |
+
.track-row__number {
|
| 377 |
+
font-size: 0.875rem;
|
| 378 |
+
color: rgba(148, 163, 184, 0.7);
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
.track-row__icon--hover {
|
| 382 |
+
display: none;
|
| 383 |
+
color: #f8fafc;
|
| 384 |
+
}
|
| 385 |
+
|
| 386 |
+
.track-row__icon--active {
|
| 387 |
+
color: #3b82f6;
|
| 388 |
+
}
|
| 389 |
+
|
| 390 |
+
.track-row:hover .track-row__number {
|
| 391 |
+
display: none;
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
+
.track-row:hover .track-row__icon--hover {
|
| 395 |
+
display: block;
|
| 396 |
+
}
|
| 397 |
+
|
| 398 |
+
/* Cover */
|
| 399 |
+
.track-row__cover {
|
| 400 |
+
width: 3.5rem;
|
| 401 |
+
height: 3.5rem;
|
| 402 |
+
flex-shrink: 0;
|
| 403 |
+
border-radius: var(--radius-md, 0.5rem);
|
| 404 |
+
object-fit: cover;
|
| 405 |
+
}
|
| 406 |
+
|
| 407 |
+
/* Track Info */
|
| 408 |
+
.track-row__info {
|
| 409 |
+
flex: 1;
|
| 410 |
+
min-width: 0;
|
| 411 |
+
display: flex;
|
| 412 |
+
flex-direction: column;
|
| 413 |
+
gap: var(--space-1, 0.25rem);
|
| 414 |
+
overflow: hidden;
|
| 415 |
+
}
|
| 416 |
+
|
| 417 |
+
.track-row__title {
|
| 418 |
+
display: block;
|
| 419 |
+
font-weight: 500;
|
| 420 |
+
font-size: 0.9375rem;
|
| 421 |
+
color: #f1f5f9;
|
| 422 |
+
background: none;
|
| 423 |
+
border: none;
|
| 424 |
+
text-align: left;
|
| 425 |
+
width: 100%;
|
| 426 |
+
padding: 0;
|
| 427 |
+
white-space: nowrap;
|
| 428 |
+
overflow: hidden;
|
| 429 |
+
text-overflow: ellipsis;
|
| 430 |
+
transition: color var(--transition-fast, 150ms ease);
|
| 431 |
+
cursor: pointer;
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
.track-row:hover .track-row__title {
|
| 435 |
+
color: #60a5fa;
|
| 436 |
+
}
|
| 437 |
+
|
| 438 |
+
.track-row__title--active {
|
| 439 |
+
color: #3b82f6;
|
| 440 |
+
}
|
| 441 |
+
|
| 442 |
+
.track-row__explicit {
|
| 443 |
+
width: 1rem;
|
| 444 |
+
height: 1rem;
|
| 445 |
+
flex-shrink: 0;
|
| 446 |
+
opacity: 0.6;
|
| 447 |
+
}
|
| 448 |
+
|
| 449 |
+
.track-row__meta {
|
| 450 |
+
display: flex;
|
| 451 |
+
align-items: center;
|
| 452 |
+
gap: var(--space-2, 0.5rem);
|
| 453 |
+
font-size: 0.8125rem;
|
| 454 |
+
color: rgba(148, 163, 184, 0.8);
|
| 455 |
+
overflow: hidden;
|
| 456 |
+
}
|
| 457 |
+
|
| 458 |
+
.track-row__artist,
|
| 459 |
+
.track-row__album {
|
| 460 |
+
white-space: nowrap;
|
| 461 |
+
overflow: hidden;
|
| 462 |
+
text-overflow: ellipsis;
|
| 463 |
+
max-width: 45%;
|
| 464 |
+
}
|
| 465 |
+
|
| 466 |
+
.track-row__sep {
|
| 467 |
+
flex-shrink: 0;
|
| 468 |
+
}
|
| 469 |
+
|
| 470 |
+
.track-row__tags {
|
| 471 |
+
font-size: 0.75rem;
|
| 472 |
+
color: rgba(100, 116, 139, 0.8);
|
| 473 |
+
}
|
| 474 |
+
|
| 475 |
+
/* Actions */
|
| 476 |
+
.track-row__actions {
|
| 477 |
+
display: flex;
|
| 478 |
+
align-items: center;
|
| 479 |
+
gap: var(--space-1, 0.25rem);
|
| 480 |
+
flex-shrink: 0;
|
| 481 |
+
}
|
| 482 |
+
|
| 483 |
+
.track-row__action-btn {
|
| 484 |
+
display: flex;
|
| 485 |
+
align-items: center;
|
| 486 |
+
justify-content: center;
|
| 487 |
+
width: 2.5rem;
|
| 488 |
+
height: 2.5rem;
|
| 489 |
+
border-radius: var(--radius-md, 0.5rem);
|
| 490 |
+
background: none;
|
| 491 |
+
border: none;
|
| 492 |
+
color: rgba(148, 163, 184, 0.7);
|
| 493 |
+
transition:
|
| 494 |
+
color var(--transition-fast, 150ms ease),
|
| 495 |
+
background var(--transition-fast, 150ms ease);
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
.track-row__action-btn:hover {
|
| 499 |
+
color: #f8fafc;
|
| 500 |
+
background: rgba(148, 163, 184, 0.1);
|
| 501 |
+
}
|
| 502 |
+
|
| 503 |
+
.track-row__spinner {
|
| 504 |
+
display: flex;
|
| 505 |
+
align-items: center;
|
| 506 |
+
justify-content: center;
|
| 507 |
+
width: 1.25rem;
|
| 508 |
+
height: 1.25rem;
|
| 509 |
+
}
|
| 510 |
+
|
| 511 |
+
.track-row__loading {
|
| 512 |
+
width: 1rem;
|
| 513 |
+
height: 1rem;
|
| 514 |
+
border: 2px solid currentColor;
|
| 515 |
+
border-top-color: transparent;
|
| 516 |
+
border-radius: 50%;
|
| 517 |
+
animation: spin 0.8s linear infinite;
|
| 518 |
+
}
|
| 519 |
+
|
| 520 |
+
@keyframes spin {
|
| 521 |
+
to { transform: rotate(360deg); }
|
| 522 |
+
}
|
| 523 |
+
|
| 524 |
+
.track-row__duration {
|
| 525 |
+
display: flex;
|
| 526 |
+
align-items: center;
|
| 527 |
+
gap: var(--space-1, 0.25rem);
|
| 528 |
+
width: 4rem;
|
| 529 |
+
justify-content: flex-end;
|
| 530 |
+
font-size: 0.8125rem;
|
| 531 |
+
color: rgba(148, 163, 184, 0.7);
|
| 532 |
+
}
|
| 533 |
+
|
| 534 |
+
/* Mobile optimizations */
|
| 535 |
+
@media (max-width: 640px) {
|
| 536 |
+
.track-row {
|
| 537 |
+
padding: var(--space-2, 0.5rem) var(--space-3, 0.75rem);
|
| 538 |
+
}
|
| 539 |
+
|
| 540 |
+
.track-row__cover {
|
| 541 |
+
width: 2.75rem;
|
| 542 |
+
height: 2.75rem;
|
| 543 |
+
}
|
| 544 |
+
|
| 545 |
+
.track-row__title {
|
| 546 |
+
font-size: 0.875rem;
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
.track-row__meta {
|
| 550 |
+
font-size: 0.75rem;
|
| 551 |
+
}
|
| 552 |
+
|
| 553 |
+
/* Hide less important actions on mobile */
|
| 554 |
+
.track-row__action-btn:nth-child(1),
|
| 555 |
+
.track-row__action-btn:nth-child(2) {
|
| 556 |
+
display: none;
|
| 557 |
+
}
|
| 558 |
+
|
| 559 |
+
.track-row__duration {
|
| 560 |
+
width: auto;
|
| 561 |
+
font-size: 0.75rem;
|
| 562 |
+
}
|
| 563 |
+
}
|
| 564 |
+
|
| 565 |
+
/* Touch device active state */
|
| 566 |
+
@media (pointer: coarse) {
|
| 567 |
+
.track-row:active {
|
| 568 |
+
background: rgba(59, 130, 246, 0.15);
|
| 569 |
+
}
|
| 570 |
+
}
|
| 571 |
+
</style>
|
| 572 |
+
|
src/lib/config.ts
ADDED
|
@@ -0,0 +1,578 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { APP_VERSION } from '$lib/version';
|
| 2 |
+
|
| 3 |
+
// CORS Proxy Configuration
|
| 4 |
+
// If you're experiencing CORS issues with the HIFI API, you can set up a proxy
|
| 5 |
+
|
| 6 |
+
type RegionPreference = 'auto' | 'us' | 'eu';
|
| 7 |
+
|
| 8 |
+
export interface ApiClusterTarget {
|
| 9 |
+
name: string;
|
| 10 |
+
baseUrl: string;
|
| 11 |
+
weight: number;
|
| 12 |
+
requiresProxy: boolean;
|
| 13 |
+
category: 'auto-only';
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
const V2_API_TARGETS = [
|
| 17 |
+
{
|
| 18 |
+
name: 'veltrix',
|
| 19 |
+
baseUrl: 'https://veltrixcode-loddless.hf.space',
|
| 20 |
+
weight: 100,
|
| 21 |
+
requiresProxy: false,
|
| 22 |
+
category: 'auto-only'
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
name: 'squid-api',
|
| 26 |
+
baseUrl: 'https://triton.squid.wtf',
|
| 27 |
+
weight: 15,
|
| 28 |
+
requiresProxy: false,
|
| 29 |
+
category: 'auto-only'
|
| 30 |
+
},
|
| 31 |
+
{
|
| 32 |
+
name: 'spotisaver-1',
|
| 33 |
+
baseUrl: 'https://hifi-one.spotisaver.net',
|
| 34 |
+
weight: 15,
|
| 35 |
+
requiresProxy: false,
|
| 36 |
+
category: 'auto-only'
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
name: 'spotisaver-2',
|
| 40 |
+
baseUrl: 'https://hifi-two.spotisaver.net',
|
| 41 |
+
weight: 15,
|
| 42 |
+
requiresProxy: false,
|
| 43 |
+
category: 'auto-only'
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
name: 'kinoplus',
|
| 47 |
+
baseUrl: 'https://tidal.kinoplus.online',
|
| 48 |
+
weight: 15,
|
| 49 |
+
requiresProxy: false,
|
| 50 |
+
category: 'auto-only'
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
name: 'hund',
|
| 54 |
+
baseUrl: 'https://hund.qqdl.site',
|
| 55 |
+
weight: 15,
|
| 56 |
+
requiresProxy: false,
|
| 57 |
+
category: 'auto-only'
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
name: 'katze',
|
| 61 |
+
baseUrl: 'https://katze.qqdl.site',
|
| 62 |
+
weight: 15,
|
| 63 |
+
requiresProxy: false,
|
| 64 |
+
category: 'auto-only'
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
name: 'maus',
|
| 68 |
+
baseUrl: 'https://maus.qqdl.site',
|
| 69 |
+
weight: 15,
|
| 70 |
+
requiresProxy: false,
|
| 71 |
+
category: 'auto-only'
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
name: 'vogel',
|
| 75 |
+
baseUrl: 'https://vogel.qqdl.site',
|
| 76 |
+
weight: 15,
|
| 77 |
+
requiresProxy: false,
|
| 78 |
+
category: 'auto-only'
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
name: 'wolf',
|
| 82 |
+
baseUrl: 'https://wolf.qqdl.site',
|
| 83 |
+
weight: 15,
|
| 84 |
+
requiresProxy: false,
|
| 85 |
+
category: 'auto-only'
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
name: 'monochrome',
|
| 89 |
+
baseUrl: 'https://arran.monochrome.tf',
|
| 90 |
+
weight: 15,
|
| 91 |
+
requiresProxy: false,
|
| 92 |
+
category: 'auto-only'
|
| 93 |
+
}
|
| 94 |
+
] satisfies ApiClusterTarget[];
|
| 95 |
+
|
| 96 |
+
const ALL_API_TARGETS = [...V2_API_TARGETS] satisfies ApiClusterTarget[];
|
| 97 |
+
const US_API_TARGETS = [] satisfies ApiClusterTarget[];
|
| 98 |
+
const TARGET_COLLECTIONS: Record<RegionPreference, ApiClusterTarget[]> = {
|
| 99 |
+
auto: [...ALL_API_TARGETS],
|
| 100 |
+
eu: [],
|
| 101 |
+
us: [...US_API_TARGETS]
|
| 102 |
+
};
|
| 103 |
+
|
| 104 |
+
const TARGETS = TARGET_COLLECTIONS.auto;
|
| 105 |
+
|
| 106 |
+
export const API_CONFIG = {
|
| 107 |
+
// Cluster of target endpoints for load distribution and redundancy
|
| 108 |
+
targets: TARGETS,
|
| 109 |
+
baseUrl: TARGETS[0]?.baseUrl ?? 'https://tidal.401658.xyz',
|
| 110 |
+
// Proxy configuration for endpoints that need it
|
| 111 |
+
useProxy: true,
|
| 112 |
+
proxyUrl: '/api/proxy'
|
| 113 |
+
};
|
| 114 |
+
|
| 115 |
+
type WeightedTarget = ApiClusterTarget & { cumulativeWeight: number };
|
| 116 |
+
|
| 117 |
+
let v1WeightedTargets: WeightedTarget[] | null = null;
|
| 118 |
+
let v2WeightedTargets: WeightedTarget[] | null = null;
|
| 119 |
+
|
| 120 |
+
function buildWeightedTargets(targets: ApiClusterTarget[]): WeightedTarget[] {
|
| 121 |
+
const validTargets = targets.filter((target) => {
|
| 122 |
+
if (!target?.baseUrl || typeof target.baseUrl !== 'string') {
|
| 123 |
+
return false;
|
| 124 |
+
}
|
| 125 |
+
if (target.weight <= 0) {
|
| 126 |
+
return false;
|
| 127 |
+
}
|
| 128 |
+
try {
|
| 129 |
+
new URL(target.baseUrl);
|
| 130 |
+
return true;
|
| 131 |
+
} catch (error) {
|
| 132 |
+
console.error(`Invalid API target URL for ${target.name}:`, error);
|
| 133 |
+
return false;
|
| 134 |
+
}
|
| 135 |
+
});
|
| 136 |
+
|
| 137 |
+
if (validTargets.length === 0) {
|
| 138 |
+
throw new Error('No valid API targets configured');
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
let cumulative = 0;
|
| 142 |
+
const collected: WeightedTarget[] = [];
|
| 143 |
+
for (const target of validTargets) {
|
| 144 |
+
cumulative += target.weight;
|
| 145 |
+
collected.push({ ...target, cumulativeWeight: cumulative });
|
| 146 |
+
}
|
| 147 |
+
return collected;
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
function ensureWeightedTargets(apiVersion: 'v1' | 'v2' = 'v2'): WeightedTarget[] {
|
| 151 |
+
if (apiVersion === 'v2') {
|
| 152 |
+
if (!v2WeightedTargets) {
|
| 153 |
+
v2WeightedTargets = buildWeightedTargets(V2_API_TARGETS);
|
| 154 |
+
}
|
| 155 |
+
return v2WeightedTargets;
|
| 156 |
+
} else {
|
| 157 |
+
if (!v1WeightedTargets) {
|
| 158 |
+
// v1 includes ALL_API_TARGETS (v1) + V2_API_TARGETS (fallback with low weight)
|
| 159 |
+
const v2Fallback = V2_API_TARGETS.map((t) => ({ ...t, weight: 1 }));
|
| 160 |
+
v1WeightedTargets = buildWeightedTargets([...ALL_API_TARGETS, ...v2Fallback]);
|
| 161 |
+
}
|
| 162 |
+
return v1WeightedTargets;
|
| 163 |
+
}
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
export function selectApiTarget(apiVersion: 'v1' | 'v2' = 'v2'): ApiClusterTarget {
|
| 167 |
+
const targets = ensureWeightedTargets(apiVersion);
|
| 168 |
+
return selectFromWeightedTargets(targets);
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
export function getPrimaryTarget(apiVersion: 'v1' | 'v2' = 'v2'): ApiClusterTarget {
|
| 172 |
+
return ensureWeightedTargets(apiVersion)[0];
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
function selectFromWeightedTargets(weighted: WeightedTarget[]): ApiClusterTarget {
|
| 176 |
+
if (weighted.length === 0) {
|
| 177 |
+
throw new Error('No weighted targets available for selection');
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
const totalWeight = weighted[weighted.length - 1]?.cumulativeWeight ?? 0;
|
| 181 |
+
if (totalWeight <= 0) {
|
| 182 |
+
return weighted[0];
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
const random = Math.random() * totalWeight;
|
| 186 |
+
for (const target of weighted) {
|
| 187 |
+
if (random < target.cumulativeWeight) {
|
| 188 |
+
return target;
|
| 189 |
+
}
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
return weighted[0];
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
export function getTargetsForRegion(region: RegionPreference = 'auto'): ApiClusterTarget[] {
|
| 196 |
+
const targets = TARGET_COLLECTIONS[region];
|
| 197 |
+
return Array.isArray(targets) ? targets : [];
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
export function selectApiTargetForRegion(region: RegionPreference): ApiClusterTarget {
|
| 201 |
+
if (region === 'auto') {
|
| 202 |
+
return selectApiTarget();
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
const targets = getTargetsForRegion(region);
|
| 206 |
+
if (targets.length === 0) {
|
| 207 |
+
return selectApiTarget();
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
const weighted = buildWeightedTargets(targets);
|
| 211 |
+
return selectFromWeightedTargets(weighted);
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
export function hasRegionTargets(region: RegionPreference): boolean {
|
| 215 |
+
if (region === 'auto') {
|
| 216 |
+
return TARGET_COLLECTIONS.auto.length > 0;
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
return getTargetsForRegion(region).length > 0;
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
function parseTargetBase(target: ApiClusterTarget): URL | null {
|
| 223 |
+
try {
|
| 224 |
+
return new URL(target.baseUrl);
|
| 225 |
+
} catch (error) {
|
| 226 |
+
console.error(`Invalid API target base URL for ${target.name}:`, error);
|
| 227 |
+
return null;
|
| 228 |
+
}
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
function getBaseApiUrl(target?: ApiClusterTarget): URL | null {
|
| 232 |
+
const chosen = target ?? getPrimaryTarget();
|
| 233 |
+
return parseTargetBase(chosen);
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
function stripTrailingSlash(path: string): string {
|
| 237 |
+
if (path === '/') return path;
|
| 238 |
+
return path.replace(/\/+$/, '') || '/';
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
function combinePaths(basePath: string, relativePath: string): string {
|
| 242 |
+
const trimmedBase = stripTrailingSlash(basePath || '/');
|
| 243 |
+
const normalizedRelative = relativePath.startsWith('/') ? relativePath : `/${relativePath}`;
|
| 244 |
+
if (trimmedBase === '/' || trimmedBase === '') {
|
| 245 |
+
return normalizedRelative;
|
| 246 |
+
}
|
| 247 |
+
if (normalizedRelative === '/') {
|
| 248 |
+
return `${trimmedBase}/`;
|
| 249 |
+
}
|
| 250 |
+
return `${trimmedBase}${normalizedRelative}`;
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
function getRelativePath(url: URL, targetBase: URL): string {
|
| 254 |
+
const basePath = stripTrailingSlash(targetBase.pathname || '/');
|
| 255 |
+
const currentPath = url.pathname || '/';
|
| 256 |
+
if (basePath === '/' || basePath === '') {
|
| 257 |
+
return currentPath.startsWith('/') ? currentPath : `/${currentPath}`;
|
| 258 |
+
}
|
| 259 |
+
if (!currentPath.startsWith(basePath)) {
|
| 260 |
+
return currentPath;
|
| 261 |
+
}
|
| 262 |
+
const relative = currentPath.slice(basePath.length);
|
| 263 |
+
if (!relative) {
|
| 264 |
+
return '/';
|
| 265 |
+
}
|
| 266 |
+
return relative.startsWith('/') ? relative : `/${relative}`;
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
function matchesTarget(url: URL, target: ApiClusterTarget): boolean {
|
| 270 |
+
const base = parseTargetBase(target);
|
| 271 |
+
if (!base) {
|
| 272 |
+
return false;
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
if (url.origin !== base.origin) {
|
| 276 |
+
return false;
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
const basePath = stripTrailingSlash(base.pathname || '/');
|
| 280 |
+
if (basePath === '/' || basePath === '') {
|
| 281 |
+
return true;
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
const targetPath = stripTrailingSlash(url.pathname || '/');
|
| 285 |
+
return targetPath === basePath || targetPath.startsWith(`${basePath}/`);
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
function findTargetForUrl(url: URL): ApiClusterTarget | null {
|
| 289 |
+
for (const target of API_CONFIG.targets) {
|
| 290 |
+
if (matchesTarget(url, target)) {
|
| 291 |
+
return target;
|
| 292 |
+
}
|
| 293 |
+
}
|
| 294 |
+
return null;
|
| 295 |
+
}
|
| 296 |
+
|
| 297 |
+
export function isProxyTarget(url: URL): boolean {
|
| 298 |
+
const target = findTargetForUrl(url);
|
| 299 |
+
return target?.requiresProxy === true;
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
function shouldPreferPrimaryTarget(url: URL): boolean {
|
| 303 |
+
const path = url.pathname.toLowerCase();
|
| 304 |
+
|
| 305 |
+
// Prefer the proxied primary target for endpoints that routinely require the legacy domain
|
| 306 |
+
if (path.includes('/album/') || path.includes('/artist/') || path.includes('/playlist/')) {
|
| 307 |
+
return true;
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
if (path.includes('/search/')) {
|
| 311 |
+
const params = url.searchParams;
|
| 312 |
+
if (params.has('a') || params.has('al') || params.has('p')) {
|
| 313 |
+
return true;
|
| 314 |
+
}
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
return false;
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
function resolveUrl(url: string): URL | null {
|
| 321 |
+
try {
|
| 322 |
+
return new URL(url);
|
| 323 |
+
} catch {
|
| 324 |
+
const baseApiUrl = getBaseApiUrl();
|
| 325 |
+
if (!baseApiUrl) {
|
| 326 |
+
return null;
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
try {
|
| 330 |
+
return new URL(url, baseApiUrl);
|
| 331 |
+
} catch {
|
| 332 |
+
return null;
|
| 333 |
+
}
|
| 334 |
+
}
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
/**
|
| 338 |
+
* Create a proxied URL if needed
|
| 339 |
+
*/
|
| 340 |
+
export function getProxiedUrl(url: string): string {
|
| 341 |
+
if (!API_CONFIG.useProxy || !API_CONFIG.proxyUrl) {
|
| 342 |
+
return url;
|
| 343 |
+
}
|
| 344 |
+
|
| 345 |
+
const targetUrl = resolveUrl(url);
|
| 346 |
+
if (!targetUrl) {
|
| 347 |
+
return url;
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
if (!isProxyTarget(targetUrl)) {
|
| 351 |
+
return url;
|
| 352 |
+
}
|
| 353 |
+
|
| 354 |
+
return `${API_CONFIG.proxyUrl}?url=${encodeURIComponent(targetUrl.toString())}`;
|
| 355 |
+
}
|
| 356 |
+
|
| 357 |
+
function isLikelyProxyErrorEntry(entry: unknown): boolean {
|
| 358 |
+
if (!entry || typeof entry !== 'object') {
|
| 359 |
+
return false;
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
const record = entry as Record<string, unknown>;
|
| 363 |
+
const status = typeof record.status === 'number' ? record.status : undefined;
|
| 364 |
+
const subStatus = typeof record.subStatus === 'number' ? record.subStatus : undefined;
|
| 365 |
+
const userMessage = typeof record.userMessage === 'string' ? record.userMessage : undefined;
|
| 366 |
+
const detail = typeof record.detail === 'string' ? record.detail : undefined;
|
| 367 |
+
|
| 368 |
+
if (typeof status === 'number' && status >= 400) {
|
| 369 |
+
return true;
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
if (typeof subStatus === 'number' && subStatus >= 400) {
|
| 373 |
+
return true;
|
| 374 |
+
}
|
| 375 |
+
|
| 376 |
+
const tokenPattern = /(token|invalid|unauthorized)/i;
|
| 377 |
+
if (userMessage && tokenPattern.test(userMessage)) {
|
| 378 |
+
return true;
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
if (detail && tokenPattern.test(detail)) {
|
| 382 |
+
return true;
|
| 383 |
+
}
|
| 384 |
+
|
| 385 |
+
return false;
|
| 386 |
+
}
|
| 387 |
+
|
| 388 |
+
function isLikelyProxyErrorPayload(payload: unknown): boolean {
|
| 389 |
+
if (Array.isArray(payload)) {
|
| 390 |
+
return payload.some((entry) => isLikelyProxyErrorEntry(entry));
|
| 391 |
+
}
|
| 392 |
+
|
| 393 |
+
if (payload && typeof payload === 'object') {
|
| 394 |
+
return isLikelyProxyErrorEntry(payload);
|
| 395 |
+
}
|
| 396 |
+
|
| 397 |
+
return false;
|
| 398 |
+
}
|
| 399 |
+
|
| 400 |
+
async function isUnexpectedProxyResponse(response: Response): Promise<boolean> {
|
| 401 |
+
if (!response.ok) {
|
| 402 |
+
return false;
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
const contentType = response.headers.get('content-type');
|
| 406 |
+
if (!contentType || !contentType.toLowerCase().includes('application/json')) {
|
| 407 |
+
return false;
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
try {
|
| 411 |
+
const payload = await response.clone().json();
|
| 412 |
+
return isLikelyProxyErrorPayload(payload);
|
| 413 |
+
} catch {
|
| 414 |
+
return false;
|
| 415 |
+
}
|
| 416 |
+
}
|
| 417 |
+
|
| 418 |
+
function isV2Target(target: ApiClusterTarget): boolean {
|
| 419 |
+
return V2_API_TARGETS.some((t) => t.name === target.name);
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
/**
|
| 423 |
+
* Fetch with CORS handling
|
| 424 |
+
*/
|
| 425 |
+
export async function fetchWithCORS(
|
| 426 |
+
url: string,
|
| 427 |
+
options?: RequestInit & {
|
| 428 |
+
apiVersion?: 'v1' | 'v2';
|
| 429 |
+
preferredQuality?: string;
|
| 430 |
+
validateResponse?: (res: Response) => Promise<boolean>;
|
| 431 |
+
}
|
| 432 |
+
): Promise<Response> {
|
| 433 |
+
const resolvedUrl = resolveUrl(url);
|
| 434 |
+
if (!resolvedUrl) {
|
| 435 |
+
throw new Error(`Unable to resolve URL: ${url}`);
|
| 436 |
+
}
|
| 437 |
+
|
| 438 |
+
const originTarget = findTargetForUrl(resolvedUrl);
|
| 439 |
+
if (!originTarget) {
|
| 440 |
+
return fetch(getProxiedUrl(resolvedUrl.toString()), {
|
| 441 |
+
...options
|
| 442 |
+
});
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
+
const apiVersion = options?.apiVersion ?? 'v2';
|
| 446 |
+
const weightedTargets = ensureWeightedTargets(apiVersion);
|
| 447 |
+
const attemptOrder: ApiClusterTarget[] = [];
|
| 448 |
+
if (shouldPreferPrimaryTarget(resolvedUrl)) {
|
| 449 |
+
const primary = getPrimaryTarget(apiVersion);
|
| 450 |
+
if (!attemptOrder.some((candidate) => candidate.name === primary.name)) {
|
| 451 |
+
attemptOrder.push(primary);
|
| 452 |
+
}
|
| 453 |
+
}
|
| 454 |
+
|
| 455 |
+
const selected = selectApiTarget(apiVersion);
|
| 456 |
+
if (!attemptOrder.some((candidate) => candidate.name === selected.name)) {
|
| 457 |
+
attemptOrder.push(selected);
|
| 458 |
+
}
|
| 459 |
+
|
| 460 |
+
for (const target of weightedTargets) {
|
| 461 |
+
if (!attemptOrder.some((candidate) => candidate.name === target.name)) {
|
| 462 |
+
attemptOrder.push(target);
|
| 463 |
+
}
|
| 464 |
+
}
|
| 465 |
+
|
| 466 |
+
let uniqueTargets = attemptOrder.filter(
|
| 467 |
+
(target, index, array) => array.findIndex((entry) => entry.name === target.name) === index
|
| 468 |
+
);
|
| 469 |
+
|
| 470 |
+
if (uniqueTargets.length === 0) {
|
| 471 |
+
uniqueTargets = [getPrimaryTarget(apiVersion)];
|
| 472 |
+
}
|
| 473 |
+
|
| 474 |
+
const originBase = parseTargetBase(originTarget);
|
| 475 |
+
if (!originBase) {
|
| 476 |
+
throw new Error('Invalid origin target configuration.');
|
| 477 |
+
}
|
| 478 |
+
|
| 479 |
+
const totalAttempts = Math.max(3, uniqueTargets.length);
|
| 480 |
+
let lastError: unknown = null;
|
| 481 |
+
let lastResponse: Response | null = null;
|
| 482 |
+
let lastUnexpectedResponse: Response | null = null;
|
| 483 |
+
let lastValidButRejectedResponse: Response | null = null;
|
| 484 |
+
|
| 485 |
+
for (let attempt = 0; attempt < totalAttempts; attempt += 1) {
|
| 486 |
+
const target = uniqueTargets[attempt % uniqueTargets.length];
|
| 487 |
+
const targetBase = parseTargetBase(target);
|
| 488 |
+
if (!targetBase) {
|
| 489 |
+
continue;
|
| 490 |
+
}
|
| 491 |
+
|
| 492 |
+
const relativePath = getRelativePath(resolvedUrl, originBase);
|
| 493 |
+
const rewrittenPath = combinePaths(targetBase.pathname || '/', relativePath);
|
| 494 |
+
const rewrittenUrl = new URL(
|
| 495 |
+
rewrittenPath + resolvedUrl.search + resolvedUrl.hash,
|
| 496 |
+
targetBase.origin
|
| 497 |
+
);
|
| 498 |
+
|
| 499 |
+
// If we are falling back to a v2 target and have a preferred quality (e.g. HI_RES_LOSSLESS),
|
| 500 |
+
// upgrade the quality parameter in the URL.
|
| 501 |
+
if (
|
| 502 |
+
isV2Target(target) &&
|
| 503 |
+
options?.preferredQuality &&
|
| 504 |
+
rewrittenUrl.searchParams.has('quality')
|
| 505 |
+
) {
|
| 506 |
+
rewrittenUrl.searchParams.set('quality', options.preferredQuality);
|
| 507 |
+
}
|
| 508 |
+
|
| 509 |
+
const finalUrl = getProxiedUrl(rewrittenUrl.toString());
|
| 510 |
+
|
| 511 |
+
const headers = new Headers(options?.headers);
|
| 512 |
+
const isCustom =
|
| 513 |
+
[...V2_API_TARGETS].some((t) => t.name === target.name) &&
|
| 514 |
+
!target.baseUrl.includes('tidal.com') &&
|
| 515 |
+
!target.baseUrl.includes('api.tidal.com') &&
|
| 516 |
+
!target.baseUrl.includes('monochrome.tf');
|
| 517 |
+
|
| 518 |
+
if (isCustom) {
|
| 519 |
+
headers.set('X-Client', `BiniLossless/${APP_VERSION}`);
|
| 520 |
+
}
|
| 521 |
+
|
| 522 |
+
try {
|
| 523 |
+
const response = await fetch(finalUrl, {
|
| 524 |
+
...options,
|
| 525 |
+
headers
|
| 526 |
+
});
|
| 527 |
+
if (response.ok) {
|
| 528 |
+
const unexpected = await isUnexpectedProxyResponse(response);
|
| 529 |
+
if (!unexpected) {
|
| 530 |
+
if (options?.validateResponse) {
|
| 531 |
+
const isValid = await options.validateResponse(response.clone());
|
| 532 |
+
if (!isValid) {
|
| 533 |
+
lastValidButRejectedResponse = response;
|
| 534 |
+
continue;
|
| 535 |
+
}
|
| 536 |
+
}
|
| 537 |
+
return response;
|
| 538 |
+
}
|
| 539 |
+
lastUnexpectedResponse = response;
|
| 540 |
+
continue;
|
| 541 |
+
}
|
| 542 |
+
|
| 543 |
+
lastResponse = response;
|
| 544 |
+
} catch (error) {
|
| 545 |
+
lastError = error;
|
| 546 |
+
if (error instanceof TypeError && error.message.includes('CORS')) {
|
| 547 |
+
continue;
|
| 548 |
+
}
|
| 549 |
+
}
|
| 550 |
+
}
|
| 551 |
+
|
| 552 |
+
if (lastValidButRejectedResponse) {
|
| 553 |
+
return lastValidButRejectedResponse;
|
| 554 |
+
}
|
| 555 |
+
|
| 556 |
+
if (lastUnexpectedResponse) {
|
| 557 |
+
return lastUnexpectedResponse;
|
| 558 |
+
}
|
| 559 |
+
|
| 560 |
+
if (lastResponse) {
|
| 561 |
+
return lastResponse;
|
| 562 |
+
}
|
| 563 |
+
|
| 564 |
+
if (lastError) {
|
| 565 |
+
if (
|
| 566 |
+
lastError instanceof TypeError &&
|
| 567 |
+
typeof lastError.message === 'string' &&
|
| 568 |
+
lastError.message.includes('CORS')
|
| 569 |
+
) {
|
| 570 |
+
throw new Error(
|
| 571 |
+
'CORS error detected. Please configure a proxy in src/lib/config.ts or enable CORS on your backend.'
|
| 572 |
+
);
|
| 573 |
+
}
|
| 574 |
+
throw lastError;
|
| 575 |
+
}
|
| 576 |
+
|
| 577 |
+
throw new Error('All API targets failed without response.');
|
| 578 |
+
}
|
src/lib/downloads.ts
ADDED
|
@@ -0,0 +1,538 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { losslessAPI } from '$lib/api';
|
| 2 |
+
import type { Album, Track, AudioQuality } from '$lib/types';
|
| 3 |
+
import type { DownloadMode } from '$lib/stores/downloadPreferences';
|
| 4 |
+
import { formatArtists } from '$lib/utils';
|
| 5 |
+
import JSZip from 'jszip';
|
| 6 |
+
|
| 7 |
+
function detectImageFormat(data: Uint8Array): { extension: string; mimeType: string } | null {
|
| 8 |
+
if (!data || data.length < 4) {
|
| 9 |
+
return null;
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
// Check for JPEG magic bytes (FF D8 FF)
|
| 13 |
+
if (data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) {
|
| 14 |
+
return { extension: 'jpg', mimeType: 'image/jpeg' };
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
// Check for PNG magic bytes (89 50 4E 47)
|
| 18 |
+
if (data[0] === 0x89 && data[1] === 0x50 && data[2] === 0x4e && data[3] === 0x47) {
|
| 19 |
+
return { extension: 'png', mimeType: 'image/png' };
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
// Check for WebP magic bytes (52 49 46 46 ... 57 45 42 50)
|
| 23 |
+
if (data.length >= 12 &&
|
| 24 |
+
data[0] === 0x52 && data[1] === 0x49 && data[2] === 0x46 && data[3] === 0x46 &&
|
| 25 |
+
data[8] === 0x57 && data[9] === 0x45 && data[10] === 0x42 && data[11] === 0x50) {
|
| 26 |
+
return { extension: 'webp', mimeType: 'image/webp' };
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
return null;
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
export function sanitizeForFilename(value: string | null | undefined): string {
|
| 33 |
+
if (!value) return 'Unknown';
|
| 34 |
+
return value
|
| 35 |
+
.replace(/[\\/:*?"<>|]/g, '_')
|
| 36 |
+
.replace(/\s+/g, ' ')
|
| 37 |
+
.trim();
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
export function getExtensionForQuality(quality: AudioQuality, convertAacToMp3 = false): string {
|
| 41 |
+
switch (quality) {
|
| 42 |
+
case 'LOW':
|
| 43 |
+
case 'HIGH':
|
| 44 |
+
return convertAacToMp3 ? 'mp3' : 'm4a';
|
| 45 |
+
default:
|
| 46 |
+
return 'flac';
|
| 47 |
+
}
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
export function buildTrackFilename(
|
| 51 |
+
album: Album,
|
| 52 |
+
track: Track,
|
| 53 |
+
quality: AudioQuality,
|
| 54 |
+
artistName?: string,
|
| 55 |
+
convertAacToMp3 = false
|
| 56 |
+
): string {
|
| 57 |
+
const extension = getExtensionForQuality(quality, convertAacToMp3);
|
| 58 |
+
const volumeNumber = Number(track.volumeNumber);
|
| 59 |
+
const trackNumber = Number(track.trackNumber);
|
| 60 |
+
|
| 61 |
+
// Check if this is a multi-volume album by checking:
|
| 62 |
+
// 1. numberOfVolumes > 1, or
|
| 63 |
+
// 2. volumeNumber is set and finite (indicating multi-volume structure)
|
| 64 |
+
const isMultiVolume = (album.numberOfVolumes && album.numberOfVolumes > 1) ||
|
| 65 |
+
Number.isFinite(volumeNumber);
|
| 66 |
+
|
| 67 |
+
let trackPart: string;
|
| 68 |
+
if (isMultiVolume) {
|
| 69 |
+
const volumePadded = Number.isFinite(volumeNumber) && volumeNumber > 0 ? `${volumeNumber}`.padStart(2, '0') : '01';
|
| 70 |
+
const trackPadded = Number.isFinite(trackNumber) && trackNumber > 0 ? `${trackNumber}`.padStart(2, '0') : '00';
|
| 71 |
+
trackPart = `${volumePadded}-${trackPadded}`;
|
| 72 |
+
} else {
|
| 73 |
+
const trackPadded = Number.isFinite(trackNumber) && trackNumber > 0 ? `${trackNumber}`.padStart(2, '0') : '00';
|
| 74 |
+
trackPart = trackPadded;
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
let title = track.title;
|
| 78 |
+
if (track.version) {
|
| 79 |
+
title = `${title} (${track.version})`;
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
const parts = [
|
| 83 |
+
sanitizeForFilename(artistName ?? formatArtists(track.artists)),
|
| 84 |
+
sanitizeForFilename(album.title ?? 'Unknown Album'),
|
| 85 |
+
`${trackPart} ${sanitizeForFilename(title)}`
|
| 86 |
+
];
|
| 87 |
+
return `${parts.join(' - ')}.${extension}`;
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
export interface AlbumDownloadCallbacks {
|
| 91 |
+
onTotalResolved?(total: number): void;
|
| 92 |
+
onTrackDownloaded?(completed: number, total: number, track: Track): void;
|
| 93 |
+
onTrackFailed?(track: Track, error: Error, attempt: number): void;
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
function escapeCsvValue(value: string): string {
|
| 97 |
+
const normalized = value.replace(/\r?\n|\r/g, ' ');
|
| 98 |
+
if (/[",]/.test(normalized)) {
|
| 99 |
+
return `"${normalized.replace(/"/g, '""')}"`;
|
| 100 |
+
}
|
| 101 |
+
return normalized;
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
export async function buildTrackLinksCsv(tracks: Track[], quality: AudioQuality): Promise<string> {
|
| 105 |
+
const header = ['Index', 'Title', 'Artist', 'Album', 'Duration', 'FLAC URL'];
|
| 106 |
+
const rows: string[][] = [];
|
| 107 |
+
|
| 108 |
+
for (const [index, track] of tracks.entries()) {
|
| 109 |
+
const streamUrl = await losslessAPI.getTrackStreamUrl(track.id, quality);
|
| 110 |
+
rows.push([
|
| 111 |
+
`${index + 1}`,
|
| 112 |
+
track.title ?? '',
|
| 113 |
+
formatArtists(track.artists),
|
| 114 |
+
track.album?.title ?? '',
|
| 115 |
+
losslessAPI.formatDuration(track.duration ?? 0),
|
| 116 |
+
streamUrl
|
| 117 |
+
]);
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
return [header, ...rows]
|
| 121 |
+
.map((row) => row.map((value) => escapeCsvValue(String(value ?? ''))).join(','))
|
| 122 |
+
.join('\n');
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
interface DownloadTrackResult {
|
| 126 |
+
success: boolean;
|
| 127 |
+
blob?: Blob;
|
| 128 |
+
error?: Error;
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
async function downloadTrackWithRetry(
|
| 132 |
+
trackId: number,
|
| 133 |
+
quality: AudioQuality,
|
| 134 |
+
filename: string,
|
| 135 |
+
track: Track,
|
| 136 |
+
callbacks?: AlbumDownloadCallbacks,
|
| 137 |
+
options?: { convertAacToMp3?: boolean; downloadCoverSeperately?: boolean }
|
| 138 |
+
): Promise<DownloadTrackResult> {
|
| 139 |
+
const maxAttempts = 3;
|
| 140 |
+
const baseDelay = 1000; // 1 second
|
| 141 |
+
const trackTitle = track.title ?? 'Unknown Track';
|
| 142 |
+
const artistName = formatArtists(track.artists);
|
| 143 |
+
|
| 144 |
+
console.log(`[Track Download] Starting download: "${trackTitle}" by ${artistName} (ID: ${trackId}, Quality: ${quality})`);
|
| 145 |
+
|
| 146 |
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
| 147 |
+
try {
|
| 148 |
+
if (attempt > 1) {
|
| 149 |
+
console.log(`[Track Download] Retry attempt ${attempt}/${maxAttempts} for "${trackTitle}"`);
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
const { blob } = await losslessAPI.fetchTrackBlob(trackId, quality, filename, {
|
| 153 |
+
ffmpegAutoTriggered: false,
|
| 154 |
+
convertAacToMp3: options?.convertAacToMp3
|
| 155 |
+
});
|
| 156 |
+
|
| 157 |
+
console.log(`[Track Download] ✓ Success: "${trackTitle}" (${(blob.size / 1024 / 1024).toFixed(2)} MB)${attempt > 1 ? ` - succeeded on attempt ${attempt}` : ''}`);
|
| 158 |
+
return { success: true, blob };
|
| 159 |
+
} catch (error) {
|
| 160 |
+
const errorObj = error instanceof Error ? error : new Error(String(error));
|
| 161 |
+
console.warn(
|
| 162 |
+
`[Track Download] ✗ Attempt ${attempt}/${maxAttempts} failed for "${trackTitle}": ${errorObj.message}`
|
| 163 |
+
);
|
| 164 |
+
|
| 165 |
+
callbacks?.onTrackFailed?.(track, errorObj, attempt);
|
| 166 |
+
|
| 167 |
+
if (attempt < maxAttempts) {
|
| 168 |
+
// Exponential backoff: 1s, 2s, 4s
|
| 169 |
+
const delay = baseDelay * Math.pow(2, attempt - 1);
|
| 170 |
+
console.log(`[Track Download] Waiting ${delay}ms before retry...`);
|
| 171 |
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
| 172 |
+
} else {
|
| 173 |
+
console.error(
|
| 174 |
+
`[Track Download] ✗✗✗ All ${maxAttempts} attempts failed for "${trackTitle}" - giving up`
|
| 175 |
+
);
|
| 176 |
+
return { success: false, error: errorObj };
|
| 177 |
+
}
|
| 178 |
+
}
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
return { success: false, error: new Error('Download failed after all retry attempts') };
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
function triggerFileDownload(blob: Blob, filename: string): void {
|
| 185 |
+
const url = URL.createObjectURL(blob);
|
| 186 |
+
const link = document.createElement('a');
|
| 187 |
+
link.href = url;
|
| 188 |
+
link.download = filename;
|
| 189 |
+
document.body.appendChild(link);
|
| 190 |
+
link.click();
|
| 191 |
+
document.body.removeChild(link);
|
| 192 |
+
URL.revokeObjectURL(url);
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
export async function downloadAlbum(
|
| 196 |
+
album: Album,
|
| 197 |
+
quality: AudioQuality,
|
| 198 |
+
callbacks?: AlbumDownloadCallbacks,
|
| 199 |
+
preferredArtistName?: string,
|
| 200 |
+
options?: { mode?: DownloadMode; convertAacToMp3?: boolean; downloadCoverSeperately?: boolean }
|
| 201 |
+
): Promise<void> {
|
| 202 |
+
const { album: fetchedAlbum, tracks } = await losslessAPI.getAlbum(album.id);
|
| 203 |
+
const canonicalAlbum = fetchedAlbum ?? album;
|
| 204 |
+
const total = tracks.length;
|
| 205 |
+
callbacks?.onTotalResolved?.(total);
|
| 206 |
+
const mode = options?.mode ?? 'individual';
|
| 207 |
+
const shouldZip = mode === 'zip' && total > 1;
|
| 208 |
+
const useCsv = mode === 'csv';
|
| 209 |
+
const convertAacToMp3 = options?.convertAacToMp3 ?? false;
|
| 210 |
+
const downloadCoverSeperately = options?.downloadCoverSeperately ?? false;
|
| 211 |
+
const artistName = sanitizeForFilename(
|
| 212 |
+
preferredArtistName ?? canonicalAlbum.artist?.name ?? 'Unknown Artist'
|
| 213 |
+
);
|
| 214 |
+
const albumTitle = sanitizeForFilename(canonicalAlbum.title ?? 'Unknown Album');
|
| 215 |
+
|
| 216 |
+
console.log(`[Album Download] ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`);
|
| 217 |
+
console.log(`[Album Download] Starting: "${albumTitle}" by ${artistName}`);
|
| 218 |
+
console.log(`[Album Download] Tracks: ${total} | Quality: ${quality} | Mode: ${mode}`);
|
| 219 |
+
console.log(`[Album Download] ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`);
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
if (useCsv) {
|
| 223 |
+
let completed = 0;
|
| 224 |
+
for (const track of tracks) {
|
| 225 |
+
completed += 1;
|
| 226 |
+
callbacks?.onTrackDownloaded?.(completed, total, track);
|
| 227 |
+
}
|
| 228 |
+
const csvContent = await buildTrackLinksCsv(tracks, quality);
|
| 229 |
+
const csvBlob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
|
| 230 |
+
triggerFileDownload(csvBlob, `${artistName} - ${albumTitle}.csv`);
|
| 231 |
+
return;
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
if (shouldZip) {
|
| 235 |
+
const zip = new JSZip();
|
| 236 |
+
let completed = 0;
|
| 237 |
+
const failedTracks: Array<{ track: Track; error: Error }> = [];
|
| 238 |
+
|
| 239 |
+
// Download cover separately for ZIP if requested
|
| 240 |
+
if (downloadCoverSeperately && canonicalAlbum.cover) {
|
| 241 |
+
try {
|
| 242 |
+
console.log('[ZIP Cover Download] Fetching cover for album...');
|
| 243 |
+
|
| 244 |
+
// Try multiple sizes as fallback
|
| 245 |
+
const coverSizes: Array<'1280' | '640' | '320'> = ['1280', '640', '320'];
|
| 246 |
+
let coverDownloadSuccess = false;
|
| 247 |
+
|
| 248 |
+
for (const size of coverSizes) {
|
| 249 |
+
if (coverDownloadSuccess) break;
|
| 250 |
+
|
| 251 |
+
const coverUrl = losslessAPI.getCoverUrl(canonicalAlbum.cover, size);
|
| 252 |
+
console.log(`[ZIP Cover Download] Attempting size ${size}:`, coverUrl);
|
| 253 |
+
|
| 254 |
+
// Try two fetch strategies: with headers, then without
|
| 255 |
+
const fetchStrategies = [
|
| 256 |
+
{
|
| 257 |
+
name: 'with-headers',
|
| 258 |
+
options: {
|
| 259 |
+
method: 'GET' as const,
|
| 260 |
+
headers: {
|
| 261 |
+
'Accept': 'image/jpeg,image/jpg,image/png,image/*',
|
| 262 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
| 263 |
+
},
|
| 264 |
+
signal: AbortSignal.timeout(10000)
|
| 265 |
+
}
|
| 266 |
+
},
|
| 267 |
+
{
|
| 268 |
+
name: 'simple',
|
| 269 |
+
options: {
|
| 270 |
+
method: 'GET' as const,
|
| 271 |
+
signal: AbortSignal.timeout(10000)
|
| 272 |
+
}
|
| 273 |
+
}
|
| 274 |
+
];
|
| 275 |
+
|
| 276 |
+
for (const strategy of fetchStrategies) {
|
| 277 |
+
if (coverDownloadSuccess) break;
|
| 278 |
+
|
| 279 |
+
console.log(`[ZIP Cover Download] Trying strategy: ${strategy.name}`);
|
| 280 |
+
|
| 281 |
+
try {
|
| 282 |
+
const coverResponse = await fetch(coverUrl, strategy.options);
|
| 283 |
+
|
| 284 |
+
console.log(`[ZIP Cover Download] Response status: ${coverResponse.status}, Content-Length: ${coverResponse.headers.get('Content-Length')}`);
|
| 285 |
+
|
| 286 |
+
if (!coverResponse.ok) {
|
| 287 |
+
console.warn(`[ZIP Cover Download] Failed with status ${coverResponse.status} for size ${size}`);
|
| 288 |
+
continue;
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
const contentType = coverResponse.headers.get('Content-Type');
|
| 292 |
+
const contentLength = coverResponse.headers.get('Content-Length');
|
| 293 |
+
|
| 294 |
+
if (contentLength && parseInt(contentLength, 10) === 0) {
|
| 295 |
+
console.warn(`[ZIP Cover Download] Content-Length is 0 for size ${size}`);
|
| 296 |
+
continue;
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
if (contentType && !contentType.startsWith('image/')) {
|
| 300 |
+
console.warn(`[ZIP Cover Download] Invalid content type: ${contentType}`);
|
| 301 |
+
continue;
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
// Use arrayBuffer directly for more reliable data retrieval
|
| 305 |
+
const arrayBuffer = await coverResponse.arrayBuffer();
|
| 306 |
+
|
| 307 |
+
if (!arrayBuffer || arrayBuffer.byteLength === 0) {
|
| 308 |
+
console.warn(`[ZIP Cover Download] Empty array buffer for size ${size}`);
|
| 309 |
+
continue;
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
const uint8Array = new Uint8Array(arrayBuffer);
|
| 313 |
+
console.log(`[ZIP Cover Download] Received ${uint8Array.length} bytes`);
|
| 314 |
+
|
| 315 |
+
// Detect image format
|
| 316 |
+
const imageFormat = detectImageFormat(uint8Array);
|
| 317 |
+
if (!imageFormat) {
|
| 318 |
+
console.warn(`[ZIP Cover Download] Unknown image format for size ${size}`);
|
| 319 |
+
continue;
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
// Add cover to ZIP with appropriate filename
|
| 323 |
+
const coverFilename = `cover.${imageFormat.extension}`;
|
| 324 |
+
zip.file(coverFilename, uint8Array, {
|
| 325 |
+
binary: true,
|
| 326 |
+
compression: 'DEFLATE',
|
| 327 |
+
compressionOptions: { level: 6 }
|
| 328 |
+
});
|
| 329 |
+
|
| 330 |
+
coverDownloadSuccess = true;
|
| 331 |
+
console.log(`[ZIP Cover Download] Successfully added cover to ZIP (${size}x${size}, format: ${imageFormat.extension}, strategy: ${strategy.name})`);
|
| 332 |
+
break;
|
| 333 |
+
} catch (sizeError) {
|
| 334 |
+
console.warn(`[ZIP Cover Download] Failed at size ${size} with strategy ${strategy.name}:`, sizeError);
|
| 335 |
+
}
|
| 336 |
+
} // End strategy loop
|
| 337 |
+
} // End size loop
|
| 338 |
+
|
| 339 |
+
if (!coverDownloadSuccess) {
|
| 340 |
+
console.warn('[ZIP Cover Download] All attempts failed');
|
| 341 |
+
}
|
| 342 |
+
} catch (coverError) {
|
| 343 |
+
console.warn('Failed to download cover for ZIP:', coverError);
|
| 344 |
+
}
|
| 345 |
+
}
|
| 346 |
+
|
| 347 |
+
for (const track of tracks) {
|
| 348 |
+
const filename = buildTrackFilename(
|
| 349 |
+
canonicalAlbum,
|
| 350 |
+
track,
|
| 351 |
+
quality,
|
| 352 |
+
preferredArtistName,
|
| 353 |
+
convertAacToMp3
|
| 354 |
+
);
|
| 355 |
+
|
| 356 |
+
const result = await downloadTrackWithRetry(
|
| 357 |
+
track.id,
|
| 358 |
+
quality,
|
| 359 |
+
filename,
|
| 360 |
+
track,
|
| 361 |
+
callbacks,
|
| 362 |
+
{ convertAacToMp3 }
|
| 363 |
+
);
|
| 364 |
+
|
| 365 |
+
if (result.success && result.blob) {
|
| 366 |
+
zip.file(filename, result.blob);
|
| 367 |
+
} else {
|
| 368 |
+
console.error(`[ZIP Download] Track failed: ${track.title}`, result.error);
|
| 369 |
+
failedTracks.push({ track, error: result.error ?? new Error('Unknown error') });
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
completed += 1;
|
| 373 |
+
callbacks?.onTrackDownloaded?.(completed, total, track);
|
| 374 |
+
}
|
| 375 |
+
|
| 376 |
+
// Add error report file if there were failures
|
| 377 |
+
if (failedTracks.length > 0) {
|
| 378 |
+
let errorReport = 'DOWNLOAD ERRORS\n';
|
| 379 |
+
errorReport += '===============\n\n';
|
| 380 |
+
errorReport += 'The following tracks failed to download after 3 attempts:\n\n';
|
| 381 |
+
|
| 382 |
+
failedTracks.forEach((item, index) => {
|
| 383 |
+
const { track, error } = item;
|
| 384 |
+
const trackTitle = track.title ?? 'Unknown Track';
|
| 385 |
+
const artistName = formatArtists(track.artists);
|
| 386 |
+
errorReport += `${index + 1}. ${trackTitle} - ${artistName}\n`;
|
| 387 |
+
errorReport += ` Error: ${error.message}\n\n`;
|
| 388 |
+
});
|
| 389 |
+
|
| 390 |
+
zip.file('_DOWNLOAD_ERRORS.txt', errorReport);
|
| 391 |
+
console.log(`[ZIP Download] Added error report with ${failedTracks.length} failed track(s)`);
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
+
const zipBlob = await zip.generateAsync({
|
| 395 |
+
type: 'blob',
|
| 396 |
+
compression: 'DEFLATE',
|
| 397 |
+
compressionOptions: { level: 6 }
|
| 398 |
+
});
|
| 399 |
+
|
| 400 |
+
const successCount = completed - failedTracks.length;
|
| 401 |
+
console.log(`[Album Download] ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`);
|
| 402 |
+
console.log(`[Album Download] ZIP Complete: "${albumTitle}"`);
|
| 403 |
+
console.log(`[Album Download] ✓ Success: ${successCount}/${total} tracks | ZIP size: ${(zipBlob.size / 1024 / 1024).toFixed(2)} MB`);
|
| 404 |
+
if (failedTracks.length > 0) {
|
| 405 |
+
console.log(`[Album Download] ✗ Failed: ${failedTracks.length} track(s) - see _DOWNLOAD_ERRORS.txt in ZIP`);
|
| 406 |
+
}
|
| 407 |
+
console.log(`[Album Download] ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`);
|
| 408 |
+
|
| 409 |
+
triggerFileDownload(zipBlob, `${artistName} - ${albumTitle}.zip`);
|
| 410 |
+
return;
|
| 411 |
+
}
|
| 412 |
+
|
| 413 |
+
let completed = 0;
|
| 414 |
+
let failedCount = 0;
|
| 415 |
+
|
| 416 |
+
for (const track of tracks) {
|
| 417 |
+
const filename = buildTrackFilename(
|
| 418 |
+
canonicalAlbum,
|
| 419 |
+
track,
|
| 420 |
+
quality,
|
| 421 |
+
preferredArtistName,
|
| 422 |
+
convertAacToMp3
|
| 423 |
+
);
|
| 424 |
+
|
| 425 |
+
const result = await downloadTrackWithRetry(
|
| 426 |
+
track.id,
|
| 427 |
+
quality,
|
| 428 |
+
filename,
|
| 429 |
+
track,
|
| 430 |
+
callbacks,
|
| 431 |
+
{ convertAacToMp3, downloadCoverSeperately }
|
| 432 |
+
);
|
| 433 |
+
|
| 434 |
+
if (result.success && result.blob) {
|
| 435 |
+
// Trigger individual download
|
| 436 |
+
const url = URL.createObjectURL(result.blob);
|
| 437 |
+
const a = document.createElement('a');
|
| 438 |
+
a.href = url;
|
| 439 |
+
a.download = filename;
|
| 440 |
+
document.body.appendChild(a);
|
| 441 |
+
a.click();
|
| 442 |
+
document.body.removeChild(a);
|
| 443 |
+
URL.revokeObjectURL(url);
|
| 444 |
+
|
| 445 |
+
// Download cover separately if enabled
|
| 446 |
+
if (downloadCoverSeperately && track.album?.cover) {
|
| 447 |
+
try {
|
| 448 |
+
const coverId = track.album.cover;
|
| 449 |
+
const coverSizes: Array<'1280' | '640' | '320'> = ['1280', '640', '320'];
|
| 450 |
+
let coverDownloadSuccess = false;
|
| 451 |
+
|
| 452 |
+
for (const size of coverSizes) {
|
| 453 |
+
if (coverDownloadSuccess) break;
|
| 454 |
+
|
| 455 |
+
const coverUrl = losslessAPI.getCoverUrl(coverId, size);
|
| 456 |
+
const fetchStrategies = [
|
| 457 |
+
{
|
| 458 |
+
name: 'with-headers',
|
| 459 |
+
options: {
|
| 460 |
+
method: 'GET' as const,
|
| 461 |
+
headers: {
|
| 462 |
+
'Accept': 'image/jpeg,image/jpg,image/png,image/*',
|
| 463 |
+
'User-Agent':
|
| 464 |
+
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
| 465 |
+
},
|
| 466 |
+
signal: AbortSignal.timeout(10000)
|
| 467 |
+
}
|
| 468 |
+
},
|
| 469 |
+
{
|
| 470 |
+
name: 'simple',
|
| 471 |
+
options: {
|
| 472 |
+
method: 'GET' as const,
|
| 473 |
+
signal: AbortSignal.timeout(10000)
|
| 474 |
+
}
|
| 475 |
+
}
|
| 476 |
+
];
|
| 477 |
+
|
| 478 |
+
for (const strategy of fetchStrategies) {
|
| 479 |
+
if (coverDownloadSuccess) break;
|
| 480 |
+
|
| 481 |
+
try {
|
| 482 |
+
const coverResponse = await fetch(coverUrl, strategy.options);
|
| 483 |
+
|
| 484 |
+
if (!coverResponse.ok) continue;
|
| 485 |
+
|
| 486 |
+
const contentType = coverResponse.headers.get('Content-Type');
|
| 487 |
+
const contentLength = coverResponse.headers.get('Content-Length');
|
| 488 |
+
|
| 489 |
+
if (contentLength && parseInt(contentLength, 10) === 0) continue;
|
| 490 |
+
if (contentType && !contentType.startsWith('image/')) continue;
|
| 491 |
+
|
| 492 |
+
const arrayBuffer = await coverResponse.arrayBuffer();
|
| 493 |
+
if (!arrayBuffer || arrayBuffer.byteLength === 0) continue;
|
| 494 |
+
|
| 495 |
+
const uint8Array = new Uint8Array(arrayBuffer);
|
| 496 |
+
const imageFormat = detectImageFormat(uint8Array);
|
| 497 |
+
if (!imageFormat) continue;
|
| 498 |
+
|
| 499 |
+
const coverBlob = new Blob([uint8Array], { type: imageFormat.mimeType });
|
| 500 |
+
const coverObjectUrl = URL.createObjectURL(coverBlob);
|
| 501 |
+
const coverLink = document.createElement('a');
|
| 502 |
+
coverLink.href = coverObjectUrl;
|
| 503 |
+
coverLink.download = `cover.${imageFormat.extension}`;
|
| 504 |
+
document.body.appendChild(coverLink);
|
| 505 |
+
coverLink.click();
|
| 506 |
+
document.body.removeChild(coverLink);
|
| 507 |
+
URL.revokeObjectURL(coverObjectUrl);
|
| 508 |
+
|
| 509 |
+
coverDownloadSuccess = true;
|
| 510 |
+
break;
|
| 511 |
+
} catch {
|
| 512 |
+
// Continue to next strategy
|
| 513 |
+
}
|
| 514 |
+
}
|
| 515 |
+
}
|
| 516 |
+
} catch (coverError) {
|
| 517 |
+
console.warn('Failed to download cover separately:', coverError);
|
| 518 |
+
}
|
| 519 |
+
}
|
| 520 |
+
} else {
|
| 521 |
+
console.error(`[Individual Download] Track failed: ${track.title}`, result.error);
|
| 522 |
+
failedCount++;
|
| 523 |
+
}
|
| 524 |
+
|
| 525 |
+
completed += 1;
|
| 526 |
+
callbacks?.onTrackDownloaded?.(completed, total, track);
|
| 527 |
+
}
|
| 528 |
+
|
| 529 |
+
// Summary logging
|
| 530 |
+
const successCount = total - failedCount;
|
| 531 |
+
console.log(`[Album Download] ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`);
|
| 532 |
+
console.log(`[Album Download] Individual Downloads Complete: "${albumTitle}"`);
|
| 533 |
+
console.log(`[Album Download] ✓ Success: ${successCount}/${total} tracks`);
|
| 534 |
+
if (failedCount > 0) {
|
| 535 |
+
console.log(`[Album Download] ✗ Failed: ${failedCount} track(s)`);
|
| 536 |
+
}
|
| 537 |
+
console.log(`[Album Download] ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`);
|
| 538 |
+
}
|
src/lib/ffmpegClient.ts
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { browser } from '$app/environment';
|
| 2 |
+
|
| 3 |
+
const CORE_BASE_URL = `https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.10/dist/esm`;
|
| 4 |
+
|
| 5 |
+
type FFmpegClass = (typeof import('@ffmpeg/ffmpeg'))['FFmpeg'];
|
| 6 |
+
type FFmpegInstance = InstanceType<FFmpegClass>;
|
| 7 |
+
type FetchFileFn = (typeof import('@ffmpeg/util'))['fetchFile'];
|
| 8 |
+
|
| 9 |
+
const CORE_JS_NAME = 'ffmpeg-core.js';
|
| 10 |
+
const CORE_WASM_NAME = 'ffmpeg-core.wasm';
|
| 11 |
+
|
| 12 |
+
export interface FfmpegLoadProgress {
|
| 13 |
+
receivedBytes: number;
|
| 14 |
+
totalBytes?: number;
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
export interface FfmpegLoadOptions {
|
| 18 |
+
signal?: AbortSignal;
|
| 19 |
+
onProgress?: (progress: FfmpegLoadProgress) => void;
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
let ffmpegInstance: FFmpegInstance | null = null;
|
| 23 |
+
let loadPromise: Promise<FFmpegInstance> | null = null;
|
| 24 |
+
let fetchFileFn: FetchFileFn | null = null;
|
| 25 |
+
let assetsPromise: Promise<{ coreUrl: string; wasmUrl: string; totalBytes?: number }> | null = null;
|
| 26 |
+
let estimatedSizePromise: Promise<number | undefined> | null = null;
|
| 27 |
+
|
| 28 |
+
async function ensureFFmpegClass(): Promise<FFmpegClass> {
|
| 29 |
+
const module = await import('@ffmpeg/ffmpeg');
|
| 30 |
+
return module.FFmpeg;
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
async function ensureFetchFile(): Promise<FetchFileFn> {
|
| 34 |
+
if (fetchFileFn) return fetchFileFn;
|
| 35 |
+
const module = await import('@ffmpeg/util');
|
| 36 |
+
fetchFileFn = module.fetchFile;
|
| 37 |
+
return fetchFileFn;
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
async function fetchHeadSize(path: string): Promise<number | undefined> {
|
| 41 |
+
try {
|
| 42 |
+
const response = await fetch(`${CORE_BASE_URL}/${path}`, { method: 'HEAD' });
|
| 43 |
+
if (!response.ok) return undefined;
|
| 44 |
+
const length = response.headers.get('Content-Length');
|
| 45 |
+
if (!length) return undefined;
|
| 46 |
+
const numeric = Number(length);
|
| 47 |
+
return Number.isFinite(numeric) ? numeric : undefined;
|
| 48 |
+
} catch (error) {
|
| 49 |
+
console.debug('Failed to probe FFmpeg asset size', error);
|
| 50 |
+
return undefined;
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
async function streamAsset(
|
| 55 |
+
path: string,
|
| 56 |
+
options?: FfmpegLoadOptions,
|
| 57 |
+
context?: {
|
| 58 |
+
zTotalKnown?: number;
|
| 59 |
+
onChunk?: (bytes: number) => void;
|
| 60 |
+
}
|
| 61 |
+
): Promise<{ url: string; size: number | undefined }> {
|
| 62 |
+
const response = await fetch(`${CORE_BASE_URL}/${path}`, {
|
| 63 |
+
signal: options?.signal
|
| 64 |
+
});
|
| 65 |
+
if (!response.ok) {
|
| 66 |
+
throw new Error(`Failed to fetch ${path} (${response.status})`);
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
const totalBytes = Number(response.headers.get('Content-Length') ?? '0');
|
| 70 |
+
const resolvedTotal =
|
| 71 |
+
Number.isFinite(totalBytes) && totalBytes > 0 ? totalBytes : context?.zTotalKnown;
|
| 72 |
+
|
| 73 |
+
if (!response.body) {
|
| 74 |
+
const blob = await response.blob();
|
| 75 |
+
const size = blob.size > 0 ? blob.size : resolvedTotal;
|
| 76 |
+
return {
|
| 77 |
+
url: URL.createObjectURL(blob),
|
| 78 |
+
size
|
| 79 |
+
};
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
const reader = response.body.getReader();
|
| 83 |
+
const chunks: Uint8Array[] = [];
|
| 84 |
+
|
| 85 |
+
while (true) {
|
| 86 |
+
const { done, value } = await reader.read();
|
| 87 |
+
if (done) break;
|
| 88 |
+
if (value) {
|
| 89 |
+
chunks.push(value);
|
| 90 |
+
context?.onChunk?.(value.byteLength);
|
| 91 |
+
}
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
const blob = new Blob(chunks as BlobPart[], {
|
| 95 |
+
type: response.headers.get('Content-Type') ?? 'application/octet-stream'
|
| 96 |
+
});
|
| 97 |
+
return {
|
| 98 |
+
url: URL.createObjectURL(blob),
|
| 99 |
+
size: blob.size > 0 ? blob.size : resolvedTotal
|
| 100 |
+
};
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
async function ensureAssets(options?: FfmpegLoadOptions) {
|
| 104 |
+
if (assetsPromise) {
|
| 105 |
+
return assetsPromise;
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
assetsPromise = (async () => {
|
| 109 |
+
const [jsSize, wasmSize] = await Promise.all([
|
| 110 |
+
fetchHeadSize(CORE_JS_NAME),
|
| 111 |
+
fetchHeadSize(CORE_WASM_NAME)
|
| 112 |
+
]);
|
| 113 |
+
const totalKnown = [jsSize, wasmSize]
|
| 114 |
+
.map((value) => (Number.isFinite(value ?? NaN) ? Number(value) : 0))
|
| 115 |
+
.reduce((sum, value) => sum + value, 0);
|
| 116 |
+
|
| 117 |
+
let cumulative = 0;
|
| 118 |
+
const notify = (bytes: number) => {
|
| 119 |
+
cumulative += bytes;
|
| 120 |
+
if (options?.onProgress) {
|
| 121 |
+
options.onProgress({
|
| 122 |
+
receivedBytes: cumulative,
|
| 123 |
+
totalBytes: totalKnown > 0 ? totalKnown : undefined
|
| 124 |
+
});
|
| 125 |
+
}
|
| 126 |
+
};
|
| 127 |
+
|
| 128 |
+
const { url: coreUrl, size: fetchedJsSize } = await streamAsset(CORE_JS_NAME, options, {
|
| 129 |
+
zTotalKnown: totalKnown > 0 ? totalKnown : undefined,
|
| 130 |
+
onChunk: notify
|
| 131 |
+
});
|
| 132 |
+
const { url: wasmUrl, size: fetchedWasmSize } = await streamAsset(CORE_WASM_NAME, options, {
|
| 133 |
+
zTotalKnown: totalKnown > 0 ? totalKnown : undefined,
|
| 134 |
+
onChunk: notify
|
| 135 |
+
});
|
| 136 |
+
|
| 137 |
+
const totalBytes = [jsSize ?? fetchedJsSize, wasmSize ?? fetchedWasmSize]
|
| 138 |
+
.filter((value): value is number => Number.isFinite(value ?? NaN))
|
| 139 |
+
.reduce((sum, value) => sum + value, 0);
|
| 140 |
+
|
| 141 |
+
return {
|
| 142 |
+
coreUrl,
|
| 143 |
+
wasmUrl,
|
| 144 |
+
totalBytes: totalBytes > 0 ? totalBytes : undefined
|
| 145 |
+
};
|
| 146 |
+
})().catch((error) => {
|
| 147 |
+
assetsPromise = null;
|
| 148 |
+
throw error;
|
| 149 |
+
});
|
| 150 |
+
|
| 151 |
+
return assetsPromise;
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
export async function estimateFfmpegDownloadSize(): Promise<number | undefined> {
|
| 155 |
+
if (!estimatedSizePromise) {
|
| 156 |
+
estimatedSizePromise = (async () => {
|
| 157 |
+
const [jsSize, wasmSize] = await Promise.all([
|
| 158 |
+
fetchHeadSize(CORE_JS_NAME),
|
| 159 |
+
fetchHeadSize(CORE_WASM_NAME)
|
| 160 |
+
]);
|
| 161 |
+
const total = [jsSize, wasmSize]
|
| 162 |
+
.filter((value): value is number => Number.isFinite(value ?? NaN))
|
| 163 |
+
.reduce((sum, value) => sum + value, 0);
|
| 164 |
+
return total > 0 ? total : undefined;
|
| 165 |
+
})();
|
| 166 |
+
}
|
| 167 |
+
return estimatedSizePromise ?? Promise.resolve(undefined);
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
export function isFFmpegSupported(): boolean {
|
| 171 |
+
return browser && typeof ReadableStream !== 'undefined' && typeof WebAssembly !== 'undefined';
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
export async function getFFmpeg(options?: FfmpegLoadOptions): Promise<FFmpegInstance> {
|
| 175 |
+
if (!isFFmpegSupported()) {
|
| 176 |
+
throw new Error('FFmpeg is not supported in this environment.');
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
if (ffmpegInstance) {
|
| 180 |
+
return ffmpegInstance;
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
if (!loadPromise) {
|
| 184 |
+
loadPromise = (async () => {
|
| 185 |
+
const FFmpegConstructor = await ensureFFmpegClass();
|
| 186 |
+
const instance = new FFmpegConstructor();
|
| 187 |
+
|
| 188 |
+
const assets = await ensureAssets(options);
|
| 189 |
+
|
| 190 |
+
// Load with memory optimization for WebAssembly
|
| 191 |
+
await instance.load({
|
| 192 |
+
coreURL: assets.coreUrl,
|
| 193 |
+
wasmURL: assets.wasmUrl
|
| 194 |
+
});
|
| 195 |
+
|
| 196 |
+
ffmpegInstance = instance;
|
| 197 |
+
URL.revokeObjectURL(assets.coreUrl);
|
| 198 |
+
URL.revokeObjectURL(assets.wasmUrl);
|
| 199 |
+
return instance;
|
| 200 |
+
})().catch((error) => {
|
| 201 |
+
loadPromise = null;
|
| 202 |
+
throw error;
|
| 203 |
+
});
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
return loadPromise;
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
export async function fetchFile(input: Parameters<FetchFileFn>[0]) {
|
| 210 |
+
const fn = await ensureFetchFile();
|
| 211 |
+
return fn(input);
|
| 212 |
+
}
|
src/lib/index.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// place files you want to import through the `$lib` alias in this folder.
|
| 2 |
+
|
| 3 |
+
// Export API and types
|
| 4 |
+
export { losslessAPI as tidalAPI } from './api';
|
| 5 |
+
export * from './types';
|
| 6 |
+
|
| 7 |
+
// Export stores
|
| 8 |
+
export {
|
| 9 |
+
playerStore,
|
| 10 |
+
currentTrack,
|
| 11 |
+
isPlaying,
|
| 12 |
+
currentTime,
|
| 13 |
+
duration,
|
| 14 |
+
volume,
|
| 15 |
+
progress
|
| 16 |
+
} from './stores/player';
|
| 17 |
+
export {
|
| 18 |
+
downloadUiStore,
|
| 19 |
+
ffmpegBanner,
|
| 20 |
+
activeTrackDownloads,
|
| 21 |
+
completedTrackDownloads,
|
| 22 |
+
erroredTrackDownloads
|
| 23 |
+
} from './stores/downloadUi';
|
| 24 |
+
|
| 25 |
+
// Export components
|
| 26 |
+
export { default as AudioPlayer } from './components/AudioPlayer.svelte';
|
| 27 |
+
export { default as SearchInterface } from './components/SearchInterface.svelte';
|
| 28 |
+
export { default as TrackList } from './components/TrackList.svelte';
|
| 29 |
+
export { default as QualitySelector } from './components/QualitySelector.svelte';
|
src/lib/server/redis.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import Redis, { type RedisOptions } from 'ioredis';
|
| 2 |
+
import { env } from '$env/dynamic/private';
|
| 3 |
+
|
| 4 |
+
let client: Redis | null | undefined;
|
| 5 |
+
let hasLoggedError = false;
|
| 6 |
+
|
| 7 |
+
function logRedisError(error: unknown): void {
|
| 8 |
+
if (hasLoggedError) return;
|
| 9 |
+
hasLoggedError = true;
|
| 10 |
+
console.error('Redis connection error:', error);
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
function buildOptions(): RedisOptions | string | null {
|
| 14 |
+
const url = env.REDIS_URL || env.REDIS_CONNECTION_STRING;
|
| 15 |
+
if (url) {
|
| 16 |
+
return url;
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
const host = env.REDIS_HOST;
|
| 20 |
+
if (!host) {
|
| 21 |
+
return null;
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
const port = env.REDIS_PORT ? Number.parseInt(env.REDIS_PORT, 10) : 6379;
|
| 25 |
+
const tlsEnabled = (env.REDIS_TLS || '').toLowerCase() === 'true';
|
| 26 |
+
|
| 27 |
+
const options: RedisOptions = {
|
| 28 |
+
host,
|
| 29 |
+
port,
|
| 30 |
+
password: env.REDIS_PASSWORD,
|
| 31 |
+
username: env.REDIS_USERNAME,
|
| 32 |
+
lazyConnect: true
|
| 33 |
+
};
|
| 34 |
+
|
| 35 |
+
if (tlsEnabled) {
|
| 36 |
+
options.tls = {};
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
return options;
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
export function getRedisClient(): Redis | null {
|
| 43 |
+
if (client !== undefined) {
|
| 44 |
+
return client;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
const options = buildOptions();
|
| 48 |
+
if (!options) {
|
| 49 |
+
client = null;
|
| 50 |
+
return client;
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
try {
|
| 54 |
+
client =
|
| 55 |
+
typeof options === 'string' ? new Redis(options, { lazyConnect: true }) : new Redis(options);
|
| 56 |
+
client.on('error', logRedisError);
|
| 57 |
+
return client;
|
| 58 |
+
} catch (error) {
|
| 59 |
+
logRedisError(error);
|
| 60 |
+
client = null;
|
| 61 |
+
return client;
|
| 62 |
+
}
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
export function isRedisEnabled(): boolean {
|
| 66 |
+
return getRedisClient() !== null;
|
| 67 |
+
}
|
src/lib/stores/downloadPreferences.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { browser } from '$app/environment';
|
| 2 |
+
import { writable } from 'svelte/store';
|
| 3 |
+
|
| 4 |
+
export type DownloadMode = 'individual' | 'zip' | 'csv';
|
| 5 |
+
|
| 6 |
+
interface DownloadPreferencesState {
|
| 7 |
+
mode: DownloadMode;
|
| 8 |
+
}
|
| 9 |
+
|
| 10 |
+
const createDownloadPreferencesStore = () => {
|
| 11 |
+
const STORAGE_KEY = 'tidal-ui.downloadMode';
|
| 12 |
+
|
| 13 |
+
const readInitialMode = (): DownloadMode => {
|
| 14 |
+
if (!browser) {
|
| 15 |
+
return 'individual';
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
const stored = localStorage.getItem(STORAGE_KEY);
|
| 19 |
+
if (stored === 'individual' || stored === 'zip' || stored === 'csv') {
|
| 20 |
+
return stored;
|
| 21 |
+
}
|
| 22 |
+
return 'individual';
|
| 23 |
+
};
|
| 24 |
+
|
| 25 |
+
const { subscribe, set, update } = writable<DownloadPreferencesState>({
|
| 26 |
+
mode: readInitialMode()
|
| 27 |
+
});
|
| 28 |
+
|
| 29 |
+
if (browser) {
|
| 30 |
+
window.addEventListener('storage', (event) => {
|
| 31 |
+
if (event.key !== STORAGE_KEY) return;
|
| 32 |
+
const value = event.newValue;
|
| 33 |
+
if (value === 'individual' || value === 'zip' || value === 'csv') {
|
| 34 |
+
set({ mode: value });
|
| 35 |
+
}
|
| 36 |
+
});
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
return {
|
| 40 |
+
subscribe,
|
| 41 |
+
setMode(mode: DownloadMode) {
|
| 42 |
+
update(() => {
|
| 43 |
+
if (browser) {
|
| 44 |
+
try {
|
| 45 |
+
localStorage.setItem(STORAGE_KEY, mode);
|
| 46 |
+
} catch (error) {
|
| 47 |
+
console.warn('Failed to persist download mode preference', error);
|
| 48 |
+
}
|
| 49 |
+
}
|
| 50 |
+
return { mode };
|
| 51 |
+
});
|
| 52 |
+
}
|
| 53 |
+
};
|
| 54 |
+
};
|
| 55 |
+
|
| 56 |
+
export const downloadPreferencesStore = createDownloadPreferencesStore();
|
src/lib/stores/downloadUi.ts
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { derived, get, writable } from 'svelte/store';
|
| 2 |
+
import type { Track, PlayableTrack } from '$lib/types';
|
| 3 |
+
import { isSonglinkTrack } from '$lib/types';
|
| 4 |
+
import { formatArtists } from '$lib/utils';
|
| 5 |
+
|
| 6 |
+
export type FfmpegPhase = 'idle' | 'countdown' | 'loading' | 'ready' | 'error';
|
| 7 |
+
|
| 8 |
+
export interface FfmpegBannerState {
|
| 9 |
+
phase: FfmpegPhase;
|
| 10 |
+
countdownSeconds: number;
|
| 11 |
+
totalBytes?: number;
|
| 12 |
+
progress: number;
|
| 13 |
+
dismissible: boolean;
|
| 14 |
+
autoTriggered: boolean;
|
| 15 |
+
error?: string;
|
| 16 |
+
startedAt?: number;
|
| 17 |
+
updatedAt?: number;
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
export type TrackDownloadStatus = 'pending' | 'running' | 'completed' | 'error' | 'cancelled';
|
| 21 |
+
|
| 22 |
+
export interface TrackDownloadTask {
|
| 23 |
+
id: string;
|
| 24 |
+
trackId: number | string;
|
| 25 |
+
title: string;
|
| 26 |
+
subtitle?: string;
|
| 27 |
+
filename: string;
|
| 28 |
+
status: TrackDownloadStatus;
|
| 29 |
+
receivedBytes: number;
|
| 30 |
+
totalBytes?: number;
|
| 31 |
+
progress: number;
|
| 32 |
+
error?: string;
|
| 33 |
+
startedAt: number;
|
| 34 |
+
updatedAt: number;
|
| 35 |
+
cancellable: boolean;
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
interface DownloadUiState {
|
| 39 |
+
ffmpeg: FfmpegBannerState;
|
| 40 |
+
tasks: TrackDownloadTask[];
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
const MAX_VISIBLE_TASKS = 4;
|
| 44 |
+
const COUNTDOWN_DEFAULT_SECONDS = 5;
|
| 45 |
+
|
| 46 |
+
const initialState: DownloadUiState = {
|
| 47 |
+
ffmpeg: {
|
| 48 |
+
phase: 'idle',
|
| 49 |
+
countdownSeconds: COUNTDOWN_DEFAULT_SECONDS,
|
| 50 |
+
totalBytes: undefined,
|
| 51 |
+
progress: 0,
|
| 52 |
+
dismissible: true,
|
| 53 |
+
autoTriggered: true,
|
| 54 |
+
startedAt: undefined,
|
| 55 |
+
updatedAt: undefined
|
| 56 |
+
},
|
| 57 |
+
tasks: []
|
| 58 |
+
};
|
| 59 |
+
|
| 60 |
+
const store = writable<DownloadUiState>(initialState);
|
| 61 |
+
|
| 62 |
+
const taskControllers = new Map<string, AbortController>();
|
| 63 |
+
let countdownInterval: ReturnType<typeof setInterval> | null = null;
|
| 64 |
+
|
| 65 |
+
function nextTaskId(prefix: string): string {
|
| 66 |
+
return `${prefix}-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
function clampProgress(value: number | null | undefined): number {
|
| 70 |
+
if (!Number.isFinite(value ?? NaN)) return 0;
|
| 71 |
+
return Math.max(0, Math.min(1, Number(value)));
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
function stopCountdownTicker() {
|
| 75 |
+
if (countdownInterval) {
|
| 76 |
+
clearInterval(countdownInterval);
|
| 77 |
+
countdownInterval = null;
|
| 78 |
+
}
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
function updateCountdownTicker() {
|
| 82 |
+
stopCountdownTicker();
|
| 83 |
+
countdownInterval = setInterval(() => {
|
| 84 |
+
store.update((state) => {
|
| 85 |
+
if (state.ffmpeg.phase !== 'countdown') {
|
| 86 |
+
stopCountdownTicker();
|
| 87 |
+
return state;
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
const nextSeconds = Math.max(0, state.ffmpeg.countdownSeconds - 1);
|
| 91 |
+
const nextPhase: FfmpegPhase = nextSeconds === 0 ? 'loading' : 'countdown';
|
| 92 |
+
return {
|
| 93 |
+
...state,
|
| 94 |
+
ffmpeg: {
|
| 95 |
+
...state.ffmpeg,
|
| 96 |
+
phase: nextPhase,
|
| 97 |
+
countdownSeconds: nextSeconds,
|
| 98 |
+
progress: 0,
|
| 99 |
+
updatedAt: Date.now(),
|
| 100 |
+
dismissible: nextPhase !== 'loading'
|
| 101 |
+
}
|
| 102 |
+
};
|
| 103 |
+
});
|
| 104 |
+
}, 1000);
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
function upsertTask(task: TrackDownloadTask): void {
|
| 108 |
+
store.update((state) => {
|
| 109 |
+
const existingIndex = state.tasks.findIndex((entry) => entry.id === task.id);
|
| 110 |
+
const tasks = state.tasks.slice();
|
| 111 |
+
if (existingIndex >= 0) {
|
| 112 |
+
tasks[existingIndex] = { ...tasks[existingIndex]!, ...task, updatedAt: Date.now() };
|
| 113 |
+
} else {
|
| 114 |
+
tasks.unshift({ ...task, updatedAt: Date.now() });
|
| 115 |
+
}
|
| 116 |
+
return {
|
| 117 |
+
...state,
|
| 118 |
+
tasks: tasks.slice(0, MAX_VISIBLE_TASKS)
|
| 119 |
+
};
|
| 120 |
+
});
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
function mutateTask(id: string, updater: (task: TrackDownloadTask) => TrackDownloadTask): void {
|
| 124 |
+
store.update((state) => {
|
| 125 |
+
const index = state.tasks.findIndex((entry) => entry.id === id);
|
| 126 |
+
if (index === -1) {
|
| 127 |
+
return state;
|
| 128 |
+
}
|
| 129 |
+
const tasks = state.tasks.slice();
|
| 130 |
+
const nextTask = updater({ ...tasks[index]! });
|
| 131 |
+
tasks[index] = { ...nextTask, updatedAt: Date.now() };
|
| 132 |
+
return { ...state, tasks };
|
| 133 |
+
});
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
function removeTask(id: string): void {
|
| 137 |
+
store.update((state) => ({
|
| 138 |
+
...state,
|
| 139 |
+
tasks: state.tasks.filter((task) => task.id !== id)
|
| 140 |
+
}));
|
| 141 |
+
const controller = taskControllers.get(id);
|
| 142 |
+
if (controller) {
|
| 143 |
+
taskControllers.delete(id);
|
| 144 |
+
}
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
export const downloadUiStore = {
|
| 148 |
+
subscribe: store.subscribe,
|
| 149 |
+
reset(): void {
|
| 150 |
+
stopCountdownTicker();
|
| 151 |
+
store.set(initialState);
|
| 152 |
+
taskControllers.clear();
|
| 153 |
+
},
|
| 154 |
+
beginTrackDownload(
|
| 155 |
+
track: PlayableTrack,
|
| 156 |
+
filename: string,
|
| 157 |
+
options?: { subtitle?: string }
|
| 158 |
+
): {
|
| 159 |
+
taskId: string;
|
| 160 |
+
controller: AbortController;
|
| 161 |
+
} {
|
| 162 |
+
const id = nextTaskId('track');
|
| 163 |
+
const controller = new AbortController();
|
| 164 |
+
taskControllers.set(id, controller);
|
| 165 |
+
|
| 166 |
+
let subtitle = options?.subtitle;
|
| 167 |
+
if (!subtitle) {
|
| 168 |
+
if (isSonglinkTrack(track)) {
|
| 169 |
+
subtitle = track.artistName;
|
| 170 |
+
} else {
|
| 171 |
+
subtitle = formatArtists(track.artists);
|
| 172 |
+
}
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
upsertTask({
|
| 176 |
+
id,
|
| 177 |
+
trackId: track.id,
|
| 178 |
+
title: track.title,
|
| 179 |
+
subtitle,
|
| 180 |
+
filename,
|
| 181 |
+
status: 'running',
|
| 182 |
+
receivedBytes: 0,
|
| 183 |
+
totalBytes: undefined,
|
| 184 |
+
progress: 0,
|
| 185 |
+
error: undefined,
|
| 186 |
+
startedAt: Date.now(),
|
| 187 |
+
updatedAt: Date.now(),
|
| 188 |
+
cancellable: true
|
| 189 |
+
});
|
| 190 |
+
return { taskId: id, controller };
|
| 191 |
+
},
|
| 192 |
+
updateTrackProgress(taskId: string, received: number, total?: number): void {
|
| 193 |
+
mutateTask(taskId, (task) => ({
|
| 194 |
+
...task,
|
| 195 |
+
receivedBytes: received,
|
| 196 |
+
totalBytes: total,
|
| 197 |
+
progress: total ? clampProgress(received / total) : task.progress
|
| 198 |
+
}));
|
| 199 |
+
},
|
| 200 |
+
updateTrackStage(taskId: string, progress: number): void {
|
| 201 |
+
mutateTask(taskId, (task) => ({
|
| 202 |
+
...task,
|
| 203 |
+
progress: clampProgress(progress)
|
| 204 |
+
}));
|
| 205 |
+
},
|
| 206 |
+
completeTrackDownload(taskId: string): void {
|
| 207 |
+
const controller = taskControllers.get(taskId);
|
| 208 |
+
if (controller) {
|
| 209 |
+
taskControllers.delete(taskId);
|
| 210 |
+
}
|
| 211 |
+
mutateTask(taskId, (task) => ({
|
| 212 |
+
...task,
|
| 213 |
+
status: task.status === 'cancelled' ? 'cancelled' : 'completed',
|
| 214 |
+
progress: task.status === 'cancelled' ? task.progress : 1,
|
| 215 |
+
cancellable: false
|
| 216 |
+
}));
|
| 217 |
+
},
|
| 218 |
+
errorTrackDownload(taskId: string, error: unknown): void {
|
| 219 |
+
const controller = taskControllers.get(taskId);
|
| 220 |
+
if (controller) {
|
| 221 |
+
taskControllers.delete(taskId);
|
| 222 |
+
}
|
| 223 |
+
mutateTask(taskId, (task) => ({
|
| 224 |
+
...task,
|
| 225 |
+
status: 'error',
|
| 226 |
+
error:
|
| 227 |
+
error instanceof Error
|
| 228 |
+
? error.message
|
| 229 |
+
: typeof error === 'string'
|
| 230 |
+
? error
|
| 231 |
+
: 'Download failed',
|
| 232 |
+
cancellable: false
|
| 233 |
+
}));
|
| 234 |
+
},
|
| 235 |
+
cancelTrackDownload(taskId: string): void {
|
| 236 |
+
const controller = taskControllers.get(taskId);
|
| 237 |
+
if (controller) {
|
| 238 |
+
controller.abort();
|
| 239 |
+
}
|
| 240 |
+
mutateTask(taskId, (task) => ({
|
| 241 |
+
...task,
|
| 242 |
+
status: 'cancelled',
|
| 243 |
+
error: undefined,
|
| 244 |
+
cancellable: false
|
| 245 |
+
}));
|
| 246 |
+
},
|
| 247 |
+
dismissTrackTask(taskId: string): void {
|
| 248 |
+
removeTask(taskId);
|
| 249 |
+
},
|
| 250 |
+
startFfmpegCountdown(totalBytes: number, options?: { autoTriggered?: boolean }): void {
|
| 251 |
+
const autoTriggered = options?.autoTriggered ?? true;
|
| 252 |
+
store.set({
|
| 253 |
+
...get(store),
|
| 254 |
+
ffmpeg: {
|
| 255 |
+
phase: autoTriggered ? 'countdown' : 'loading',
|
| 256 |
+
countdownSeconds: autoTriggered ? COUNTDOWN_DEFAULT_SECONDS : 0,
|
| 257 |
+
totalBytes: totalBytes > 0 ? totalBytes : undefined,
|
| 258 |
+
progress: 0,
|
| 259 |
+
dismissible: autoTriggered,
|
| 260 |
+
autoTriggered,
|
| 261 |
+
error: undefined,
|
| 262 |
+
startedAt: Date.now(),
|
| 263 |
+
updatedAt: Date.now()
|
| 264 |
+
}
|
| 265 |
+
});
|
| 266 |
+
if (autoTriggered) {
|
| 267 |
+
updateCountdownTicker();
|
| 268 |
+
} else {
|
| 269 |
+
stopCountdownTicker();
|
| 270 |
+
}
|
| 271 |
+
},
|
| 272 |
+
skipFfmpegCountdown(): void {
|
| 273 |
+
store.update((state) => {
|
| 274 |
+
if (state.ffmpeg.phase !== 'countdown') {
|
| 275 |
+
return state;
|
| 276 |
+
}
|
| 277 |
+
stopCountdownTicker();
|
| 278 |
+
return {
|
| 279 |
+
...state,
|
| 280 |
+
ffmpeg: {
|
| 281 |
+
...state.ffmpeg,
|
| 282 |
+
phase: 'loading',
|
| 283 |
+
countdownSeconds: 0,
|
| 284 |
+
progress: 0,
|
| 285 |
+
dismissible: false,
|
| 286 |
+
updatedAt: Date.now()
|
| 287 |
+
}
|
| 288 |
+
};
|
| 289 |
+
});
|
| 290 |
+
},
|
| 291 |
+
startFfmpegLoading(): void {
|
| 292 |
+
stopCountdownTicker();
|
| 293 |
+
store.update((state) => ({
|
| 294 |
+
...state,
|
| 295 |
+
ffmpeg: {
|
| 296 |
+
...state.ffmpeg,
|
| 297 |
+
phase: 'loading',
|
| 298 |
+
countdownSeconds: 0,
|
| 299 |
+
progress: 0,
|
| 300 |
+
dismissible: false,
|
| 301 |
+
updatedAt: Date.now()
|
| 302 |
+
}
|
| 303 |
+
}));
|
| 304 |
+
},
|
| 305 |
+
updateFfmpegProgress(progress: number): void {
|
| 306 |
+
store.update((state) => ({
|
| 307 |
+
...state,
|
| 308 |
+
ffmpeg: {
|
| 309 |
+
...state.ffmpeg,
|
| 310 |
+
phase: 'loading',
|
| 311 |
+
progress: clampProgress(progress),
|
| 312 |
+
dismissible: false,
|
| 313 |
+
updatedAt: Date.now()
|
| 314 |
+
}
|
| 315 |
+
}));
|
| 316 |
+
},
|
| 317 |
+
completeFfmpeg(): void {
|
| 318 |
+
stopCountdownTicker();
|
| 319 |
+
store.update((state) => ({
|
| 320 |
+
...state,
|
| 321 |
+
ffmpeg: {
|
| 322 |
+
...state.ffmpeg,
|
| 323 |
+
phase: 'ready',
|
| 324 |
+
progress: 1,
|
| 325 |
+
countdownSeconds: 0,
|
| 326 |
+
dismissible: true,
|
| 327 |
+
updatedAt: Date.now()
|
| 328 |
+
}
|
| 329 |
+
}));
|
| 330 |
+
},
|
| 331 |
+
errorFfmpeg(error: unknown): void {
|
| 332 |
+
stopCountdownTicker();
|
| 333 |
+
store.update((state) => ({
|
| 334 |
+
...state,
|
| 335 |
+
ffmpeg: {
|
| 336 |
+
...state.ffmpeg,
|
| 337 |
+
phase: 'error',
|
| 338 |
+
progress: 0,
|
| 339 |
+
dismissible: true,
|
| 340 |
+
error:
|
| 341 |
+
error instanceof Error
|
| 342 |
+
? error.message
|
| 343 |
+
: typeof error === 'string'
|
| 344 |
+
? error
|
| 345 |
+
: 'Failed to load FFmpeg',
|
| 346 |
+
updatedAt: Date.now()
|
| 347 |
+
}
|
| 348 |
+
}));
|
| 349 |
+
},
|
| 350 |
+
dismissFfmpeg(): void {
|
| 351 |
+
stopCountdownTicker();
|
| 352 |
+
store.update((state) => ({
|
| 353 |
+
...state,
|
| 354 |
+
ffmpeg: {
|
| 355 |
+
phase: 'idle',
|
| 356 |
+
countdownSeconds: COUNTDOWN_DEFAULT_SECONDS,
|
| 357 |
+
totalBytes: undefined,
|
| 358 |
+
progress: 0,
|
| 359 |
+
dismissible: true,
|
| 360 |
+
autoTriggered: true,
|
| 361 |
+
error: undefined,
|
| 362 |
+
startedAt: undefined,
|
| 363 |
+
updatedAt: Date.now()
|
| 364 |
+
}
|
| 365 |
+
}));
|
| 366 |
+
}
|
| 367 |
+
};
|
| 368 |
+
|
| 369 |
+
export const activeTrackDownloads = derived(store, ($state) =>
|
| 370 |
+
$state.tasks.filter((task) => task.status === 'running')
|
| 371 |
+
);
|
| 372 |
+
|
| 373 |
+
export const completedTrackDownloads = derived(store, ($state) =>
|
| 374 |
+
$state.tasks.filter((task) => task.status === 'completed')
|
| 375 |
+
);
|
| 376 |
+
|
| 377 |
+
export const erroredTrackDownloads = derived(store, ($state) =>
|
| 378 |
+
$state.tasks.filter((task) => task.status === 'error')
|
| 379 |
+
);
|
| 380 |
+
|
| 381 |
+
export const ffmpegBanner = derived(store, ($state) => $state.ffmpeg);
|
src/lib/stores/lyrics.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { browser } from '$app/environment';
|
| 2 |
+
import { get, writable } from 'svelte/store';
|
| 3 |
+
import type { Track, PlayableTrack } from '$lib/types';
|
| 4 |
+
import { currentTrack as currentTrackStore } from '$lib/stores/player';
|
| 5 |
+
|
| 6 |
+
export interface LyricsState {
|
| 7 |
+
open: boolean;
|
| 8 |
+
maximized: boolean;
|
| 9 |
+
track: PlayableTrack | null;
|
| 10 |
+
refreshToken: number;
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
const initialState: LyricsState = {
|
| 14 |
+
open: false,
|
| 15 |
+
maximized: false,
|
| 16 |
+
track: null,
|
| 17 |
+
refreshToken: 0
|
| 18 |
+
};
|
| 19 |
+
|
| 20 |
+
function createLyricsStore() {
|
| 21 |
+
const store = writable<LyricsState>({ ...initialState });
|
| 22 |
+
|
| 23 |
+
let currentTrack: PlayableTrack | null = null;
|
| 24 |
+
|
| 25 |
+
currentTrackStore.subscribe((track) => {
|
| 26 |
+
currentTrack = track ?? null;
|
| 27 |
+
store.update((state) => {
|
| 28 |
+
const trackChanged = state.track?.id !== currentTrack?.id;
|
| 29 |
+
return {
|
| 30 |
+
...state,
|
| 31 |
+
track: currentTrack,
|
| 32 |
+
refreshToken: trackChanged ? state.refreshToken + 1 : state.refreshToken
|
| 33 |
+
};
|
| 34 |
+
});
|
| 35 |
+
});
|
| 36 |
+
|
| 37 |
+
function open(targetTrack?: PlayableTrack | null) {
|
| 38 |
+
const nextTrack = targetTrack ?? currentTrack;
|
| 39 |
+
store.update((state) => ({
|
| 40 |
+
...state,
|
| 41 |
+
open: true,
|
| 42 |
+
track: nextTrack ?? state.track,
|
| 43 |
+
maximized:
|
| 44 |
+
browser && window.matchMedia('(max-width: 640px)').matches ? true : state.maximized,
|
| 45 |
+
refreshToken:
|
| 46 |
+
nextTrack && state.track?.id !== nextTrack.id ? state.refreshToken + 1 : state.refreshToken
|
| 47 |
+
}));
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
function close() {
|
| 51 |
+
store.update((state) => ({
|
| 52 |
+
...state,
|
| 53 |
+
open: false,
|
| 54 |
+
maximized: false
|
| 55 |
+
}));
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
function toggle() {
|
| 59 |
+
const state = get(store);
|
| 60 |
+
if (state.open) {
|
| 61 |
+
close();
|
| 62 |
+
} else {
|
| 63 |
+
open();
|
| 64 |
+
}
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
function toggleMaximize() {
|
| 68 |
+
store.update((state) => ({
|
| 69 |
+
...state,
|
| 70 |
+
maximized: !state.maximized
|
| 71 |
+
}));
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
function refresh() {
|
| 75 |
+
store.update((state) => ({
|
| 76 |
+
...state,
|
| 77 |
+
refreshToken: state.refreshToken + 1
|
| 78 |
+
}));
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
return {
|
| 82 |
+
subscribe: store.subscribe,
|
| 83 |
+
open,
|
| 84 |
+
close,
|
| 85 |
+
toggle,
|
| 86 |
+
toggleMaximize,
|
| 87 |
+
refresh
|
| 88 |
+
};
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
export const lyricsStore = createLyricsStore();
|
src/lib/stores/performance.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { derived, readable } from 'svelte/store';
|
| 2 |
+
import { browser } from '$app/environment';
|
| 3 |
+
import { userPreferencesStore } from './userPreferences';
|
| 4 |
+
import { type PerformanceLevel } from '$lib/utils/performance';
|
| 5 |
+
|
| 6 |
+
/**
|
| 7 |
+
* Derived store that provides the effective performance level
|
| 8 |
+
* based on user preferences.
|
| 9 |
+
*/
|
| 10 |
+
export const effectivePerformanceLevel = derived(
|
| 11 |
+
userPreferencesStore,
|
| 12 |
+
($prefs): PerformanceLevel => {
|
| 13 |
+
return $prefs.performanceMode as PerformanceLevel;
|
| 14 |
+
}
|
| 15 |
+
);
|
| 16 |
+
|
| 17 |
+
/**
|
| 18 |
+
* Store that tracks if user prefers reduced motion
|
| 19 |
+
*/
|
| 20 |
+
export const reducedMotion = readable(false, (set) => {
|
| 21 |
+
if (!browser) {
|
| 22 |
+
return;
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
const mediaQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
|
| 26 |
+
|
| 27 |
+
set(mediaQuery.matches);
|
| 28 |
+
|
| 29 |
+
const handler = (e: MediaQueryListEvent) => {
|
| 30 |
+
set(e.matches);
|
| 31 |
+
};
|
| 32 |
+
|
| 33 |
+
mediaQuery.addEventListener('change', handler);
|
| 34 |
+
|
| 35 |
+
return () => {
|
| 36 |
+
mediaQuery.removeEventListener('change', handler);
|
| 37 |
+
};
|
| 38 |
+
});
|
| 39 |
+
|
| 40 |
+
/**
|
| 41 |
+
* Derived store that determines if animations should be enabled
|
| 42 |
+
*/
|
| 43 |
+
export const animationsEnabled = derived(
|
| 44 |
+
[effectivePerformanceLevel, reducedMotion],
|
| 45 |
+
([$perfLevel, $reducedMotion]) => {
|
| 46 |
+
if ($reducedMotion) {
|
| 47 |
+
return false;
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
return $perfLevel !== 'low';
|
| 51 |
+
}
|
| 52 |
+
);
|
src/lib/stores/player.ts
ADDED
|
@@ -0,0 +1,473 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Audio player store for managing playback state
|
| 2 |
+
import { writable, derived, get } from 'svelte/store';
|
| 3 |
+
import { browser } from '$app/environment';
|
| 4 |
+
import type { Track, AudioQuality, PlayableTrack } from '$lib/types';
|
| 5 |
+
import { deriveTrackQuality } from '$lib/utils/audioQuality';
|
| 6 |
+
import { userPreferencesStore } from '$lib/stores/userPreferences';
|
| 7 |
+
|
| 8 |
+
interface PlayerState {
|
| 9 |
+
currentTrack: PlayableTrack | null;
|
| 10 |
+
isPlaying: boolean;
|
| 11 |
+
currentTime: number;
|
| 12 |
+
duration: number;
|
| 13 |
+
volume: number;
|
| 14 |
+
quality: AudioQuality;
|
| 15 |
+
qualitySource: 'auto' | 'manual';
|
| 16 |
+
isLoading: boolean;
|
| 17 |
+
queue: PlayableTrack[];
|
| 18 |
+
queueIndex: number;
|
| 19 |
+
sampleRate: number | null;
|
| 20 |
+
bitDepth: number | null;
|
| 21 |
+
replayGain: number | null;
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
const initialPreferences = get(userPreferencesStore);
|
| 25 |
+
|
| 26 |
+
const initialState: PlayerState = {
|
| 27 |
+
currentTrack: null,
|
| 28 |
+
isPlaying: false,
|
| 29 |
+
currentTime: 0,
|
| 30 |
+
duration: 0,
|
| 31 |
+
volume: 0.8,
|
| 32 |
+
quality: initialPreferences.playbackQuality,
|
| 33 |
+
qualitySource: 'manual',
|
| 34 |
+
isLoading: false,
|
| 35 |
+
queue: [],
|
| 36 |
+
queueIndex: -1,
|
| 37 |
+
sampleRate: null,
|
| 38 |
+
bitDepth: null,
|
| 39 |
+
replayGain: null
|
| 40 |
+
};
|
| 41 |
+
|
| 42 |
+
function createPlayerStore() {
|
| 43 |
+
let startState = initialState;
|
| 44 |
+
if (browser) {
|
| 45 |
+
try {
|
| 46 |
+
const stored = sessionStorage.getItem('tidal-player-store');
|
| 47 |
+
if (stored) {
|
| 48 |
+
const parsed = JSON.parse(stored);
|
| 49 |
+
startState = {
|
| 50 |
+
...initialState,
|
| 51 |
+
...parsed,
|
| 52 |
+
isPlaying: false,
|
| 53 |
+
isLoading: false
|
| 54 |
+
};
|
| 55 |
+
}
|
| 56 |
+
} catch (e) {
|
| 57 |
+
console.warn('Failed to restore player state', e);
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
const { subscribe, set, update } = writable<PlayerState>(startState);
|
| 62 |
+
|
| 63 |
+
if (browser) {
|
| 64 |
+
subscribe((state) => {
|
| 65 |
+
try {
|
| 66 |
+
const toSave = {
|
| 67 |
+
currentTrack: state.currentTrack,
|
| 68 |
+
queue: state.queue,
|
| 69 |
+
queueIndex: state.queueIndex,
|
| 70 |
+
volume: state.volume,
|
| 71 |
+
quality: state.quality,
|
| 72 |
+
qualitySource: state.qualitySource,
|
| 73 |
+
currentTime: state.currentTime,
|
| 74 |
+
duration: state.duration,
|
| 75 |
+
sampleRate: state.sampleRate,
|
| 76 |
+
bitDepth: state.bitDepth,
|
| 77 |
+
replayGain: state.replayGain
|
| 78 |
+
};
|
| 79 |
+
sessionStorage.setItem('tidal-player-store', JSON.stringify(toSave));
|
| 80 |
+
} catch (e) {
|
| 81 |
+
console.warn('Failed to save player state', e);
|
| 82 |
+
}
|
| 83 |
+
});
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
const applyAutoQuality = (state: PlayerState, track: PlayableTrack | null): PlayerState => {
|
| 87 |
+
if (state.qualitySource === 'manual') {
|
| 88 |
+
return state;
|
| 89 |
+
}
|
| 90 |
+
// SonglinkTrack will be converted to Track before playing, so use LOSSLESS for now
|
| 91 |
+
if (track && 'isSonglinkTrack' in track && track.isSonglinkTrack) {
|
| 92 |
+
const nextQuality: AudioQuality = 'LOSSLESS';
|
| 93 |
+
if (state.quality === nextQuality) {
|
| 94 |
+
return state;
|
| 95 |
+
}
|
| 96 |
+
return { ...state, quality: nextQuality };
|
| 97 |
+
}
|
| 98 |
+
const derived = deriveTrackQuality(track as Track | null);
|
| 99 |
+
const nextQuality: AudioQuality = derived ?? 'LOSSLESS';
|
| 100 |
+
if (state.quality === nextQuality) {
|
| 101 |
+
return state;
|
| 102 |
+
}
|
| 103 |
+
return { ...state, quality: nextQuality };
|
| 104 |
+
};
|
| 105 |
+
|
| 106 |
+
const resolveSampleRate = (state: PlayerState, track: PlayableTrack | null): number | null => {
|
| 107 |
+
// SonglinkTrack doesn't have sampleRate, return null
|
| 108 |
+
if (track && 'isSonglinkTrack' in track && track.isSonglinkTrack) {
|
| 109 |
+
return null;
|
| 110 |
+
}
|
| 111 |
+
if (state.currentTrack && track && 'id' in state.currentTrack && 'id' in track && state.currentTrack.id === track.id) {
|
| 112 |
+
return state.sampleRate;
|
| 113 |
+
}
|
| 114 |
+
return null;
|
| 115 |
+
};
|
| 116 |
+
|
| 117 |
+
return {
|
| 118 |
+
subscribe,
|
| 119 |
+
setTrack: (track: PlayableTrack) =>
|
| 120 |
+
update((state) => {
|
| 121 |
+
const next: PlayerState = {
|
| 122 |
+
...state,
|
| 123 |
+
currentTrack: track,
|
| 124 |
+
duration: track.duration,
|
| 125 |
+
currentTime: 0,
|
| 126 |
+
isLoading: true,
|
| 127 |
+
sampleRate: resolveSampleRate(state, track),
|
| 128 |
+
bitDepth: null,
|
| 129 |
+
replayGain: null
|
| 130 |
+
};
|
| 131 |
+
return applyAutoQuality(next, track);
|
| 132 |
+
}),
|
| 133 |
+
play: () => update((state) => ({ ...state, isPlaying: true })),
|
| 134 |
+
pause: () => update((state) => ({ ...state, isPlaying: false })),
|
| 135 |
+
togglePlay: () => update((state) => ({ ...state, isPlaying: !state.isPlaying })),
|
| 136 |
+
setCurrentTime: (time: number) => update((state) => ({ ...state, currentTime: time })),
|
| 137 |
+
setDuration: (duration: number) => update((state) => ({ ...state, duration })),
|
| 138 |
+
setSampleRate: (sampleRate: number | null) => update((state) => ({ ...state, sampleRate })),
|
| 139 |
+
setBitDepth: (bitDepth: number | null) => update((state) => ({ ...state, bitDepth })),
|
| 140 |
+
setReplayGain: (replayGain: number | null) => update((state) => ({ ...state, replayGain })),
|
| 141 |
+
setVolume: (volume: number) => update((state) => ({ ...state, volume })),
|
| 142 |
+
setQuality: (quality: AudioQuality) =>
|
| 143 |
+
update((state) => {
|
| 144 |
+
userPreferencesStore.setPlaybackQuality(quality);
|
| 145 |
+
return { ...state, quality, qualitySource: 'manual' };
|
| 146 |
+
}),
|
| 147 |
+
setLoading: (isLoading: boolean) => update((state) => ({ ...state, isLoading })),
|
| 148 |
+
setQueue: (queue: PlayableTrack[], startIndex: number = 0) =>
|
| 149 |
+
update((state) => {
|
| 150 |
+
const hasTracks = queue.length > 0;
|
| 151 |
+
const clampedIndex = hasTracks
|
| 152 |
+
? Math.min(Math.max(startIndex, 0), queue.length - 1)
|
| 153 |
+
: -1;
|
| 154 |
+
const nextTrack = hasTracks ? queue[clampedIndex]! : null;
|
| 155 |
+
|
| 156 |
+
// Check if we are staying on the same track (prevent reload if so)
|
| 157 |
+
const isSameTrack = state.currentTrack && nextTrack && state.currentTrack.id === nextTrack.id;
|
| 158 |
+
|
| 159 |
+
let next: PlayerState = {
|
| 160 |
+
...state,
|
| 161 |
+
queue,
|
| 162 |
+
queueIndex: clampedIndex,
|
| 163 |
+
currentTrack: nextTrack,
|
| 164 |
+
isPlaying: hasTracks ? state.isPlaying : false,
|
| 165 |
+
isLoading: isSameTrack ? state.isLoading : hasTracks,
|
| 166 |
+
currentTime: isSameTrack ? state.currentTime : 0,
|
| 167 |
+
duration: isSameTrack ? state.duration : (nextTrack?.duration ?? 0),
|
| 168 |
+
sampleRate: isSameTrack ? state.sampleRate : resolveSampleRate(state, nextTrack),
|
| 169 |
+
bitDepth: isSameTrack ? state.bitDepth : null,
|
| 170 |
+
replayGain: isSameTrack ? state.replayGain : null
|
| 171 |
+
};
|
| 172 |
+
|
| 173 |
+
if (!hasTracks) {
|
| 174 |
+
next = {
|
| 175 |
+
...next,
|
| 176 |
+
queueIndex: -1,
|
| 177 |
+
currentTrack: null,
|
| 178 |
+
isPlaying: false,
|
| 179 |
+
isLoading: false,
|
| 180 |
+
currentTime: 0,
|
| 181 |
+
duration: 0,
|
| 182 |
+
sampleRate: null,
|
| 183 |
+
bitDepth: null,
|
| 184 |
+
replayGain: null
|
| 185 |
+
};
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
return applyAutoQuality(next, next.currentTrack);
|
| 189 |
+
}),
|
| 190 |
+
enqueue: (track: PlayableTrack) =>
|
| 191 |
+
update((state) => {
|
| 192 |
+
const queue = state.queue.slice();
|
| 193 |
+
if (queue.length === 0) {
|
| 194 |
+
const next: PlayerState = {
|
| 195 |
+
...state,
|
| 196 |
+
queue: [track],
|
| 197 |
+
queueIndex: 0,
|
| 198 |
+
currentTrack: track,
|
| 199 |
+
isPlaying: true,
|
| 200 |
+
isLoading: true,
|
| 201 |
+
currentTime: 0,
|
| 202 |
+
duration: track.duration,
|
| 203 |
+
sampleRate: resolveSampleRate(state, track),
|
| 204 |
+
bitDepth: null,
|
| 205 |
+
replayGain: null
|
| 206 |
+
};
|
| 207 |
+
return applyAutoQuality(next, track);
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
queue.push(track);
|
| 211 |
+
return {
|
| 212 |
+
...state,
|
| 213 |
+
queue
|
| 214 |
+
};
|
| 215 |
+
}),
|
| 216 |
+
enqueueNext: (track: PlayableTrack) =>
|
| 217 |
+
update((state) => {
|
| 218 |
+
const queue = state.queue.slice();
|
| 219 |
+
let queueIndex = state.queueIndex;
|
| 220 |
+
if (queue.length === 0 || queueIndex === -1) {
|
| 221 |
+
const next: PlayerState = {
|
| 222 |
+
...state,
|
| 223 |
+
queue: [track],
|
| 224 |
+
queueIndex: 0,
|
| 225 |
+
currentTrack: track,
|
| 226 |
+
isPlaying: true,
|
| 227 |
+
isLoading: true,
|
| 228 |
+
currentTime: 0,
|
| 229 |
+
duration: track.duration,
|
| 230 |
+
sampleRate: resolveSampleRate(state, track),
|
| 231 |
+
bitDepth: null,
|
| 232 |
+
replayGain: null
|
| 233 |
+
};
|
| 234 |
+
return applyAutoQuality(next, track);
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
const insertIndex = Math.min(queueIndex + 1, queue.length);
|
| 238 |
+
queue.splice(insertIndex, 0, track);
|
| 239 |
+
if (insertIndex <= queueIndex) {
|
| 240 |
+
queueIndex += 1;
|
| 241 |
+
}
|
| 242 |
+
return {
|
| 243 |
+
...state,
|
| 244 |
+
queue,
|
| 245 |
+
queueIndex
|
| 246 |
+
};
|
| 247 |
+
}),
|
| 248 |
+
next: () =>
|
| 249 |
+
update((state) => {
|
| 250 |
+
if (state.queueIndex < state.queue.length - 1) {
|
| 251 |
+
const newIndex = state.queueIndex + 1;
|
| 252 |
+
const nextTrack = state.queue[newIndex] ?? null;
|
| 253 |
+
const nextState: PlayerState = {
|
| 254 |
+
...state,
|
| 255 |
+
queueIndex: newIndex,
|
| 256 |
+
currentTrack: nextTrack,
|
| 257 |
+
currentTime: 0,
|
| 258 |
+
duration: nextTrack?.duration ?? 0,
|
| 259 |
+
sampleRate: resolveSampleRate(state, nextTrack),
|
| 260 |
+
bitDepth: null,
|
| 261 |
+
replayGain: null
|
| 262 |
+
};
|
| 263 |
+
return applyAutoQuality(nextState, nextTrack);
|
| 264 |
+
}
|
| 265 |
+
return state;
|
| 266 |
+
}),
|
| 267 |
+
previous: () =>
|
| 268 |
+
update((state) => {
|
| 269 |
+
if (state.queueIndex > 0) {
|
| 270 |
+
const newIndex = state.queueIndex - 1;
|
| 271 |
+
const nextTrack = state.queue[newIndex] ?? null;
|
| 272 |
+
const nextState: PlayerState = {
|
| 273 |
+
...state,
|
| 274 |
+
queueIndex: newIndex,
|
| 275 |
+
currentTrack: nextTrack,
|
| 276 |
+
currentTime: 0,
|
| 277 |
+
duration: nextTrack?.duration ?? 0,
|
| 278 |
+
sampleRate: resolveSampleRate(state, nextTrack),
|
| 279 |
+
bitDepth: null,
|
| 280 |
+
replayGain: null
|
| 281 |
+
};
|
| 282 |
+
return applyAutoQuality(nextState, nextTrack);
|
| 283 |
+
}
|
| 284 |
+
return state;
|
| 285 |
+
}),
|
| 286 |
+
shuffleQueue: () =>
|
| 287 |
+
update((state) => {
|
| 288 |
+
const {
|
| 289 |
+
queue: originalQueue,
|
| 290 |
+
queueIndex: originalIndex,
|
| 291 |
+
currentTrack: originalCurrent
|
| 292 |
+
} = state;
|
| 293 |
+
|
| 294 |
+
if (originalQueue.length <= 1) {
|
| 295 |
+
return state;
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
const queue = originalQueue.slice();
|
| 299 |
+
let pinnedTrack: PlayableTrack | null = null;
|
| 300 |
+
|
| 301 |
+
if (originalCurrent) {
|
| 302 |
+
const locatedIndex = queue.findIndex((track) => track.id === originalCurrent.id);
|
| 303 |
+
if (locatedIndex >= 0) {
|
| 304 |
+
pinnedTrack = queue.splice(locatedIndex, 1)[0] ?? null;
|
| 305 |
+
}
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
if (!pinnedTrack && originalIndex >= 0 && originalIndex < queue.length) {
|
| 309 |
+
pinnedTrack = queue.splice(originalIndex, 1)[0] ?? null;
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
if (!pinnedTrack && originalCurrent) {
|
| 313 |
+
pinnedTrack = originalCurrent;
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
for (let i = queue.length - 1; i > 0; i -= 1) {
|
| 317 |
+
const j = Math.floor(Math.random() * (i + 1));
|
| 318 |
+
[queue[i], queue[j]] = [queue[j]!, queue[i]!];
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
if (pinnedTrack) {
|
| 322 |
+
queue.unshift(pinnedTrack);
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
+
const nextQueueIndex = queue.length > 0 ? 0 : -1;
|
| 326 |
+
const nextCurrentTrack = queue.length > 0 ? (queue[0] ?? null) : null;
|
| 327 |
+
|
| 328 |
+
let nextState: PlayerState = {
|
| 329 |
+
...state,
|
| 330 |
+
queue,
|
| 331 |
+
queueIndex: nextQueueIndex,
|
| 332 |
+
currentTrack: nextCurrentTrack,
|
| 333 |
+
currentTime: 0,
|
| 334 |
+
duration: nextCurrentTrack?.duration ?? 0,
|
| 335 |
+
sampleRate: resolveSampleRate(state, nextCurrentTrack),
|
| 336 |
+
bitDepth: null,
|
| 337 |
+
replayGain: null
|
| 338 |
+
};
|
| 339 |
+
|
| 340 |
+
if (nextQueueIndex === -1) {
|
| 341 |
+
nextState = {
|
| 342 |
+
...nextState,
|
| 343 |
+
currentTrack: null,
|
| 344 |
+
currentTime: 0,
|
| 345 |
+
duration: 0,
|
| 346 |
+
sampleRate: null,
|
| 347 |
+
bitDepth: null,
|
| 348 |
+
replayGain: null
|
| 349 |
+
};
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
return applyAutoQuality(nextState, nextState.currentTrack);
|
| 353 |
+
}),
|
| 354 |
+
playAtIndex: (index: number) =>
|
| 355 |
+
update((state) => {
|
| 356 |
+
if (index < 0 || index >= state.queue.length) {
|
| 357 |
+
return state;
|
| 358 |
+
}
|
| 359 |
+
|
| 360 |
+
const nextTrack = state.queue[index] ?? null;
|
| 361 |
+
const nextState: PlayerState = {
|
| 362 |
+
...state,
|
| 363 |
+
queueIndex: index,
|
| 364 |
+
currentTrack: nextTrack,
|
| 365 |
+
currentTime: 0,
|
| 366 |
+
isPlaying: true,
|
| 367 |
+
isLoading: true,
|
| 368 |
+
duration: nextTrack?.duration ?? 0,
|
| 369 |
+
sampleRate: resolveSampleRate(state, nextTrack),
|
| 370 |
+
bitDepth: null,
|
| 371 |
+
replayGain: null
|
| 372 |
+
};
|
| 373 |
+
return applyAutoQuality(nextState, nextTrack);
|
| 374 |
+
}),
|
| 375 |
+
removeFromQueue: (index: number) =>
|
| 376 |
+
update((state) => {
|
| 377 |
+
if (index < 0 || index >= state.queue.length) {
|
| 378 |
+
return state;
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
const queue = state.queue.slice();
|
| 382 |
+
queue.splice(index, 1);
|
| 383 |
+
let queueIndex = state.queueIndex;
|
| 384 |
+
let currentTrack = state.currentTrack;
|
| 385 |
+
let isPlaying = state.isPlaying;
|
| 386 |
+
let currentTime = state.currentTime;
|
| 387 |
+
let duration = state.duration;
|
| 388 |
+
let isLoading = state.isLoading;
|
| 389 |
+
|
| 390 |
+
if (queue.length === 0) {
|
| 391 |
+
const nextState: PlayerState = {
|
| 392 |
+
...state,
|
| 393 |
+
queue,
|
| 394 |
+
queueIndex: -1,
|
| 395 |
+
currentTrack: null,
|
| 396 |
+
isPlaying: false,
|
| 397 |
+
isLoading: false,
|
| 398 |
+
currentTime: 0,
|
| 399 |
+
duration: 0,
|
| 400 |
+
sampleRate: null,
|
| 401 |
+
bitDepth: null,
|
| 402 |
+
replayGain: null
|
| 403 |
+
};
|
| 404 |
+
return applyAutoQuality(nextState, null);
|
| 405 |
+
}
|
| 406 |
+
|
| 407 |
+
if (index < queueIndex) {
|
| 408 |
+
queueIndex -= 1;
|
| 409 |
+
} else if (index === queueIndex) {
|
| 410 |
+
if (queueIndex >= queue.length) {
|
| 411 |
+
queueIndex = queue.length - 1;
|
| 412 |
+
}
|
| 413 |
+
currentTrack = queue[queueIndex] ?? null;
|
| 414 |
+
currentTime = 0;
|
| 415 |
+
duration = currentTrack?.duration ?? 0;
|
| 416 |
+
if (!currentTrack) {
|
| 417 |
+
isPlaying = false;
|
| 418 |
+
isLoading = false;
|
| 419 |
+
} else {
|
| 420 |
+
isLoading = true;
|
| 421 |
+
}
|
| 422 |
+
}
|
| 423 |
+
const nextSampleRate =
|
| 424 |
+
state.currentTrack && currentTrack && state.currentTrack.id === currentTrack.id
|
| 425 |
+
? state.sampleRate
|
| 426 |
+
: null;
|
| 427 |
+
|
| 428 |
+
const nextState: PlayerState = {
|
| 429 |
+
...state,
|
| 430 |
+
queue,
|
| 431 |
+
queueIndex,
|
| 432 |
+
currentTrack,
|
| 433 |
+
isPlaying,
|
| 434 |
+
isLoading,
|
| 435 |
+
currentTime,
|
| 436 |
+
duration,
|
| 437 |
+
sampleRate: nextSampleRate,
|
| 438 |
+
replayGain: state.replayGain
|
| 439 |
+
};
|
| 440 |
+
return applyAutoQuality(nextState, currentTrack);
|
| 441 |
+
}),
|
| 442 |
+
clearQueue: () =>
|
| 443 |
+
update((state) => {
|
| 444 |
+
const nextState: PlayerState = {
|
| 445 |
+
...state,
|
| 446 |
+
queue: [],
|
| 447 |
+
queueIndex: -1,
|
| 448 |
+
currentTrack: null,
|
| 449 |
+
isPlaying: false,
|
| 450 |
+
isLoading: false,
|
| 451 |
+
currentTime: 0,
|
| 452 |
+
duration: 0,
|
| 453 |
+
sampleRate: null,
|
| 454 |
+
bitDepth: null,
|
| 455 |
+
replayGain: null
|
| 456 |
+
};
|
| 457 |
+
return applyAutoQuality(nextState, null);
|
| 458 |
+
}),
|
| 459 |
+
reset: () => set(initialState)
|
| 460 |
+
};
|
| 461 |
+
}
|
| 462 |
+
|
| 463 |
+
export const playerStore = createPlayerStore();
|
| 464 |
+
|
| 465 |
+
// Derived stores for convenience
|
| 466 |
+
export const currentTrack = derived(playerStore, ($store) => $store.currentTrack);
|
| 467 |
+
export const isPlaying = derived(playerStore, ($store) => $store.isPlaying);
|
| 468 |
+
export const currentTime = derived(playerStore, ($store) => $store.currentTime);
|
| 469 |
+
export const duration = derived(playerStore, ($store) => $store.duration);
|
| 470 |
+
export const volume = derived(playerStore, ($store) => $store.volume);
|
| 471 |
+
export const progress = derived(playerStore, ($store) =>
|
| 472 |
+
$store.duration > 0 ? ($store.currentTime / $store.duration) * 100 : 0
|
| 473 |
+
);
|
src/lib/stores/region.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { browser } from '$app/environment';
|
| 2 |
+
import { writable } from 'svelte/store';
|
| 3 |
+
|
| 4 |
+
export type RegionOption = 'auto' | 'us' | 'eu';
|
| 5 |
+
|
| 6 |
+
const STORAGE_KEY = 'tidal-ui.region';
|
| 7 |
+
|
| 8 |
+
const readInitialRegion = (): RegionOption => {
|
| 9 |
+
if (!browser) {
|
| 10 |
+
return 'auto';
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
const stored = localStorage.getItem(STORAGE_KEY);
|
| 14 |
+
if (stored === 'us' || stored === 'eu' || stored === 'auto') {
|
| 15 |
+
return stored;
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
return 'auto';
|
| 19 |
+
};
|
| 20 |
+
|
| 21 |
+
const createRegionStore = () => {
|
| 22 |
+
const { subscribe, set, update } = writable<RegionOption>(readInitialRegion());
|
| 23 |
+
|
| 24 |
+
if (browser) {
|
| 25 |
+
subscribe((value) => {
|
| 26 |
+
try {
|
| 27 |
+
localStorage.setItem(STORAGE_KEY, value);
|
| 28 |
+
} catch (error) {
|
| 29 |
+
console.warn('Failed to persist region preference', error);
|
| 30 |
+
}
|
| 31 |
+
});
|
| 32 |
+
|
| 33 |
+
window.addEventListener('storage', (event) => {
|
| 34 |
+
if (event.key !== STORAGE_KEY) return;
|
| 35 |
+
const value = event.newValue;
|
| 36 |
+
if (value === 'us' || value === 'eu' || value === 'auto') {
|
| 37 |
+
set(value);
|
| 38 |
+
}
|
| 39 |
+
});
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
return {
|
| 43 |
+
subscribe,
|
| 44 |
+
setRegion(value: RegionOption) {
|
| 45 |
+
update(() => value);
|
| 46 |
+
}
|
| 47 |
+
};
|
| 48 |
+
};
|
| 49 |
+
|
| 50 |
+
export const regionStore = createRegionStore();
|
src/lib/stores/searchStore.svelte.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { browser } from '$app/environment';
|
| 2 |
+
import type { Track, Album, Artist, Playlist, SonglinkTrack } from '$lib/types';
|
| 3 |
+
|
| 4 |
+
export type SearchTab = 'tracks' | 'albums' | 'artists' | 'playlists';
|
| 5 |
+
|
| 6 |
+
class SearchStore {
|
| 7 |
+
query = $state('');
|
| 8 |
+
activeTab = $state<SearchTab>('tracks');
|
| 9 |
+
isLoading = $state(false);
|
| 10 |
+
tracks = $state<(Track | SonglinkTrack)[]>([]);
|
| 11 |
+
albums = $state<Album[]>([]);
|
| 12 |
+
artists = $state<Artist[]>([]);
|
| 13 |
+
playlists = $state<Playlist[]>([]);
|
| 14 |
+
error = $state<string | null>(null);
|
| 15 |
+
|
| 16 |
+
// Playlist conversion state
|
| 17 |
+
isPlaylistConversionMode = $state(false);
|
| 18 |
+
playlistConversionTotal = $state(0);
|
| 19 |
+
playlistLoadingMessage = $state<string | null>(null);
|
| 20 |
+
|
| 21 |
+
constructor() {
|
| 22 |
+
if (browser) {
|
| 23 |
+
const stored = sessionStorage.getItem('tidal-ui-search-store');
|
| 24 |
+
if (stored) {
|
| 25 |
+
try {
|
| 26 |
+
const data = JSON.parse(stored);
|
| 27 |
+
this.query = data.query ?? '';
|
| 28 |
+
this.activeTab = data.activeTab ?? 'tracks';
|
| 29 |
+
this.tracks = data.tracks ?? [];
|
| 30 |
+
this.albums = data.albums ?? [];
|
| 31 |
+
this.artists = data.artists ?? [];
|
| 32 |
+
this.playlists = data.playlists ?? [];
|
| 33 |
+
this.isPlaylistConversionMode = data.isPlaylistConversionMode ?? false;
|
| 34 |
+
this.playlistConversionTotal = data.playlistConversionTotal ?? 0;
|
| 35 |
+
} catch (e) {
|
| 36 |
+
console.error('Failed to restore search state:', e);
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
$effect.root(() => {
|
| 41 |
+
$effect(() => {
|
| 42 |
+
const data = {
|
| 43 |
+
query: this.query,
|
| 44 |
+
activeTab: this.activeTab,
|
| 45 |
+
tracks: this.tracks,
|
| 46 |
+
albums: this.albums,
|
| 47 |
+
artists: this.artists,
|
| 48 |
+
playlists: this.playlists,
|
| 49 |
+
isPlaylistConversionMode: this.isPlaylistConversionMode,
|
| 50 |
+
playlistConversionTotal: this.playlistConversionTotal
|
| 51 |
+
};
|
| 52 |
+
try {
|
| 53 |
+
sessionStorage.setItem('tidal-ui-search-store', JSON.stringify(data));
|
| 54 |
+
} catch (e) {
|
| 55 |
+
console.warn('Failed to save search state to sessionStorage:', e);
|
| 56 |
+
}
|
| 57 |
+
});
|
| 58 |
+
});
|
| 59 |
+
}
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
reset() {
|
| 63 |
+
this.query = '';
|
| 64 |
+
this.activeTab = 'tracks';
|
| 65 |
+
this.isLoading = false;
|
| 66 |
+
this.tracks = [];
|
| 67 |
+
this.albums = [];
|
| 68 |
+
this.artists = [];
|
| 69 |
+
this.playlists = [];
|
| 70 |
+
this.error = null;
|
| 71 |
+
this.isPlaylistConversionMode = false;
|
| 72 |
+
this.playlistConversionTotal = 0;
|
| 73 |
+
this.playlistLoadingMessage = null;
|
| 74 |
+
}
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
export const searchStore = new SearchStore();
|
src/lib/stores/userPreferences.ts
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { browser } from '$app/environment';
|
| 2 |
+
import { writable } from 'svelte/store';
|
| 3 |
+
import type { AudioQuality } from '$lib/types';
|
| 4 |
+
import { type PerformanceLevel } from '$lib/utils/performance';
|
| 5 |
+
|
| 6 |
+
export type PerformanceMode = 'medium' | 'low';
|
| 7 |
+
|
| 8 |
+
export interface UserPreferencesState {
|
| 9 |
+
playbackQuality: AudioQuality;
|
| 10 |
+
convertAacToMp3: boolean;
|
| 11 |
+
downloadCoversSeperately: boolean;
|
| 12 |
+
performanceMode: PerformanceMode;
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
const STORAGE_KEY = 'tidal-ui.userPreferences';
|
| 16 |
+
|
| 17 |
+
const DEFAULT_STATE: UserPreferencesState = {
|
| 18 |
+
playbackQuality: 'HI_RES_LOSSLESS',
|
| 19 |
+
convertAacToMp3: false,
|
| 20 |
+
downloadCoversSeperately: false,
|
| 21 |
+
performanceMode: 'medium'
|
| 22 |
+
};
|
| 23 |
+
|
| 24 |
+
/**
|
| 25 |
+
* Detect if the user is on a mobile/touch device for initial performance setting
|
| 26 |
+
*/
|
| 27 |
+
function detectIsMobileDevice(): boolean {
|
| 28 |
+
if (!browser) return false;
|
| 29 |
+
|
| 30 |
+
// Check for touch capability
|
| 31 |
+
const hasTouch = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
|
| 32 |
+
|
| 33 |
+
// Check screen size (typical mobile breakpoint)
|
| 34 |
+
const isSmallScreen = window.innerWidth <= 768;
|
| 35 |
+
|
| 36 |
+
// Check for mobile user agent patterns
|
| 37 |
+
const mobileUA = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
|
| 38 |
+
navigator.userAgent
|
| 39 |
+
);
|
| 40 |
+
|
| 41 |
+
return hasTouch && (isSmallScreen || mobileUA);
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
function parseStoredPreferences(raw: string | null): UserPreferencesState {
|
| 45 |
+
if (!raw) {
|
| 46 |
+
return DEFAULT_STATE;
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
try {
|
| 50 |
+
const parsed = JSON.parse(raw) as Partial<UserPreferencesState>;
|
| 51 |
+
const quality = parsed?.playbackQuality;
|
| 52 |
+
const convertFlag = parsed?.convertAacToMp3;
|
| 53 |
+
const downloadCoversFlag = parsed?.downloadCoversSeperately;
|
| 54 |
+
const perfMode = parsed?.performanceMode;
|
| 55 |
+
return {
|
| 56 |
+
playbackQuality:
|
| 57 |
+
quality === 'HI_RES_LOSSLESS' ||
|
| 58 |
+
quality === 'LOSSLESS' ||
|
| 59 |
+
quality === 'HIGH' ||
|
| 60 |
+
quality === 'LOW'
|
| 61 |
+
? quality
|
| 62 |
+
: DEFAULT_STATE.playbackQuality,
|
| 63 |
+
convertAacToMp3:
|
| 64 |
+
typeof convertFlag === 'boolean' ? convertFlag : DEFAULT_STATE.convertAacToMp3,
|
| 65 |
+
downloadCoversSeperately:
|
| 66 |
+
typeof downloadCoversFlag === 'boolean'
|
| 67 |
+
? downloadCoversFlag
|
| 68 |
+
: DEFAULT_STATE.downloadCoversSeperately,
|
| 69 |
+
performanceMode:
|
| 70 |
+
perfMode === 'medium' || perfMode === 'low' ? perfMode : DEFAULT_STATE.performanceMode
|
| 71 |
+
};
|
| 72 |
+
} catch (error) {
|
| 73 |
+
console.warn('Failed to parse stored user preferences', error);
|
| 74 |
+
return DEFAULT_STATE;
|
| 75 |
+
}
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
const readInitialPreferences = (): UserPreferencesState => {
|
| 79 |
+
if (!browser) {
|
| 80 |
+
return DEFAULT_STATE;
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
try {
|
| 84 |
+
const storedRaw = localStorage.getItem(STORAGE_KEY);
|
| 85 |
+
|
| 86 |
+
// If no stored preferences, detect mobile and set appropriate defaults
|
| 87 |
+
if (!storedRaw) {
|
| 88 |
+
const isMobile = detectIsMobileDevice();
|
| 89 |
+
const initialState: UserPreferencesState = {
|
| 90 |
+
...DEFAULT_STATE,
|
| 91 |
+
// Mobile devices default to 'medium' performance (already default)
|
| 92 |
+
// Could set to 'low' for very resource-constrained devices if needed
|
| 93 |
+
performanceMode: isMobile ? 'medium' : 'medium'
|
| 94 |
+
};
|
| 95 |
+
|
| 96 |
+
// Persist the initial preferences so this detection only runs once
|
| 97 |
+
try {
|
| 98 |
+
localStorage.setItem(STORAGE_KEY, JSON.stringify(initialState));
|
| 99 |
+
} catch {
|
| 100 |
+
// Ignore storage errors
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
return initialState;
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
return parseStoredPreferences(storedRaw);
|
| 107 |
+
} catch (error) {
|
| 108 |
+
console.warn('Unable to read user preferences from storage', error);
|
| 109 |
+
return DEFAULT_STATE;
|
| 110 |
+
}
|
| 111 |
+
};
|
| 112 |
+
|
| 113 |
+
const createUserPreferencesStore = () => {
|
| 114 |
+
const { subscribe, set, update } = writable<UserPreferencesState>(readInitialPreferences());
|
| 115 |
+
|
| 116 |
+
if (browser) {
|
| 117 |
+
subscribe((state) => {
|
| 118 |
+
try {
|
| 119 |
+
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
|
| 120 |
+
} catch (error) {
|
| 121 |
+
console.warn('Failed to persist user preferences', error);
|
| 122 |
+
}
|
| 123 |
+
});
|
| 124 |
+
|
| 125 |
+
window.addEventListener('storage', (event) => {
|
| 126 |
+
if (event.key !== STORAGE_KEY) return;
|
| 127 |
+
set(parseStoredPreferences(event.newValue));
|
| 128 |
+
});
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
return {
|
| 132 |
+
subscribe,
|
| 133 |
+
setPlaybackQuality(quality: AudioQuality) {
|
| 134 |
+
update((state) => {
|
| 135 |
+
if (state.playbackQuality === quality) {
|
| 136 |
+
return state;
|
| 137 |
+
}
|
| 138 |
+
return { ...state, playbackQuality: quality };
|
| 139 |
+
});
|
| 140 |
+
},
|
| 141 |
+
setConvertAacToMp3(value: boolean) {
|
| 142 |
+
update((state) => {
|
| 143 |
+
if (state.convertAacToMp3 === value) {
|
| 144 |
+
return state;
|
| 145 |
+
}
|
| 146 |
+
return { ...state, convertAacToMp3: value };
|
| 147 |
+
});
|
| 148 |
+
},
|
| 149 |
+
toggleConvertAacToMp3() {
|
| 150 |
+
update((state) => ({ ...state, convertAacToMp3: !state.convertAacToMp3 }));
|
| 151 |
+
},
|
| 152 |
+
setDownloadCoversSeperately(value: boolean) {
|
| 153 |
+
update((state) => {
|
| 154 |
+
if (state.downloadCoversSeperately === value) {
|
| 155 |
+
return state;
|
| 156 |
+
}
|
| 157 |
+
return { ...state, downloadCoversSeperately: value };
|
| 158 |
+
});
|
| 159 |
+
},
|
| 160 |
+
toggleDownloadCoversSeperately() {
|
| 161 |
+
update((state) => ({ ...state, downloadCoversSeperately: !state.downloadCoversSeperately }));
|
| 162 |
+
},
|
| 163 |
+
setPerformanceMode(mode: PerformanceMode) {
|
| 164 |
+
update((state) => {
|
| 165 |
+
if (state.performanceMode === mode) {
|
| 166 |
+
return state;
|
| 167 |
+
}
|
| 168 |
+
return { ...state, performanceMode: mode };
|
| 169 |
+
});
|
| 170 |
+
},
|
| 171 |
+
getEffectivePerformanceLevel(): PerformanceLevel {
|
| 172 |
+
const state = readInitialPreferences();
|
| 173 |
+
return state.performanceMode as PerformanceLevel;
|
| 174 |
+
},
|
| 175 |
+
reset() {
|
| 176 |
+
set(DEFAULT_STATE);
|
| 177 |
+
}
|
| 178 |
+
};
|
| 179 |
+
};
|
| 180 |
+
|
| 181 |
+
export const userPreferencesStore = createUserPreferencesStore();
|
src/lib/types.ts
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Type definitions based on HIFI API
|
| 2 |
+
|
| 3 |
+
export interface Track {
|
| 4 |
+
id: number;
|
| 5 |
+
title: string;
|
| 6 |
+
duration: number;
|
| 7 |
+
replayGain?: number;
|
| 8 |
+
peak?: number;
|
| 9 |
+
allowStreaming: boolean;
|
| 10 |
+
streamReady: boolean;
|
| 11 |
+
streamStartDate?: string;
|
| 12 |
+
premiumStreamingOnly: boolean;
|
| 13 |
+
trackNumber: number;
|
| 14 |
+
volumeNumber: number;
|
| 15 |
+
version: string | null;
|
| 16 |
+
popularity: number;
|
| 17 |
+
copyright?: string;
|
| 18 |
+
url: string;
|
| 19 |
+
isrc?: string;
|
| 20 |
+
editable: boolean;
|
| 21 |
+
explicit: boolean;
|
| 22 |
+
audioQuality: string;
|
| 23 |
+
audioModes: string[];
|
| 24 |
+
artist: Artist;
|
| 25 |
+
artists: Artist[];
|
| 26 |
+
album: Album;
|
| 27 |
+
mixes?: Record<string, string>;
|
| 28 |
+
mediaMetadata?: {
|
| 29 |
+
tags: string[];
|
| 30 |
+
};
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
export interface Artist {
|
| 34 |
+
id: number;
|
| 35 |
+
name: string;
|
| 36 |
+
type: string;
|
| 37 |
+
picture?: string;
|
| 38 |
+
url?: string;
|
| 39 |
+
popularity?: number;
|
| 40 |
+
artistTypes?: string[];
|
| 41 |
+
artistRoles?: Array<{
|
| 42 |
+
category: string;
|
| 43 |
+
categoryId: number;
|
| 44 |
+
}>;
|
| 45 |
+
mixes?: Record<string, string>;
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
export interface ArtistDetails extends Artist {
|
| 49 |
+
albums: Album[];
|
| 50 |
+
tracks: Track[];
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
export interface Album {
|
| 54 |
+
id: number;
|
| 55 |
+
title: string;
|
| 56 |
+
cover: string;
|
| 57 |
+
videoCover: string | null;
|
| 58 |
+
releaseDate?: string;
|
| 59 |
+
duration?: number;
|
| 60 |
+
numberOfTracks?: number;
|
| 61 |
+
numberOfVideos?: number;
|
| 62 |
+
numberOfVolumes?: number;
|
| 63 |
+
explicit?: boolean;
|
| 64 |
+
popularity?: number;
|
| 65 |
+
type?: string;
|
| 66 |
+
upc?: string;
|
| 67 |
+
copyright?: string;
|
| 68 |
+
artist?: Artist;
|
| 69 |
+
artists?: Artist[];
|
| 70 |
+
audioQuality?: string;
|
| 71 |
+
audioModes?: string[];
|
| 72 |
+
url?: string;
|
| 73 |
+
vibrantColor?: string;
|
| 74 |
+
streamReady?: boolean;
|
| 75 |
+
allowStreaming?: boolean;
|
| 76 |
+
mediaMetadata?: {
|
| 77 |
+
tags: string[];
|
| 78 |
+
};
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
export interface Playlist {
|
| 82 |
+
uuid: string;
|
| 83 |
+
title: string;
|
| 84 |
+
description: string;
|
| 85 |
+
image: string;
|
| 86 |
+
squareImage?: string;
|
| 87 |
+
duration: number;
|
| 88 |
+
numberOfTracks: number;
|
| 89 |
+
numberOfVideos: number;
|
| 90 |
+
creator: {
|
| 91 |
+
id: number;
|
| 92 |
+
name: string;
|
| 93 |
+
picture: string | null;
|
| 94 |
+
};
|
| 95 |
+
created: string;
|
| 96 |
+
lastUpdated: string;
|
| 97 |
+
type: string;
|
| 98 |
+
publicPlaylist: boolean;
|
| 99 |
+
url: string;
|
| 100 |
+
popularity: number;
|
| 101 |
+
promotedArtists?: Artist[];
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
export interface TrackInfo {
|
| 105 |
+
trackId: number;
|
| 106 |
+
audioQuality: string;
|
| 107 |
+
audioMode: string;
|
| 108 |
+
manifest: string;
|
| 109 |
+
manifestMimeType: string;
|
| 110 |
+
manifestHash?: string;
|
| 111 |
+
assetPresentation: string;
|
| 112 |
+
albumReplayGain?: number;
|
| 113 |
+
albumPeakAmplitude?: number;
|
| 114 |
+
trackReplayGain?: number;
|
| 115 |
+
trackPeakAmplitude?: number;
|
| 116 |
+
bitDepth?: number;
|
| 117 |
+
sampleRate?: number;
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
export interface SearchResponse<T> {
|
| 121 |
+
limit: number;
|
| 122 |
+
offset: number;
|
| 123 |
+
totalNumberOfItems: number;
|
| 124 |
+
items: T[];
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
export interface CoverImage {
|
| 128 |
+
id: number;
|
| 129 |
+
name: string;
|
| 130 |
+
'1280': string;
|
| 131 |
+
'640': string;
|
| 132 |
+
'80': string;
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
export interface Lyrics {
|
| 136 |
+
trackId: number;
|
| 137 |
+
lyricsProvider: string;
|
| 138 |
+
providerCommontrackId: string;
|
| 139 |
+
providerLyricsId: string;
|
| 140 |
+
lyrics: string;
|
| 141 |
+
subtitles: string;
|
| 142 |
+
isRightToLeft: boolean;
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
export type AudioQuality = 'HI_RES_LOSSLESS' | 'LOSSLESS' | 'HIGH' | 'LOW';
|
| 146 |
+
|
| 147 |
+
export interface StreamData {
|
| 148 |
+
originalTrack: string;
|
| 149 |
+
trackInfo: TrackInfo;
|
| 150 |
+
songInfo: Track;
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
export interface TrackLookup {
|
| 154 |
+
track: Track;
|
| 155 |
+
info: TrackInfo;
|
| 156 |
+
originalTrackUrl?: string;
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
export interface TrackRecommendationsResponse {
|
| 160 |
+
version: string,
|
| 161 |
+
data: {
|
| 162 |
+
limit: number;
|
| 163 |
+
offset: number;
|
| 164 |
+
totalNumberOfItems: number,
|
| 165 |
+
items: {
|
| 166 |
+
track: Track;
|
| 167 |
+
sources: string[]
|
| 168 |
+
}[]
|
| 169 |
+
}
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
/**
|
| 173 |
+
* Songlink API response types (copied to avoid circular dependency)
|
| 174 |
+
*/
|
| 175 |
+
export interface SonglinkEntity {
|
| 176 |
+
id: string;
|
| 177 |
+
type: 'song' | 'album';
|
| 178 |
+
title?: string;
|
| 179 |
+
artistName?: string;
|
| 180 |
+
thumbnailUrl?: string;
|
| 181 |
+
thumbnailWidth?: number;
|
| 182 |
+
thumbnailHeight?: number;
|
| 183 |
+
apiProvider: string;
|
| 184 |
+
platforms: string[];
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
export interface SonglinkPlatformLink {
|
| 188 |
+
country: string;
|
| 189 |
+
url: string;
|
| 190 |
+
nativeAppUriMobile?: string;
|
| 191 |
+
nativeAppUriDesktop?: string;
|
| 192 |
+
entityUniqueId: string;
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
export interface SonglinkResponse {
|
| 196 |
+
entityUniqueId: string;
|
| 197 |
+
userCountry: string;
|
| 198 |
+
pageUrl: string;
|
| 199 |
+
entitiesByUniqueId: Record<string, SonglinkEntity>;
|
| 200 |
+
linksByPlatform: Record<string, SonglinkPlatformLink>;
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
/**
|
| 204 |
+
* Represents a track from Songlink API that hasn't been converted to a full TIDAL track yet
|
| 205 |
+
* Used to defer expensive TIDAL API calls until the track is actually played
|
| 206 |
+
*/
|
| 207 |
+
export interface SonglinkTrack {
|
| 208 |
+
// Unique identifier (e.g., "spotify:track:3RiPr603aXAoi4GHyXx0uy")
|
| 209 |
+
id: string;
|
| 210 |
+
title: string;
|
| 211 |
+
artistName: string;
|
| 212 |
+
// Duration is unknown from Songlink, use placeholder
|
| 213 |
+
duration: number;
|
| 214 |
+
thumbnailUrl: string;
|
| 215 |
+
// Store the original URL for later conversion
|
| 216 |
+
sourceUrl: string;
|
| 217 |
+
// Store Songlink response data
|
| 218 |
+
songlinkData: SonglinkResponse;
|
| 219 |
+
// Flag to identify this as a Songlink track
|
| 220 |
+
isSonglinkTrack: true;
|
| 221 |
+
// Optional Tidal ID if available
|
| 222 |
+
tidalId?: number;
|
| 223 |
+
// Assume CD quality for display purposes
|
| 224 |
+
audioQuality: 'LOSSLESS';
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
/**
|
| 228 |
+
* Union type for tracks that can be played
|
| 229 |
+
*/
|
| 230 |
+
export type PlayableTrack = Track | SonglinkTrack;
|
| 231 |
+
|
| 232 |
+
/**
|
| 233 |
+
* Type guard to check if a track is a SonglinkTrack
|
| 234 |
+
*/
|
| 235 |
+
export function isSonglinkTrack(track: PlayableTrack): track is SonglinkTrack {
|
| 236 |
+
return 'isSonglinkTrack' in track && track.isSonglinkTrack === true;
|
| 237 |
+
}
|
src/lib/utils.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Artist } from './types';
|
| 2 |
+
|
| 3 |
+
/**
|
| 4 |
+
* Formats an array of artists into a readable string for UI display.
|
| 5 |
+
* For single artist: "Artist Name"
|
| 6 |
+
* For multiple artists: "Artist1, Artist2 & Artist3"
|
| 7 |
+
*
|
| 8 |
+
* @param artists - Array of artists
|
| 9 |
+
* @returns Formatted artist string
|
| 10 |
+
*/
|
| 11 |
+
export function formatArtists(artists: Artist[] | undefined): string {
|
| 12 |
+
if (!artists || artists.length === 0) {
|
| 13 |
+
return 'Unknown Artist';
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
if (artists.length === 1) {
|
| 17 |
+
return artists[0].name;
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
if (artists.length === 2) {
|
| 21 |
+
return `${artists[0].name} & ${artists[1].name}`;
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
// For 3 or more artists: "Artist1, Artist2 & Artist3"
|
| 25 |
+
const allButLast = artists.slice(0, -1).map(a => a.name).join(', ');
|
| 26 |
+
const last = artists[artists.length - 1].name;
|
| 27 |
+
return `${allButLast} & ${last}`;
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
/**
|
| 31 |
+
* Formats an array of artists for metadata tags (ID3, etc.).
|
| 32 |
+
* Uses semicolons as the standard delimiter.
|
| 33 |
+
* For single artist: "Artist Name"
|
| 34 |
+
* For multiple artists: "Artist1; Artist2; Artist3"
|
| 35 |
+
*
|
| 36 |
+
* @param artists - Array of artists
|
| 37 |
+
* @returns Formatted artist string for metadata
|
| 38 |
+
*/
|
| 39 |
+
export function formatArtistsForMetadata(artists: Artist[] | undefined): string {
|
| 40 |
+
if (!artists || artists.length === 0) {
|
| 41 |
+
return 'Unknown Artist';
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
return artists.map(a => a.name).join('; ');
|
| 45 |
+
}
|
src/lib/utils/audioQuality.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { AudioQuality, Track } from '$lib/types';
|
| 2 |
+
|
| 3 |
+
const QUALITY_PRIORITY: readonly AudioQuality[] = [
|
| 4 |
+
'HI_RES_LOSSLESS',
|
| 5 |
+
'LOSSLESS',
|
| 6 |
+
'HIGH',
|
| 7 |
+
'LOW'
|
| 8 |
+
];
|
| 9 |
+
|
| 10 |
+
const QUALITY_TOKENS: Record<AudioQuality, readonly string[]> = {
|
| 11 |
+
HI_RES_LOSSLESS: [
|
| 12 |
+
'HI_RES_LOSSLESS',
|
| 13 |
+
'HIRES_LOSSLESS',
|
| 14 |
+
'HIRESLOSSLESS',
|
| 15 |
+
'HIFI_PLUS',
|
| 16 |
+
'HI_RES_FLAC',
|
| 17 |
+
'HI_RES',
|
| 18 |
+
'HIRES',
|
| 19 |
+
'MASTER',
|
| 20 |
+
'MASTER_QUALITY',
|
| 21 |
+
'MQA'
|
| 22 |
+
],
|
| 23 |
+
LOSSLESS: ['LOSSLESS', 'HIFI'],
|
| 24 |
+
HIGH: ['HIGH', 'HIGH_QUALITY'],
|
| 25 |
+
LOW: ['LOW', 'LOW_QUALITY']
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
const QUALITY_RANK = new Map<AudioQuality, number>(
|
| 29 |
+
QUALITY_PRIORITY.map((quality, index) => [quality, index])
|
| 30 |
+
);
|
| 31 |
+
|
| 32 |
+
const sanitizeToken = (value: string): string => value.trim().toUpperCase().replace(/[^A-Z0-9]+/g, '_');
|
| 33 |
+
|
| 34 |
+
export function normalizeQualityToken(value?: string | null): AudioQuality | null {
|
| 35 |
+
if (!value) {
|
| 36 |
+
return null;
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
const token = sanitizeToken(value);
|
| 40 |
+
|
| 41 |
+
for (const [quality, aliases] of Object.entries(QUALITY_TOKENS) as Array<[
|
| 42 |
+
AudioQuality,
|
| 43 |
+
readonly string[]
|
| 44 |
+
]>) {
|
| 45 |
+
if (aliases.includes(token)) {
|
| 46 |
+
return quality;
|
| 47 |
+
}
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
return null;
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
export function deriveQualityFromTags(rawTags?: unknown): AudioQuality | null {
|
| 54 |
+
if (!Array.isArray(rawTags)) {
|
| 55 |
+
return null;
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
const candidates: AudioQuality[] = [];
|
| 59 |
+
for (const tag of rawTags) {
|
| 60 |
+
if (typeof tag !== 'string') {
|
| 61 |
+
continue;
|
| 62 |
+
}
|
| 63 |
+
const normalized = normalizeQualityToken(tag);
|
| 64 |
+
if (normalized && !candidates.includes(normalized)) {
|
| 65 |
+
candidates.push(normalized);
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
return pickBestQuality(candidates);
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
export function pickBestQuality(
|
| 73 |
+
candidates: Array<AudioQuality | null | undefined>
|
| 74 |
+
): AudioQuality | null {
|
| 75 |
+
let best: AudioQuality | null = null;
|
| 76 |
+
|
| 77 |
+
for (const candidate of candidates) {
|
| 78 |
+
if (!candidate) {
|
| 79 |
+
continue;
|
| 80 |
+
}
|
| 81 |
+
if (!best) {
|
| 82 |
+
best = candidate;
|
| 83 |
+
continue;
|
| 84 |
+
}
|
| 85 |
+
const currentRank = QUALITY_RANK.get(candidate) ?? Number.POSITIVE_INFINITY;
|
| 86 |
+
const bestRank = QUALITY_RANK.get(best) ?? Number.POSITIVE_INFINITY;
|
| 87 |
+
if (currentRank < bestRank) {
|
| 88 |
+
best = candidate;
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
return best;
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
export function deriveTrackQuality(track?: Track | null): AudioQuality | null {
|
| 96 |
+
if (!track) {
|
| 97 |
+
return null;
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
const candidates: Array<AudioQuality | null> = [
|
| 101 |
+
deriveQualityFromTags(track.mediaMetadata?.tags),
|
| 102 |
+
deriveQualityFromTags(track.album?.mediaMetadata?.tags),
|
| 103 |
+
normaliz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 6 |
+
r: number;
|
| 7 |
+
g: number;
|
| 8 |
+
b: number;
|
| 9 |
+
a: number;
|
| 10 |
+
saturation?: number;
|
| 11 |
+
luminance?: number;
|
| 12 |
+
vibrancy?: number;
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
/**
|
| 16 |
+
* Calculate HSV saturation for a color
|
| 17 |
+
*/
|
| 18 |
+
export function calculateSaturation(color: Color): number {
|
| 19 |
+
const r_norm = color.r / 255;
|
| 20 |
+
const g_norm = color.g / 255;
|
| 21 |
+
const b_norm = color.b / 255;
|
| 22 |
+
const max = Math.max(r_norm, g_norm, b_norm);
|
| 23 |
+
const min = Math.min(r_norm, g_norm, b_norm);
|
| 24 |
+
const delta = max - min;
|
| 25 |
+
|
| 26 |
+
if (delta < 0.00001 || max < 0.00001) return 0;
|
| 27 |
+
return delta / max; // HSV saturation
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
/**
|
| 31 |
+
* Calculate relative luminance (ITU-R BT.709)
|
| 32 |
+
*/
|
| 33 |
+
export function calculateLuminance(color: Color): number {
|
| 34 |
+
// Convert to linear RGB
|
| 35 |
+
const linearize = (v: number) => {
|
| 36 |
+
v /= 255;
|
| 37 |
+
return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
|
| 38 |
+
};
|
| 39 |
+
|
| 40 |
+
const r = linearize(color.r);
|
| 41 |
+
const g = linearize(color.g);
|
| 42 |
+
const b = linearize(color.b);
|
| 43 |
+
|
| 44 |
+
// ITU-R BT.709 weights
|
| 45 |
+
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
/**
|
| 49 |
+
* Calculate vibrancy score (favors mid-luminance and high saturation)
|
| 50 |
+
*/
|
| 51 |
+
export function calculateVibrancy(color: Color): number {
|
| 52 |
+
const saturation = color.saturation ?? calculateSaturation(color);
|
| 53 |
+
const luminance = color.luminance ?? calculateLuminance(color);
|
| 54 |
+
|
| 55 |
+
// Vibrancy formula: favor mid-luminance and high saturation
|
| 56 |
+
const lumFactor = 1.0 - Math.abs(luminance - 0.5) * 1.8;
|
| 57 |
+
return saturation * 0.5 + Math.max(0, lumFactor) * 0.5;
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
/**
|
| 61 |
+
* Get average color from a canvas region, selecting most vibrant sample if significantly better
|
| 62 |
+
*/
|
| 63 |
+
export function getAverageColor(
|
| 64 |
+
ctx: CanvasRenderingContext2D,
|
| 65 |
+
x: number,
|
| 66 |
+
y: number,
|
| 67 |
+
w: number,
|
| 68 |
+
h: number
|
| 69 |
+
): Color {
|
| 70 |
+
const imageData = ctx.getImageData(x, y, w, h);
|
| 71 |
+
const data = imageData.data;
|
| 72 |
+
const samples: Color[] = [];
|
| 73 |
+
|
| 74 |
+
let totalR = 0,
|
| 75 |
+
totalG = 0,
|
| 76 |
+
totalB = 0,
|
| 77 |
+
totalA = 0;
|
| 78 |
+
let count = 0;
|
| 79 |
+
|
| 80 |
+
// Sample every pixel
|
| 81 |
+
for (let i = 0; i < data.length; i += 4) {
|
| 82 |
+
const r = data[i]!;
|
| 83 |
+
const g = data[i + 1]!;
|
| 84 |
+
const b = data[i + 2]!;
|
| 85 |
+
const a = data[i + 3]!;
|
| 86 |
+
|
| 87 |
+
totalR += r;
|
| 88 |
+
totalG += g;
|
| 89 |
+
totalB += b;
|
| 90 |
+
totalA += a;
|
| 91 |
+
count++;
|
| 92 |
+
|
| 93 |
+
const color: Color = { r, g, b, a };
|
| 94 |
+
color.saturation = calculateSaturation(color);
|
| 95 |
+
color.luminance = calculateLuminance(color);
|
| 96 |
+
color.vibrancy = calculateVibrancy(color);
|
| 97 |
+
|
| 98 |
+
samples.push(color);
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
// Calculate average color
|
| 102 |
+
const avgColor: Color = {
|
| 103 |
+
r: Math.round(totalR / count),
|
| 104 |
+
g: Math.round(totalG / count),
|
| 105 |
+
b: Math.round(totalB / count),
|
| 106 |
+
a: Math.round(totalA / count)
|
| 107 |
+
};
|
| 108 |
+
avgColor.saturation = calculateSaturation(avgColor);
|
| 109 |
+
avgColor.luminance = calculateLuminance(avgColor);
|
| 110 |
+
avgColor.vibrancy = calculateVibrancy(avgColor);
|
| 111 |
+
|
| 112 |
+
// Select most vibrant sample if 20% better than average
|
| 113 |
+
let best = avgColor;
|
| 114 |
+
for (const sample of samples) {
|
| 115 |
+
if (sample.vibrancy! > best.vibrancy! * 1.2) {
|
| 116 |
+
best = sample;
|
| 117 |
+
}
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
return best;
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
/**
|
| 124 |
+
* Extract color palette from image in a grid pattern
|
| 125 |
+
*/
|
| 126 |
+
export async function extractPaletteFromImage(
|
| 127 |
+
imageUrl: string,
|
| 128 |
+
gridWidth: number = 8,
|
| 129 |
+
gridHeight: number = 5,
|
| 130 |
+
stretchedWidth: number = 32,
|
| 131 |
+
stretchedHeight: number = 18
|
| 132 |
+
): Promise<Color[]> {
|
| 133 |
+
return new Promise((resolve, reject) => {
|
| 134 |
+
const tempCanvas = document.createElement('canvas');
|
| 135 |
+
tempCanvas.width = stretchedWidth;
|
| 136 |
+
tempCanvas.height = stretchedHeight;
|
| 137 |
+
const tempCtx = tempCanvas.getContext('2d', { willReadFrequently: true });
|
| 138 |
+
|
| 139 |
+
if (!tempCtx) {
|
| 140 |
+
reject(new Error('Failed to get canvas context'));
|
| 141 |
+
return;
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
// Try CORS fetch first
|
| 145 |
+
fetch(imageUrl, { mode: 'cors' })
|
| 146 |
+
.then((response) => response.blob())
|
| 147 |
+
.then((blob) => {
|
| 148 |
+
const img = new Image();
|
| 149 |
+
img.onload = () => {
|
| 150 |
+
tempCtx.drawImage(img, 0, 0, stretchedWidth, stretchedHeight);
|
| 151 |
+
const palette = extractPaletteFromCanvas(
|
| 152 |
+
tempCtx,
|
| 153 |
+
gridWidth,
|
| 154 |
+
gridHeight,
|
| 155 |
+
stretchedWidth,
|
| 156 |
+
stretchedHeight
|
| 157 |
+
);
|
| 158 |
+
resolve(palette);
|
| 159 |
+
URL.revokeObjectURL(img.src);
|
| 160 |
+
};
|
| 161 |
+
img.onerror = () => {
|
| 162 |
+
reject(new Error('Failed to load image'));
|
| 163 |
+
URL.revokeObjectURL(img.src);
|
| 164 |
+
};
|
| 165 |
+
img.src = URL.createObjectURL(blob);
|
| 166 |
+
})
|
| 167 |
+
.catch(() => {
|
| 168 |
+
// Fallback to img.crossOrigin
|
| 169 |
+
const img = new Image();
|
| 170 |
+
img.crossOrigin = 'anonymous';
|
| 171 |
+
img.onload = () => {
|
| 172 |
+
tempCtx.drawImage(img, 0, 0, stretchedWidth, stretchedHeight);
|
| 173 |
+
const palette = extractPaletteFromCanvas(
|
| 174 |
+
tempCtx,
|
| 175 |
+
gridWidth,
|
| 176 |
+
gridHeight,
|
| 177 |
+
stretchedWidth,
|
| 178 |
+
stretchedHeight
|
| 179 |
+
);
|
| 180 |
+
resolve(palette);
|
| 181 |
+
};
|
| 182 |
+
img.onerror = () => reject(new Error('Failed to load image with CORS'));
|
| 183 |
+
img.src = imageUrl;
|
| 184 |
+
});
|
| 185 |
+
});
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
/**
|
| 189 |
+
* Extract palette from canvas context
|
| 190 |
+
*/
|
| 191 |
+
function extractPaletteFromCanvas(
|
| 192 |
+
ctx: CanvasRenderingContext2D,
|
| 193 |
+
gridWidth: number,
|
| 194 |
+
gridHeight: number,
|
| 195 |
+
canvasWidth: number,
|
| 196 |
+
canvasHeight: number
|
| 197 |
+
): Color[] {
|
| 198 |
+
const palette: Color[] = [];
|
| 199 |
+
const cellW = canvasWidth / gridWidth;
|
| 200 |
+
const cellH = canvasHeight / gridHeight;
|
| 201 |
+
|
| 202 |
+
for (let j = 0; j < gridHeight; j++) {
|
| 203 |
+
for (let i = 0; i < gridWidth; i++) {
|
| 204 |
+
const x = Math.floor(i * cellW);
|
| 205 |
+
const y = Math.floor(j * cellH);
|
| 206 |
+
const color = getAverageColor(ctx, x, y, Math.ceil(cellW), Math.ceil(cellH));
|
| 207 |
+
palette.push(color);
|
| 208 |
+
}
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
return palette;
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
/**
|
| 215 |
+
* RGB to HSL conversion
|
| 216 |
+
*/
|
| 217 |
+
export function rgbToHsl(r: number, g: number, b: number): [number, number, number] {
|
| 218 |
+
r /= 255;
|
| 219 |
+
g /= 255;
|
| 220 |
+
b /= 255;
|
| 221 |
+
|
| 222 |
+
const max = Math.max(r, g, b);
|
| 223 |
+
const min = Math.min(r, g, b);
|
| 224 |
+
const delta = max - min;
|
| 225 |
+
|
| 226 |
+
let h = 0;
|
| 227 |
+
let s = 0;
|
| 228 |
+
const l = (max + min) / 2;
|
| 229 |
+
|
| 230 |
+
if (delta !== 0) {
|
| 231 |
+
s = l > 0.5 ? delta / (2 - max - min) : delta / (max + min);
|
| 232 |
+
|
| 233 |
+
if (max === r) {
|
| 234 |
+
h = ((g - b) / delta + (g < b ? 6 : 0)) / 6;
|
| 235 |
+
} else if (max === g) {
|
| 236 |
+
h = ((b - r) / delta + 2) / 6;
|
| 237 |
+
} else {
|
| 238 |
+
h = ((r - g) / delta + 4) / 6;
|
| 239 |
+
}
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
return [h, s, l];
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
/**
|
| 246 |
+
* HSL to RGB conversion
|
| 247 |
+
*/
|
| 248 |
+
export function hslToRgb(h: number, s: number, l: number): [number, number, number] {
|
| 249 |
+
const hue2rgb = (p: number, q: number, t: number) => {
|
| 250 |
+
if (t < 0) t += 1;
|
| 251 |
+
if (t > 1) t -= 1;
|
| 252 |
+
if (t < 1 / 6) return p + (q - p) * 6 * t;
|
| 253 |
+
if (t < 1 / 2) return q;
|
| 254 |
+
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
|
| 255 |
+
return p;
|
| 256 |
+
};
|
| 257 |
+
|
| 258 |
+
let r, g, b;
|
| 259 |
+
|
| 260 |
+
if (s === 0) {
|
| 261 |
+
r = g = b = l;
|
| 262 |
+
} else {
|
| 263 |
+
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
|
| 264 |
+
const p = 2 * l - q;
|
| 265 |
+
r = hue2rgb(p, q, h + 1 / 3);
|
| 266 |
+
g = hue2rgb(p, q, h);
|
| 267 |
+
b = hue2rgb(p, q, h - 1 / 3);
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
/**
|
| 274 |
+
* Get most vibrant color from palette for lyrics highlighting
|
| 275 |
+
*/
|
| 276 |
+
export function getMostVibrantColor(
|
| 277 |
+
palette: Color[],
|
| 278 |
+
minLuminanceThreshold: number = 0.15
|
| 279 |
+
): Color {
|
| 280 |
+
// Filter out very dark colors
|
| 281 |
+
const filteredPalette = palette.filter(
|
| 282 |
+
(color) => calculateLuminance(color) > minLuminanceThreshold
|
| 283 |
+
);
|
| 284 |
+
|
| 285 |
+
if (filteredPalette.length === 0) {
|
| 286 |
+
// Fallback to brightest color if all are too dark
|
| 287 |
+
return palette.reduce((prev, curr) =>
|
| 288 |
+
calculateLuminance(curr) > calculateLuminance(prev) ? curr : prev
|
| 289 |
+
);
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
// Sort by vibrancy and select best
|
| 293 |
+
const selectedColor = filteredPalette.reduce((prev, curr) => {
|
| 294 |
+
const prevVibrancy = prev.vibrancy ?? calculateVibrancy(prev);
|
| 295 |
+
const currVibrancy = curr.vibrancy ?? calculateVibrancy(curr);
|
| 296 |
+
return currVibrancy > prevVibrancy ? curr : prev;
|
| 297 |
+
});
|
| 298 |
+
|
| 299 |
+
// Convert to HSL and boost saturation by 20%
|
| 300 |
+
const [h, s, l] = rgbToHsl(selectedColor.r, selectedColor.g, selectedColor.b);
|
| 301 |
+
const increasedSaturation = Math.min(1.0, s * 1.2);
|
| 302 |
+
const [r, g, b] = hslToRgb(h, increasedSaturation, l);
|
| 303 |
+
|
| 304 |
+
return { r, g, b, a: selectedColor.a };
|
| 305 |
+
}
|
src/lib/utils/colorPalette.ts
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { browser } from '$app/environment';
|
| 2 |
+
type ColorThiefModule = typeof import('colorthief');
|
| 3 |
+
type ColorThiefConstructor = ColorThiefModule extends { default: infer D }
|
| 4 |
+
? D extends new (...args: unknown[]) => unknown
|
| 5 |
+
? D
|
| 6 |
+
: ColorThiefModule extends new (...args: unknown[]) => unknown
|
| 7 |
+
? ColorThiefModule
|
| 8 |
+
: never
|
| 9 |
+
: ColorThiefModule extends new (...args: unknown[]) => unknown
|
| 10 |
+
? ColorThiefModule
|
| 11 |
+
: never;
|
| 12 |
+
type ColorThiefInstance = InstanceType<ColorThiefConstructor>;
|
| 13 |
+
|
| 14 |
+
export interface RGBColor {
|
| 15 |
+
red: number;
|
| 16 |
+
green: number;
|
| 17 |
+
blue: number;
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
export interface PaletteResult {
|
| 21 |
+
dominant: RGBColor;
|
| 22 |
+
accent: RGBColor;
|
| 23 |
+
palette: RGBColor[];
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
const DEFAULT_COLOR: RGBColor = { red: 15, green: 23, blue: 42 };
|
| 27 |
+
|
| 28 |
+
const clamp = (value: number, min = 0, max = 255) => Math.min(max, Math.max(min, value));
|
| 29 |
+
|
| 30 |
+
const mix = (color: RGBColor, target: RGBColor, factor: number): RGBColor => ({
|
| 31 |
+
red: clamp(Math.round(color.red + (target.red - color.red) * factor)),
|
| 32 |
+
green: clamp(Math.round(color.green + (target.green - color.green) * factor)),
|
| 33 |
+
blue: clamp(Math.round(color.blue + (target.blue - color.blue) * factor))
|
| 34 |
+
});
|
| 35 |
+
|
| 36 |
+
const distance = (a: RGBColor, b: RGBColor): number => {
|
| 37 |
+
const dr = a.red - b.red;
|
| 38 |
+
const dg = a.green - b.green;
|
| 39 |
+
const db = a.blue - b.blue;
|
| 40 |
+
return Math.sqrt(dr * dr + dg * dg + db * db);
|
| 41 |
+
};
|
| 42 |
+
|
| 43 |
+
const saturation = ({ red, green, blue }: RGBColor): number => {
|
| 44 |
+
const r = red / 255;
|
| 45 |
+
const g = green / 255;
|
| 46 |
+
const b = blue / 255;
|
| 47 |
+
const max = Math.max(r, g, b);
|
| 48 |
+
const min = Math.min(r, g, b);
|
| 49 |
+
if (max === min) return 0;
|
| 50 |
+
const l = (max + min) / 2;
|
| 51 |
+
const d = max - min;
|
| 52 |
+
return l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
| 53 |
+
};
|
| 54 |
+
|
| 55 |
+
export const rgbToCss = ({ red, green, blue }: RGBColor, alpha?: number): string => {
|
| 56 |
+
const r = Math.round(clamp(red));
|
| 57 |
+
const g = Math.round(clamp(green));
|
| 58 |
+
const b = Math.round(clamp(blue));
|
| 59 |
+
|
| 60 |
+
if (alpha === undefined) {
|
| 61 |
+
return `rgb(${r}, ${g}, ${b})`;
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
const normalizedAlpha = Math.min(Math.max(alpha, 0), 1);
|
| 65 |
+
return `rgba(${r}, ${g}, ${b}, ${normalizedAlpha.toFixed(3)})`;
|
| 66 |
+
};
|
| 67 |
+
|
| 68 |
+
export const lighten = (color: RGBColor, amount: number): RGBColor => mix(color, { red: 255, green: 255, blue: 255 }, amount);
|
| 69 |
+
export const darken = (color: RGBColor, amount: number): RGBColor => mix(color, { red: 0, green: 0, blue: 0 }, amount);
|
| 70 |
+
|
| 71 |
+
/**
|
| 72 |
+
* Calculate relative luminance of a color (WCAG standard)
|
| 73 |
+
* Returns a value between 0 (black) and 1 (white)
|
| 74 |
+
*/
|
| 75 |
+
const getLuminance = ({ red, green, blue }: RGBColor): number => {
|
| 76 |
+
// Convert to sRGB
|
| 77 |
+
const rsRGB = red / 255;
|
| 78 |
+
const gsRGB = green / 255;
|
| 79 |
+
const bsRGB = blue / 255;
|
| 80 |
+
|
| 81 |
+
// Apply gamma correction
|
| 82 |
+
const r = rsRGB <= 0.03928 ? rsRGB / 12.92 : Math.pow((rsRGB + 0.055) / 1.055, 2.4);
|
| 83 |
+
const g = gsRGB <= 0.03928 ? gsRGB / 12.92 : Math.pow((gsRGB + 0.055) / 1.055, 2.4);
|
| 84 |
+
const b = bsRGB <= 0.03928 ? bsRGB / 12.92 : Math.pow((bsRGB + 0.055) / 1.055, 2.4);
|
| 85 |
+
|
| 86 |
+
// Calculate luminance
|
| 87 |
+
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
| 88 |
+
};
|
| 89 |
+
|
| 90 |
+
/**
|
| 91 |
+
* Calculate contrast ratio between two colors (WCAG standard)
|
| 92 |
+
* Returns a value between 1 and 21
|
| 93 |
+
*/
|
| 94 |
+
const getContrastRatio = (color1: RGBColor, color2: RGBColor): number => {
|
| 95 |
+
const lum1 = getLuminance(color1);
|
| 96 |
+
const lum2 = getLuminance(color2);
|
| 97 |
+
const lighter = Math.max(lum1, lum2);
|
| 98 |
+
const darker = Math.min(lum1, lum2);
|
| 99 |
+
return (lighter + 0.05) / (darker + 0.05);
|
| 100 |
+
};
|
| 101 |
+
|
| 102 |
+
/**
|
| 103 |
+
* Ensure a color has sufficient contrast against white and grey text
|
| 104 |
+
* Darkens the color if necessary to meet minimum contrast requirements
|
| 105 |
+
*/
|
| 106 |
+
export const ensureTextContrast = (color: RGBColor): RGBColor => {
|
| 107 |
+
const WHITE: RGBColor = { red: 255, green: 255, blue: 255 };
|
| 108 |
+
const GREY: RGBColor = { red: 156, green: 163, blue: 175 }; // ~gray-400
|
| 109 |
+
|
| 110 |
+
const MIN_CONTRAST_WHITE = 4.5; // WCAG AA standard for normal text
|
| 111 |
+
const MIN_CONTRAST_GREY = 3.0; // Slightly lower for grey text
|
| 112 |
+
|
| 113 |
+
let adjustedColor = { ...color };
|
| 114 |
+
let contrastWhite = getContrastRatio(adjustedColor, WHITE);
|
| 115 |
+
let contrastGrey = getContrastRatio(adjustedColor, GREY);
|
| 116 |
+
let attempts = 0;
|
| 117 |
+
const MAX_ATTEMPTS = 20;
|
| 118 |
+
|
| 119 |
+
// Darken the color until it meets contrast requirements
|
| 120 |
+
while ((contrastWhite < MIN_CONTRAST_WHITE || contrastGrey < MIN_CONTRAST_GREY) && attempts < MAX_ATTEMPTS) {
|
| 121 |
+
adjustedColor = darken(adjustedColor, 0.08);
|
| 122 |
+
contrastWhite = getContrastRatio(adjustedColor, WHITE);
|
| 123 |
+
contrastGrey = getContrastRatio(adjustedColor, GREY);
|
| 124 |
+
attempts++;
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
return adjustedColor;
|
| 128 |
+
};
|
| 129 |
+
|
| 130 |
+
const FALLBACK_RESULT: PaletteResult = {
|
| 131 |
+
dominant: DEFAULT_COLOR,
|
| 132 |
+
accent: { red: 30, green: 64, blue: 175 },
|
| 133 |
+
palette: [DEFAULT_COLOR]
|
| 134 |
+
};
|
| 135 |
+
|
| 136 |
+
const toRgbColor = (value: number[] | undefined | null): RGBColor => ({
|
| 137 |
+
red: clamp(Math.round(value?.[0] ?? DEFAULT_COLOR.red)),
|
| 138 |
+
green: clamp(Math.round(value?.[1] ?? DEFAULT_COLOR.green)),
|
| 139 |
+
blue: clamp(Math.round(value?.[2] ?? DEFAULT_COLOR.blue))
|
| 140 |
+
});
|
| 141 |
+
|
| 142 |
+
const selectAccentColor = (dominant: RGBColor, candidates: RGBColor[]): RGBColor => {
|
| 143 |
+
if (candidates.length === 0) {
|
| 144 |
+
return dominant;
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
const vivid = candidates.filter((color) => saturation(color) > 0.2);
|
| 148 |
+
const ranking = (vivid.length > 0 ? vivid : candidates).slice().sort((a, b) => distance(dominant, b) - distance(dominant, a));
|
| 149 |
+
return ranking[0] ?? dominant;
|
| 150 |
+
};
|
| 151 |
+
|
| 152 |
+
let colorThiefPromise: Promise<ColorThiefInstance | null> | null = null;
|
| 153 |
+
|
| 154 |
+
const loadColorThief = async (): Promise<ColorThiefInstance | null> => {
|
| 155 |
+
if (!browser) return null;
|
| 156 |
+
if (!colorThiefPromise) {
|
| 157 |
+
colorThiefPromise = (import('colorthief') as Promise<ColorThiefModule | { default: ColorThiefConstructor }>)
|
| 158 |
+
.then((module) => {
|
| 159 |
+
const ctor = (module as { default?: ColorThiefConstructor }).default ?? (module as ColorThiefConstructor);
|
| 160 |
+
return new ctor();
|
| 161 |
+
})
|
| 162 |
+
.catch((error) => {
|
| 163 |
+
console.warn('Failed to load Color Thief', error);
|
| 164 |
+
return null;
|
| 165 |
+
}) as Promise<ColorThiefInstance | null>;
|
| 166 |
+
}
|
| 167 |
+
return colorThiefPromise;
|
| 168 |
+
};
|
| 169 |
+
|
| 170 |
+
export async function extractPaletteFromImage(url: string, precision = 32): Promise<PaletteResult> {
|
| 171 |
+
if (!browser) {
|
| 172 |
+
return FALLBACK_RESULT;
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
const colorThief = await loadColorThief();
|
| 176 |
+
if (!colorThief) {
|
| 177 |
+
return FALLBACK_RESULT;
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
const image = new Image();
|
| 181 |
+
image.crossOrigin = 'anonymous';
|
| 182 |
+
image.decoding = 'async';
|
| 183 |
+
|
| 184 |
+
const loadPromise = new Promise<HTMLImageElement>((resolve, reject) => {
|
| 185 |
+
image.onload = () => resolve(image);
|
| 186 |
+
image.onerror = (event) => reject(event);
|
| 187 |
+
});
|
| 188 |
+
|
| 189 |
+
image.src = url;
|
| 190 |
+
|
| 191 |
+
let loadedImage: HTMLImageElement;
|
| 192 |
+
try {
|
| 193 |
+
loadedImage = await loadPromise;
|
| 194 |
+
} catch (error) {
|
| 195 |
+
console.warn('Failed to load image for palette extraction', error);
|
| 196 |
+
return FALLBACK_RESULT;
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
let paletteValues: number[][] = [];
|
| 200 |
+
let dominantValue: number[] | undefined;
|
| 201 |
+
const colorCount = 6;
|
| 202 |
+
const quality = Math.max(1, Math.round(precision / 4));
|
| 203 |
+
try {
|
| 204 |
+
paletteValues = colorThief.getPalette(loadedImage, colorCount, quality) ?? [];
|
| 205 |
+
dominantValue = paletteValues[0] ?? colorThief.getColor(loadedImage, quality);
|
| 206 |
+
} catch (error) {
|
| 207 |
+
console.warn('Color Thief failed to extract palette', error);
|
| 208 |
+
return FALLBACK_RESULT;
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
const paletteColors = paletteValues.map((value) => toRgbColor(value));
|
| 212 |
+
const dominant = toRgbColor(dominantValue);
|
| 213 |
+
const accent = selectAccentColor(dominant, paletteColors.slice(1));
|
| 214 |
+
|
| 215 |
+
return {
|
| 216 |
+
dominant,
|
| 217 |
+
accent,
|
| 218 |
+
palette: paletteColors.length > 0 ? paletteColors : [dominant]
|
| 219 |
+
};
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
/**
|
| 223 |
+
* WebGL-specific palette extraction that follows the YouLyPlus specification:
|
| 224 |
+
* - Extracts exactly 40 colors from an 8x5 grid
|
| 225 |
+
* - Calculates vibrancy (saturation + luminance weighting)
|
| 226 |
+
* - Returns the most vibrant color for lyrics highlighting
|
| 227 |
+
*/
|
| 228 |
+
export async function extractPaletteFromImageWebGL(url: string): Promise<{ palette: RGBColor[], mostVibrant: RGBColor }> {
|
| 229 |
+
if (!browser) {
|
| 230 |
+
const defaultPalette = Array(40).fill(DEFAULT_COLOR);
|
| 231 |
+
return { palette: defaultPalette, mostVibrant: DEFAULT_COLOR };
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
// Constants from specification
|
| 235 |
+
const STRETCHED_GRID_WIDTH = 32;
|
| 236 |
+
const STRETCHED_GRID_HEIGHT = 18;
|
| 237 |
+
const MASTER_PALETTE_TEX_WIDTH = 8;
|
| 238 |
+
const MASTER_PALETTE_TEX_HEIGHT = 5;
|
| 239 |
+
const MIN_LUMINANCE_THRESHOLD = 0.15;
|
| 240 |
+
|
| 241 |
+
// Load image
|
| 242 |
+
const image = new Image();
|
| 243 |
+
image.crossOrigin = 'anonymous';
|
| 244 |
+
image.decoding = 'async';
|
| 245 |
+
|
| 246 |
+
const loadPromise = new Promise<HTMLImageElement>((resolve, reject) => {
|
| 247 |
+
image.onload = () => resolve(image);
|
| 248 |
+
image.onerror = (event) => reject(event);
|
| 249 |
+
});
|
| 250 |
+
|
| 251 |
+
image.src = url;
|
| 252 |
+
|
| 253 |
+
let loadedImage: HTMLImageElement;
|
| 254 |
+
try {
|
| 255 |
+
loadedImage = await loadPromise;
|
| 256 |
+
} catch (error) {
|
| 257 |
+
console.warn('Failed to load image for WebGL palette extraction', error);
|
| 258 |
+
const defaultPalette = Array(40).fill(DEFAULT_COLOR);
|
| 259 |
+
return { palette: defaultPalette, mostVibrant: DEFAULT_COLOR };
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
// Create temporary canvas for color extraction
|
| 263 |
+
const tempCanvas = document.createElement('canvas');
|
| 264 |
+
tempCanvas.width = STRETCHED_GRID_WIDTH;
|
| 265 |
+
tempCanvas.height = STRETCHED_GRID_HEIGHT;
|
| 266 |
+
const tempCtx = tempCanvas.getContext('2d');
|
| 267 |
+
|
| 268 |
+
if (!tempCtx) {
|
| 269 |
+
const defaultPalette = Array(40).fill(DEFAULT_COLOR);
|
| 270 |
+
return { palette: defaultPalette, mostVibrant: DEFAULT_COLOR };
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
// Draw image to canvas
|
| 274 |
+
tempCtx.drawImage(loadedImage, 0, 0, STRETCHED_GRID_WIDTH, STRETCHED_GRID_HEIGHT);
|
| 275 |
+
|
| 276 |
+
// Extract colors from 8x5 grid
|
| 277 |
+
const cellW = STRETCHED_GRID_WIDTH / MASTER_PALETTE_TEX_WIDTH;
|
| 278 |
+
const cellH = STRETCHED_GRID_HEIGHT / MASTER_PALETTE_TEX_HEIGHT;
|
| 279 |
+
const palette: RGBColor[] = [];
|
| 280 |
+
|
| 281 |
+
for (let j = 0; j < MASTER_PALETTE_TEX_HEIGHT; j++) {
|
| 282 |
+
for (let i = 0; i < MASTER_PALETTE_TEX_WIDTH; i++) {
|
| 283 |
+
const x = Math.floor(i * cellW);
|
| 284 |
+
const y = Math.floor(j * cellH);
|
| 285 |
+
let color = getAverageColorWithVibrancy(tempCtx, x, y, Math.ceil(cellW), Math.ceil(cellH));
|
| 286 |
+
|
| 287 |
+
// Very aggressively tone down bright colors for better contrast
|
| 288 |
+
const lum = calculateLuminance(color);
|
| 289 |
+
if (lum > 0.3) {
|
| 290 |
+
// Reduce by up to 65% for very bright colors
|
| 291 |
+
const darkenAmount = (lum - 0.3) * 0.93;
|
| 292 |
+
const darkened = darken(color, darkenAmount);
|
| 293 |
+
color = { ...darkened, vibrancy: color.vibrancy } as RGBColor & { vibrancy: number };
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
palette.push(color);
|
| 297 |
+
}
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
// Find most vibrant color for lyrics (filtering out very dark colors)
|
| 301 |
+
const filteredPalette = palette.filter(color => calculateLuminance(color) > MIN_LUMINANCE_THRESHOLD);
|
| 302 |
+
let mostVibrant = filteredPalette.length > 0 ? filteredPalette[0] : palette[0];
|
| 303 |
+
|
| 304 |
+
for (const color of filteredPalette) {
|
| 305 |
+
if ((color as any).vibrancy > (mostVibrant as any).vibrancy) {
|
| 306 |
+
mostVibrant = color;
|
| 307 |
+
}
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
return { palette, mostVibrant };
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
/**
|
| 314 |
+
* Calculate saturation using HSV model (as per specification)
|
| 315 |
+
*/
|
| 316 |
+
const calculateSaturationHSV = (color: RGBColor): number => {
|
| 317 |
+
const r_norm = color.red / 255;
|
| 318 |
+
const g_norm = color.green / 255;
|
| 319 |
+
const b_norm = color.blue / 255;
|
| 320 |
+
const max = Math.max(r_norm, g_norm, b_norm);
|
| 321 |
+
const min = Math.min(r_norm, g_norm, b_norm);
|
| 322 |
+
const delta = max - min;
|
| 323 |
+
|
| 324 |
+
if (delta < 0.00001 || max < 0.00001) return 0;
|
| 325 |
+
return delta / max; // HSV saturation
|
| 326 |
+
};
|
| 327 |
+
|
| 328 |
+
/**
|
| 329 |
+
* Calculate relative luminance (ITU-R BT.709)
|
| 330 |
+
*/
|
| 331 |
+
const calculateLuminance = (color: RGBColor): number => {
|
| 332 |
+
const linearize = (v: number) => {
|
| 333 |
+
v /= 255;
|
| 334 |
+
return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
|
| 335 |
+
};
|
| 336 |
+
|
| 337 |
+
const r = linearize(color.red);
|
| 338 |
+
const g = linearize(color.green);
|
| 339 |
+
const b = linearize(color.blue);
|
| 340 |
+
|
| 341 |
+
// ITU-R BT.709 weights
|
| 342 |
+
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
| 343 |
+
};
|
| 344 |
+
|
| 345 |
+
/**
|
| 346 |
+
* Calculate vibrancy: combination of saturation and mid-luminance preference
|
| 347 |
+
*/
|
| 348 |
+
const calculateVibrancy = (color: RGBColor): number => {
|
| 349 |
+
const sat = calculateSaturationHSV(color);
|
| 350 |
+
const lum = calculateLuminance(color);
|
| 351 |
+
|
| 352 |
+
// Favor mid-luminance colors (around 0.5)
|
| 353 |
+
const lumFactor = 1.0 - Math.abs(lum - 0.5) * 1.8;
|
| 354 |
+
|
| 355 |
+
// Vibrancy formula from specification
|
| 356 |
+
return (sat * 0.5) + (Math.max(0, lumFactor) * 0.5);
|
| 357 |
+
};
|
| 358 |
+
|
| 359 |
+
/**
|
| 360 |
+
* Extract average color from a region, with vibrancy-based selection
|
| 361 |
+
*/
|
| 362 |
+
const getAverageColorWithVibrancy = (ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number): RGBColor & { vibrancy: number } => {
|
| 363 |
+
const imageData = ctx.getImageData(x, y, w, h);
|
| 364 |
+
const data = imageData.data;
|
| 365 |
+
const samples: Array<RGBColor & { saturation: number; luminance: number; vibrancy: number }> = [];
|
| 366 |
+
|
| 367 |
+
let avgR = 0, avgG = 0, avgB = 0;
|
| 368 |
+
let count = 0;
|
| 369 |
+
|
| 370 |
+
// Sample pixels and calculate average
|
| 371 |
+
for (let i = 0; i < data.length; i += 4) {
|
| 372 |
+
const color = {
|
| 373 |
+
red: data[i],
|
| 374 |
+
green: data[i + 1],
|
| 375 |
+
blue: data[i + 2]
|
| 376 |
+
};
|
| 377 |
+
|
| 378 |
+
avgR += color.red;
|
| 379 |
+
avgG += color.green;
|
| 380 |
+
avgB += color.blue;
|
| 381 |
+
count++;
|
| 382 |
+
|
| 383 |
+
// Store some samples for vibrancy comparison
|
| 384 |
+
if (i % 16 === 0) { // Sample every 4th pixel
|
| 385 |
+
const saturation = calculateSaturationHSV(color);
|
| 386 |
+
const luminance = calculateLuminance(color);
|
| 387 |
+
const vibrancy = calculateVibrancy(color);
|
| 388 |
+
|
| 389 |
+
samples.push({ ...color, saturation, luminance, vibrancy });
|
| 390 |
+
}
|
| 391 |
+
}
|
| 392 |
+
|
| 393 |
+
const avgColor: RGBColor & { vibrancy: number } = {
|
| 394 |
+
red: Math.round(avgR / count),
|
| 395 |
+
green: Math.round(avgG / count),
|
| 396 |
+
blue: Math.round(avgB / count),
|
| 397 |
+
vibrancy: 0
|
| 398 |
+
};
|
| 399 |
+
|
| 400 |
+
avgColor.vibrancy = calculateVibrancy(avgColor);
|
| 401 |
+
|
| 402 |
+
// Select most vibrant sample if it's significantly better (20% threshold)
|
| 403 |
+
let best = avgColor;
|
| 404 |
+
for (const sample of samples) {
|
| 405 |
+
if (sample.vibrancy > best.vibrancy * 1.2) {
|
| 406 |
+
best = { ...sample };
|
| 407 |
+
}
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
return best;
|
| 411 |
+
};
|
src/lib/utils/performance.ts
ADDED
|
@@ -0,0 +1,642 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Performance detection and optimization utilities
|
| 3 |
+
*/
|
| 4 |
+
|
| 5 |
+
export type PerformanceLevel = 'high' | 'medium' | 'low';
|
| 6 |
+
|
| 7 |
+
type PerformanceListener = (level: PerformanceLevel) => void;
|
| 8 |
+
|
| 9 |
+
interface PerformanceMetrics {
|
| 10 |
+
cpuCores: number;
|
| 11 |
+
memory?: number; // GB
|
| 12 |
+
connection?: string;
|
| 13 |
+
gpu?: string;
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
const PERFORMANCE_PRIORITY: Record<PerformanceLevel, number> = {
|
| 17 |
+
high: 3,
|
| 18 |
+
medium: 2,
|
| 19 |
+
low: 1
|
| 20 |
+
};
|
| 21 |
+
|
| 22 |
+
const DEBUG_NAMESPACE = '[tidal-ui] performance';
|
| 23 |
+
|
| 24 |
+
function debugLog(message: string, details?: unknown): void {
|
| 25 |
+
if (typeof console === 'undefined') {
|
| 26 |
+
return;
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
if (typeof details !== 'undefined') {
|
| 30 |
+
console.info(DEBUG_NAMESPACE, message, details);
|
| 31 |
+
} else {
|
| 32 |
+
console.info(DEBUG_NAMESPACE, message);
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
type GraphicsTier = 'advanced' | 'standard' | 'limited' | 'software' | 'none';
|
| 37 |
+
|
| 38 |
+
interface GraphicsAssessment {
|
| 39 |
+
tier: GraphicsTier;
|
| 40 |
+
renderer?: string;
|
| 41 |
+
maxTextureSize?: number | null;
|
| 42 |
+
shadingLanguage?: string | null;
|
| 43 |
+
contextType?: 'webgl2' | 'webgl' | 'experimental-webgl';
|
| 44 |
+
reason?: string;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
const SOFTWARE_RENDERER_KEYWORDS = [
|
| 48 |
+
'swiftshader',
|
| 49 |
+
'llvmpipe',
|
| 50 |
+
'softpipe',
|
| 51 |
+
'software',
|
| 52 |
+
'basic render driver',
|
| 53 |
+
'angle (software',
|
| 54 |
+
'mesa llvmpipe',
|
| 55 |
+
'd3d11warp',
|
| 56 |
+
'gdi generic'
|
| 57 |
+
];
|
| 58 |
+
|
| 59 |
+
function levelFromScore(score: number): PerformanceLevel {
|
| 60 |
+
if (score >= 4) {
|
| 61 |
+
return 'high';
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
if (score >= 1) {
|
| 65 |
+
return 'medium';
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
return 'low';
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
function graphicsTierToLevel(tier: GraphicsTier): PerformanceLevel {
|
| 72 |
+
switch (tier) {
|
| 73 |
+
case 'advanced':
|
| 74 |
+
return 'high';
|
| 75 |
+
case 'standard':
|
| 76 |
+
return 'medium';
|
| 77 |
+
default:
|
| 78 |
+
return 'low';
|
| 79 |
+
}
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
function safeGetNumberParameter(
|
| 83 |
+
context: WebGLRenderingContext | WebGL2RenderingContext,
|
| 84 |
+
parameter: number
|
| 85 |
+
): number | null {
|
| 86 |
+
try {
|
| 87 |
+
const value = context.getParameter(parameter);
|
| 88 |
+
if (typeof value === 'number' && Number.isFinite(value)) {
|
| 89 |
+
return value;
|
| 90 |
+
}
|
| 91 |
+
} catch (error) {
|
| 92 |
+
debugLog('Failed to read WebGL numeric parameter', { parameter, error });
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
return null;
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
function extractGraphicsAssessment(
|
| 99 |
+
context: WebGLRenderingContext | WebGL2RenderingContext,
|
| 100 |
+
contextType: 'webgl2' | 'webgl' | 'experimental-webgl',
|
| 101 |
+
usedFallback: boolean
|
| 102 |
+
): GraphicsAssessment {
|
| 103 |
+
let renderer: string | undefined;
|
| 104 |
+
let shadingLanguage: string | undefined;
|
| 105 |
+
|
| 106 |
+
try {
|
| 107 |
+
const debugInfo = context.getExtension('WEBGL_debug_renderer_info');
|
| 108 |
+
if (debugInfo) {
|
| 109 |
+
renderer = context.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) as string | undefined;
|
| 110 |
+
} else {
|
| 111 |
+
renderer = context.getParameter(context.RENDERER) as string | undefined;
|
| 112 |
+
}
|
| 113 |
+
} catch (error) {
|
| 114 |
+
debugLog('Failed to read WebGL renderer info', error);
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
try {
|
| 118 |
+
shadingLanguage = context.getParameter(context.SHADING_LANGUAGE_VERSION) as string | undefined;
|
| 119 |
+
} catch (error) {
|
| 120 |
+
debugLog('Failed to read WebGL shading language version', error);
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
const maxTextureSize = safeGetNumberParameter(context, context.MAX_TEXTURE_SIZE);
|
| 124 |
+
const normalizedRenderer = renderer?.toLowerCase() ?? '';
|
| 125 |
+
const isSoftwareRenderer = SOFTWARE_RENDERER_KEYWORDS.some((keyword) =>
|
| 126 |
+
normalizedRenderer.includes(keyword)
|
| 127 |
+
);
|
| 128 |
+
|
| 129 |
+
let tier: GraphicsTier;
|
| 130 |
+
let reason: string;
|
| 131 |
+
|
| 132 |
+
if (isSoftwareRenderer) {
|
| 133 |
+
tier = 'software';
|
| 134 |
+
reason = 'Software renderer detected';
|
| 135 |
+
} else if (usedFallback) {
|
| 136 |
+
tier = 'limited';
|
| 137 |
+
reason = 'WebGL context only available with major performance caveat';
|
| 138 |
+
} else if (maxTextureSize !== null && maxTextureSize < 4096) {
|
| 139 |
+
tier = 'limited';
|
| 140 |
+
reason = 'Low max texture size';
|
| 141 |
+
} else if (contextType === 'webgl2') {
|
| 142 |
+
tier = 'advanced';
|
| 143 |
+
reason = 'WebGL2 context available';
|
| 144 |
+
} else {
|
| 145 |
+
tier = 'standard';
|
| 146 |
+
reason = 'WebGL context available';
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
const loseContextExt = context.getExtension('WEBGL_lose_context');
|
| 150 |
+
loseContextExt?.loseContext();
|
| 151 |
+
|
| 152 |
+
return {
|
| 153 |
+
tier,
|
| 154 |
+
reason,
|
| 155 |
+
renderer,
|
| 156 |
+
maxTextureSize,
|
| 157 |
+
shadingLanguage,
|
| 158 |
+
contextType
|
| 159 |
+
};
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
const listeners = new Set<PerformanceListener>();
|
| 163 |
+
let cachedPerformanceLevel: PerformanceLevel | null = null;
|
| 164 |
+
let benchmarkInFlight: Promise<void> | null = null;
|
| 165 |
+
let pendingVisibilityBenchmark = false;
|
| 166 |
+
|
| 167 |
+
const DEFAULT_LEVEL: PerformanceLevel = 'medium';
|
| 168 |
+
|
| 169 |
+
function rank(level: PerformanceLevel): number {
|
| 170 |
+
return PERFORMANCE_PRIORITY[level];
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
function pickConservativeLevel(a: PerformanceLevel, b: PerformanceLevel): PerformanceLevel {
|
| 174 |
+
return rank(a) <= rank(b) ? a : b;
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
function notifyPerformanceLevel(level: PerformanceLevel): void {
|
| 178 |
+
cachedPerformanceLevel = level;
|
| 179 |
+
debugLog('Performance level updated', { level });
|
| 180 |
+
|
| 181 |
+
for (const listener of listeners) {
|
| 182 |
+
try {
|
| 183 |
+
listener(level);
|
| 184 |
+
} catch (error) {
|
| 185 |
+
console.warn('Performance listener threw an error', error);
|
| 186 |
+
}
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
if (typeof window !== 'undefined') {
|
| 190 |
+
window.dispatchEvent(new CustomEvent('tidal:performance-detected', { detail: level }));
|
| 191 |
+
}
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
/**
|
| 195 |
+
* Detect device performance capabilities
|
| 196 |
+
*/
|
| 197 |
+
export function detectPerformance(): PerformanceLevel {
|
| 198 |
+
if (cachedPerformanceLevel) {
|
| 199 |
+
debugLog('Using cached performance level', { level: cachedPerformanceLevel });
|
| 200 |
+
scheduleBenchmark();
|
| 201 |
+
return cachedPerformanceLevel;
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
const baseline = evaluateHardwareBaseline();
|
| 205 |
+
debugLog('Baseline performance estimated', { baseline });
|
| 206 |
+
notifyPerformanceLevel(baseline);
|
| 207 |
+
scheduleBenchmark();
|
| 208 |
+
return baseline;
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
export function subscribeToPerformanceChanges(listener: PerformanceListener): () => void {
|
| 212 |
+
if (cachedPerformanceLevel) {
|
| 213 |
+
listener(cachedPerformanceLevel);
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
listeners.add(listener);
|
| 217 |
+
|
| 218 |
+
return () => {
|
| 219 |
+
listeners.delete(listener);
|
| 220 |
+
};
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
function evaluateHardwareBaseline(): PerformanceLevel {
|
| 224 |
+
if (typeof window === 'undefined') {
|
| 225 |
+
return DEFAULT_LEVEL;
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
const metrics: PerformanceMetrics = {
|
| 229 |
+
cpuCores: navigator.hardwareConcurrency || 4
|
| 230 |
+
};
|
| 231 |
+
|
| 232 |
+
if ('deviceMemory' in navigator) {
|
| 233 |
+
metrics.memory = (navigator as { deviceMemory?: number }).deviceMemory;
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
if ('connection' in navigator) {
|
| 237 |
+
const conn = (navigator as { connection?: { effectiveType?: string } }).connection;
|
| 238 |
+
metrics.connection = conn?.effectiveType;
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
let score = 0;
|
| 242 |
+
|
| 243 |
+
if (metrics.cpuCores >= 10) {
|
| 244 |
+
score += 3;
|
| 245 |
+
} else if (metrics.cpuCores >= 6) {
|
| 246 |
+
score += 2;
|
| 247 |
+
} else if (metrics.cpuCores >= 4) {
|
| 248 |
+
score += 1;
|
| 249 |
+
} else {
|
| 250 |
+
score -= 1;
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
if (metrics.memory) {
|
| 254 |
+
if (metrics.memory >= 12) {
|
| 255 |
+
score += 3;
|
| 256 |
+
} else if (metrics.memory >= 8) {
|
| 257 |
+
score += 2;
|
| 258 |
+
} else if (metrics.memory >= 4) {
|
| 259 |
+
score += 1;
|
| 260 |
+
} else if (metrics.memory < 3) {
|
| 261 |
+
score -= 2;
|
| 262 |
+
}
|
| 263 |
+
} else {
|
| 264 |
+
score += 1;
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
if (metrics.connection) {
|
| 268 |
+
if (metrics.connection === '4g' || metrics.connection === '5g') {
|
| 269 |
+
score += 1;
|
| 270 |
+
} else if (metrics.connection === '2g') {
|
| 271 |
+
score -= 2;
|
| 272 |
+
} else if (metrics.connection === '3g') {
|
| 273 |
+
score -= 1;
|
| 274 |
+
}
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
if (metrics.cpuCores <= 2) {
|
| 278 |
+
score -= 1.5;
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
const cpuLevel = levelFromScore(score);
|
| 282 |
+
const graphics = assessGraphicsSupport();
|
| 283 |
+
|
| 284 |
+
if (graphics.tier === 'none' || graphics.tier === 'software') {
|
| 285 |
+
debugLog('Hardware baseline forced to low due to insufficient graphics support', {
|
| 286 |
+
metrics,
|
| 287 |
+
cpuScore: score,
|
| 288 |
+
cpuLevel,
|
| 289 |
+
graphics
|
| 290 |
+
});
|
| 291 |
+
return 'low';
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
const gpuLevel = graphicsTierToLevel(graphics.tier);
|
| 295 |
+
const baseline = cpuLevel === 'low' || gpuLevel !== 'high' ? 'medium' : 'high';
|
| 296 |
+
|
| 297 |
+
debugLog('Hardware baseline scored', {
|
| 298 |
+
metrics,
|
| 299 |
+
cpuScore: score,
|
| 300 |
+
cpuLevel,
|
| 301 |
+
gpuLevel,
|
| 302 |
+
graphics,
|
| 303 |
+
baseline
|
| 304 |
+
});
|
| 305 |
+
|
| 306 |
+
return baseline;
|
| 307 |
+
}
|
| 308 |
+
|
| 309 |
+
function scheduleBenchmark(): void {
|
| 310 |
+
if (benchmarkInFlight) {
|
| 311 |
+
debugLog('Graphics benchmark already running; skipping new request');
|
| 312 |
+
return;
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
if (typeof window === 'undefined') {
|
| 316 |
+
return;
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
|
| 320 |
+
if (!pendingVisibilityBenchmark) {
|
| 321 |
+
pendingVisibilityBenchmark = true;
|
| 322 |
+
debugLog('Deferring graphics benchmark until tab becomes visible');
|
| 323 |
+
document.addEventListener(
|
| 324 |
+
'visibilitychange',
|
| 325 |
+
() => {
|
| 326 |
+
pendingVisibilityBenchmark = false;
|
| 327 |
+
debugLog('Tab visible; retrying deferred graphics benchmark');
|
| 328 |
+
scheduleBenchmark();
|
| 329 |
+
},
|
| 330 |
+
{ once: true }
|
| 331 |
+
);
|
| 332 |
+
}
|
| 333 |
+
return;
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
debugLog('Launching graphics benchmark to refine performance level');
|
| 337 |
+
benchmarkInFlight = runGraphicsBenchmark()
|
| 338 |
+
.then((result: PerformanceLevel | null) => {
|
| 339 |
+
benchmarkInFlight = null;
|
| 340 |
+
if (!result) {
|
| 341 |
+
debugLog('Graphics benchmark produced no result; keeping current level');
|
| 342 |
+
return;
|
| 343 |
+
}
|
| 344 |
+
|
| 345 |
+
const current = cachedPerformanceLevel ?? result;
|
| 346 |
+
const finalLevel = pickConservativeLevel(current, result);
|
| 347 |
+
if (cachedPerformanceLevel !== finalLevel) {
|
| 348 |
+
notifyPerformanceLevel(finalLevel);
|
| 349 |
+
debugLog('Performance level adjusted after benchmark', {
|
| 350 |
+
initial: current,
|
| 351 |
+
benchmark: result,
|
| 352 |
+
final: finalLevel
|
| 353 |
+
});
|
| 354 |
+
} else {
|
| 355 |
+
debugLog('Benchmark confirmed existing performance level', {
|
| 356 |
+
initial: current,
|
| 357 |
+
benchmark: result
|
| 358 |
+
});
|
| 359 |
+
}
|
| 360 |
+
})
|
| 361 |
+
.catch((error: unknown) => {
|
| 362 |
+
benchmarkInFlight = null;
|
| 363 |
+
debugLog('Graphics benchmark failed to run', error);
|
| 364 |
+
});
|
| 365 |
+
}
|
| 366 |
+
|
| 367 |
+
function assessGraphicsSupport(): GraphicsAssessment {
|
| 368 |
+
if (typeof document === 'undefined') {
|
| 369 |
+
const assessment: GraphicsAssessment = {
|
| 370 |
+
tier: 'limited',
|
| 371 |
+
reason: 'Document unavailable for graphics probe'
|
| 372 |
+
};
|
| 373 |
+
debugLog('Graphics capability detected', assessment);
|
| 374 |
+
return assessment;
|
| 375 |
+
}
|
| 376 |
+
|
| 377 |
+
let assessment: GraphicsAssessment = { tier: 'none', reason: 'Unable to acquire any WebGL context' };
|
| 378 |
+
|
| 379 |
+
try {
|
| 380 |
+
const canvas = document.createElement('canvas');
|
| 381 |
+
const highPerfAttrs: WebGLContextAttributes = {
|
| 382 |
+
powerPreference: 'high-performance',
|
| 383 |
+
antialias: false
|
| 384 |
+
};
|
| 385 |
+
|
| 386 |
+
const gl2 = canvas.getContext('webgl2', highPerfAttrs) as WebGL2RenderingContext | null;
|
| 387 |
+
if (gl2) {
|
| 388 |
+
assessment = extractGraphicsAssessment(gl2, 'webgl2', false);
|
| 389 |
+
} else {
|
| 390 |
+
const strictAttrs: WebGLContextAttributes = {
|
| 391 |
+
powerPreference: 'high-performance',
|
| 392 |
+
antialias: false,
|
| 393 |
+
failIfMajorPerformanceCaveat: true
|
| 394 |
+
};
|
| 395 |
+
const glStrict = canvas.getContext('webgl', strictAttrs) as WebGLRenderingContext | null;
|
| 396 |
+
if (glStrict) {
|
| 397 |
+
assessment = extractGraphicsAssessment(glStrict, 'webgl', false);
|
| 398 |
+
} else {
|
| 399 |
+
const fallback =
|
| 400 |
+
(canvas.getContext('webgl', highPerfAttrs) as WebGLRenderingContext | null) ||
|
| 401 |
+
(canvas.getContext('experimental-webgl', highPerfAttrs) as WebGLRenderingContext | null);
|
| 402 |
+
if (fallback) {
|
| 403 |
+
const contextType = fallback instanceof WebGL2RenderingContext ? 'webgl2' : 'webgl';
|
| 404 |
+
assessment = extractGraphicsAssessment(fallback, contextType, true);
|
| 405 |
+
}
|
| 406 |
+
}
|
| 407 |
+
}
|
| 408 |
+
} catch (error) {
|
| 409 |
+
debugLog('Graphics probing failed', { error });
|
| 410 |
+
assessment = {
|
| 411 |
+
tier: 'limited',
|
| 412 |
+
reason: 'Exception while probing graphics capabilities'
|
| 413 |
+
};
|
| 414 |
+
}
|
| 415 |
+
|
| 416 |
+
debugLog('Graphics capability detected', assessment);
|
| 417 |
+
return assessment;
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
function runGraphicsBenchmark(): Promise<PerformanceLevel | null> {
|
| 421 |
+
if (typeof window === 'undefined' || typeof document === 'undefined') {
|
| 422 |
+
debugLog('Skipping graphics benchmark: window or document unavailable');
|
| 423 |
+
return Promise.resolve(null);
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
+
if (!('requestAnimationFrame' in window)) {
|
| 427 |
+
debugLog('Skipping graphics benchmark: requestAnimationFrame unsupported');
|
| 428 |
+
return Promise.resolve(null);
|
| 429 |
+
}
|
| 430 |
+
|
| 431 |
+
if (document.visibilityState === 'hidden') {
|
| 432 |
+
debugLog('Skipping graphics benchmark: document hidden');
|
| 433 |
+
return Promise.resolve(null);
|
| 434 |
+
}
|
| 435 |
+
|
| 436 |
+
return new Promise((resolve) => {
|
| 437 |
+
let isResolved = false;
|
| 438 |
+
let summary: {
|
| 439 |
+
averageFrame: number;
|
| 440 |
+
worstFrame: number;
|
| 441 |
+
averageWorkload: number;
|
| 442 |
+
stutterRatio: number;
|
| 443 |
+
} | null = null;
|
| 444 |
+
const cleanup = (canvas?: HTMLCanvasElement) => {
|
| 445 |
+
if (canvas && canvas.parentNode) {
|
| 446 |
+
canvas.parentNode.removeChild(canvas);
|
| 447 |
+
}
|
| 448 |
+
};
|
| 449 |
+
|
| 450 |
+
const failSafe = window.setTimeout(() => {
|
| 451 |
+
if (!isResolved) {
|
| 452 |
+
isResolved = true;
|
| 453 |
+
debugLog('Graphics benchmark timed out; falling back to cached level');
|
| 454 |
+
cleanup();
|
| 455 |
+
resolve(null);
|
| 456 |
+
}
|
| 457 |
+
}, 1500);
|
| 458 |
+
|
| 459 |
+
try {
|
| 460 |
+
debugLog('Beginning graphics benchmark workload');
|
| 461 |
+
const canvas = document.createElement('canvas');
|
| 462 |
+
canvas.width = 640;
|
| 463 |
+
canvas.height = 640;
|
| 464 |
+
canvas.style.position = 'fixed';
|
| 465 |
+
canvas.style.left = '-9999px';
|
| 466 |
+
canvas.style.pointerEvents = 'none';
|
| 467 |
+
canvas.style.opacity = '0';
|
| 468 |
+
document.body.appendChild(canvas);
|
| 469 |
+
|
| 470 |
+
const context = canvas.getContext('2d', {
|
| 471 |
+
willReadFrequently: false,
|
| 472 |
+
alpha: false
|
| 473 |
+
});
|
| 474 |
+
|
| 475 |
+
if (!context) {
|
| 476 |
+
window.clearTimeout(failSafe);
|
| 477 |
+
cleanup(canvas);
|
| 478 |
+
debugLog('Canvas context unavailable; forcing low performance mode');
|
| 479 |
+
resolve('low');
|
| 480 |
+
return;
|
| 481 |
+
}
|
| 482 |
+
|
| 483 |
+
let seed = 7;
|
| 484 |
+
const palette = ['#0f172a', '#1e293b', '#1d4ed8', '#2563eb', '#38bdf8'];
|
| 485 |
+
|
| 486 |
+
const random = () => {
|
| 487 |
+
seed = (seed * 1664525 + 1013904223) % 4294967296;
|
| 488 |
+
return seed / 4294967296;
|
| 489 |
+
};
|
| 490 |
+
|
| 491 |
+
const frameTimes: number[] = [];
|
| 492 |
+
const workloadTimes: number[] = [];
|
| 493 |
+
const totalFrames = 60;
|
| 494 |
+
let frameCount = 0;
|
| 495 |
+
let lastTimestamp = 0;
|
| 496 |
+
|
| 497 |
+
const renderWorkload = () => {
|
| 498 |
+
const start = performance.now();
|
| 499 |
+
context.globalCompositeOperation = 'lighter';
|
| 500 |
+
context.clearRect(0, 0, canvas.width, canvas.height);
|
| 501 |
+
for (let i = 0; i < 220; i += 1) {
|
| 502 |
+
const size = 10 + ((i + frameCount) % 18) * 7;
|
| 503 |
+
const x = random() * (canvas.width + size) - size;
|
| 504 |
+
const y = random() * (canvas.height + size) - size;
|
| 505 |
+
context.globalAlpha = 0.14 + ((i % 8) * 0.1);
|
| 506 |
+
context.fillStyle = palette[i % palette.length]!;
|
| 507 |
+
context.fillRect(x, y, size, size);
|
| 508 |
+
}
|
| 509 |
+
context.globalCompositeOperation = 'source-over';
|
| 510 |
+
workloadTimes.push(performance.now() - start);
|
| 511 |
+
};
|
| 512 |
+
|
| 513 |
+
const finish = (result: PerformanceLevel | null) => {
|
| 514 |
+
if (isResolved) return;
|
| 515 |
+
isResolved = true;
|
| 516 |
+
window.clearTimeout(failSafe);
|
| 517 |
+
cleanup(canvas);
|
| 518 |
+
debugLog('Graphics benchmark completed', { result, summary });
|
| 519 |
+
resolve(result);
|
| 520 |
+
};
|
| 521 |
+
|
| 522 |
+
const step = (timestamp: number) => {
|
| 523 |
+
if (frameCount > 0) {
|
| 524 |
+
frameTimes.push(timestamp - lastTimestamp);
|
| 525 |
+
}
|
| 526 |
+
lastTimestamp = timestamp;
|
| 527 |
+
|
| 528 |
+
renderWorkload();
|
| 529 |
+
|
| 530 |
+
frameCount += 1;
|
| 531 |
+
if (frameCount >= totalFrames) {
|
| 532 |
+
const trimmedFrames = frameTimes.slice(5);
|
| 533 |
+
if (!trimmedFrames.length) {
|
| 534 |
+
finish(null);
|
| 535 |
+
return;
|
| 536 |
+
}
|
| 537 |
+
|
| 538 |
+
const averageFrame = trimmedFrames.reduce((sum, value) => sum + value, 0) / trimmedFrames.length;
|
| 539 |
+
const worstFrame = Math.max(...trimmedFrames);
|
| 540 |
+
const averageWorkload = workloadTimes.reduce((sum, value) => sum + value, 0) / workloadTimes.length;
|
| 541 |
+
const stutterRatio = trimmedFrames.filter((value) => value > 24).length / trimmedFrames.length;
|
| 542 |
+
|
| 543 |
+
summary = {
|
| 544 |
+
averageFrame,
|
| 545 |
+
worstFrame,
|
| 546 |
+
averageWorkload,
|
| 547 |
+
stutterRatio
|
| 548 |
+
};
|
| 549 |
+
|
| 550 |
+
let benchmarkLevel: PerformanceLevel = 'high';
|
| 551 |
+
if (averageFrame > 32 || worstFrame > 52 || averageWorkload > 16 || stutterRatio > 0.35) {
|
| 552 |
+
benchmarkLevel = 'low';
|
| 553 |
+
} else if (averageFrame > 24 || worstFrame > 40 || averageWorkload > 10 || stutterRatio > 0.22) {
|
| 554 |
+
benchmarkLevel = 'medium';
|
| 555 |
+
}
|
| 556 |
+
|
| 557 |
+
finish(benchmarkLevel);
|
| 558 |
+
return;
|
| 559 |
+
}
|
| 560 |
+
|
| 561 |
+
window.requestAnimationFrame(step);
|
| 562 |
+
};
|
| 563 |
+
|
| 564 |
+
window.requestAnimationFrame((initialTimestamp) => {
|
| 565 |
+
lastTimestamp = initialTimestamp;
|
| 566 |
+
window.requestAnimationFrame(step);
|
| 567 |
+
});
|
| 568 |
+
} catch (error) {
|
| 569 |
+
console.warn('Graphics benchmark failed', error);
|
| 570 |
+
window.clearTimeout(failSafe);
|
| 571 |
+
cleanup();
|
| 572 |
+
resolve(null);
|
| 573 |
+
}
|
| 574 |
+
});
|
| 575 |
+
}
|
| 576 |
+
|
| 577 |
+
/**
|
| 578 |
+
* Check if user prefers reduced motion
|
| 579 |
+
*/
|
| 580 |
+
export function prefersReducedMotion(): boolean {
|
| 581 |
+
if (typeof window === 'undefined') {
|
| 582 |
+
return false;
|
| 583 |
+
}
|
| 584 |
+
|
| 585 |
+
return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
| 586 |
+
}
|
| 587 |
+
|
| 588 |
+
/**
|
| 589 |
+
* Get optimal blur value based on performance level
|
| 590 |
+
*/
|
| 591 |
+
export function getOptimalBlur(defaultBlur: number, performanceLevel: PerformanceLevel): number {
|
| 592 |
+
switch (performanceLevel) {
|
| 593 |
+
case 'high':
|
| 594 |
+
return defaultBlur;
|
| 595 |
+
case 'medium':
|
| 596 |
+
return Math.round(defaultBlur * 0.6);
|
| 597 |
+
case 'low':
|
| 598 |
+
return Math.round(defaultBlur * 0.3);
|
| 599 |
+
}
|
| 600 |
+
}
|
| 601 |
+
|
| 602 |
+
/**
|
| 603 |
+
* Get optimal saturation value based on performance level
|
| 604 |
+
*/
|
| 605 |
+
export function getOptimalSaturate(
|
| 606 |
+
defaultSaturate: number,
|
| 607 |
+
performanceLevel: PerformanceLevel
|
| 608 |
+
): number {
|
| 609 |
+
switch (performanceLevel) {
|
| 610 |
+
case 'high':
|
| 611 |
+
return defaultSaturate;
|
| 612 |
+
case 'medium':
|
| 613 |
+
return Math.min(defaultSaturate, 130);
|
| 614 |
+
case 'low':
|
| 615 |
+
return 100; // No saturation boost
|
| 616 |
+
}
|
| 617 |
+
}
|
| 618 |
+
|
| 619 |
+
/**
|
| 620 |
+
* Check if animations should be enabled
|
| 621 |
+
*/
|
| 622 |
+
export function shouldEnableAnimations(performanceLevel: PerformanceLevel): boolean {
|
| 623 |
+
if (prefersReducedMotion()) {
|
| 624 |
+
return false;
|
| 625 |
+
}
|
| 626 |
+
|
| 627 |
+
return performanceLevel !== 'low';
|
| 628 |
+
}
|
| 629 |
+
|
| 630 |
+
/**
|
| 631 |
+
* Get optimal number of gradient colors based on performance
|
| 632 |
+
*/
|
| 633 |
+
export function getOptimalGradientColors(performanceLevel: PerformanceLevel): number {
|
| 634 |
+
switch (performanceLevel) {
|
| 635 |
+
case 'high':
|
| 636 |
+
return 5;
|
| 637 |
+
case 'medium':
|
| 638 |
+
return 3;
|
| 639 |
+
case 'low':
|
| 640 |
+
return 2;
|
| 641 |
+
}
|
| 642 |
+
}
|
src/lib/utils/songlink.ts
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Songlink API utilities for converting streaming links between platforms
|
| 3 |
+
*/
|
| 4 |
+
|
| 5 |
+
export interface SonglinkResponse {
|
| 6 |
+
entityUniqueId: string;
|
| 7 |
+
userCountry: string;
|
| 8 |
+
pageUrl: string;
|
| 9 |
+
entitiesByUniqueId: Record<string, SonglinkEntity>;
|
| 10 |
+
linksByPlatform: Record<string, SonglinkPlatformLink>;
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
export interface SonglinkEntity {
|
| 14 |
+
id: string;
|
| 15 |
+
type: 'song' | 'album';
|
| 16 |
+
title?: string;
|
| 17 |
+
artistName?: string;
|
| 18 |
+
thumbnailUrl?: string;
|
| 19 |
+
thumbnailWidth?: number;
|
| 20 |
+
thumbnailHeight?: number;
|
| 21 |
+
apiProvider: string;
|
| 22 |
+
platforms: string[];
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
export interface SonglinkPlatformLink {
|
| 26 |
+
country: string;
|
| 27 |
+
url: string;
|
| 28 |
+
nativeAppUriMobile?: string;
|
| 29 |
+
nativeAppUriDesktop?: string;
|
| 30 |
+
entityUniqueId: string;
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
export interface TidalInfo {
|
| 34 |
+
type: 'track' | 'album' | 'playlist';
|
| 35 |
+
id: string;
|
| 36 |
+
url: string;
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
/**
|
| 40 |
+
* Supported streaming platforms
|
| 41 |
+
*/
|
| 42 |
+
export const SUPPORTED_PLATFORMS = [
|
| 43 |
+
{ id: 'spotify', name: 'Spotify', pattern: /spotify\.com\/(track|album|playlist)/ },
|
| 44 |
+
{ id: 'appleMusic', name: 'Apple Music', pattern: /music\.apple\.com/ },
|
| 45 |
+
{ id: 'youtubeMusic', name: 'YouTube Music', pattern: /music\.youtube\.com/ },
|
| 46 |
+
{ id: 'deezer', name: 'Deezer', pattern: /deezer\.com\/(track|album|playlist)/ },
|
| 47 |
+
{ id: 'soundcloud', name: 'SoundCloud', pattern: /soundcloud\.com/ },
|
| 48 |
+
{ id: 'tidal', name: 'TIDAL', pattern: /tidal\.com\/(browse\/)?(track|album|playlist)/ },
|
| 49 |
+
{ id: 'amazon', name: 'Amazon Music', pattern: /music\.amazon\.com/ },
|
| 50 |
+
{ id: 'pandora', name: 'Pandora', pattern: /pandora\.com/ }
|
| 51 |
+
] as const;
|
| 52 |
+
|
| 53 |
+
/**
|
| 54 |
+
* Detect if URL is from a supported streaming platform
|
| 55 |
+
*/
|
| 56 |
+
export function isSupportedStreamingUrl(url: string): boolean {
|
| 57 |
+
try {
|
| 58 |
+
const parsedUrl = new URL(url);
|
| 59 |
+
return SUPPORTED_PLATFORMS.some((platform) => platform.pattern.test(parsedUrl.href));
|
| 60 |
+
} catch {
|
| 61 |
+
return false;
|
| 62 |
+
}
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
/**
|
| 66 |
+
* Detect if URL is a Spotify playlist
|
| 67 |
+
*/
|
| 68 |
+
export function isSpotifyPlaylistUrl(url: string): boolean {
|
| 69 |
+
try {
|
| 70 |
+
const parsedUrl = new URL(url);
|
| 71 |
+
return /spotify\.com\/playlist/.test(parsedUrl.href);
|
| 72 |
+
} catch {
|
| 73 |
+
return false;
|
| 74 |
+
}
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
/**
|
| 78 |
+
* Extract TIDAL information from Songlink response
|
| 79 |
+
*/
|
| 80 |
+
export function extractTidalInfo(response: SonglinkResponse): TidalInfo | null {
|
| 81 |
+
// Find TIDAL link in linksByPlatform
|
| 82 |
+
const tidalLink = response.linksByPlatform.tidal;
|
| 83 |
+
if (!tidalLink?.url) {
|
| 84 |
+
return null;
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
// Parse TIDAL URL to extract type and ID
|
| 88 |
+
const url = tidalLink.url;
|
| 89 |
+
const match = url.match(/tidal\.com\/(?:browse\/)?(\w+)\/(\d+)/);
|
| 90 |
+
|
| 91 |
+
if (!match) {
|
| 92 |
+
return null;
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
const [, type, id] = match;
|
| 96 |
+
|
| 97 |
+
// Map Songlink types to our types
|
| 98 |
+
let tidalType: 'track' | 'album' | 'playlist';
|
| 99 |
+
if (type === 'track' || type === 'song') {
|
| 100 |
+
tidalType = 'track';
|
| 101 |
+
} else if (type === 'album') {
|
| 102 |
+
tidalType = 'album';
|
| 103 |
+
} else if (type === 'playlist') {
|
| 104 |
+
tidalType = 'playlist';
|
| 105 |
+
} else {
|
| 106 |
+
return null;
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
// Validate that the ID is numeric
|
| 110 |
+
const numericId = Number(id);
|
| 111 |
+
if (!Number.isFinite(numericId) || numericId <= 0) {
|
| 112 |
+
console.warn('TIDAL ID is not a valid number:', id);
|
| 113 |
+
return null;
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
return {
|
| 117 |
+
type: tidalType,
|
| 118 |
+
id,
|
| 119 |
+
url
|
| 120 |
+
};
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
/**
|
| 124 |
+
* Fetch Songlink data for a given URL
|
| 125 |
+
*/
|
| 126 |
+
export async function fetchSonglinkData(
|
| 127 |
+
url: string,
|
| 128 |
+
options?: {
|
| 129 |
+
userCountry?: string;
|
| 130 |
+
songIfSingle?: boolean;
|
| 131 |
+
}
|
| 132 |
+
): Promise<SonglinkResponse> {
|
| 133 |
+
const params = new URLSearchParams();
|
| 134 |
+
params.set('url', url);
|
| 135 |
+
|
| 136 |
+
if (options?.userCountry) {
|
| 137 |
+
params.set('userCountry', options.userCountry);
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
if (options?.songIfSingle !== undefined) {
|
| 141 |
+
params.set('songIfSingle', options.songIfSingle.toString());
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
// Randomly prefer backup API 50% of the time for load balancing
|
| 145 |
+
const preferBackup = Math.random() < 0.5;
|
| 146 |
+
if (preferBackup) {
|
| 147 |
+
params.set('preferBackup', 'true');
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
const apiUrl = `/api/songlink?${params.toString()}`;
|
| 151 |
+
|
| 152 |
+
const response = await fetch(apiUrl);
|
| 153 |
+
|
| 154 |
+
if (!response.ok) {
|
| 155 |
+
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
| 156 |
+
throw new Error(error.error || `Failed to fetch Songlink data: ${response.status}`);
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
return response.json();
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
/**
|
| 163 |
+
* Convert a streaming platform URL to TIDAL information
|
| 164 |
+
*/
|
| 165 |
+
export async function convertToTidal(
|
| 166 |
+
url: string,
|
| 167 |
+
options?: {
|
| 168 |
+
userCountry?: string;
|
| 169 |
+
songIfSingle?: boolean;
|
| 170 |
+
}
|
| 171 |
+
): Promise<TidalInfo | null> {
|
| 172 |
+
try {
|
| 173 |
+
const songlinkData = await fetchSonglinkData(url, options);
|
| 174 |
+
return extractTidalInfo(songlinkData);
|
| 175 |
+
} catch (error) {
|
| 176 |
+
console.error('Failed to convert URL to TIDAL:', error);
|
| 177 |
+
return null;
|
| 178 |
+
}
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
/**
|
| 182 |
+
* Get platform name from URL
|
| 183 |
+
*/
|
| 184 |
+
export function getPlatformName(url: string): string | null {
|
| 185 |
+
try {
|
| 186 |
+
const parsedUrl = new URL(url);
|
| 187 |
+
const platform = SUPPORTED_PLATFORMS.find((p) => p.pattern.test(parsedUrl.href));
|
| 188 |
+
return platform?.name || null;
|
| 189 |
+
} catch {
|
| 190 |
+
return null;
|
| 191 |
+
}
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
/**
|
| 195 |
+
* Convert a Spotify playlist to an array of track URLs for Songlink conversion
|
| 196 |
+
*/
|
| 197 |
+
export async function convertSpotifyPlaylist(playlistUrl: string): Promise<string[]> {
|
| 198 |
+
// Strip query parameters from the URL
|
| 199 |
+
let cleanUrl = playlistUrl;
|
| 200 |
+
try {
|
| 201 |
+
const url = new URL(playlistUrl);
|
| 202 |
+
cleanUrl = `${url.origin}${url.pathname}`;
|
| 203 |
+
} catch (e) {
|
| 204 |
+
// If URL parsing fails, use original URL
|
| 205 |
+
console.warn('Failed to parse playlist URL, using as-is:', e);
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
const response = await fetch('/api/spotify-playlist', {
|
| 209 |
+
method: 'POST',
|
| 210 |
+
headers: {
|
| 211 |
+
'Content-Type': 'application/json'
|
| 212 |
+
},
|
| 213 |
+
body: JSON.stringify({ playlistUrl: cleanUrl })
|
| 214 |
+
});
|
| 215 |
+
|
| 216 |
+
if (!response.ok) {
|
| 217 |
+
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
| 218 |
+
throw new Error(error.error || `Failed to fetch Spotify playlist: ${response.status}`);
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
const data = await response.json();
|
| 222 |
+
return data.songLinks;
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
/**
|
| 226 |
+
* Extract TIDAL song entity from Songlink response for display
|
| 227 |
+
* Prioritizes the entityUniqueId, then falls back to any TIDAL_SONG entity
|
| 228 |
+
*/
|
| 229 |
+
export function extractTidalSongEntity(response: SonglinkResponse): SonglinkEntity | null {
|
| 230 |
+
// First try the primary entity if it's a TIDAL song
|
| 231 |
+
const primaryEntity = response.entitiesByUniqueId[response.entityUniqueId];
|
| 232 |
+
if (primaryEntity?.apiProvider === 'tidal') {
|
| 233 |
+
return primaryEntity;
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
// Fallback: find any TIDAL_SONG entity
|
| 237 |
+
const tidalKey = Object.keys(response.entitiesByUniqueId).find((key) =>
|
| 238 |
+
key.startsWith('TIDAL_SONG::')
|
| 239 |
+
);
|
| 240 |
+
|
| 241 |
+
return tidalKey ? response.entitiesByUniqueId[tidalKey] || null : null;
|
| 242 |
+
}
|
src/lib/utils/urlParser.ts
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Utility functions for parsing Tidal URLs
|
| 3 |
+
*/
|
| 4 |
+
|
| 5 |
+
export type TidalUrlType = 'track' | 'album' | 'artist' | 'playlist' | 'unknown';
|
| 6 |
+
|
| 7 |
+
export interface TidalUrlParseResult {
|
| 8 |
+
type: TidalUrlType;
|
| 9 |
+
trackId?: number;
|
| 10 |
+
albumId?: number;
|
| 11 |
+
artistId?: number;
|
| 12 |
+
playlistId?: string;
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
/**
|
| 16 |
+
* Parse a Tidal URL and extract the relevant IDs
|
| 17 |
+
*
|
| 18 |
+
* Supported URL formats:
|
| 19 |
+
* - Track: https://tidal.com/album/{albumId}/track/{trackId}
|
| 20 |
+
* - Album: https://tidal.com/album/{albumId}
|
| 21 |
+
* - Artist: https://tidal.com/artist/{artistId}
|
| 22 |
+
* - Playlist: https://tidal.com/playlist/{playlistId}
|
| 23 |
+
*
|
| 24 |
+
* Also supports:
|
| 25 |
+
* - listen.tidal.com domain
|
| 26 |
+
* - browse/ prefix (e.g., https://tidal.com/browse/track/{trackId})
|
| 27 |
+
*/
|
| 28 |
+
export function parseTidalUrl(url: string): TidalUrlParseResult {
|
| 29 |
+
try {
|
| 30 |
+
// Clean up the URL - remove whitespace
|
| 31 |
+
const cleanUrl = url.trim();
|
| 32 |
+
|
| 33 |
+
// Parse the URL
|
| 34 |
+
let urlObj: URL;
|
| 35 |
+
try {
|
| 36 |
+
urlObj = new URL(cleanUrl);
|
| 37 |
+
} catch {
|
| 38 |
+
// If it's not a valid URL, try adding https://
|
| 39 |
+
urlObj = new URL(`https://${cleanUrl}`);
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
// Check if it's a Tidal domain
|
| 43 |
+
const hostname = urlObj.hostname.toLowerCase();
|
| 44 |
+
if (!hostname.includes('tidal.com')) {
|
| 45 |
+
return { type: 'unknown' };
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
const pathname = urlObj.pathname;
|
| 49 |
+
|
| 50 |
+
// Track URL patterns:
|
| 51 |
+
// /album/{albumId}/track/{trackId}
|
| 52 |
+
// /browse/track/{trackId}
|
| 53 |
+
const trackMatch = pathname.match(/\/(?:album\/\d+\/)?track\/(\d+)/);
|
| 54 |
+
if (trackMatch) {
|
| 55 |
+
const trackId = parseInt(trackMatch[1]!, 10);
|
| 56 |
+
if (!isNaN(trackId)) {
|
| 57 |
+
// Also try to extract album ID if present
|
| 58 |
+
const albumMatch = pathname.match(/\/album\/(\d+)\//);
|
| 59 |
+
const albumId = albumMatch ? parseInt(albumMatch[1]!, 10) : undefined;
|
| 60 |
+
|
| 61 |
+
return {
|
| 62 |
+
type: 'track',
|
| 63 |
+
trackId,
|
| 64 |
+
albumId: albumId && !isNaN(albumId) ? albumId : undefined
|
| 65 |
+
};
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
// Album URL pattern: /album/{albumId}
|
| 70 |
+
const albumMatch = pathname.match(/\/album\/(\d+)(?:\/|$)/);
|
| 71 |
+
if (albumMatch) {
|
| 72 |
+
const albumId = parseInt(albumMatch[1]!, 10);
|
| 73 |
+
if (!isNaN(albumId)) {
|
| 74 |
+
return {
|
| 75 |
+
type: 'album',
|
| 76 |
+
albumId
|
| 77 |
+
};
|
| 78 |
+
}
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
// Artist URL pattern: /artist/{artistId}
|
| 82 |
+
const artistMatch = pathname.match(/\/artist\/(\d+)/);
|
| 83 |
+
if (artistMatch) {
|
| 84 |
+
const artistId = parseInt(artistMatch[1]!, 10);
|
| 85 |
+
if (!isNaN(artistId)) {
|
| 86 |
+
return {
|
| 87 |
+
type: 'artist',
|
| 88 |
+
artistId
|
| 89 |
+
};
|
| 90 |
+
}
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
// Playlist URL pattern: /playlist/{playlistId}
|
| 94 |
+
// Note: Playlist IDs are UUIDs (strings), not numbers
|
| 95 |
+
const playlistMatch = pathname.match(/\/playlist\/([a-f0-9-]+)/i);
|
| 96 |
+
if (playlistMatch) {
|
| 97 |
+
return {
|
| 98 |
+
type: 'playlist',
|
| 99 |
+
playlistId: playlistMatch[1]!
|
| 100 |
+
};
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
return { type: 'unknown' };
|
| 104 |
+
} catch (error) {
|
| 105 |
+
console.error('Failed to parse Tidal URL:', error);
|
| 106 |
+
return { type: 'unknown' };
|
| 107 |
+
}
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
/**
|
| 111 |
+
* Validate if a string looks like a Tidal URL
|
| 112 |
+
*/
|
| 113 |
+
export function isTidalUrl(url: string): boolean {
|
| 114 |
+
const cleaned = url.trim().toLowerCase();
|
| 115 |
+
return cleaned.includes('tidal.com') &&
|
| 116 |
+
(cleaned.startsWith('http://') ||
|
| 117 |
+
cleaned.startsWith('https://') ||
|
| 118 |
+
cleaned.startsWith('tidal.com') ||
|
| 119 |
+
cleaned.startsWith('listen.tidal.com'));
|
| 120 |
+
}
|
src/lib/utils/webglShaders.ts
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* WebGL shader programs for dynamic background rendering
|
| 3 |
+
*/
|
| 4 |
+
|
| 5 |
+
// Vertex shader (shared by all passes)
|
| 6 |
+
export const vertexShaderSource = `
|
| 7 |
+
attribute vec2 a_position;
|
| 8 |
+
attribute vec2 a_texCoord;
|
| 9 |
+
varying vec2 v_uv;
|
| 10 |
+
|
| 11 |
+
void main() {
|
| 12 |
+
gl_Position = vec4(a_position, 0.0, 1.0);
|
| 13 |
+
v_uv = a_texCoord;
|
| 14 |
+
}
|
| 15 |
+
`;
|
| 16 |
+
|
| 17 |
+
// Pass 1: Cell State Update (GPGPU)
|
| 18 |
+
// Updates animation state for each of the 40 cells
|
| 19 |
+
export const updateStateShaderSource = `
|
| 20 |
+
precision highp float;
|
| 21 |
+
|
| 22 |
+
uniform sampler2D u_currentStateTexture;
|
| 23 |
+
uniform float u_deltaTime;
|
| 24 |
+
uniform float u_time;
|
| 25 |
+
varying vec2 v_uv;
|
| 26 |
+
|
| 27 |
+
// Simple pseudo-random function
|
| 28 |
+
float random(vec2 co) {
|
| 29 |
+
return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
void main() {
|
| 33 |
+
vec4 currentState = texture2D(u_currentStateTexture, v_uv);
|
| 34 |
+
float sourceIdx_norm = currentState.r;
|
| 35 |
+
float targetIdx_norm = currentState.g;
|
| 36 |
+
float progress = currentState.b;
|
| 37 |
+
float speed = currentState.a * 10.0;
|
| 38 |
+
|
| 39 |
+
// Advance transition progress
|
| 40 |
+
progress += speed * u_deltaTime;
|
| 41 |
+
|
| 42 |
+
if (progress >= 1.0) {
|
| 43 |
+
// Transition complete - pick new target color
|
| 44 |
+
progress = fract(progress);
|
| 45 |
+
sourceIdx_norm = targetIdx_norm;
|
| 46 |
+
|
| 47 |
+
// Generate new random target index (0-39 mapped to 0.0-1.0)
|
| 48 |
+
vec2 seed = v_uv + vec2(u_time * 0.001, progress);
|
| 49 |
+
float newTargetIdx = floor(random(seed) * 40.0);
|
| 50 |
+
targetIdx_norm = newTargetIdx / 39.0;
|
| 51 |
+
|
| 52 |
+
// Generate new random speed
|
| 53 |
+
seed = v_uv + vec2(u_time * 0.002, progress * 2.0);
|
| 54 |
+
speed = (random(seed) * 0.5 + 0.5) * 0.48;
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
gl_FragColor = vec4(sourceIdx_norm, targetIdx_norm, progress, speed / 10.0);
|
| 58 |
+
}
|
| 59 |
+
`;
|
| 60 |
+
|
| 61 |
+
// Pass 2: Color Rendering
|
| 62 |
+
// Renders the 8x5 grid with smooth color transitions
|
| 63 |
+
export const colorRenderShaderSource = `
|
| 64 |
+
precision highp float;
|
| 65 |
+
|
| 66 |
+
uniform sampler2D u_paletteTexture;
|
| 67 |
+
uniform sampler2D u_cellStateTexture;
|
| 68 |
+
uniform float u_songPaletteTransitionProgress;
|
| 69 |
+
uniform float u_scrollOffset;
|
| 70 |
+
varying vec2 v_uv;
|
| 71 |
+
|
| 72 |
+
// Get color from master palette (8x10 texture)
|
| 73 |
+
// y_offset = 0.0 for previous palette, 5.0 for target palette
|
| 74 |
+
vec4 getColorFromMasterPalette(int index, float y_offset) {
|
| 75 |
+
float texY_row = floor(float(index) / 8.0);
|
| 76 |
+
float texX_col = mod(float(index), 8.0);
|
| 77 |
+
float u = (texX_col + 0.5) / 8.0;
|
| 78 |
+
float v = (texY_row + y_offset + 0.5) / 10.0;
|
| 79 |
+
return texture2D(u_paletteTexture, vec2(u, v));
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
// Get interpolated color for a cell
|
| 83 |
+
vec4 getCellColor(vec2 uv) {
|
| 84 |
+
vec4 cellState = texture2D(u_cellStateTexture, uv);
|
| 85 |
+
int sourceColorIndex = int(cellState.r * 39.0 + 0.5);
|
| 86 |
+
int targetColorIndex = int(cellState.g * 39.0 + 0.5);
|
| 87 |
+
float fadeProgress = cellState.b;
|
| 88 |
+
|
| 89 |
+
// Get colors from both palette layers
|
| 90 |
+
vec4 prevPalette_source = getColorFromMasterPalette(sourceColorIndex, 0.0);
|
| 91 |
+
vec4 targetPalette_source = getColorFromMasterPalette(sourceColorIndex, 5.0);
|
| 92 |
+
vec4 colorA = mix(prevPalette_source, targetPalette_source, u_songPaletteTransitionProgress);
|
| 93 |
+
|
| 94 |
+
vec4 prevPalette_target = getColorFromMasterPalette(targetColorIndex, 0.0);
|
| 95 |
+
vec4 targetPalette_target = getColorFromMasterPalette(targetColorIndex, 5.0);
|
| 96 |
+
vec4 colorB = mix(prevPalette_target, targetPalette_target, u_songPaletteTransitionProgress);
|
| 97 |
+
|
| 98 |
+
return mix(colorA, colorB, fadeProgress);
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
void main() {
|
| 102 |
+
float scrolledX = v_uv.x - u_scrollOffset;
|
| 103 |
+
|
| 104 |
+
// Wrap around for seamless horizontal scrolling
|
| 105 |
+
scrolledX = fract(scrolledX);
|
| 106 |
+
|
| 107 |
+
float cellX = scrolledX * 8.0;
|
| 108 |
+
float cellXFrac = fract(cellX);
|
| 109 |
+
|
| 110 |
+
// Sample adjacent cells and interpolate for smoothness
|
| 111 |
+
vec2 cell1UV = vec2(scrolledX, v_uv.y);
|
| 112 |
+
vec2 cell2UV = vec2(fract(scrolledX + 1.0/8.0), v_uv.y);
|
| 113 |
+
|
| 114 |
+
vec4 color1 = getCellColor(cell1UV);
|
| 115 |
+
vec4 color2 = getCellColor(cell2UV);
|
| 116 |
+
|
| 117 |
+
gl_FragColor = mix(color1, color2, cellXFrac);
|
| 118 |
+
}
|
| 119 |
+
`;
|
| 120 |
+
|
| 121 |
+
// Pass 3 & 4: Gaussian Blur
|
| 122 |
+
// Separable 9-tap Gaussian blur (horizontal and vertical)
|
| 123 |
+
export const blurFragmentShaderSource = `
|
| 124 |
+
precision highp float;
|
| 125 |
+
|
| 126 |
+
uniform sampler2D u_image;
|
| 127 |
+
uniform vec2 u_resolution;
|
| 128 |
+
uniform vec2 u_direction;
|
| 129 |
+
varying vec2 v_uv;
|
| 130 |
+
|
| 131 |
+
void main() {
|
| 132 |
+
vec2 texelSize = 1.0 / u_resolution;
|
| 133 |
+
vec3 result = texture2D(u_image, v_uv).rgb * 0.227027;
|
| 134 |
+
|
| 135 |
+
// 9-tap Gaussian kernel
|
| 136 |
+
result += texture2D(u_image, v_uv + texelSize * u_direction * 1.0).rgb * 0.1945946;
|
| 137 |
+
result += texture2D(u_image, v_uv - texelSize * u_direction * 1.0).rgb * 0.1945946;
|
| 138 |
+
result += texture2D(u_image, v_uv + texelSize * u_direction * 2.0).rgb * 0.1216216;
|
| 139 |
+
result += texture2D(u_image, v_uv - texelSize * u_direction * 2.0).rgb * 0.1216216;
|
| 140 |
+
result += texture2D(u_image, v_uv + texelSize * u_direction * 3.0).rgb * 0.05405405;
|
| 141 |
+
result += texture2D(u_image, v_uv - texelSize * u_direction * 3.0).rgb * 0.05405405;
|
| 142 |
+
result += texture2D(u_image, v_uv + texelSize * u_direction * 4.0).rgb * 0.01621621;
|
| 143 |
+
result += texture2D(u_image, v_uv - texelSize * u_direction * 4.0).rgb * 0.01621621;
|
| 144 |
+
|
| 145 |
+
gl_FragColor = vec4(result, 1.0);
|
| 146 |
+
}
|
| 147 |
+
`;
|
| 148 |
+
|
| 149 |
+
/**
|
| 150 |
+
* Create and compile a shader
|
| 151 |
+
*/
|
| 152 |
+
export function createShader(
|
| 153 |
+
gl: WebGLRenderingContext,
|
| 154 |
+
type: number,
|
| 155 |
+
source: string
|
| 156 |
+
): WebGLShader | null {
|
| 157 |
+
const shader = gl.createShader(type);
|
| 158 |
+
if (!shader) return null;
|
| 159 |
+
|
| 160 |
+
gl.shaderSource(shader, source);
|
| 161 |
+
gl.compileShader(shader);
|
| 162 |
+
|
| 163 |
+
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
|
| 164 |
+
console.error('Shader compilation error:', gl.getShaderInfoLog(shader));
|
| 165 |
+
gl.deleteShader(shader);
|
| 166 |
+
return null;
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
return shader;
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
/**
|
| 173 |
+
* Create and link a shader program
|
| 174 |
+
*/
|
| 175 |
+
export function createProgram(
|
| 176 |
+
gl: WebGLRenderingContext,
|
| 177 |
+
vertexShader: WebGLShader,
|
| 178 |
+
fragmentShader: WebGLShader
|
| 179 |
+
): WebGLProgram | null {
|
| 180 |
+
const program = gl.createProgram();
|
| 181 |
+
if (!program) return null;
|
| 182 |
+
|
| 183 |
+
gl.attachShader(program, vertexShader);
|
| 184 |
+
gl.attachShader(program, fragmentShader);
|
| 185 |
+
gl.linkProgram(program);
|
| 186 |
+
|
| 187 |
+
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
|
| 188 |
+
console.error('Program linking error:', gl.getProgramInfoLog(program));
|
| 189 |
+
gl.deleteProgram(program);
|
| 190 |
+
return null;
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
return program;
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
/**
|
| 197 |
+
* Set up a full-screen quad (two triangles)
|
| 198 |
+
*/
|
| 199 |
+
export function setupQuad(gl: WebGLRenderingContext): void {
|
| 200 |
+
const positions = new Float32Array([
|
| 201 |
+
-1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0
|
| 202 |
+
]);
|
| 203 |
+
|
| 204 |
+
const texCoords = new Float32Array([0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0]);
|
| 205 |
+
|
| 206 |
+
const positionBuffer = gl.createBuffer();
|
| 207 |
+
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
|
| 208 |
+
gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);
|
| 209 |
+
|
| 210 |
+
const texCoordBuffer = gl.createBuffer();
|
| 211 |
+
gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
|
| 212 |
+
gl.bufferData(gl.ARRAY_BUFFER, texCoords, gl.STATIC_DRAW);
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
/**
|
| 216 |
+
* Create a texture
|
| 217 |
+
*/
|
| 218 |
+
export function createTexture(
|
| 219 |
+
gl: WebGLRenderingContext,
|
| 220 |
+
width: number,
|
| 221 |
+
height: number,
|
| 222 |
+
data: Uint8Array | null = null
|
| 223 |
+
): WebGLTexture | null {
|
| 224 |
+
const texture = gl.createTexture();
|
| 225 |
+
if (!texture) return null;
|
| 226 |
+
|
| 227 |
+
gl.bindTexture(gl.TEXTURE_2D, texture);
|
| 228 |
+
gl.texImage2D(
|
| 229 |
+
gl.TEXTURE_2D,
|
| 230 |
+
0,
|
| 231 |
+
gl.RGBA,
|
| 232 |
+
width,
|
| 233 |
+
height,
|
| 234 |
+
0,
|
| 235 |
+
gl.RGBA,
|
| 236 |
+
gl.UNSIGNED_BYTE,
|
| 237 |
+
data
|
| 238 |
+
);
|
| 239 |
+
|
| 240 |
+
// Use nearest neighbor filtering for palette and state textures
|
| 241 |
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
|
| 242 |
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
|
| 243 |
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
| 244 |
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
| 245 |
+
|
| 246 |
+
return texture;
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
/**
|
| 250 |
+
* Create a framebuffer with attached texture
|
| 251 |
+
*/
|
| 252 |
+
export function createFramebuffer(
|
| 253 |
+
gl: WebGLRenderingContext,
|
| 254 |
+
texture: WebGLTexture
|
| 255 |
+
): WebGLFramebuffer | null {
|
| 256 |
+
const framebuffer = gl.createFramebuffer();
|
| 257 |
+
if (!framebuffer) return null;
|
| 258 |
+
|
| 259 |
+
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
|
| 260 |
+
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
|
| 261 |
+
|
| 262 |
+
const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
|
| 263 |
+
if (status !== gl.FRAMEBUFFER_COMPLETE) {
|
| 264 |
+
console.error('Framebuffer incomplete:', status);
|
| 265 |
+
gl.deleteFramebuffer(framebuffer);
|
| 266 |
+
return null;
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
| 270 |
+
return framebuffer;
|
| 271 |
+
}
|
src/lib/version.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
export const APP_VERSION = 'v3.4';
|
src/routes/+layout.server.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { LayoutServerLoad } from './$types';
|
| 2 |
+
import { env } from '$env/dynamic/private';
|
| 3 |
+
|
| 4 |
+
export const load: LayoutServerLoad = () => {
|
| 5 |
+
return {
|
| 6 |
+
title: env.TITLE ?? 'BiniLossless'
|
| 7 |
+
};
|
| 8 |
+
};
|
src/routes/+layout.svelte
ADDED
|
@@ -0,0 +1,1362 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<script lang="ts">
|
| 2 |
+
import { onMount } from 'svelte';
|
| 3 |
+
import { get } from 'svelte/store';
|
| 4 |
+
import { fade } from 'svelte/transition';
|
| 5 |
+
import '../app.css';
|
| 6 |
+
import favicon from '$lib/assets/favicon.svg';
|
| 7 |
+
import AudioPlayer from '$lib/components/AudioPlayer.svelte';
|
| 8 |
+
import LyricsPopup from '$lib/components/LyricsPopup.svelte';
|
| 9 |
+
import DynamicBackgroundWebGL from '$lib/components/DynamicBackground.svelte';
|
| 10 |
+
import { playerStore } from '$lib/stores/player';
|
| 11 |
+
import { downloadUiStore } from '$lib/stores/downloadUi';
|
| 12 |
+
import { downloadPreferencesStore, type DownloadMode } from '$lib/stores/downloadPreferences';
|
| 13 |
+
import { userPreferencesStore } from '$lib/stores/userPreferences';
|
| 14 |
+
import { effectivePerformanceLevel } from '$lib/stores/performance';
|
| 15 |
+
import { losslessAPI, type TrackDownloadProgress } from '$lib/api';
|
| 16 |
+
import { sanitizeForFilename, getExtensionForQuality, buildTrackLinksCsv } from '$lib/downloads';
|
| 17 |
+
import { formatArtists } from '$lib/utils';
|
| 18 |
+
import { navigating, page } from '$app/stores';
|
| 19 |
+
import { goto } from '$app/navigation';
|
| 20 |
+
import JSZip from 'jszip';
|
| 21 |
+
import {
|
| 22 |
+
Archive,
|
| 23 |
+
FileSpreadsheet,
|
| 24 |
+
ChevronDown,
|
| 25 |
+
LoaderCircle,
|
| 26 |
+
Download,
|
| 27 |
+
Check,
|
| 28 |
+
Settings
|
| 29 |
+
} from 'lucide-svelte';
|
| 30 |
+
import type { Navigation } from '@sveltejs/kit';
|
| 31 |
+
import { type Track, type AudioQuality, type PlayableTrack, isSonglinkTrack } from '$lib/types';
|
| 32 |
+
|
| 33 |
+
let { children, data } = $props();
|
| 34 |
+
const pageTitle = $derived(data?.title ?? 'BiniLossless');
|
| 35 |
+
let headerHeight = $state(0);
|
| 36 |
+
let playerHeight = $state(0);
|
| 37 |
+
let viewportHeight = $state(0);
|
| 38 |
+
let navigationState = $state<Navigation | null>(null);
|
| 39 |
+
let showSettingsMenu = $state(false);
|
| 40 |
+
let performanceLevel = $state<'high' | 'medium' | 'low'>('high');
|
| 41 |
+
let isZipDownloading = $state(false);
|
| 42 |
+
let isCsvExporting = $state(false);
|
| 43 |
+
let isLegacyQueueDownloading = $state(false);
|
| 44 |
+
let settingsMenuContainer: HTMLDivElement | null = null;
|
| 45 |
+
const downloadMode = $derived($downloadPreferencesStore.mode);
|
| 46 |
+
const queueActionBusy = $derived(
|
| 47 |
+
downloadMode === 'zip'
|
| 48 |
+
? Boolean(isZipDownloading || isLegacyQueueDownloading || isCsvExporting)
|
| 49 |
+
: downloadMode === 'csv'
|
| 50 |
+
? Boolean(isCsvExporting)
|
| 51 |
+
: Boolean(isLegacyQueueDownloading)
|
| 52 |
+
);
|
| 53 |
+
|
| 54 |
+
const isEmbed = $derived($page.url.pathname.startsWith('/embed'));
|
| 55 |
+
|
| 56 |
+
$effect(() => {
|
| 57 |
+
const current = $playerStore.currentTrack;
|
| 58 |
+
if (current && !isSonglinkTrack(current)) {
|
| 59 |
+
const newPath = `/track/${current.id}`;
|
| 60 |
+
const isTrackPage = $page.url.pathname.startsWith('/track/');
|
| 61 |
+
|
| 62 |
+
if ($page.url.pathname !== newPath && !$navigating) {
|
| 63 |
+
if (isTrackPage) {
|
| 64 |
+
goto(newPath, { keepFocus: true, noScroll: true });
|
| 65 |
+
}
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
});
|
| 69 |
+
const mainMinHeight = $derived(() => Math.max(0, viewportHeight - headerHeight - playerHeight));
|
| 70 |
+
const contentPaddingBottom = $derived(() => Math.max(playerHeight, 24));
|
| 71 |
+
const mainMarginBottom = $derived(() => Math.max(playerHeight, 128));
|
| 72 |
+
const settingsMenuOffset = $derived(() => Math.max(0, headerHeight + 12));
|
| 73 |
+
const FRIENDLY_ROUTE_MESSAGES: Record<string, string> = {
|
| 74 |
+
album: 'Opening album',
|
| 75 |
+
artist: 'Visiting artist',
|
| 76 |
+
playlist: 'Loading playlist'
|
| 77 |
+
};
|
| 78 |
+
|
| 79 |
+
const QUALITY_OPTIONS: Array<{ value: AudioQuality; label: string; description: string; disabled?: boolean }> = [
|
| 80 |
+
{
|
| 81 |
+
value: 'HI_RES_LOSSLESS',
|
| 82 |
+
label: 'Hi-Res',
|
| 83 |
+
description: '24-bit FLAC (DASH) up to 192 kHz',
|
| 84 |
+
disabled: false
|
| 85 |
+
},
|
| 86 |
+
{
|
| 87 |
+
value: 'LOSSLESS',
|
| 88 |
+
label: 'CD Lossless',
|
| 89 |
+
description: '16-bit / 44.1 kHz FLAC'
|
| 90 |
+
},
|
| 91 |
+
{
|
| 92 |
+
value: 'HIGH',
|
| 93 |
+
label: '320kbps AAC',
|
| 94 |
+
description: 'High quality AAC streaming'
|
| 95 |
+
},
|
| 96 |
+
{
|
| 97 |
+
value: 'LOW',
|
| 98 |
+
label: '96kbps AAC',
|
| 99 |
+
description: 'Data saver AAC streaming'
|
| 100 |
+
}
|
| 101 |
+
];
|
| 102 |
+
|
| 103 |
+
const PERFORMANCE_OPTIONS: Array<{
|
| 104 |
+
value: 'medium' | 'low';
|
| 105 |
+
label: string;
|
| 106 |
+
description: string;
|
| 107 |
+
}> = [
|
| 108 |
+
{
|
| 109 |
+
value: 'medium',
|
| 110 |
+
label: 'Balanced',
|
| 111 |
+
description: 'Smooth animations with visual effects'
|
| 112 |
+
},
|
| 113 |
+
{
|
| 114 |
+
value: 'low',
|
| 115 |
+
label: 'Performance',
|
| 116 |
+
description: 'Minimal effects for better performance'
|
| 117 |
+
}
|
| 118 |
+
];
|
| 119 |
+
|
| 120 |
+
const playbackQualityLabel = $derived(() => {
|
| 121 |
+
const quality = $playerStore.quality;
|
| 122 |
+
if (quality === 'HI_RES_LOSSLESS') {
|
| 123 |
+
return 'Hi-Res';
|
| 124 |
+
}
|
| 125 |
+
if (quality === 'LOSSLESS') {
|
| 126 |
+
return 'CD';
|
| 127 |
+
}
|
| 128 |
+
return QUALITY_OPTIONS.find((option) => option.value === quality)?.label ?? 'Quality';
|
| 129 |
+
});
|
| 130 |
+
|
| 131 |
+
const convertAacToMp3 = $derived($userPreferencesStore.convertAacToMp3);
|
| 132 |
+
const downloadCoversSeperately = $derived($userPreferencesStore.downloadCoversSeperately);
|
| 133 |
+
|
| 134 |
+
function selectPlaybackQuality(quality: AudioQuality): void {
|
| 135 |
+
playerStore.setQuality(quality);
|
| 136 |
+
showSettingsMenu = false;
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
function toggleAacConversion(): void {
|
| 140 |
+
userPreferencesStore.toggleConvertAacToMp3();
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
function toggleDownloadCoversSeperately(): void {
|
| 144 |
+
userPreferencesStore.toggleDownloadCoversSeperately();
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
function setDownloadMode(mode: DownloadMode): void {
|
| 148 |
+
downloadPreferencesStore.setMode(mode);
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
function setPerformanceMode(mode: 'medium' | 'low'): void {
|
| 152 |
+
userPreferencesStore.setPerformanceMode(mode);
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
const navigationMessage = $derived(() => {
|
| 156 |
+
if (!navigationState) return '';
|
| 157 |
+
const pathname = navigationState.to?.url?.pathname ?? '';
|
| 158 |
+
const [primarySegment] = pathname.split('/').filter(Boolean);
|
| 159 |
+
if (!primarySegment) return 'Loading';
|
| 160 |
+
const key = primarySegment.toLowerCase();
|
| 161 |
+
if (key in FRIENDLY_ROUTE_MESSAGES) {
|
| 162 |
+
return FRIENDLY_ROUTE_MESSAGES[key]!;
|
| 163 |
+
}
|
| 164 |
+
const normalized = key.replace(/[-_]+/g, ' ');
|
| 165 |
+
return `Loading ${normalized.charAt(0).toUpperCase()}${normalized.slice(1)}`;
|
| 166 |
+
});
|
| 167 |
+
|
| 168 |
+
// Update page title with currently playing song
|
| 169 |
+
$effect(() => {
|
| 170 |
+
if (typeof document === 'undefined') return;
|
| 171 |
+
|
| 172 |
+
const track = $playerStore.currentTrack;
|
| 173 |
+
const isPlaying = $playerStore.isPlaying;
|
| 174 |
+
|
| 175 |
+
if (track) {
|
| 176 |
+
const artist = isSonglinkTrack(track) ? track.artistName : formatArtists(track.artists);
|
| 177 |
+
const title = track.title ?? 'Unknown Track';
|
| 178 |
+
const prefix = isPlaying ? '▶' : '⏸';
|
| 179 |
+
document.title = `${prefix} ${title} • ${artist} | BiniLossless`;
|
| 180 |
+
} else {
|
| 181 |
+
document.title = pageTitle;
|
| 182 |
+
}
|
| 183 |
+
});
|
| 184 |
+
|
| 185 |
+
function collectQueueState(): { tracks: PlayableTrack[]; quality: AudioQuality } {
|
| 186 |
+
const state = get(playerStore);
|
| 187 |
+
const tracks = state.queue.length
|
| 188 |
+
? state.queue
|
| 189 |
+
: state.currentTrack
|
| 190 |
+
? [state.currentTrack]
|
| 191 |
+
: [];
|
| 192 |
+
return { tracks, quality: state.quality };
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
function buildQueueFilename(track: PlayableTrack, index: number, quality: AudioQuality): string {
|
| 196 |
+
const ext = getExtensionForQuality(quality, convertAacToMp3);
|
| 197 |
+
const order = `${index + 1}`.padStart(2, '0');
|
| 198 |
+
const artistName = sanitizeForFilename(isSonglinkTrack(track) ? track.artistName : formatArtists(track.artists));
|
| 199 |
+
const titleName = sanitizeForFilename(track.title ?? `Track ${order}`);
|
| 200 |
+
return `${order} - ${artistName} - ${titleName}.${ext}`;
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
function triggerFileDownload(blob: Blob, filename: string): void {
|
| 204 |
+
const url = URL.createObjectURL(blob);
|
| 205 |
+
const link = document.createElement('a');
|
| 206 |
+
link.href = url;
|
| 207 |
+
link.download = filename;
|
| 208 |
+
document.body.appendChild(link);
|
| 209 |
+
link.click();
|
| 210 |
+
document.body.removeChild(link);
|
| 211 |
+
URL.revokeObjectURL(url);
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
function timestampedFilename(extension: string): string {
|
| 215 |
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
| 216 |
+
return `tidal-export-${stamp}.${extension}`;
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
async function downloadQueueAsZip(tracks: PlayableTrack[], quality: AudioQuality): Promise<void> {
|
| 220 |
+
isZipDownloading = true;
|
| 221 |
+
|
| 222 |
+
try {
|
| 223 |
+
const zip = new JSZip();
|
| 224 |
+
for (const [index, track] of tracks.entries()) {
|
| 225 |
+
const trackId = isSonglinkTrack(track) ? track.tidalId : track.id;
|
| 226 |
+
if (!trackId) continue;
|
| 227 |
+
|
| 228 |
+
const filename = buildQueueFilename(track, index, quality);
|
| 229 |
+
const { blob } = await losslessAPI.fetchTrackBlob(trackId, quality, filename, {
|
| 230 |
+
ffmpegAutoTriggered: false,
|
| 231 |
+
convertAacToMp3
|
| 232 |
+
});
|
| 233 |
+
zip.file(filename, blob);
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
const zipBlob = await zip.generateAsync({
|
| 237 |
+
type: 'blob',
|
| 238 |
+
compression: 'DEFLATE',
|
| 239 |
+
compressionOptions: { level: 6 }
|
| 240 |
+
});
|
| 241 |
+
|
| 242 |
+
triggerFileDownload(zipBlob, timestampedFilename('zip'));
|
| 243 |
+
} catch (error) {
|
| 244 |
+
console.error('Failed to build ZIP export', error);
|
| 245 |
+
alert('Unable to build ZIP export. Please try again.');
|
| 246 |
+
} finally {
|
| 247 |
+
isZipDownloading = false;
|
| 248 |
+
}
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
async function exportQueueAsCsv(tracks: PlayableTrack[], quality: AudioQuality): Promise<void> {
|
| 252 |
+
isCsvExporting = true;
|
| 253 |
+
|
| 254 |
+
try {
|
| 255 |
+
// @ts-ignore - buildTrackLinksCsv needs update but we can cast for now or update it later
|
| 256 |
+
const csvContent = await buildTrackLinksCsv(tracks, quality);
|
| 257 |
+
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
|
| 258 |
+
triggerFileDownload(blob, timestampedFilename('csv'));
|
| 259 |
+
} catch (error) {
|
| 260 |
+
console.error('Failed to export queue as CSV', error);
|
| 261 |
+
alert('Unable to export CSV. Please try again.');
|
| 262 |
+
} finally {
|
| 263 |
+
isCsvExporting = false;
|
| 264 |
+
}
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
async function handleExportQueueCsv(): Promise<void> {
|
| 268 |
+
const { tracks, quality } = collectQueueState();
|
| 269 |
+
if (tracks.length === 0) {
|
| 270 |
+
showSettingsMenu = false;
|
| 271 |
+
alert('Add tracks to the queue before exporting.');
|
| 272 |
+
return;
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
showSettingsMenu = false;
|
| 276 |
+
await exportQueueAsCsv(tracks, quality);
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
async function downloadQueueIndividually(tracks: PlayableTrack[], quality: AudioQuality): Promise<void> {
|
| 280 |
+
if (isLegacyQueueDownloading) {
|
| 281 |
+
return;
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
isLegacyQueueDownloading = true;
|
| 285 |
+
const errors: string[] = [];
|
| 286 |
+
|
| 287 |
+
try {
|
| 288 |
+
for (const [index, track] of tracks.entries()) {
|
| 289 |
+
const trackId = isSonglinkTrack(track) ? track.tidalId : track.id;
|
| 290 |
+
if (!trackId) continue;
|
| 291 |
+
|
| 292 |
+
const filename = buildQueueFilename(track, index, quality);
|
| 293 |
+
// @ts-ignore - downloadUiStore needs update to accept PlayableTrack or we cast
|
| 294 |
+
const { taskId, controller } = downloadUiStore.beginTrackDownload(track as Track, filename, {
|
| 295 |
+
subtitle: isSonglinkTrack(track) ? track.artistName : (track.album?.title ?? formatArtists(track.artists))
|
| 296 |
+
});
|
| 297 |
+
downloadUiStore.skipFfmpegCountdown();
|
| 298 |
+
|
| 299 |
+
try {
|
| 300 |
+
await losslessAPI.downloadTrack(trackId, quality, filename, {
|
| 301 |
+
signal: controller.signal,
|
| 302 |
+
onProgress: (progress: TrackDownloadProgress) => {
|
| 303 |
+
if (progress.stage === 'downloading') {
|
| 304 |
+
downloadUiStore.updateTrackProgress(
|
| 305 |
+
taskId,
|
| 306 |
+
progress.receivedBytes,
|
| 307 |
+
progress.totalBytes
|
| 308 |
+
);
|
| 309 |
+
} else {
|
| 310 |
+
downloadUiStore.updateTrackStage(taskId, progress.progress);
|
| 311 |
+
}
|
| 312 |
+
},
|
| 313 |
+
onFfmpegCountdown: ({ totalBytes }) => {
|
| 314 |
+
const bytes = typeof totalBytes === 'number' ? totalBytes : 0;
|
| 315 |
+
downloadUiStore.startFfmpegCountdown(bytes, { autoTriggered: false });
|
| 316 |
+
},
|
| 317 |
+
onFfmpegStart: () => downloadUiStore.startFfmpegLoading(),
|
| 318 |
+
onFfmpegProgress: (value) => downloadUiStore.updateFfmpegProgress(value),
|
| 319 |
+
onFfmpegComplete: () => downloadUiStore.completeFfmpeg(),
|
| 320 |
+
onFfmpegError: (error) => downloadUiStore.errorFfmpeg(error),
|
| 321 |
+
ffmpegAutoTriggered: false,
|
| 322 |
+
convertAacToMp3,
|
| 323 |
+
downloadCoverSeperately: downloadCoversSeperately
|
| 324 |
+
});
|
| 325 |
+
downloadUiStore.completeTrackDownload(taskId);
|
| 326 |
+
} catch (error) {
|
| 327 |
+
if (error instanceof DOMException && error.name === 'AbortError') {
|
| 328 |
+
downloadUiStore.completeTrackDownload(taskId);
|
| 329 |
+
continue;
|
| 330 |
+
}
|
| 331 |
+
console.error('Failed to download track from queue:', error);
|
| 332 |
+
downloadUiStore.errorTrackDownload(taskId, error);
|
| 333 |
+
const label = `${isSonglinkTrack(track) ? track.artistName : formatArtists(track.artists)} - ${track.title ?? 'Unknown Track'}`;
|
| 334 |
+
const message =
|
| 335 |
+
error instanceof Error && error.message
|
| 336 |
+
? error.message
|
| 337 |
+
: 'Failed to download track. Please try again.';
|
| 338 |
+
errors.push(`${label}: ${message}`);
|
| 339 |
+
}
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
if (errors.length > 0) {
|
| 343 |
+
const summary = [
|
| 344 |
+
'Unable to download some tracks individually:',
|
| 345 |
+
...errors.slice(0, 3),
|
| 346 |
+
errors.length > 3 ? `…and ${errors.length - 3} more` : undefined
|
| 347 |
+
]
|
| 348 |
+
.filter(Boolean)
|
| 349 |
+
.join('\n');
|
| 350 |
+
alert(summary);
|
| 351 |
+
}
|
| 352 |
+
} finally {
|
| 353 |
+
isLegacyQueueDownloading = false;
|
| 354 |
+
}
|
| 355 |
+
}
|
| 356 |
+
|
| 357 |
+
async function handleQueueDownload(): Promise<void> {
|
| 358 |
+
if (queueActionBusy) {
|
| 359 |
+
return;
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
const { tracks, quality } = collectQueueState();
|
| 363 |
+
if (tracks.length === 0) {
|
| 364 |
+
showSettingsMenu = false;
|
| 365 |
+
alert('Add tracks to the queue before downloading.');
|
| 366 |
+
return;
|
| 367 |
+
}
|
| 368 |
+
|
| 369 |
+
showSettingsMenu = false;
|
| 370 |
+
|
| 371 |
+
if (downloadMode === 'csv') {
|
| 372 |
+
await exportQueueAsCsv(tracks, quality);
|
| 373 |
+
return;
|
| 374 |
+
}
|
| 375 |
+
|
| 376 |
+
const useZip = downloadMode === 'zip' && tracks.length > 1;
|
| 377 |
+
if (useZip) {
|
| 378 |
+
await downloadQueueAsZip(tracks, quality);
|
| 379 |
+
return;
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
await downloadQueueIndividually(tracks, quality);
|
| 383 |
+
}
|
| 384 |
+
|
| 385 |
+
const handlePlayerHeight = (height: number) => {
|
| 386 |
+
playerHeight = height;
|
| 387 |
+
};
|
| 388 |
+
|
| 389 |
+
let controllerChangeHandler: (() => void) | null = null;
|
| 390 |
+
|
| 391 |
+
onMount(() => {
|
| 392 |
+
// Subscribe to performance level and update data attribute
|
| 393 |
+
const unsubPerf = effectivePerformanceLevel.subscribe((level) => {
|
| 394 |
+
performanceLevel = level;
|
| 395 |
+
if (typeof document !== 'undefined') {
|
| 396 |
+
document.documentElement.setAttribute('data-performance', level);
|
| 397 |
+
}
|
| 398 |
+
});
|
| 399 |
+
|
| 400 |
+
const updateViewportHeight = () => {
|
| 401 |
+
viewportHeight = window.innerHeight;
|
| 402 |
+
};
|
| 403 |
+
updateViewportHeight();
|
| 404 |
+
window.addEventListener('resize', updateViewportHeight);
|
| 405 |
+
const handleDocumentClick = (event: MouseEvent) => {
|
| 406 |
+
const target = event.target as Node | null;
|
| 407 |
+
if (showSettingsMenu) {
|
| 408 |
+
const root = settingsMenuContainer;
|
| 409 |
+
if (!root || !target || !root.contains(target)) {
|
| 410 |
+
showSettingsMenu = false;
|
| 411 |
+
}
|
| 412 |
+
}
|
| 413 |
+
};
|
| 414 |
+
document.addEventListener('click', handleDocumentClick);
|
| 415 |
+
const unsubscribe = navigating.subscribe((value) => {
|
| 416 |
+
navigationState = value;
|
| 417 |
+
});
|
| 418 |
+
|
| 419 |
+
if ('serviceWorker' in navigator) {
|
| 420 |
+
const registerServiceWorker = async () => {
|
| 421 |
+
try {
|
| 422 |
+
const registration = await navigator.serviceWorker.register('/service-worker.js');
|
| 423 |
+
const sendSkipWaiting = () => {
|
| 424 |
+
if (registration.waiting) {
|
| 425 |
+
registration.waiting.postMessage({ type: 'SKIP_WAITING' });
|
| 426 |
+
}
|
| 427 |
+
};
|
| 428 |
+
|
| 429 |
+
if (registration.waiting) {
|
| 430 |
+
sendSkipWaiting();
|
| 431 |
+
}
|
| 432 |
+
|
| 433 |
+
registration.addEventListener('updatefound', () => {
|
| 434 |
+
const newWorker = registration.installing;
|
| 435 |
+
if (!newWorker) return;
|
| 436 |
+
newWorker.addEventListener('statechange', () => {
|
| 437 |
+
if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
|
| 438 |
+
sendSkipWaiting();
|
| 439 |
+
}
|
| 440 |
+
});
|
| 441 |
+
});
|
| 442 |
+
} catch (error) {
|
| 443 |
+
console.error('Service worker registration failed', error);
|
| 444 |
+
}
|
| 445 |
+
};
|
| 446 |
+
|
| 447 |
+
registerServiceWorker();
|
| 448 |
+
|
| 449 |
+
let refreshing = false;
|
| 450 |
+
controllerChangeHandler = () => {
|
| 451 |
+
if (refreshing) return;
|
| 452 |
+
refreshing = true;
|
| 453 |
+
window.location.reload();
|
| 454 |
+
};
|
| 455 |
+
navigator.serviceWorker.addEventListener('controllerchange', controllerChangeHandler);
|
| 456 |
+
}
|
| 457 |
+
return () => {
|
| 458 |
+
window.removeEventListener('resize', updateViewportHeight);
|
| 459 |
+
document.removeEventListener('click', handleDocumentClick);
|
| 460 |
+
unsubscribe();
|
| 461 |
+
unsubPerf();
|
| 462 |
+
if (controllerChangeHandler) {
|
| 463 |
+
navigator.serviceWorker.removeEventListener('controllerchange', controllerChangeHandler);
|
| 464 |
+
}
|
| 465 |
+
};
|
| 466 |
+
});
|
| 467 |
+
</script>
|
| 468 |
+
|
| 469 |
+
<svelte:head>
|
| 470 |
+
<title>{pageTitle}</title>
|
| 471 |
+
<link rel="icon" href={favicon} />
|
| 472 |
+
<link rel="manifest" href="/manifest.webmanifest" />
|
| 473 |
+
<link rel="icon" href="/icons/icon.svg" type="image/svg+xml" />
|
| 474 |
+
<meta name="theme-color" content="#0f172a" />
|
| 475 |
+
<meta name="apple-mobile-web-app-capable" content="yes" />
|
| 476 |
+
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
| 477 |
+
</svelte:head>
|
| 478 |
+
|
| 479 |
+
{#if isEmbed}
|
| 480 |
+
{@render children?.()}
|
| 481 |
+
<AudioPlayer headless={true} />
|
| 482 |
+
{:else}
|
| 483 |
+
<div class="app-root">
|
| 484 |
+
<DynamicBackgroundWebGL />
|
| 485 |
+
<div class="app-shell">
|
| 486 |
+
<header class="app-header glass-panel" bind:clientHeight={headerHeight}>
|
| 487 |
+
<div class="app-header__inner">
|
| 488 |
+
<a href="/" class="brand" aria-label="Home">
|
| 489 |
+
<div class="brand__text">
|
| 490 |
+
<h1 class="brand__title">{data.title}</h1>
|
| 491 |
+
<p class="brand__subtitle">sailing on PCM tidal waves</p>
|
| 492 |
+
</div>
|
| 493 |
+
</a>
|
| 494 |
+
|
| 495 |
+
<div class="toolbar">
|
| 496 |
+
<div class="settings-trigger" bind:this={settingsMenuContainer}>
|
| 497 |
+
<button
|
| 498 |
+
onclick={() => {
|
| 499 |
+
showSettingsMenu = !showSettingsMenu;
|
| 500 |
+
}}
|
| 501 |
+
type="button"
|
| 502 |
+
class={`toolbar-button glass-button ${showSettingsMenu ? 'is-active' : ''}`}
|
| 503 |
+
aria-haspopup="true"
|
| 504 |
+
aria-expanded={showSettingsMenu}
|
| 505 |
+
aria-label={`Settings menu (${playbackQualityLabel()})`}
|
| 506 |
+
>
|
| 507 |
+
<span class="toolbar-button__label">
|
| 508 |
+
<Settings size={16} />
|
| 509 |
+
<span class="toolbar-button__text">Settings</span>
|
| 510 |
+
</span>
|
| 511 |
+
<span class="text-gray-400">{playbackQualityLabel()}</span>
|
| 512 |
+
<span class={`toolbar-button__chevron ${showSettingsMenu ? 'is-open' : ''}`}>
|
| 513 |
+
<ChevronDown size={16} />
|
| 514 |
+
</span>
|
| 515 |
+
</button>
|
| 516 |
+
{#if showSettingsMenu}
|
| 517 |
+
<div
|
| 518 |
+
class="settings-menu glass-popover"
|
| 519 |
+
style={`--settings-menu-offset: ${settingsMenuOffset()}px;`}
|
| 520 |
+
>
|
| 521 |
+
<div class="settings-grid">
|
| 522 |
+
<section class="settings-section settings-section--wide">
|
| 523 |
+
<p class="section-heading">Streaming & Downloads</p>
|
| 524 |
+
<div class="option-grid">
|
| 525 |
+
{#each QUALITY_OPTIONS as option}
|
| 526 |
+
<button
|
| 527 |
+
type="button"
|
| 528 |
+
onclick={() => selectPlaybackQuality(option.value)}
|
| 529 |
+
class={`glass-option ${option.value === $playerStore.quality ? 'is-active' : ''} ${option.disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
|
| 530 |
+
aria-pressed={option.value === $playerStore.quality}
|
| 531 |
+
disabled={option.disabled}
|
| 532 |
+
>
|
| 533 |
+
<div class="glass-option__content">
|
| 534 |
+
<span class="glass-option__label">{option.label}</span>
|
| 535 |
+
<span class="glass-option__description">{option.description}</span>
|
| 536 |
+
</div>
|
| 537 |
+
{#if option.value === $playerStore.quality}
|
| 538 |
+
<Check size={16} class="glass-option__check" />
|
| 539 |
+
{/if}
|
| 540 |
+
</button>
|
| 541 |
+
{/each}
|
| 542 |
+
</div>
|
| 543 |
+
</section>
|
| 544 |
+
<section class="settings-section settings-section--wide">
|
| 545 |
+
<p class="section-heading">Conversions</p>
|
| 546 |
+
<button
|
| 547 |
+
type="button"
|
| 548 |
+
onclick={toggleAacConversion}
|
| 549 |
+
class={`glass-option ${convertAacToMp3 ? 'is-active' : ''}`}
|
| 550 |
+
aria-pressed={convertAacToMp3}
|
| 551 |
+
>
|
| 552 |
+
<span class="glass-option__content">
|
| 553 |
+
<span class="glass-option__label">Convert AAC downloads to MP3</span>
|
| 554 |
+
<span class="glass-option__description">Applies to 320kbps and 96kbps downloads.</span>
|
| 555 |
+
</span>
|
| 556 |
+
<span class={`glass-option__chip ${convertAacToMp3 ? 'is-active' : ''}`}>
|
| 557 |
+
{convertAacToMp3 ? 'On' : 'Off'}
|
| 558 |
+
</span>
|
| 559 |
+
</button>
|
| 560 |
+
<button
|
| 561 |
+
type="button"
|
| 562 |
+
onclick={toggleDownloadCoversSeperately}
|
| 563 |
+
class={`glass-option ${downloadCoversSeperately ? 'is-active' : ''}`}
|
| 564 |
+
aria-pressed={downloadCoversSeperately}
|
| 565 |
+
>
|
| 566 |
+
<span class="glass-option__content">
|
| 567 |
+
<span class="glass-option__label">Download covers separately</span>
|
| 568 |
+
<span class="glass-option__description">Save cover.jpg alongside audio files.</span>
|
| 569 |
+
</span>
|
| 570 |
+
<span class={`glass-option__chip ${downloadCoversSeperately ? 'is-active' : ''}`}>
|
| 571 |
+
{downloadCoversSeperately ? 'On' : 'Off'}
|
| 572 |
+
</span>
|
| 573 |
+
</button>
|
| 574 |
+
</section>
|
| 575 |
+
<section class="settings-section settings-section--wide">
|
| 576 |
+
<p class="section-heading">Queue exports</p>
|
| 577 |
+
<div class="option-grid option-grid--compact">
|
| 578 |
+
<button
|
| 579 |
+
type="button"
|
| 580 |
+
onclick={() => setDownloadMode('individual')}
|
| 581 |
+
class={`glass-option glass-option--compact ${downloadMode === 'individual' ? 'is-active' : ''}`}
|
| 582 |
+
aria-pressed={downloadMode === 'individual'}
|
| 583 |
+
>
|
| 584 |
+
<span class="glass-option__content">
|
| 585 |
+
<span class="glass-option__label">
|
| 586 |
+
<Download size={16} />
|
| 587 |
+
<span>Individual files</span>
|
| 588 |
+
</span>
|
| 589 |
+
</span>
|
| 590 |
+
{#if downloadMode === 'individual'}
|
| 591 |
+
<Check size={14} class="glass-option__check" />
|
| 592 |
+
{/if}
|
| 593 |
+
</button>
|
| 594 |
+
<button
|
| 595 |
+
type="button"
|
| 596 |
+
onclick={() => setDownloadMode('zip')}
|
| 597 |
+
class={`glass-option glass-option--compact ${downloadMode === 'zip' ? 'is-active' : ''}`}
|
| 598 |
+
aria-pressed={downloadMode === 'zip'}
|
| 599 |
+
>
|
| 600 |
+
<span class="glass-option__content">
|
| 601 |
+
<span class="glass-option__label">
|
| 602 |
+
<Archive size={16} />
|
| 603 |
+
<span>ZIP archive</span>
|
| 604 |
+
</span>
|
| 605 |
+
</span>
|
| 606 |
+
{#if downloadMode === 'zip'}
|
| 607 |
+
<Check size={14} class="glass-option__check" />
|
| 608 |
+
{/if}
|
| 609 |
+
</button>
|
| 610 |
+
<button
|
| 611 |
+
type="button"
|
| 612 |
+
onclick={() => setDownloadMode('csv')}
|
| 613 |
+
class={`glass-option glass-option--compact ${downloadMode === 'csv' ? 'is-active' : ''}`}
|
| 614 |
+
aria-pressed={downloadMode === 'csv'}
|
| 615 |
+
>
|
| 616 |
+
<span class="glass-option__content">
|
| 617 |
+
<span class="glass-option__label">
|
| 618 |
+
<FileSpreadsheet size={16} />
|
| 619 |
+
<span>Export links</span>
|
| 620 |
+
</span>
|
| 621 |
+
</span>
|
| 622 |
+
{#if downloadMode === 'csv'}
|
| 623 |
+
<Check size={14} class="glass-option__check" />
|
| 624 |
+
{/if}
|
| 625 |
+
</button>
|
| 626 |
+
</div>
|
| 627 |
+
</section>
|
| 628 |
+
<section class="settings-section settings-section--wide">
|
| 629 |
+
<p class="section-heading">Performance Mode</p>
|
| 630 |
+
<div class="option-grid option-grid--compact">
|
| 631 |
+
{#each PERFORMANCE_OPTIONS as option}
|
| 632 |
+
<button
|
| 633 |
+
type="button"
|
| 634 |
+
onclick={() => setPerformanceMode(option.value)}
|
| 635 |
+
class={`glass-option glass-option--compact ${option.value === $userPreferencesStore.performanceMode ? 'is-active' : ''}`}
|
| 636 |
+
aria-pressed={option.value === $userPreferencesStore.performanceMode}
|
| 637 |
+
>
|
| 638 |
+
<div class="glass-option__content">
|
| 639 |
+
<span class="glass-option__label">{option.label}</span>
|
| 640 |
+
</div>
|
| 641 |
+
{#if option.value === $userPreferencesStore.performanceMode}
|
| 642 |
+
<Check size={14} class="glass-option__check" />
|
| 643 |
+
{/if}
|
| 644 |
+
</button>
|
| 645 |
+
{/each}
|
| 646 |
+
</div>
|
| 647 |
+
</section>
|
| 648 |
+
<section class="settings-section settings-section--bordered">
|
| 649 |
+
<p class="section-heading">Queue actions</p>
|
| 650 |
+
<div class="actions-column">
|
| 651 |
+
<button
|
| 652 |
+
onclick={handleQueueDownload}
|
| 653 |
+
type="button"
|
| 654 |
+
class="glass-action"
|
| 655 |
+
disabled={queueActionBusy}
|
| 656 |
+
>
|
| 657 |
+
<span class="glass-action__label">
|
| 658 |
+
{#if downloadMode === 'zip'}
|
| 659 |
+
<Archive size={16} />
|
| 660 |
+
<span>Download queue</span>
|
| 661 |
+
{:else if downloadMode === 'csv'}
|
| 662 |
+
<FileSpreadsheet size={16} />
|
| 663 |
+
<span>Export queue links</span>
|
| 664 |
+
{:else}
|
| 665 |
+
<Download size={16} />
|
| 666 |
+
<span>Download queue</span>
|
| 667 |
+
{/if}
|
| 668 |
+
</span>
|
| 669 |
+
{#if queueActionBusy}
|
| 670 |
+
<LoaderCircle size={16} class="glass-action__spinner" />
|
| 671 |
+
{/if}
|
| 672 |
+
</button>
|
| 673 |
+
<button
|
| 674 |
+
onclick={handleExportQueueCsv}
|
| 675 |
+
type="button"
|
| 676 |
+
class="glass-action"
|
| 677 |
+
disabled={isCsvExporting}
|
| 678 |
+
>
|
| 679 |
+
<span class="glass-action__label">
|
| 680 |
+
<FileSpreadsheet size={16} />
|
| 681 |
+
<span>Export links as CSV</span>
|
| 682 |
+
</span>
|
| 683 |
+
{#if isCsvExporting}
|
| 684 |
+
<LoaderCircle size={16} class="glass-action__spinner" />
|
| 685 |
+
{/if}
|
| 686 |
+
</button>
|
| 687 |
+
</div>
|
| 688 |
+
<p class="section-footnote">
|
| 689 |
+
Queue actions follow your selection above. ZIP bundles require at least two tracks,
|
| 690 |
+
while CSV exports capture the track links without downloading audio.
|
| 691 |
+
</p>
|
| 692 |
+
</section>
|
| 693 |
+
</div>
|
| 694 |
+
</div>
|
| 695 |
+
{/if}
|
| 696 |
+
</div>
|
| 697 |
+
<a
|
| 698 |
+
target="_blank"
|
| 699 |
+
rel="noopener noreferrer"
|
| 700 |
+
href="https://github.com/uimaxbai/tidal-ui"
|
| 701 |
+
class="toolbar-icon"
|
| 702 |
+
aria-label="Project GitHub"
|
| 703 |
+
>
|
| 704 |
+
<svg
|
| 705 |
+
viewBox="0 0 98 96"
|
| 706 |
+
class="toolbar-icon__svg"
|
| 707 |
+
aria-hidden="true"
|
| 708 |
+
width="98"
|
| 709 |
+
height="96"
|
| 710 |
+
xmlns="http://www.w3.org/2000/svg"
|
| 711 |
+
>
|
| 712 |
+
<path
|
| 713 |
+
fill-rule="evenodd"
|
| 714 |
+
clip-rule="evenodd"
|
| 715 |
+
d="M48.854 0C21.839 0 0 22 0 49.217c0 21.756 13.993 40.172 33.405 46.69 2.427.49 3.316-1.059 3.316-2.362 0-1.141-.08-5.052-.08-9.127-13.59 2.934-16.42-5.867-16.42-5.867-2.184-5.704-5.42-7.17-5.42-7.17-4.448-3.015.324-3.015.324-3.015 4.934.326 7.523 5.052 7.523 5.052 4.367 7.496 11.404 5.378 14.235 4.074.404-3.178 1.699-5.378 3.074-6.6-10.839-1.141-22.243-5.378-22.243-24.283 0-5.378 1.94-9.778 5.014-13.2-.485-1.222-2.184-6.275.486-13.038 0 0 4.125-1.304 13.426 5.052a46.97 46.97 0 0 1 12.214-1.63c4.125 0 8.33.571 12.213 1.63 9.302-6.356 13.427-5.052 13.427-5.052 2.67 6.763.97 11.816.485 13.038 3.155 3.422 5.015 7.822 5.015 13.2 0 18.905-11.404 23.06-22.324 24.283 1.78 1.548 3.316 4.481 3.316 9.126 0 6.6-.08 11.897-.08 13.526 0 1.304.89 2.853 3.316 2.364 19.412-6.52 33.405-24.935 33.405-46.691C97.707 22 75.788 0 48.854 0z"
|
| 716 |
+
fill="#fff"
|
| 717 |
+
/>
|
| 718 |
+
</svg>
|
| 719 |
+
</a>
|
| 720 |
+
</div>
|
| 721 |
+
</div>
|
| 722 |
+
</header>
|
| 723 |
+
|
| 724 |
+
<main
|
| 725 |
+
class="app-main glass-panel !mb-56 !sm:mb-40"
|
| 726 |
+
style={`min-height: ${mainMinHeight}px; margin-bottom: ${mainMarginBottom}px;`}
|
| 727 |
+
>
|
| 728 |
+
<div class="app-main__inner">
|
| 729 |
+
{@render children?.()}
|
| 730 |
+
</div>
|
| 731 |
+
</main>
|
| 732 |
+
|
| 733 |
+
<AudioPlayer onHeightChange={handlePlayerHeight} />
|
| 734 |
+
</div>
|
| 735 |
+
</div>
|
| 736 |
+
|
| 737 |
+
<LyricsPopup />
|
| 738 |
+
{/if}
|
| 739 |
+
|
| 740 |
+
<!--
|
| 741 |
+
{#if navigationState}
|
| 742 |
+
<div
|
| 743 |
+
transition:fade={{ duration: 200 }}
|
| 744 |
+
class="navigation-overlay"
|
| 745 |
+
>
|
| 746 |
+
<div class="navigation-overlay__progress">
|
| 747 |
+
<div class="navigation-progress"></div>
|
| 748 |
+
</div>
|
| 749 |
+
<div class="navigation-overlay__content">
|
| 750 |
+
<span class="navigation-overlay__label">{navigationMessage()}</span>
|
| 751 |
+
</div>
|
| 752 |
+
</div>
|
| 753 |
+
{/if}
|
| 754 |
+
-->
|
| 755 |
+
|
| 756 |
+
<style>
|
| 757 |
+
:global(:root) {
|
| 758 |
+
--bloom-primary: #0f172a;
|
| 759 |
+
--bloom-secondary: #1f2937;
|
| 760 |
+
--bloom-accent: #3b82f6;
|
| 761 |
+
--bloom-glow: rgba(59, 130, 246, 0.35);
|
| 762 |
+
--bloom-tertiary: rgba(99, 102, 241, 0.32);
|
| 763 |
+
--bloom-quaternary: rgba(30, 64, 175, 0.28);
|
| 764 |
+
--surface-color: rgba(15, 23, 42, 0.68);
|
| 765 |
+
--surface-border: rgba(148, 163, 184, 0.18);
|
| 766 |
+
--surface-highlight: rgba(148, 163, 184, 0.35);
|
| 767 |
+
--accent-color: var(--bloom-accent);
|
| 768 |
+
}
|
| 769 |
+
|
| 770 |
+
:global(body) {
|
| 771 |
+
margin: 0;
|
| 772 |
+
min-height: 100vh;
|
| 773 |
+
font-family:
|
| 774 |
+
'Figtree',
|
| 775 |
+
-apple-system,
|
| 776 |
+
BlinkMacSystemFont,
|
| 777 |
+
'Segoe UI',
|
| 778 |
+
Roboto,
|
| 779 |
+
'Helvetica Neue',
|
| 780 |
+
Arial,
|
| 781 |
+
sans-serif;
|
| 782 |
+
background: radial-gradient(circle at top, rgba(15, 23, 42, 0.85), rgba(10, 12, 24, 0.95));
|
| 783 |
+
color: #f8fafc;
|
| 784 |
+
}
|
| 785 |
+
|
| 786 |
+
.app-root {
|
| 787 |
+
position: relative;
|
| 788 |
+
min-height: 100vh;
|
| 789 |
+
color: inherit;
|
| 790 |
+
}
|
| 791 |
+
|
| 792 |
+
.app-shell {
|
| 793 |
+
position: relative;
|
| 794 |
+
z-index: 1;
|
| 795 |
+
display: flex;
|
| 796 |
+
flex-direction: column;
|
| 797 |
+
min-height: 100vh;
|
| 798 |
+
}
|
| 799 |
+
|
| 800 |
+
.glass-panel {
|
| 801 |
+
background: rgba(15, 23, 42, 0.45);
|
| 802 |
+
border: 1px solid var(--surface-border, rgba(148, 163, 184, 0.15));
|
| 803 |
+
border-radius: var(--radius-2xl, 1.25rem);
|
| 804 |
+
backdrop-filter: blur(var(--perf-blur-high, 32px)) saturate(var(--perf-saturate, 160%));
|
| 805 |
+
-webkit-backdrop-filter: blur(var(--perf-blur-high, 32px)) saturate(var(--perf-saturate, 160%));
|
| 806 |
+
box-shadow:
|
| 807 |
+
0 25px 60px rgba(2, 6, 23, 0.4),
|
| 808 |
+
0 4px 16px rgba(15, 23, 42, 0.3),
|
| 809 |
+
inset 0 1px 0 rgba(255, 255, 255, 0.08),
|
| 810 |
+
inset 0 0 60px rgba(255, 255, 255, 0.02);
|
| 811 |
+
transition:
|
| 812 |
+
border-color 0.8s cubic-bezier(0.4, 0, 0.2, 1),
|
| 813 |
+
box-shadow var(--transition-slow, 0.3s ease),
|
| 814 |
+
transform var(--transition-base, 0.2s ease);
|
| 815 |
+
}
|
| 816 |
+
|
| 817 |
+
.app-header {
|
| 818 |
+
position: sticky;
|
| 819 |
+
top: 0;
|
| 820 |
+
padding: 0.75rem clamp(1.2rem, 2.5vw, 2rem);
|
| 821 |
+
display: flex;
|
| 822 |
+
align-items: center;
|
| 823 |
+
justify-content: space-between;
|
| 824 |
+
gap: 1rem;
|
| 825 |
+
z-index: 12;
|
| 826 |
+
border-radius: 0;
|
| 827 |
+
border-left: none;
|
| 828 |
+
border-right: none;
|
| 829 |
+
border-top: none;
|
| 830 |
+
}
|
| 831 |
+
|
| 832 |
+
.app-header__inner {
|
| 833 |
+
width: 100%;
|
| 834 |
+
display: flex;
|
| 835 |
+
align-items: center;
|
| 836 |
+
justify-content: space-between;
|
| 837 |
+
gap: clamp(0.75rem, 1.5vw, 2rem);
|
| 838 |
+
}
|
| 839 |
+
|
| 840 |
+
.brand {
|
| 841 |
+
display: flex;
|
| 842 |
+
align-items: center;
|
| 843 |
+
gap: 0.65rem;
|
| 844 |
+
text-decoration: none;
|
| 845 |
+
color: inherit;
|
| 846 |
+
font-weight: 600;
|
| 847 |
+
transition: opacity 150ms ease, transform 180ms ease;
|
| 848 |
+
}
|
| 849 |
+
|
| 850 |
+
.brand:hover {
|
| 851 |
+
opacity: 0.88;
|
| 852 |
+
transform: translateY(-1px);
|
| 853 |
+
}
|
| 854 |
+
|
| 855 |
+
.brand__title {
|
| 856 |
+
font-size: clamp(1.4rem, 2.2vw, 1.9rem);
|
| 857 |
+
margin: 0;
|
| 858 |
+
background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 50%, #cbd5e1 100%);
|
| 859 |
+
-webkit-background-clip: text;
|
| 860 |
+
background-clip: text;
|
| 861 |
+
color: transparent;
|
| 862 |
+
}
|
| 863 |
+
|
| 864 |
+
.brand__subtitle {
|
| 865 |
+
margin: 0.15rem 0 0;
|
| 866 |
+
font-size: 0.72rem;
|
| 867 |
+
color: rgba(148, 163, 184, 0.7);
|
| 868 |
+
font-weight: 400;
|
| 869 |
+
letter-spacing: 0.02em;
|
| 870 |
+
}
|
| 871 |
+
|
| 872 |
+
.toolbar {
|
| 873 |
+
display: flex;
|
| 874 |
+
align-items: center;
|
| 875 |
+
gap: 0.6rem;
|
| 876 |
+
}
|
| 877 |
+
|
| 878 |
+
.toolbar-icon {
|
| 879 |
+
display: inline-flex;
|
| 880 |
+
align-items: center;
|
| 881 |
+
justify-content: center;
|
| 882 |
+
width: 2.2rem;
|
| 883 |
+
height: 2.2rem;
|
| 884 |
+
border-radius: 999px;
|
| 885 |
+
border: 1px solid rgba(148, 163, 184, 0.2);
|
| 886 |
+
background: transparent;
|
| 887 |
+
backdrop-filter: blur(var(--perf-blur-low, 24px)) saturate(var(--perf-saturate, 160%));
|
| 888 |
+
-webkit-backdrop-filter: blur(var(--perf-blur-low, 24px)) saturate(var(--perf-saturate, 160%));
|
| 889 |
+
color: inherit;
|
| 890 |
+
transition: border-color 160ms ease, transform 180ms ease, box-shadow 180ms ease;
|
| 891 |
+
}
|
| 892 |
+
|
| 893 |
+
.toolbar-icon:hover {
|
| 894 |
+
transform: translateY(-2px);
|
| 895 |
+
border-color: rgba(148, 163, 184, 0.4);
|
| 896 |
+
box-shadow:
|
| 897 |
+
0 8px 24px rgba(8, 11, 19, 0.35),
|
| 898 |
+
0 0 20px rgba(59, 130, 246, 0.1);
|
| 899 |
+
}
|
| 900 |
+
|
| 901 |
+
.toolbar-icon__svg {
|
| 902 |
+
width: 16px;
|
| 903 |
+
height: 16px;
|
| 904 |
+
flex-shrink: 0;
|
| 905 |
+
}
|
| 906 |
+
|
| 907 |
+
.toolbar-button {
|
| 908 |
+
display: inline-flex;
|
| 909 |
+
align-items: center;
|
| 910 |
+
gap: 0.75rem;
|
| 911 |
+
border-radius: 999px;
|
| 912 |
+
border: 1px solid var(--surface-border, rgba(148, 163, 184, 0.2));
|
| 913 |
+
padding: 0.55rem 0.95rem 0.55rem 0.85rem;
|
| 914 |
+
font-size: 0.8rem;
|
| 915 |
+
line-height: 1;
|
| 916 |
+
font-weight: 600;
|
| 917 |
+
color: inherit;
|
| 918 |
+
cursor: pointer;
|
| 919 |
+
background: transparent;
|
| 920 |
+
backdrop-filter: blur(var(--perf-blur-low, 24px)) saturate(var(--perf-saturate, 160%));
|
| 921 |
+
-webkit-backdrop-filter: blur(var(--perf-blur-low, 24px)) saturate(var(--perf-saturate, 160%));
|
| 922 |
+
transition:
|
| 923 |
+
border-color 1.2s cubic-bezier(0.4, 0, 0.2, 1),
|
| 924 |
+
box-shadow 160ms ease,
|
| 925 |
+
transform 160ms ease;
|
| 926 |
+
}
|
| 927 |
+
|
| 928 |
+
.toolbar-button:hover {
|
| 929 |
+
border-color: var(--bloom-accent, rgba(148, 163, 184, 0.32));
|
| 930 |
+
box-shadow: 0 10px 28px rgba(8, 11, 19, 0.28);
|
| 931 |
+
}
|
| 932 |
+
|
| 933 |
+
.toolbar-button.is-active {
|
| 934 |
+
border-color: var(--bloom-accent, rgba(59, 130, 246, 0.6));
|
| 935 |
+
box-shadow: 0 10px 28px rgba(59, 130, 246, 0.24);
|
| 936 |
+
}
|
| 937 |
+
|
| 938 |
+
.toolbar-button__label {
|
| 939 |
+
display: inline-flex;
|
| 940 |
+
align-items: center;
|
| 941 |
+
gap: 0.6rem;
|
| 942 |
+
}
|
| 943 |
+
|
| 944 |
+
.toolbar-button__text {
|
| 945 |
+
display: none;
|
| 946 |
+
}
|
| 947 |
+
|
| 948 |
+
.toolbar-button__chip {
|
| 949 |
+
font-size: 0.65rem;
|
| 950 |
+
letter-spacing: 0.16em;
|
| 951 |
+
text-transform: uppercase;
|
| 952 |
+
padding: 0.3rem 0.6rem;
|
| 953 |
+
border-radius: 999px;
|
| 954 |
+
background: transparent;
|
| 955 |
+
backdrop-filter: blur(12px) saturate(130%);
|
| 956 |
+
-webkit-backdrop-filter: blur(12px) saturate(130%);
|
| 957 |
+
border: 1px solid rgba(59, 130, 246, 0.35);
|
| 958 |
+
color: rgba(191, 219, 254, 0.95);
|
| 959 |
+
}
|
| 960 |
+
|
| 961 |
+
.toolbar-button__chevron {
|
| 962 |
+
transition: transform 180ms ease;
|
| 963 |
+
display: inline-flex;
|
| 964 |
+
align-items: center;
|
| 965 |
+
justify-content: center;
|
| 966 |
+
}
|
| 967 |
+
|
| 968 |
+
.toolbar-button__chevron.is-open {
|
| 969 |
+
transform: rotate(180deg);
|
| 970 |
+
}
|
| 971 |
+
|
| 972 |
+
.settings-trigger {
|
| 973 |
+
position: relative;
|
| 974 |
+
}
|
| 975 |
+
|
| 976 |
+
.settings-menu {
|
| 977 |
+
position: fixed;
|
| 978 |
+
top: var(--settings-menu-offset, 88px);
|
| 979 |
+
left: calc(env(safe-area-inset-left, 0px) + 0.75rem);
|
| 980 |
+
right: calc(env(safe-area-inset-right, 0px) + 0.75rem);
|
| 981 |
+
margin: 0;
|
| 982 |
+
max-height: calc(100vh - var(--settings-menu-offset, 88px) - 8rem);
|
| 983 |
+
overflow-y: auto;
|
| 984 |
+
padding: clamp(0.85rem, 1.5vw, 1.2rem);
|
| 985 |
+
border-radius: 18px;
|
| 986 |
+
background: rgba(15, 23, 42, 0.75);
|
| 987 |
+
border: 1px solid rgba(148, 163, 184, 0.25);
|
| 988 |
+
backdrop-filter: blur(48px) saturate(180%) brightness(1.05);
|
| 989 |
+
-webkit-backdrop-filter: blur(48px) saturate(180%) brightness(1.05);
|
| 990 |
+
box-shadow:
|
| 991 |
+
0 25px 60px rgba(2, 6, 23, 0.5),
|
| 992 |
+
0 3px 15px rgba(15, 23, 42, 0.35),
|
| 993 |
+
inset 0 1px 0 rgba(255, 255, 255, 0.06),
|
| 994 |
+
inset 0 0 40px rgba(255, 255, 255, 0.015);
|
| 995 |
+
z-index: 100;
|
| 996 |
+
isolation: isolate;
|
| 997 |
+
will-change: transform;
|
| 998 |
+
transform: translateZ(0);
|
| 999 |
+
transition:
|
| 1000 |
+
border-color 1.2s cubic-bezier(0.4, 0, 0.2, 1),
|
| 1001 |
+
box-shadow 0.3s ease;
|
| 1002 |
+
}
|
| 1003 |
+
/* Hide scrollbar for Chrome, Safari and Opera */
|
| 1004 |
+
.settings-menu::-webkit-scrollbar {
|
| 1005 |
+
display: none;
|
| 1006 |
+
}
|
| 1007 |
+
|
| 1008 |
+
/* Hide scrollbar for IE, Edge and Firefox */
|
| 1009 |
+
.settings-menu {
|
| 1010 |
+
-ms-overflow-style: none; /* IE and Edge */
|
| 1011 |
+
scrollbar-width: none; /* Firefox */
|
| 1012 |
+
}
|
| 1013 |
+
|
| 1014 |
+
.settings-grid {
|
| 1015 |
+
display: grid;
|
| 1016 |
+
gap: 0.85rem;
|
| 1017 |
+
}
|
| 1018 |
+
|
| 1019 |
+
.settings-section {
|
| 1020 |
+
display: flex;
|
| 1021 |
+
flex-direction: column;
|
| 1022 |
+
gap: 0.5rem;
|
| 1023 |
+
}
|
| 1024 |
+
|
| 1025 |
+
.settings-section--wide {
|
| 1026 |
+
grid-column: span 1;
|
| 1027 |
+
}
|
| 1028 |
+
|
| 1029 |
+
.section-heading {
|
| 1030 |
+
font-size: 0.65rem;
|
| 1031 |
+
text-transform: uppercase;
|
| 1032 |
+
letter-spacing: 0.16em;
|
| 1033 |
+
font-weight: 700;
|
| 1034 |
+
margin: 0;
|
| 1035 |
+
color: rgba(203, 213, 225, 0.68);
|
| 1036 |
+
}
|
| 1037 |
+
|
| 1038 |
+
.option-grid {
|
| 1039 |
+
display: grid;
|
| 1040 |
+
gap: 0.45rem;
|
| 1041 |
+
}
|
| 1042 |
+
|
| 1043 |
+
.option-grid--compact {
|
| 1044 |
+
display: grid;
|
| 1045 |
+
grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));
|
| 1046 |
+
gap: 0.4rem;
|
| 1047 |
+
}
|
| 1048 |
+
|
| 1049 |
+
.glass-option {
|
| 1050 |
+
position: relative;
|
| 1051 |
+
display: flex;
|
| 1052 |
+
align-items: center;
|
| 1053 |
+
justify-content: space-between;
|
| 1054 |
+
gap: 0.6rem;
|
| 1055 |
+
border-radius: 12px;
|
| 1056 |
+
border: 1px solid rgba(148, 163, 184, 0.18);
|
| 1057 |
+
background: transparent;
|
| 1058 |
+
backdrop-filter: blur(var(--perf-blur-medium, 28px)) saturate(var(--perf-saturate, 160%));
|
| 1059 |
+
-webkit-backdrop-filter: blur(var(--perf-blur-medium, 28px)) saturate(var(--perf-saturate, 160%));
|
| 1060 |
+
padding: 0.5rem 0.65rem;
|
| 1061 |
+
color: inherit;
|
| 1062 |
+
font-size: 0.8rem;
|
| 1063 |
+
cursor: pointer;
|
| 1064 |
+
text-align: left;
|
| 1065 |
+
transition: border-color 140ms ease, transform 140ms ease, box-shadow 160ms ease;
|
| 1066 |
+
}
|
| 1067 |
+
|
| 1068 |
+
.glass-option--compact {
|
| 1069 |
+
padding: 0.45rem 0.6rem;
|
| 1070 |
+
gap: 0.5rem;
|
| 1071 |
+
border-radius: 10px;
|
| 1072 |
+
}
|
| 1073 |
+
|
| 1074 |
+
.glass-option--compact .glass-option__label {
|
| 1075 |
+
font-size: 0.75rem;
|
| 1076 |
+
font-weight: 600;
|
| 1077 |
+
}
|
| 1078 |
+
|
| 1079 |
+
.glass-option--compact .glass-option__description {
|
| 1080 |
+
display: none;
|
| 1081 |
+
}
|
| 1082 |
+
|
| 1083 |
+
.glass-option:hover {
|
| 1084 |
+
transform: translateY(-1px);
|
| 1085 |
+
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.22);
|
| 1086 |
+
border-color: rgba(148, 163, 184, 0.26);
|
| 1087 |
+
}
|
| 1088 |
+
|
| 1089 |
+
.glass-option.is-active {
|
| 1090 |
+
border-color: var(--bloom-accent, rgba(59, 130, 246, 0.6));
|
| 1091 |
+
background: transparent;
|
| 1092 |
+
box-shadow:
|
| 1093 |
+
0 12px 28px rgba(59, 130, 246, 0.2),
|
| 1094 |
+
inset 0 0 32px rgba(59, 130, 246, 0.06);
|
| 1095 |
+
}
|
| 1096 |
+
|
| 1097 |
+
.glass-option__content {
|
| 1098 |
+
display: flex;
|
| 1099 |
+
flex-direction: column;
|
| 1100 |
+
gap: 0.2rem;
|
| 1101 |
+
}
|
| 1102 |
+
|
| 1103 |
+
.glass-option__label {
|
| 1104 |
+
display: inline-flex;
|
| 1105 |
+
align-items: center;
|
| 1106 |
+
gap: 0.45rem;
|
| 1107 |
+
font-weight: 600;
|
| 1108 |
+
font-size: 0.8rem;
|
| 1109 |
+
}
|
| 1110 |
+
|
| 1111 |
+
.glass-option__description {
|
| 1112 |
+
font-size: 0.68rem;
|
| 1113 |
+
opacity: 0.58;
|
| 1114 |
+
line-height: 1.3;
|
| 1115 |
+
}
|
| 1116 |
+
|
| 1117 |
+
.glass-option__check {
|
| 1118 |
+
color: rgba(191, 219, 254, 0.95);
|
| 1119 |
+
flex-shrink: 0;
|
| 1120 |
+
}
|
| 1121 |
+
|
| 1122 |
+
.glass-option__chip {
|
| 1123 |
+
display: inline-flex;
|
| 1124 |
+
align-items: center;
|
| 1125 |
+
justify-content: center;
|
| 1126 |
+
font-size: 0.66rem;
|
| 1127 |
+
letter-spacing: 0.16em;
|
| 1128 |
+
text-transform: uppercase;
|
| 1129 |
+
padding: 0.2rem 0.55rem;
|
| 1130 |
+
border-radius: 999px;
|
| 1131 |
+
background: transparent;
|
| 1132 |
+
backdrop-filter: blur(16px) saturate(140%);
|
| 1133 |
+
-webkit-backdrop-filter: blur(16px) saturate(140%);
|
| 1134 |
+
border: 1px solid rgba(148, 163, 184, 0.45);
|
| 1135 |
+
color: rgba(226, 232, 240, 0.82);
|
| 1136 |
+
flex-shrink: 0;
|
| 1137 |
+
}
|
| 1138 |
+
|
| 1139 |
+
.glass-option__chip.is-active {
|
| 1140 |
+
border-color: var(--bloom-accent, rgba(59, 130, 246, 0.7));
|
| 1141 |
+
color: rgba(219, 234, 254, 0.95);
|
| 1142 |
+
box-shadow: inset 0 0 20px rgba(59, 130, 246, 0.15);
|
| 1143 |
+
}
|
| 1144 |
+
|
| 1145 |
+
.settings-section--bordered {
|
| 1146 |
+
padding-top: 0.65rem;
|
| 1147 |
+
border-top: 1px solid rgba(148, 163, 184, 0.12);
|
| 1148 |
+
}
|
| 1149 |
+
|
| 1150 |
+
.actions-column {
|
| 1151 |
+
display: flex;
|
| 1152 |
+
flex-direction: column;
|
| 1153 |
+
gap: 0.5rem;
|
| 1154 |
+
}
|
| 1155 |
+
|
| 1156 |
+
.glass-action {
|
| 1157 |
+
display: flex;
|
| 1158 |
+
align-items: center;
|
| 1159 |
+
justify-content: space-between;
|
| 1160 |
+
gap: 0.85rem;
|
| 1161 |
+
border-radius: 14px;
|
| 1162 |
+
border: 1px solid rgba(148, 163, 184, 0.2);
|
| 1163 |
+
background: transparent;
|
| 1164 |
+
backdrop-filter: blur(var(--perf-blur-medium, 28px)) saturate(var(--perf-saturate, 160%));
|
| 1165 |
+
-webkit-backdrop-filter: blur(var(--perf-blur-medium, 28px)) saturate(var(--perf-saturate, 160%));
|
| 1166 |
+
padding: 0.7rem 0.9rem;
|
| 1167 |
+
font-size: 0.8rem;
|
| 1168 |
+
font-weight: 600;
|
| 1169 |
+
color: inherit;
|
| 1170 |
+
cursor: pointer;
|
| 1171 |
+
transition: border-color 140ms ease, box-shadow 160ms ease, transform 160ms ease;
|
| 1172 |
+
}
|
| 1173 |
+
|
| 1174 |
+
.glass-action:disabled {
|
| 1175 |
+
opacity: 0.6;
|
| 1176 |
+
cursor: not-allowed;
|
| 1177 |
+
}
|
| 1178 |
+
|
| 1179 |
+
.glass-action:hover:not(:disabled) {
|
| 1180 |
+
transform: translateY(-1px);
|
| 1181 |
+
border-color: rgba(148, 163, 184, 0.32);
|
| 1182 |
+
box-shadow: 0 10px 28px rgba(8, 11, 19, 0.28);
|
| 1183 |
+
}
|
| 1184 |
+
|
| 1185 |
+
.glass-action__label {
|
| 1186 |
+
display: inline-flex;
|
| 1187 |
+
align-items: center;
|
| 1188 |
+
gap: 0.55rem;
|
| 1189 |
+
}
|
| 1190 |
+
|
| 1191 |
+
.glass-action__spinner {
|
| 1192 |
+
animation: spin 1s linear infinite;
|
| 1193 |
+
color: rgba(203, 213, 225, 0.85);
|
| 1194 |
+
}
|
| 1195 |
+
|
| 1196 |
+
.section-footnote {
|
| 1197 |
+
margin: 0;
|
| 1198 |
+
font-size: 0.68rem;
|
| 1199 |
+
color: rgba(203, 213, 225, 0.58);
|
| 1200 |
+
line-height: 1.4;
|
| 1201 |
+
}
|
| 1202 |
+
|
| 1203 |
+
.app-main {
|
| 1204 |
+
flex: 1;
|
| 1205 |
+
padding: clamp(1.5rem, 2.4vw, 2.75rem);
|
| 1206 |
+
margin: clamp(1rem, 1.5vw, 1.75rem) clamp(0.75rem, 2vw, 1.5rem);
|
| 1207 |
+
border-radius: 20px;
|
| 1208 |
+
position: relative;
|
| 1209 |
+
z-index: 1;
|
| 1210 |
+
}
|
| 1211 |
+
|
| 1212 |
+
.app-main__inner {
|
| 1213 |
+
max-width: min(1100px, 100%);
|
| 1214 |
+
margin: 0 auto;
|
| 1215 |
+
}
|
| 1216 |
+
|
| 1217 |
+
.navigation-overlay {
|
| 1218 |
+
position: fixed;
|
| 1219 |
+
inset: 0;
|
| 1220 |
+
display: flex;
|
| 1221 |
+
flex-direction: column;
|
| 1222 |
+
align-items: center;
|
| 1223 |
+
justify-content: center;
|
| 1224 |
+
gap: 2rem;
|
| 1225 |
+
background: transparent;
|
| 1226 |
+
backdrop-filter: blur(var(--perf-blur-high, 32px)) saturate(var(--perf-saturate, 160%));
|
| 1227 |
+
-webkit-backdrop-filter: blur(var(--perf-blur-high, 32px)) saturate(var(--perf-saturate, 160%));
|
| 1228 |
+
z-index: 50;
|
| 1229 |
+
}
|
| 1230 |
+
|
| 1231 |
+
.navigation-overlay__progress {
|
| 1232 |
+
position: absolute;
|
| 1233 |
+
top: 0;
|
| 1234 |
+
left: 0;
|
| 1235 |
+
right: 0;
|
| 1236 |
+
height: 3px;
|
| 1237 |
+
overflow: hidden;
|
| 1238 |
+
background: transparent;
|
| 1239 |
+
backdrop-filter: blur(8px) saturate(120%);
|
| 1240 |
+
-webkit-backdrop-filter: blur(8px) saturate(120%);
|
| 1241 |
+
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.15);
|
| 1242 |
+
}
|
| 1243 |
+
|
| 1244 |
+
.navigation-progress {
|
| 1245 |
+
position: absolute;
|
| 1246 |
+
top: 0;
|
| 1247 |
+
bottom: 0;
|
| 1248 |
+
left: -40%;
|
| 1249 |
+
width: 60%;
|
| 1250 |
+
background: linear-gradient(
|
| 1251 |
+
90deg,
|
| 1252 |
+
transparent,
|
| 1253 |
+
var(--bloom-accent, rgba(96, 165, 250, 0.9)),
|
| 1254 |
+
transparent
|
| 1255 |
+
);
|
| 1256 |
+
box-shadow: 0 0 12px var(--bloom-accent, rgba(96, 165, 250, 0.5));
|
| 1257 |
+
animation: shimmer 1.2s ease-in-out infinite;
|
| 1258 |
+
}
|
| 1259 |
+
|
| 1260 |
+
.navigation-overlay__content {
|
| 1261 |
+
font-size: 0.78rem;
|
| 1262 |
+
letter-spacing: 0.28em;
|
| 1263 |
+
text-transform: uppercase;
|
| 1264 |
+
color: rgba(226, 232, 240, 0.9);
|
| 1265 |
+
}
|
| 1266 |
+
|
| 1267 |
+
@keyframes shimmer {
|
| 1268 |
+
0% {
|
| 1269 |
+
transform: translateX(0);
|
| 1270 |
+
opacity: 0.2;
|
| 1271 |
+
}
|
| 1272 |
+
50% {
|
| 1273 |
+
transform: translateX(250%);
|
| 1274 |
+
opacity: 0.85;
|
| 1275 |
+
}
|
| 1276 |
+
100% {
|
| 1277 |
+
transform: translateX(400%);
|
| 1278 |
+
opacity: 0;
|
| 1279 |
+
}
|
| 1280 |
+
}
|
| 1281 |
+
|
| 1282 |
+
:global(.animate-spin-slower) {
|
| 1283 |
+
animation: spin-slower 1.8s cubic-bezier(0.4, 0, 0.2, 1) infinite;
|
| 1284 |
+
}
|
| 1285 |
+
|
| 1286 |
+
@keyframes spin {
|
| 1287 |
+
0% {
|
| 1288 |
+
transform: rotate(0deg);
|
| 1289 |
+
}
|
| 1290 |
+
100% {
|
| 1291 |
+
transform: rotate(360deg);
|
| 1292 |
+
}
|
| 1293 |
+
}
|
| 1294 |
+
|
| 1295 |
+
@keyframes spin-slower {
|
| 1296 |
+
0% {
|
| 1297 |
+
transform: rotate(0deg);
|
| 1298 |
+
}
|
| 1299 |
+
100% {
|
| 1300 |
+
transform: rotate(360deg);
|
| 1301 |
+
}
|
| 1302 |
+
}
|
| 1303 |
+
|
| 1304 |
+
@media (min-width: 520px) {
|
| 1305 |
+
.toolbar-button__text {
|
| 1306 |
+
display: inline;
|
| 1307 |
+
}
|
| 1308 |
+
}
|
| 1309 |
+
|
| 1310 |
+
@media (min-width: 768px) {
|
| 1311 |
+
.settings-menu {
|
| 1312 |
+
position: absolute;
|
| 1313 |
+
right: 0;
|
| 1314 |
+
left: auto;
|
| 1315 |
+
width: 30rem;
|
| 1316 |
+
max-height: calc(100vh - var(--settings-menu-offset, 88px) - 8rem);
|
| 1317 |
+
padding: 1.3rem;
|
| 1318 |
+
border-radius: 18px;
|
| 1319 |
+
top: calc(var(--settings-menu-offset, 88px) - 8px);
|
| 1320 |
+
}
|
| 1321 |
+
|
| 1322 |
+
|
| 1323 |
+
.settings-grid {
|
| 1324 |
+
display: grid;
|
| 1325 |
+
grid-template-columns: repeat(2, minmax(0, 1fr));
|
| 1326 |
+
gap: 1.2rem;
|
| 1327 |
+
}
|
| 1328 |
+
|
| 1329 |
+
.settings-section--wide {
|
| 1330 |
+
grid-column: span 2;
|
| 1331 |
+
}
|
| 1332 |
+
|
| 1333 |
+
.option-grid--compact {
|
| 1334 |
+
grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
|
| 1335 |
+
}
|
| 1336 |
+
|
| 1337 |
+
.settings-section--bordered {
|
| 1338 |
+
border-top: none;
|
| 1339 |
+
padding-top: 0;
|
| 1340 |
+
}
|
| 1341 |
+
}
|
| 1342 |
+
|
| 1343 |
+
@media (max-width: 640px) {
|
| 1344 |
+
.app-header {
|
| 1345 |
+
border-radius: 0;
|
| 1346 |
+
padding: 0.65rem 1rem;
|
| 1347 |
+
}
|
| 1348 |
+
|
| 1349 |
+
.toolbar {
|
| 1350 |
+
gap: 0.5rem;
|
| 1351 |
+
}
|
| 1352 |
+
|
| 1353 |
+
.toolbar-button {
|
| 1354 |
+
padding: 0.5rem 0.8rem;
|
| 1355 |
+
}
|
| 1356 |
+
|
| 1357 |
+
.app-main {
|
| 1358 |
+
padding: 1.4rem;
|
| 1359 |
+
margin: 1rem 0.75rem;
|
| 1360 |
+
}
|
| 1361 |
+
}
|
| 1362 |
+
</style>
|
src/routes/+page.server.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { LayoutServerLoad } from './$types';
|
| 2 |
+
import { env } from '$env/dynamic/private';
|
| 3 |
+
|
| 4 |
+
export const load: LayoutServerLoad = () => {
|
| 5 |
+
return {
|
| 6 |
+
title: env.TITLE ?? 'BiniLossless',
|
| 7 |
+
slogan: env.SLOGAN ?? 'The easiest way to stream Hi-Res lossless FLACs.'
|
| 8 |
+
};
|
| 9 |
+
};
|
src/routes/+page.svelte
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<script lang="ts">
|
| 2 |
+
import SearchInterface from '$lib/components/SearchInterface.svelte';
|
| 3 |
+
import { type Track, type PlayableTrack, isSonglinkTrack } from '$lib/types';
|
| 4 |
+
import { playerStore } from '$lib/stores/player';
|
| 5 |
+
import { onMount } from 'svelte';
|
| 6 |
+
import { APP_VERSION } from '$lib/version';
|
| 7 |
+
import { losslessAPI } from '$lib/api.js';
|
| 8 |
+
|
| 9 |
+
let { data } = $props();
|
| 10 |
+
|
| 11 |
+
onMount(() => {
|
| 12 |
+
if (APP_VERSION) {
|
| 13 |
+
try {
|
| 14 |
+
umami.track('app_loaded', { version: APP_VERSION, host: window.location.hostname } );
|
| 15 |
+
} catch {}
|
| 16 |
+
}
|
| 17 |
+
});
|
| 18 |
+
|
| 19 |
+
async function fillQueueWithRecommendations(track: PlayableTrack) {
|
| 20 |
+
if (isSonglinkTrack(track)) return;
|
| 21 |
+
|
| 22 |
+
const recommendations = await losslessAPI.getRecommendations(track.id);
|
| 23 |
+
playerStore.setQueue([track, ...recommendations], 0);
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
function handleTrackSelect(track: PlayableTrack) {
|
| 27 |
+
playerStore.setQueue([track], 0);
|
| 28 |
+
playerStore.play();
|
| 29 |
+
|
| 30 |
+
fillQueueWithRecommendations(track);
|
| 31 |
+
}
|
| 32 |
+
</script>
|
| 33 |
+
|
| 34 |
+
<svelte:head>
|
| 35 |
+
<title>{data.title}</title>
|
| 36 |
+
<meta name="description" content="Stream and download lossless music in Hi-Res, CD quality, and more" />
|
| 37 |
+
</svelte:head>
|
| 38 |
+
|
| 39 |
+
<div class="homepage">
|
| 40 |
+
<!-- Hero Section -->
|
| 41 |
+
<section class="hero">
|
| 42 |
+
<div class="hero__content">
|
| 43 |
+
<div class="hero__title-wrapper">
|
| 44 |
+
<h1 class="hero__title">{data.title}</h1>
|
| 45 |
+
<span class="hero__version text-gray-400">{APP_VERSION}</span>
|
| 46 |
+
</div>
|
| 47 |
+
<p class="hero__slogan">{data.slogan}</p>
|
| 48 |
+
</div>
|
| 49 |
+
</section>
|
| 50 |
+
|
| 51 |
+
<!-- Search Interface -->
|
| 52 |
+
<section class="search-section">
|
| 53 |
+
<SearchInterface onTrackSelect={handleTrackSelect} />
|
| 54 |
+
</section>
|
| 55 |
+
</div>
|
| 56 |
+
|
| 57 |
+
<style>
|
| 58 |
+
.homepage {
|
| 59 |
+
display: flex;
|
| 60 |
+
flex-direction: column;
|
| 61 |
+
gap: var(--space-10, 2.5rem);
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
.hero {
|
| 65 |
+
padding: var(--space-10, 2.5rem) 0 var(--space-6, 1.5rem);
|
| 66 |
+
text-align: center;
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
.hero__content {
|
| 70 |
+
max-width: 42rem;
|
| 71 |
+
margin: 0 auto;
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
.hero__title-wrapper {
|
| 75 |
+
display: inline-flex;
|
| 76 |
+
align-items: baseline;
|
| 77 |
+
gap: var(--space-3, 0.75rem);
|
| 78 |
+
margin-bottom: var(--space-4, 1rem);
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
.hero__title {
|
| 82 |
+
font-size: clamp(2.5rem, 8vw, 4rem);
|
| 83 |
+
font-weight: 700;
|
| 84 |
+
line-height: 1.1;
|
| 85 |
+
margin: 0;
|
| 86 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
|
| 87 |
+
background-size: 200% 200%;
|
| 88 |
+
-webkit-background-clip: text;
|
| 89 |
+
background-clip: text;
|
| 90 |
+
color: transparent;
|
| 91 |
+
animation: gradient-shift 8s ease infinite;
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
@keyframes gradient-shift {
|
| 95 |
+
0%, 100% { background-position: 0% 50%; }
|
| 96 |
+
50% { background-position: 100% 50%; }
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
.hero__version {
|
| 100 |
+
font-size: 0.75rem;
|
| 101 |
+
font-weight: 500;
|
| 102 |
+
letter-spacing: 0.05em;
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
@keyframes float {
|
| 106 |
+
0%, 100% { transform: translateY(0); }
|
| 107 |
+
50% { transform: translateY(-1px); }
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
.hero__slogan {
|
| 111 |
+
font-size: clamp(1rem, 2.5vw, 1.25rem);
|
| 112 |
+
color: rgba(148, 163, 184, 0.9);
|
| 113 |
+
margin: 0;
|
| 114 |
+
line-height: 1.6;
|
| 115 |
+
max-width: 36rem;
|
| 116 |
+
margin: 0 auto;
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
.search-section {
|
| 120 |
+
width: 100%;
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
/* Mobile adjustments */
|
| 124 |
+
@media (max-width: 640px) {
|
| 125 |
+
.hero {
|
| 126 |
+
padding: var(--space-6, 1.5rem) 0 var(--space-4, 1rem);
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
.hero__title-wrapper {
|
| 130 |
+
flex-direction: column;
|
| 131 |
+
align-items: center;
|
| 132 |
+
gap: var(--space-2, 0.5rem);
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
.hero__version {
|
| 136 |
+
margin-top: var(--space-1, 0.25rem);
|
| 137 |
+
}
|
| 138 |
+
}
|
| 139 |
+
</style>
|
| 140 |
+
|