Compare commits

...
64 Commits
Author SHA1 Message Date
mrleo1nidandCursor efe78d7e07 feat(desktop): wrap the web client in a Tauri app
ci / api / api (push) Successful in 43s
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 1m19s
ci / desktop / rust (desktop proxy) (push) Failing after 3m34s
ci / ts / ts (packages + web) (push) Failing after 2m49s
release / release (версия и заметки) (push) Successful in 5s
ci / db / db (push) Successful in 40s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 1m12s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Successful in 1m28s
release / android (APK в релиз) (push) Failing after 2m0s
EOF

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 23:45:03 +03:00
mrleo1nidandCursor fa79394869 feat: add personal playlists and shareable track links
release / release (версия и заметки) (push) Successful in 6s
release / android (APK в релиз) (push) Successful in 4m8s
EOF

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 23:37:53 +03:00
mrleo1nid 3a097c15c8 perf(web): preload restored audio before playback
ci / ts / ts (packages + web) (push) Successful in 2m20s
release / release (версия и заметки) (push) Successful in 5s
release / android (APK в релиз) (push) Successful in 3m43s
2026-10-21 22:49:10 +03:00
mrleo1nid 20abe20686 fix(mobile): prevent crash when restoring a saved playback queue
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 1m32s
ci / ts / ts (packages + web) (push) Successful in 2m49s
release / release (версия и заметки) (push) Successful in 9s
release / android (APK в релиз) (push) Successful in 4m20s
2026-10-21 18:41:48 +03:00
mrleo1nid c34272d508 fix(auth): allow admins to change any username including their own
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 1m6s
ci / api / api (push) Successful in 49s
ci / db / db (push) Successful in 1m17s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 1m25s
ci / ts / ts (packages + web) (push) Successful in 2m59s
2026-10-21 17:33:19 +03:00
mrleo1nid b0cbd0f149 fix: repair Android startup and improve mobile web layouts
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 1m17s
ci / ts / ts (packages + web) (push) Successful in 2m22s
release / android (APK в релиз) (push) Successful in 4m15s
release / release (версия и заметки) (push) Successful in 6s
2026-10-21 17:14:05 +03:00
mrleo1nid 4c2286e70d feat(web): react wave and ambient visuals to live audio
ci / ts / ts (packages + web) (push) Failing after 2m2s
2026-10-21 16:44:04 +03:00
mrleo1nid 9223516547 fix(web): soften wave glow and follow liquid shape
ci / ts / ts (packages + web) (push) Successful in 2m25s
2026-10-21 16:33:22 +03:00
mrleo1nidandClaude Opus 5.5 7b7ce78de8 fix(web): align the upload queue settings fields
ci / ts / ts (packages + web) (push) Successful in 1m53s
Labels that wrapped to two lines pushed their inputs down, the storage
select had its own label style, and the checkbox sat in the middle of its
cell. The section now lays label, input and hint rows out with subgrid, and
the select no longer stretches past its column.

Also add a web-fake launch config that runs the web app on the fake API.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 10:44:20 +03:00
mrleo1nidandClaude Opus 5.5 4d2c6ce22f fix(web): treat AIFF and WavPack as lossless in the upload format hint
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 1m30s
ci / ts / ts (packages + web) (push) Successful in 2m11s
The web check only accepted FLAC and WAV, so AIFF files were flagged
"needs attention" although the server already counts them as lossless.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 10:35:43 +03:00
mrleo1nidandClaude Opus 5.5 dca7173a88 ci(ts): install Playwright system deps and cache the browser
ci / ts / ts (packages + web) (push) Successful in 3m30s
E2e failed to launch Chromium on the runner (missing libnspr4.so). Install
with --with-deps and cache ~/.cache/ms-playwright, since the primary download
host is unreachable from the runner and the fallback takes minutes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 10:25:21 +03:00
mrleo1nid 1e3b350dfc feat(upload): enhance audio upload handling and user feedback
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 1m1s
ci / db / db (push) Successful in 1m16s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 1m12s
ci / api / api (push) Successful in 45s
ci / recommender / recommender (push) Successful in 1m50s
ci / ts / ts (packages + web) (push) Failing after 6m53s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Successful in 1m13s
- Introduced a new warning for users uploading non-FLAC or WAV formats, indicating that these formats should only be used as a last resort.
- Added functionality to highlight files needing format attention in the upload queue.
- Updated the UI to provide clearer guidance on acceptable audio formats during uploads.
- Improved documentation to reflect changes in upload requirements and user interface updates.
2026-10-21 10:07:43 +03:00
mrleo1nidandClaude Opus 5.5 74da457362 feat(auth): make upload review a separate grant instead of an admin privilege
Reviewing the upload queue is now a per-user flag (reviews_uploads), not part
of the admin role: several people can hold it, a moderator can have it, and an
admin may not. Only admins grant or revoke it; existing admins keep it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 10:07:05 +03:00
mrleo1nidandCursor 066ba24834 feat: finish the upload, playback, and test gaps from the docs
ci / api / api (push) Successful in 40s
ci / db / db (push) Successful in 1m3s
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Failing after 1m48s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Successful in 46s
ci / ts / ts (packages + web) (push) Failing after 4m57s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 5m7s
Quality upgrades, batch covers, staging preview, and resume after reload are in the queue. Loudness and crossfade work on web and Android, and the documented checks now have suites.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 09:37:53 +03:00
mrleo1nidandCursor 2b76060ea3 fix(web): keep menu labels on one line and fold the admin section by default
ci / ts / ts (packages + web) (push) Successful in 1m27s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 09:06:33 +03:00
mrleo1nidandCursor dfc72b1d69 chore(deploy): leave database backups to external tools
ci / db / db (push) Successful in 1m40s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Successful in 3m51s
ci / ts / ts (packages + web) (push) Successful in 54s
The app no longer dumps Postgres, restores it, or checks copies in CI.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 09:03:06 +03:00
mrleo1nidandClaude Opus 5.5 978f03b8f8 feat(admin): reset a user's recommendations from the users panel
ci / api / api (push) Successful in 40s
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 55s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 1m10s
ci / db / db (push) Successful in 2m35s
ci / ts / ts (packages + web) (push) Successful in 1m23s
- POST /admin/users/{id}/reset-recommendations clears the taste profile
  (onboarding, CF vector, bandit), play stats and wave impressions; likes,
  dislikes and history stay, wave sessions stay so a playing wave keeps going
- moderators may reset plain users, admins anyone including themselves;
  the reset is written to the audit log
- users panel gets the menu action with a confirmation; docs updated

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 08:52:31 +03:00
mrleo1nidandClaude Opus 5.5 b27b915b63 feat(web): settings to keep the search open and hide home pickers; collapsible menu sections
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 2m44s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 1m43s
ci / ts / ts (packages + web) (push) Successful in 1m16s
ci / api / api (push) Successful in 2m27s
ci / db / db (push) Successful in 2m23s
- appearance settings get "collapse search" (off keeps the field always open)
  and separate switches for the activity and mood pickers on the home page;
  stored in ui_prefs (search_collapse, home_activities, home_moods)
- Collection and Admin headers in the sidebar fold their items; the state is
  remembered in the browser, a folded Admin shows the review queue badge;
  icon-only and phone layouts always show every item

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 08:26:48 +03:00
mrleo1nidandClaude Opus 5.5 73e642c1ec fix(mobile): APK starts on Android 15+ 16 KB page devices and emulators
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 2m56s
release / android (APK в релиз) (push) Successful in 4m53s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 3m27s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Successful in 1m2s
ci / ts / ts (packages + web) (push) Successful in 1m48s
release / release (версия и заметки) (push) Successful in 8s
On an Android 16 emulator the release APK crashed at launch with
"Cannot read property 'NativeModule' of undefined": libexpo-modules-core.so
was missing for the ABI the device picked. Two build defects:

- librnskia.so was linked with 4 KB segment alignment (Skia 2.0.0-next.4
  lacks ANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES), so 16 KB page devices cannot
  load it; a pnpm patch adds the flag
- the APK carried incomplete x86, x86_64 and armeabi-v7a folders from the
  React Native libraries; an Expo config plugin keeps only arm64-v8a, the ABI
  the native modules are built for (the APK also halves in size)

scripts/check-apk.mjs now fails the release on another ABI, a missing core
library or a library not aligned to 16 KB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 03:22:13 +03:00
mrleo1nidandClaude Opus 5.5 66f5749fc1 fix(deploy): take the Gitea address for Android updates from git remote
ci / api / api (push) Successful in 22s
ci / db / db (push) Successful in 2m4s
release / release (версия и заметки) (push) Successful in 5s
release / android (APK в релиз) (push) Successful in 4m11s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Successful in 1m33s
The server kept the git.example.lan placeholder from .env.example, so the
/android page and in-app updates had no release. install.sh and update.sh now
fill GITEA_URL and GITEA_REPO from the clone's origin (https, ssh and scp
forms, credentials stripped) when they are empty or still the placeholder,
and the API treats the placeholder as not configured.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 00:23:28 +03:00
mrleo1nidandClaude Opus 5.5 823d1eb841 fix(web): suggestions stay open when you return to the search quickly
ci / ts / ts (packages + web) (push) Successful in 1m1s
release / android (APK в релиз) (push) Successful in 4m10s
release / release (версия и заметки) (push) Successful in 6s
Leaving the field scheduled a close 120 ms later; coming back and typing
within that window let the old timer hide the fresh suggestions. Focus now
cancels the pending close. This also made the search box test flaky.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 00:13:08 +03:00
mrleo1nidandClaude Opus 5.5 860072e542 feat(web): choose where the search sits, and controls no longer select text
ci / api / api (push) Successful in 36s
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 48s
ci / ts / ts (packages + web) (push) Canceled after 12s
ci / db / db (push) Successful in 2m43s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 59s
- settings get a search position (left, center by default, right); the top bar
  is three zones and the suggestions open towards the free space
- buttons, chips, tabs, menu items and the home screen controls are not
  text-selectable, so clicks and double clicks no longer highlight labels

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 00:11:06 +03:00
mrleo1nidandClaude Opus 5.5 d2f17d8d62 ci(db): fail early with a clear message when the runner disk is full
ci / db / db (push) Successful in 45s
release / release (версия и заметки) (push) Successful in 6s
release / android (APK в релиз) (push) Successful in 3m47s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 00:03:32 +03:00
mrleo1nidandClaude Opus 5.5 4763339335 ci(db): wait for the service containers before the tests
ci / db / db (push) Successful in 53s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 23:59:28 +03:00
mrleo1nidandClaude Opus 5.5 fda6ed48ab feat: Android download page, analysis retry and a collapsible search
ci / api / api (push) Successful in 37s
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 46s
ci / db / db (push) Failing after 14s
ci / recommender / recommender (push) Successful in 51s
ci / ts / ts (packages + web) (push) Successful in 57s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 1m2s
- /android is a public page with the latest APK, the server address to copy
  and three install steps; linked from the sign-in screen and the profile menu
- failed audio analysis can be retried from the library page, which also shows
  the most common error; the analyzer no longer burns attempts on files that
  are missing because the disk is not mounted
- the top bar search folds into a round button and slides open on click, "/"
  or Ctrl+K

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 23:55:51 +03:00
mrleo1nidandClaude Opus 5.5 2d49cb3f19 fix(web): header dropdowns sit above the page again
ci / ts / ts (packages + web) (push) Successful in 50s
release / release (версия и заметки) (push) Successful in 5s
release / android (APK в релиз) (push) Successful in 3m45s
Every shell child got the same z-index, so the page painted over the search
suggestions and the profile menu and swallowed their clicks: suggestions could
not be picked, and the language switch and settings item did nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 23:47:18 +03:00
mrleo1nidandClaude Opus 5.5 3da82e902a fix(library): survive a music disk that is not mounted
ci / api / api (push) Successful in 29s
ci / db / db (push) Successful in 47s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Successful in 52s
release / release (версия и заметки) (push) Successful in 4s
release / android (APK в релиз) (push) Successful in 3m20s
On the test server the host music folder was not mounted, so every stream and
fingerprint failed with no such file, and a scan of the empty folder would have
marked the whole library missing and purged it after 30 days.

- a scan of an empty source folder with known files aborts with a clear error
- fingerprinting skips such a source with one warning instead of one per file
- LIBRARY_HOST mounts use rslave, so a disk mounted after start shows up
- update.sh refuses to deploy with an empty LIBRARY_HOST

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 23:34:52 +03:00
mrleo1nidandClaude Opus 5.5 421b1a3eb9 ci: allow manual runs of the db and mobile checks
ci / db / db (push) Successful in 54s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 56s
release / release (версия и заметки) (push) Successful in 5s
release / android (APK в релиз) (push) Successful in 3m24s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 23:18:11 +03:00
mrleo1nidandClaude Opus 5.5 b8243c3072 docs(roadmap): M6 and M7 status
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 23:15:59 +03:00
mrleo1nidandClaude Opus 5.5 30f063456e fix(mobile): white text sits on the contrast-safe accent fill (M7)
ci / mobile / mobile (Metro-бандл Android) (push) Failing after 7s
ci / ts / ts (packages + web) (push) Successful in 49s
Primary buttons, selected segments and context chips use accent-fill, as on
the web, so their labels meet WCAG AA contrast.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 23:15:38 +03:00
mrleo1nidandClaude Opus 5.5 de4e59d9f8 fix(web): accessibility pass to WCAG 2.1 AA (M7)
ci / mobile / mobile (Metro-бандл Android) (push) Canceled after 31s
ci / ts / ts (packages + web) (push) Canceled after 0s
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 44s
An axe-core audit of every screen in both themes found low contrast on white
text over the accent and on caption text, track rows using row roles without
cells, and unlabelled progress bars. Accent fills now use a darker token,
caption text meets 4.5:1, track lists are lists and progress bars are labelled.
The queue drawer slides in from the right as designed, takes focus, closes on
Escape and notes that the wave never ends.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 23:15:03 +03:00
mrleo1nidandClaude Opus 5.5 c0e50bf88e docs: administrator guide (M7)
Day-to-day operation after install: users and roles, storages and scans, the
upload queue, wave metrics and training, updates, backups and restore,
monitoring and common situations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 23:02:54 +03:00
mrleo1nidandClaude Opus 5.5 86c3e4e477 test(load): k6 smoke for 100 wave listeners and 20 rps suggest (M7)
Three minutes of wave sessions with stream starts, play events and next batches
alongside a steady suggest load; thresholds follow the documented p95 targets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 23:01:10 +03:00
mrleo1nidandClaude Opus 5.5 aacf55679a feat(deploy): nightly database backups with verified restore (M7)
ci / db / db (push) Failing after 52s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Successful in 1m3s
A backup container dumps the database every night, keeps 14 daily and 8 weekly
copies and once a week restores a copy into a scratch database to check tables
and row counts. update.sh takes a copy before updating, restore.sh brings one
back and keeps the old database aside. CI runs the dump, verify and restore
cycle on the database the end-to-end journey filled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 22:59:27 +03:00
mrleo1nidandClaude Opus 5.5 d91ff89c64 feat(admin): wave metrics split by model version (M6)
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 51s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 1m5s
ci / ts / ts (packages + web) (push) Successful in 1m3s
ci / api / api (push) Successful in 29s
ci / db / db (push) Failing after 12s
The library page compares listen-through, early-skip and like rates per
impression model version, so v1 and the trained ranker can be compared online.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 22:57:11 +03:00
mrleo1nidandClaude Opus 5.5 fbbe5d7528 feat(search): personalize suggestions by listening history (M6)
ci / api / api (push) Successful in 18s
ci / db / db (push) Successful in 30s
Suggest fetches three times as many candidates and reranks them in the API:
what the user plays, finishes and likes moves up a few positions and what they
dislike moves down, with Meilisearch relevance still the base order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 22:55:07 +03:00
mrleo1nidandClaude Opus 5.5 e250837de9 fix(search): reindex on a fresh Meilisearch
ci / db / db (push) Successful in 34s
release / release (версия и заметки) (push) Successful in 5s
ci / api / api (push) Successful in 19s
release / android (APK в релиз) (push) Successful in 3m17s
Deleting a missing <uid>_next index is accepted with 202 and fails inside the
task with index_not_found. That error was not treated as not-found, so the first
reindex aborted and search stayed unavailable until indexes existed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 22:44:59 +03:00
mrleo1nidandClaude Opus 5.5 58bd14ef38 feat(recommender): LightGBM lambdarank ranker with impression features (M6)
ci / db / db (push) Failing after 1m15s
ci / api / api (push) Successful in 17s
ci / recommender / recommender (push) Successful in 32s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Successful in 1m41s
The wave logs each served candidate's feature vector to rec_impression_features.
Nightly training joins them with impression outcomes, validates on the last week
and activates the model only when it beats the v1 order and the active model.
The service loads the active ranker and uses its order in place of the v1 score.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 22:41:26 +03:00
mrleo1nidandClaude Opus 5.5 fb07f962eb feat: taste onboarding for new listeners (M6)
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 1m2s
ci / db / db (push) Failing after 1m29s
ci / ts / ts (packages + web) (push) Successful in 49s
ci / api / api (push) Successful in 1m25s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 48s
ci / recommender / recommender (push) Successful in 21s
- GET /onboarding offers the library's top artists (with album covers)
  and genres and says whether to show it (not done and < 10 plays);
  PUT /me/onboarding stores the choice or a skip (migration 00009).
- The recommender seeds the taste from it while the user has fewer than
  30 scored tracks: chosen artists' tracks +1, chosen genres +0.5.
- Web: onboarding replaces the wave on the home page until done or
  skipped; artist grid with covers, genre chips, at least 3 artists.
- e2e journey and the recommender DB test cover it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 22:35:43 +03:00
mrleo1nidandClaude Opus 5.5 ff0aafdb1e feat(recommender): Thompson-sampling bandit over candidate sources (M6)
ci / recommender / recommender (push) Failing after 4s
ci / db / db (push) Failing after 2m21s
Nightly Beta(α, β) per user and source from wave impressions (reward:
complete or like, ×0.99 daily decay) stored in user_profiles_rec.bandit;
the wave adds 0.2·(θ − 0.5) per candidate source, sources without data
stay neutral. The user's exploration share now follows how well `fresh`
does against the other sources.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 22:31:24 +03:00
mrleo1nidandClaude Opus 5.5 f7722e28ad ci(release): rebalance APK build memory so it does not thrash and get OOM-killed
release / android (APK в релиз) (push) Successful in 3m19s
release / release (версия и заметки) (push) Successful in 8s
v0.7.3 crawled for 35 minutes at the 6 GB cap and was killed without a
log. The container now gets 7 GB, the Gradle heap is 2 GB, the Metro
node process is capped at 1.5 GB and the job times out after 60 minutes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 22:12:54 +03:00
mrleo1nidandClaude Opus 5.5 ed0302d90f docs(uploads): import writes only the final track file
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 22:11:56 +03:00
mrleo1nidandClaude Opus 5.5 85fceaa686 fix(storage-agent): write nothing but the music files to the mounted storage
ci / api / api (push) Successful in 50s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Failing after 10s
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Failing after 31m43s
ci / db / db (push) Failing after 19s
- Imported tracks are created directly under their final name with
  O_EXCL (never overwriting; " (2)" on conflict), fsync'ed and checked
  against SHA-256 — no hidden .pipu-tmp file next to them any more.
- On any failure the agent removes its own partial file and the empty
  directories it created for it.
- The write check uses access(W_OK) and the read-only mount flag instead
  of creating and deleting .pipu-write-test in the storage root.
- Tests assert the storage tree holds only audio files after successful
  and failed writes and after the write check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:22:49 +03:00
mrleo1nidandClaude Opus 5.5 6ad49fe0e3 fix(wave): switch to the new context right away when activity or mood changes
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 1m38s
ci / ts / ts (packages + web) (push) Successful in 1m47s
release / release (версия и заметки) (push) Successful in 12s
release / android (APK в релиз) (push) Failing after 34m58s
Changing the activity or mood used to keep the current track playing
and only replace the upcoming ones, so nothing seemed to happen. Now the
first track of the new batch starts immediately (web and Android). The
interrupted track is not reported to the wave as a skip and is recorded
in history only if it played for at least 30 s, so a context change does
not teach the recommender a false dislike.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:18:26 +03:00
mrleo1nidandClaude Opus 5.5 7cf741d82f ci(release): recover from a corrupted Gradle cache instead of failing
release / release (версия и заметки) (push) Successful in 10s
release / android (APK в релиз) (push) Successful in 9m5s
A hard reboot of the runner VM mid-build left broken transform metadata
in the persistent Gradle cache ("Could not read workspace metadata").
The APK step now detects it, drops the transforms cache and retries the
build once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:04:33 +03:00
mrleo1nidandClaude Opus 5.5 4fb4e124a0 ci(release): cap the Android build so it cannot freeze the runner host
release / android (APK в релиз) (push) Failing after 2m4s
release / release (версия и заметки) (push) Successful in 9s
The APK job container now runs with --cpus=3 --memory=6g and no swap;
CMake / ninja for the React Native native code are limited to 2 jobs
(they used every core), and Gradle runs under nice / ionice. Notes for
hypervisor-hosted runners (Proxmox) are in docs/ci-cd.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 18:59:46 +03:00
mrleo1nidandClaude Opus 5.5 4cca427b82 test(e2e): log service warnings and give search indexing more time
ci / api / api (push) Successful in 33s
ci / db / db (push) Failing after 1m34s
release / release (версия и заметки) (push) Successful in 11s
release / android (APK в релиз) (push) Canceled after 29m27s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 18:29:17 +03:00
mrleo1nidandClaude Opus 5.5 2285107d04 test: end-to-end user journey in CI; fix ALS vectors for small libraries
ci / api / api (push) Successful in 30s
ci / recommender / recommender (push) Successful in 30s
ci / db / db (push) Failing after 1m8s
- newApp (extracted from main) is the exact production wiring; the
  `ci / db` job now also runs it on PostgreSQL, Redis and Meilisearch
  and walks the main user flows over HTTP: first admin sign-in and
  credential change, local source and scan, search, album / artist /
  top tracks, signed stream, events and history, likes, fallback wave,
  playback state, upload queue up to review.
- ALS on a small library produced fewer than 64 factors and the insert
  into vector(64) failed; vectors are now zero-padded to the column size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 18:26:36 +03:00
mrleo1nidandClaude Opus 5.5 f5c276092f ci: integration tests on PostgreSQL + pgvector for migrations and store SQL
ci / db / db (push) Failing after 53s
ci / api / api (push) Successful in 34s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Successful in 1m9s
ci / recommender / recommender (push) Successful in 36s
New `ci / db` job with a pgvector service: Go applies all migrations,
rolls them back to zero and applies them again, then runs the scanner,
fingerprint, write-template, top-tracks and upload-queue store queries;
Python runs the analysis worker, catalog / profile loading and a full
ALS training run against the same schema. Until now this SQL ran
nowhere before reaching a real server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 18:18:44 +03:00
mrleo1nidandClaude Opus 5.5 1c4e209e86 feat(web): align the web UI with the design prototype
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 52s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 1m36s
ci / ts / ts (packages + web) (push) Successful in 1m39s
ci / api / api (push) Successful in 43s
- Ambient background in the app shell: three drifting blurred blobs,
  the third one tinted with the current track's cover; can be turned off
  in settings and stays still with reduced motion.
- Island player variant (floating glass panel) next to the bar, chosen
  in settings; player source line ("Album · …", "My Wave"), reactions
  around the transport controls, queue drawer.
- Sidebar: like / dislike counters, pending uploads badge on Queue,
  admin Settings page holding the upload queue limits.
- Collection: header tile with kicker, underline tabs, time / number
  lead column with an equalizer for the current track, album column,
  dimmed dislikes with undo, Play all / Shuffle pills.
- Album: cover-tinted header and Play / Shuffle; artist: artist wave,
  Play and popular tracks (new GET /artists/{id}/top-tracks).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 18:13:24 +03:00
mrleo1nidandClaude Opus 5.5 3afed02f23 feat(recommender): nightly ALS with offline metrics and CF candidates in the wave (M6)
ci / recommender / recommender (push) Successful in 37s
- Implicit scores from play events and reactions per the signals table
  (90-day half-life, weaker skips outside the wave, dislikes override).
- numpy ALS for implicit feedback; time-split evaluation on the last
  7 days (NDCG@10, Recall@50) against a popularity baseline; a new model
  is activated only if NDCG@10 does not regress by more than 2%.
- Vectors are written to track_embeddings.cf and user_profiles_rec.taste_cf,
  versions to model_versions; NightlyTrainer runs at TRAIN_HOUR and on
  first start, `pipu-rec train` runs it manually.
- Wave: cf and item_cf candidate sources and a 0.10 cf term in the v1
  score; impressions are tagged heuristic-v1+cf.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 17:54:25 +03:00
mrleo1nidandClaude Opus 5.5 a3f212d253 feat(web): suggest tracks, my uploads and admin upload queue screens (M5.5)
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 3m4s
ci / ts / ts (packages + web) (push) Successful in 1m23s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Successful in 52s
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 1m51s
- Suggest tracks: drag-and-drop of files and folders with relative
  paths, streaming SHA-256 in a Web Worker (hash-wasm), duplicate
  precheck, batch reservation and tus-js-client upload (8 MB chunks,
  4 in parallel, token refresh on 401, resume of failed files).
- My uploads: statuses, rejection reasons, withdraw, quota meter.
- Upload queue (admin): status tabs, possible-duplicate filter, batches,
  metadata and storage editing, bulk approve / reject with a reason,
  import retry, and the queue settings form.
- Sidebar section for moderators and admins; ru / en strings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 17:46:18 +03:00
mrleo1nidandClaude Opus 5.5 ca106e8eb1 feat(api): upload queue with quota, tus intake, processing and import (M5.5)
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 1m3s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 1m22s
ci / ts / ts (packages + web) (push) Successful in 1m38s
ci / api / api (push) Successful in 46s
- Migration 00008: upload_batches, upload_files, upload_quota.
- Quota reserved under a row lock when a batch is created; every status
  change goes through one transition that frees space in the same
  transaction. SHA-256 duplicates are rejected before any upload.
- tus 1.0.0 core (HEAD/PATCH) for the author only; offset is the real
  staging file size, data beyond the declared size is refused (ADR-015).
- Processing worker: ffprobe checks, SHA-256 verification, exact and
  Chromaprint duplicates against library and queue, metadata from tags
  or the dropped folder path, possible_duplicate on metadata match, and
  the target path from write_template reusing existing folder spelling.
- Import worker: edited tags written with ffmpeg stream copy, file
  written by storage-agent, point scan of the new file, imported status;
  idempotent and resumed after restart. Stale uploads expire after 24 h,
  orphan staging files are removed at startup.
- API: quota, precheck, batches, my uploads, withdraw, admin list,
  metadata edit, bulk review, retry and queue settings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 17:23:05 +03:00
mrleo1nidandClaude Opus 5.5 f66be2ba0a feat: storage writes via storage-agent, accepts_uploads and write_template (M5.5)
ci / api / api (push) Successful in 33s
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 43s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 1m11s
ci / ts / ts (packages + web) (push) Successful in 1m10s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Successful in 51s
- storage-agent: POST /internal/files copies a staged file into a source
  (temp file, fsync, SHA-256 check, hard link so nothing is overwritten,
  " (2)" suffix on conflict, owner PIPU_FILE_UID/GID) and
  POST /internal/files/test. NFS sources that accept uploads are mounted
  rw in an agent-only /library-rw and bind-mounted read-only for others;
  local sources are written through /library-host-rw.
- meta: write templates ({track:02}, {disc:1-}, [optional]) with name
  sanitising and length limits, suggestion from the source's regexes
  and a reversibility check against 50 catalogue tracks.
- API and admin UI: accepts_uploads / write_template on sources,
  write-template suggest and check endpoints, write test result.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 13:46:56 +03:00
mrleo1nidandClaude Opus 5.5 9b50038bb4 feat(api): SHA-256 and Chromaprint fingerprints for the library (M5.5)
ci / api / api (push) Successful in 27s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Successful in 58s
A background Fingerprinter runs after every scan and at startup, one file
at a time, filling media_files.sha256 and track_fingerprints (fpcalc raw,
first 120 s). Without fpcalc only SHA-256 is computed and files stay
queued for Chromaprint. Changing a file's content resets its prints.
Similarity() compares raw prints with a ±80-point alignment search; it is
the basis for duplicate detection in the upload queue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 13:37:05 +03:00
mrleo1nidandClaude Opus 5.5 ed063d3763 feat(mobile): Skia wave, wave player view, themes and playback settings (M5)
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 1m30s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 2m57s
ci / ts / ts (packages + web) (push) Successful in 1m16s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Successful in 33s
- My Wave is rendered with react-native-skia on the UI thread; physics
  and colour helpers moved to @pipu/core (wave-anim) and shared with web.
- Full-screen player honours ui_prefs.mobile_player (cover / wave).
- Theme switching (dark / light / system) via a theme context and
  useColors() across all screens.
- Profile: theme, wave variant, player view, sound quality sheet
  (Wi-Fi / mobile / downloads), recent-tracks cache clearing on next
  cold start, and a change-password sheet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 13:30:21 +03:00
mrleo1nidandClaude Opus 5.5 756e915ff9 feat(mobile): queue track reactions made offline and sync on reconnect (M5)
Likes and dislikes without a network are kept in a pending_reactions
table (last reaction per track wins) and sent when the connection
returns, instead of being rolled back. Downloaded track DTOs pick up the
new reaction so the offline wave and Downloads reflect it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 13:08:36 +03:00
mrleo1nidandClaude Opus 5.5 be34ee5361 feat(mobile): offline downloads, persistent event queue and offline start (M5)
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 1m7s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Canceled after 4m15s
ci / ts / ts (packages + web) (push) Canceled after 17m42s
ci / mobile / mobile (Metro-бандл Android) (push) Canceled after 18m52s
- Downloads queue (2 parallel, Wi-Fi only by default) stores files under
  the app's document directory and track metadata in SQLite; Collection
  gets a Downloads tab, album and player screens get download buttons.
- Player plays downloaded files and local covers; My Wave falls back to
  a shuffle of downloaded tracks when the server is unreachable.
- Playback events that fail on the network are kept in SQLite and sent
  when the connection returns.
- AuthSession can open offline with the cached user and fetches an
  access token before the first request once online.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 13:02:47 +03:00
mrleo1nidandClaude Opus 5.5 765345e0f4 feat(mobile): self-update dialog with verified APK download and install (M5)
ci / ts / ts (packages + web) (push) Successful in 1m0s
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 57s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 1m33s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Successful in 35s
Checks the server for a newer release at most every 6 hours and on
demand in Profile, shows release notes, downloads the APK with progress,
verifies SHA-256 in 1 MB chunks and hands it to the system installer.
Updates below min_supported cannot be dismissed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 12:55:34 +03:00
mrleo1nidandClaude Opus 5.5 6a67c27f50 feat(api): Android self-update endpoints proxied from Gitea releases (M5)
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 43s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 1m12s
ci / api / api (push) Successful in 35s
ci / ts / ts (packages + web) (push) Successful in 1m20s
GET /api/v1/app/android/latest reads the latest Gitea release with the
server token (cached for 10 minutes); the download endpoint caches the
APK under /updates, verifies its SHA-256 and serves it with Range.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 12:52:41 +03:00
mrleo1nidandClaude Opus 5.5 9fd616da57 feat(mobile): sign-in, tabs, search, collection and background player (M5)
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 1m39s
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 1m2s
ci / ts / ts (packages + web) (push) Successful in 1m5s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Successful in 39s
- expo-router app in src/app: connect (server check, recent servers),
  login, mandatory credential / password change, tabs Home / Search /
  Collection / Profile, album and artist pages, full-screen player
- AuthSession per server with the refresh token in expo-secure-store
  (Android Keystore); language from the profile
- player on react-native-track-player: ExoPlayer queue with a
  notification and lock-screen controls via a playback service, 500 MB
  stream cache, quality by network (Wi-Fi high, cellular medium),
  play events with played time, reactions, playback state restore and
  the endless My Wave with feedback
- home: pulsing wave circle driven by BPM / energy in the cover
  palette, activity and mood chips that switch the wave on the fly
- New Architecture is off until react-native-track-player supports it;
  the release build runs codegen only when it is on; query-string is a
  direct dependency because expo-router 5.1 imports it undeclared

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 12:48:55 +03:00
mrleo1nidandClaude Opus 5.5 eaedd1fc62 feat(web): My Wave button, mood picker and endless wave playback (M4)
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 41s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 1m13s
ci / ts / ts (packages + web) (push) Successful in 1m14s
ci / api / api (push) Successful in 36s
- WaveButton: TypeScript port of the prototype's canvas animation
  (orb and liquid), breathing at rest, pulsing to the track's BPM and
  energy in the cover palette, following the cursor, pressing with a
  spring; reduced motion and hidden tabs slow or stop it
- home: the wave in the centre with activity and mood chips; changing
  them while playing rebuilds the upcoming tracks without stopping
- player wave mode: asks for the next batch when two tracks are left,
  sends complete / skip / early skip / like / dislike as feedback and
  refreshes the queue right after a reaction or an early skip
- tracks expose bpm, energy and loudness once analysed; library page
  shows analysis progress and 7-day wave metrics; wave style setting

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 12:29:38 +03:00
mrleo1nidandClaude Opus 5.5 3908814cda feat(api): My Wave sessions with a Go fallback and wave metrics (M4)
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 40s
ci / mobile / mobile (Metro-бандл Android) (push) Failing after 9s
ci / api / api (push) Successful in 35s
ci / ts / ts (packages + web) (push) Successful in 51s
- /wave/options, POST /wave/sessions (activity, mood, seed),
  /next with reactions, PATCH to switch the context on the fly, DELETE
- the recommender is called with an 800 ms budget; on failure the api
  serves a fallback wave of likes, favourite artists and random
  available tracks with the same dislike / recent / served filters
- every served track is an impression with its source and model; wave
  events (context_type wave) set its outcome, reactions win
- library status shows the analysis queue and 7-day wave metrics:
  listen-through, early skip and like rate

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 12:23:17 +03:00
mrleo1nidandClaude Opus 5.5 ef29b85320 feat(rec): audio analyzer and My Wave v1 engine (M4)
ci / api / api (push) Successful in 27s
ci / recommender / recommender (push) Successful in 1m0s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Successful in 1m26s
- migration 00006: track features and embeddings (pgvector, HNSW),
  analysis queue filled by a trigger on new tracks, wave sessions and
  impressions, recommender profiles, model versions
- analyzer basic-1 (ADR-014): ffmpeg decode, three 30 s excerpts,
  256-d timbre/rhythm embedding, tempo by onset autocorrelation, key,
  loudness, energy, danceability, acousticness, intro length; worker
  with SKIP LOCKED claims, retries and re-analysis on version change
- wave engine v1: candidates (session/taste similarity, fresh,
  liked artists, rediscover, popular, exploration, seed), filters
  (dislikes, played in 3 h, already served), heuristic score, activity
  and mood fit from contexts.yaml with relaxing thresholds, MMR with
  one track per artist, exploration share, session vector updated by
  reactions and a change of course after three skips
- POST /internal/wave/batch with the catalog index cached in memory
  and the session kept in Redis

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 12:20:55 +03:00
327 changed files with 33074 additions and 6477 deletions

No files matched your search

+32 -3
View File
@@ -4,14 +4,43 @@
{ {
"name": "design", "name": "design",
"runtimeExecutable": "python", "runtimeExecutable": "python",
"runtimeArgs": ["-m", "http.server", "8765", "--bind", "127.0.0.1", "--directory", "docs"], "runtimeArgs": [
"-m",
"http.server",
"8765",
"--bind",
"127.0.0.1",
"--directory",
"docs"
],
"port": 8765 "port": 8765
}, },
{ {
"name": "web", "name": "web",
"runtimeExecutable": "pnpm", "runtimeExecutable": "pnpm",
"runtimeArgs": ["--filter", "@pipu/web", "dev"], "runtimeArgs": [
"--filter",
"@pipu/web",
"dev"
],
"port": 5173 "port": 5173
},
{
"name": "web-fake",
"runtimeExecutable": "pnpm",
"runtimeArgs": [
"--filter",
"@pipu/web",
"exec",
"vite",
"--port",
"4173",
"--strictPort"
],
"env": {
"VITE_E2E": "1"
},
"port": 4173
} }
] ]
} }
+1 -1
View File
@@ -1,4 +1,4 @@
# Go: сервис api и storage-agent (docs/ci-cd.md). Только при изменении их кода или контракта. # Go: сервис api и storage-agent. Только при изменении их кода или контракта.
name: ci / api name: ci / api
on: on:
+1 -1
View File
@@ -1,4 +1,4 @@
# Сгенерированный код (Go-сервер, TS-клиент, дизайн-токены) совпадает с исходниками (docs/ci-cd.md). # Сгенерированный код (Go-сервер, TS-клиент, дизайн-токены) совпадает с исходниками.
name: ci / contract name: ci / contract
on: on:
+84
View File
@@ -0,0 +1,84 @@
# Интеграционные проверки SQL на настоящем PostgreSQL + pgvector: миграции вверх / вниз / вверх,
# запросы сканера, отпечатков, шаблонов и очереди, сквозной сценарий пользователя через HTTP (Go),
# загрузка каталога, профиля и обучение ALS (Python).
name: ci / db
on:
workflow_dispatch: # перезапуск вручную (например, после чистки раннера)
push:
branches: [main]
paths:
- 'services/api/**'
- 'services/recommender/**'
- '.gitea/workflows/ci-db.yml'
pull_request:
paths:
- 'services/api/**'
- 'services/recommender/**'
- '.gitea/workflows/ci-db.yml'
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
db:
runs-on: ubuntu-latest
services:
postgres:
image: pgvector/pgvector:0.8.7-pg17
env:
POSTGRES_USER: pipu
POSTGRES_PASSWORD: pipu
POSTGRES_DB: pipu
options: >-
--health-cmd "pg_isready -U pipu"
--health-interval 5s
--health-timeout 5s
--health-retries 20
redis:
image: redis:7.4-alpine
meilisearch:
image: getmeili/meilisearch:v1.11
env:
MEILI_MASTER_KEY: ci-master-key-0123456789
MEILI_ENV: development
env:
TEST_DATABASE_URL: postgres://pipu:pipu@postgres:5432/pipu?sslmode=disable
TEST_REDIS_URL: redis://redis:6379/0
TEST_MEILI_URL: http://meilisearch:7700
TEST_MEILI_KEY: ci-master-key-0123456789
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with: { go-version: "1.24", cache-dependency-path: services/api/go.sum }
# Контейнеры сервисов стартуют параллельно с job: без ожидания тесты иногда не находят даже DNS-имя postgres.
- name: Место на раннере и готовность Postgres, Redis, Meilisearch
run: |
# Диск раннера общий с контейнерами сервисов: при нехватке места Postgres падает посреди тестов.
free=$(df -Pm / | awk 'NR==2 {print $4}')
echo "свободно на раннере: ${free} МБ"
[ "$free" -ge 2048 ] || { echo "на раннере меньше 2 ГБ — почистите: docker system prune -af" >&2; exit 1; }
for svc in postgres:5432 redis:6379 meilisearch:7700; do
host=${svc%:*}; port=${svc#*:}
for i in $(seq 1 60); do
if getent hosts "$host" >/dev/null && timeout 2 bash -c "</dev/tcp/$host/$port" 2>/dev/null; then
echo "$svc готов"; break
fi
[ "$i" = 60 ] && { echo "$svc не поднялся за 2 минуты" >&2; exit 1; }
sleep 2
done
done
- name: Go — миграции и запросы store
working-directory: services/api
run: go test -tags integration -count=1 -v ./internal/dbtest/
- name: Go — сквозной сценарий пользователя (newApp на Postgres, Redis, Meilisearch)
working-directory: services/api
run: go test -tags integration -count=1 -v -run TestUserJourney ./cmd/api/
- uses: astral-sh/setup-uv@v6
with: { version: "0.10.2", enable-cache: true, cache-dependency-glob: services/recommender/uv.lock }
- name: Python — каталог, профиль, обучение ALS
working-directory: services/recommender
run: |
uv sync --frozen
uv run pytest -q tests/test_db_integration.py
+33
View File
@@ -0,0 +1,33 @@
# Rust-часть десктопа: прокси и проверки URL. Полная сборка инсталлятора — локально
# (`pnpm --filter @pipu/desktop bundle`): на раннере нет Windows и WebKitGTK.
name: ci / desktop
on:
push:
branches: [main]
paths:
- 'apps/desktop/**'
- '.gitea/workflows/ci-desktop.yml'
pull_request:
paths:
- 'apps/desktop/**'
- '.gitea/workflows/ci-desktop.yml'
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
rust:
name: rust (desktop proxy)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Rust
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable --profile minimal
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libdbus-1-dev
- run: cargo test --manifest-path apps/desktop/src-tauri/Cargo.toml
+2 -1
View File
@@ -1,7 +1,8 @@
# Expo: expo-doctor и Metro-бандл Android (docs/ci-cd.md). Полная сборка APK — только в release.yml. # Expo: expo-doctor и Metro-бандл Android. Полная сборка APK — только в release.yml.
name: ci / mobile name: ci / mobile
on: on:
workflow_dispatch: # перезапуск вручную (например, после чистки раннера)
push: push:
branches: [main] branches: [main]
paths: paths:
+1 -1
View File
@@ -1,4 +1,4 @@
# Python: recommender и analyzer (docs/ci-cd.md). # Python: recommender и analyzer.
name: ci / recommender name: ci / recommender
on: on:
+9 -1
View File
@@ -1,4 +1,4 @@
# TypeScript: пакеты, веб, typecheck мобильного приложения, скрипты релиза (docs/ci-cd.md). # TypeScript: пакеты, веб, typecheck мобильного приложения, скрипты релиза.
name: ci / ts name: ci / ts
on: on:
@@ -51,3 +51,11 @@ jobs:
- run: pnpm typecheck - run: pnpm typecheck
- run: pnpm test - run: pnpm test
- run: pnpm --filter @pipu/web build - run: pnpm --filter @pipu/web build
# Браузер качается долго (основной CDN Microsoft из раннера недоступен) — кэшируем по lock-файлу.
# Системные библиотеки (libnspr4 и т.п.) в образе раннера нет, их ставит --with-deps на каждом прогоне.
- uses: actions/cache@v4
with:
path: ~/.cache/ms-playwright
key: playwright-${{ hashFiles('pnpm-lock.yaml') }}
- run: pnpm --filter @pipu/web exec playwright install --with-deps chromium
- run: pnpm --filter @pipu/web test:e2e
+1 -1
View File
@@ -49,7 +49,7 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
# Обычный docker build через Docker хоста раннера, а не buildx-контейнер: кэш слоёв и # Обычный docker build через Docker хоста раннера, а не buildx-контейнер: кэш слоёв и
# --mount=type=cache переживают job, повторная сборка занимает секунды. Фиксированные теги # --mount=type=cache переживают job, повторная сборка занимает секунды. Фиксированные теги
# не дают копиться образам; кэш сборки чистит на хосте `docker builder prune` (docs/ci-cd.md). # не дают копиться образам; кэш сборки чистит на хосте `docker builder prune`.
- name: Сборка образов - name: Сборка образов
env: { DOCKER_BUILDKIT: "1" } env: { DOCKER_BUILDKIT: "1" }
run: | run: |
+37
View File
@@ -0,0 +1,37 @@
# Ночные проверки, которым нужен поднятый стенд или эмулятор. На каждый push не запускаются.
name: nightly / e2e
on:
workflow_dispatch:
schedule:
- cron: "0 3 * * *"
jobs:
schemathesis:
name: schemathesis
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: pip install schemathesis
- name: Фаззинг API
env:
PIPU_API_URL: ${{ vars.PIPU_API_URL }}
PIPU_API_TOKEN: ${{ secrets.PIPU_API_TOKEN }}
run: |
if [ -z "$PIPU_API_URL" ]; then echo "PIPU_API_URL is not set"; exit 0; fi
sh tests/contract/schemathesis.sh
maestro:
name: maestro
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Сценарии Android
env:
PIPU_E2E_SERVER: ${{ vars.PIPU_E2E_SERVER }}
PIPU_E2E_USER: ${{ vars.PIPU_E2E_USER }}
PIPU_E2E_PASSWORD: ${{ secrets.PIPU_E2E_PASSWORD }}
run: |
if [ -z "$PIPU_E2E_SERVER" ]; then echo "emulator flow is configured in apps/mobile/.maestro"; exit 0; fi
curl -Ls "https://get.maestro.mobile.dev" | bash
~/.maestro/bin/maestro test apps/mobile/.maestro
+37 -6
View File
@@ -1,4 +1,4 @@
# Релиз по тегу vMAJOR.MINOR.PATCH[-rc.N] (docs/ci-cd.md): Gitea Release с заметками → APK. # Релиз по тегу vMAJOR.MINOR.PATCH[-rc.N]: Gitea Release с заметками → APK.
# Релиз создаётся сразу (статус Android — «собирается»); сборка APK докладывает в него файлы # Релиз создаётся сразу (статус Android — «собирается»); сборка APK докладывает в него файлы
# и переписывает статус: собран / не удалась (scripts/release.mjs). # и переписывает статус: собран / не удалась (scripts/release.mjs).
# Docker-образы не публикуются: сервер собирает их сам из клонированного репозитория (deploy/update.sh). # Docker-образы не публикуются: сервер собирает их сам из клонированного репозитория (deploy/update.sh).
@@ -48,16 +48,21 @@ jobs:
android: android:
name: android (APK в релиз) name: android (APK в релиз)
needs: release needs: release
# Обычно 10–15 минут; дольше — значит, сборка упёрлась в память, лучше упасть, чем держать раннер.
timeout-minutes: 60
runs-on: ubuntu-latest runs-on: ubuntu-latest
# Постоянные кэши на хосте раннера: дистрибутив и зависимости Gradle, его build cache, Android SDK и NDK # Постоянные кэши на хосте раннера: дистрибутив и зависимости Gradle, его build cache, Android SDK и NDK
# переживают job (−4 мин на релиз). Работают, если в config.yaml раннера разрешены тома # переживают job (−4 мин на релиз). Работают, если в config.yaml раннера разрешены тома
# (container.valid_volumes: ['/opt/ci-cache/**'], docs/ci-cd.md); иначе раннер их пропускает и всё качается заново. # (container.valid_volumes: ['/opt/ci-cache/**']); иначе раннер их пропускает и всё качается заново.
# с блоком container act запускает шаги через sh; скриптам нужен bash (массивы, pipefail) # с блоком container act запускает шаги через sh; скриптам нужен bash (массивы, pipefail)
defaults: defaults:
run: run:
shell: bash shell: bash
container: container:
image: docker.gitea.com/runner-images:ubuntu-latest image: docker.gitea.com/runner-images:ubuntu-latest
# Жёсткие пределы контейнера: сборка не должна забирать всю VM раннера (а через неё — хост гипервизора).
# Своп запрещён (memory-swap = memory): лучше OOM внутри контейнера, чем подвисший хост.
options: --cpus=3 --memory=7g --memory-swap=7g
volumes: volumes:
- /opt/ci-cache/gradle:/root/.gradle - /opt/ci-cache/gradle:/root/.gradle
- /opt/ci-cache/android:/root/.android - /opt/ci-cache/android:/root/.android
@@ -100,6 +105,11 @@ jobs:
# CI=1 — Metro без file watcher и с 2 воркерами (metro.config.js); NODE_ENV нужен expo для .env-файлов # CI=1 — Metro без file watcher и с 2 воркерами (metro.config.js); NODE_ENV нужен expo для .env-файлов
CI: "1" CI: "1"
NODE_ENV: production NODE_ENV: production
# CMake / ninja нативной части React Native по умолчанию берут все ядра — ограничиваем.
CMAKE_BUILD_PARALLEL_LEVEL: "2"
NINJAFLAGS: "-j2"
# JS-бандл (Metro) собирается внутри Gradle отдельным node — не даём ему разрастись.
NODE_OPTIONS: "--max-old-space-size=1536"
# Только arm64-v8a: C++-часть React Native собирается под каждую ABI, и четыре ABI # Только arm64-v8a: C++-часть React Native собирается под каждую ABI, и четыре ABI
# вместе с NDK (~2.5 ГБ) не помещаются на диск раннера. arm64 — все устройства с 2017+. # вместе с NDK (~2.5 ГБ) не помещаются на диск раннера. arm64 — все устройства с 2017+.
# Память: на раннере 8 ГБ, и без ограничений Gradle + демон Kotlin + Metro вызывают OOM killer. # Память: на раннере 8 ГБ, и без ограничений Gradle + демон Kotlin + Metro вызывают OOM killer.
@@ -109,14 +119,35 @@ jobs:
# библиотек, но плагин RN не объявляет эту зависимость, и с прогретым кэшем CMake успевал раньше codegen. # библиотек, но плагин RN не объявляет эту зависимость, и с прогретым кэшем CMake успевал раньше codegen.
# Оба вызова идут через один демон Gradle (одинаковые jvmargs), поэтому второй не платит за старт JVM. # Оба вызова идут через один демон Gradle (одинаковые jvmargs), поэтому второй не платит за старт JVM.
run: | run: |
set -o pipefail
npx expo prebuild --platform android --clean --no-install npx expo prebuild --platform android --clean --no-install
cd android cd android
gradle=(./gradlew --max-workers=2 --build-cache -PreactNativeArchitectures=arm64-v8a # nice / ionice: сборка уступает CPU и диск всему остальному на машине
-Pkotlin.compiler.execution.strategy=in-process -Dorg.gradle.jvmargs="-Xmx2560m -XX:MaxMetaspaceSize=512m") gradle=(nice -n 19 ionice -c 3 ./gradlew --max-workers=2 --build-cache -PreactNativeArchitectures=arm64-v8a
"${gradle[@]}" generateCodegenArtifactsFromSchema -Pkotlin.compiler.execution.strategy=in-process -Dorg.gradle.jvmargs="-Xmx2048m -XX:MaxMetaspaceSize=512m")
"${gradle[@]}" assembleRelease -x lintVitalRelease # Без New Architecture (app.config.ts) CMake приложения не собирается — отдельный codegen не нужен.
if grep -q '^newArchEnabled=true' gradle.properties; then
"${gradle[@]}" generateCodegenArtifactsFromSchema
fi
# Постоянный кэш Gradle мог побиться (VM раннера перезагрузили посреди сборки): «Could not read workspace
# metadata» — удаляем кэш трансформаций и повторяем один раз, а не падаем до ручной чистки.
if ! "${gradle[@]}" assembleRelease -x lintVitalRelease 2>&1 | tee /tmp/gradle.log; then
if grep -qE "Could not read workspace metadata|Corrupted|is corrupt" /tmp/gradle.log; then
echo "::warning::кэш Gradle повреждён — чистим transforms и собираем заново"
./gradlew --stop || true
rm -rf ~/.gradle/caches/*/transforms ~/.gradle/caches/transforms-*
"${gradle[@]}" assembleRelease -x lintVitalRelease
else
exit 1
fi
fi
./gradlew --stop ./gradlew --stop
# Только arm64-v8a, все нужные .so на месте и выровнены по 16 КБ — иначе APK падает при запуске
# на части устройств (Android 15+ с 16 КБ страницами, эмуляторы x86).
- name: Проверка APK (ABI, 16 КБ страницы)
run: node scripts/check-apk.mjs apps/mobile/android/app/build/outputs/apk/release/app-release.apk
- name: Диагностика сбоя (диск, память, OOM) - name: Диагностика сбоя (диск, память, OOM)
if: failure() if: failure()
run: | run: |
+6
View File
@@ -27,6 +27,8 @@ __pycache__/
# generated test audio # generated test audio
tests/fixtures/music/out/ tests/fixtures/music/out/
apps/web/test-results/
apps/web/playwright-report/
# os / editors # os / editors
.DS_Store .DS_Store
@@ -35,3 +37,7 @@ Thumbs.db
.vscode/* .vscode/*
!.vscode/extensions.json !.vscode/extensions.json
.cache/ .cache/
apps/desktop/src-tauri/target/
apps/desktop/src-tauri/gen/
apps/desktop/src-tauri/tauri.release.json
apps/desktop/release/
+4 -4
View File
@@ -1,11 +1,10 @@
# pipu-music # pipu-music
Self-hosted музыкальный сервис: веб и Android-приложение, библиотека на NFS, Self-hosted музыкальный сервис: веб, десктоп и Android-приложение, библиотека на NFS,
умная бесконечная лента «Моя волна» с учётом вкуса, звучания треков и настроения. умная бесконечная лента «Моя волна» с учётом вкуса, звучания треков и настроения.
- Идея продукта: [docs/IDEA.md](docs/IDEA.md) - Идея продукта: [docs/IDEA.md](docs/IDEA.md)
- Документация для разработки: [docs/README.md](docs/README.md) - Документация: [docs/README.md](docs/README.md)
- План: [docs/roadmap.md](docs/roadmap.md)
- Установка сервера на свой домен: [docs/install-guide.md](docs/install-guide.md) - Установка сервера на свой домен: [docs/install-guide.md](docs/install-guide.md)
## Структура ## Структура
@@ -16,6 +15,7 @@ Self-hosted музыкальный сервис: веб и Android-прилож
| `services/api` | Go: публичный API (`cmd/api`) и агент хранилищ (`cmd/storage-agent`) | | `services/api` | Go: публичный API (`cmd/api`) и агент хранилищ (`cmd/storage-agent`) |
| `services/recommender` | Python: рекомендации (`pipu-rec serve`) и аудиоанализ (`pipu-rec analyze`) | | `services/recommender` | Python: рекомендации (`pipu-rec serve`) и аудиоанализ (`pipu-rec analyze`) |
| `apps/web` | Веб-клиент (React + Vite) | | `apps/web` | Веб-клиент (React + Vite) |
| `apps/desktop` | Десктоп Windows / Linux / macOS (Tauri, тот же веб) |
| `apps/mobile` | Android-приложение (React Native + Expo) | | `apps/mobile` | Android-приложение (React Native + Expo) |
| `packages/*` | Общий TS-код: `api-client`, `core`, `i18n`, `design-tokens` | | `packages/*` | Общий TS-код: `api-client`, `core`, `i18n`, `design-tokens` |
| `deploy/` | Docker Compose, nginx, скрипты установки и обновления | | `deploy/` | Docker Compose, nginx, скрипты установки и обновления |
@@ -67,4 +67,4 @@ pnpm generate && (cd services/api && go generate ./...)
Тег `vX.Y.Z` (или `vX.Y.Z-rc.N`) запускает `.gitea/workflows/release.yml`: Gitea Release с заметками → подписанный APK докладывается в него. Тег `vX.Y.Z` (или `vX.Y.Z-rc.N`) запускает `.gitea/workflows/release.yml`: Gitea Release с заметками → подписанный APK докладывается в него.
Docker-образы не публикуются: сервер клонирует репозиторий и собирает их сам (`deploy/update.sh`, Docker-образы не публикуются: сервер клонирует репозиторий и собирает их сам (`deploy/update.sh`,
[docs/install-guide.md](docs/install-guide.md)). Нужные секреты — в шапке workflow и в [docs/ci-cd.md](docs/ci-cd.md). [docs/install-guide.md](docs/install-guide.md)). Нужные секреты перечислены в шапке `.gitea/workflows/release.yml`.
+1454 -8
View File
File diff suppressed because it is too large. Load diff
+17
View File
@@ -0,0 +1,17 @@
import { execFileSync } from 'node:child_process';
import { readFileSync, writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const root = dirname(fileURLToPath(import.meta.url));
const conf = JSON.parse(readFileSync(resolve(root, 'src-tauri/tauri.conf.json'), 'utf8'));
let version = '0.0.0';
try {
const tag = execFileSync('git', ['describe', '--tags', '--abbrev=0'], { encoding: 'utf8' }).trim();
version = tag.replace(/^v/, '').replace(/-rc\.\d+$/, '');
} catch {
// local untagged build
}
conf.version = version;
writeFileSync(resolve(root, 'src-tauri/tauri.release.json'), JSON.stringify(conf, null, 2));
console.log(`desktop version ${version}`);
+15
View File
@@ -0,0 +1,15 @@
{
"name": "@pipu/desktop",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "tauri dev",
"bundle": "node inject-version.mjs && tauri build --config src-tauri/tauri.release.json",
"tauri": "tauri",
"icons": "tauri icon ../web/public/favicon.svg"
},
"devDependencies": {
"@tauri-apps/cli": "^2.9.0"
}
}
+42
View File
@@ -0,0 +1,42 @@
[package]
name = "pipu-desktop"
version = "0.0.0"
edition = "2021"
[lib]
name = "pipu_desktop_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[[bin]]
name = "pipu-desktop"
path = "src/main.rs"
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = ["tray-icon"] }
tauri-plugin-window-state = "2"
tauri-plugin-single-instance = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["net", "sync", "time"] }
axum = "0.8"
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "stream", "json"] }
uuid = { version = "1", features = ["v4"] }
url = "2"
souvlaki = "0.8.3"
[target.'cfg(target_os = "windows")'.dependencies]
keyring = { version = "3.6.3", features = ["windows-native"] }
[target.'cfg(target_os = "linux")'.dependencies]
keyring = { version = "3.6.3", features = ["sync-secret-service", "crypto-rust"] }
[target.'cfg(target_os = "macos")'.dependencies]
keyring = { version = "3.6.3", features = ["apple-native"] }
[profile.release]
strip = true
lto = "thin"
codegen-units = 1
+3
View File
@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}
@@ -0,0 +1,7 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "main",
"description": "Only the bundled main window may invoke desktop integration.",
"windows": ["main"],
"permissions": ["core:default", "core:event:default"]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

+157
View File
@@ -0,0 +1,157 @@
mod media;
mod proxy;
mod store;
use media::Media;
use proxy::Proxy;
use serde::Serialize;
use std::sync::Mutex;
use tauri::{
image::Image,
include_image,
menu::{Menu, MenuItem},
tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent},
AppHandle, Manager, State,
};
struct AppState {
proxy: Proxy,
media: Media,
server: Mutex<Option<String>>,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Bootstrap {
proxy_base: String,
server: Option<String>,
}
fn show_main(app: &AppHandle) {
if let Some(window) = app.get_webview_window("main") {
let _ = window.unminimize();
let _ = window.show();
let _ = window.set_focus();
}
}
#[tauri::command]
fn bootstrap(app: AppHandle, state: State<AppState>) -> Result<Bootstrap, String> {
Ok(Bootstrap {
proxy_base: state.proxy.base.clone(),
server: store::load_server(&app)?,
})
}
#[tauri::command]
async fn set_server(app: AppHandle, state: State<'_, AppState>, url: String) -> Result<String, String> {
let server = proxy::validate_server(&url)?;
state.proxy.check(&server).await?;
store::save_server(&app, Some(&server))?;
*state.proxy.server.write().map_err(|e| e.to_string())? = Some(server.clone());
*state.server.lock().map_err(|e| e.to_string())? = Some(server.clone());
Ok(server)
}
#[tauri::command]
fn clear_server(app: AppHandle, state: State<AppState>) -> Result<(), String> {
store::save_server(&app, None)?;
store::save_user(&app, None)?;
store::save_refresh(None)?;
*state.proxy.server.write().map_err(|e| e.to_string())? = None;
*state.server.lock().map_err(|e| e.to_string())? = None;
Ok(())
}
#[tauri::command]
fn token_get() -> Result<Option<String>, String> {
store::load_refresh()
}
#[tauri::command]
fn token_set(token: String) -> Result<(), String> {
store::save_refresh(Some(&token))
}
#[tauri::command]
fn token_clear() -> Result<(), String> {
store::save_refresh(None)
}
#[tauri::command]
fn user_get(app: AppHandle) -> Result<Option<String>, String> {
store::load_user(&app)
}
#[tauri::command]
fn user_set(app: AppHandle, json: String) -> Result<(), String> {
store::save_user(&app, Some(&json))
}
#[tauri::command]
fn user_clear(app: AppHandle) -> Result<(), String> {
store::save_user(&app, None)
}
#[tauri::command]
fn media_set(
state: State<AppState>,
title: String,
artist: String,
album: String,
cover_url: Option<String>,
playing: bool,
) -> Result<(), String> {
state.media.set(&title, &artist, &album, cover_url.as_deref(), playing)
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_single_instance::init(|app, _, _| show_main(app)))
.plugin(tauri_plugin_window_state::Builder::default().build())
.setup(|app| {
let saved = store::load_server(app.handle())?;
let proxy = tauri::async_runtime::block_on(Proxy::start(saved.clone())).map_err(|e| e.to_string())?;
let media = Media::new();
if let Some(window) = app.get_webview_window("main") {
let _ = media.attach(app.handle().clone(), &window);
}
app.manage(AppState {
proxy,
media,
server: Mutex::new(saved),
});
let open = MenuItem::with_id(app, "open", "Открыть", true, None::<&str>)?;
let quit = MenuItem::with_id(app, "quit", "Выход", true, None::<&str>)?;
let menu = Menu::with_items(app, &[&open, &quit])?;
let icon: Image = include_image!("../icons/32x32.png");
TrayIconBuilder::new()
.icon(icon)
.menu(&menu)
.show_menu_on_left_click(false)
.on_menu_event(|app, event| match event.id.as_ref() {
"open" => show_main(app),
"quit" => app.exit(0),
_ => {}
})
.on_tray_icon_event(|tray, event| {
if let TrayIconEvent::Click {
button: MouseButton::Left,
button_state: MouseButtonState::Up,
..
} = event
{
show_main(tray.app_handle());
}
})
.build(app)?;
Ok(())
})
.invoke_handler(tauri::generate_handler![
bootstrap, set_server, clear_server, token_get, token_set, token_clear, user_get, user_set, user_clear, media_set
])
.run(tauri::generate_context!())
.expect("desktop app failed to start");
}
+5
View File
@@ -0,0 +1,5 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
pipu_desktop_lib::run();
}
+62
View File
@@ -0,0 +1,62 @@
use souvlaki::{MediaControlEvent, MediaControls, MediaMetadata, MediaPlayback, PlatformConfig};
use std::sync::Mutex;
use tauri::{AppHandle, Emitter, WebviewWindow};
pub struct Media {
controls: Mutex<Option<MediaControls>>,
}
impl Media {
pub fn new() -> Self {
Self { controls: Mutex::new(None) }
}
pub fn attach(&self, app: AppHandle, window: &WebviewWindow) -> Result<(), String> {
#[cfg(target_os = "windows")]
let hwnd = window.hwnd().ok().map(|h| h.0 as *mut std::ffi::c_void);
#[cfg(not(target_os = "windows"))]
let hwnd = {
let _ = window;
None
};
let mut controls = MediaControls::new(PlatformConfig {
dbus_name: "app.pipu.music.desktop",
display_name: "Pipu Music",
hwnd,
})
.map_err(|e| format!("{e:?}"))?;
let handle = app.clone();
controls
.attach(move |event| {
let name = match event {
MediaControlEvent::Play => "play",
MediaControlEvent::Pause => "pause",
MediaControlEvent::Toggle => "toggle",
MediaControlEvent::Next => "next",
MediaControlEvent::Previous => "previous",
MediaControlEvent::Stop => "stop",
_ => return,
};
let _ = handle.emit("media", name);
})
.map_err(|e| format!("{e:?}"))?;
*self.controls.lock().map_err(|e| e.to_string())? = Some(controls);
Ok(())
}
pub fn set(&self, title: &str, artist: &str, album: &str, cover_url: Option<&str>, playing: bool) -> Result<(), String> {
let mut slot = self.controls.lock().map_err(|e| e.to_string())?;
let Some(controls) = slot.as_mut() else { return Ok(()); };
controls
.set_metadata(MediaMetadata {
title: Some(title),
artist: Some(artist),
album: Some(album),
cover_url,
duration: None,
})
.map_err(|e| format!("{e:?}"))?;
let playback = if playing { MediaPlayback::Playing { progress: None } } else { MediaPlayback::Paused { progress: None } };
controls.set_playback(playback).map_err(|e| format!("{e:?}"))
}
}
+168
View File
@@ -0,0 +1,168 @@
//! Loopback-only streaming transport. The random per-process path is a capability;
//! it never leaves the app except for OS media artwork requests. No open proxy.
use axum::{body::Body, extract::{Request, State}, http::{HeaderMap, HeaderValue, Method, StatusCode}, response::{IntoResponse, Response}, Router};
use serde_json::Value;
use std::{sync::{Arc, RwLock}, time::Duration};
use url::Url;
#[derive(Clone)]
pub struct Proxy {
pub server: Arc<RwLock<Option<String>>>,
pub base: String,
secret: String,
authority: String,
client: reqwest::Client,
}
pub fn validate_server(raw: &str) -> Result<String, String> {
let url = Url::parse(raw.trim()).map_err(|_| "Invalid server URL")?;
if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none()
|| !url.username().is_empty() || url.password().is_some()
|| url.query().is_some() || url.fragment().is_some()
{ return Err("Use an HTTP(S) server address without credentials, query or fragment".into()); }
Ok(url.as_str().trim_end_matches('/').to_string())
}
impl Proxy {
pub async fn start(server: Option<String>) -> Result<Self, String> {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.map_err(|e| e.to_string())?;
let authority = listener.local_addr().map_err(|e| e.to_string())?.to_string();
let secret = uuid::Uuid::new_v4().simple().to_string();
let proxy = Self {
server: Arc::new(RwLock::new(server)),
base: format!("http://{authority}/{secret}"), secret, authority,
client: reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.connect_timeout(Duration::from_secs(10))
.read_timeout(Duration::from_secs(60))
.build().map_err(|e| e.to_string())?,
};
let router = Router::new().fallback(forward).with_state(proxy.clone());
tauri::async_runtime::spawn(async move {
if let Err(e) = axum::serve(listener, router).await { eprintln!("Desktop transport stopped: {e}"); }
});
Ok(proxy)
}
pub async fn check(&self, server: &str) -> Result<(), String> {
let response = self.client.get(format!("{server}/api/v1/server-info"))
.timeout(Duration::from_secs(10)).send().await.map_err(|_| "Server unavailable")?;
if !response.status().is_success() { return Err("Server unavailable".into()); }
let info: Value = response.json().await.map_err(|_| "Not a Pipu server")?;
if info.get("api_version").is_none() || info.get("name").is_none() { return Err("Not a Pipu server".into()); }
Ok(())
}
}
fn allowed_origin(origin: &str) -> bool {
matches!(origin, "tauri://localhost" | "http://tauri.localhost")
|| (cfg!(debug_assertions) && origin == "http://127.0.0.1:5173")
}
// Signed media and tus URLs are relative in the API. Rewrite only API URLs from
// the configured server; never route arbitrary URLs supplied in server content.
fn local_url(value: &str, server: &str, base: &str) -> Option<String> {
if value.starts_with("/api/") { return Some(format!("{base}{value}")); }
value.strip_prefix(server).filter(|p| p.starts_with("/api/"))
.map(|p| format!("{base}{p}"))
}
fn rewrite_json(value: &mut Value, server: &str, base: &str) {
match value {
Value::Array(items) => items.iter_mut().for_each(|v| rewrite_json(v, server, base)),
Value::Object(fields) => for (key, v) in fields {
if matches!(key.as_str(), "stream_url" | "cover_url" | "tus_url" | "download_url") {
if let Some(url) = v.as_str().and_then(|s| local_url(s, server, base)) { *v = Value::String(url); }
} else { rewrite_json(v, server, base); }
},
_ => {}
}
}
fn cors(headers: &mut HeaderMap, origin: Option<&str>) {
if let Some(origin) = origin {
headers.insert("access-control-allow-origin", HeaderValue::from_str(origin).unwrap());
headers.insert("vary", HeaderValue::from_static("Origin"));
}
headers.insert("access-control-allow-methods", HeaderValue::from_static("GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS"));
headers.insert("access-control-allow-headers", HeaderValue::from_static("authorization, content-type, range, tus-resumable, upload-length, upload-offset, upload-metadata, upload-defer-length, x-requested-with"));
headers.insert("access-control-expose-headers", HeaderValue::from_static("content-range, accept-ranges, location, upload-offset, upload-length, tus-resumable, retry-after"));
}
async fn forward(State(proxy): State<Proxy>, request: Request) -> Response {
let origin = request.headers().get("origin").and_then(|v| v.to_str().ok()).map(str::to_owned);
if request.headers().get("host").and_then(|v| v.to_str().ok()) != Some(&proxy.authority)
|| origin.as_deref().is_some_and(|s| !allowed_origin(s))
{ return StatusCode::FORBIDDEN.into_response(); }
let prefix = format!("/{}/api/", proxy.secret);
let Some(tail) = request.uri().path().strip_prefix(&prefix) else { return StatusCode::NOT_FOUND.into_response(); };
// Prevent URL normalization escaping the configured API path, including encoded segments.
if tail.split('/').any(|s| s == "." || s == "..") || tail.to_lowercase().contains("%2e")
|| tail.contains('\\') || tail.to_lowercase().contains("%5c") || tail.to_lowercase().contains("%2f")
{ return StatusCode::BAD_REQUEST.into_response(); }
if origin.is_none() && !matches!(*request.method(), Method::GET | Method::HEAD) {
return StatusCode::FORBIDDEN.into_response();
}
let mut response = if request.method() == Method::OPTIONS {
StatusCode::NO_CONTENT.into_response()
} else {
match transfer(&proxy, request, tail.to_owned()).await {
Ok(response) => response,
Err(_) => (StatusCode::BAD_GATEWAY, "Server unavailable").into_response(),
}
};
cors(response.headers_mut(), origin.as_deref());
response
}
async fn transfer(proxy: &Proxy, request: Request, tail: String) -> Result<Response, String> {
let server = proxy.server.read().map_err(|_| "State unavailable")?.clone().ok_or("No server selected")?;
let query = request.uri().query().map(|q| format!("?{q}")).unwrap_or_default();
let url = format!("{server}/api/{tail}{query}");
let (parts, body) = request.into_parts();
let mut upstream = proxy.client.request(parts.method.clone(), url);
for name in ["authorization", "content-type", "content-length", "range", "if-range", "if-none-match", "tus-resumable", "upload-length", "upload-offset", "upload-metadata", "upload-defer-length"] {
if let Some(value) = parts.headers.get(name) { upstream = upstream.header(name, value); }
}
let upstream = upstream.body(reqwest::Body::wrap_stream(body.into_data_stream())).send().await.map_err(|e| e.to_string())?;
let status = upstream.status();
let mut headers = HeaderMap::new();
for name in ["content-type", "content-length", "content-range", "accept-ranges", "etag", "last-modified", "cache-control", "upload-offset", "upload-length", "tus-resumable", "retry-after", "content-disposition"] {
if let Some(value) = upstream.headers().get(name) { headers.insert(name, value.clone()); }
}
if let Some(location) = upstream.headers().get("location").and_then(|v| v.to_str().ok()) {
let local = local_url(location, &server, &proxy.base).ok_or("External redirect refused")?;
headers.insert("location", HeaderValue::from_str(&local).map_err(|e| e.to_string())?);
}
let json = headers.get("content-type").and_then(|v| v.to_str().ok())
.is_some_and(|v| v.contains("application/json") || v.contains("application/problem+json"));
let body = if json && parts.method != Method::HEAD {
// Bound only JSON, never buffer a song or an upload in memory.
let bytes = axum::body::to_bytes(Body::from_stream(upstream.bytes_stream()), 16 * 1024 * 1024).await.map_err(|e| e.to_string())?;
let mut value: Value = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?;
rewrite_json(&mut value, &server, &proxy.base);
headers.remove("content-length");
headers.remove("etag");
Body::from(serde_json::to_vec(&value).map_err(|e| e.to_string())?)
} else { Body::from_stream(upstream.bytes_stream()) };
let mut response = Response::new(body);
*response.status_mut() = status;
*response.headers_mut() = headers;
Ok(response)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn validates_server_and_scopes_media_urls() {
assert_eq!(validate_server("https://music.example/pipu/").unwrap(), "https://music.example/pipu");
for url in ["file:///etc/passwd", "https://user:pass@host", "https://host/?token=x", "https://host/#x"] { assert!(validate_server(url).is_err()); }
assert_eq!(local_url("https://music.example.evil/api/a", "https://music.example", "http://local"), None);
let mut value = serde_json::json!({"tracks": [{"stream_url": "/api/v1/stream/a?sig=b", "title": "/api/private", "album": {"cover_url": "/api/v1/covers/a"}}]});
rewrite_json(&mut value, "https://music.example", "http://local/key");
assert_eq!(value["tracks"][0]["stream_url"], "http://local/key/api/v1/stream/a?sig=b");
assert_eq!(value["tracks"][0]["title"], "/api/private");
assert_eq!(value["tracks"][0]["album"]["cover_url"], "http://local/key/api/v1/covers/a");
}
}
+80
View File
@@ -0,0 +1,80 @@
use std::fs;
use std::path::PathBuf;
use tauri::{AppHandle, Manager};
const SERVICE: &str = "app.pipu.music.desktop";
fn config_dir(app: &AppHandle) -> Result<PathBuf, String> {
let dir = app.path().app_config_dir().map_err(|e| e.to_string())?;
fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
Ok(dir)
}
pub fn load_server(app: &AppHandle) -> Result<Option<String>, String> {
let path = config_dir(app)?.join("server.txt");
match fs::read_to_string(path) {
Ok(s) => {
let s = s.trim().to_string();
Ok((!s.is_empty()).then_some(s))
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e.to_string()),
}
}
pub fn save_server(app: &AppHandle, server: Option<&str>) -> Result<(), String> {
let path = config_dir(app)?.join("server.txt");
match server {
Some(s) => fs::write(path, s).map_err(|e| e.to_string()),
None => match fs::remove_file(path) {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e.to_string()),
},
}
}
fn refresh_entry() -> Result<keyring::Entry, String> {
keyring::Entry::new(SERVICE, "refresh").map_err(|e| e.to_string())
}
pub fn load_refresh() -> Result<Option<String>, String> {
match refresh_entry()?.get_password() {
Ok(s) => Ok(Some(s)),
Err(keyring::Error::NoEntry) => Ok(None),
Err(e) => Err(e.to_string()),
}
}
pub fn save_refresh(token: Option<&str>) -> Result<(), String> {
let entry = refresh_entry()?;
match token {
Some(t) => entry.set_password(t).map_err(|e| e.to_string()),
None => match entry.delete_credential() {
Ok(()) => Ok(()),
Err(keyring::Error::NoEntry) => Ok(()),
Err(e) => Err(e.to_string()),
},
}
}
pub fn load_user(app: &AppHandle) -> Result<Option<String>, String> {
let path = config_dir(app)?.join("user.json");
match fs::read_to_string(path) {
Ok(s) => Ok(Some(s)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e.to_string()),
}
}
pub fn save_user(app: &AppHandle, json: Option<&str>) -> Result<(), String> {
let path = config_dir(app)?.join("user.json");
match json {
Some(s) => fs::write(path, s).map_err(|e| e.to_string()),
None => match fs::remove_file(path) {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e.to_string()),
},
}
}
+31
View File
@@ -0,0 +1,31 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Pipu Music",
"version": "0.0.0",
"identifier": "app.pipu.music.desktop",
"build": {
"beforeDevCommand": "pnpm --filter @pipu/web dev",
"devUrl": "http://127.0.0.1:5173",
"beforeBuildCommand": "pnpm --filter @pipu/web build",
"frontendDist": "../../web/dist"
},
"app": {
"withGlobalTauri": true,
"windows": [{ "label": "main", "title": "Pipu Music", "width": 1200, "height": 800, "minWidth": 720, "minHeight": 540 }],
"security": {
"csp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: http://127.0.0.1:*; font-src 'self' data:; media-src 'self' blob: http://127.0.0.1:*; connect-src 'self' ipc: http://ipc.localhost http://127.0.0.1:*; object-src 'none'; base-uri 'self'; frame-src 'none'"
}
},
"bundle": {
"active": true,
"targets": ["nsis", "appimage", "deb", "rpm"],
"category": "Music",
"shortDescription": "Self-hosted music player",
"icon": ["icons/32x32.png", "icons/128x128.png", "icons/128x128@2x.png", "icons/icon.ico", "icons/icon.icns"],
"linux": {
"deb": { "depends": ["libwebkit2gtk-4.1-0", "libayatana-appindicator3-1", "libsecret-1-0", "gstreamer1.0-plugins-good", "gstreamer1.0-plugins-bad", "gstreamer1.0-libav"] },
"appimage": { "bundleMediaFramework": true }
},
"windows": { "nsis": { "installMode": "currentUser", "languages": ["English", "Russian"], "displayLanguageSelector": true } }
}
}
+5
View File
@@ -0,0 +1,5 @@
appId: app.pipu.music
---
- runFlow: login.yaml
- tapOn: "Коллекция"
- assertVisible: "Лайки"
+15
View File
@@ -0,0 +1,15 @@
appId: app.pipu.music
---
- launchApp:
clearState: true
- assertVisible: "Адрес сервера"
- tapOn: "Адрес сервера"
- inputText: ${PIPU_E2E_SERVER}
- tapOn: "Подключиться"
- assertVisible: "Вход"
- tapOn: "Логин"
- inputText: ${PIPU_E2E_USER}
- tapOn: "Пароль"
- inputText: ${PIPU_E2E_PASSWORD}
- tapOn: "Войти"
- assertVisible: "Бегаю"
+10
View File
@@ -0,0 +1,10 @@
appId: app.pipu.music
---
- launchApp:
clearState: true
- assertVisible: "Адрес сервера|Server address"
- stopApp
- launchApp
- assertVisible: "Адрес сервера|Server address"
- openLink: "pipu://album/1"
- assertVisible: "Адрес сервера|Server address"
+6
View File
@@ -0,0 +1,6 @@
appId: app.pipu.music
---
- runFlow: login.yaml
- tapOn: "Профиль"
- assertVisible: "Проверить обновления"
- tapOn: "Проверить обновления"
+12 -2
View File
@@ -12,7 +12,9 @@ export default ({ config }: ConfigContext): ExpoConfig => ({
version, version,
orientation: 'portrait', orientation: 'portrait',
userInterfaceStyle: 'automatic', userInterfaceStyle: 'automatic',
newArchEnabled: true, // react-native-track-player 4 не поддерживает New Architecture (React Native Directory) — фоновое
// воспроизведение и уведомление важнее; вернём, когда плеер её поддержит (docs/mobile.md).
newArchEnabled: false,
backgroundColor: '#05070D', backgroundColor: '#05070D',
android: { android: {
package: 'app.pipu.music', package: 'app.pipu.music',
@@ -23,9 +25,17 @@ export default ({ config }: ConfigContext): ExpoConfig => ({
}, },
platforms: ['android'], platforms: ['android'],
plugins: [ plugins: [
// Маршруты — файлы в src/app (docs/mobile.md).
['expo-router', { root: './src/app' }],
'expo-secure-store',
// Сервер часто живёт в домашней сети без TLS (http://192.168.1.10:8080), а release-сборка // Сервер часто живёт в домашней сети без TLS (http://192.168.1.10:8080), а release-сборка
// Android по умолчанию запрещает незашифрованный HTTP. // Android по умолчанию запрещает незашифрованный HTTP.
['expo-build-properties', { android: { usesCleartextTraffic: true } }], // Распаковываем .so при установке: SoLoader на x86_64 с ARM-трансляцией ищет
// внутри APK lib/x86_64 вместо arm64-v8a и не находит libreactnative.so.
['expo-build-properties', { android: { usesCleartextTraffic: true, useLegacyPackaging: true } }],
// APK только под arm64-v8a — та же ABI, под которую собираются нативные модули (plugins/withArm64Only.js).
'./plugins/withArm64Only',
], ],
extra: { versionCode }, extra: { versionCode },
experiments: { typedRoutes: false },
}); });
+7 -3
View File
@@ -1,5 +1,9 @@
import { registerRootComponent } from 'expo'; // Фоновый сервис плеера регистрируется до запуска UI: кнопки уведомления и гарнитуры
// работают, даже когда интерфейс выгружен (docs/mobile.md#воспроизведение).
import TrackPlayer from 'react-native-track-player';
import { App } from './src/App'; import { PlaybackService } from './src/player/service';
registerRootComponent(App); TrackPlayer.registerPlaybackService(() => PlaybackService);
import 'expo-router/entry';
+33 -3
View File
@@ -7,23 +7,53 @@
"start": "expo start --dev-client", "start": "expo start --dev-client",
"android": "expo run:android", "android": "expo run:android",
"prebuild": "expo prebuild --platform android --clean", "prebuild": "expo prebuild --platform android --clean",
"typecheck": "tsc --noEmit" "typecheck": "tsc --noEmit",
"test": "vitest run"
}, },
"dependencies": { "dependencies": {
"@expo/vector-icons": "^14.1.0",
"@pipu/api-client": "workspace:*", "@pipu/api-client": "workspace:*",
"@pipu/core": "workspace:*", "@pipu/core": "workspace:*",
"@pipu/design-tokens": "workspace:*", "@pipu/design-tokens": "workspace:*",
"@pipu/i18n": "workspace:*", "@pipu/i18n": "workspace:*",
"@react-native-community/netinfo": "11.4.1",
"@shopify/react-native-skia": "2.0.0-next.4",
"@tanstack/react-query": "^5.104.4",
"expo": "~53.0.20", "expo": "~53.0.20",
"expo-build-properties": "~0.14.8", "expo-build-properties": "~0.14.8",
"expo-constants": "~17.1.7", "expo-constants": "~17.1.7",
"expo-file-system": "~18.1.11",
"expo-font": "~13.3.2",
"expo-intent-launcher": "~12.1.5",
"expo-linking": "~7.1.7",
"expo-router": "~5.1.11",
"expo-secure-store": "~14.2.4",
"expo-sqlite": "~15.2.14",
"expo-status-bar": "~2.2.3", "expo-status-bar": "~2.2.3",
"i18next": "^25.2.1", "i18next": "^25.2.1",
"js-sha256": "^1.0.0",
"query-string": "^7.1.3",
"react": "19.0.0", "react": "19.0.0",
"react-i18next": "^15.5.3", "react-i18next": "^15.5.3",
"react-native": "0.79.6" "react-native": "0.79.6",
"react-native-reanimated": "~3.17.5",
"react-native-safe-area-context": "5.4.0",
"react-native-screens": "~4.11.1",
"react-native-track-player": "^4.1.2"
}, },
"devDependencies": { "devDependencies": {
"@types/react": "~19.0.10" "@types/node": "^22.20.5",
"@types/react": "~19.0.10",
"vitest": "^3.2.7"
},
"expo": {
"doctor": {
"reactNativeDirectoryCheck": {
"exclude": [
"react-native-track-player"
],
"listUnknownPackages": false
}
}
} }
} }
+18
View File
@@ -0,0 +1,18 @@
// Только arm64-v8a в APK. Наши нативные модули (Expo, Skia, Reanimated) собираются под одну ABI
// (-PreactNativeArchitectures=arm64-v8a в release.yml), а готовые библиотеки React Native приносят
// каталоги всех ABI. Без фильтра x86/x86_64-эмулятор и 32-битные устройства выбирают неполный каталог
// и падают при старте: «couldn't find DSO to load: libexpo-modules-core.so».
const { withAppBuildGradle } = require('expo/config-plugins');
const MARKER = '// pipu: arm64-v8a only';
module.exports = function withArm64Only(config) {
return withAppBuildGradle(config, (cfg) => {
if (cfg.modResults.contents.includes(MARKER)) return cfg;
cfg.modResults.contents = cfg.modResults.contents.replace(
/defaultConfig\s*\{/,
(m) => `${m}\n ${MARKER}\n ndk { abiFilters "arm64-v8a" }`,
);
return cfg;
});
};
-33
View File
@@ -1,33 +0,0 @@
import { createI18n, pickLocale } from '@pipu/i18n';
import { StatusBar } from 'expo-status-bar';
import type { i18n as I18n } from 'i18next';
import { useEffect, useState } from 'react';
import { I18nextProvider } from 'react-i18next';
import { ActivityIndicator, View } from 'react-native';
import { ConnectScreen } from './ConnectScreen';
import { colors } from './theme';
export function App() {
const [i18n, setI18n] = useState<I18n | null>(null);
useEffect(() => {
const deviceLocale = Intl.DateTimeFormat().resolvedOptions().locale;
void createI18n(pickLocale([deviceLocale])).then(setI18n);
}, []);
if (!i18n) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: colors.bg }}>
<ActivityIndicator color={colors.accent} />
</View>
);
}
return (
<I18nextProvider i18n={i18n}>
<StatusBar style="light" />
<ConnectScreen />
</I18nextProvider>
);
}
-122
View File
@@ -1,122 +0,0 @@
import { createApiClient } from '@pipu/api-client';
import { checkServer, normalizeServerUrl, type ServerCheck } from '@pipu/core';
import Constants from 'expo-constants';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ActivityIndicator, Pressable, StyleSheet, Text, TextInput, View } from 'react-native';
import { colors, radius } from './theme';
const appVersionCode = Number(Constants.expoConfig?.extra?.versionCode ?? 0);
type State = { kind: 'idle' } | { kind: 'checking' } | { kind: 'invalid' } | ({ kind: 'done' } & ServerCheck);
/** Экран подключения к серверу (docs/mobile.md). В M0 — только проверка /server-info. */
export function ConnectScreen() {
const { t } = useTranslation();
const [address, setAddress] = useState('');
const [state, setState] = useState<State>({ kind: 'idle' });
const checking = state.kind === 'checking';
async function onCheck() {
if (checking) return;
const baseUrl = normalizeServerUrl(address);
if (!baseUrl) {
setState({ kind: 'invalid' });
return;
}
setState({ kind: 'checking' });
const res = await checkServer(createApiClient({ baseUrl }), appVersionCode);
setState({ kind: 'done', ...res });
}
return (
<View style={styles.screen}>
<View style={styles.card}>
<Text style={styles.title}>{t('app.name')}</Text>
<Text style={styles.muted}>{t('app.tagline')}</Text>
<Text style={styles.label}>{t('server.address')}</Text>
<TextInput
value={address}
onChangeText={setAddress}
onSubmitEditing={onCheck}
editable={!checking}
placeholder="https://music.home.lan"
placeholderTextColor={colors.text3}
autoCapitalize="none"
autoCorrect={false}
keyboardType="url"
style={styles.input}
/>
{state.kind === 'checking' && (
<View style={[styles.status, { backgroundColor: colors.surface2 }]}>
<ActivityIndicator color={colors.text2} />
<Text style={{ color: colors.text2 }}>{t('server.checking')}</Text>
</View>
)}
{state.kind === 'invalid' && <Status ok={false} text={t('server.invalid_address')} />}
{state.kind === 'done' && state.status === 'ok' && (
<Status ok text={t('server.online', { version: state.info.version })} />
)}
{state.kind === 'done' && state.status === 'unsupported_app' && (
<Status ok={false} text={t('server.unsupported_app')} />
)}
{state.kind === 'done' && state.status === 'offline' && <Status ok={false} text={t('server.offline')} />}
<Pressable
onPress={onCheck}
disabled={checking}
accessibilityState={{ disabled: checking, busy: checking }}
style={({ pressed }) => [styles.button, (pressed || checking) && { opacity: 0.6 }]}
>
<Text style={styles.buttonText}>{t('server.check')}</Text>
</Pressable>
</View>
</View>
);
}
function Status({ ok, text }: { ok: boolean; text: string }) {
return (
<View style={[styles.status, { backgroundColor: ok ? colors['ok-soft'] : colors['danger-soft'] }]}>
<Text style={{ color: ok ? colors.ok : colors.danger, fontWeight: '500' }}>{text}</Text>
</View>
);
}
const styles = StyleSheet.create({
screen: { flex: 1, backgroundColor: colors.bg, justifyContent: 'center', padding: 16 },
card: {
gap: 12,
padding: 24,
borderRadius: radius.xl,
backgroundColor: colors.surface,
borderWidth: 1,
borderColor: colors.line2,
},
title: { color: colors.text, fontSize: 26, fontWeight: '600' },
muted: { color: colors.text2, lineHeight: 21 },
label: { color: colors.text2, fontSize: 13, fontWeight: '500', marginTop: 8 },
input: {
height: 48,
paddingHorizontal: 14,
borderRadius: radius.md,
backgroundColor: colors.surface2,
borderWidth: 1,
borderColor: colors.line2,
color: colors.text,
fontSize: 15,
},
status: { flexDirection: 'row', alignItems: 'center', gap: 8, padding: 12, borderRadius: 10 },
button: {
height: 48,
borderRadius: radius.md,
backgroundColor: colors.accent,
alignItems: 'center',
justifyContent: 'center',
},
buttonText: { color: '#fff', fontWeight: '600', fontSize: 15 },
});
+148
View File
@@ -0,0 +1,148 @@
import { useNetInfo } from '@react-native-community/netinfo';
import { Tabs, useRouter } from 'expo-router';
import { useTranslation } from 'react-i18next';
import { Pressable, Text, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { player } from '../../player/controller';
import { usePlayerState } from '../../player/hooks';
import { useColors } from '../../theme';
import { Cover, Icon, type IconName } from '../../ui/kit';
import { UpdateDialog } from '../../ui/UpdateDialog';
const ICONS: Record<string, IconName> = { index: 'home', search: 'search', collection: 'library-music', profile: 'person' };
export default function TabsLayout() {
const colors = useColors();
const { t } = useTranslation();
const labels: Record<string, string> = {
index: t('nav.home'),
search: t('mobile.search'),
collection: t('nav.collection'),
profile: t('mobile.profile'),
};
const net = useNetInfo();
return (
<>
{net.isConnected === false && <OfflineBanner text={t('mobile.offline')} />}
<Tabs
screenOptions={{ headerShown: false, sceneStyle: { backgroundColor: colors.bg } }}
tabBar={({ state, navigation }) => (
<View>
<MiniPlayer />
<TabBar
routes={state.routes.map((r) => r.name)}
active={state.index}
labels={labels}
onPress={(name) => navigation.navigate(name)}
/>
</View>
)}
>
<Tabs.Screen name="index" />
<Tabs.Screen name="search" />
<Tabs.Screen name="collection" />
<Tabs.Screen name="profile" />
</Tabs>
<UpdateDialog />
</>
);
}
function TabBar({
routes,
active,
labels,
onPress,
}: {
routes: string[];
active: number;
labels: Record<string, string>;
onPress: (name: string) => void;
}) {
const colors = useColors();
const insets = useSafeAreaInsets();
return (
<View
accessibilityRole="tablist"
style={{
flexDirection: 'row',
paddingBottom: insets.bottom,
backgroundColor: colors.bg2,
borderTopWidth: 1,
borderTopColor: colors.line,
}}
>
{routes.map((name, i) => {
const on = i === active;
return (
<Pressable
key={name}
onPress={() => onPress(name)}
accessibilityRole="tab"
accessibilityState={{ selected: on }}
accessibilityLabel={labels[name]}
style={{ flex: 1, alignItems: 'center', paddingVertical: 8, gap: 2 }}
>
<Icon name={ICONS[name] ?? 'circle'} color={on ? colors.accent2 : colors.text3} />
<Text style={{ fontSize: 11, color: on ? colors.text : colors.text3, fontWeight: on ? '600' : '400' }}>
{labels[name]}
</Text>
</Pressable>
);
})}
</View>
);
}
/** Мини-плеер над навигацией; нажатие — полноэкранный плеер. */
function MiniPlayer() {
const colors = useColors();
const { t } = useTranslation();
const router = useRouter();
const st = usePlayerState();
const track = st.track;
if (!track) return null;
const progress = st.durationMs ? Math.min(st.positionMs / st.durationMs, 1) : 0;
return (
<Pressable
onPress={() => router.push('/player')}
accessibilityRole="button"
accessibilityLabel={t('mobile.open_player')}
style={{ backgroundColor: colors.surface, borderTopWidth: 1, borderTopColor: colors.line }}
>
<View style={{ height: 2, backgroundColor: colors.surface3 }}>
<View style={{ height: 2, width: `${progress * 100}%`, backgroundColor: colors.accent2 }} />
</View>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 12, paddingVertical: 8 }}>
<Cover album={track.album} size={42} />
<View style={{ flex: 1, minWidth: 0 }}>
<Text numberOfLines={1} style={{ color: colors.text, fontWeight: '600' }}>
{track.title}
</Text>
<Text numberOfLines={1} style={{ color: colors.text2, fontSize: 12 }}>
{track.artists.map((a) => a.name).join(', ')}
</Text>
</View>
<Pressable onPress={() => player.toggle()} hitSlop={10} accessibilityRole="button" accessibilityLabel={t(st.playing ? 'player.pause' : 'player.play')}>
<Icon name={st.playing ? 'pause' : 'play-arrow'} size={32} color={colors.text} />
</Pressable>
<Pressable onPress={() => player.next()} hitSlop={10} accessibilityRole="button" accessibilityLabel={t('player.next')}>
<Icon name="skip-next" size={28} color={colors.text2} />
</Pressable>
</View>
</Pressable>
);
}
/** Нет сети: доступны «Скачанное» и офлайн-волна. */
function OfflineBanner({ text }: { text: string }) {
const colors = useColors();
const insets = useSafeAreaInsets();
return (
<View accessibilityRole="alert" style={{ paddingTop: insets.top + 6, paddingBottom: 6, paddingHorizontal: 16, backgroundColor: colors.surface3, flexDirection: 'row', gap: 8, alignItems: 'center' }}>
<Icon name="cloud-off" size={16} color={colors.text2} />
<Text style={{ color: colors.text2, fontSize: 12 }}>{text}</Text>
</View>
);
}
+161
View File
@@ -0,0 +1,161 @@
import { unwrap, type Track } from '@pipu/core';
import { useRouter } from 'expo-router';
import { useInfiniteQuery } from '@tanstack/react-query';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { FlatList, Text, View } from 'react-native';
import { useSession } from '../../lib/session';
import { downloads } from '../../offline/downloads';
import { player } from '../../player/controller';
import { usePlayerState } from '../../player/hooks';
import { useColors } from '../../theme';
import { DownloadButton, useDownloads } from '../../ui/downloads';
import { Button, H1, Muted, Screen, Segmented, TrackRow } from '../../ui/kit';
type Tab = 'history' | 'likes' | 'dislikes' | 'downloads';
export default function CollectionScreen() {
const colors = useColors();
const { t, i18n } = useTranslation();
const session = useSession();
const current = usePlayerState().track;
const [tab, setTab] = useState<Tab>('likes');
const router = useRouter();
const list = useInfiniteQuery({
queryKey: ['m-collection', tab],
enabled: tab !== 'downloads',
initialPageParam: undefined as string | undefined,
queryFn: async ({ pageParam }) => {
const query = { query: { cursor: pageParam, limit: 100 } };
if (tab === 'history') {
const page = unwrap(await session.client.GET('/api/v1/me/history', { params: query }));
return { items: page.items.map((i) => ({ track: i.track, at: i.played_at })), next: page.next_cursor };
}
const path = tab === 'likes' ? '/api/v1/me/likes' : '/api/v1/me/dislikes';
const page = unwrap(await session.client.GET(path, { params: query }));
return { items: page.items.map((i) => ({ track: i.track, at: i.created_at })), next: page.next_cursor };
},
getNextPageParam: (p) => p.next ?? undefined,
});
const items = list.data?.pages.flatMap((p) => p.items) ?? [];
/** Все лайки целиком, а не только загруженные страницы списка. */
const downloadAllLikes = async () => {
let cursor: string | undefined;
do {
const page = unwrap(await session.client.GET('/api/v1/me/likes', { params: { query: { cursor, limit: 100 } } }));
await downloads.enqueue(page.items.map((i) => i.track));
cursor = page.next_cursor ?? undefined;
} while (cursor);
};
const tracks: Track[] = items.map((i) => i.track);
const time = new Intl.DateTimeFormat(i18n.language, { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
const context = tab === 'history' ? ({ type: 'history' } as const) : ({ type: 'collection', id: tab } as const);
const empty = { history: 'collection.empty_history', likes: 'collection.empty_likes', dislikes: 'collection.empty_dislikes' } as const;
const tabs = (
<View style={{ gap: 12 }}>
<Button title={t('playlists.title')} icon="queue-music" variant="secondary" onPress={() => router.push('/playlists')} />
<Segmented<Tab>
value={tab}
onChange={setTab}
options={[
{ value: 'likes', label: t('collection.likes') },
{ value: 'history', label: t('collection.history') },
{ value: 'downloads', label: t('mobile.dl_title') },
{ value: 'dislikes', label: t('collection.dislikes') },
]}
/>
</View>
);
if (tab === 'downloads') return <DownloadsTab tabs={tabs} />;
return (
<Screen>
<FlatList
data={items}
keyExtractor={(it, i) => `${it.track.id}-${i}`}
onEndReached={() => list.hasNextPage && void list.fetchNextPage()}
onRefresh={() => void list.refetch()}
refreshing={list.isRefetching}
ListHeaderComponent={
<View style={{ padding: 16, gap: 14 }}>
<H1>{t('collection.title')}</H1>
{tabs}
{tab === 'likes' && tracks.length > 0 && (
<Button title={t('collection.play_all')} icon="play-arrow" onPress={() => void player.playList(tracks, 0, context)} />
)}
{tab === 'likes' && tracks.length > 0 && (
<Button title={t('mobile.dl_all_likes')} variant="secondary" icon="download" onPress={() => void downloadAllLikes()} />
)}
</View>
}
ListEmptyComponent={list.isSuccess ? <Text style={{ color: colors.text3, textAlign: 'center', padding: 24 }}>{t(empty[tab])}</Text> : null}
renderItem={({ item, index }) => (
<TrackRow
track={item.track}
current={current?.id === item.track.id}
meta={tab === 'history' ? time.format(new Date(item.at)) : undefined}
onPress={() => void player.playList(tracks, index, context)}
onLike={tab === 'dislikes' ? undefined : () => void player.react(item.track, item.track.reaction === 'like' ? null : 'like').then(() => list.refetch())}
/>
)}
/>
</Screen>
);
}
const MB = 1024 * 1024;
/** Коллекция → Скачанное: работает без сети, данные — из SQLite. */
function DownloadsTab({ tabs }: { tabs: React.ReactNode }) {
const colors = useColors();
const { t } = useTranslation();
const dl = useDownloads();
const current = usePlayerState().track;
const [usage, setUsage] = useState<{ used: number; free: number } | null>(null);
const items = [...dl.items.values()];
const done = items.filter((i) => i.status === 'done').map((i) => i.track);
const pending = items.filter((i) => i.status === 'queued' || i.status === 'downloading').length;
const failed = items.some((i) => i.status === 'error');
const context = { type: 'collection', id: 'downloads' } as const;
useEffect(() => {
void downloads.usage().then(setUsage);
}, [done.length]);
return (
<Screen>
<FlatList
data={items}
keyExtractor={(it) => it.track.id}
ListHeaderComponent={
<View style={{ padding: 16, gap: 14 }}>
<H1>{t('collection.title')}</H1>
{tabs}
{usage && <Muted>{t('mobile.dl_usage', { used: (usage.used / MB).toFixed(0), free: (usage.free / MB / 1024).toFixed(1) })}</Muted>}
{pending > 0 && (
<Muted>{t(dl.allowed ? 'mobile.dl_pending' : dl.wifiOnly ? 'mobile.dl_waiting_wifi' : 'mobile.dl_waiting_network', { count: pending })}</Muted>
)}
{failed && <Button title={t('mobile.dl_retry')} variant="secondary" icon="refresh" onPress={() => void downloads.retry()} />}
{done.length > 0 && <Button title={t('collection.play_all')} icon="play-arrow" onPress={() => void player.playList(done, 0, context)} />}
</View>
}
ListEmptyComponent={<Text style={{ color: colors.text3, textAlign: 'center', padding: 24 }}>{t('mobile.dl_empty')}</Text>}
renderItem={({ item }) => (
<TrackRow
track={item.track}
current={current?.id === item.track.id}
meta={item.status === 'downloading' ? `${Math.round(item.progress * 100)}%` : undefined}
onPress={() => {
if (item.status === 'done') void player.playList(done, done.indexOf(item.track), context);
}}
trailing={<DownloadButton track={item.track} size={20} />}
/>
)}
/>
</Screen>
);
}
+133
View File
@@ -0,0 +1,133 @@
import { unwrap } from '@pipu/core';
import { useQuery } from '@tanstack/react-query';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Pressable, ScrollView, Text, View } from 'react-native';
import { useSession, useUser } from '../../lib/session';
import { player } from '../../player/controller';
import { usePlayerState } from '../../player/hooks';
import { useColors } from '../../theme';
import { ErrorBox, Icon, Screen, useErrorText, type IconName } from '../../ui/kit';
import { WaveOrb } from '../../ui/wave/WaveOrb';
/** Имена из /wave/options (Material Symbols) → MaterialIcons. */
function iconFor(name: string): IconName {
const map: Record<string, string> = { rainy: 'umbrella', sentiment_satisfied: 'sentiment-satisfied' };
return (map[name] ?? name.replace(/_/g, '-')) as IconName;
}
/**
* Главная: кнопка «Моя волна» (Skia, вид orb / liquid из профиля) и выбор занятия / настроения.
* На Android спектр недоступен, поэтому пульс берётся из BPM и energy трека (docs/mobile.md).
*/
export default function HomeScreen() {
const colors = useColors();
const { t } = useTranslation();
const tr = t as unknown as (k: string) => string;
const session = useSession();
const user = useUser();
const st = usePlayerState();
const errorText = useErrorText();
const [error, setError] = useState<unknown>(null);
const [activity, setActivity] = useState<string | null>(st.wave?.activity ?? null);
const [mood, setMood] = useState<string | null>(st.wave?.mood ?? null);
const options = useQuery({
queryKey: ['wave-options'],
queryFn: async () => unwrap(await session.client.GET('/api/v1/wave/options')),
staleTime: Infinity,
});
const waveOn = st.wave !== null;
const playing = waveOn && st.playing;
const run = (fn: () => Promise<void>) => {
setError(null);
fn().catch(setError);
};
const onWave = () => (waveOn ? player.toggle() : run(() => player.startWave(activity, mood)));
const choose = (kind: 'activity' | 'mood', key: string) => {
const a = kind === 'activity' ? (activity === key ? null : key) : activity;
const m = kind === 'mood' ? (mood === key ? null : key) : mood;
setActivity(a);
setMood(m);
if (waveOn) run(() => player.setWaveContext(a, m));
};
const ctx = [activity && tr(`wave.activities.${activity}`), mood && tr(`wave.moods.${mood}`)].filter(Boolean).join(' · ') || t('wave.for_you');
return (
<Screen>
<ScrollView contentContainerStyle={{ alignItems: 'center', paddingVertical: 32, gap: 24, paddingHorizontal: 16 }}>
<WaveOrb
variant={user.ui_prefs.wave_variant ?? 'orb'}
size={260}
playing={playing}
bpm={st.track?.features?.bpm ?? 100}
energy={st.track?.features?.energy ?? 0.6}
colors={waveOn ? st.track?.album.cover_colors : undefined}
onPress={onWave}
label={t(playing ? 'wave.pause' : 'wave.start')}
>
<Icon name={playing ? 'pause' : 'play-arrow'} size={44} color="#fff" />
<Text style={{ color: '#fff', fontSize: 22, fontWeight: '700' }}>{t('wave.title')}</Text>
<Text style={{ color: 'rgba(255,255,255,0.85)', fontSize: 13 }}>{ctx}</Text>
</WaveOrb>
{st.wave?.fallback && <Text style={{ color: colors.text2, fontSize: 13 }}>{t('wave.fallback')}</Text>}
<ErrorBox>{error ? errorText(error) : null}</ErrorBox>
{options.data && (
<>
<Chips title={t('wave.activity_label')} options={options.data.activities} value={activity} label={(k) => tr(`wave.activities.${k}`)} onPick={(k) => choose('activity', k)} />
<Chips title={t('wave.mood_label')} options={options.data.moods} value={mood} label={(k) => tr(`wave.moods.${k}`)} onPick={(k) => choose('mood', k)} />
</>
)}
</ScrollView>
</Screen>
);
}
function Chips({
title,
options,
value,
label,
onPick,
}: {
title: string;
options: { key: string; icon: string }[];
value: string | null;
label: (k: string) => string;
onPick: (k: string) => void;
}) {
const colors = useColors();
return (
<View style={{ alignItems: 'center', gap: 10, width: '100%' }}>
<Text style={{ color: colors.text3, fontSize: 11, fontWeight: '700', letterSpacing: 0.8, textTransform: 'uppercase' }}>{title}</Text>
<View style={{ flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'center', gap: 8 }}>
{options.map((o) => {
const on = value === o.key;
return (
<Pressable
key={o.key}
onPress={() => onPick(o.key)}
accessibilityRole="button"
accessibilityState={{ selected: on }}
style={{
flexDirection: 'row',
alignItems: 'center',
gap: 6,
height: 38,
paddingHorizontal: 14,
borderRadius: 999,
backgroundColor: on ? colors['accent-fill'] : colors.surface2,
borderWidth: 1,
borderColor: on ? colors.accent : colors.line,
}}
>
<Icon name={iconFor(o.icon)} size={18} color={on ? '#fff' : colors.text2} />
<Text style={{ color: on ? '#fff' : colors.text, fontWeight: '500' }}>{label(o.key)}</Text>
</Pressable>
);
})}
</View>
</View>
);
}
+207
View File
@@ -0,0 +1,207 @@
import type { components } from '@pipu/api-client';
import { unwrap } from '@pipu/core';
import { SUPPORTED_LOCALES, type Locale } from '@pipu/i18n';
import Constants from 'expo-constants';
import * as Linking from 'expo-linking';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Pressable, ScrollView, Switch, Text, View } from 'react-native';
import { playerCache } from '../../lib/prefs';
import { useSession, useSessionCtx, useUser } from '../../lib/session';
import { updater } from '../../lib/update';
import { downloads } from '../../offline/downloads';
import { player } from '../../player/controller';
import { radius, useColors } from '../../theme';
import { Button, H1, Icon, Muted, Screen, Segmented } from '../../ui/kit';
import { useDownloads } from '../../ui/downloads';
import { PasswordSheet, QualitySheet, useQualityPrefs } from '../../ui/settings';
import { useUpdateState } from '../../ui/UpdateDialog';
type UiPrefs = components['schemas']['UiPrefs'];
const MB = 1024 * 1024;
export default function ProfileScreen() {
const colors = useColors();
const { t, i18n } = useTranslation();
const session = useSession();
const user = useUser();
const { server, disconnect } = useSessionCtx();
const staff = user.role !== 'user';
const update = useUpdateState();
const dl = useDownloads();
const quality = useQualityPrefs();
const [sheet, setSheet] = useState<'quality' | 'password' | null>(null);
const [cache, setCache] = useState<{ bytes: number; pending: boolean } | null>(null);
useEffect(() => {
void Promise.all([playerCache.size(), playerCache.clearPending()]).then(([bytes, pending]) => setCache({ bytes, pending }));
}, []);
// Оптимистично, как в вебе: настройка применяется сразу, сервер подтверждает.
const setPrefs = async (prefs: UiPrefs) => {
session.setUser({ ...user, ui_prefs: { ...user.ui_prefs, ...prefs } });
try {
session.setUser(unwrap(await session.client.PATCH('/api/v1/me', { body: { ui_prefs: prefs } })));
} catch {
session.setUser(user);
}
};
const clearCache = async () => {
await playerCache.requestClear();
setCache((c) => (c ? { ...c, pending: true } : c));
};
const setLocale = async (l: Locale) => {
await i18n.changeLanguage(l);
try {
session.setUser(unwrap(await session.client.PATCH('/api/v1/me', { body: { locale: l } })));
} catch {
// язык уже сменился локально
}
};
const logout = async () => {
await player.reset();
await session.logout();
};
return (
<Screen>
<ScrollView contentContainerStyle={{ padding: 16, gap: 16 }}>
<H1>{user.display_name ?? user.username}</H1>
<Muted>
@{user.username} · {t(`roles.${user.role}`)}
</Muted>
<Section>
<Row label={t('language.label')}>
<Segmented<Locale>
value={(SUPPORTED_LOCALES as readonly string[]).includes(i18n.language) ? (i18n.language as Locale) : 'en'}
options={SUPPORTED_LOCALES.map((l) => ({ value: l, label: l.toUpperCase() }))}
onChange={(l) => void setLocale(l)}
/>
</Row>
</Section>
<Section>
<Row label={t('settings.theme')}>
<Segmented<NonNullable<UiPrefs['theme']>>
value={user.ui_prefs.theme ?? 'system'}
options={[
{ value: 'dark', label: t('settings.theme_dark') },
{ value: 'light', label: t('settings.theme_light') },
{ value: 'system', label: t('settings.theme_system') },
]}
onChange={(v) => void setPrefs({ theme: v })}
/>
</Row>
<Row label={t('settings.wave_variant')}>
<Segmented<NonNullable<UiPrefs['wave_variant']>>
value={user.ui_prefs.wave_variant ?? 'orb'}
options={[
{ value: 'orb', label: t('settings.wave_orb') },
{ value: 'liquid', label: t('settings.wave_liquid') },
]}
onChange={(v) => void setPrefs({ wave_variant: v })}
/>
</Row>
<Row label={t('mobile.player_view')}>
<Segmented<NonNullable<UiPrefs['mobile_player']>>
value={user.ui_prefs.mobile_player ?? 'cover'}
options={[
{ value: 'cover', label: t('mobile.player_cover') },
{ value: 'wave', label: t('mobile.player_wave') },
]}
onChange={(v) => void setPrefs({ mobile_player: v })}
/>
</Row>
<Row label={t('settings.normalize')}>
<Switch value={user.ui_prefs.normalize !== false} onValueChange={(v) => void setPrefs({ normalize: v })} />
</Row>
<Row label={t('settings.crossfade', { seconds: user.ui_prefs.crossfade_s ?? 0 })}>
<Segmented
value={String([0, 2, 4, 6].includes(user.ui_prefs.crossfade_s ?? 0) ? (user.ui_prefs.crossfade_s ?? 0) : 0)}
options={['0', '2', '4', '6'].map((v) => ({ value: v, label: v }))}
onChange={(v) => void setPrefs({ crossfade_s: Number(v) })}
/>
</Row>
</Section>
<Section>
<Pressable onPress={() => setSheet('quality')} accessibilityRole="button" style={{ paddingVertical: 4 }}>
<Row label={t('mobile.quality')}>
<Text style={{ color: colors.text2 }}>
{t(`mobile.q_${quality.wifi}`)} · {t(`mobile.q_${quality.cellular}`)}
</Text>
</Row>
</Pressable>
<Row label={t('mobile.cache')}>
{cache?.pending ? (
<Text style={{ color: colors.text3, fontSize: 12 }}>{t('mobile.cache_pending')}</Text>
) : (
<Pressable onPress={() => void clearCache()} accessibilityRole="button" hitSlop={8}>
<Text style={{ color: colors.accent2, fontWeight: '500' }}>
{t('mobile.cache_clear', { size: ((cache?.bytes ?? 0) / MB).toFixed(0) })}
</Text>
</Pressable>
)}
</Row>
<Row label={t('mobile.dl_wifi_only')}>
<Switch value={dl.wifiOnly} onValueChange={(v) => void downloads.setWifiOnly(v)} />
</Row>
<Row label={t('mobile.dl_auto_likes')}>
<Switch value={dl.autoLikes} onValueChange={(v) => void downloads.setAutoLikes(v)} />
</Row>
</Section>
<Section>
<Row label={t('mobile.server')}>
<Text style={{ color: colors.text2 }} numberOfLines={1}>
{server?.replace(/^https?:\/\//, '')}
</Text>
</Row>
{staff && server && (
<Pressable onPress={() => void Linking.openURL(`${server}/admin/users`)} accessibilityRole="link" style={{ flexDirection: 'row', alignItems: 'center', gap: 10, paddingVertical: 12 }}>
<Icon name="open-in-new" size={20} color={colors.accent2} />
<Text style={{ color: colors.accent2, fontWeight: '500' }}>{t('mobile.open_admin')}</Text>
</Pressable>
)}
</Section>
<Button title={t('settings.change_password')} variant="secondary" icon="lock" onPress={() => setSheet('password')} />
<Button
title={t(update.status === 'checking' ? 'mobile.update_checking' : 'mobile.update_check')}
variant="secondary"
icon="system-update"
busy={update.status === 'checking'}
onPress={() => void updater.check(session, true)}
/>
{update.status === 'latest' && <Muted>{t('mobile.update_latest')}</Muted>}
<Button title={t('profile.logout')} variant="danger" icon="logout" onPress={() => void logout()} />
<Button title={t('mobile.change_server')} variant="ghost" onPress={() => void logout().then(disconnect)} />
<Text style={{ color: colors.text3, textAlign: 'center', fontSize: 12 }}>
{t('mobile.version', { version: Constants.expoConfig?.version ?? '0.0.0' })}
</Text>
</ScrollView>
<QualitySheet visible={sheet === 'quality'} onClose={() => setSheet(null)} />
<PasswordSheet visible={sheet === 'password'} onClose={() => setSheet(null)} />
</Screen>
);
}
function Section({ children }: { children: React.ReactNode }) {
const colors = useColors();
return <View style={{ padding: 16, borderRadius: radius.lg, backgroundColor: colors.surface, gap: 8 }}>{children}</View>;
}
function Row({ label, children }: { label: string; children: React.ReactNode }) {
const colors = useColors();
return (
<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
<Text style={{ color: colors.text }}>{label}</Text>
<View style={{ flexShrink: 1 }}>{children}</View>
</View>
);
}
+142
View File
@@ -0,0 +1,142 @@
import { unwrap } from '@pipu/core';
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { useRouter } from 'expo-router';
import * as SecureStore from 'expo-secure-store';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { FlatList, Pressable, Text, TextInput, View } from 'react-native';
import { useSession } from '../../lib/session';
import { player } from '../../player/controller';
import { usePlayerState } from '../../player/hooks';
import { radius, useColors } from '../../theme';
import { Cover, Icon, Screen, TrackRow, useErrorText } from '../../ui/kit';
const RECENT_KEY = 'pipu.recent_searches';
/** Поиск: подсказки по мере ввода (debounce 250 мс), недавние запросы — локально. */
export default function SearchScreen() {
const colors = useColors();
const { t } = useTranslation();
const session = useSession();
const router = useRouter();
const current = usePlayerState().track;
const errorText = useErrorText();
const [q, setQ] = useState('');
const [debounced, setDebounced] = useState('');
const [recent, setRecent] = useState<string[]>([]);
useEffect(() => {
void SecureStore.getItemAsync(RECENT_KEY).then((v) => setRecent(v ? (JSON.parse(v) as string[]) : []));
}, []);
useEffect(() => {
const id = setTimeout(() => setDebounced(q.trim()), 250);
return () => clearTimeout(id);
}, [q]);
const remember = (query: string) => {
const next = [query, ...recent.filter((r) => r !== query)].slice(0, 10);
setRecent(next);
void SecureStore.setItemAsync(RECENT_KEY, JSON.stringify(next));
};
const res = useQuery({
queryKey: ['m-search', debounced],
enabled: debounced !== '',
placeholderData: keepPreviousData,
queryFn: async ({ signal }) =>
unwrap(await session.client.GET('/api/v1/search', { params: { query: { q: debounced } }, signal })),
});
const data = debounced ? res.data : undefined;
return (
<Screen>
<View style={{ padding: 16, gap: 8 }}>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 8, height: 46, paddingHorizontal: 12, borderRadius: radius.md, backgroundColor: colors.surface2 }}>
<Icon name="search" color={colors.text3} />
<TextInput
value={q}
onChangeText={setQ}
onSubmitEditing={() => q.trim() && remember(q.trim())}
placeholder={t('search.placeholder')}
placeholderTextColor={colors.text3}
autoCorrect={false}
autoCapitalize="none"
accessibilityLabel={t('search.label')}
style={{ flex: 1, color: colors.text, fontSize: 16 }}
returnKeyType="search"
/>
{!!q && (
<Pressable onPress={() => setQ('')} hitSlop={10} accessibilityRole="button" accessibilityLabel={t('form.close')}>
<Icon name="close" color={colors.text3} size={20} />
</Pressable>
)}
</View>
{data?.corrected_query && <Text style={{ color: colors.warn, fontSize: 13 }}>{t('search.corrected', { query: data.corrected_query })}</Text>}
{res.error && <Text style={{ color: colors.danger }}>{errorText(res.error)}</Text>}
</View>
{!debounced ? (
<View style={{ paddingHorizontal: 16, gap: 4 }}>
{recent.length > 0 && (
<View style={{ flexDirection: 'row', justifyContent: 'space-between', marginBottom: 4 }}>
<Text style={{ color: colors.text3, fontSize: 12, fontWeight: '700', textTransform: 'uppercase' }}>{t('mobile.recent_searches')}</Text>
<Pressable onPress={() => { setRecent([]); void SecureStore.deleteItemAsync(RECENT_KEY); }} accessibilityRole="button">
<Text style={{ color: colors.accent2 }}>{t('mobile.clear_recent')}</Text>
</Pressable>
</View>
)}
{recent.map((r) => (
<Pressable key={r} onPress={() => setQ(r)} style={{ flexDirection: 'row', alignItems: 'center', gap: 10, paddingVertical: 10 }}>
<Icon name="history" size={20} color={colors.text3} />
<Text style={{ color: colors.text }}>{r}</Text>
</Pressable>
))}
</View>
) : (
<FlatList
data={data?.tracks ?? []}
keyExtractor={(tr) => tr.id}
ListHeaderComponent={
<View style={{ gap: 4 }}>
{data?.artists.map((a) => (
<Pressable key={a.id} onPress={() => { remember(debounced); router.push(`/artist/${a.id}`); }} style={{ flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 16, paddingVertical: 8 }}>
<Cover album={{ id: a.id }} size={44} round />
<View>
<Text style={{ color: colors.text, fontWeight: '600' }}>{a.name}</Text>
<Text style={{ color: colors.text3, fontSize: 12 }}>{t('search.artist_kind')}</Text>
</View>
</Pressable>
))}
{data?.albums.map((al) => (
<Pressable key={al.id} onPress={() => { remember(debounced); router.push(`/album/${al.id}`); }} style={{ flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 16, paddingVertical: 8 }}>
<Cover album={al} size={44} />
<View style={{ flex: 1 }}>
<Text numberOfLines={1} style={{ color: colors.text, fontWeight: '600' }}>{al.title}</Text>
<Text style={{ color: colors.text3, fontSize: 12 }}>{[al.artist.name, al.year].filter(Boolean).join(' · ')}</Text>
</View>
</Pressable>
))}
</View>
}
ListEmptyComponent={
res.isSuccess && !data?.artists.length && !data?.albums.length ? (
<Text style={{ color: colors.text3, textAlign: 'center', marginTop: 24 }}>{t('search.nothing')}</Text>
) : null
}
renderItem={({ item, index }) => (
<TrackRow
track={item}
current={current?.id === item.id}
onPress={() => {
remember(debounced);
void player.playList(data?.tracks ?? [], index, { type: 'search', id: debounced });
}}
onLike={() => void player.react(item, item.reaction === 'like' ? null : 'like').then(() => res.refetch())}
/>
)}
/>
)}
</Screen>
);
}
+118
View File
@@ -0,0 +1,118 @@
import { createI18n, pickLocale, SUPPORTED_LOCALES, type Locale } from '@pipu/i18n';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Stack } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import type { i18n as I18n } from 'i18next';
import { useEffect, useState } from 'react';
import { I18nextProvider, useTranslation } from 'react-i18next';
import { ActivityIndicator, AppState, useColorScheme, View } from 'react-native';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { SessionProvider, useAuthState, useSessionCtx } from '../lib/session';
import { downloads } from '../offline/downloads';
import { player } from '../player/controller';
import { ThemeContext, useColors } from '../theme';
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: 1, staleTime: 30_000 } } });
export default function RootLayout() {
const [i18n, setI18n] = useState<I18n | null>(null);
useEffect(() => {
const deviceLocale = Intl.DateTimeFormat().resolvedOptions().locale;
void createI18n(pickLocale([deviceLocale])).then(setI18n);
}, []);
if (!i18n) return <Splash />;
return (
<SafeAreaProvider>
<I18nextProvider i18n={i18n}>
<QueryClientProvider client={queryClient}>
<SessionProvider>
<Gate />
</SessionProvider>
</QueryClientProvider>
</I18nextProvider>
</SafeAreaProvider>
);
}
function Splash() {
const colors = useColors();
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: colors.bg }}>
<ActivityIndicator color={colors.accent} />
</View>
);
}
const isLocale = (l: string): l is Locale => (SUPPORTED_LOCALES as readonly string[]).includes(l);
/**
* Куда пускать: без сервера — подключение, без входа — логин, с обязательной сменой пароля — setup,
* иначе — вкладки. Те же правила, что у веба (docs/auth-and-roles.md).
*/
function Gate() {
const { server, session, ready } = useSessionCtx();
const auth = useAuthState();
const { i18n } = useTranslation();
const user = auth.status === 'signed_in' ? auth.user : null;
const system = useColorScheme();
// Тема из профиля; «system» и экраны до входа — по настройке телефона.
const pref = user?.ui_prefs.theme ?? 'system';
const theme = pref === 'system' ? (system === 'light' ? 'light' : 'dark') : pref;
useEffect(() => {
player.attach(user ? session : null, server ?? '', user?.id ?? null);
void downloads.attach(user ? session : null, server ?? '', user?.id ?? null);
if (user) void player.restore();
}, [user?.id, session, server]);
useEffect(() => {
if (user && isLocale(user.locale) && user.locale !== i18n.language) void i18n.changeLanguage(user.locale);
}, [user?.locale, i18n]);
// Свёрнутое приложение досылает события и позицию.
useEffect(() => {
const sub = AppState.addEventListener('change', (st) => st !== 'active' && player.flush());
return () => sub.remove();
}, []);
if (!ready) return <Splash />;
return (
<ThemeContext.Provider value={theme}>
<StatusBar style={theme === 'dark' ? 'light' : 'dark'} />
<Screens />
</ThemeContext.Provider>
);
}
function Screens() {
const colors = useColors();
const { server, session } = useSessionCtx();
const auth = useAuthState();
const connected = !!server && !!session;
const user = connected && auth.status === 'signed_in' ? auth.user : null;
const needsSetup = !!user && (user.must_change_credentials || user.must_change_password);
return (
<Stack screenOptions={{ headerShown: false, contentStyle: { backgroundColor: colors.bg } }}>
{/* Guards exclude screens before render: an effect redirect runs after useSession/useUser throw. */}
<Stack.Protected guard={!connected}>
<Stack.Screen name="connect" />
</Stack.Protected>
<Stack.Protected guard={connected && !user}>
<Stack.Screen name="login" />
</Stack.Protected>
<Stack.Protected guard={needsSetup}>
<Stack.Screen name="setup" />
</Stack.Protected>
<Stack.Protected guard={!!user && !needsSetup}>
<Stack.Screen name="(tabs)" />
<Stack.Screen name="album/[id]" />
<Stack.Screen name="artist/[id]" />
<Stack.Screen name="playlists" />
<Stack.Screen name="player" options={{ presentation: 'modal', animation: 'slide_from_bottom' }} />
</Stack.Protected>
</Stack>
);
}
+68
View File
@@ -0,0 +1,68 @@
import { unwrap } from '@pipu/core';
import { useQuery } from '@tanstack/react-query';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { useTranslation } from 'react-i18next';
import { FlatList, Pressable, Text, View } from 'react-native';
import { useSession } from '../../lib/session';
import { downloads } from '../../offline/downloads';
import { player } from '../../player/controller';
import { usePlayerState } from '../../player/hooks';
import { useColors } from '../../theme';
import { Button, Cover, Icon, Screen, TrackRow, formatDuration, useErrorText } from '../../ui/kit';
export default function AlbumScreen() {
const colors = useColors();
const { id } = useLocalSearchParams<{ id: string }>();
const { t } = useTranslation();
const router = useRouter();
const session = useSession();
const current = usePlayerState().track;
const errorText = useErrorText();
const album = useQuery({
queryKey: ['album', id],
queryFn: async () => unwrap(await session.client.GET('/api/v1/albums/{id}', { params: { path: { id } } })),
});
const a = album.data;
const ctx = { type: 'album' as const, id };
return (
<Screen>
<FlatList
data={a?.tracks ?? []}
keyExtractor={(tr) => tr.id}
ListHeaderComponent={
<View style={{ padding: 16, gap: 12, alignItems: 'center' }}>
<Pressable onPress={() => router.back()} style={{ alignSelf: 'flex-start' }} accessibilityRole="button" accessibilityLabel={t('form.close')}>
<Icon name="arrow-back" color={colors.text} />
</Pressable>
{album.error ? <Text style={{ color: colors.danger }}>{errorText(album.error)}</Text> : null}
{a && (
<>
<Cover album={a} size={220} />
<Text style={{ color: colors.text, fontSize: 22, fontWeight: '700', textAlign: 'center' }}>{a.title}</Text>
<Pressable onPress={() => router.push(`/artist/${a.artist.id}`)}>
<Text style={{ color: colors.text2 }}>
{a.artist.name}
{a.year ? ` · ${a.year}` : ''} · {formatDuration(a.duration_ms)}
</Text>
</Pressable>
<Button title={t('player.play')} icon="play-arrow" onPress={() => void player.playList(a.tracks, 0, ctx)} />
<Button title={t('mobile.dl_album')} variant="secondary" icon="download" onPress={() => void downloads.enqueue(a.tracks)} />
</>
)}
</View>
}
renderItem={({ item, index }) => (
<TrackRow
track={item}
numbered={item.track_no ?? index + 1}
current={current?.id === item.id}
onPress={() => void player.playList(a?.tracks ?? [], index, ctx)}
onLike={() => void player.react(item, item.reaction === 'like' ? null : 'like').then(() => album.refetch())}
/>
)}
/>
</Screen>
);
}
+58
View File
@@ -0,0 +1,58 @@
import { unwrap } from '@pipu/core';
import { useQuery } from '@tanstack/react-query';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { useTranslation } from 'react-i18next';
import { FlatList, Pressable, Text, View } from 'react-native';
import { useSession } from '../../lib/session';
import { useColors } from '../../theme';
import { Cover, Icon, Screen } from '../../ui/kit';
export default function ArtistScreen() {
const colors = useColors();
const { id } = useLocalSearchParams<{ id: string }>();
const { t } = useTranslation();
const router = useRouter();
const session = useSession();
const artist = useQuery({
queryKey: ['artist', id],
queryFn: async () => unwrap(await session.client.GET('/api/v1/artists/{id}', { params: { path: { id } } })),
});
const albums = useQuery({
queryKey: ['artist-albums', id],
queryFn: async () => unwrap(await session.client.GET('/api/v1/artists/{id}/albums', { params: { path: { id } } })).items,
});
return (
<Screen>
<FlatList
data={albums.data ?? []}
keyExtractor={(a) => a.id}
numColumns={2}
columnWrapperStyle={{ gap: 12, paddingHorizontal: 16 }}
contentContainerStyle={{ gap: 16, paddingBottom: 24 }}
ListHeaderComponent={
<View style={{ padding: 16, gap: 10, alignItems: 'center' }}>
<Pressable onPress={() => router.back()} style={{ alignSelf: 'flex-start' }} accessibilityRole="button" accessibilityLabel={t('form.close')}>
<Icon name="arrow-back" color={colors.text} />
</Pressable>
<Cover album={{ id }} size={140} round />
<Text style={{ color: colors.text, fontSize: 24, fontWeight: '700' }}>{artist.data?.name ?? '…'}</Text>
{artist.data && (
<Text style={{ color: colors.text2 }}>
{t('catalog.album_count', { count: artist.data.album_count })} · {t('catalog.track_count', { count: artist.data.track_count })}
</Text>
)}
</View>
}
renderItem={({ item }) => (
<Pressable onPress={() => router.push(`/album/${item.id}`)} style={{ flex: 1, gap: 6 }} accessibilityRole="button">
<Cover album={item} size={160} />
<Text numberOfLines={1} style={{ color: colors.text, fontWeight: '600' }}>{item.title}</Text>
<Text style={{ color: colors.text3, fontSize: 12 }}>{item.year ?? ''}</Text>
</Pressable>
)}
/>
</Screen>
);
}
+83
View File
@@ -0,0 +1,83 @@
import { createApiClient } from '@pipu/api-client';
import { checkServer, normalizeServerUrl, type ServerCheck } from '@pipu/core';
import { useQuery } from '@tanstack/react-query';
import Constants from 'expo-constants';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Pressable, ScrollView, Text, View } from 'react-native';
import { useSessionCtx } from '../lib/session';
import { forgetServer, loadServers } from '../lib/storage';
import { radius, useColors } from '../theme';
import { Button, ErrorBox, Field, H1, Icon, Muted, Screen } from '../ui/kit';
const appVersionCode = Number(Constants.expoConfig?.extra?.versionCode ?? 0);
/** Подключение: адрес → проверка /server-info (версия, совместимость) → вход. */
export default function ConnectScreen() {
const colors = useColors();
const { t } = useTranslation();
const { connect } = useSessionCtx();
const [address, setAddress] = useState('');
const [checking, setChecking] = useState(false);
const [result, setResult] = useState<ServerCheck | 'invalid' | null>(null);
const servers = useQuery({ queryKey: ['saved-servers'], queryFn: loadServers });
const onConnect = async (raw = address) => {
const baseUrl = normalizeServerUrl(raw);
if (!baseUrl) return setResult('invalid');
setChecking(true);
const res = await checkServer(createApiClient({ baseUrl }), appVersionCode);
setChecking(false);
setResult(res);
if (res.status === 'ok') await connect(baseUrl, res.info.version);
};
return (
<Screen>
<ScrollView contentContainerStyle={{ padding: 20, gap: 14, flexGrow: 1, justifyContent: 'center' }} keyboardShouldPersistTaps="handled">
<H1>{t('app.name')}</H1>
<Muted>{t('app.tagline')}</Muted>
<Field
label={t('server.address')}
value={address}
onChangeText={setAddress}
onSubmitEditing={() => void onConnect()}
placeholder="https://music.home.lan"
keyboardType="url"
editable={!checking}
/>
{result === 'invalid' && <ErrorBox>{t('server.invalid_address')}</ErrorBox>}
{result !== null && result !== 'invalid' && result.status === 'unsupported_app' && (
<ErrorBox>{t('server.unsupported_app')}</ErrorBox>
)}
{result !== null && result !== 'invalid' && result.status === 'offline' && <ErrorBox>{t('server.offline')}</ErrorBox>}
<Button title={t('mobile.connect')} onPress={() => void onConnect()} busy={checking} disabled={!address.trim()} />
{!!servers.data?.length && (
<View style={{ gap: 8, marginTop: 16 }}>
<Text style={{ color: colors.text3, fontSize: 12, fontWeight: '700', textTransform: 'uppercase' }}>
{t('mobile.servers')}
</Text>
{servers.data.map((sv) => (
<View key={sv.url} style={{ flexDirection: 'row', alignItems: 'center', gap: 10, padding: 12, borderRadius: radius.md, backgroundColor: colors.surface }}>
<Pressable style={{ flex: 1 }} onPress={() => void onConnect(sv.url)} accessibilityRole="button">
<Text style={{ color: colors.text, fontWeight: '600' }}>{sv.url.replace(/^https?:\/\//, '')}</Text>
<Text style={{ color: colors.text3, fontSize: 12 }}>pipu {sv.version}</Text>
</Pressable>
<Pressable
onPress={() => void forgetServer(sv.url).then(() => servers.refetch())}
hitSlop={10}
accessibilityRole="button"
accessibilityLabel={t('mobile.forget_server')}
>
<Icon name="close" size={20} color={colors.text3} />
</Pressable>
</View>
))}
</View>
)}
</ScrollView>
</Screen>
);
}
+51
View File
@@ -0,0 +1,51 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ScrollView } from 'react-native';
import { useSessionCtx } from '../lib/session';
import { Button, ErrorBox, Field, H1, Muted, Screen, useErrorText } from '../ui/kit';
export default function LoginScreen() {
const { t } = useTranslation(['auth', 'common']);
const { server, session, disconnect } = useSessionCtx();
const errorText = useErrorText();
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<unknown>(null);
const submit = async () => {
if (!session) return;
setBusy(true);
setError(null);
try {
await session.login(username.trim(), password); // переход сделает Gate
} catch (e) {
setError(e);
setPassword('');
} finally {
setBusy(false);
}
};
return (
<Screen>
<ScrollView contentContainerStyle={{ padding: 20, gap: 14, flexGrow: 1, justifyContent: 'center' }} keyboardShouldPersistTaps="handled">
<H1>{t('login.title')}</H1>
<Muted>{server?.replace(/^https?:\/\//, '')}</Muted>
<Field label={t('login.username')} value={username} onChangeText={setUsername} autoComplete="username" />
<Field
label={t('login.password')}
value={password}
onChangeText={setPassword}
secure
autoComplete="password"
onSubmitEditing={() => void submit()}
/>
<ErrorBox>{error ? errorText(error) : null}</ErrorBox>
<Button title={t('login.submit')} onPress={() => void submit()} busy={busy} disabled={!username.trim() || !password} />
<Button title={t('common:mobile.change_server')} variant="ghost" onPress={() => void disconnect()} />
</ScrollView>
</Screen>
);
}
+142
View File
@@ -0,0 +1,142 @@
import { useRouter } from 'expo-router';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Alert, Pressable, Share, Text, View, type LayoutChangeEvent } from 'react-native';
import { trackShareUrl } from '@pipu/core';
import { useSessionCtx, useUser } from '../lib/session';
import { player } from '../player/controller';
import { usePlayerState } from '../player/hooks';
import { useColors } from '../theme';
import { DownloadButton } from '../ui/downloads';
import { Cover, Icon, Screen, formatDuration } from '../ui/kit';
import { WaveOrb } from '../ui/wave/WaveOrb';
/**
* Полноэкранный плеер: вид `cover` (крупная обложка) или `wave` (визуализация волны в цветах обложки) — по профилю;
* прогресс с перемоткой, лайк / дизлайк, скачать, управление.
*/
export default function PlayerScreen() {
const colors = useColors();
const { t } = useTranslation();
const router = useRouter();
const st = usePlayerState();
const prefs = useUser().ui_prefs;
const { server } = useSessionCtx();
const [sharing, setSharing] = useState(false);
const [barWidth, setBarWidth] = useState(1);
const track = st.track;
if (!track) {
return (
<Screen>
<Pressable onPress={() => router.back()} style={{ padding: 16 }} accessibilityRole="button" accessibilityLabel={t('mobile.close_player')}>
<Icon name="keyboard-arrow-down" size={32} color={colors.text} />
</Pressable>
</Screen>
);
}
const duration = st.durationMs || track.duration_ms;
const progress = duration ? Math.min(st.positionMs / duration, 1) : 0;
const react = (r: 'like' | 'dislike') => void player.react(track, track.reaction === r ? null : r).catch(() => undefined);
const share = async () => {
if (!server || sharing) return;
setSharing(true);
try {
await Share.share({ title: track.title, message: trackShareUrl(server, track.id) }, { dialogTitle: t('player.share') });
} catch {
Alert.alert(t('player.share'), t('player.share_error'));
} finally {
setSharing(false);
}
};
return (
<Screen>
<View style={{ flex: 1, padding: 24, gap: 24, justifyContent: 'space-between' }}>
<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
<Pressable onPress={() => router.back()} hitSlop={10} accessibilityRole="button" accessibilityLabel={t('mobile.close_player')}>
<Icon name="keyboard-arrow-down" size={32} color={colors.text} />
</Pressable>
<Text style={{ color: colors.text2, fontSize: 13 }}>{st.wave ? t('wave.title') : t('mobile.now_playing')}</Text>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 16 }}>
<Pressable onPress={() => void share()} disabled={!server || sharing} hitSlop={10} accessibilityRole="button" accessibilityLabel={t('player.share')} accessibilityState={{ disabled: !server || sharing }}>
<Icon name="share" size={24} color={colors.text} />
</Pressable>
<DownloadButton track={track} />
</View>
</View>
<View style={{ alignItems: 'center' }}>
{prefs.mobile_player === 'wave' ? (
<WaveOrb
variant={prefs.wave_variant ?? 'orb'}
size={280}
playing={st.playing}
bpm={track.features?.bpm ?? 100}
energy={track.features?.energy ?? 0.6}
colors={track.album.cover_colors}
>
<Cover album={track.album} size={96} round />
</WaveOrb>
) : (
<Cover album={track.album} size={300} />
)}
</View>
<View style={{ gap: 4 }}>
<Text numberOfLines={2} style={{ color: colors.text, fontSize: 22, fontWeight: '700' }}>
{track.title}
</Text>
<Text numberOfLines={1} style={{ color: colors.text2, fontSize: 15 }}>
{track.artists.map((a) => a.name).join(', ')}
</Text>
</View>
<View style={{ gap: 6 }}>
<Pressable
onLayout={(e: LayoutChangeEvent) => setBarWidth(e.nativeEvent.layout.width || 1)}
onPress={(e) => player.seek((e.nativeEvent.locationX / barWidth) * duration)}
accessibilityRole="adjustable"
accessibilityLabel={t('player.progress')}
accessibilityValue={{ min: 0, max: Math.round(duration / 1000), now: Math.round(st.positionMs / 1000) }}
accessibilityActions={[{ name: 'increment' }, { name: 'decrement' }]}
onAccessibilityAction={(e) => player.seek(st.positionMs + (e.nativeEvent.actionName === 'increment' ? 10_000 : -10_000))}
style={{ height: 24, justifyContent: 'center' }}
>
<View style={{ height: 4, borderRadius: 2, backgroundColor: colors.surface3 }}>
<View style={{ height: 4, borderRadius: 2, width: `${progress * 100}%`, backgroundColor: colors.accent2 }} />
</View>
</Pressable>
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<Text style={{ color: colors.text3, fontSize: 12 }}>{formatDuration(st.positionMs)}</Text>
<Text style={{ color: colors.text3, fontSize: 12 }}>{formatDuration(duration)}</Text>
</View>
</View>
<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
<Pressable onPress={() => react('dislike')} hitSlop={10} accessibilityRole="button" accessibilityLabel={t(track.reaction === 'dislike' ? 'player.undislike' : 'player.dislike')}>
<Icon name="heart-broken" size={28} color={track.reaction === 'dislike' ? colors.danger : colors.text2} />
</Pressable>
<Pressable onPress={() => void player.prev()} hitSlop={10} accessibilityRole="button" accessibilityLabel={t('player.prev')}>
<Icon name="skip-previous" size={40} color={colors.text} />
</Pressable>
<Pressable
onPress={() => player.toggle()}
accessibilityRole="button"
accessibilityLabel={t(st.playing ? 'player.pause' : 'player.play')}
style={{ width: 72, height: 72, borderRadius: 36, backgroundColor: colors.text, alignItems: 'center', justifyContent: 'center' }}
>
<Icon name={st.playing ? 'pause' : 'play-arrow'} size={40} color={colors.bg} />
</Pressable>
<Pressable onPress={() => player.next()} hitSlop={10} accessibilityRole="button" accessibilityLabel={t('player.next')}>
<Icon name="skip-next" size={40} color={colors.text} />
</Pressable>
<Pressable onPress={() => react('like')} hitSlop={10} accessibilityRole="button" accessibilityLabel={t(track.reaction === 'like' ? 'player.unlike' : 'player.like')}>
<Icon name={track.reaction === 'like' ? 'favorite' : 'favorite-border'} size={28} color={track.reaction === 'like' ? colors.accent2 : colors.text2} />
</Pressable>
</View>
</View>
</Screen>
);
}
+129
View File
@@ -0,0 +1,129 @@
import type { components } from '@pipu/api-client';
import { unwrap } from '@pipu/core';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Alert, FlatList, Modal, ScrollView, View } from 'react-native';
import { useSession, useUser } from '../lib/session';
import { player } from '../player/controller';
import { Button, ErrorBox, Field, H1, Muted, Screen, TrackRow, formatDuration, useErrorText } from '../ui/kit';
type Playlist = components['schemas']['Playlist'];
const input = (p: Playlist) => ({ name: p.name, description: p.description, revision: p.revision, track_ids: p.tracks.map(t => t.id) });
export default function PlaylistsScreen() {
const { id, track } = useLocalSearchParams<{ id?: string; track?: string }>();
return id ? <Detail key={id} id={id} /> : <List key={track ?? 'list'} track={track} />;
}
function List({ track }: { track?: string }) {
const session = useSession();
const user = useUser();
const router = useRouter();
const { t } = useTranslation();
const cache = useQueryClient();
const errorText = useErrorText();
const [create, setCreate] = useState(false);
const [search, setSearch] = useState('');
const list = useQuery({ queryKey: ['m-playlists', user.id], queryFn: async () => unwrap(await session.client.GET('/api/v1/me/playlists')) });
const add = useMutation({ mutationFn: async (id: string) => {
const p = unwrap(await session.client.GET('/api/v1/me/playlists/{id}', { params: { path: { id } } }));
const body = input(p); body.track_ids = [...new Set([...body.track_ids, track!])];
return unwrap(await session.client.PUT('/api/v1/me/playlists/{id}', { params: { path: { id } }, body }));
}, onSuccess: () => { void cache.invalidateQueries({ queryKey: ['m-playlists'] }); router.back(); } });
return <Screen><FlatList
data={list.data?.items.filter(p => p.name.toLocaleLowerCase().includes(search.toLocaleLowerCase())) ?? []}
keyExtractor={p => p.id} onRefresh={() => void list.refetch()} refreshing={list.isRefetching}
contentContainerStyle={{ padding: 16, gap: 12 }}
ListHeaderComponent={<View style={{ gap: 12 }}>
<Button title={t('form.close')} variant="ghost" onPress={() => router.back()} />
<H1>{t(track ? 'playlists.add' : 'playlists.title')}</H1>
<Button title={t('playlists.create')} onPress={() => setCreate(true)} disabled={add.isPending} />
<Field label={t('playlists.search')} value={search} onChangeText={setSearch} />
<ErrorBox>{list.error || add.error ? errorText(list.error ?? add.error) : null}</ErrorBox>
{list.isPending && <Muted>{t('playlists.loading')}</Muted>}
</View>}
ListEmptyComponent={list.isSuccess ? <Muted>{t(search ? 'playlists.no_results' : 'playlists.empty')}</Muted> : null}
renderItem={({ item }) => <Button title={`${item.name} · ${item.track_count}`} variant="secondary" disabled={add.isPending}
onPress={() => track ? add.mutate(item.id) : router.push({ pathname: '/playlists', params: { id: item.id } })} />}
/>{create && <Editor track={track} onClose={() => setCreate(false)} onSaved={p => {
setCreate(false); if (track) router.back(); else router.push({ pathname: '/playlists', params: { id: p.id } });
}} />}</Screen>;
}
function Editor({ playlist, track, onClose, onSaved }: { playlist?: Playlist; track?: string; onClose: () => void; onSaved: (p: Playlist) => void }) {
const session = useSession();
const { t } = useTranslation();
const cache = useQueryClient();
const errorText = useErrorText();
const [original] = useState(playlist);
const [name, setName] = useState(playlist?.name ?? '');
const [description, setDescription] = useState(playlist?.description ?? '');
const save = useMutation({ mutationFn: async () => {
const body = { name: name.trim(), description, track_ids: original?.tracks.map(t => t.id) ?? (track ? [track] : []) };
return original ? unwrap(await session.client.PUT('/api/v1/me/playlists/{id}', { params: { path: { id: original.id } }, body: { ...body, revision: original.revision } }))
: unwrap(await session.client.POST('/api/v1/me/playlists', { body }));
}, onSuccess: p => { void cache.invalidateQueries({ queryKey: ['m-playlists'] }); onSaved(p); },
onError: () => { void cache.invalidateQueries({ queryKey: ['m-playlists'] }); } });
return <Modal animationType="slide" onRequestClose={() => { if (!save.isPending) onClose(); }}><Screen><ScrollView keyboardShouldPersistTaps="handled" contentContainerStyle={{ padding: 20, gap: 16 }}>
<H1>{t(original ? 'playlists.edit' : 'playlists.create')}</H1>
<Field label={t('playlists.name')} value={name} onChangeText={setName} maxLength={120} autoFocus />
<Field label={t('playlists.description')} value={description} onChangeText={setDescription} maxLength={2000} multiline />
<ErrorBox>{save.error ? errorText(save.error) : null}</ErrorBox>
<Button title={t('playlists.save')} disabled={!name.trim()} busy={save.isPending} onPress={() => save.mutate()} />
<Button title={t('form.cancel')} variant="ghost" disabled={save.isPending} onPress={onClose} />
</ScrollView></Screen></Modal>;
}
function Detail({ id }: { id: string }) {
const session = useSession();
const user = useUser();
const router = useRouter();
const { t } = useTranslation();
const cache = useQueryClient();
const errorText = useErrorText();
const [edit, setEdit] = useState(false);
const [manage, setManage] = useState(false);
const [playError, setPlayError] = useState<unknown>();
const key = ['m-playlists', user.id, id];
const query = useQuery({ queryKey: key, queryFn: async () => unwrap(await session.client.GET('/api/v1/me/playlists/{id}', { params: { path: { id } } })) });
const p = query.data;
const save = useMutation({ mutationFn: async (ids: string[]) => unwrap(await session.client.PUT('/api/v1/me/playlists/{id}', { params: { path: { id } }, body: { ...input(p!), track_ids: ids } })),
onSuccess: data => { cache.setQueryData(key, data); void cache.invalidateQueries({ queryKey: ['m-playlists'] }); },
onError: () => { void cache.invalidateQueries({ queryKey: ['m-playlists'] }); } });
const deletion = useMutation({ mutationFn: async () => unwrap(await session.client.DELETE('/api/v1/me/playlists/{id}', { params: { path: { id } } })),
onSuccess: () => { cache.removeQueries({ queryKey: key }); void cache.invalidateQueries({ queryKey: ['m-playlists'] }); router.back(); } });
const play = (shuffle: boolean) => {
const tracks = p?.tracks.filter(t => t.available) ?? [];
if (shuffle) for (let i=tracks.length-1;i>0;i--) { const j=Math.floor(Math.random()*(i+1)); [tracks[i],tracks[j]]=[tracks[j]!,tracks[i]!]; }
if (tracks.length) void player.playList(tracks,0,{ type:'collection', id, label:p?.name }).catch(setPlayError);
};
const move = (index: number, delta: number) => {
const ids = p!.tracks.map(t => t.id); [ids[index],ids[index+delta]]=[ids[index+delta]!,ids[index]!]; save.mutate(ids);
};
return <Screen><FlatList data={p?.tracks ?? []} keyExtractor={t => t.id} onRefresh={() => void query.refetch()} refreshing={query.isRefetching}
ListHeaderComponent={<View style={{ padding:16,gap:12 }}>
<Button title={t('playlists.title')} variant="ghost" onPress={() => router.back()} />
<ErrorBox>{query.error || save.error || deletion.error || playError ? errorText(query.error ?? save.error ?? deletion.error ?? playError) : null}</ErrorBox>
{query.isPending && <Muted>{t('playlists.loading')}</Muted>}
{p && <><H1>{p.name}</H1><Muted>{p.description}</Muted><Muted>{t('catalog.track_count',{count:p.track_count})} · {formatDuration(p.duration_ms)}</Muted>
<Button title={t('collection.play_all')} disabled={!p.tracks.some(t => t.available)} onPress={() => play(false)} />
<Button title={t('collection.shuffle')} variant="secondary" disabled={!p.tracks.some(t => t.available)} onPress={() => play(true)} />
<Button title={t('playlists.edit')} variant="secondary" disabled={save.isPending || deletion.isPending} onPress={() => setEdit(true)} />
<Button title={t('playlists.manage')} variant="secondary" onPress={() => setManage(!manage)} />
<Button title={t('playlists.delete')} variant="danger" disabled={save.isPending} busy={deletion.isPending} onPress={() => Alert.alert(t('playlists.delete'),t('playlists.delete_confirm',{name:p.name}),[
{text:t('form.cancel'),style:'cancel'}, {text:t('playlists.delete'),style:'destructive',onPress:()=>deletion.mutate()},
])} />
</>}
</View>}
ListEmptyComponent={p ? <View style={{padding:16}}><Muted>{t('playlists.empty_tracks')}</Muted></View> : null}
renderItem={({item,index}) => <View><TrackRow track={item} onPress={() => void player.playList(p!.tracks,index,{type:'collection',id,label:p!.name}).catch(setPlayError)} />
{manage && <View style={{padding:12,gap:6}}>
<Button title={t('playlists.move_up',{name:item.title})} variant="ghost" disabled={!index || save.isPending} onPress={() => move(index,-1)} />
<Button title={t('playlists.move_down',{name:item.title})} variant="ghost" disabled={index===p!.tracks.length-1 || save.isPending} onPress={() => move(index,1)} />
<Button title={t('playlists.remove_track',{name:item.title})} variant="danger" disabled={save.isPending} onPress={() => save.mutate(p!.tracks.filter(t => t.id!==item.id).map(t => t.id))} />
</View>}
</View>}
/>{edit && p && <Editor playlist={p} onClose={() => setEdit(false)} onSaved={() => setEdit(false)} />}</Screen>;
}
+72
View File
@@ -0,0 +1,72 @@
import { ApiError, unwrap } from '@pipu/core';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ScrollView } from 'react-native';
import { useSession, useUser } from '../lib/session';
import { Button, ErrorBox, Field, H1, Muted, Screen, useErrorText } from '../ui/kit';
/** Обязательный шаг: новые логин и пароль админа после первого запуска или замена временного пароля. */
export default function SetupScreen() {
const { t } = useTranslation(['auth', 'common']);
const session = useSession();
const user = useUser();
const errorText = useErrorText();
const admin = user.must_change_credentials;
const min = user.role === 'user' ? 8 : 12;
const [username, setUsername] = useState(user.username);
const [password, setPassword] = useState('');
const [repeat, setRepeat] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<unknown>(null);
const mismatch = repeat !== '' && repeat !== password;
const fieldErr = (f: string) => (error instanceof ApiError && error.fieldCode(f) ? errorText(error) : undefined);
const submit = async () => {
setBusy(true);
setError(null);
try {
const res = admin
? await session.client.POST('/api/v1/me/bootstrap-credentials', { body: { new_username: username.trim(), new_password: password } })
: await session.client.POST('/api/v1/me/password', { body: { new_password: password } });
await session.apply(unwrap(res));
} catch (e) {
setError(e);
} finally {
setBusy(false);
}
};
return (
<Screen>
<ScrollView contentContainerStyle={{ padding: 20, gap: 14, flexGrow: 1, justifyContent: 'center' }} keyboardShouldPersistTaps="handled">
<H1>{t(admin ? 'setup.admin_title' : 'setup.password_title')}</H1>
<Muted>{t(admin ? 'setup.admin_text' : 'setup.password_text')}</Muted>
{admin && <Field label={t('setup.new_username')} value={username} onChangeText={setUsername} error={fieldErr('new_username')} />}
<Field
label={t('setup.new_password')}
value={password}
onChangeText={setPassword}
secure
hint={t('setup.min_length', { min })}
error={fieldErr('new_password')}
/>
<Field
label={t('setup.repeat_password')}
value={repeat}
onChangeText={setRepeat}
secure
error={mismatch ? t('common:form.passwords_mismatch') : undefined}
/>
<ErrorBox>{error && !fieldErr('new_password') && !fieldErr('new_username') ? errorText(error) : null}</ErrorBox>
<Button
title={t('setup.submit')}
onPress={() => void submit()}
busy={busy}
disabled={!password || password !== repeat || (admin && !username.trim())}
/>
<Button title={t('setup.logout')} variant="ghost" onPress={() => void session.logout()} />
</ScrollView>
</Screen>
);
}
+67
View File
@@ -0,0 +1,67 @@
import * as FileSystem from 'expo-file-system';
import * as SecureStore from 'expo-secure-store';
export type Quality = 'original' | 'high' | 'medium' | 'low';
export const QUALITIES: readonly Quality[] = ['original', 'high', 'medium', 'low'];
/** Качество звука по типу сети и для загрузок (настройка устройства, на сервер не уходит). */
export interface QualityPrefs {
wifi: Quality;
cellular: Quality;
download: Quality;
}
const QUALITY_KEY = 'pipu.quality';
const CLEAR_CACHE_KEY = 'pipu.cache.clear';
const DEFAULT_QUALITY: QualityPrefs = { wifi: 'high', cellular: 'medium', download: 'high' };
let quality: QualityPrefs = DEFAULT_QUALITY;
let loaded: Promise<void> | null = null;
const listeners = new Set<() => void>();
export const qualityPrefs = {
get: () => quality,
subscribe(fn: () => void) {
listeners.add(fn);
return () => listeners.delete(fn);
},
async load(): Promise<QualityPrefs> {
loaded ??= SecureStore.getItemAsync(QUALITY_KEY)
.then((raw) => {
if (raw) quality = { ...DEFAULT_QUALITY, ...(JSON.parse(raw) as Partial<QualityPrefs>) };
})
.catch(() => undefined);
await loaded;
return quality;
},
async set(patch: Partial<QualityPrefs>) {
quality = { ...quality, ...patch };
for (const fn of listeners) fn();
await SecureStore.setItemAsync(QUALITY_KEY, JSON.stringify(quality));
},
};
/**
* Кэш недавних стримов ExoPlayer (KotlinAudio кладёт его в `cacheDir/TrackPlayer`). Пока сервис плеера жив,
* SimpleCache держит индекс в памяти — поэтому очистка откладывается до следующего холодного запуска.
*/
const PLAYER_CACHE = `${FileSystem.cacheDirectory}TrackPlayer`;
export const playerCache = {
async size(): Promise<number> {
const info = await FileSystem.getInfoAsync(PLAYER_CACHE, { size: true }).catch(() => null);
return info?.exists ? (info.size ?? 0) : 0;
},
async requestClear() {
await SecureStore.setItemAsync(CLEAR_CACHE_KEY, '1');
},
async clearPending(): Promise<boolean> {
return (await SecureStore.getItemAsync(CLEAR_CACHE_KEY)) === '1';
},
/** Вызывается до setupPlayer, когда сервис ещё не запущен. */
async clearIfRequested() {
if (!(await this.clearPending())) return;
await FileSystem.deleteAsync(PLAYER_CACHE, { idempotent: true }).catch(() => undefined);
await SecureStore.deleteItemAsync(CLEAR_CACHE_KEY);
},
};
+7
View File
@@ -0,0 +1,7 @@
export type ReleaseNeed = 'current' | 'optional' | 'required';
/** Нужно ли обновление: обязательное, если установленная версия ниже min_supported. */
export function releaseNeed(installed: number, versionCode: number, minSupported: number): ReleaseNeed {
if (versionCode <= installed) return 'current';
return installed < minSupported ? 'required' : 'optional';
}
+91
View File
@@ -0,0 +1,91 @@
import { AuthSession, type AuthState } from '@pipu/core';
import Constants from 'expo-constants';
import { createContext, useCallback, useContext, useEffect, useMemo, useState, useSyncExternalStore, type ReactNode } from 'react';
import { currentServer, refreshStoreFor, rememberServer, setCurrentServer } from './storage';
interface SessionCtx {
/** Адрес сервера; null — сервер не выбран (экран подключения). */
server: string | null;
session: AuthSession | null;
ready: boolean;
connect: (url: string, version: string) => Promise<void>;
disconnect: () => Promise<void>;
}
const Ctx = createContext<SessionCtx | null>(null);
function deviceName(): string {
return Constants.deviceName ?? 'Android';
}
function makeSession(url: string) {
return new AuthSession({ baseUrl: url, clientType: 'android', deviceName: deviceName(), refreshStore: refreshStoreFor(url) });
}
/** Текущий сервер и сессия на нём; при запуске восстанавливает вход по сохранённому refresh-токену. */
export function SessionProvider({ children }: { children: ReactNode }) {
const [server, setServer] = useState<string | null>(null);
const [session, setSession] = useState<AuthSession | null>(null);
const [ready, setReady] = useState(false);
useEffect(() => {
void (async () => {
const url = await currentServer();
if (url) {
const s = makeSession(url);
await s.restore();
setServer(url);
setSession(s);
}
setReady(true);
})();
}, []);
const connect = useCallback(async (url: string, version: string) => {
await rememberServer({ url, version });
await setCurrentServer(url);
const s = makeSession(url);
await s.restore(); // на этом сервере уже могли войти раньше
setServer(url);
setSession(s);
}, []);
const disconnect = useCallback(async () => {
await setCurrentServer(null);
setServer(null);
setSession(null);
}, []);
const value = useMemo(() => ({ server, session, ready, connect, disconnect }), [server, session, ready, connect, disconnect]);
return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
}
export function useSessionCtx(): SessionCtx {
const c = useContext(Ctx);
if (!c) throw new Error('useSessionCtx outside SessionProvider');
return c;
}
/** Сессия вошедшего пользователя (экраны внутри приложения). */
export function useSession(): AuthSession {
const { session } = useSessionCtx();
if (!session) throw new Error('no session');
return session;
}
const UNKNOWN: AuthState = { status: 'unknown' };
export function useAuthState(): AuthState {
const { session } = useSessionCtx();
return useSyncExternalStore(
(fn) => session?.subscribe(fn) ?? (() => undefined),
() => session?.state ?? UNKNOWN,
);
}
export function useUser() {
const state = useAuthState();
if (state.status !== 'signed_in') throw new Error('not signed in');
return state.user;
}
+81
View File
@@ -0,0 +1,81 @@
import type { AuthUser, RefreshStore } from '@pipu/core';
import * as SecureStore from 'expo-secure-store';
// Всё храним в SecureStore (Android Keystore): список серверов маленький, а refresh-токен — секрет.
const SERVERS_KEY = 'pipu.servers';
const CURRENT_KEY = 'pipu.server';
export interface SavedServer {
url: string;
version: string;
/** Последний вошедший логин — подставляется в форму входа. */
username?: string;
}
/** Ключи SecureStore — только [A-Za-z0-9._-]: адрес сервера превращаем в безопасный суффикс. */
function keyFor(url: string): string {
let h = 0;
for (const ch of url) h = (h * 31 + ch.charCodeAt(0)) >>> 0;
return `pipu.rt.${h.toString(36)}`;
}
export async function loadServers(): Promise<SavedServer[]> {
try {
const raw = await SecureStore.getItemAsync(SERVERS_KEY);
return raw ? (JSON.parse(raw) as SavedServer[]) : [];
} catch {
return [];
}
}
/** Сохраняет сервер наверх списка (последний использованный — первый). */
export async function rememberServer(server: SavedServer): Promise<void> {
const list = (await loadServers()).filter((s) => s.url !== server.url);
await SecureStore.setItemAsync(SERVERS_KEY, JSON.stringify([server, ...list].slice(0, 10)));
}
export async function forgetServer(url: string): Promise<void> {
const list = (await loadServers()).filter((s) => s.url !== url);
await SecureStore.setItemAsync(SERVERS_KEY, JSON.stringify(list));
await refreshStoreFor(url).clear();
if ((await currentServer()) === url) await SecureStore.deleteItemAsync(CURRENT_KEY);
}
export async function currentServer(): Promise<string | null> {
return SecureStore.getItemAsync(CURRENT_KEY);
}
export async function setCurrentServer(url: string | null): Promise<void> {
if (url) await SecureStore.setItemAsync(CURRENT_KEY, url);
else await SecureStore.deleteItemAsync(CURRENT_KEY);
}
/** Refresh-токен сервера (у каждого сервера — свой) и последний пользователь — для запуска без сети. */
export function refreshStoreFor(url: string): RefreshStore {
const key = keyFor(url);
const userKey = key.replace('pipu.rt.', 'pipu.user.');
return {
get: () => SecureStore.getItemAsync(key),
set: (token) => SecureStore.setItemAsync(key, token),
clear: async () => {
await SecureStore.deleteItemAsync(key);
await SecureStore.deleteItemAsync(userKey);
},
getUser: async () => {
try {
const raw = await SecureStore.getItemAsync(userKey);
return raw ? (JSON.parse(raw) as AuthUser) : null;
} catch {
return null;
}
},
setUser: (user) => SecureStore.setItemAsync(userKey, JSON.stringify(user)),
};
}
/** Короткий стабильный хэш строки — для имён файлов и ключей. */
export function shortHash(s: string): string {
let h = 0;
for (const ch of s) h = (h * 31 + ch.charCodeAt(0)) >>> 0;
return h.toString(36);
}
+187
View File
@@ -0,0 +1,187 @@
import { unwrap, type AuthSession } from '@pipu/core';
import type { components } from '@pipu/api-client';
import Constants from 'expo-constants';
import * as FileSystem from 'expo-file-system';
import * as IntentLauncher from 'expo-intent-launcher';
import * as SecureStore from 'expo-secure-store';
import { sha256 } from 'js-sha256';
import { releaseNeed } from './releaseNeed';
export type AndroidRelease = components['schemas']['AndroidRelease'];
/** Состояние самообновления (docs/mobile.md#самообновление). */
export type UpdateState =
| { status: 'idle' }
| { status: 'checking' }
| { status: 'latest' }
| {
status: 'available';
release: AndroidRelease;
required: boolean;
dismissed: boolean;
}
| {
status: 'downloading';
release: AndroidRelease;
required: boolean;
progress: number;
}
| { status: 'verifying'; release: AndroidRelease; required: boolean }
| {
status: 'ready';
release: AndroidRelease;
required: boolean;
file: string;
}
| {
status: 'error';
release: AndroidRelease;
required: boolean;
error: 'bad_checksum' | 'failed';
};
const CHECK_EVERY_MS = 6 * 60 * 60 * 1000;
const CHECKED_KEY = 'pipu.update.checked';
const HASH_CHUNK = 1 << 20;
const APK_MIME = 'application/vnd.android.package-archive';
export function installedVersionCode(): number {
return Number((Constants.expoConfig?.extra as { versionCode?: number } | undefined)?.versionCode ?? 0);
}
/** SHA-256 файла кусками по 1 МБ: целиком APK в память JS не читаем. */
async function fileSha256(uri: string, size: number): Promise<string> {
const hash = sha256.create();
for (let pos = 0; pos < size; pos += HASH_CHUNK) {
const b64 = await FileSystem.readAsStringAsync(uri, {
encoding: FileSystem.EncodingType.Base64,
position: pos,
length: Math.min(HASH_CHUNK, size - pos),
});
const bin = atob(b64);
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
hash.update(bytes);
}
return hash.hex();
}
class Updater {
private current: UpdateState = { status: 'idle' };
private readonly listeners = new Set<() => void>();
private download: FileSystem.DownloadResumable | null = null;
get state(): UpdateState {
return this.current;
}
subscribe = (fn: () => void) => {
this.listeners.add(fn);
return () => this.listeners.delete(fn);
};
private set(s: UpdateState) {
this.current = s;
for (const fn of this.listeners) fn();
}
/** Проверка: автоматически — не чаще раза в 6 часов, вручную (профиль) — всегда. */
async check(session: AuthSession, manual = false): Promise<void> {
if (['checking', 'downloading', 'verifying'].includes(this.current.status)) return;
if (!manual) {
const last = Number((await SecureStore.getItemAsync(CHECKED_KEY)) ?? 0);
if (Date.now() - last < CHECK_EVERY_MS) return;
}
if (manual) this.set({ status: 'checking' });
try {
const release = unwrap(await session.client.GET('/api/v1/app/android/latest'));
await SecureStore.setItemAsync(CHECKED_KEY, String(Date.now()));
const installed = installedVersionCode();
const need = releaseNeed(installed, release.version_code, release.min_supported);
if (need !== 'current') {
this.set({
status: 'available',
release,
required: need === 'required',
dismissed: false,
});
} else {
this.set(manual ? { status: 'latest' } : { status: 'idle' });
}
} catch {
// Нет релиза или сервер без Gitea — молча; при ручной проверке показываем «последняя версия».
this.set(manual ? { status: 'latest' } : { status: 'idle' });
}
}
dismiss() {
const s = this.current;
if (s.status === 'available' && !s.required) this.set({ ...s, dismissed: true });
else if (s.status === 'latest') this.set({ status: 'idle' });
}
/** Скачивает APK с сервера (с Bearer), сверяет SHA-256 и запускает установщик. */
async downloadAndInstall(session: AuthSession, server: string): Promise<void> {
const s = this.current;
if (s.status !== 'available' && s.status !== 'error' && s.status !== 'ready') return;
const { release, required } = s;
if (s.status === 'ready') return this.install(s.file);
// Любой запрос через client обновит access-токен, если он истёк.
await session.client.GET('/api/v1/app/android/latest').catch(() => undefined);
const file = `${FileSystem.cacheDirectory}pipu-music-${release.version}.apk`;
this.set({ status: 'downloading', release, required, progress: 0 });
try {
await FileSystem.deleteAsync(file, { idempotent: true });
this.download = FileSystem.createDownloadResumable(
server + release.download_url,
file,
{ headers: { Authorization: `Bearer ${session.accessToken ?? ''}` } },
(p) => {
const total = p.totalBytesExpectedToWrite > 0 ? p.totalBytesExpectedToWrite : release.size;
this.set({
status: 'downloading',
release,
required,
progress: total ? p.totalBytesWritten / total : 0,
});
},
);
const res = await this.download.downloadAsync();
this.download = null;
if (!res || res.status !== 200) throw new Error(`status ${res?.status}`);
this.set({ status: 'verifying', release, required });
const info = await FileSystem.getInfoAsync(file);
const size = info.exists ? info.size : 0;
if ((await fileSha256(file, size)) !== release.sha256.toLowerCase()) {
await FileSystem.deleteAsync(file, { idempotent: true });
this.set({ status: 'error', release, required, error: 'bad_checksum' });
return;
}
this.set({ status: 'ready', release, required, file });
await this.install(file);
} catch {
this.download = null;
this.set({ status: 'error', release, required, error: 'failed' });
}
}
private async install(file: string) {
const uri = await FileSystem.getContentUriAsync(file);
await IntentLauncher.startActivityAsync('android.intent.action.VIEW', {
data: uri,
type: APK_MIME,
flags: 1, // FLAG_GRANT_READ_URI_PERMISSION
});
}
/** Экран «Установка неизвестных приложений» для нашего пакета. */
async openInstallSettings() {
const pkg = Constants.expoConfig?.android?.package ?? 'app.pipu.music';
await IntentLauncher.startActivityAsync('android.settings.MANAGE_UNKNOWN_APP_SOURCES', { data: `package:${pkg}` });
}
}
export const updater = new Updater();
+38
View File
@@ -0,0 +1,38 @@
import * as SQLite from 'expo-sqlite';
let db: Promise<SQLite.SQLiteDatabase> | null = null;
/**
* Локальная база офлайн-режима (docs/mobile.md#офлайн). `owner` — хэш «сервер + пользователь»:
* скачанное, неотправленные события и реакции одного аккаунта не видны другому.
*/
export function getDb(): Promise<SQLite.SQLiteDatabase> {
db ??= (async () => {
const d = await SQLite.openDatabaseAsync('pipu.db');
await d.execAsync(`
PRAGMA journal_mode = WAL;
CREATE TABLE IF NOT EXISTS downloads (
owner TEXT NOT NULL,
track_id TEXT NOT NULL,
track TEXT NOT NULL,
status TEXT NOT NULL,
bytes INTEGER NOT NULL DEFAULT 0,
added_at INTEGER NOT NULL,
PRIMARY KEY (owner, track_id)
);
CREATE TABLE IF NOT EXISTS pending_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner TEXT NOT NULL,
body TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS pending_reactions (
owner TEXT NOT NULL,
track_id TEXT NOT NULL,
reaction TEXT,
PRIMARY KEY (owner, track_id)
);
`);
return d;
})();
return db;
}
+289
View File
@@ -0,0 +1,289 @@
import NetInfo, { type NetInfoState } from '@react-native-community/netinfo';
import { unwrap, type AuthSession, type Track } from '@pipu/core';
import * as FileSystem from 'expo-file-system';
import * as SecureStore from 'expo-secure-store';
import { qualityPrefs } from '../lib/prefs';
import { shortHash } from '../lib/storage';
import { getDb } from './db';
export type DownloadStatus = 'queued' | 'downloading' | 'done' | 'error';
export interface DownloadItem {
track: Track;
status: DownloadStatus;
progress: number;
bytes: number;
addedAt: number;
}
export interface DownloadsState {
items: ReadonlyMap<string, DownloadItem>;
wifiOnly: boolean;
autoLikes: boolean;
/** Сеть разрешает загрузку прямо сейчас (с учётом «только Wi-Fi»). */
allowed: boolean;
}
const PARALLEL = 2;
const WIFI_KEY = 'pipu.dl.wifi';
const AUTO_LIKES_KEY = 'pipu.dl.autolikes';
/**
* Загрузки для офлайна: файлы — в documentDirectory/offline/<owner>/, метаданные (DTO трека) — в SQLite.
* Не более двух загрузок параллельно; по умолчанию только по Wi-Fi; прерванные продолжаются при запуске.
*/
class Downloads {
private session: AuthSession | null = null;
private server = '';
private owner = '';
private active = new Map<string, FileSystem.DownloadResumable | null>();
private net: NetInfoState | null = null;
private unsubscribeNet: (() => void) | null = null;
private listeners = new Set<() => void>();
private current: DownloadsState = { items: new Map(), wifiOnly: true, autoLikes: false, allowed: false };
get state(): DownloadsState {
return this.current;
}
subscribe = (fn: () => void) => {
this.listeners.add(fn);
return () => this.listeners.delete(fn);
};
private set(patch: Partial<DownloadsState>) {
this.current = { ...this.current, ...patch };
for (const fn of this.listeners) fn();
}
private setItem(id: string, patch: Partial<DownloadItem> | null) {
const items = new Map(this.current.items);
if (patch === null) items.delete(id);
else {
const prev = items.get(id);
if (!prev && !patch.track) return;
items.set(id, { ...(prev as DownloadItem), ...patch });
}
this.set({ items });
}
private get dir() {
return `${FileSystem.documentDirectory}offline/${this.owner}/`;
}
private file(trackId: string) {
return `${this.dir}${trackId}.opus`;
}
private cover(albumId: string) {
return `${this.dir}covers/${albumId}.webp`;
}
/** Привязка к пользователю: загружает список скачанного и продолжает незавершённые загрузки. */
async attach(session: AuthSession | null, server: string, userId: string | null) {
const owner = session && userId ? shortHash(`${server}|${userId}`) : '';
if (owner === this.owner && session === this.session) return;
for (const d of this.active.values()) void d?.pauseAsync().catch(() => undefined);
this.active.clear();
this.session = session;
this.server = server;
this.owner = owner;
if (!owner) {
this.set({ items: new Map() });
return;
}
const [wifi, autoLikes] = await Promise.all([SecureStore.getItemAsync(WIFI_KEY), SecureStore.getItemAsync(AUTO_LIKES_KEY)]);
await FileSystem.makeDirectoryAsync(`${this.dir}covers/`, { intermediates: true }).catch(() => undefined);
const db = await getDb();
await db.runAsync(`UPDATE downloads SET status = 'queued' WHERE owner = ? AND status = 'downloading'`, owner);
const rows = await db.getAllAsync<{ track_id: string; track: string; status: DownloadStatus; bytes: number; added_at: number }>(
'SELECT track_id, track, status, bytes, added_at FROM downloads WHERE owner = ? ORDER BY added_at',
owner,
);
const items = new Map<string, DownloadItem>();
for (const r of rows) {
items.set(r.track_id, { track: JSON.parse(r.track) as Track, status: r.status, progress: r.status === 'done' ? 1 : 0, bytes: r.bytes, addedAt: r.added_at });
}
this.set({ items, wifiOnly: wifi !== '0', autoLikes: autoLikes === '1' });
this.unsubscribeNet ??= NetInfo.addEventListener((st) => {
this.net = st;
this.set({ allowed: this.networkAllowed() });
this.pump();
});
this.net = await NetInfo.fetch();
this.set({ allowed: this.networkAllowed() });
this.pump();
}
private networkAllowed(): boolean {
if (!this.net?.isConnected) return false;
return !this.current.wifiOnly || this.net.type === 'wifi' || this.net.type === 'ethernet';
}
async setWifiOnly(v: boolean) {
await SecureStore.setItemAsync(WIFI_KEY, v ? '1' : '0');
this.set({ wifiOnly: v });
this.set({ allowed: this.networkAllowed() });
this.pump();
}
async setAutoLikes(v: boolean) {
await SecureStore.setItemAsync(AUTO_LIKES_KEY, v ? '1' : '0');
this.set({ autoLikes: v });
}
isDownloaded(trackId: string): boolean {
return this.current.items.get(trackId)?.status === 'done';
}
/** Локальный файл трека, если он скачан. */
localTrack(trackId: string): string | undefined {
return this.isDownloaded(trackId) ? this.file(trackId) : undefined;
}
localCover(track: Track): string | undefined {
return this.isDownloaded(track.id) && track.album.cover_url ? this.cover(track.album.id) : undefined;
}
/** Обложка альбома на устройстве, если из него что-то скачано. */
localAlbumCover(albumId: string): string | undefined {
for (const it of this.current.items.values()) {
if (it.status === 'done' && it.track.album.id === albumId && it.track.album.cover_url) return this.cover(albumId);
}
return undefined;
}
/** Скачанные треки в порядке добавления. */
downloaded(): Track[] {
return [...this.current.items.values()].filter((i) => i.status === 'done').map((i) => i.track);
}
async enqueue(tracks: Track[]) {
if (!this.owner) return;
const db = await getDb();
const now = Date.now();
for (const [n, t] of tracks.entries()) {
if (!t.available || this.current.items.has(t.id)) continue;
const addedAt = now + n;
await db.runAsync(
`INSERT OR IGNORE INTO downloads (owner, track_id, track, status, added_at) VALUES (?, ?, ?, 'queued', ?)`,
this.owner,
t.id,
JSON.stringify(t),
addedAt,
);
this.setItem(t.id, { track: t, status: 'queued', progress: 0, bytes: 0, addedAt });
}
this.pump();
}
async remove(trackIds: string[]) {
const db = await getDb();
for (const id of trackIds) {
const d = this.active.get(id);
this.active.delete(id);
await d?.pauseAsync().catch(() => undefined);
await FileSystem.deleteAsync(this.file(id), { idempotent: true });
await FileSystem.deleteAsync(`${this.file(id)}.part`, { idempotent: true });
await db.runAsync('DELETE FROM downloads WHERE owner = ? AND track_id = ?', this.owner, id);
this.setItem(id, null);
}
this.pump();
}
/** Реакция в сохранённом DTO: офлайн-волна и списки скачанного видят её без сети. */
async setReaction(trackId: string, reaction: Track['reaction']) {
const it = this.current.items.get(trackId);
if (!it || it.track.reaction === reaction) return;
const track = { ...it.track, reaction };
this.setItem(trackId, { track });
const db = await getDb();
await db.runAsync('UPDATE downloads SET track = ? WHERE owner = ? AND track_id = ?', JSON.stringify(track), this.owner, trackId);
}
/** Повторить загрузки с ошибкой. */
async retry() {
const db = await getDb();
await db.runAsync(`UPDATE downloads SET status = 'queued' WHERE owner = ? AND status = 'error'`, this.owner);
for (const [id, it] of this.current.items) if (it.status === 'error') this.setItem(id, { status: 'queued', progress: 0 });
this.pump();
}
/** Занято на устройстве и свободно в телефоне (байты). */
async usage(): Promise<{ used: number; free: number }> {
let used = 0;
for (const it of this.current.items.values()) used += it.bytes;
const free = await FileSystem.getFreeDiskStorageAsync().catch(() => 0);
return { used, free };
}
private pump() {
if (!this.owner || !this.current.allowed) return;
for (const [id, it] of this.current.items) {
if (this.active.size >= PARALLEL) return;
if (it.status !== 'queued' || this.active.has(id)) continue;
this.active.set(id, null);
void this.run(id).finally(() => {
this.active.delete(id);
this.pump();
});
}
}
private async run(id: string) {
const session = this.session;
const owner = this.owner;
if (!session) return;
const db = await getDb();
const status = async (s: DownloadStatus, patch: Partial<DownloadItem> = {}, track?: Track) => {
if (this.owner !== owner) return;
await db.runAsync(
'UPDATE downloads SET status = ?, bytes = ?, track = COALESCE(?, track) WHERE owner = ? AND track_id = ?',
s,
patch.bytes ?? 0,
track ? JSON.stringify(track) : null,
owner,
id,
);
this.setItem(id, { status: s, ...patch, ...(track ? { track } : {}) });
};
try {
await status('downloading', { progress: 0 });
// Подписанные ссылки живут 12 ч — перед загрузкой берём свежий DTO.
const res = unwrap(await session.client.POST('/api/v1/tracks/batch', { body: { ids: [id] } }));
const track = res.items[0];
if (!track?.available || !track.stream_url) {
await status('error');
return;
}
const part = `${this.file(id)}.part`;
const q = (await qualityPrefs.load()).download;
const dl = FileSystem.createDownloadResumable(`${this.abs(track.stream_url)}&q=${q}`, part, {}, (p) => {
if (p.totalBytesExpectedToWrite > 0) this.setItem(id, { progress: p.totalBytesWritten / p.totalBytesExpectedToWrite });
});
this.active.set(id, dl);
const out = await dl.downloadAsync();
if (this.active.get(id) !== dl) return; // отменено (удалили или сменился пользователь)
if (!out || out.status !== 200) throw new Error(`status ${out?.status}`);
await FileSystem.moveAsync({ from: part, to: this.file(id) });
if (track.album.cover_url) {
const cover = this.cover(track.album.id);
const info = await FileSystem.getInfoAsync(cover);
if (!info.exists) await FileSystem.downloadAsync(`${this.abs(track.album.cover_url)}&size=300`, cover).catch(() => undefined);
}
const info = await FileSystem.getInfoAsync(this.file(id));
await status('done', { progress: 1, bytes: info.exists ? info.size : 0 }, track);
} catch {
await status('error', { progress: 0 });
}
}
private abs(path: string) {
return /^https?:/.test(path) ? path : this.server + path;
}
}
export const downloads = new Downloads();
+120
View File
@@ -0,0 +1,120 @@
import { ApiError, unwrap, type AuthSession, type PlayEvent } from '@pipu/core';
import { shortHash } from '../lib/storage';
import { getDb } from './db';
const BATCH = 500;
type Reaction = 'like' | 'dislike' | null;
/**
* Отправка событий прослушивания и реакций с запасом на офлайн: что не ушло из-за сети — в SQLite,
* досылается при появлении сети (`POST /events` идемпотентен по id события, реакция — PUT/DELETE,
* для трека хранится только последняя).
*/
export class PersistentEvents {
private readonly owner: string;
private draining = false;
constructor(
private readonly session: AuthSession,
server: string,
userId: string,
) {
this.owner = shortHash(`${server}|${userId}`);
}
private async post(events: PlayEvent[]) {
unwrap(await this.session.client.POST('/api/v1/events', { body: { events } }));
}
/** Sink для EventBuffer: при сетевой ошибке сохраняет пачку и «успешно» завершается. */
send = async (events: PlayEvent[]) => {
try {
await this.post(events);
void this.drain();
} catch (e) {
if (!isNetwork(e)) throw e;
const db = await getDb();
await db.runAsync('INSERT INTO pending_events (owner, body) VALUES (?, ?)', this.owner, JSON.stringify(events));
}
};
private async putReaction(trackId: string, reaction: Reaction) {
const params = { params: { path: { id: trackId } } };
if (reaction) unwrap(await this.session.client.PUT('/api/v1/me/reactions/tracks/{id}', { ...params, body: { reaction } }));
else unwrap(await this.session.client.DELETE('/api/v1/me/reactions/tracks/{id}', params));
}
/** Реакция на трек. Без сети — откладывается и возвращает `queued`; ошибку сервера пробрасывает. */
async react(trackId: string, reaction: Reaction): Promise<'sent' | 'queued'> {
const db = await getDb();
try {
await this.putReaction(trackId, reaction);
} catch (e) {
if (!isNetwork(e)) throw e;
await db.runAsync(
'INSERT OR REPLACE INTO pending_reactions (owner, track_id, reaction) VALUES (?, ?, ?)',
this.owner,
trackId,
reaction,
);
return 'queued';
}
// Более свежая реакция ушла — отложенная устарела.
await db.runAsync('DELETE FROM pending_reactions WHERE owner = ? AND track_id = ?', this.owner, trackId);
void this.drain();
return 'sent';
}
/** Досылает отложенные реакции и пачки событий; останавливается на первой сетевой ошибке. */
async drain() {
if (this.draining) return;
this.draining = true;
try {
const db = await getDb();
const reactions = await db.getAllAsync<{ track_id: string; reaction: Reaction }>(
'SELECT track_id, reaction FROM pending_reactions WHERE owner = ?',
this.owner,
);
for (const r of reactions) {
try {
await this.putReaction(r.track_id, r.reaction);
} catch (e) {
if (isNetwork(e)) return;
// трек удалён из библиотеки и т. п. — отбрасываем
}
await db.runAsync(
'DELETE FROM pending_reactions WHERE owner = ? AND track_id = ? AND reaction IS ?',
this.owner,
r.track_id,
r.reaction,
);
}
for (;;) {
const rows = await db.getAllAsync<{ id: number; body: string }>(
'SELECT id, body FROM pending_events WHERE owner = ? ORDER BY id LIMIT 20',
this.owner,
);
if (!rows.length) return;
for (const r of rows) {
const events = JSON.parse(r.body) as PlayEvent[];
try {
for (let i = 0; i < events.length; i += BATCH) await this.post(events.slice(i, i + BATCH));
} catch (e) {
if (isNetwork(e)) return;
// Сервер отверг пачку (4xx) — повтор не поможет, отбрасываем.
}
await db.runAsync('DELETE FROM pending_events WHERE id = ?', r.id);
}
}
} finally {
this.draining = false;
}
}
}
function isNetwork(e: unknown): boolean {
if (e instanceof ApiError) return e.code === 'common.network' || e.status >= 500;
return true; // fetch бросает TypeError без ответа сервера
}
+454
View File
@@ -0,0 +1,454 @@
import NetInfo from '@react-native-community/netinfo';
import {
EventBuffer,
PlayAttempt,
normalizeGain,
unwrap,
type AuthSession,
type PlayContext,
type Track,
} from '@pipu/core';
import TrackPlayer, {
AppKilledPlaybackBehavior,
Capability,
Event,
State,
type Track as RntpTrack,
} from 'react-native-track-player';
import { playerCache, qualityPrefs, type Quality } from '../lib/prefs';
import { downloads } from '../offline/downloads';
import { PersistentEvents } from '../offline/events';
import { offlineWave } from './offlineWave';
import { eventId } from './eventId';
export { offlineWave };
export interface WaveInfo {
sessionId: string;
activity: string | null;
mood: string | null;
fallback: boolean;
}
export interface PlayerState {
ready: boolean;
track: Track | null;
queue: Track[];
index: number;
playing: boolean;
buffering: boolean;
positionMs: number;
durationMs: number;
context: PlayContext | null;
wave: WaveInfo | null;
}
type WaveOutcome = 'complete' | 'skip' | 'skip_early' | 'like' | 'dislike';
const WAVE_REFILL_AT = 2;
const EARLY_SKIP_MS = 30_000;
const SAVE_EVERY_MS = 10_000;
const playable = (t: Track) => t.available && (!!t.stream_url || downloads.isDownloaded(t.id));
/** Ссылки API относительные — для приложения нужен полный адрес сервера. */
export function absolute(server: string, path: string | null | undefined): string | undefined {
if (!path) return undefined;
return /^https?:/.test(path) ? path : server + path;
}
/** Качество по сети (docs/playback.md#качество): Wi-Fi — high, сотовая — medium. */
/** Качество стрима по типу сети — из настроек профиля. */
async function quality(): Promise<Quality> {
const prefs = await qualityPrefs.load();
try {
const net = await NetInfo.fetch();
return net.type === 'cellular' ? prefs.cellular : prefs.wifi;
} catch {
return prefs.wifi;
}
}
/**
* Плеер Android. Очередь живёт в ExoPlayer (react-native-track-player) — играет и с выгруженным UI;
* здесь — зеркало очереди с DTO треков, учёт прослушиваний (PlayAttempt из @pipu/core), события,
* реакции и бесконечная волна. Один экземпляр на процесс: им пользуются и экраны, и фоновый сервис.
*/
class Controller {
private session: AuthSession | null = null;
private server = '';
private events: EventBuffer | null = null;
private persistent: PersistentEvents | null = null;
private unsubscribeNet: (() => void) | null = null;
private attempt: PlayAttempt | null = null;
private lastPositionMs = 0;
private lastSave = 0;
private waveFeedback: { track_id: string; outcome: WaveOutcome }[] = [];
private waveLoading = false;
private neutralSwitch = false; // следующая смена трека — из-за нового контекста волны
private setupDone: Promise<void> | null = null;
private listeners = new Set<() => void>();
private state: PlayerState = {
ready: false, track: null, queue: [], index: 0, playing: false, buffering: false, positionMs: 0, durationMs: 0,
context: null, wave: null,
};
subscribe = (fn: () => void) => {
this.listeners.add(fn);
return () => this.listeners.delete(fn);
};
getState = () => this.state;
private update(patch: Partial<PlayerState>) {
this.state = { ...this.state, ...patch };
for (const fn of this.listeners) fn();
}
/** Привязка к вошедшему пользователю: события и реакции уходят на его сервер, без сети — копятся в SQLite. */
attach(session: AuthSession | null, server: string, userId: string | null) {
if (this.session === session) return;
void this.events?.flush();
this.session = session;
this.server = server;
this.persistent = session && userId ? new PersistentEvents(session, server, userId) : null;
const sink = this.persistent;
this.events = sink ? new EventBuffer({ send: sink.send }, Date.now, undefined, eventId) : null;
void sink?.drain();
this.unsubscribeNet ??= NetInfo.addEventListener((st) => {
if (st.isConnected) void this.persistent?.drain();
});
if (!session) void this.reset();
}
setup(): Promise<void> {
this.setupDone ??= (async () => {
// Очистка кэша из профиля — только пока сервис плеера не запущен (иначе SimpleCache держит файлы).
if (!(await TrackPlayer.isServiceRunning().catch(() => true))) await playerCache.clearIfRequested();
try {
// 500 МБ кэша ExoPlayer для недавних стримов (значение — в КБ).
await TrackPlayer.setupPlayer({ maxCacheSize: 500 * 1024, autoHandleInterruptions: true });
} catch {
// уже настроен (повторный запуск JS при живом сервисе)
}
await TrackPlayer.updateOptions({
capabilities: [Capability.Play, Capability.Pause, Capability.SkipToNext, Capability.SkipToPrevious, Capability.SeekTo],
compactCapabilities: [Capability.Play, Capability.Pause, Capability.SkipToNext],
progressUpdateEventInterval: 1,
android: { appKilledPlaybackBehavior: AppKilledPlaybackBehavior.StopPlaybackAndRemoveNotification },
});
this.bind();
this.update({ ready: true });
})();
return this.setupDone;
}
private bind() {
TrackPlayer.addEventListener(Event.PlaybackState, ({ state }) => {
this.update({ playing: state === State.Playing, buffering: state === State.Buffering || state === State.Loading });
if (state === State.Paused) this.save();
});
TrackPlayer.addEventListener(Event.PlaybackProgressUpdated, ({ position, duration }) => {
const ms = Math.round(position * 1000);
this.attempt?.tick(ms);
this.lastPositionMs = ms;
this.update({ positionMs: ms, durationMs: Math.round(duration * 1000) || this.state.durationMs });
if (this.state.playing && Date.now() - this.lastSave > SAVE_EVERY_MS) this.save();
const cf = Math.min(6, Math.max(0, this.userPrefs()?.crossfade_s ?? 0));
const left = duration - position;
const fade = cf > 0 && left < cf ? Math.max(0, left / cf) : 1;
void this.applyVolume(this.state.track, fade);
});
TrackPlayer.addEventListener(Event.PlaybackActiveTrackChanged, ({ index, lastPosition }) => {
this.finishAttempt(lastPosition);
if (index === undefined || index === null) return;
const track = this.state.queue[index];
if (!track) return;
this.attempt = new PlayAttempt(track, 0);
this.update({ track, index, positionMs: 0, durationMs: track.duration_ms });
void this.applyVolume(track, 1);
this.events?.push({
type: 'play_start', track_id: track.id, position_ms: 0, context_type: this.state.context?.type,
context_id: this.state.context?.id,
});
this.save();
void this.refillWave();
});
TrackPlayer.addEventListener(Event.PlaybackQueueEnded, () => {
this.finishAttempt(this.lastPositionMs / 1000, true);
void this.events?.flush();
});
TrackPlayer.addEventListener(Event.PlaybackError, () => {
// Ссылка могла устареть или трек пропал — переходим дальше, ExoPlayer не застрянет на ошибке.
void TrackPlayer.skipToNext().catch(() => undefined);
});
}
/** Завершение попытки: доиграно (позиция у конца) или пропущено. */
private finishAttempt(lastPositionS: number, ended = false) {
const a = this.attempt;
if (!a) return;
this.attempt = null;
const pos = Math.round(lastPositionS * 1000);
if (this.neutralSwitch) {
this.neutralSwitch = false;
if (a.playedMs >= EARLY_SKIP_MS) {
this.events?.push({ type: 'skip', track_id: a.track.id, position_ms: pos, played_ms: Math.round(a.playedMs) });
void this.events?.flush();
}
return;
}
const kind = ended ? 'play_end' : a.outcome(pos);
this.events?.push({ type: kind, track_id: a.track.id, position_ms: pos, played_ms: Math.round(a.playedMs) });
void this.events?.flush();
if (kind === 'play_end') this.noteWave(a.track.id, 'complete');
else {
const early = a.playedMs < EARLY_SKIP_MS;
this.noteWave(a.track.id, early ? 'skip_early' : 'skip');
if (early) void this.refillWave(true);
}
}
private userPrefs() {
const st = this.session?.state;
return st?.status === 'signed_in' ? st.user.ui_prefs : undefined;
}
/** Громкость 0..1: нормализация вниз к −14 LUFS и затухание кроссфейда в конце трека. */
private async applyVolume(track: Track | null, fade: number) {
const gain = Math.min(1, normalizeGain(track?.features?.loudness_lufs, this.userPrefs()?.normalize !== false) * fade);
await TrackPlayer.setVolume(gain).catch(() => undefined);
}
private async toRntp(tracks: Track[]): Promise<RntpTrack[]> {
const q = await quality();
// Скачанный трек играется из файла (и без сети), остальные — стримом по качеству сети.
return tracks.map((t) => ({
id: t.id,
url: downloads.localTrack(t.id) ?? `${absolute(this.server, t.stream_url)}&q=${q}`,
title: t.title,
artist: t.artists.map((a) => a.name).join(', '),
album: t.album.title,
artwork: downloads.localCover(t) ?? (t.album.cover_url ? `${absolute(this.server, t.album.cover_url)}&size=300` : undefined),
duration: t.duration_ms / 1000,
}));
}
async playList(tracks: Track[], index: number, context: PlayContext) {
const list = tracks.filter(playable);
const target = tracks[index];
if (!target || !list.length) return;
await this.setup();
this.leaveWave();
this.finishAttempt(this.lastPositionMs / 1000);
const start = Math.max(list.indexOf(target), 0);
this.update({ queue: list, context, index: start, track: list[start] ?? null });
await TrackPlayer.reset();
await TrackPlayer.add(await this.toRntp(list));
await TrackPlayer.skip(start);
await TrackPlayer.play();
}
toggle() {
void (this.state.playing ? TrackPlayer.pause() : TrackPlayer.play());
}
next() {
void TrackPlayer.skipToNext().catch(() => undefined);
}
async prev() {
const { position } = await TrackPlayer.getProgress();
if (position > 3) await TrackPlayer.seekTo(0);
else await TrackPlayer.skipToPrevious().catch(() => TrackPlayer.seekTo(0));
}
seek(ms: number) {
const t = this.state.track;
if (t) this.events?.push({ type: 'seek', track_id: t.id, from_ms: this.lastPositionMs, position_ms: ms });
this.attempt?.seek(ms);
this.lastPositionMs = ms;
void TrackPlayer.seekTo(ms / 1000);
}
/** Реакция на трек: сразу в UI; без сети запоминается и уходит на сервер при появлении связи. */
async react(track: Track, reaction: 'like' | 'dislike' | null) {
if (!this.persistent) return;
const prev = track.reaction;
const apply = (r: Track['reaction']) => {
this.update({
queue: this.state.queue.map((t) => (t.id === track.id ? { ...t, reaction: r } : t)),
track: this.state.track?.id === track.id ? { ...this.state.track, reaction: r } : this.state.track,
});
void downloads.setReaction(track.id, r);
};
apply(reaction);
this.events?.push({ type: reaction ?? (prev === 'like' ? 'unlike' : 'undislike'), track_id: track.id });
try {
await this.persistent.react(track.id, reaction);
} catch (e) {
apply(prev);
throw e;
}
if (reaction === 'like' && downloads.state.autoLikes) void downloads.enqueue([{ ...track, reaction }]);
if (reaction) {
this.noteWave(track.id, reaction);
void this.refillWave(true);
}
if (reaction === 'dislike' && this.state.track?.id === track.id) this.next();
}
// --- «Моя волна» ---
async startWave(activity: string | null, mood: string | null) {
if (!this.session) return;
await this.setup();
this.leaveWave();
let res;
try {
res = unwrap(await this.session.client.POST('/api/v1/wave/sessions', { body: { activity, mood } }));
} catch (e) {
// Нет связи с сервером — офлайн-волна из скачанного.
const local = offlineWave(downloads.downloaded());
if (!local.length) throw e;
return this.playList(local, 0, { type: 'collection', id: 'downloads' });
}
const tracks = res.tracks.filter(playable);
if (!tracks.length) return;
this.finishAttempt(this.lastPositionMs / 1000);
this.update({
queue: tracks, index: 0, track: tracks[0] ?? null, context: { type: 'wave', id: res.session_id },
wave: { sessionId: res.session_id, activity: res.activity, mood: res.mood, fallback: res.fallback },
});
await TrackPlayer.reset();
await TrackPlayer.add(await this.toRntp(tracks));
await TrackPlayer.play();
}
async setWaveContext(activity: string | null, mood: string | null) {
const wave = this.state.wave;
if (!wave || !this.session) return this.startWave(activity, mood);
const res = unwrap(
await this.session.client.PATCH('/api/v1/wave/sessions/{id}', {
params: { path: { id: wave.sessionId } },
body: { activity, mood },
}),
);
await this.replaceUpcoming(res.tracks);
this.update({ wave: { ...wave, activity: res.activity, mood: res.mood, fallback: res.fallback } });
// Новый контекст звучит сразу; прерванный трек — не скип для волны (как в вебе).
if (res.tracks.some(playable)) {
this.neutralSwitch = true;
await TrackPlayer.skipToNext().catch(() => {
this.neutralSwitch = false;
});
}
}
private leaveWave() {
const wave = this.state.wave;
if (!wave) return;
this.waveFeedback = [];
this.update({ wave: null });
void this.session?.client
.DELETE('/api/v1/wave/sessions/{id}', { params: { path: { id: wave.sessionId } } })
.catch(() => undefined);
}
private noteWave(trackId: string, outcome: WaveOutcome) {
if (this.state.wave) this.waveFeedback.push({ track_id: trackId, outcome });
}
/** Убрать не начатые треки и поставить новые (после реакции или смены контекста). */
private async replaceUpcoming(tracks: Track[]) {
const keep = this.state.queue.slice(0, this.state.index + 1);
await TrackPlayer.removeUpcomingTracks();
const add = tracks.filter(playable);
await TrackPlayer.add(await this.toRntp(add));
this.update({ queue: [...keep, ...add] });
}
private async refillWave(refresh = false) {
const wave = this.state.wave;
if (!wave || !this.session || this.waveLoading) return;
const remaining = this.state.queue.length - this.state.index - 1;
if (!refresh && remaining > WAVE_REFILL_AT) return;
this.waveLoading = true;
const feedback = this.waveFeedback;
this.waveFeedback = [];
try {
const res = unwrap(
await this.session.client.POST('/api/v1/wave/sessions/{id}/next', {
params: { path: { id: wave.sessionId } },
body: { feedback },
}),
);
if (this.state.wave?.sessionId !== wave.sessionId) return;
if (refresh) await this.replaceUpcoming(res.tracks);
else {
const add = res.tracks.filter(playable);
await TrackPlayer.add(await this.toRntp(add));
this.update({ queue: [...this.state.queue, ...add] });
}
this.update({ wave: { ...wave, fallback: res.fallback } });
} catch {
this.waveFeedback = [...feedback, ...this.waveFeedback];
} finally {
this.waveLoading = false;
}
}
// --- состояние ---
private save() {
const t = this.state.track;
if (!t || !this.session) return;
this.lastSave = Date.now();
void this.session.client
.PUT('/api/v1/me/playback-state', {
body: {
track_id: t.id,
position_ms: this.lastPositionMs,
queue: this.state.queue.slice(0, 500).map((x) => x.id),
queue_index: Math.min(this.state.index, 499),
context: this.state.context ? { type: this.state.context.type, id: this.state.context.id } : undefined,
device_id: 'android',
},
})
.catch(() => undefined);
}
/** Восстановить последний трек и позицию (на паузе, без автозапуска). */
async restore() {
if (!this.session || this.state.track) return;
await this.setup();
try {
const st = unwrap(await this.session.client.GET('/api/v1/me/playback-state'));
if (!st.track_id || !st.queue.length) return;
const res = unwrap(await this.session.client.POST('/api/v1/tracks/batch', { body: { ids: st.queue } }));
const tracks = res.items.filter(playable);
const idx = Math.max(tracks.findIndex((t) => t.id === st.track_id), 0);
if (!tracks.length) return;
this.update({ queue: tracks, index: idx, track: tracks[idx] ?? null, context: (st.context as PlayContext | null) ?? null });
await TrackPlayer.reset();
await TrackPlayer.add(await this.toRntp(tracks));
await TrackPlayer.skip(idx, tracks[idx]?.id === st.track_id ? st.position_ms / 1000 : 0);
} catch {
// офлайн или нет сохранённого состояния
}
}
async reset() {
this.attempt = null;
this.update({ queue: [], track: null, index: 0, playing: false, positionMs: 0, wave: null, context: null });
if (this.setupDone) await TrackPlayer.reset().catch(() => undefined);
}
flush() {
this.save();
void this.events?.flush();
}
}
export const player = new Controller();
+9
View File
@@ -0,0 +1,9 @@
import { uuidv7 } from '@pipu/core';
/** Hermes has no Web Crypto. Expo's installed native runtime supplies secure UUID randomness. */
export function eventId(now: number): string {
return uuidv7(now, () => {
const hex = globalThis.expo.uuidv4().replace(/-/g, '');
return Uint8Array.from(hex.match(/../g)!, (byte) => parseInt(byte, 16));
});
}
+9
View File
@@ -0,0 +1,9 @@
import { useSyncExternalStore } from 'react';
import { player, type PlayerState } from './controller';
export function usePlayerState(): PlayerState {
return useSyncExternalStore(player.subscribe, player.getState);
}
export { player };
+10
View File
@@ -0,0 +1,10 @@
import type { Track } from '@pipu/core';
/** Офлайн-волна: скачанные треки без дизлайков, лайкнутые чаще оказываются ближе к началу. */
export function offlineWave(tracks: Track[], random: () => number = Math.random): Track[] {
return tracks
.filter((t) => t.reaction !== 'dislike')
.map((t) => ({ t, key: random() * (t.reaction === 'like' ? 0.5 : 1) }))
.sort((a, b) => a.key - b.key)
.map((x) => x.t);
}
+21
View File
@@ -0,0 +1,21 @@
import TrackPlayer, { Event } from 'react-native-track-player';
import { player } from './controller';
/**
* Фоновый сервис: кнопки уведомления, экрана блокировки и гарнитуры. Работает и без UI —
* команды уходят прямо в ExoPlayer, а учёт прослушиваний ведёт тот же контроллер.
*/
export async function PlaybackService(): Promise<void> {
TrackPlayer.addEventListener(Event.RemotePlay, () => void TrackPlayer.play());
TrackPlayer.addEventListener(Event.RemotePause, () => void TrackPlayer.pause());
TrackPlayer.addEventListener(Event.RemoteStop, () => void TrackPlayer.stop());
TrackPlayer.addEventListener(Event.RemoteNext, () => player.next());
TrackPlayer.addEventListener(Event.RemotePrevious, () => void player.prev());
TrackPlayer.addEventListener(Event.RemoteSeek, ({ position }) => player.seek(position * 1000));
// Звонок / голосовой ассистент: приостанавливаем и продолжаем сами (autoHandleInterruptions — для фокуса).
TrackPlayer.addEventListener(Event.RemoteDuck, ({ paused, permanent }) => {
if (permanent) void TrackPlayer.pause();
else if (paused) void TrackPlayer.pause();
});
}
+17 -3
View File
@@ -1,5 +1,19 @@
import { tokens } from '@pipu/design-tokens'; import { tokens, type ThemeName } from '@pipu/design-tokens';
import { createContext, useContext } from 'react';
// Пока только тёмная тема; переключение тем — вместе с профилем (M5). export type Colors = Record<keyof typeof tokens.color.dark, string>;
export const colors = tokens.color.dark;
/** Активная тема (dark / light); выбирается в профиле (`ui_prefs.theme`, «system» — по настройке телефона). */
export const ThemeContext = createContext<ThemeName>('dark');
export function useThemeName(): ThemeName {
return useContext(ThemeContext);
}
export function useColors(): Colors {
return tokens.color[useThemeName()];
}
/** Цвета до входа и загрузки настроек (сплэш) — тёмная тема. */
export const darkColors: Colors = tokens.color.dark;
export const radius = tokens.radius; export const radius = tokens.radius;
+127
View File
@@ -0,0 +1,127 @@
import { useEffect, useSyncExternalStore } from 'react';
import { useTranslation } from 'react-i18next';
import { AppState, Modal, Pressable, ScrollView, Text, View } from 'react-native';
import { useSession, useSessionCtx } from '../lib/session';
import { updater } from '../lib/update';
import { radius, useColors } from '../theme';
import { Button } from './kit';
export function useUpdateState() {
return useSyncExternalStore(updater.subscribe, () => updater.state);
}
/** Проверяет обновления при запуске и возврате в приложение; показывает диалог с «Что нового». */
export function UpdateDialog() {
const colors = useColors();
const { t } = useTranslation();
const session = useSession();
const { server } = useSessionCtx();
const st = useUpdateState();
useEffect(() => {
void updater.check(session);
const sub = AppState.addEventListener('change', (s) => {
if (s === 'active') void updater.check(session);
});
return () => sub.remove();
}, [session]);
if (st.status === 'idle' || st.status === 'checking' || st.status === 'latest') return null;
if (st.status === 'available' && st.dismissed) return null;
const { release, required } = st;
const busy = st.status === 'downloading' || st.status === 'verifying';
const action = () => void updater.downloadAndInstall(session, server ?? '');
return (
<Modal transparent animationType="fade" visible onRequestClose={() => updater.dismiss()}>
<View
style={{
flex: 1,
backgroundColor: 'rgba(0,0,0,0.6)',
justifyContent: 'center',
padding: 24,
}}
>
<View
style={{
backgroundColor: colors.surface,
borderRadius: radius.lg,
padding: 20,
gap: 12,
maxHeight: '80%',
}}
>
<Text style={{ color: colors.text, fontSize: 18, fontWeight: '700' }}>
{t('mobile.update_title', { version: release.version })}
</Text>
{required && <Text style={{ color: colors.danger }}>{t('mobile.update_required')}</Text>}
{release.notes_md.trim() !== '' && (
<ScrollView style={{ maxHeight: 240 }}>
<Text style={{ color: colors.text2, lineHeight: 20 }}>{plainNotes(release.notes_md)}</Text>
</ScrollView>
)}
<Text style={{ color: colors.text3, fontSize: 12 }}>
{t('mobile.update_size', {
size: (release.size / 1048576).toFixed(1),
})}
</Text>
{st.status === 'downloading' && (
<View style={{ gap: 6 }}>
<View
style={{
height: 4,
borderRadius: 2,
backgroundColor: colors.surface3,
}}
>
<View
style={{
height: 4,
borderRadius: 2,
width: `${Math.round(st.progress * 100)}%`,
backgroundColor: colors.accent2,
}}
/>
</View>
<Text style={{ color: colors.text2, fontSize: 12 }}>
{t('mobile.update_downloading', {
percent: Math.round(st.progress * 100),
})}
</Text>
</View>
)}
{st.status === 'verifying' && <Text style={{ color: colors.text2, fontSize: 12 }}>{t('mobile.update_verifying')}</Text>}
{st.status === 'error' && (
<Text style={{ color: colors.danger }}>
{t(st.error === 'bad_checksum' ? 'mobile.update_bad_checksum' : 'mobile.update_failed')}
</Text>
)}
{st.status === 'ready' && (
<View style={{ gap: 4 }}>
<Text style={{ color: colors.text2, fontSize: 12 }}>{t('mobile.update_allow')}</Text>
<Pressable onPress={() => void updater.openInstallSettings()} accessibilityRole="link">
<Text style={{ color: colors.accent2, fontWeight: '500' }}>{t('mobile.update_open_settings')}</Text>
</Pressable>
</View>
)}
<Button title={t('mobile.update_install')} icon="system-update" busy={busy} onPress={action} />
{!required && !busy && <Button title={t('mobile.update_later')} variant="ghost" onPress={() => updater.dismiss()} />}
</View>
</View>
</Modal>
);
}
/** Заметки релиза — Markdown; в диалоге показываем текстом без разметки заголовков и выделения. */
function plainNotes(md: string): string {
return md
.replace(/^#{1,6}\s*/gm, '')
.replace(/\*\*(.+?)\*\*/g, '$1')
.replace(/^\s*[-*]\s+/gm, '• ')
.replace(/\[(.+?)\]\(.+?\)/g, '$1')
.trim();
}
+44
View File
@@ -0,0 +1,44 @@
import type { Track } from '@pipu/core';
import { useSyncExternalStore } from 'react';
import { useTranslation } from 'react-i18next';
import { ActivityIndicator, Pressable } from 'react-native';
import { downloads, type DownloadItem, type DownloadsState } from '../offline/downloads';
import { useColors } from '../theme';
import { Icon } from './kit';
export function useDownloads(): DownloadsState {
return useSyncExternalStore(downloads.subscribe, () => downloads.state);
}
export function useDownloadItem(trackId: string): DownloadItem | undefined {
return useSyncExternalStore(downloads.subscribe, () => downloads.state.items.get(trackId));
}
/** Кнопка «скачать / скачано» у трека: повторное нажатие удаляет загрузку. */
export function DownloadButton({ track, size = 26 }: { track: Track; size?: number }) {
const colors = useColors();
const { t } = useTranslation();
const item = useDownloadItem(track.id);
const busy = item?.status === 'queued' || item?.status === 'downloading';
const onPress = () => void (item ? downloads.remove([track.id]) : downloads.enqueue([track]));
return (
<Pressable
onPress={onPress}
hitSlop={10}
disabled={!track.available}
accessibilityRole="button"
accessibilityLabel={t(item ? 'mobile.dl_remove' : 'mobile.dl_download')}
>
{busy ? (
<ActivityIndicator size="small" color={colors.accent2} />
) : (
<Icon
name={item?.status === 'done' ? 'download-done' : item?.status === 'error' ? 'error-outline' : 'download'}
size={size}
color={item?.status === 'done' ? colors.accent2 : item?.status === 'error' ? colors.danger : colors.text2}
/>
)}
</Pressable>
);
}
+336
View File
@@ -0,0 +1,336 @@
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { useRouter } from 'expo-router';
import { ApiError, type Track } from '@pipu/core';
import type { ComponentProps, ReactNode } from 'react';
import { useState, useSyncExternalStore } from 'react';
import { useTranslation } from 'react-i18next';
import {
ActivityIndicator,
Image,
Modal,
Pressable,
StyleSheet,
Text,
TextInput,
View,
type StyleProp,
type TextInputProps,
type ViewStyle,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useSessionCtx } from '../lib/session';
import { downloads } from '../offline/downloads';
import { absolute } from '../player/controller';
import { radius, useColors, type Colors } from '../theme';
export type IconName = ComponentProps<typeof MaterialIcons>['name'];
export function Icon({ name, size = 22, color }: { name: IconName; size?: number; color?: string }) {
const colors = useColors();
return <MaterialIcons name={name} size={size} color={color ?? colors.text2} />;
}
export function Screen({ children, scroll = false, style }: { children: ReactNode; scroll?: boolean; style?: StyleProp<ViewStyle> }) {
const s = useStyles();
void scroll;
return (
<SafeAreaView style={[s.screen, style]} edges={['top', 'left', 'right']}>
{children}
</SafeAreaView>
);
}
export function H1({ children }: { children: ReactNode }) {
const s = useStyles();
return <Text style={s.h1}>{children}</Text>;
}
export function Muted({ children, style }: { children: ReactNode; style?: StyleProp<ViewStyle> }) {
const s = useStyles();
return <Text style={[s.muted, style as object]}>{children}</Text>;
}
export function Field({
label,
error,
hint,
secure,
...rest
}: TextInputProps & { label: string; error?: string; hint?: string; secure?: boolean }) {
const s = useStyles();
const colors = useColors();
const { t } = useTranslation();
const [shown, setShown] = useState(false);
return (
<View style={{ gap: 6 }}>
<Text style={s.label}>{label}</Text>
<View>
<TextInput
placeholderTextColor={colors.text3}
autoCapitalize="none"
autoCorrect={false}
secureTextEntry={secure && !shown}
accessibilityLabel={label}
style={[s.input, error ? { borderColor: colors.danger } : null, secure ? { paddingRight: 48 } : null]}
{...rest}
/>
{secure && (
<Pressable
onPress={() => setShown((v) => !v)}
style={s.reveal}
accessibilityRole="button"
accessibilityLabel={shown ? t('form.hide_password') : t('form.show_password')}
>
<Icon name={shown ? 'visibility-off' : 'visibility'} size={20} color={colors.text3} />
</Pressable>
)}
</View>
{(error ?? hint) && <Text style={{ color: error ? colors.danger : colors.text3, fontSize: 12 }}>{error ?? hint}</Text>}
</View>
);
}
export function Button({
title,
onPress,
variant = 'primary',
busy,
disabled,
icon,
}: {
title: string;
onPress: () => void;
variant?: 'primary' | 'secondary' | 'ghost' | 'danger';
busy?: boolean;
disabled?: boolean;
icon?: IconName;
}) {
const s = useStyles();
const colors = useColors();
const bg = { primary: colors['accent-fill'], secondary: colors.surface3, ghost: 'transparent', danger: colors['danger-soft'] }[variant];
const fg = { primary: '#fff', secondary: colors.text, ghost: colors.text2, danger: colors.danger }[variant];
return (
<Pressable
onPress={onPress}
disabled={disabled || busy}
accessibilityRole="button"
accessibilityState={{ disabled: disabled || busy, busy }}
style={({ pressed }) => [s.button, { backgroundColor: bg, opacity: disabled ? 0.5 : pressed ? 0.75 : 1 }]}
>
{busy ? <ActivityIndicator color={fg} /> : icon ? <Icon name={icon} size={20} color={fg} /> : null}
<Text style={{ color: fg, fontWeight: '600', fontSize: 15 }}>{title}</Text>
</Pressable>
);
}
export function ErrorBox({ children }: { children?: ReactNode }) {
const s = useStyles();
const colors = useColors();
if (!children) return null;
return (
<View style={s.error} accessibilityRole="alert">
<Text style={{ color: colors.danger, fontWeight: '500' }}>{children}</Text>
</View>
);
}
/** Текст ошибки API: перевод errors:<code>. */
export function useErrorText(): (err: unknown) => string {
const { t, i18n } = useTranslation();
const tr = t as unknown as (k: string, o?: Record<string, unknown>) => string;
return (err) => {
const code = err instanceof ApiError ? err.code : 'common.internal';
const key = `errors:${code}`;
return i18n.exists(key) ? tr(key, err instanceof ApiError ? err.params : {}) : tr('errors:common.internal');
};
}
export function Cover({
album,
size,
round,
}: {
album: { id: string; cover_url?: string | null; cover_colors?: string[] };
size: number;
round?: boolean;
}) {
const colors = useColors();
const { server } = useSessionCtx();
const remote = server ? absolute(server, album.cover_url) : undefined;
const px = size * 2 <= 64 ? 64 : size * 2 <= 300 ? 300 : 1200;
// У скачанных альбомов обложка 300 px лежит на устройстве — работает и без сети.
const local = useSyncExternalStore(downloads.subscribe, () => (px <= 300 ? downloads.localAlbumCover(album.id) : undefined));
const uri = local ?? (remote ? `${remote}&size=${px}` : undefined);
const bg = album.cover_colors?.[0] ?? colors.surface3;
return (
<View style={{ width: size, height: size, borderRadius: round ? size / 2 : 8, backgroundColor: bg, overflow: 'hidden', alignItems: 'center', justifyContent: 'center' }}>
{uri ? (
<Image source={{ uri }} style={{ width: size, height: size }} />
) : (
<Icon name={round ? 'person' : 'album'} size={size * 0.45} color="rgba(255,255,255,0.8)" />
)}
</View>
);
}
export function formatDuration(ms: number): string {
const sec = Math.max(0, Math.round(ms / 1000));
return `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, '0')}`;
}
export function TrackRow({
track,
current,
onPress,
onLike,
numbered,
meta,
trailing,
}: {
track: Track;
current?: boolean;
onPress: () => void;
onLike?: () => void;
numbered?: number;
meta?: string;
trailing?: ReactNode;
}) {
const s = useStyles();
const colors = useColors();
const { t } = useTranslation();
const liked = track.reaction === 'like';
const router = useRouter();
const saved = useSyncExternalStore(downloads.subscribe, () => downloads.isDownloaded(track.id));
return (
<Pressable
onPress={onPress}
disabled={!track.available}
accessibilityRole="button"
accessibilityLabel={`${track.title}, ${track.artists.map((a) => a.name).join(', ')}`}
style={({ pressed }) => [s.row, current && { backgroundColor: colors['accent-soft'] }, pressed && { backgroundColor: colors.hover }, !track.available && { opacity: 0.4 }]}
>
{numbered !== undefined ? (
<Text style={s.num}>{numbered}</Text>
) : (
<Cover album={track.album} size={44} />
)}
<View style={{ flex: 1, minWidth: 0 }}>
<Text numberOfLines={1} style={[s.rowTitle, current && { color: colors.accent2 }]}>
{track.title}
</Text>
<Text numberOfLines={1} style={s.rowSub}>
{track.artists.map((a) => a.name).join(', ')}
{meta ? ` · ${meta}` : ''}
</Text>
</View>
{onLike && (
<Pressable
onPress={onLike}
hitSlop={10}
accessibilityRole="button"
accessibilityLabel={t(liked ? 'player.unlike' : 'player.like')}
>
<Icon name={liked ? 'favorite' : 'favorite-border'} size={20} color={liked ? colors.accent2 : colors.text3} />
</Pressable>
)}
{trailing}
<Pressable accessibilityRole="button" accessibilityLabel={t('playlists.add')} style={{ padding: 8 }}
onPress={(e) => { e.stopPropagation(); router.push({ pathname: '/playlists', params: { track: track.id } }); }}>
<Icon name="playlist-add" size={22} />
</Pressable>
{saved && !trailing && <Icon name="download-done" size={16} color={colors.accent2} />}
<Text style={s.duration}>{formatDuration(track.duration_ms)}</Text>
</Pressable>
);
}
/** Нижний лист: затемнение, заголовок, содержимое; закрывается кнопкой «назад» и тапом по фону. */
export function Sheet({ visible, title, onClose, children }: { visible: boolean; title: string; onClose: () => void; children: ReactNode }) {
const colors = useColors();
const { t } = useTranslation();
return (
<Modal transparent animationType="slide" visible={visible} onRequestClose={onClose}>
<Pressable style={{ flex: 1, backgroundColor: colors.overlay }} onPress={onClose} accessibilityLabel={title} />
<SafeAreaView edges={['bottom']} style={{ backgroundColor: colors.surface, borderTopLeftRadius: radius.lg, borderTopRightRadius: radius.lg }}>
<View style={{ padding: 20, gap: 16 }}>
<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
<Text style={{ color: colors.text, fontSize: 18, fontWeight: '700' }} accessibilityRole="header">
{title}
</Text>
<Pressable onPress={onClose} hitSlop={10} accessibilityRole="button" accessibilityLabel={t('form.close')}>
<Icon name="close" color={colors.text2} />
</Pressable>
</View>
{children}
</View>
</SafeAreaView>
</Modal>
);
}
export function Segmented<T extends string>({
value,
options,
onChange,
}: {
value: T;
options: { value: T; label: string }[];
onChange: (v: T) => void;
}) {
const s = useStyles();
const colors = useColors();
return (
<View style={s.segmented} accessibilityRole="tablist">
{options.map((o) => (
<Pressable
key={o.value}
onPress={() => onChange(o.value)}
accessibilityRole="tab"
accessibilityState={{ selected: value === o.value }}
style={[s.segment, value === o.value && { backgroundColor: colors['accent-fill'] }]}
>
<Text style={{ color: value === o.value ? '#fff' : colors.text2, fontWeight: '600', fontSize: 13 }}>{o.label}</Text>
</Pressable>
))}
</View>
);
}
const styles = new Map<Colors, ReturnType<typeof makeStyles>>();
/** Стили кита под активную тему (создаются один раз на тему). */
function useStyles() {
const colors = useColors();
let st = styles.get(colors);
if (!st) styles.set(colors, (st = makeStyles(colors)));
return st;
}
const makeStyles = (colors: Colors) =>
StyleSheet.create({
screen: { flex: 1, backgroundColor: colors.bg },
h1: { color: colors.text, fontSize: 26, fontWeight: '700', letterSpacing: -0.3 },
muted: { color: colors.text2, lineHeight: 21 },
label: { color: colors.text2, fontSize: 13, fontWeight: '600' },
input: {
height: 48,
paddingHorizontal: 14,
borderRadius: radius.md,
backgroundColor: colors.surface2,
borderWidth: 1,
borderColor: colors.line2,
color: colors.text,
fontSize: 15,
},
reveal: { position: 'absolute', right: 6, top: 6, width: 36, height: 36, alignItems: 'center', justifyContent: 'center' },
button: { height: 48, borderRadius: radius.md, flexDirection: 'row', gap: 8, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 18 },
error: { padding: 12, borderRadius: 10, backgroundColor: colors['danger-soft'] },
row: { flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 16, paddingVertical: 8, minHeight: 60 },
num: { width: 44, textAlign: 'center', color: colors.text3, fontVariant: ['tabular-nums'] },
rowTitle: { color: colors.text, fontSize: 15, fontWeight: '500' },
rowSub: { color: colors.text2, fontSize: 13, marginTop: 2 },
duration: { color: colors.text3, fontSize: 12, fontVariant: ['tabular-nums'] },
segmented: { flexDirection: 'row', gap: 2, padding: 3, borderRadius: 10, backgroundColor: colors.surface2, alignSelf: 'flex-start' },
segment: { paddingHorizontal: 14, height: 32, borderRadius: 8, alignItems: 'center', justifyContent: 'center' },
});
+110
View File
@@ -0,0 +1,110 @@
import { ApiError, unwrap } from '@pipu/core';
import { useState, useSyncExternalStore } from 'react';
import { useTranslation } from 'react-i18next';
import { Text, View } from 'react-native';
import { QUALITIES, qualityPrefs, type Quality, type QualityPrefs } from '../lib/prefs';
import { useSession } from '../lib/session';
import { useColors } from '../theme';
import { Button, ErrorBox, Field, Segmented, Sheet, useErrorText } from './kit';
export function useQualityPrefs(): QualityPrefs {
return useSyncExternalStore(qualityPrefs.subscribe, qualityPrefs.get);
}
/** Лист «Качество звука»: Wi-Fi / сотовая / загрузки. */
export function QualitySheet({ visible, onClose }: { visible: boolean; onClose: () => void }) {
const { t } = useTranslation();
const colors = useColors();
const prefs = useQualityPrefs();
const row = (key: keyof QualityPrefs) => (
<View style={{ gap: 8 }}>
<Text style={{ color: colors.text2, fontSize: 13, fontWeight: '600' }}>{t(`mobile.quality_${key}`)}</Text>
<Segmented<Quality>
value={prefs[key]}
options={QUALITIES.map((q) => ({ value: q, label: t(`mobile.q_${q}`) }))}
onChange={(q) => void qualityPrefs.set({ [key]: q })}
/>
</View>
);
return (
<Sheet visible={visible} title={t('mobile.quality')} onClose={onClose}>
{row('wifi')}
{row('cellular')}
{row('download')}
<Text style={{ color: colors.text3, fontSize: 12 }}>{t('mobile.quality_hint')}</Text>
</Sheet>
);
}
/** Лист смены пароля: после смены сервер выдаёт новую пару токенов, остальные сессии завершаются. */
export function PasswordSheet({ visible, onClose }: { visible: boolean; onClose: () => void }) {
const { t } = useTranslation();
const colors = useColors();
const session = useSession();
const errorText = useErrorText();
const [current, setCurrent] = useState('');
const [next, setNext] = useState('');
const [repeat, setRepeat] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<unknown>(null);
const [done, setDone] = useState(false);
const mismatch = repeat !== '' && repeat !== next;
const fieldErr = (f: string) => (error instanceof ApiError && error.fieldCode(f) ? errorText(error) : undefined);
const close = () => {
setCurrent('');
setNext('');
setRepeat('');
setError(null);
setDone(false);
onClose();
};
const submit = async () => {
setBusy(true);
setError(null);
try {
const tokens = unwrap(await session.client.POST('/api/v1/me/password', { body: { current_password: current, new_password: next } }));
await session.apply(tokens);
setDone(true);
setCurrent('');
setNext('');
setRepeat('');
} catch (e) {
setError(e);
} finally {
setBusy(false);
}
};
return (
<Sheet visible={visible} title={t('settings.password')} onClose={close}>
{done ? (
<>
<Text style={{ color: colors.ok }}>{t('settings.password_changed')}</Text>
<Button title={t('form.close')} onPress={close} />
</>
) : (
<>
<Field label={t('settings.current_password')} value={current} onChangeText={setCurrent} secure autoComplete="current-password" error={fieldErr('current_password')} />
<Field label={t('settings.new_password')} value={next} onChangeText={setNext} secure autoComplete="new-password" error={fieldErr('new_password')} />
<Field
label={t('settings.repeat_password')}
value={repeat}
onChangeText={setRepeat}
secure
autoComplete="new-password"
error={mismatch ? t('form.passwords_mismatch') : undefined}
/>
<ErrorBox>{error && !fieldErr('current_password') && !fieldErr('new_password') ? errorText(error) : null}</ErrorBox>
<Button
title={t('settings.change_password')}
busy={busy}
disabled={!current || !next || mismatch || repeat === ''}
onPress={() => void submit()}
/>
</>
)}
</Sheet>
);
}
+110
View File
@@ -0,0 +1,110 @@
import { initialWaveState, step, WAVE_COLORS, waveScale, type WaveState } from '@pipu/core';
import { Canvas, createPicture, Picture } from '@shopify/react-native-skia';
import { useFocusEffect } from 'expo-router';
import { useCallback, useEffect, useState, type ReactNode } from 'react';
import { AppState, Pressable, View } from 'react-native';
import Animated, { useAnimatedStyle, useDerivedValue, useFrameCallback, useReducedMotion, useSharedValue } from 'react-native-reanimated';
import { useThemeName } from '../../theme';
import { drawLiquid, drawOrb } from './draw';
export interface WaveOrbProps {
variant: 'orb' | 'liquid';
playing: boolean;
bpm?: number;
energy?: number;
colors?: readonly string[];
size: number;
label?: string;
onPress?: () => void;
children?: ReactNode;
}
/**
* «Моя волна» на Skia (docs/design.md#3): в покое «дышит», при игре пульсирует в такт BPM с силой от energy,
* при нажатии сжимается с отскоком. Кадры считаются в UI-потоке; вне экрана и в фоне анимация стоит.
* Без `onPress` — декоративная визуализация (полноэкранный плеер в виде «волна»).
*/
export function WaveOrb({ variant, playing, bpm = 100, energy = 0.6, colors, size, label, onPress, children }: WaveOrbProps) {
const dark = useThemeName() === 'dark';
const reduced = useReducedMotion();
const [focused, setFocused] = useState(true);
useFocusEffect(
useCallback(() => {
setFocused(true);
return () => setFocused(false);
}, []),
);
const [foreground, setForeground] = useState(AppState.currentState === 'active');
const palette = (colors?.length === 3 ? colors : WAVE_COLORS) as [string, string, string];
const props = useSharedValue({ variant, playing, bpm, energy, colors: palette, dark, reduced });
const state = useSharedValue<WaveState>(initialWaveState(size));
const pressT = useSharedValue(0);
// Новый объект на каждом кадре — пересчёт картинки (одно и то же число могло бы не вызвать его).
const time = useSharedValue({ ts: 0, dt: 0 });
useEffect(() => {
props.value = { variant, playing, bpm, energy, colors: palette, dark, reduced };
}, [variant, playing, bpm, energy, palette[0], palette[1], palette[2], dark, reduced]);
useEffect(() => {
const sub = AppState.addEventListener('change', (st) => setForeground(st === 'active'));
return () => sub.remove();
}, []);
const frame = useFrameCallback((info) => {
time.value = { ts: info.timestamp, dt: Math.min(0.05, (info.timeSincePreviousFrame ?? 16) / 1000) };
}, false);
useEffect(() => {
frame.setActive(focused && foreground);
}, [focused, foreground]);
const S = size * 1.6;
const picture = useDerivedValue(() => {
const dt = time.value.dt;
const s = state.value;
Object.assign(s, props.value);
s.size = size;
if (pressT.value === 0 && s.pressT === 1) s.pressV -= 0.12; // отпустили — отскок
s.pressT = pressT.value;
step(s, dt);
const r = size * 0.5 * waveScale(s);
return createPicture(
(canvas) => {
if (s.variant === 'liquid') drawLiquid(canvas, S / 2, S / 2, r, s);
else drawOrb(canvas, S / 2, S / 2, r, s);
},
{ width: S, height: S },
);
});
const labelStyle = useAnimatedStyle(() => {
void time.value.ts; // пересчёт на каждом кадре
const s = state.value;
return { transform: [{ scale: waveScale(s) + s.pulse * 0.03 }] };
});
const body = (
<View style={{ width: size, height: size, alignItems: 'center', justifyContent: 'center' }}>
<Canvas style={{ position: 'absolute', width: S, height: S, left: (size - S) / 2, top: (size - S) / 2 }} pointerEvents="none">
<Picture picture={picture} />
</Canvas>
<Animated.View style={[{ alignItems: 'center', justifyContent: 'center', gap: 4 }, labelStyle]} pointerEvents="none">
{children}
</Animated.View>
</View>
);
if (!onPress) return <View accessibilityElementsHidden importantForAccessibility="no-hide-descendants">{body}</View>;
return (
<Pressable
onPress={onPress}
onPressIn={() => (pressT.value = 1)}
onPressOut={() => (pressT.value = 0)}
accessibilityRole="button"
accessibilityLabel={label}
accessibilityState={{ selected: playing }}
>
{body}
</Pressable>
);
}
+129
View File
@@ -0,0 +1,129 @@
// Отрисовка «Моей волны» на Skia — тот же алгоритм, что Canvas 2D в вебе (apps/web/src/widgets/wave/draw.ts).
// Функции — worklet'ы: кадр собирается в UI-потоке Reanimated, JS-поток не участвует.
import { mix, rgb, rgba, type Rgb, type WaveState } from '@pipu/core';
import { BlendMode, ClipOp, PaintStyle, Skia, TileMode, type SkCanvas, type SkPaint } from '@shopify/react-native-skia';
function radial(cx: number, cy: number, r0: number, r1: number, colors: string[], pos: number[]): SkPaint {
'worklet';
const p = Skia.Paint();
p.setAntiAlias(true);
p.setShader(
Skia.Shader.MakeTwoPointConicalGradient(
{ x: cx, y: cy },
r0,
{ x: cx, y: cy },
r1,
colors.map((c) => Skia.Color(c)),
pos,
TileMode.Clamp,
),
);
return p;
}
/** Градиент со смещённым центром (аналог createRadialGradient(x0, y0, 0, x1, y1, r)). */
function conical(x0: number, y0: number, x1: number, y1: number, r: number, colors: string[]): SkPaint {
'worklet';
const p = Skia.Paint();
p.setAntiAlias(true);
p.setShader(Skia.Shader.MakeTwoPointConicalGradient({ x: x0, y: y0 }, 0, { x: x1, y: y1 }, r, colors.map((c) => Skia.Color(c)), [0, 1], TileMode.Clamp));
return p;
}
export function drawOrb(canvas: SkCanvas, cx: number, cy: number, r: number, s: WaveState) {
'worklet';
const t = s.t;
const c1 = rgb(s.colors[0]);
const c2 = rgb(s.colors[1]);
const c3 = rgb(s.colors[2]);
canvas.drawCircle(
cx,
cy,
r * 1.65,
radial(cx, cy, r * 0.6, r * 1.65, [rgba(c1, 0.32 + s.pulse * 0.35 + s.hover * 0.12), rgba(c2, 0.1 + s.pulse * 0.12), rgba(c1, 0)], [0, 0.5, 1]),
);
canvas.save();
const clip = Skia.Path.Make();
clip.addCircle(cx, cy, r);
canvas.clipPath(clip, ClipOp.Intersect, true);
const bg = Skia.Paint();
bg.setColor(Skia.Color(s.dark ? '#060B1C' : '#0B1533'));
const box = Skia.XYWHRect(cx - r, cy - r, r * 2, r * 2);
canvas.drawRect(box, bg);
const blobs: Rgb[] = [c1, c2, c3, c1, c2];
for (let i = 0; i < blobs.length; i++) {
const c = blobs[i]!;
const a = t * (0.25 + i * 0.07) + i * 1.7;
const bx = cx + Math.cos(a) * r * (0.35 + 0.12 * Math.sin(t * 0.3 + i)) + s.mx * r * 0.18 * s.hover;
const by = cy + Math.sin(a * 1.3) * r * 0.38 + s.my * r * 0.18 * s.hover;
const br = r * (0.75 + 0.15 * Math.sin(t * 0.7 + i) + s.pulse * 0.2);
const g = radial(bx, by, 0, br, [rgba(c, 0.55), rgba(c, 0)], [0, 1]);
g.setBlendMode(BlendMode.Plus);
canvas.drawRect(box, g);
}
const lines = 9;
for (let l = 0; l < lines; l++) {
const yy = cy - r * 0.75 + (l / (lines - 1)) * r * 1.5;
const amp = r * (0.03 + 0.05 * s.amp + 0.09 * s.pulse + 0.03 * s.hover);
const path = Skia.Path.Make();
for (let x = -r; x <= r; x += 4) {
const y = yy + Math.sin((x / r) * (3 + l * 0.4) + t * (1.2 + l * 0.15) + l) * amp * Math.cos((x / r) * 1.4);
if (x === -r) path.moveTo(cx + x, y);
else path.lineTo(cx + x, y);
}
const stroke = Skia.Paint();
stroke.setAntiAlias(true);
stroke.setStyle(PaintStyle.Stroke);
stroke.setStrokeWidth(1.5);
stroke.setColor(Skia.Color(`rgba(255,255,255,${0.05 + 0.05 * s.amp + (l % 3 === 0 ? 0.05 : 0)})`));
stroke.setBlendMode(BlendMode.Plus);
canvas.drawPath(path, stroke);
}
canvas.drawRect(box, conical(cx - r * 0.35, cy - r * 0.45, cx - r * 0.35, cy - r * 0.45, r * 0.9, ['rgba(255,255,255,0.18)', 'rgba(255,255,255,0)']));
canvas.restore();
const ring = Skia.Paint();
ring.setAntiAlias(true);
ring.setStyle(PaintStyle.Stroke);
ring.setStrokeWidth(1);
ring.setColor(Skia.Color(rgba(mix(c1, [255, 255, 255], 0.4), 0.35 + s.pulse * 0.3)));
canvas.drawCircle(cx, cy, r - 0.5, ring);
}
export function drawLiquid(canvas: SkCanvas, cx: number, cy: number, r: number, s: WaveState) {
'worklet';
const t = s.t;
const cols: Rgb[] = [rgb(s.colors[0]), rgb(s.colors[1]), rgb(s.colors[2])];
canvas.drawCircle(cx, cy, r * 1.6, radial(cx, cy, r * 0.4, r * 1.6, [rgba(cols[0]!, 0.3 + s.pulse * 0.3), rgba(cols[0]!, 0)], [0, 1]));
for (let L = 0; L < 3; L++) {
const path = Skia.Path.Make();
const P = 140;
for (let j = 0; j <= P; j++) {
const th = (j / P) * Math.PI * 2;
const w =
1 +
0.06 * Math.sin(3 * th + t * (0.9 + L * 0.2) + L * 2) +
0.04 * Math.sin(5 * th - t * (1.3 + L * 0.1) + L) +
0.03 * Math.sin(7 * th + t * 1.7) * (0.5 + s.amp) +
0.08 * s.pulse * Math.sin(2 * th + L) +
0.16 * s.hover * Math.pow(Math.max(0, Math.cos(th - s.ang)), 3);
const rr = r * (0.86 - L * 0.07) * w;
const x = cx + Math.cos(th) * rr;
const y = cy + Math.sin(th) * rr;
if (j) path.lineTo(x, y);
else path.moveTo(x, y);
}
path.close();
const ox = Math.cos(t * 0.4 + L * 2) * r * 0.3;
const oy = Math.sin(t * 0.5 + L) * r * 0.3;
const c = cols[L]!;
const g = conical(cx + ox, cy + oy, cx, cy, r * 1.1, [rgba(mix(c, [255, 255, 255], 0.25), 0.85), rgba(c, 0.25)]);
g.setAlphaf(s.dark ? 0.6 : 0.75);
g.setBlendMode(s.dark ? BlendMode.Plus : BlendMode.SrcOver);
canvas.drawPath(path, g);
}
}
+19
View File
@@ -0,0 +1,19 @@
import { afterEach, expect, it, vi } from 'vitest';
import { EventBuffer } from '@pipu/core';
import { eventId } from '../src/player/eventId';
afterEach(() => vi.unstubAllGlobals());
it('queues restored-track events on Hermes without Web Crypto', () => {
vi.stubGlobal('crypto', undefined);
const nativeUuid = vi.fn()
.mockReturnValueOnce('00000000-0000-4fff-bfff-ffffffffffff')
.mockReturnValueOnce('00000000-0000-4fff-bfff-fffffffffffe');
vi.stubGlobal('expo', { uuidv4: nativeUuid });
const buffer = new EventBuffer({ send: vi.fn() }, () => 0x0190_0000_0000, undefined, eventId);
buffer.push({ type: 'play_start', track_id: 'restored-track' });
buffer.push({ type: 'skip', track_id: 'restored-track' });
expect(buffer.pending[0]?.id).toBe('01900000-0000-7fff-bfff-ffffffffffff');
expect(buffer.pending[1]?.id).not.toBe(buffer.pending[0]?.id);
expect(nativeUuid).toHaveBeenCalledTimes(2);
});
+38
View File
@@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest';
import { releaseNeed } from '../src/lib/releaseNeed';
import { offlineWave } from '../src/player/offlineWave';
import type { Track } from '@pipu/core';
function track(id: string, reaction: Track['reaction']): Track {
return {
id,
title: id,
duration_ms: 1000,
artists: [],
album: { id: 'a', title: 'A', year: null, cover_url: null, cover_colors: [] },
genres: [],
disc_no: 1,
track_no: 1,
available: true,
stream_url: null,
reaction,
features: null,
};
}
describe('offline wave', () => {
it('drops dislikes and keeps likes ahead of the rest', () => {
const tracks = [track('d', 'dislike'), track('n', null), track('l', 'like')];
const order = offlineWave(tracks, () => 0.5).map((t) => t.id);
expect(order).toEqual(['l', 'n']);
});
});
describe('update dialog decision', () => {
it('marks an older install below the minimum as required', () => {
expect(releaseNeed(10, 12, 11)).toBe('required');
expect(releaseNeed(11, 12, 11)).toBe('optional');
expect(releaseNeed(12, 12, 11)).toBe('current');
});
});
+7
View File
@@ -0,0 +1,7 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: ['test/**/*.test.ts'],
},
});
+2
View File
@@ -8,6 +8,8 @@ WORKDIR /repo
# Сначала только манифесты workspace: слой с установкой зависимостей пересобирается лишь при их изменении, # Сначала только манифесты workspace: слой с установкой зависимостей пересобирается лишь при их изменении,
# а не при любой правке кода. Новый пакет в apps/ или packages/ — добавить его package.json сюда. # а не при любой правке кода. Новый пакет в apps/ или packages/ — добавить его package.json сюда.
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
# pnpm-патчи зависимостей (lockfile ссылается на них, без них --frozen-lockfile падает)
COPY patches/ patches/
COPY apps/web/package.json apps/web/ COPY apps/web/package.json apps/web/
COPY apps/mobile/package.json apps/mobile/ COPY apps/mobile/package.json apps/mobile/
COPY packages/api-client/package.json packages/api-client/ COPY packages/api-client/package.json packages/api-client/
+119
View File
@@ -0,0 +1,119 @@
import { expect, test, type Page } from '@playwright/test';
async function login(page: Page, username: string) {
await page.addInitScript(() => localStorage.setItem('pipu.locale', 'ru'));
await page.goto('/login');
await page.getByLabel('Логин', { exact: true }).fill(username);
await page.getByRole('textbox', { name: 'Пароль', exact: true }).fill(`${username}-password`);
await page.getByRole('button', { name: 'Войти', exact: true }).click();
await expect(page.getByRole('button', { name: 'Ещё', exact: true })).toBeVisible();
}
async function fits(page: Page) {
await expect.poll(() => page.evaluate(() => {
const main = document.querySelector('main')!;
return Math.max(document.documentElement.scrollWidth - innerWidth, main.scrollWidth - main.clientWidth);
})).toBeLessThanOrEqual(1);
}
for (const [width, username] of [[320, 'mobile-admin'], [390, 'moderator'], [430, 'alice']] as const) {
test(`mobile ${width}: ${username} navigation, forms and search`, async ({ page }, info) => {
test.setTimeout(60_000);
await page.setViewportSize({ width, height: 844 });
await login(page, username);
await fits(page);
const bottom = page.getByRole('navigation', { name: 'Навигация' }).filter({ has: page.getByRole('button', { name: 'Ещё', exact: true }) });
await expect(bottom.getByRole('link')).toHaveCount(3);
await page.getByRole('button', { name: 'Ещё', exact: true }).click();
const dialog = page.getByRole('dialog', { name: 'Навигация' });
await expect(dialog).toBeVisible();
await expect(dialog.getByRole('link', { name: 'Дизлайки', exact: true })).toBeVisible();
if (username !== 'alice') {
await expect(dialog.getByRole('link', { name: 'Пользователи', exact: true })).toBeVisible();
await expect(dialog.getByRole('link', { name: 'Очередь', exact: true })).toBeVisible();
await expect(dialog.getByRole('link', { name: 'Хранилища', exact: true })).toHaveCount(username === 'mobile-admin' ? 1 : 0);
await dialog.getByRole('link', { name: 'Пользователи', exact: true }).click();
await expect(dialog).not.toBeVisible();
await expect(page.getByRole('heading', { name: 'Пользователи', exact: true })).toBeVisible();
await fits(page);
await page.screenshot({ path: info.outputPath('users.png') });
await page.getByRole('button', { name: /Действия.*alice/ }).click();
const menu = page.getByRole('menu');
await expect(menu).toBeVisible();
const rect = await menu.boundingBox();
expect(rect!.x).toBeGreaterThanOrEqual(0);
expect(rect!.x + rect!.width).toBeLessThanOrEqual(width);
await page.keyboard.press('Escape');
await page.getByRole('button', { name: 'Создать пользователя', exact: true }).click();
await expect(page.getByRole('dialog')).toBeVisible();
await page.screenshot({ path: info.outputPath('create-user.png') });
await page.getByRole('button', { name: 'Закрыть', exact: true }).click();
} else {
await expect(dialog.getByRole('link', { name: 'Пользователи', exact: true })).toHaveCount(0);
await page.getByRole('button', { name: 'Закрыть', exact: true }).click();
}
await page.getByRole('button', { name: 'Меню профиля' }).click();
await page.getByRole('menuitem', { name: 'Настройки', exact: true }).click();
await expect(page.getByRole('heading', { name: 'Настройки', exact: true })).toBeVisible();
await fits(page);
await page.screenshot({ path: info.outputPath('settings.png') });
for (const name of ['Слева', 'По центру', 'Справа']) {
await page.getByRole('button', { name, exact: true }).click();
await page.getByRole('combobox', { name: 'Поиск', exact: true }).fill('кино');
await expect(page.getByRole('option', { name: /Кино/ }).first()).toBeVisible();
await fits(page);
await page.getByRole('combobox', { name: 'Поиск', exact: true }).press('Escape');
}
if (username !== 'alice') {
await page.getByRole('button', { name: 'Ещё', exact: true }).click();
await page.getByRole('dialog').getByRole('link', { name: 'Очередь', exact: true }).click();
await expect(page.getByRole('heading', { name: 'Очередь на добавление' })).toBeVisible();
await expect(page.locator('audio')).toBeVisible();
await fits(page);
await page.getByRole('checkbox', { name: /^Выбрать Длинное/ }).check();
await expect(page.getByRole('region', { name: 'Действия с выбранными' })).toBeVisible();
await fits(page);
await page.screenshot({ path: info.outputPath('upload-queue.png') });
await page.getByRole('region', { name: 'Действия с выбранными' }).getByRole('button', { name: 'Отклонить' }).click();
await expect(page.getByRole('dialog')).toBeVisible();
await page.getByRole('button', { name: 'Закрыть', exact: true }).click();
}
if (username === 'mobile-admin') {
await page.getByRole('button', { name: 'Ещё', exact: true }).click();
await page.getByRole('dialog').getByRole('link', { name: 'Хранилища', exact: true }).click();
await expect(page.getByRole('article', { name: 'Музыкальное хранилище' })).toBeVisible();
await fits(page);
await page.getByRole('button', { name: 'Шаблоны путей', exact: true }).click();
await page.getByRole('button', { name: 'Добавить шаблон', exact: true }).click();
await fits(page);
await page.screenshot({ path: info.outputPath('patterns.png') });
}
});
}
test('mobile player keeps the island above navigation and exposes the queue', async ({ page }, info) => {
await page.setViewportSize({ width: 320, height: 740 });
await login(page, 'alice');
const box = page.getByRole('combobox', { name: 'Поиск', exact: true });
await box.fill('кино');
await box.press('Enter');
await page.getByRole('link', { name: /Группа крови/ }).first().click();
await page.getByRole('listitem').first().click();
const player = page.getByRole('contentinfo', { name: 'Плеер' });
await expect(player.getByRole('button', { name: 'Очередь', exact: true })).toBeVisible();
expect((await player.getByText('Группа крови', { exact: true }).boundingBox())!.width).toBeGreaterThan(40);
await fits(page);
await page.getByRole('button', { name: 'Меню профиля' }).click();
await page.getByRole('menuitem', { name: 'Настройки', exact: true }).click();
await page.getByRole('button', { name: 'Остров', exact: true }).click();
const nav = page.getByRole('navigation').filter({ has: page.getByRole('button', { name: 'Ещё', exact: true }) });
await expect.poll(async () => {
const p = await player.boundingBox();
const n = await nav.boundingBox();
return p!.y + p!.height <= n!.y + 1;
}).toBe(true);
await player.getByRole('button', { name: 'Очередь', exact: true }).click();
await expect(page.getByRole('complementary', { name: 'Очередь', exact: true })).toBeVisible();
await page.screenshot({ path: info.outputPath('player-queue.png') });
});
+34
View File
@@ -0,0 +1,34 @@
import { expect, test } from '@playwright/test';
for (const width of [320, 1280]) {
test(`playlists at ${width}px`, async ({ page }, info) => {
await page.setViewportSize({ width, height: 900 });
await page.addInitScript(() => localStorage.setItem('pipu.locale', 'ru'));
await page.goto('/login');
await page.getByLabel('Логин', { exact: true }).fill('alice');
await page.getByRole('textbox', { name: 'Пароль', exact: true }).fill('alice-password');
await page.getByRole('button', { name: 'Войти', exact: true }).click();
if (width < 768) await page.getByRole('button', { name: 'Ещё', exact: true }).click();
await page.getByRole('link', { name: 'Плейлисты', exact: true }).click();
await page.getByRole('button', { name: 'Создать плейлист', exact: true }).click();
await page.getByLabel('Название', { exact: true }).fill('Музыка для долгой дороги');
await page.getByLabel('Описание', { exact: true }).fill('Любимые песни всегда рядом');
await page.getByRole('button', { name: 'Сохранить', exact: true }).click();
await expect(page.getByRole('heading', { name: 'Музыка для долгой дороги' })).toBeVisible();
await page.getByRole('combobox', { name: 'Поиск', exact: true }).fill('кино');
await page.getByRole('combobox', { name: 'Поиск', exact: true }).press('Enter');
await page.getByRole('button', { name: 'Добавить в плейлист', exact: true }).first().click();
await page.getByRole('button', { name: /Музыка для долгой дороги · 0/ }).click();
await expect(page.getByRole('dialog')).toHaveCount(0);
if (width < 768) await page.getByRole('button', { name: 'Ещё', exact: true }).click();
await page.getByRole('link', { name: 'Плейлисты', exact: true }).click();
await page.getByRole('link', { name: /Музыка для долгой дороги/ }).click();
await page.getByRole('button', { name: 'Управлять треками' }).click();
await expect(page.getByRole('button', { name: /Убрать .* из плейлиста/ })).toBeVisible();
await expect.poll(() => page.evaluate(() => {
const main = document.querySelector('main')!;
return Math.max(document.documentElement.scrollWidth - innerWidth, main.scrollWidth - main.clientWidth);
})).toBeLessThanOrEqual(1);
await page.screenshot({ path: info.outputPath('playlist.png') });
});
}
+58
View File
@@ -0,0 +1,58 @@
import { expect, test } from '@playwright/test';
test.beforeEach(async ({ page }) => {
await page.addInitScript(() => localStorage.setItem('pipu.locale', 'ru'));
});
test('1. bootstrap admin changes credentials and lands on home', async ({ page }) => {
await page.goto('/login');
await expect(page.getByText(/Первый запуск/)).toBeVisible();
await page.getByLabel('Логин').fill('admin');
await page.getByRole('textbox', { name: 'Пароль' }).fill('admin-password');
await page.getByRole('button', { name: 'Войти' }).click();
await expect(page.getByRole('heading', { name: 'Смените логин и пароль' })).toBeVisible();
await page.getByLabel('Новый логин').fill('owner');
await page.getByRole('textbox', { name: 'Новый пароль' }).fill('a-strong-owner-pass');
await page.getByRole('textbox', { name: 'Повторите пароль' }).fill('a-strong-owner-pass');
await page.getByRole('button', { name: 'Сохранить и продолжить' }).click();
await expect(page.getByRole('button', { name: 'Бегаю' })).toBeVisible();
});
test('4. search suggest opens the artist and Enter opens search', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Логин').fill('alice');
await page.getByRole('textbox', { name: 'Пароль' }).fill('alice-password');
await page.getByRole('button', { name: 'Войти' }).click();
const box = page.getByRole('combobox', { name: 'Поиск' });
await box.fill('кино');
await page.getByRole('option', { name: /Кино/ }).first().click();
await expect(page.getByRole('heading', { name: 'Кино' })).toBeVisible();
await box.fill('кино');
// A suggestion under the pointer must not become a keyboard selection.
const suggestion = page.getByRole('option', { name: /Кино/ }).first();
await suggestion.hover();
await expect(suggestion).toHaveAttribute('aria-selected', 'false');
await box.press('Enter');
await expect(page).toHaveURL(/\/search\?q=/);
});
test('settings expose crossfade and loudness normalization', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Логин').fill('alice');
await page.getByRole('textbox', { name: 'Пароль' }).fill('alice-password');
await page.getByRole('button', { name: 'Войти' }).click();
await page.getByRole('button', { name: 'Меню профиля' }).click();
await page.getByRole('menuitem', { name: 'Настройки' }).click();
await expect(page.getByText('Выравнивание громкости')).toBeVisible();
const slider = page.getByRole('slider', { name: /Кроссфейд/ });
await slider.fill('4');
await expect(page.getByText('Кроссфейд, 4 с')).toBeVisible();
});
test('9. login page switches between Russian and English', async ({ page }) => {
await page.goto('/login');
await page.getByRole('button', { name: 'EN' }).click();
await expect(page.getByRole('heading', { name: 'Sign in' })).toBeVisible();
await page.getByRole('button', { name: 'RU' }).click();
await expect(page.getByRole('heading', { name: 'Вход' })).toBeVisible();
});
+1 -1
View File
@@ -2,7 +2,7 @@
<html lang="ru" data-theme="dark"> <html lang="ru" data-theme="dark">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="color-scheme" content="dark light" /> <meta name="color-scheme" content="dark light" />
<link rel="icon" href="/favicon.svg" type="image/svg+xml" /> <link rel="icon" href="/favicon.svg" type="image/svg+xml" />
<title>pipu</title> <title>pipu</title>
+9 -2
View File
@@ -8,7 +8,8 @@
"build": "tsc --noEmit && vite build", "build": "tsc --noEmit && vite build",
"preview": "vite preview", "preview": "vite preview",
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit",
"test": "vitest run" "test": "vitest run",
"test:e2e": "playwright test"
}, },
"dependencies": { "dependencies": {
"@fontsource/jetbrains-mono": "^5.2.6", "@fontsource/jetbrains-mono": "^5.2.6",
@@ -21,11 +22,16 @@
"@pipu/i18n": "workspace:*", "@pipu/i18n": "workspace:*",
"@tanstack/react-query": "^5.80.7", "@tanstack/react-query": "^5.80.7",
"@tanstack/react-router": "^1.120.20", "@tanstack/react-router": "^1.120.20",
"@tanstack/react-virtual": "^3.14.21",
"hash-wasm": "^4.12.0",
"music-metadata": "^12.2.3",
"react": "^19.1.0", "react": "^19.1.0",
"react-dom": "^19.1.0", "react-dom": "^19.1.0",
"react-i18next": "^15.5.3" "react-i18next": "^15.5.3",
"tus-js-client": "^4.3.1"
}, },
"devDependencies": { "devDependencies": {
"@playwright/test": "^1.64.1",
"@testing-library/dom": "^10.4.0", "@testing-library/dom": "^10.4.0",
"@testing-library/jest-dom": "^6.9.1", "@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.0", "@testing-library/react": "^16.3.0",
@@ -33,6 +39,7 @@
"@types/react": "^19.1.8", "@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6", "@types/react-dom": "^19.1.6",
"@vitejs/plugin-react": "^4.5.2", "@vitejs/plugin-react": "^4.5.2",
"axe-core": "^4.14.0",
"jsdom": "^26.1.0", "jsdom": "^26.1.0",
"vite": "^6.3.5", "vite": "^6.3.5",
"vitest": "^3.2.4" "vitest": "^3.2.4"
+13
View File
@@ -0,0 +1,13 @@
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './e2e',
timeout: 30_000,
use: { baseURL: 'http://127.0.0.1:4173', ...devices['Desktop Chrome'] },
webServer: {
command: 'pnpm exec vite --port 4173 --strictPort',
url: 'http://127.0.0.1:4173',
reuseExistingServer: !process.env.CI,
env: { VITE_E2E: '1' },
},
});
+170 -6
View File
@@ -4,6 +4,7 @@ import { QueryClient } from '@tanstack/react-query';
import { createMemoryHistory } from '@tanstack/react-router'; import { createMemoryHistory } from '@tanstack/react-router';
import { cleanup, render, screen, waitFor, within } from '@testing-library/react'; import { cleanup, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event'; import userEvent from '@testing-library/user-event';
import axe from 'axe-core';
import { I18nextProvider } from 'react-i18next'; import { I18nextProvider } from 'react-i18next';
import { afterEach, describe, expect, it } from 'vitest'; import { afterEach, describe, expect, it } from 'vitest';
@@ -79,7 +80,7 @@ describe('sign-in', () => {
await user.type(screen.getByLabelText(label), 'a-strong-owner-pass'); await user.type(screen.getByLabelText(label), 'a-strong-owner-pass');
} }
await user.click(screen.getByRole('button', { name: 'Сохранить и продолжить' })); await user.click(screen.getByRole('button', { name: 'Сохранить и продолжить' }));
await screen.findByText('Привет, owner!'); await screen.findByRole('button', { name: 'Запустить «Мою волну»' });
expect(router.state.location.pathname).toBe('/'); expect(router.state.location.pathname).toBe('/');
expect(api.calls.find((c) => c.path === '/api/v1/me/bootstrap-credentials' && c.body)?.body).toMatchObject({ expect(api.calls.find((c) => c.path === '/api/v1/me/bootstrap-credentials' && c.body)?.body).toMatchObject({
new_username: 'owner', new_username: 'owner',
@@ -93,7 +94,7 @@ describe('sign-in', () => {
await user.type(screen.getByLabelText('Новый пароль'), 'bobs-own-pass'); await user.type(screen.getByLabelText('Новый пароль'), 'bobs-own-pass');
await user.type(screen.getByLabelText('Повторите пароль'), 'bobs-own-pass'); await user.type(screen.getByLabelText('Повторите пароль'), 'bobs-own-pass');
await user.click(screen.getByRole('button', { name: 'Сохранить и продолжить' })); await user.click(screen.getByRole('button', { name: 'Сохранить и продолжить' }));
await screen.findByText('Привет, bob!'); await screen.findByRole('button', { name: 'Запустить «Мою волну»' });
}); });
it('signs out from the profile menu', async () => { it('signs out from the profile menu', async () => {
@@ -110,14 +111,15 @@ describe('navigation by role', () => {
it('hides the admin section from listeners and blocks the route', async () => { it('hides the admin section from listeners and blocks the route', async () => {
const alice = makeUser('alice', 'user'); const alice = makeUser('alice', 'user');
const { router } = await renderApp([alice], '/admin/users', { signedInAs: alice }); const { router } = await renderApp([alice], '/admin/users', { signedInAs: alice });
await screen.findByText('Привет, alice!'); await screen.findByRole('button', { name: 'Запустить «Мою волну»' });
expect(router.state.location.pathname).toBe('/'); expect(router.state.location.pathname).toBe('/');
expect(screen.queryByRole('link', { name: 'Пользователи' })).not.toBeInTheDocument(); expect(screen.queryByRole('link', { name: 'Пользователи' })).not.toBeInTheDocument();
}); });
it('shows users but not the audit log to moderators', async () => { it('shows users but not the audit log to moderators', async () => {
const mod = makeUser('mod', 'moderator'); const mod = makeUser('mod', 'moderator');
await renderApp([mod], '/', { signedInAs: mod }); const { user } = await renderApp([mod], '/', { signedInAs: mod });
await user.click(await screen.findByRole('button', { name: 'Админка' }));
expect(await screen.findByRole('link', { name: 'Пользователи' })).toBeInTheDocument(); expect(await screen.findByRole('link', { name: 'Пользователи' })).toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Журнал' })).not.toBeInTheDocument(); expect(screen.queryByRole('link', { name: 'Журнал' })).not.toBeInTheDocument();
}); });
@@ -152,6 +154,39 @@ describe('users admin', () => {
expect(await within(table).findByText('@ilya')).toBeInTheDocument(); expect(await within(table).findByText('@ilya')).toBeInTheDocument();
}); });
it.each(['root', 'anna'])('lets admins change the username of %s', async (target) => {
const root = makeUser('root', 'admin');
const anna = makeUser('anna', 'user');
const { user, api, session } = await renderApp([root, anna], '/admin/users', { signedInAs: root });
await user.click(await screen.findByRole('button', { name: `Действия с ${target}` }));
await user.click(screen.getByRole('menuitem', { name: 'Изменить логин' }));
const dialog = screen.getByRole('dialog', { name: 'Изменить логин' });
const input = within(dialog).getByLabelText('Логин');
await user.clear(input);
await user.type(input, `new.${target}`);
await user.click(within(dialog).getByRole('button', { name: 'Сохранить' }));
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
expect(await screen.findByText(`@new.${target}`)).toBeInTheDocument();
expect(api.users.get(target === 'root' ? root.id : anna.id)?.username).toBe(`new.${target}`);
if (target === 'root') expect(session.state).toMatchObject({ status: 'signed_in', user: { username: 'new.root' } });
});
it('keeps the username dialog open when the new username is taken', async () => {
const root = makeUser('root', 'admin');
const anna = makeUser('anna', 'user');
const { user, api } = await renderApp([root, anna], '/admin/users', { signedInAs: root });
await user.click(await screen.findByRole('button', { name: 'Действия с anna' }));
await user.click(screen.getByRole('menuitem', { name: 'Изменить логин' }));
const dialog = screen.getByRole('dialog', { name: 'Изменить логин' });
const input = within(dialog).getByLabelText('Логин');
await user.clear(input);
await user.type(input, 'ROOT');
await user.click(within(dialog).getByRole('button', { name: 'Сохранить' }));
await waitFor(() => expect(input).toHaveAttribute('aria-invalid', 'true'));
expect(api.users.get(anna.id)?.username).toBe('anna');
expect(dialog).toBeInTheDocument();
});
it('offers moderators only what they may do', async () => { it('offers moderators only what they may do', async () => {
const mod = makeUser('mod', 'moderator'); const mod = makeUser('mod', 'moderator');
const anna = makeUser('anna', 'user'); const anna = makeUser('anna', 'user');
@@ -164,7 +199,7 @@ describe('users admin', () => {
await user.click(screen.getByRole('button', { name: 'Действия с anna' })); await user.click(screen.getByRole('button', { name: 'Действия с anna' }));
const items = screen.getAllByRole('menuitem').map((i) => i.textContent); const items = screen.getAllByRole('menuitem').map((i) => i.textContent);
expect(items).toEqual(['Сбросить пароль', 'Заблокировать']); expect(items).toEqual(['Сбросить пароль', 'Сбросить рекомендации', 'Заблокировать']);
await user.keyboard('{Escape}'); await user.keyboard('{Escape}');
await user.click(screen.getByRole('button', { name: 'Создать пользователя' })); await user.click(screen.getByRole('button', { name: 'Создать пользователя' }));
@@ -246,11 +281,35 @@ describe('search box', () => {
}); });
describe('player', () => { describe('player', () => {
it('opens a shared track after login and copies its page URL from the player', async () => {
const alice = makeUser('alice', 'user');
const path = '/track/00000000-0000-4000-8000-000000000101';
const { user, router } = await renderApp([alice], path);
await screen.findByRole('heading', { name: 'Вход' });
await user.type(screen.getByLabelText('Логин'), alice.username);
await user.type(screen.getByLabelText('Пароль'), alice.password);
await user.click(screen.getByRole('button', { name: 'Войти' }));
await screen.findByRole('heading', { name: 'Закрой за мной дверь' });
expect(router.state.location.pathname).toBe(path);
await user.click(screen.getByRole('listitem'));
const bar = screen.getByRole('contentinfo', { name: 'Плеер' });
await user.click(within(bar).getByRole('button', { name: 'Поделиться треком' }));
expect(await within(bar).findByRole('status')).toHaveTextContent('Ссылка на трек скопирована');
expect(await navigator.clipboard.readText()).toBe(`${window.location.origin}${path}`);
});
it('shows a missing shared track without starting playback', async () => {
const alice = makeUser('alice', 'user');
await renderApp([alice], '/track/missing', { signedInAs: alice });
expect(await screen.findByRole('alert')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Пауза' })).not.toBeInTheDocument();
});
it('plays an album from a clicked row, likes and pauses with the keyboard', async () => { it('plays an album from a clicked row, likes and pauses with the keyboard', async () => {
const alice = makeUser('alice', 'user'); const alice = makeUser('alice', 'user');
const { user, api } = await renderApp([alice], '/album/00000000-0000-4000-8000-0000000000bb', { signedInAs: alice }); const { user, api } = await renderApp([alice], '/album/00000000-0000-4000-8000-0000000000bb', { signedInAs: alice });
const row = (await screen.findByText('Закрой за мной дверь')).closest('[role="row"]')!; const row = (await screen.findByText('Закрой за мной дверь')).closest('[role="listitem"]')!;
await user.click(row); await user.click(row);
const bar = screen.getByRole('contentinfo', { name: 'Плеер' }); const bar = screen.getByRole('contentinfo', { name: 'Плеер' });
await waitFor(() => expect(within(bar).getByText('Закрой за мной дверь')).toBeInTheDocument()); await waitFor(() => expect(within(bar).getByText('Закрой за мной дверь')).toBeInTheDocument());
@@ -285,6 +344,59 @@ describe('player', () => {
}); });
}); });
describe('my wave', () => {
it('starts the wave and switches the mood on the fly', async () => {
const alice = makeUser('alice', 'user');
const { user, api } = await renderApp([alice], '/', { signedInAs: alice });
await user.click(await screen.findByRole('button', { name: 'Бегаю' }));
await user.click(screen.getByRole('button', { name: 'Запустить «Мою волну»' }));
const bar = screen.getByRole('contentinfo', { name: 'Плеер' });
await waitFor(() => expect(within(bar).getByText('Группа крови')).toBeInTheDocument());
expect(api.calls.find((c) => c.method === 'POST' && c.path === '/api/v1/wave/sessions')?.body).toEqual({
activity: 'running',
mood: null,
});
expect(screen.getByRole('button', { name: 'Пауза «Моей волны»' })).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Спокойное' }));
await waitFor(() =>
expect(api.calls.find((c) => c.method === 'PATCH' && c.path.startsWith('/api/v1/wave/sessions/'))?.body).toEqual({
activity: 'running',
mood: 'calm',
}),
);
expect(within(bar).getByText('Группа крови')).toBeInTheDocument(); // музыка не прервалась
expect(screen.getByText('Бегаю · Спокойное')).toBeInTheDocument();
});
});
describe('suggest tracks', () => {
it('warns that lossless formats are the ones to send', async () => {
const admin = makeUser('admin', 'admin');
await renderApp([admin], '/uploads/new', { signedInAs: admin });
expect(await screen.findByText(/Нужны FLAC, WAV или AIFF/)).toBeInTheDocument();
expect(screen.getByText(/MP3 — только в крайнем случае/)).toBeInTheDocument();
});
});
describe('accessibility', () => {
it('home and login have no serious axe violations', async () => {
const alice = makeUser('alice', 'user');
await renderApp([alice], '/', { signedInAs: alice });
await screen.findByRole('button', { name: 'Бегаю' });
const home = await axe.run(document.body, { resultTypes: ['violations'] });
expect(home.violations.filter((v) => v.impact === 'serious' || v.impact === 'critical')).toEqual([]);
cleanup();
await renderApp([], '/login');
await screen.findByRole('heading', { name: 'Вход' });
const login = await axe.run(document.body, { resultTypes: ['violations'] });
expect(login.violations.filter((v) => v.impact === 'serious' || v.impact === 'critical')).toEqual([]);
});
});
describe('safeRedirect', () => { describe('safeRedirect', () => {
it.each([ it.each([
['/settings', '/settings'], ['/settings', '/settings'],
@@ -295,3 +407,55 @@ describe('safeRedirect', () => {
expect(safeRedirect(input)).toBe(expected); expect(safeRedirect(input)).toBe(expected);
}); });
}); });
describe('playlists', () => {
it('creates, edits, adds an album, reorders, removes and deletes a playlist', async () => {
const alice = makeUser('alice', 'user');
const { user, router, api } = await renderApp([alice], '/collection/playlists', { signedInAs: alice });
await user.click(await screen.findByRole('button', { name: 'Создать плейлист' }));
await user.type(screen.getByLabelText('Название'), 'В дорогу');
await user.type(screen.getByLabelText('Описание'), 'Музыка для дороги');
await user.click(screen.getByRole('button', { name: 'Сохранить' }));
await screen.findByRole('heading', { name: 'В дорогу' });
const id = [...api.playlists.keys()][0]!;
expect(api.playlists.get(id)?.description).toBe('Музыка для дороги');
await router.navigate({ to: '/album/$id', params: { id: '00000000-0000-4000-8000-0000000000bb' } });
await screen.findByRole('heading', { name: 'Группа крови' });
await user.click(screen.getAllByRole('button', { name: 'Добавить в плейлист' })[0]!);
await user.click(await screen.findByRole('button', { name: 'В дорогу · 0' }));
await waitFor(() => expect(api.playlists.get(id)?.tracks).toHaveLength(2));
await router.navigate({ to: '/playlist/$id', params: { id } });
await user.click(await screen.findByRole('button', { name: 'Управлять треками' }));
await user.click(screen.getByRole('button', { name: 'Переместить «Закрой за мной дверь» выше' }));
await waitFor(() => expect(api.playlists.get(id)?.tracks[0]?.title).toBe('Закрой за мной дверь'));
await waitFor(() => expect(screen.getByRole('button', { name: 'Убрать «Группа крови» из плейлиста' })).toBeEnabled());
await user.click(screen.getByRole('button', { name: 'Убрать «Группа крови» из плейлиста' }));
await waitFor(() => expect(api.playlists.get(id)?.tracks).toHaveLength(1));
await user.click(screen.getByRole('button', { name: 'Изменить плейлист' }));
await user.clear(screen.getByLabelText('Название'));
await user.type(screen.getByLabelText('Название'), 'Вечер');
await user.click(screen.getByRole('button', { name: 'Сохранить' }));
await screen.findByRole('heading', { name: 'Вечер' });
await user.click(screen.getByRole('button', { name: 'Удалить плейлист' }));
await user.click(within(screen.getByRole('dialog')).getByRole('button', { name: 'Удалить плейлист' }));
await screen.findByRole('heading', { name: 'Плейлисты' });
expect(api.playlists.size).toBe(0);
});
it('keeps stale editor open on conflict without overwriting newer changes', async () => {
const alice = makeUser('alice', 'user');
const { user, api } = await renderApp([alice], '/collection/playlists', { signedInAs: alice });
await user.click(await screen.findByRole('button', { name: 'Создать плейлист' }));
await user.type(screen.getByLabelText('Название'), 'Первый');
await user.click(screen.getByRole('button', { name: 'Сохранить' }));
await screen.findByRole('heading', { name: 'Первый' });
await user.click(screen.getByRole('button', { name: 'Изменить плейлист' }));
const item = [...api.playlists.values()][0]!;
api.playlists.set(item.id, { ...item, revision: 2, name: 'Другое устройство' });
await user.type(screen.getByLabelText('Название'), ' изменён');
await user.click(screen.getByRole('button', { name: 'Сохранить' }));
expect(await screen.findByRole('alert')).toHaveTextContent('Плейлист изменён на другом устройстве');
expect(screen.getByRole('dialog')).toBeInTheDocument();
expect(api.playlists.get(item.id)?.name).toBe('Другое устройство');
});
});
+81 -12
View File
@@ -7,16 +7,26 @@ import {
redirect, redirect,
type ParsedLocation, type ParsedLocation,
} from '@tanstack/react-router'; } from '@tanstack/react-router';
import { lazy } from 'react';
import { AuditPage } from '../pages/admin/AuditPage'; const AuditPage = lazy(() => import('../pages/admin/AuditPage').then((m) => ({ default: m.AuditPage })));
import { LibraryPage } from '../pages/admin/LibraryPage'; const LibraryPage = lazy(() => import('../pages/admin/LibraryPage').then((m) => ({ default: m.LibraryPage })));
import { PatternsPage } from '../pages/admin/PatternsPage'; const PatternsPage = lazy(() => import('../pages/admin/PatternsPage').then((m) => ({ default: m.PatternsPage })));
import { SourcesPage } from '../pages/admin/SourcesPage'; const AdminSettingsPage = lazy(() => import('../pages/admin/AdminSettingsPage').then((m) => ({ default: m.AdminSettingsPage })));
import { UsersPage } from '../pages/admin/UsersPage'; const UploadQueuePage = lazy(() => import('../pages/admin/UploadQueuePage').then((m) => ({ default: m.UploadQueuePage })));
const MyUploadsPage = lazy(() => import('../pages/uploads/MyUploadsPage').then((m) => ({ default: m.MyUploadsPage })));
const SuggestPage = lazy(() => import('../pages/uploads/SuggestPage').then((m) => ({ default: m.SuggestPage })));
const SourcesPage = lazy(() => import('../pages/admin/SourcesPage').then((m) => ({ default: m.SourcesPage })));
const UsersPage = lazy(() => import('../pages/admin/UsersPage').then((m) => ({ default: m.UsersPage })));
import type { DesktopHandle } from '../desktop';
import { AlbumPage } from '../pages/AlbumPage'; import { AlbumPage } from '../pages/AlbumPage';
import { ConnectPage } from '../pages/ConnectPage';
import { TrackPage } from '../pages/TrackPage';
import { ArtistPage } from '../pages/ArtistPage'; import { ArtistPage } from '../pages/ArtistPage';
import { CollectionPage } from '../pages/CollectionPage'; import { CollectionPage } from '../pages/CollectionPage';
import { PlaylistPage, PlaylistsPage } from '../pages/PlaylistsPage';
import { HomePage } from '../pages/HomePage'; import { HomePage } from '../pages/HomePage';
import { AppDownloadPage } from '../pages/AppDownloadPage';
import { LoginPage } from '../pages/LoginPage'; import { LoginPage } from '../pages/LoginPage';
import { SearchPage, type SearchType } from '../pages/SearchPage'; import { SearchPage, type SearchType } from '../pages/SearchPage';
import { SettingsPage } from '../pages/SettingsPage'; import { SettingsPage } from '../pages/SettingsPage';
@@ -26,6 +36,7 @@ import { RouteError } from '../widgets/RouteError';
export interface RouterContext { export interface RouterContext {
session: AuthSession; session: AuthSession;
desktop: DesktopHandle | null;
} }
/** Куда пользователю можно попасть сейчас: обязательные шаги первого входа важнее всего. */ /** Куда пользователю можно попасть сейчас: обязательные шаги первого входа важнее всего. */
@@ -44,9 +55,12 @@ export function safeRedirect(target: unknown): string {
return typeof target === 'string' && target.startsWith('/') && !target.startsWith('//') ? target : '/'; return typeof target === 'string' && target.startsWith('/') && !target.startsWith('//') ? target : '/';
} }
function requireUser(session: AuthSession, location: ParsedLocation): AuthUser { function requireUser(session: AuthSession, location: ParsedLocation, desktop: DesktopHandle | null): AuthUser {
const user = signedInUser(session); const user = signedInUser(session);
if (!user) throw redirect({ to: '/login', search: { redirect: location.href } }); if (!user) {
if (desktop && !desktop.server) throw redirect({ to: '/connect' });
throw redirect({ to: '/login', search: { redirect: location.href } });
}
return user; return user;
} }
@@ -55,12 +69,26 @@ const rootRoute = createRootRouteWithContext<RouterContext>()({
errorComponent: RouteError, errorComponent: RouteError,
}); });
// Публичная: ссылку на приложение отправляют тем, у кого ещё нет аккаунта на этом устройстве.
const androidAppRoute = createRoute({ getParentRoute: () => rootRoute, path: '/android', component: AppDownloadPage });
const connectRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/connect',
beforeLoad: ({ context }) => {
if (!context.desktop) throw redirect({ to: '/login' });
if (context.desktop.server) throw redirect({ to: '/login' });
},
component: ConnectPage,
});
const loginRoute = createRoute({ const loginRoute = createRoute({
getParentRoute: () => rootRoute, getParentRoute: () => rootRoute,
path: '/login', path: '/login',
validateSearch: (search: Record<string, unknown>): { redirect?: string } => validateSearch: (search: Record<string, unknown>): { redirect?: string } =>
typeof search.redirect === 'string' ? { redirect: search.redirect } : {}, typeof search.redirect === 'string' ? { redirect: search.redirect } : {},
beforeLoad: ({ context, search }) => { beforeLoad: ({ context, search }) => {
if (context.desktop && !context.desktop.server) throw redirect({ to: '/connect' });
const user = signedInUser(context.session); const user = signedInUser(context.session);
if (!user) return; if (!user) return;
const home = homeFor(user); const home = homeFor(user);
@@ -74,7 +102,7 @@ const setupAdminRoute = createRoute({
getParentRoute: () => rootRoute, getParentRoute: () => rootRoute,
path: '/setup/admin', path: '/setup/admin',
beforeLoad: ({ context, location }) => { beforeLoad: ({ context, location }) => {
const user = requireUser(context.session, location); const user = requireUser(context.session, location, context.desktop);
if (homeFor(user) !== '/setup/admin') throw redirect({ to: homeFor(user) }); if (homeFor(user) !== '/setup/admin') throw redirect({ to: homeFor(user) });
}, },
component: () => <SetupPage variant="admin" />, component: () => <SetupPage variant="admin" />,
@@ -84,7 +112,7 @@ const setupPasswordRoute = createRoute({
getParentRoute: () => rootRoute, getParentRoute: () => rootRoute,
path: '/setup/password', path: '/setup/password',
beforeLoad: ({ context, location }) => { beforeLoad: ({ context, location }) => {
const user = requireUser(context.session, location); const user = requireUser(context.session, location, context.desktop);
if (homeFor(user) !== '/setup/password') throw redirect({ to: homeFor(user) }); if (homeFor(user) !== '/setup/password') throw redirect({ to: homeFor(user) });
}, },
component: () => <SetupPage variant="password" />, component: () => <SetupPage variant="password" />,
@@ -95,7 +123,7 @@ const appRoute = createRoute({
getParentRoute: () => rootRoute, getParentRoute: () => rootRoute,
id: 'app', id: 'app',
beforeLoad: ({ context, location }) => { beforeLoad: ({ context, location }) => {
const user = requireUser(context.session, location); const user = requireUser(context.session, location, context.desktop);
const home = homeFor(user); const home = homeFor(user);
if (home !== '/') throw redirect({ to: home }); if (home !== '/') throw redirect({ to: home });
return { user }; return { user };
@@ -108,6 +136,9 @@ const adminOnly = ({ context }: { context: { user: AuthUser } }) => {
}; };
const homeRoute = createRoute({ getParentRoute: () => appRoute, path: '/', component: HomePage }); const homeRoute = createRoute({ getParentRoute: () => appRoute, path: '/', component: HomePage });
const trackRoute = createRoute({ getParentRoute: () => appRoute, path: '/track/$id', component: () => <TrackPage key={trackRoute.useParams().id} id={trackRoute.useParams().id} /> });
const playlistsRoute = createRoute({ getParentRoute: () => appRoute, path: '/collection/playlists', component: PlaylistsPage });
const playlistRoute = createRoute({ getParentRoute: () => appRoute, path: '/playlist/$id', component: () => <PlaylistPage id={playlistRoute.useParams().id} /> });
const settingsRoute = createRoute({ getParentRoute: () => appRoute, path: '/settings', component: SettingsPage }); const settingsRoute = createRoute({ getParentRoute: () => appRoute, path: '/settings', component: SettingsPage });
@@ -205,12 +236,42 @@ const libraryRoute = createRoute({
component: LibraryPage, component: LibraryPage,
}); });
/** Предложение треков — модераторы и админ (docs/uploads.md#1). */
const staffOnly = ({ context }: { context: { user: AuthUser } }) => {
if (context.user.role === 'user') throw redirect({ to: '/' });
};
const suggestRoute = createRoute({ getParentRoute: () => appRoute, path: '/uploads/new', beforeLoad: staffOnly, component: SuggestPage });
const myUploadsRoute = createRoute({ getParentRoute: () => appRoute, path: '/uploads/mine', beforeLoad: staffOnly, component: MyUploadsPage });
const uploadQueueRoute = createRoute({
getParentRoute: () => appRoute,
path: '/admin/uploads',
beforeLoad: ({ context }) => {
if (!context.user.reviews_uploads) throw redirect({ to: '/' });
},
component: UploadQueuePage,
});
const adminSettingsRoute = createRoute({
getParentRoute: () => appRoute,
path: '/admin/settings',
beforeLoad: adminOnly,
component: AdminSettingsPage,
});
const routeTree = rootRoute.addChildren([ const routeTree = rootRoute.addChildren([
androidAppRoute,
connectRoute,
loginRoute, loginRoute,
setupAdminRoute, setupAdminRoute,
setupPasswordRoute, setupPasswordRoute,
appRoute.addChildren([ appRoute.addChildren([
homeRoute, homeRoute,
trackRoute,
playlistsRoute,
playlistRoute,
settingsRoute, settingsRoute,
searchRoute, searchRoute,
historyRoute, historyRoute,
@@ -223,11 +284,19 @@ const routeTree = rootRoute.addChildren([
sourcesRoute, sourcesRoute,
patternsRoute, patternsRoute,
libraryRoute, libraryRoute,
suggestRoute,
myUploadsRoute,
uploadQueueRoute,
adminSettingsRoute,
]), ]),
]); ]);
export function createAppRouter(session: AuthSession, opts: { history?: Parameters<typeof createRouter>[0]['history'] } = {}) { export function createAppRouter(
const router = createRouter({ routeTree, context: { session }, defaultPreload: false, ...opts }); session: AuthSession,
opts: { history?: Parameters<typeof createRouter>[0]['history']; desktop?: DesktopHandle | null } = {},
) {
const { desktop = null, ...rest } = opts;
const router = createRouter({ routeTree, context: { session, desktop }, defaultPreload: false, ...rest });
// Выход, блокировка, отзыв сессии — guards пересчитываются, и пользователь уходит на /login. // Выход, блокировка, отзыв сессии — guards пересчитываются, и пользователь уходит на /login.
session.subscribe(() => void router.invalidate()); session.subscribe(() => void router.invalidate());
return router; return router;
+28
View File
@@ -0,0 +1,28 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createDesktop, isDesktop } from './desktop';
afterEach(() => {
vi.unstubAllGlobals();
});
describe('desktop bridge', () => {
it('is inactive in the browser', () => {
expect(isDesktop()).toBe(false);
});
it('bootstraps through the Tauri invoke surface', async () => {
const invoke = vi.fn(async (cmd: string) => {
if (cmd === 'bootstrap') return { proxyBase: 'http://127.0.0.1:9/abc', server: 'https://music.example' };
if (cmd === 'set_server') return 'https://music.example/pipu';
return null;
});
(window as Window & { __TAURI__?: unknown }).__TAURI__ = { core: { invoke }, event: { listen: vi.fn() } };
const desktop = await createDesktop();
expect(desktop?.proxyBase).toBe('http://127.0.0.1:9/abc');
expect(desktop?.server).toBe('https://music.example');
await desktop?.setServer('https://music.example/pipu');
expect(invoke).toHaveBeenCalledWith('set_server', { url: 'https://music.example/pipu' });
delete (window as Window & { __TAURI__?: unknown }).__TAURI__;
});
});
+94
View File
@@ -0,0 +1,94 @@
import type { AuthUser, RefreshStore } from '@pipu/core';
import { createContext, createElement, useContext, type ReactNode } from 'react';
type Tauri = {
core: { invoke: (cmd: string, args?: Record<string, unknown>) => Promise<unknown> };
event: { listen: (event: string, handler: (e: { payload: string }) => void) => Promise<() => void> };
};
function api(): Tauri | undefined {
return (window as Window & { __TAURI__?: Tauri }).__TAURI__;
}
export function isDesktop(): boolean {
return api() !== undefined;
}
function invoke<T>(cmd: string, args?: Record<string, unknown>): Promise<T> {
const tauri = api();
if (!tauri) throw new Error('Tauri API unavailable');
return tauri.core.invoke(cmd, args) as Promise<T>;
}
export type DesktopHandle = {
proxyBase: string;
server: string | null;
setServer: (url: string) => Promise<string>;
clearServer: () => Promise<void>;
refreshStore: RefreshStore;
listenMedia: (handler: (action: string) => void) => Promise<() => void>;
setMedia: (info: { title: string; artist: string; album: string; coverUrl?: string | null; playing: boolean }) => void;
};
export const DesktopContext = createContext<DesktopHandle | null>(null);
export function DesktopProvider({ value, children }: { value: DesktopHandle | null; children: ReactNode }) {
return createElement(DesktopContext.Provider, { value }, children);
}
export function useDesktop(): DesktopHandle | null {
return useContext(DesktopContext);
}
let active: DesktopHandle | null = null;
export function desktopHandle(): DesktopHandle | null {
return active;
}
export async function createDesktop(): Promise<DesktopHandle | null> {
if (!isDesktop()) return null;
const boot = await invoke<{ proxyBase: string; server: string | null }>('bootstrap');
const handle: DesktopHandle = {
proxyBase: boot.proxyBase,
server: boot.server,
setServer: async (url) => {
const server = await invoke<string>('set_server', { url });
handle.server = server;
return server;
},
clearServer: async () => {
await invoke('clear_server');
handle.server = null;
},
refreshStore: {
get: () => invoke<string | null>('token_get'),
set: (token) => invoke('token_set', { token }),
clear: async () => {
await invoke('token_clear');
await invoke('user_clear');
},
getUser: async () => {
const json = await invoke<string | null>('user_get');
return json ? (JSON.parse(json) as AuthUser) : null;
},
setUser: (user) => invoke('user_set', { json: JSON.stringify(user) }),
},
listenMedia: async (handler) => {
const tauri = api();
if (!tauri) return () => undefined;
return tauri.event.listen('media', (e) => handler(e.payload));
},
setMedia: (info) => {
void invoke('media_set', {
title: info.title,
artist: info.artist,
album: info.album,
coverUrl: info.coverUrl ?? null,
playing: info.playing,
});
},
};
active = handle;
return handle;
}
+59
View File
@@ -110,6 +110,56 @@
grid-template-columns: 40px minmax(0, 2fr) minmax(0, 1fr) auto; grid-template-columns: 40px minmax(0, 2fr) minmax(0, 1fr) auto;
} }
.track:has(.lead) {
grid-template-columns: 44px 44px minmax(0, 1fr) auto;
}
.track:has(.lead):has(.trackAlbum) {
grid-template-columns: 44px 44px minmax(0, 1.4fr) minmax(0, 1fr) auto;
}
.lead {
display: flex;
justify-content: center;
font-size: 13px;
color: var(--text3);
font-variant-numeric: tabular-nums;
}
.dimmed {
opacity: 0.6;
}
.eq {
display: flex;
gap: 2px;
align-items: flex-end;
height: 14px;
}
.eq span {
width: 3px;
height: 14px;
border-radius: 2px;
background: var(--accent2);
transform-origin: bottom;
animation: pipuEq 0.55s ease-in-out infinite alternate;
}
.eq span:nth-child(2) {
animation-duration: 0.72s;
animation-delay: 0.1s;
}
.eq span:nth-child(3) {
animation-duration: 0.89s;
animation-delay: 0.2s;
}
.eqPaused span {
animation-play-state: paused;
}
.track:hover { .track:hover {
background: var(--hover); background: var(--hover);
} }
@@ -220,3 +270,12 @@
display: none; display: none;
} }
} }
@media (max-width: 767px) {
.grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; }
.track, .track:has(.trackAlbum) { gap: 8px; padding: 6px 4px; }
.track:has(.lead), .track:has(.lead):has(.trackAlbum) { grid-template-columns: 24px 40px minmax(0, 1fr) auto; }
.end { gap: 4px; }
.like { opacity: 1; width: 44px; height: 44px; }
.track:has([data-playlist-actions]) .end { grid-column: 3 / -1; justify-content: flex-end; }
}
+129 -62
View File
@@ -1,12 +1,14 @@
import type { components } from '@pipu/api-client'; import type { components } from '@pipu/api-client';
import { Link } from '@tanstack/react-router'; import { Link } from '@tanstack/react-router';
import { Fragment } from 'react'; import { useVirtualizer } from '@tanstack/react-virtual';
import { Fragment, useRef, type ReactNode } from 'react';
import { AddToPlaylist } from './playlists';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { formatDuration } from '../shared/lib/format'; import { formatDuration } from '../shared/lib/format';
import { usePlayer, usePlayerState } from '../player/context'; import { usePlayer, usePlayerState } from '../player/context';
import type { PlayContext } from '../player/player'; import type { PlayContext } from '../player/player';
import { albumIcon, likeFillIcon, likeIcon, personIcon, playIcon } from '../shared/ui/icons'; import { albumIcon, likeFillIcon, likeIcon, personIcon, playIcon, undoIcon} from '../shared/ui/icons';
import { cx, Icon } from '../shared/ui/ui'; import { cx, Icon } from '../shared/ui/ui';
import s from './catalog.module.css'; import s from './catalog.module.css';
@@ -112,85 +114,150 @@ export function TrackList({
numbered, numbered,
context, context,
rowMeta, rowMeta,
lead,
disliked,
actions,
}: { }: {
tracks: Track[]; tracks: Track[];
showAlbum?: boolean; showAlbum?: boolean;
numbered?: boolean; numbered?: boolean;
context: PlayContext; context: PlayContext;
/** Дополнительный текст под исполнителями (например, время прослушивания в истории). */ /** Дополнительный текст под исполнителями. */
rowMeta?: (t: Track, i: number) => string | undefined; rowMeta?: (t: Track, i: number) => string | undefined;
/** Первая колонка перед обложкой (docs/design: время в истории, номер в лайках); у текущего трека — эквалайзер. */
lead?: (t: Track, i: number) => string;
/** Список дизлайков: строки приглушены, вместо лайка — «снять дизлайк». */
disliked?: boolean;
actions?: (track: Track, index: number) => ReactNode;
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
const player = usePlayer(); const player = usePlayer();
const current = usePlayerState().track; const { track: current, playing } = usePlayerState();
const listRef = useRef<HTMLDivElement>(null);
const discs = new Set(tracks.map((tr) => tr.disc_no ?? 1)); const discs = new Set(tracks.map((tr) => tr.disc_no ?? 1));
const multiDisc = Boolean(numbered && discs.size > 1);
const virtual = tracks.length > 30 && !multiDisc;
const virtualizer = useVirtualizer({
count: virtual ? tracks.length : 0,
getScrollElement: () => listRef.current?.closest('main') ?? null,
estimateSize: () => 68,
overscan: 8,
});
const row = (tr: Track, i: number) => {
const isCurrent = current?.id === tr.id;
const play = () => tr.available && player.playList(tracks, i, context);
const liked = tr.reaction === 'like';
const meta = rowMeta?.(tr, i);
return (
<div
role="listitem"
tabIndex={tr.available ? 0 : -1}
aria-current={isCurrent || undefined}
className={cx(s.track, !tr.available && s.unavailable, isCurrent && s.current)}
title={tr.available ? undefined : t('catalog.unavailable')}
onClick={(e) => {
if (e.currentTarget.contains(e.target as Node) && !(e.target as HTMLElement).closest('a, button')) play();
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && e.target === e.currentTarget) play();
}}
>
{lead && <span className={s.lead}>{isCurrent ? <Equalizer playing={playing} /> : lead(tr, i)}</span>}
<span className={cx(s.num, disliked && s.dimmed)}>
{numbered ? (tr.track_no ?? i + 1) : <Cover album={tr.album} size={lead ? 44 : 40} />}
{tr.available && (
<span className={s.playHint} aria-hidden>
<Icon src={playIcon} size={20} />
</span>
)}
</span>
<span className={cx(s.trackMain, disliked && s.dimmed)}>
<span className={s.trackTitle}>{tr.title}</span>
<span className={s.trackArtists}>
<ArtistLinks artists={tr.artists} />
{meta && <span className={s.rowMeta}> · {meta}</span>}
</span>
</span>
{showAlbum && (
<Link to="/album/$id" params={{ id: tr.album.id }} className={cx(s.link, s.trackAlbum)}>
{tr.album.title}
</Link>
)}
<span className={s.end} data-playlist-actions={actions ? true : undefined}>
{actions ? actions(tr, i) : <AddToPlaylist trackIds={[tr.id]} compact />}
{disliked ? (
<button
type="button"
className={cx(s.like, s.liked)}
aria-label={t('player.undislike')}
onClick={() => void player.react(tr, null).catch(() => undefined)}
>
<Icon src={undoIcon} size={18} />
</button>
) : (
<button
type="button"
className={cx(s.like, liked && s.liked)}
aria-label={t(liked ? 'player.unlike' : 'player.like')}
aria-pressed={liked}
onClick={() => void player.react(tr, liked ? null : 'like').catch(() => undefined)}
>
<Icon src={liked ? likeFillIcon : likeIcon} size={18} />
</button>
)}
<span className={s.duration}>{formatDuration(tr.duration_ms)}</span>
</span>
</div>
);
};
let lastDisc: number | null = null; let lastDisc: number | null = null;
return ( return (
<div className={s.tracks} role="table" aria-label={t('search.tracks')}> <div
{tracks.map((tr, i) => { ref={listRef}
const disc = tr.disc_no ?? 1; className={s.tracks}
const header = numbered && discs.size > 1 && disc !== lastDisc; role="list"
lastDisc = disc; aria-label={t('search.tracks')}
const isCurrent = current?.id === tr.id; style={virtual ? { height: virtualizer.getTotalSize(), position: 'relative' } : undefined}
const play = () => tr.available && player.playList(tracks, i, context); >
const liked = tr.reaction === 'like'; {virtual
const meta = rowMeta?.(tr, i); ? virtualizer.getVirtualItems().map((vi) => (
return (
<Fragment key={`${tr.id}-${i}`}>
{header && <div className={s.disc}>{t('catalog.disc', { n: disc })}</div>}
<div <div
role="row" key={vi.key}
tabIndex={tr.available ? 0 : -1} data-index={vi.index}
aria-current={isCurrent || undefined} ref={virtualizer.measureElement}
className={cx(s.track, !tr.available && s.unavailable, isCurrent && s.current)} style={{ position: 'absolute', top: 0, left: 0, width: '100%', transform: `translateY(${vi.start}px)` }}
title={tr.available ? undefined : t('catalog.unavailable')}
onClick={(e) => {
if (!(e.target as HTMLElement).closest('a, button')) play();
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && e.target === e.currentTarget) play();
}}
> >
<span className={s.num}> {row(tracks[vi.index]!, vi.index)}
{numbered ? (tr.track_no ?? i + 1) : <Cover album={tr.album} size={40} />}
{tr.available && (
<span className={s.playHint} aria-hidden>
<Icon src={playIcon} size={20} />
</span>
)}
</span>
<span className={s.trackMain}>
<span className={s.trackTitle}>{tr.title}</span>
<span className={s.trackArtists}>
<ArtistLinks artists={tr.artists} />
{meta && <span className={s.rowMeta}> · {meta}</span>}
</span>
</span>
{showAlbum && (
<Link to="/album/$id" params={{ id: tr.album.id }} className={cx(s.link, s.trackAlbum)}>
{tr.album.title}
</Link>
)}
<span className={s.end}>
<button
type="button"
className={cx(s.like, liked && s.liked)}
aria-label={t(liked ? 'player.unlike' : 'player.like')}
aria-pressed={liked}
onClick={() => void player.react(tr, liked ? null : 'like').catch(() => undefined)}
>
<Icon src={liked ? likeFillIcon : likeIcon} size={18} />
</button>
<span className={s.duration}>{formatDuration(tr.duration_ms)}</span>
</span>
</div> </div>
</Fragment> ))
); : tracks.map((tr, i) => {
})} const disc = tr.disc_no ?? 1;
const header = multiDisc && disc !== lastDisc;
lastDisc = disc;
return (
<Fragment key={`${tr.id}-${i}`}>
{header && <div className={s.disc}>{t('catalog.disc', { n: disc })}</div>}
{row(tr, i)}
</Fragment>
);
})}
</div> </div>
); );
} }
/** Эквалайзер текущего трека (`pipuEq`, docs/design.md#2): три столбика, на паузе замирают. */
export function Equalizer({ playing }: { playing: boolean }) {
return (
<span className={cx(s.eq, !playing && s.eqPaused)} aria-hidden>
<span />
<span />
<span />
</span>
);
}
export function ArtistChip({ artist }: { artist: ArtistRef }) { export function ArtistChip({ artist }: { artist: ArtistRef }) {
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
+17
View File
@@ -0,0 +1,17 @@
import { unwrap } from '@pipu/core';
import { useQuery } from '@tanstack/react-query';
import { useSession } from '../app/session';
/** Сколько лайков и дизлайков — счётчики в меню (total из первой страницы списка). */
export function useCollectionCounts() {
const session = useSession();
const total = (path: '/api/v1/me/likes' | '/api/v1/me/dislikes') => ({
queryKey: ['collection-count', path],
queryFn: async () => unwrap(await session.client.GET(path, { params: { query: { limit: 1 } } })).total,
staleTime: 60_000,
});
const likes = useQuery(total('/api/v1/me/likes'));
const dislikes = useQuery(total('/api/v1/me/dislikes'));
return { likes: likes.data, dislikes: dislikes.data };
}
+97
View File
@@ -0,0 +1,97 @@
import type { components } from '@pipu/api-client';
import { unwrap } from '@pipu/core';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useSession } from '../app/session';
import { useErrorText } from '../shared/lib/errors';
import { Button, Dialog, Field, FormError, Icon } from '../shared/ui/ui';
import { queueIcon } from '../shared/ui/icons';
import s from './catalog.module.css';
export type Playlist = components['schemas']['Playlist'];
export type PlaylistInput = components['schemas']['PlaylistInput'];
export function usePlaylists(enabled = true) {
const session = useSession();
return useQuery({ queryKey: ['playlists'], enabled,
queryFn: async () => unwrap(await session.client.GET('/api/v1/me/playlists')) });
}
export function usePlaylist(id: string) {
const session = useSession();
return useQuery({ queryKey: ['playlists', id],
queryFn: async () => unwrap(await session.client.GET('/api/v1/me/playlists/{id}', { params: { path: { id } } })) });
}
export function playlistInput(p: Playlist): PlaylistInput & { revision: number } {
return { name: p.name, description: p.description, track_ids: p.tracks.map(t => t.id), revision: p.revision };
}
export function PlaylistEditor({ playlist, trackIds = [], onClose, onSaved }: {
playlist?: Playlist; trackIds?: string[]; onClose: () => void; onSaved: (p: Playlist) => void;
}) {
const { t } = useTranslation();
const session = useSession();
const cache = useQueryClient();
const errorText = useErrorText();
const [original] = useState(playlist);
const [name, setName] = useState(playlist?.name ?? '');
const [description, setDescription] = useState(playlist?.description ?? '');
const save = useMutation({ mutationFn: async () => {
const body = { name: name.trim(), description, track_ids: original?.tracks.map(t => t.id) ?? trackIds };
return original
? unwrap(await session.client.PUT('/api/v1/me/playlists/{id}', { params: { path: { id: original.id } }, body: { ...body, revision: original.revision } }))
: unwrap(await session.client.POST('/api/v1/me/playlists', { body }));
}, onSuccess: p => {
cache.setQueryData(['playlists', p.id], p);
void cache.invalidateQueries({ queryKey: ['playlists'] });
onSaved(p);
}, onError: () => { void cache.invalidateQueries({ queryKey: ['playlists'] }); } });
const close = useCallback(() => { if (!save.isPending) onClose(); }, [save.isPending, onClose]);
return <Dialog title={t(playlist ? 'playlists.edit' : 'playlists.create')} onClose={close}>
<form onSubmit={e => { e.preventDefault(); if (!save.isPending && name.trim()) save.mutate(); }}>
<Field label={t('playlists.name')} value={name} onChange={setName} maxLength={120} required autoFocus />
<Field label={t('playlists.description')} value={description} onChange={setDescription} maxLength={2000} />
<FormError>{save.error ? errorText(save.error) : null}</FormError>
<Button variant="primary" type="submit" busy={save.isPending} disabled={!name.trim()}>{t('playlists.save')}</Button>
<Button variant="ghost" onClick={onClose} disabled={save.isPending}>{t('form.cancel')}</Button>
</form>
</Dialog>;
}
/** Mounted only while open, so catalog rows do not each subscribe to the playlist list. */
function PlaylistPicker({ trackIds, onClose }: { trackIds: string[]; onClose: () => void }) {
const { t } = useTranslation();
const session = useSession();
const cache = useQueryClient();
const errorText = useErrorText();
const list = usePlaylists();
const [create, setCreate] = useState(false);
const add = useMutation({ mutationFn: async (id: string) => {
const p = unwrap(await session.client.GET('/api/v1/me/playlists/{id}', { params: { path: { id } } }));
const body = playlistInput(p);
body.track_ids = [...new Set([...body.track_ids, ...trackIds])];
return unwrap(await session.client.PUT('/api/v1/me/playlists/{id}', { params: { path: { id } }, body }));
}, onSuccess: () => { void cache.invalidateQueries({ queryKey: ['playlists'] }); onClose(); } });
if (create) return <PlaylistEditor trackIds={trackIds} onClose={() => setCreate(false)} onSaved={onClose} />;
return <Dialog title={t('playlists.add')} onClose={() => { if (!add.isPending) onClose(); }}>
<FormError>{list.error || add.error ? errorText(list.error ?? add.error) : null}</FormError>
{list.isPending && <p role="status">{t('playlists.loading')}</p>}
{list.isSuccess && list.data.items.length === 0 && <p>{t('playlists.empty')}</p>}
<div style={{ display: 'grid', gap: 8 }}>
{list.data?.items.map(p => <Button key={p.id} disabled={add.isPending} onClick={() => add.mutate(p.id)}>{p.name} · {p.track_count}</Button>)}
<Button variant="primary" disabled={add.isPending} onClick={() => setCreate(true)}>{t('playlists.create')}</Button>
</div>
</Dialog>;
}
export function AddToPlaylist({ trackIds, compact = false }: { trackIds: string[]; compact?: boolean }) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
return <>
{compact ? <button type="button" className={s.like} aria-label={t('playlists.add')} title={t('playlists.add')} onClick={() => setOpen(true)}><Icon src={queueIcon} size={18} /></button>
: <Button icon={queueIcon} disabled={trackIds.length === 0} onClick={() => setOpen(true)}>{t('playlists.add')}</Button>}
{open && <PlaylistPicker trackIds={trackIds} onClose={() => setOpen(false)} />}
</>;
}
@@ -0,0 +1,18 @@
import { describe, expect, it } from 'vitest';
import { needsFormatAttention } from './files';
describe('needsFormatAttention', () => {
it('marks everything except lossless formats', () => {
expect(needsFormatAttention('flac', 'a.mp3')).toBe(false);
expect(needsFormatAttention('WAV', 'track.wav')).toBe(false);
expect(needsFormatAttention(null, 'Кино/01.wav')).toBe(false);
expect(needsFormatAttention('aiff', 'a.aif')).toBe(false);
expect(needsFormatAttention(null, 'track.AIFF')).toBe(false);
expect(needsFormatAttention(null, 'track.wv')).toBe(false);
expect(needsFormatAttention('mp3', 'a.flac')).toBe(true);
expect(needsFormatAttention(null, 'folder/song.MP3')).toBe(true);
expect(needsFormatAttention(null, 'song.m4a')).toBe(true);
expect(needsFormatAttention(null, 'noext')).toBe(false);
});
});
+65
View File
@@ -0,0 +1,65 @@
// Сбор файлов из drag-and-drop и выбора папки с относительными путями (они подсказывают альбом, docs/uploads.md#5).
export interface PickedFile {
file: File;
relPath: string; // «Кино/1988 - Группа крови/01 - Группа крови.flac» или просто имя файла
}
/** Форматы, которые принимает очередь (сервер всё равно проверяет содержимое через ffprobe). */
export const AUDIO_EXTENSIONS = ['flac', 'mp3', 'm4a', 'ogg', 'opus', 'wav', 'aiff', 'aif', 'wv'];
/** То, что просим присылать. MP3 и прочие — крайний случай, их помечает очередь. */
// Lossless — как в quality.go на сервере.
const PREFERRED_AUDIO = new Set(['flac', 'wav', 'aiff', 'aif', 'wv']);
export function audioExt(name: string): string {
const base = name.split(/[/\\]/).pop() ?? name;
const dot = base.lastIndexOf('.');
if (dot < 0 || dot === base.length - 1) return '';
return base.slice(dot + 1).toLowerCase();
}
/** Не lossless (FLAC, WAV, AIFF, WavPack): в очереди на добавление такой файл нужно выделить. */
export function needsFormatAttention(format: string | null | undefined, name: string): boolean {
const ext = (format || audioExt(name)).toLowerCase();
return ext !== '' && !PREFERRED_AUDIO.has(ext);
}
export function isAudio(name: string): boolean {
const ext = name.split('.').pop()?.toLowerCase() ?? '';
return AUDIO_EXTENSIONS.includes(ext);
}
/** Файлы из <input type="file"> (в том числе webkitdirectory — тогда путь есть в webkitRelativePath). */
export function fromInput(list: FileList | null): PickedFile[] {
return [...(list ?? [])].map((file) => ({ file, relPath: file.webkitRelativePath || file.name }));
}
/** Файлы из перетаскивания: папки обходятся рекурсивно (FileSystemEntry API). */
export async function fromDrop(dt: DataTransfer): Promise<PickedFile[]> {
const entries = [...dt.items]
.filter((it) => it.kind === 'file')
.map((it) => it.webkitGetAsEntry?.())
.filter((e): e is FileSystemEntry => !!e);
if (!entries.length) return fromInput(dt.files);
const out: PickedFile[] = [];
for (const e of entries) await walk(e, '', out);
return out;
}
async function walk(entry: FileSystemEntry, prefix: string, out: PickedFile[]) {
const path = prefix ? `${prefix}/${entry.name}` : entry.name;
if (entry.isFile) {
const file = await new Promise<File>((resolve, reject) => (entry as FileSystemFileEntry).file(resolve, reject));
out.push({ file, relPath: path });
return;
}
if (!entry.isDirectory || entry.name.startsWith('.')) return;
const reader = (entry as FileSystemDirectoryEntry).createReader();
// readEntries отдаёт порциями (~100), пока не вернёт пустой массив.
for (;;) {
const batch = await new Promise<FileSystemEntry[]>((resolve, reject) => reader.readEntries(resolve, reject));
if (!batch.length) break;
for (const child of batch) await walk(child, path, out);
}
}
@@ -0,0 +1,40 @@
/// <reference lib="webworker" />
// SHA-256 файла потоком (docs/uploads.md#4): Web Crypto не умеет считать по частям, а файлы бывают по 2 ГБ —
// hash-wasm считает чанками в воркере, не держа файл в памяти и не блокируя интерфейс.
import { createSHA256 } from 'hash-wasm';
export interface HashRequest {
id: string;
file: File;
}
export type HashResponse =
| { id: string; type: 'progress'; done: number }
| { id: string; type: 'done'; sha256: string }
| { id: string; type: 'error'; message: string };
const ctx = self as unknown as DedicatedWorkerGlobalScope;
ctx.onmessage = async (e: MessageEvent<HashRequest>) => {
const { id, file } = e.data;
try {
const h = await createSHA256();
h.init();
const reader = file.stream().getReader();
let done = 0;
let lastReport = 0;
for (;;) {
const chunk = await reader.read();
if (chunk.done) break;
h.update(chunk.value);
done += chunk.value.byteLength;
if (done - lastReport > 8 << 20) {
lastReport = done;
ctx.postMessage({ id, type: 'progress', done } satisfies HashResponse);
}
}
ctx.postMessage({ id, type: 'done', sha256: h.digest('hex') } satisfies HashResponse);
} catch (err) {
ctx.postMessage({ id, type: 'error', message: err instanceof Error ? err.message : String(err) } satisfies HashResponse);
}
};
+415
View File
@@ -0,0 +1,415 @@
import { unwrap, type AuthSession } from '@pipu/core';
import * as tus from 'tus-js-client';
import { isAudio, type PickedFile } from './files';
import type { HashRequest, HashResponse } from './hash.worker';
// Загрузка пачки в очередь на добавление (docs/uploads.md#5): SHA-256 в воркере → предпроверка дублей
// (ничего не резервирует) → POST /uploads (резерв квоты) → tus, до 4 файлов параллельно, куски по 8 МБ.
// Синглтон модуля: загрузка продолжается при переходах по приложению, но не переживает перезагрузку страницы.
export type Stage =
| 'hashing'
| 'checking'
| 'ready'
| 'duplicate'
| 'too_large'
| 'uploading'
| 'done'
| 'rejected'
| 'error'
| 'resume';
export interface UploadItem {
id: string;
file: File | null;
size: number;
relPath: string;
stage: Stage;
progress: number; // 0..1 текущего этапа (хэш или загрузка)
sha256?: string;
tags?: { artist?: string; title?: string; album?: string; duration_ms?: number };
trackId?: string | null;
possibleDuplicate?: boolean;
code?: string; // код отказа сервера: uploads.queue_full, uploads.duplicate, …
message?: string;
uploadFileId?: string;
tusUrl?: string;
}
export interface UploaderState {
items: UploadItem[];
skipped: number; // не аудио (обложки, .cue, …)
busy: boolean; // идёт загрузка
batchId: string | null;
error: unknown;
}
const PARALLEL = 4;
const CHUNK = 8 << 20;
const PENDING_KEY = 'pipu.uploads.pending';
interface PendingUpload {
id: string;
name: string;
size: number;
relPath: string;
sha256: string;
tusUrl: string;
uploadFileId: string;
}
let seq = 0;
export class Uploader {
private state: UploaderState = { items: [], skipped: 0, busy: false, batchId: null, error: null };
private listeners = new Set<() => void>();
private worker: Worker | null = null;
private hashQueue: string[] = [];
private hashing = false;
private uploads = new Map<string, tus.Upload>();
private refreshing: Promise<unknown> | null = null;
constructor(private readonly session: AuthSession) {
this.restore();
}
subscribe = (fn: () => void) => {
this.listeners.add(fn);
return () => this.listeners.delete(fn);
};
getState = () => this.state;
private set(patch: Partial<UploaderState>) {
this.state = { ...this.state, ...patch };
for (const fn of this.listeners) fn();
}
private patch(id: string, p: Partial<UploadItem>) {
this.set({ items: this.state.items.map((it) => (it.id === id ? { ...it, ...p } : it)) });
}
private item(id: string) {
return this.state.items.find((it) => it.id === id);
}
/** Добавить файлы (из перетаскивания или выбора); не-аудио отбрасываются. */
add(files: PickedFile[]) {
if (this.state.busy) return;
const fresh: UploadItem[] = [];
let skipped = 0;
for (const f of files) {
if (!isAudio(f.file.name)) {
skipped++;
continue;
}
// Тот же путь и размер уже в списке — не добавляем второй раз.
if (this.state.items.some((it) => it.relPath === f.relPath && it.size === f.file.size)) continue;
fresh.push({ id: `f${++seq}`, file: f.file, size: f.file.size, relPath: f.relPath, stage: 'hashing', progress: 0 });
}
this.set({ items: [...this.state.items, ...fresh], skipped: this.state.skipped + skipped, batchId: null, error: null });
this.hashQueue.push(...fresh.map((it) => it.id));
void this.hashNext();
}
remove(id: string) {
if (this.state.busy) return;
this.hashQueue = this.hashQueue.filter((x) => x !== id);
this.set({ items: this.state.items.filter((it) => it.id !== id) });
this.persist();
}
/** Очистить список (после завершения или чтобы начать заново). */
clear() {
if (this.state.busy) return;
this.hashQueue = [];
this.set({ items: [], skipped: 0, batchId: null, error: null });
this.persist();
}
private hashWorker(): Worker {
this.worker ??= new Worker(new URL('./hash.worker.ts', import.meta.url), { type: 'module' });
return this.worker;
}
private async hashNext() {
if (this.hashing) return;
this.hashing = true;
try {
while (this.hashQueue.length) {
const id = this.hashQueue.shift()!;
const it = this.item(id);
if (!it) continue;
try {
const sha256 = await this.hash(it);
await this.readTags(it);
this.patch(id, { sha256, stage: 'checking', progress: 1 });
} catch (err) {
this.patch(id, { stage: 'error', message: err instanceof Error ? err.message : String(err) });
}
}
await this.precheck();
} finally {
this.hashing = false;
}
}
private hash(it: UploadItem): Promise<string> {
const file = it.file;
if (!file) return Promise.reject(new Error('no file'));
const w = this.hashWorker();
return new Promise((resolve, reject) => {
const onMessage = (e: MessageEvent<HashResponse>) => {
const m = e.data;
if (m.id !== it.id) return;
if (m.type === 'progress') {
this.patch(it.id, { progress: m.done / Math.max(it.size, 1) });
return;
}
w.removeEventListener('message', onMessage);
if (m.type === 'done') resolve(m.sha256);
else reject(new Error(m.message));
};
w.addEventListener('message', onMessage);
w.postMessage({ id: it.id, file } satisfies HashRequest);
});
}
/** Предпроверка всех посчитанных файлов: дубли отсеиваются до загрузки. */
private async precheck() {
const pending = this.state.items.filter((it) => it.stage === 'checking' && it.sha256);
if (!pending.length) return;
try {
const res = unwrap(
await this.session.client.POST('/api/v1/uploads/precheck', {
body: {
files: pending.map((it) => ({
client_id: it.id,
size: it.size,
sha256: it.sha256!,
artist: it.tags?.artist,
title: it.tags?.title,
album: it.tags?.album,
duration_ms: it.tags?.duration_ms,
})),
},
}),
);
for (const r of res.files) {
const stage: Stage = r.result === 'accepted' ? 'ready' : r.result;
this.patch(r.client_id, { stage, trackId: r.track_id, possibleDuplicate: r.possible_duplicate });
}
} catch (err) {
// Предпроверка — подсказка: при сбое файлы всё равно можно отправить, сервер проверит дубли сам.
for (const it of pending) this.patch(it.id, { stage: 'ready' });
this.set({ error: err });
}
}
get ready(): UploadItem[] {
return this.state.items.filter((it) => it.stage === 'ready');
}
/** Создать пачку (резерв квоты) и загрузить принятые файлы. */
async start(comment: string) {
const ready = this.ready;
if (this.state.busy || !ready.length) return;
this.set({ busy: true, error: null });
try {
const res = unwrap(
await this.session.client.POST('/api/v1/uploads', {
body: {
comment: comment.trim() || undefined,
files: ready.map((it) => ({
client_id: it.id,
name: it.file?.name ?? it.relPath,
rel_path: it.relPath.includes('/') ? it.relPath : undefined,
size: it.size,
sha256: it.sha256!,
})),
},
}),
);
this.set({ batchId: res.batch_id });
const queue: { id: string; url: string }[] = [];
for (const f of res.files) {
if (f.rejected) this.patch(f.client_id, { stage: 'rejected', code: f.rejected, trackId: f.track_id });
else if (f.tus_url && f.upload_file_id) {
this.patch(f.client_id, { uploadFileId: f.upload_file_id, tusUrl: f.tus_url, stage: 'uploading', progress: 0 });
queue.push({ id: f.client_id, url: f.tus_url });
}
}
this.persist();
await Promise.all(Array.from({ length: Math.min(PARALLEL, queue.length) }, () => this.drain(queue)));
} catch (err) {
this.set({ error: err });
} finally {
this.set({ busy: false });
}
}
/** Повторить оборвавшиеся загрузки: место уже зарезервировано, tus продолжит с принятого смещения. */
async retryFailed() {
const failed = this.state.items.filter((it) => it.stage === 'error' && it.tusUrl);
if (this.state.busy || !failed.length) return;
this.set({ busy: true, error: null });
try {
const queue = failed.map((it) => {
this.patch(it.id, { stage: 'uploading', message: undefined });
return { id: it.id, url: it.tusUrl! };
});
await Promise.all(Array.from({ length: Math.min(PARALLEL, queue.length) }, () => this.drain(queue)));
} finally {
this.set({ busy: false });
}
}
private async drain(queue: { id: string; url: string }[]) {
for (let next = queue.shift(); next; next = queue.shift()) await this.upload(next.id, next.url);
}
private upload(id: string, url: string): Promise<void> {
const it = this.item(id);
if (!it?.file) return Promise.resolve();
const file = it.file;
return new Promise((resolve) => {
const up = new tus.Upload(file, {
uploadUrl: url,
chunkSize: CHUNK,
retryDelays: [0, 1000, 3000, 5000, 10000, 20000],
storeFingerprintForResuming: false,
onBeforeRequest: async (req) => {
await this.refreshing;
const token = this.session.accessToken;
if (token) req.setHeader('Authorization', `Bearer ${token}`);
},
onShouldRetry: (err) => {
const status = (err as tus.DetailedError).originalResponse?.getStatus();
if (status === 401) {
this.refreshing = this.session.refresh();
return true;
}
// Сеть, перегрузка, рассинхрон смещения — повторяем (tus-js-client спросит HEAD и продолжит).
return status === undefined || status === 0 || status >= 500 || status === 409 || status === 423;
},
onProgress: (sent, total) => this.patch(id, { progress: sent / Math.max(total, 1) }),
onSuccess: () => {
this.uploads.delete(id);
this.patch(id, { stage: 'done', progress: 1 });
this.persist();
resolve();
},
onError: (err) => {
this.uploads.delete(id);
this.patch(id, { stage: 'error', message: err.message });
resolve();
},
});
this.uploads.set(id, up);
up.start();
});
}
private async readTags(it: UploadItem) {
if (!it.file) return;
try {
const { parseBlob } = await import('music-metadata');
const meta = await parseBlob(it.file);
const duration = meta.format.duration;
this.patch(it.id, {
tags: {
artist: meta.common.artist,
title: meta.common.title,
album: meta.common.album,
duration_ms: duration ? Math.round(duration * 1000) : undefined,
},
});
} catch {
// Теги — подсказка для предпроверки; без них сервер прочитает их сам.
}
}
/** Незавершённые tus-загрузки переживают перезагрузку: файл выбирают заново и докачивают. */
private persist() {
const pending: PendingUpload[] = this.state.items
.filter((it): it is UploadItem & { sha256: string; tusUrl: string; uploadFileId: string } =>
Boolean(it.tusUrl && it.sha256 && it.uploadFileId && it.stage !== 'done'),
)
.map((it) => ({
id: it.id,
name: it.file?.name ?? it.relPath,
size: it.size,
relPath: it.relPath,
sha256: it.sha256,
tusUrl: it.tusUrl,
uploadFileId: it.uploadFileId,
}));
try {
if (pending.length) localStorage.setItem(PENDING_KEY, JSON.stringify(pending));
else localStorage.removeItem(PENDING_KEY);
} catch {
// Приватный режим — докачка после перезагрузки недоступна.
}
}
private restore() {
try {
const raw = localStorage.getItem(PENDING_KEY);
if (!raw) return;
const rows = JSON.parse(raw) as PendingUpload[];
if (!Array.isArray(rows) || !rows.length) return;
this.state = {
...this.state,
items: rows.map((r) => ({
id: r.id,
file: null,
size: r.size,
relPath: r.relPath,
stage: 'resume' as const,
progress: 0,
sha256: r.sha256,
tusUrl: r.tusUrl,
uploadFileId: r.uploadFileId,
})),
};
} catch {
localStorage.removeItem(PENDING_KEY);
}
}
/** Приложить заново те же файлы и продолжить tus с принятого смещения. */
async continueWith(files: PickedFile[]) {
const waiting = this.state.items.filter((it) => it.stage === 'resume' && it.tusUrl);
if (!waiting.length) return;
const queue: { id: string; url: string }[] = [];
for (const picked of files) {
const it = waiting.find((w) => w.size === picked.file.size && (w.relPath === picked.relPath || w.relPath.endsWith(picked.file.name)));
if (!it) continue;
this.patch(it.id, { file: picked.file, stage: 'hashing', progress: 0 });
const sha = await this.hash(this.item(it.id)!);
if (sha !== it.sha256) {
this.patch(it.id, { stage: 'error', message: 'sha256' });
continue;
}
this.patch(it.id, { stage: 'uploading', progress: 0 });
queue.push({ id: it.id, url: it.tusUrl! });
}
if (!queue.length) return;
this.set({ busy: true });
try {
await Promise.all(Array.from({ length: Math.min(PARALLEL, queue.length) }, () => this.drain(queue)));
} finally {
this.set({ busy: false });
this.persist();
}
}
}
let instance: { session: AuthSession; uploader: Uploader } | null = null;
/** Загрузчик текущей сессии (новый при смене пользователя). */
export function uploaderFor(session: AuthSession): Uploader {
if (instance?.session !== session) instance = { session, uploader: new Uploader(session) };
return instance.uploader;
}
+16 -3
View File
@@ -9,6 +9,7 @@ import { I18nextProvider } from 'react-i18next';
import { App } from './App'; import { App } from './App';
import { createAppRouter } from './app/router'; import { createAppRouter } from './app/router';
import { applyTheme } from './app/session'; import { applyTheme } from './app/session';
import { createDesktop, DesktopProvider } from './desktop';
const LOCALE_KEY = 'pipu.locale'; const LOCALE_KEY = 'pipu.locale';
@@ -48,6 +49,10 @@ function deviceName(): string {
} }
applyTheme(undefined); applyTheme(undefined);
if (import.meta.env.VITE_E2E === '1') {
const { installE2EFetch } = await import('./test/e2eBridge');
installE2EFetch();
}
const i18n = await createI18n(pickLocale([...storedLocale(), ...navigator.languages])); const i18n = await createI18n(pickLocale([...storedLocale(), ...navigator.languages]));
document.documentElement.lang = i18n.language; document.documentElement.lang = i18n.language;
i18n.on('languageChanged', (l) => { i18n.on('languageChanged', (l) => {
@@ -59,15 +64,23 @@ i18n.on('languageChanged', (l) => {
} }
}); });
const session = new AuthSession({ clientType: 'web', deviceName: deviceName() }); const desktop = await createDesktop();
const session = new AuthSession({
clientType: desktop ? 'desktop' : 'web',
deviceName: desktop ? 'Pipu / Desktop' : deviceName(),
baseUrl: desktop?.proxyBase,
refreshStore: desktop?.refreshStore,
});
// До первого рендера узнаём, есть ли сессия (refresh-cookie), — guards роутера решают сразу. // До первого рендера узнаём, есть ли сессия (refresh-cookie), — guards роутера решают сразу.
await session.restore(); await session.restore();
const router = createAppRouter(session); const router = createAppRouter(session, { desktop });
createRoot(document.getElementById('root')!).render( createRoot(document.getElementById('root')!).render(
<StrictMode> <StrictMode>
<I18nextProvider i18n={i18n}> <I18nextProvider i18n={i18n}>
<App session={session} router={router} /> <DesktopProvider value={desktop}>
<App session={session} router={router} />
</DesktopProvider>
</I18nextProvider> </I18nextProvider>
</StrictMode>, </StrictMode>,
); );
+30 -10
View File
@@ -5,7 +5,11 @@ import { useTranslation } from 'react-i18next';
import { useSession } from '../app/session'; import { useSession } from '../app/session';
import { Cover, TrackList } from '../entities/catalog'; import { Cover, TrackList } from '../entities/catalog';
import { AddToPlaylist } from '../entities/playlists';
import { usePlayer } from '../player/context';
import { formatDuration } from '../shared/lib/format'; import { formatDuration } from '../shared/lib/format';
import { playIcon, shuffleIcon } from '../shared/ui/icons';
import { Button } from '../shared/ui/ui';
import { NotFound } from './NotFound'; import { NotFound } from './NotFound';
import s from './page.module.css'; import s from './page.module.css';
import c from './catalog.module.css'; import c from './catalog.module.css';
@@ -13,6 +17,7 @@ import c from './catalog.module.css';
export function AlbumPage({ id }: { id: string }) { export function AlbumPage({ id }: { id: string }) {
const { t } = useTranslation(); const { t } = useTranslation();
const session = useSession(); const session = useSession();
const player = usePlayer();
const album = useQuery({ const album = useQuery({
queryKey: ['album', id], queryKey: ['album', id],
queryFn: async () => unwrap(await session.client.GET('/api/v1/albums/{id}', { params: { path: { id } } })), queryFn: async () => unwrap(await session.client.GET('/api/v1/albums/{id}', { params: { path: { id } } })),
@@ -21,17 +26,12 @@ export function AlbumPage({ id }: { id: string }) {
if (album.isError) return <NotFound error={album.error} />; if (album.isError) return <NotFound error={album.error} />;
const a = album.data; const a = album.data;
const colors = a?.cover_colors.length === 3 ? a.cover_colors : null; const colors = a?.cover_colors.length === 3 ? a.cover_colors : null;
const ctx = { type: 'album' as const, id, label: a?.title };
return ( return (
<div className={s.page}> <div className={s.page}>
<header className={c.hero}> <header className={c.hero}>
{colors && ( {colors && <span className={c.tint} style={{ background: `linear-gradient(180deg, ${colors[0]}66, transparent)` }} aria-hidden />}
<span
className={c.heroBg}
style={{ background: `linear-gradient(135deg, ${colors[0]}, ${colors[1]})` }}
aria-hidden
/>
)}
<Cover album={a ?? { id }} size={200} /> <Cover album={a ?? { id }} size={200} />
<div className={c.heroBody}> <div className={c.heroBody}>
<span className={c.kind}>{t('catalog.album')}</span> <span className={c.kind}>{t('catalog.album')}</span>
@@ -41,13 +41,33 @@ export function AlbumPage({ id }: { id: string }) {
<Link to="/artist/$id" params={{ id: a.artist.id }}> <Link to="/artist/$id" params={{ id: a.artist.id }}>
{a.artist.name} {a.artist.name}
</Link> </Link>
{a.year ? ` · ${a.year}` : ''} · {t('catalog.track_count', { count: a.tracks.length })} ·{' '} {a.year ? ` · ${a.year}` : ''} · {t('catalog.track_count', { count: a.tracks.length })} · {formatDuration(a.duration_ms)}
{formatDuration(a.duration_ms)}
</span> </span>
)} )}
{a && a.tracks.some((tr) => tr.available) && (
<div className={c.heroActions}>
<AddToPlaylist trackIds={a.tracks.map(tr => tr.id)} />
<Button variant="primary" className={c.pill} icon={playIcon} onClick={() => player.playList(a.tracks, 0, ctx)}>
{t('catalog.play')}
</Button>
<Button
className={c.pill}
icon={shuffleIcon}
onClick={() =>
player.playList(
[...a.tracks].sort(() => Math.random() - 0.5),
0,
ctx,
)
}
>
{t('collection.shuffle')}
</Button>
</div>
)}
</div> </div>
</header> </header>
{a && <TrackList tracks={a.tracks} numbered context={{ type: 'album', id: a.id, label: a.title }} />} {a && <TrackList tracks={a.tracks} numbered context={ctx} />}
</div> </div>
); );
} }
+70
View File
@@ -0,0 +1,70 @@
import { useQuery } from '@tanstack/react-query';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useSession } from '../app/session';
import { formatBytes } from '../shared/lib/format';
import { checkIcon, copyIcon, downloadIcon } from '../shared/ui/icons';
import { Icon } from '../shared/ui/ui';
import { AuthLayout } from './AuthLayout';
import s from './auth.module.css';
/**
* Публичная страница Android-приложения (/android): ссылку можно просто отправить человеку.
* APK — последний релиз, который сервер сам берёт из Gitea (docs/mobile.md#самообновление).
*/
export function AppDownloadPage() {
const { t, i18n } = useTranslation(['auth', 'common']);
const session = useSession();
const [copied, setCopied] = useState(false);
const latest = useQuery({
queryKey: ['android-latest'],
queryFn: async () => (await session.client.GET('/api/v1/app/android/latest')).data ?? null,
staleTime: 10 * 60_000,
});
const server = location.origin;
const copy = () =>
void navigator.clipboard?.writeText(server).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 1500);
});
const r = latest.data;
return (
<AuthLayout footer={<a href="/login">{t('app.to_login')}</a>}>
<span className={s.badge}>Android</span>
<h1>{t('app.title')}</h1>
<p className={s.lead}>{t('app.subtitle')}</p>
{latest.isPending ? null : r ? (
<>
<a className={s.download} href={r.download_url} download>
<Icon src={downloadIcon} size={22} />
<span>
{t('app.download')}
<span className={s.downloadMeta}>
{t('app.version', { version: r.version })} · {formatBytes(r.size, i18n.language)}
</span>
</span>
</a>
<ol className={s.steps}>
<li>{t('app.step_install')}</li>
<li>
{t('app.step_server')}
<button type="button" className={s.server} onClick={copy} aria-label={t('app.copy_server')}>
<code>{server}</code>
<Icon src={copied ? checkIcon : copyIcon} size={16} />
</button>
</li>
<li>{t('app.step_updates')}</li>
</ol>
<details className={s.details}>
<summary>{t('app.checksum')}</summary>
<code>{r.sha256}</code>
</details>
</>
) : (
<div className={s.hint}>{t('app.unavailable')}</div>
)}
</AuthLayout>
);
}
Loaded 100 of 327 files, more files were not shown because too many files have changed in this diff. Show more