74 Commits

Author SHA1 Message Date
austinried
2bf3e8853d 1.3.0 changelog 2022-04-26 13:19:45 +09:00
austinried
e14099472a bump version 1.3.0 2022-04-26 13:17:01 +09:00
austinried
ac06e21f37 Update release.yml 2022-04-26 12:53:43 +09:00
austinried
92e2fd93f9 Create release.yml 2022-04-26 12:49:50 +09:00
jazzyjabroni
a5ccba69ec Translated using Weblate (Danish)
Currently translated at 59.7% (40 of 67 strings)

Added translation using Weblate (Danish)

Co-authored-by: jazzyjabroni <lordcarmack@tuta.io>
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/da/
Translation: Subtracks/subtracks
2022-04-26 11:59:34 +09:00
Sargon-Isa
23eb05a368 Translated using Weblate (German)
Currently translated at 100.0% (67 of 67 strings)

Co-authored-by: Sargon-Isa <Sargon_isa@hotmail.de>
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/de/
Translation: Subtracks/subtracks
2022-04-26 11:59:34 +09:00
austinried
1f9ee9b462 Merge remote-tracking branch 'weblate/main' into main 2022-04-21 15:01:28 +09:00
Weblate (bot)
237b8d2fc6 Translations update from Hosted Weblate (#112)
* Added translation using Weblate (Chinese (Simplified))

* Translated using Weblate (Chinese (Simplified))

Currently translated at 86.5% (58 of 67 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/zh_Hans/

* Translated using Weblate (Chinese (Simplified))

Currently translated at 100.0% (67 of 67 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/zh_Hans/

Co-authored-by: Hillwah <curvycode@gmail.com>
2022-04-21 15:00:36 +09:00
Hillwah
35eada710e Translated using Weblate (Chinese (Simplified))
Currently translated at 100.0% (67 of 67 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/zh_Hans/
2022-04-21 07:58:39 +02:00
Hillwah
86ef5af6f6 Translated using Weblate (Chinese (Simplified))
Currently translated at 86.5% (58 of 67 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/zh_Hans/
2022-04-21 07:58:39 +02:00
Hillwah
76b290c8b3 Added translation using Weblate (Chinese (Simplified)) 2022-04-21 07:58:39 +02:00
austinried
a92ad7bfc9 Bugfix/large playlist crash (#111)
* get all song coverArt as they are rendered

doing it all up front was too heavy
temporarily disabled mapping artwork in setQueue, need to fix this

* use cache data for track artwork when available

* fix round art in context menu for songs

* set only the first artwork at play time

then set the rest in the playback service

* handle both cached images and fetching images

* remove commented code

* fix shuffle

fix first thumbnail not being updated on shuffle for now playing background
2022-04-21 14:58:35 +09:00
austinried
1944add558 disable/unmount tabs while clearing image cache 2022-04-21 12:32:01 +09:00
austinried
05e4b46469 fix context menu i18n & view actions 2022-04-21 11:16:28 +09:00
austinried
00652952d8 remove CHECK_LICENSE permission
seems to have been added by react-native-blob-util
2022-04-19 12:55:47 +09:00
retiolus
83864217f9 Translated using Weblate (Catalan)
Currently translated at 89.5% (60 of 67 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/ca/
2022-04-19 10:30:08 +09:00
retiolus
b3ab75699e Added translation using Weblate (Catalan) 2022-04-19 10:30:08 +09:00
Saverio Napolitano
5cde911113 Translated using Weblate (Italian)
Currently translated at 100.0% (67 of 67 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/it/
2022-04-19 10:30:08 +09:00
Saverio Napolitano
7fda50857f Added translation using Weblate (Italian) 2022-04-19 10:30:08 +09:00
austinried
4ab51ea11a Update issue templates 2022-04-19 10:02:51 +09:00
Austin Riedhammer
fcd5c1b167 Translated using Weblate (Japanese)
Currently translated at 28.3% (19 of 67 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/ja/
2022-04-17 15:06:51 +09:00
austinried
2ccb397164 Merge branch 'main' of github.com:austinried/subtracks into main 2022-04-16 20:20:55 +09:00
Weblate (bot)
4e3a3133d7 Translations update from Hosted Weblate (#103)
* Translated using Weblate (German)

Currently translated at 97.0% (65 of 67 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/de/

* Translated using Weblate (German)

Currently translated at 100.0% (67 of 67 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/de/

Co-authored-by: Sargon <Sargon_isa@hotmail.de>
2022-04-16 20:16:59 +09:00
Sargon
2edd3a73fd Translated using Weblate (German)
Currently translated at 100.0% (67 of 67 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/de/
2022-04-16 11:38:38 +02:00
Sargon
4855043cda Translated using Weblate (German)
Currently translated at 97.0% (65 of 67 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/de/
2022-04-16 11:38:38 +02:00
austinried
e6e997e4b5 fix plurals falling back to en when no count 2022-04-16 18:38:22 +09:00
austinried
c78fc65279 fix empty strings in nb-NO
(i don't know how to pluralize these though, just placeholders)
2022-04-16 18:06:59 +09:00
austinried
52e95dc959 don't use i18n namespaces
there's no need to keep reloading different parts of the object we already cached
2022-04-16 18:06:06 +09:00
austinried
b8948fb646 fix norwegian language not being selected
use BCP langauge codes for file names
2022-04-16 17:41:36 +09:00
austinried
a91ac29626 Merge remote-tracking branch 'weblate/main' into main 2022-04-16 17:16:19 +09:00
Weblate (bot)
aca677a432 Translations update from Hosted Weblate (#102)
* Added translation using Weblate (German)

* Translated using Weblate (Norwegian Bokmål)

Currently translated at 98.5% (66 of 67 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/nb_NO/

* Translated using Weblate (French)

Currently translated at 100.0% (67 of 67 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/fr/

* Translated using Weblate (Russian)

Currently translated at 95.5% (64 of 67 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/ru/

* Translated using Weblate (German)

Currently translated at 94.0% (63 of 67 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/de/

Co-authored-by: Sargon <Sargon_isa@hotmail.de>
Co-authored-by: Allan Nordhøy <epost@anotheragency.no>
Co-authored-by: Clyhtsuriva <aimeric@adjutor.xyz>
Co-authored-by: Nikita Epifanov <nikgreens@protonmail.com>
2022-04-16 17:10:23 +09:00
Sargon
708a404a21 Translated using Weblate (German)
Currently translated at 94.0% (63 of 67 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/de/
2022-04-16 10:01:49 +02:00
Nikita Epifanov
7fa861d609 Translated using Weblate (Russian)
Currently translated at 95.5% (64 of 67 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/ru/
2022-04-16 10:01:49 +02:00
Clyhtsuriva
5a201c783f Translated using Weblate (French)
Currently translated at 100.0% (67 of 67 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/fr/
2022-04-16 10:01:49 +02:00
Allan Nordhøy
f98ed31475 Translated using Weblate (Norwegian Bokmål)
Currently translated at 98.5% (66 of 67 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/nb_NO/
2022-04-16 10:01:49 +02:00
Sargon
6ebf1d265e Added translation using Weblate (German) 2022-04-16 10:01:49 +02:00
austinried
07c4d14adf don't require build for i18n file PRs 2022-04-16 17:01:39 +09:00
Weblate (bot)
6b1b4c2c4f Added translation using Weblate (Russian) (#101)
Co-authored-by: Nikita Epifanov <nikgreens@protonmail.com>
2022-04-15 22:49:15 +09:00
dependabot[bot]
658d134f64 Bump async from 2.6.3 to 2.6.4 (#100)
Bumps [async](https://github.com/caolan/async) from 2.6.3 to 2.6.4.
- [Release notes](https://github.com/caolan/async/releases)
- [Changelog](https://github.com/caolan/async/blob/v2.6.4/CHANGELOG.md)
- [Commits](https://github.com/caolan/async/compare/v2.6.3...v2.6.4)

---
updated-dependencies:
- dependency-name: async
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-04-15 14:02:22 +09:00
austinried
a9dbcfb69d add edit server string i18n
set add/edit header title with i18n
fix albums plural in artist view
2022-04-15 12:55:11 +09:00
austinried
860a4cec16 Localization support (#99)
* basic i18n poc

* translate home, filters, tabs

support dot notation in backend for namespaces

* i18n context menu, artist filters, list controls

also nothings here
fix backend not caching fallback

* i18n queue, artist view, search/results

* i18n settings and server view

* Added translation using Weblate (Norwegian Bokmål)

* Translated using Weblate (Norwegian Bokmål)

Currently translated at 100.0% (6 of 6 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/nb_NO/

* Update translation files

Updated by "Cleanup translation files" hook in Weblate.

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/

* Update translation files

Updated by "Cleanup translation files" hook in Weblate.

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/

* Update translation files

Updated by "Cleanup translation files" hook in Weblate.

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/

* fix url escaping

* added some mostly naive text overflow fixes

rewrote filter context menu as a slide in because the old one apparently can't handle dynamic width

* Added translation using Weblate (French)

* Translated using Weblate (French)

Currently translated at 17.4% (11 of 63 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/fr/

* Translated using Weblate (French)

Currently translated at 19.0% (12 of 63 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/fr/

* Translated using Weblate (French)

Currently translated at 40.0% (26 of 65 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/fr/

* add weblate and some pretty badges to readme

* fix link

* Translated using Weblate (French)

Currently translated at 50.7% (33 of 65 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/fr/

* Translated using Weblate (English)

Currently translated at 100.0% (65 of 65 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/en/

* Translated using Weblate (French)

Currently translated at 90.7% (59 of 65 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/fr/

* i18n now playing context type

fix overscroll on new filter menu
fix getting default namespace from the i18n backend

* Translated using Weblate (French)

Currently translated at 96.9% (63 of 65 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/fr/

* Translated using Weblate (French)

Currently translated at 100.0% (66 of 66 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/fr/

* Translated using Weblate (Japanese) (#98)

Currently translated at 7.5% (5 of 66 strings)

Translation: Subtracks/subtracks
Translate-URL: https://hosted.weblate.org/projects/subtracks/subtracks/ja/

Co-authored-by: Austin Riedhammer <austinried@functionkey.xyz>

* little note to remind me why that's there

* update licenses

Co-authored-by: Allan Nordhøy <epost@anotheragency.no>
Co-authored-by: Hosted Weblate <hosted@weblate.org>
Co-authored-by: Clyhtsuriva <aimeric@adjutor.xyz>
2022-04-15 12:11:00 +09:00
austinried
4905f75564 Merge branch 'main' of github.com:austinried/subtracks into main 2022-04-12 10:21:37 +09:00
austinried
6b53d9444d bump version 2022-04-12 10:18:33 +09:00
austinried
f39a29159a Fix pausing after playing a few tracks (#94)
we only get this error when playing so we should always keep playing
2022-04-12 09:45:38 +09:00
austinried
c1a4b5ede8 restore repeat mode when rebuilding the queue (#93) 2022-04-12 09:45:10 +09:00
austinried
d0319eb32d remove ruby stuff for iOS 2022-04-11 15:36:18 +09:00
austinried
9524080d00 move back to api 30 2022-04-11 15:15:57 +09:00
austinried
cba32e75b3 downgrade async-storage a bit
some kind of java/jetifier issue in 1.17 that i don't want to deal with
2022-04-11 13:53:11 +09:00
austinried
37d81cb87a update licences 2022-04-11 12:28:33 +09:00
austinried
f911688c78 upgade deps
async-storage 1.17.3: required updating sdk to 31, kotlin to 1.6.10
react-native-track-player 2.1.3: added new "android:exported" prop required by API 31
react-native-fs: 2.19.0
2022-04-11 12:14:45 +09:00
austinried
bfa6b6f08a upgrade to react-native 0.67.4 2022-04-11 11:07:17 +09:00
austinried
87e83516a1 filter topSongs backup search by artistName 2022-04-11 10:47:51 +09:00
austinried
8196704ccd React Query refactor (#91)
* initial react-query experiments

* use queries for item screens

send the data we do have over routing to prepopulate (album/playlist)
use number for starred because sending Date freaks out react-navigation

* add in equiv. song cover art fix

* reorg, switch artistview over

start mapping song cover art when any are available

* refactor useStar to queries

fix caching for starred items and album cover art

* add hook to reset queries on server change

* refactor search to use query

* fix song cover art setting

* use query for artistInfo

* remove last bits of library state

* cleanup

* use query key factory

already fixed one wrong key...

* require coverart size

* let's try no promise queues on these for now

* image cache uses query

* perf fix for playlist parsing

also use placeholder data so we don't have to deal with staleness

* drill that disabled

also list controls doesn't need its own songs hook/copy

* switch to react-native-blob-util for downloads

slightly slower but allows us to use DownloadManager, which backgrounds downloads so they are no longer corrupted when the app suspends

* add a fake "top songs" based on artist search

then sorted by play count/ratings
artistview should load now even if topSongs fails

* try not to swap between topSongs/search on refetch

set queueContext by song list so the index isn't off if the list changes

* add content type validation for file fetching

also try to speed up existing file return by limiting fs ops

* if the HEAD fails, don't queue the download

* clean up params

* reimpl clear image cache

* precompute contextId

prevents wrong "is playing" when any mismatch between queue and list

* clear images from all servers

use external files dir instead of cache

* fix pressable disabled flicker

don't retry topsongs on failure
try to optimize setqueue and fixcoverart a bit

* wait for queries during clear

* break out fetchExistingFile from fetchFile

allows to tell if file is coming from disk or not
only show placeholder/loading spinner if actually fetching image

* forgot these wouldn't do anything with objects

* remove query cache when switching servers

* add content-disposition extension gathering

add support for progress hook (needs native support still)

* added custom RNBU pkg with progress changes

* fully unmount tabs when server changes

prevents unwanted requests, gives fresh start on switch
fix fixCoverArt not re-rendering in certain cases on search

* use serverId from fetch deps

* fix lint

* update licenses

* just use the whole lodash package

* make using cache buster optional
2022-04-11 09:40:51 +09:00
dependabot[bot]
cbd88d0f13 Bump cocoapods-downloader from 1.5.1 to 1.6.3 (#88)
Bumps [cocoapods-downloader](https://github.com/CocoaPods/cocoapods-downloader) from 1.5.1 to 1.6.3.
- [Release notes](https://github.com/CocoaPods/cocoapods-downloader/releases)
- [Changelog](https://github.com/CocoaPods/cocoapods-downloader/blob/master/CHANGELOG.md)
- [Commits](https://github.com/CocoaPods/cocoapods-downloader/compare/1.5.1...1.6.3)

---
updated-dependencies:
- dependency-name: cocoapods-downloader
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-04-06 17:12:10 +09:00
austinried
ecb706310b remove react-native-get-random-values (#87)
swap in react-native-uuid, which is a js-only impl of uuid without native requirements
2022-04-06 01:22:05 +09:00
austinried
caf544069e switch to useSafeAreaInsets().top (#85)
StatusBar.currentHeight seems just broken on some devices
2022-04-04 12:48:10 +09:00
austinried
8bc4caae78 some files still using old folder names 2022-04-03 10:29:23 +09:00
austinried
5a2ab98af5 repeat v1.1.2 changelog for google play 2022-04-01 10:22:23 +09:00
austinried
3ab9ea9fe8 bump version for google play 2022-04-01 10:19:32 +09:00
austinried
b761ad8b84 Release/v1.1.2 (#82)
* add changelog

* increment version
2022-03-28 16:16:48 +09:00
austinried
5169b726ce encode values before using in url (#81) 2022-03-28 15:44:58 +09:00
austinried
41f00ef3f1 update build to main branch
add new ignores
2022-03-28 14:32:08 +09:00
dependabot[bot]
abdd1667b7 Bump ansi-regex from 4.1.0 to 4.1.1 (#80)
Bumps [ansi-regex](https://github.com/chalk/ansi-regex) from 4.1.0 to 4.1.1.
- [Release notes](https://github.com/chalk/ansi-regex/releases)
- [Commits](https://github.com/chalk/ansi-regex/compare/v4.1.0...v4.1.1)

---
updated-dependencies:
- dependency-name: ansi-regex
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-03-28 14:21:17 +09:00
dependabot[bot]
b6c689ea7e Bump minimist from 1.2.5 to 1.2.6 (#79)
Bumps [minimist](https://github.com/substack/minimist) from 1.2.5 to 1.2.6.
- [Release notes](https://github.com/substack/minimist/releases)
- [Commits](https://github.com/substack/minimist/compare/1.2.5...1.2.6)

---
updated-dependencies:
- dependency-name: minimist
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-03-28 14:21:05 +09:00
dependabot[bot]
2c8bcbcb2f Bump plist from 3.0.4 to 3.0.5 (#78)
Bumps [plist](https://github.com/TooTallNate/node-plist) from 3.0.4 to 3.0.5.
- [Release notes](https://github.com/TooTallNate/node-plist/releases)
- [Changelog](https://github.com/TooTallNate/plist.js/blob/master/History.md)
- [Commits](https://github.com/TooTallNate/node-plist/commits)

---
updated-dependencies:
- dependency-name: plist
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-03-28 14:06:20 +09:00
austinried
e412b33d4e run validation before yarn license (#77)
* run validation before yarn license

* attempt to fix CI errors

https://github.com/yarnpkg/yarn/issues/7212
2022-03-28 14:05:49 +09:00
austinried
081251061d Library store refactor (#76)
* start of music store refactor

moving stuff into a state cache
better separate it from view logic

* added paginated list/album list

* reworked fetchAlbumList to remove ui state

refactored home screen to use new method
i broke playing songs somehow, JS thread goes into a loop

* don't reset parts manually, do it all at once

* fixed perf issue related to too many rerenders

rerenders were caused by strict equality check on object/array picks
switched artistInfo to new store
updated zustand and fixed deprecation warnings

* update typescript

and use workspace tsc version for vscode

* remove old artistInfo

* switched to new playlist w/songs

removed more unused stuff

* remove unused + (slightly) rework search

* refactor star

* use only original/large imges for covers/artist

fix view artist from context menu
add loading indicators to song list and artist views (show info we have right away)

* set starred/unstar assuming it works

and correct state on error

* reorg, remove old music slice files

* added back fix for song cover art

* sort artists by localCompare name

* update licenses

* fix now playing background grey bar

* update react-native-gesture-handler

for node-fetch security alert

* fix another gradient height grey bar issue

* update licenses again

* remove thumbnail cache

* rename to remove "Library" from methods

* Revert "remove thumbnail cache"

This reverts commit e0db4931f1.

* use ids for lists, pull state later

* Revert "use only original/large imges for covers/artist"

This reverts commit c9aea9065c.

* deep equal ListItem props for now

this needs a bigger refactor

* use immer as middleware

* refactor api client to use string method

hoping to use this for requestKey/deduping next

* use thumbnails in list items

* Revert "refactor api client to use string method"

This reverts commit 234326135b.

* rename/cleanup

* store servers by id

* get rid of settings selectors

* renames for clarity

remove unused estimateContentLength setting

* remove trackplayer selectors

* fix migration for library filter settings

* fixed shuffle order reporting wrong track/queue

* removed the other selectors

* don't actually need es6/react for our state

* fix slow artist sort on star

localeCompare is too slow for large lists
2022-03-28 13:30:57 +09:00
austinried
09ca4974c5 don't run prepare on yarn install... 2022-03-12 09:24:52 +09:00
austinried
d9781f3a47 add build instructions
add yarn script to prepare exoplayer/ffmpeg
2022-02-02 16:03:05 +09:00
austinried
ec390f593c Upgrade React Native and deps (#68)
* upgrade RN to 0.67-rc.6
upgrade react-native-reanimated to 2.3.1
debug and release building/working

* update to RN stable 0.67

* yarn upgrade

also use xmldom builtin types

* ignore ndk dir for linting

* upgrade types (RN 0.67 not out yet)

* remove deprecated rule

* actually i like that one, keep for now

* update licenses

* upgrade RN types and use builtin dep

* upgrade RN 0.67.1
2022-01-23 13:36:02 +09:00
austinried
6883a556bf fix boolean 2022-01-12 09:25:45 +09:00
Andrej Shadura
100be96fca Fix autocorrect/autofill in server settings (#59) (#60)
Prevent autocorrection on URLs, disable autoCorrect and
autoCapitalise and set importantForAutofill.
2022-01-11 22:08:42 +09:00
austinried
c1e26d23cf reduce api version to lowest currently needed (#53) 2021-12-18 09:50:16 +09:00
austinried
329ef919f7 add .nvmrc for node 14.x 2021-12-15 14:38:15 +09:00
115 changed files with 11941 additions and 4674 deletions

2
.bundle/config Normal file
View File

@@ -0,0 +1,2 @@
BUNDLE_PATH: "vendor/bundle"
BUNDLE_FORCE_RUBY_PLATFORM: 1

View File

@@ -1,6 +1,6 @@
module.exports = { module.exports = {
root: true, root: true,
ignorePatterns: ['submodules/**'], ignorePatterns: ['submodules/**', 'ndk/**'],
extends: '@react-native-community', extends: '@react-native-community',
rules: { rules: {
'@typescript-eslint/no-unused-vars': ['warn'], '@typescript-eslint/no-unused-vars': ['warn'],

32
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,32 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Smartphone (please complete the following information):**
- Device: [e.g. Pixel 4]
- OS: [e.g. Android 12]
- Subtracks version [e.g. 1.2.0]
**Additional context**
Add any other context about the problem here.

View File

@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: enhancement
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

17
.github/release.yml vendored Normal file
View File

@@ -0,0 +1,17 @@
changelog:
exclude:
labels:
- ignore-for-release
- dependencies
authors:
- weblate
categories:
- title: New
labels:
- enhancement
- title: Fixed
labels:
- bug
- title: Other Changes
labels:
- "*"

View File

@@ -4,18 +4,27 @@ on:
push: push:
paths-ignore: paths-ignore:
- assets/** - assets/**
- .vscode/**
- .eslintrc.js
- .prettierrc.js
- BUILDING.md
- README.md - README.md
- LICENSE - LICENSE
branches: branches:
- master - main
- release/* - release/*
pull_request: pull_request:
paths-ignore: paths-ignore:
- assets/** - assets/**
- .vscode/**
- android/app/src/main/assets/custom/i18n/**
- .eslintrc.js
- .prettierrc.js
- BUILDING.md
- README.md - README.md
- LICENSE - LICENSE
branches: branches:
- master - main
jobs: jobs:
build: build:
@@ -24,21 +33,29 @@ jobs:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
with: with:
submodules: recursive submodules: recursive
- run: | - run: |
rm submodules/ExoPlayer/gradle/wrapper/gradle-wrapper.jar rm submodules/ExoPlayer/gradle/wrapper/gradle-wrapper.jar
- uses: gradle/wrapper-validation-action@v1
- uses: actions/setup-node@v2 - uses: actions/setup-node@v2
with: with:
node-version: '14' node-version: '14'
cache: 'yarn' cache: 'yarn'
- run: | - run: |
yarn install yarn install --network-concurrency 1
- run: | - run: |
yarn lint --max-warnings 0 yarn lint --max-warnings 0
- run: | - run: |
yarn license yarn license
- run: | - run: |
scripts/prepare-exoplayer-ffmpeg.sh yarn prepare-build
- uses: gradle/wrapper-validation-action@v1
- uses: gradle/gradle-build-action@v1 - uses: gradle/gradle-build-action@v1
with: with:
distributions-cache-enabled: true distributions-cache-enabled: true
@@ -46,11 +63,14 @@ jobs:
configuration-cache-enabled: true configuration-cache-enabled: true
build-root-directory: android build-root-directory: android
arguments: assembleRelease -PsignReleaseWithDebug=true arguments: assembleRelease -PsignReleaseWithDebug=true
- run: | - run: |
mkdir bin mkdir bin
- run: > - run: >
mv android/app/build/outputs/apk/release/app-release.apk mv android/app/build/outputs/apk/release/app-release.apk
bin/subtracks-${GITHUB_SHA}.apk bin/subtracks-${GITHUB_SHA}.apk
- uses: actions/upload-artifact@v2 - uses: actions/upload-artifact@v2
with: with:
name: subtracks-testing name: subtracks-testing

View File

@@ -12,27 +12,36 @@ jobs:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
with: with:
submodules: recursive submodules: recursive
- run: | - run: |
rm submodules/ExoPlayer/gradle/wrapper/gradle-wrapper.jar rm submodules/ExoPlayer/gradle/wrapper/gradle-wrapper.jar
- uses: gradle/wrapper-validation-action@v1
- uses: actions/setup-node@v2 - uses: actions/setup-node@v2
with: with:
node-version: '14' node-version: '14'
cache: 'yarn' cache: 'yarn'
- name: Get subtracks version - name: Get subtracks version
run: | run: |
echo "SUBTRACKS_VERSION=$(node -e "console.log(require('./package.json').version);")" >> $GITHUB_ENV echo "SUBTRACKS_VERSION=$(node -e "console.log(require('./package.json').version);")" >> $GITHUB_ENV
- run: | - run: |
yarn install yarn install --network-concurrency 1
- run: | - run: |
yarn license yarn license
- run: | - run: |
scripts/prepare-exoplayer-ffmpeg.sh yarn prepare-build
- uses: gradle/wrapper-validation-action@v1
- name: Retrieve keystore file - name: Retrieve keystore file
env: env:
SUBTRACKS_KEYSTORE_BASE64: ${{ secrets.SUBTRACKS_KEYSTORE_BASE64 }} SUBTRACKS_KEYSTORE_BASE64: ${{ secrets.SUBTRACKS_KEYSTORE_BASE64 }}
run: | run: |
echo "$SUBTRACKS_KEYSTORE_BASE64" | base64 --decode > android/app/subtracks.keystore echo "$SUBTRACKS_KEYSTORE_BASE64" | base64 --decode > android/app/subtracks.keystore
- name: Build release APK - name: Build release APK
env: env:
SUBTRACKS_UPLOAD_KEY_PASSWORD: ${{ secrets.SUBTRACKS_UPLOAD_KEY_PASSWORD }} SUBTRACKS_UPLOAD_KEY_PASSWORD: ${{ secrets.SUBTRACKS_UPLOAD_KEY_PASSWORD }}
@@ -44,11 +53,14 @@ jobs:
-PSUBTRACKS_UPLOAD_KEY_ALIAS=subtracks -PSUBTRACKS_UPLOAD_KEY_ALIAS=subtracks
-PSUBTRACKS_UPLOAD_KEY_PASSWORD="$SUBTRACKS_UPLOAD_KEY_PASSWORD" -PSUBTRACKS_UPLOAD_KEY_PASSWORD="$SUBTRACKS_UPLOAD_KEY_PASSWORD"
-PSUBTRACKS_UPLOAD_STORE_PASSWORD="$SUBTRACKS_UPLOAD_STORE_PASSWORD" -PSUBTRACKS_UPLOAD_STORE_PASSWORD="$SUBTRACKS_UPLOAD_STORE_PASSWORD"
- run: | - run: |
mkdir bin mkdir bin
- run: > - run: >
mv android/app/build/outputs/apk/release/app-release.apk mv android/app/build/outputs/apk/release/app-release.apk
bin/subtracks-${SUBTRACKS_VERSION}.apk bin/subtracks-${SUBTRACKS_VERSION}.apk
- name: Build release AAB - name: Build release AAB
env: env:
SUBTRACKS_UPLOAD_KEY_PASSWORD: ${{ secrets.SUBTRACKS_UPLOAD_KEY_PASSWORD }} SUBTRACKS_UPLOAD_KEY_PASSWORD: ${{ secrets.SUBTRACKS_UPLOAD_KEY_PASSWORD }}
@@ -60,9 +72,11 @@ jobs:
-PSUBTRACKS_UPLOAD_KEY_ALIAS=subtracks -PSUBTRACKS_UPLOAD_KEY_ALIAS=subtracks
-PSUBTRACKS_UPLOAD_KEY_PASSWORD="$SUBTRACKS_UPLOAD_KEY_PASSWORD" -PSUBTRACKS_UPLOAD_KEY_PASSWORD="$SUBTRACKS_UPLOAD_KEY_PASSWORD"
-PSUBTRACKS_UPLOAD_STORE_PASSWORD="$SUBTRACKS_UPLOAD_STORE_PASSWORD" -PSUBTRACKS_UPLOAD_STORE_PASSWORD="$SUBTRACKS_UPLOAD_STORE_PASSWORD"
- run: > - run: >
mv android/app/build/outputs/bundle/release/app-release.aab mv android/app/build/outputs/bundle/release/app-release.aab
bin/subtracks-${SUBTRACKS_VERSION}.aab bin/subtracks-${SUBTRACKS_VERSION}.aab
- uses: actions/upload-artifact@v2 - uses: actions/upload-artifact@v2
with: with:
name: subtracks-release name: subtracks-release

1
.gitignore vendored
View File

@@ -28,6 +28,7 @@ build/
.gradle .gradle
local.properties local.properties
*.iml *.iml
*.hprof
# node.js # node.js
# #

1
.nvmrc Normal file
View File

@@ -0,0 +1 @@
14

View File

@@ -1,7 +1,7 @@
module.exports = { module.exports = {
bracketSpacing: true, bracketSpacing: true,
jsxBracketSameLine: true,
singleQuote: true, singleQuote: true,
jsxBracketSameLine: true,
trailingComma: 'all', trailingComma: 'all',
arrowParens: 'avoid', arrowParens: 'avoid',
printWidth: 120, printWidth: 120,

3
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"typescript.tsdk": "node_modules/typescript/lib"
}

59
BUILDING.md Normal file
View File

@@ -0,0 +1,59 @@
# Building from source
Instructions are provided here for Linux, specifically Ubuntu 20.04, but other operating systems should be fine as long as the requirements are met.
## Requirements
### Base
- git
- wget
- unzip
- node.js (14.x)
- yarn (1.x)
### React Native
Subtracks is a React Native application, which means you need to make sure you are set up for that. Follow the guide here to set up your development environment (React Native CLI, not Expo):
https://reactnative.dev/docs/environment-setup
When setting up your environment, make sure to install the following dependency versions:
- Node 14
- Java JDK 11 (tested with openjdk-11-jdk)
### ExoPlayer
We also need the requirements to build ExoPlayer's ffmpeg extension for Android, which should be covered by:
- build-essential (make, etc.)
More information on building ffmpeg can be found here (this is what the `prepare-build` script does):
https://github.com/google/ExoPlayer/tree/r2.11.4/extensions/ffmpeg
## Building
Clone the repository, making sure to recurse submodules, and change into the directory:
```sh
git clone --recursive https://github.com/austinried/subtracks.git
cd subtracks
```
Install the yarn packages and prepare the ExoPlayer ffmpeg extension by running the yarn script:
```sh
yarn install
yarn prepare-build
```
### Debug
In a separate terminal start Metro, which will be an ongoing process that serves javascript bundles to the build:
```sh
yarn start
```
Run the android debug build script, which will start the build and also start your default emulator and push the build to it (or push the build to a running emulator/already connected device):
```sh
yarn android
```
### Release
Similar to the debug build, except we don't need to run Metro first:
```sh
yarn android:release
```
The generated APK will be written to `android/app/build/outputs/apk/release/app-release.apk`

View File

@@ -3,6 +3,8 @@
# #
Subtracks is an Android open source music streaming app for [Subsonic-API-compatible](http://www.subsonic.org/pages/api.jsp) servers ([Subsonic](http://www.subsonic.org/pages/index.jsp), [Navidrome](https://www.navidrome.org/), [Airsonic](https://airsonic.github.io/), and more). It's designed to give you clean and convenient access to your music in the style of modern media players. Subtracks is an Android open source music streaming app for [Subsonic-API-compatible](http://www.subsonic.org/pages/api.jsp) servers ([Subsonic](http://www.subsonic.org/pages/index.jsp), [Navidrome](https://www.navidrome.org/), [Airsonic](https://airsonic.github.io/), and more). It's designed to give you clean and convenient access to your music in the style of modern media players.
[![Translation status](https://hosted.weblate.org/widgets/subtracks/-/subtracks/svg-badge.svg)](https://hosted.weblate.org/engage/subtracks/) ![GitHub Workflow Status (branch)](https://img.shields.io/github/workflow/status/austinried/subtracks/build-release-debugsign/main) ![GitHub release (latest SemVer)](https://img.shields.io/github/v/release/austinried/subtracks?label=github) ![F-Droid](https://img.shields.io/f-droid/v/com.subtracks)
# Screenshots # Screenshots
<p float="left"> <p float="left">
<img src="metadata/en-US/images/phoneScreenshots/01_home.png" alt="home" width="200"/> <img src="metadata/en-US/images/phoneScreenshots/01_home.png" alt="home" width="200"/>
@@ -42,3 +44,13 @@ Subtracks is an Android open source music streaming app for [Subsonic-API-compat
- Multi-select actions - Multi-select actions
- Performance & animation improvements - Performance & animation improvements
- More shuffle play modes - More shuffle play modes
# Building
See [Building from source](BUILDING.md).
# Translations
Want to see Subtracks in your language? Visit the project on [Weblate](https://hosted.weblate.org/engage/subtracks/) to help!
<a href="https://hosted.weblate.org/engage/subtracks/">
<img src="https://hosted.weblate.org/widgets/subtracks/-/subtracks/multi-auto.svg" alt="Translation status" />
</a>

View File

@@ -134,8 +134,8 @@ android {
applicationId "com.subtracks" applicationId "com.subtracks"
minSdkVersion rootProject.ext.minSdkVersion minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 5 versionCode 9
versionName '1.1.1' versionName '1.3.0'
} }
splits { splits {
abi { abi {

View File

@@ -10,3 +10,7 @@
# Add any project specific keep options here: # Add any project specific keep options here:
-keep class com.facebook.react.turbomodule.** { *; } -keep class com.facebook.react.turbomodule.** { *; }
# react-native-reanimated
# https://github.com/software-mansion/react-native-reanimated/pull/2725
-keep class com.swmansion.** {*;}

View File

@@ -2,6 +2,7 @@
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission tools:node="remove" android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission tools:node="remove" android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission tools:node="remove" android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission tools:node="remove" android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission tools:node="remove" android:name="com.android.vending.CHECK_LICENSE"/>
<application android:name=".MainApplication" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:allowBackup="false" android:theme="@style/AppTheme" android:usesCleartextTraffic="true" android:networkSecurityConfig="@xml/network_security_config"> <application android:name=".MainApplication" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:allowBackup="false" android:theme="@style/AppTheme" android:usesCleartextTraffic="true" android:networkSecurityConfig="@xml/network_security_config">
<activity android:name=".MainActivity" android:label="@string/app_name" android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode" android:launchMode="singleTask" android:windowSoftInputMode="adjustPan"> <activity android:name=".MainActivity" android:label="@string/app_name" android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode" android:launchMode="singleTask" android:windowSoftInputMode="adjustPan">
<intent-filter> <intent-filter>

View File

@@ -0,0 +1,152 @@
{
"resources": {
"album": {
"lists": {
"newest": "Afegit recentment",
"sort": "Ordenar els àlbums",
"random": "Aleatori",
"byGenre": "Per gènere",
"alphabeticalByName": "Pel nom",
"alphabeticalByArtist": "Per artista",
"byYear": "Per any",
"frequent": "Escoltat freqüentment",
"recent": "Reproduït recentment",
"starred": "Favorits"
},
"actions": {
"play": "Reproduir l'àlbum",
"view": "Veure l'àlbum"
},
"name": "Àlbum",
"name_plural": "Àlbums"
},
"artist": {
"lists": {
"sort": "Ordenar els artistes",
"starred": "Preferits",
"alphabeticalByName": "Pel nom",
"random": "Aleatori"
},
"name": "Artista",
"name_plural": "Artistes",
"actions": {
"view": "Veure l'artista"
}
},
"queue": {
"name": "Cua",
"name_plural": "Cues"
},
"song": {
"name": "Cançó",
"name_plural": "Cançons",
"lists": {
"artistTopSongs": "Millors cançons"
}
},
"playlist": {
"actions": {
"play": "Reproduir la llista de reproducció"
},
"name": "Playlist",
"name_plural": "Playlists"
}
},
"context": {
"actions": {
"unstar": "Eliminar dels preferits",
"star": "Afegir als favorits"
}
},
"navigation": {
"tabs": {
"home": "Inici",
"search": "Cercar",
"library": "Biblioteca",
"settings": "Paràmetres"
}
},
"messages": {
"nothingHere": "Aquí no hi ha res…"
},
"settings": {
"servers": {
"fields": {
"username": "Nom dusuari",
"password": "Contrasenya",
"address": "Adreça"
},
"options": {
"forcePlaintextPassword": {
"title": "Forçar la contrasenya de text sense format",
"descriptionOn": "Enviar la contrasenya en text sense format (llegat, assegura't que la teva connexió sigui segura!)",
"descriptionOff": "Enviar la contrasenya com a fitxa + sal"
}
},
"actions": {
"add": "Afegir un servidor",
"testConnection": "Comprovar la connexió",
"save": "Desar",
"edit": "Editar el servidor",
"delete": "Esborrar"
},
"messages": {
"connectionOk": "Connexió a {{address}} OK!",
"connectionFailed": "La connexió a {{address}} ha fallat, comprova la configuració o el servidor"
},
"name": "Servidors"
},
"network": {
"name": "Xarxa",
"values": {
"seconds": "{{value}} segons",
"kbps": "{{value}}kbit/s",
"unlimitedKbps": "Il·limitat"
},
"options": {
"maxBuffer": {
"title": "Temps màxim de buffer"
},
"maxBitrateWifi": {
"title": "Taxa de bits màxima (Wi-Fi)"
},
"maxBitrateMobile": {
"title": "Taxa de bits màxima (mòbil)"
},
"minBuffer": {
"title": "Temps mínim de buffer"
}
}
},
"music": {
"options": {
"scrobble": {
"title": "Capturar la lectura",
"descriptionOn": "Capturar l'historial de reproduccions",
"descriptionOff": "No capturar l'historial de reproducció"
}
},
"name": "Música"
},
"reset": {
"name": "Reinicialitzar",
"actions": {
"clearImageCache": "Esborrar la memòria cau d'imatges"
}
},
"about": {
"name": "Quant a",
"version": "versió {{version}}",
"actions": {
"projectHomepage": "Pàgina d'inici del projecte",
"licenses": "Llicències"
}
}
},
"search": {
"nowPlayingContext": "Resultats de la cerca",
"inputPlaceholder": "Cercar",
"moreResults": "Més…",
"headerTitle": "Cercar: {{query}}"
}
}

View File

@@ -0,0 +1,92 @@
{
"resources": {
"album": {
"lists": {
"byGenre": "Efter genre",
"alphabeticalByName": "Efter navn",
"alphabeticalByArtist": "Efter kunstner",
"byYear": "Efter år",
"sort": "Sortér albums"
},
"actions": {
"play": "Afspil album",
"view": "Se album"
}
},
"artist": {
"name": "Kunstner",
"name_plural": "Kunstnere",
"lists": {
"sort": "Sortér kunstnere",
"alphabeticalByName": "Efter navn"
},
"actions": {
"view": "Se kunstnere"
}
},
"song": {
"lists": {
"artistTopSongs": "Top sange"
},
"name": "Sang",
"name_plural": "Sange"
}
},
"navigation": {
"tabs": {
"library": "Bibliotek",
"search": "Søg",
"settings": "Indstillinger"
}
},
"search": {
"inputPlaceholder": "Søg",
"headerTitle": "Søg: {{query}}",
"nowPlayingContext": "Søgeresultater",
"moreResults": "Mere…"
},
"settings": {
"servers": {
"name": "Servere",
"fields": {
"address": "Adresse",
"username": "Brugernavn",
"password": "Adgangskode"
},
"actions": {
"add": "Tilføj server",
"edit": "Redigér server",
"testConnection": "Test forbindelse",
"delete": "Slet",
"save": "Gem"
},
"messages": {
"connectionOk": "Forbindelse til {{address}} OK!"
}
},
"network": {
"name": "Netværk",
"values": {
"kbps": "{{value}}kbps",
"unlimitedKbps": "Ubegrænset",
"seconds": "{{value}} sekunder"
}
},
"music": {
"name": "Musik"
},
"reset": {
"name": "Nulstil",
"actions": {
"clearImageCache": "Ryd billede cache"
}
},
"about": {
"name": "Omkring",
"version": "version {{version}}",
"actions": {
"licenses": "Licenser"
}
}
}
}

View File

@@ -0,0 +1,152 @@
{
"resources": {
"song": {
"lists": {
"artistTopSongs": "Top Lieder"
},
"name": "Lied",
"name_plural": "Lieder"
},
"album": {
"name": "Album",
"name_plural": "Alben",
"lists": {
"sort": "Alben sortieren",
"random": "Zufällig",
"frequent": "Häufig abgespielt",
"recent": "Kürzlich abgespielt",
"starred": "Favoriten",
"byYear": "Nach Jahr",
"byGenre": "Nach Genre",
"alphabeticalByName": "Nach Name",
"newest": "Kürzlich hinzugefügt",
"alphabeticalByArtist": "Nach Interpreten"
},
"actions": {
"play": "Album abspielen",
"view": "Album anzeigen"
}
},
"artist": {
"name": "Interpret",
"name_plural": "Interpreten",
"lists": {
"sort": "Interpreten sortieren",
"random": "Zufällig",
"alphabeticalByName": "Nach Name",
"starred": "Favoriten"
},
"actions": {
"view": "Interpret anzeigen"
}
},
"playlist": {
"name": "Wiedergabeliste",
"name_plural": "Wiedergabelisten",
"actions": {
"play": "Wiedergabeliste abspielen"
}
},
"queue": {
"name": "Warteschlange",
"name_plural": "Warteschlangen"
}
},
"context": {
"actions": {
"star": "Markieren",
"unstar": "Markierung entfernen"
}
},
"navigation": {
"tabs": {
"home": "Startseite",
"library": "Bibliothek",
"search": "Suche",
"settings": "Einstellungen"
}
},
"search": {
"inputPlaceholder": "Suche",
"headerTitle": "Suche: {{query}}",
"nowPlayingContext": "Suchergebnis",
"moreResults": "Mehr…"
},
"settings": {
"servers": {
"fields": {
"address": "Adresse",
"password": "Passwort",
"username": "Nutzername"
},
"options": {
"forcePlaintextPassword": {
"title": "Erzwinge Klartextpasswort",
"descriptionOn": "Passwort als Klartext senden (Veraltet, stellen Sie sicher, dass Ihre Verbindung sicher ist!)",
"descriptionOff": "Sende Passwort als Token + Salt"
}
},
"actions": {
"add": "Server hinzufügen",
"edit": "Server bearbeiten",
"testConnection": "Verbindung testen",
"delete": "Löschen",
"save": "Speichern"
},
"messages": {
"connectionOk": "Verbindung zu {{address}} ist OK!",
"connectionFailed": "Verbindung zu {{address}} fehlgeschlagen, überprüfe Einstellungen oder Server"
},
"name": "Server"
},
"network": {
"name": "Netzwerk",
"values": {
"kbps": "{{value}}kbps",
"unlimitedKbps": "Unbegrenzt",
"seconds": "{{value}} Sekunden"
},
"options": {
"maxBitrateWifi": {
"title": "Maximale Bitrate (WLAN)"
},
"maxBuffer": {
"title": "Maxilmale Pufferzeit"
},
"minBuffer": {
"title": "Minimale Pufferzeit"
},
"maxBitrateMobile": {
"title": "Maximale Bitrate (Mobil)"
}
}
},
"music": {
"name": "Musik",
"options": {
"scrobble": {
"descriptionOn": "Scrobble Wiedergabeverlauf",
"descriptionOff": "Kein Scrobble für Wiedergabeverlauf",
"title": "Scrobble Wiedergabe"
}
}
},
"reset": {
"name": "Zurücksetzen",
"actions": {
"clearImageCache": "Bildzwischenspeicher löschen"
}
},
"about": {
"name": "Über",
"actions": {
"projectHomepage": "Projektseite",
"licenses": "Lizenzen"
},
"version": "Version {{version}}"
}
},
"messages": {
"nothingHere": "Hier ist nichts…"
}
}

View File

@@ -0,0 +1,152 @@
{
"resources": {
"song": {
"name": "Song",
"name_plural": "Songs",
"lists": {
"artistTopSongs": "Top Songs"
}
},
"album": {
"name": "Album",
"name_plural": "Albums",
"lists": {
"sort": "Sort Albums",
"random": "Random",
"newest": "Recently Added",
"frequent": "Frequently Played",
"recent": "Recently Played",
"starred": "Starred",
"alphabeticalByName": "By Name",
"alphabeticalByArtist": "By Artist",
"byYear": "By Year",
"byGenre": "By Genre"
},
"actions": {
"play": "Play Album",
"view": "View Album"
}
},
"artist": {
"name": "Artist",
"name_plural": "Artists",
"lists": {
"sort": "Sort Artists",
"random": "Random",
"starred": "Starred",
"alphabeticalByName": "By Name"
},
"actions": {
"view": "View Artist"
}
},
"playlist": {
"name": "Playlist",
"name_plural": "Playlists",
"actions": {
"play": "Play Playlist"
}
},
"queue": {
"name": "Queue",
"name_plural": "Queues"
}
},
"context": {
"actions": {
"star": "Star",
"unstar": "Unstar"
}
},
"navigation": {
"tabs": {
"home": "Home",
"library": "Library",
"search": "Search",
"settings": "Settings"
}
},
"messages": {
"nothingHere": "Nothing here…"
},
"search": {
"inputPlaceholder": "Search",
"headerTitle": "Search: {{query}}",
"moreResults": "More…",
"nowPlayingContext": "Search Results"
},
"settings": {
"servers": {
"name": "Servers",
"fields": {
"address": "Address",
"username": "Username",
"password": "Password"
},
"options": {
"forcePlaintextPassword": {
"title": "Force plaintext password",
"descriptionOn": "Send password in plaintext (legacy, make sure your connection is secure!)",
"descriptionOff": "Send password as token + salt"
}
},
"actions": {
"add": "Add Server",
"edit": "Edit Server",
"testConnection": "Test Connection",
"delete": "Delete",
"save": "Save"
},
"messages": {
"connectionOk": "Connection to {{address}} OK!",
"connectionFailed": "Connection to {{address}} failed, check settings or server"
}
},
"network": {
"name": "Network",
"values": {
"kbps": "{{value}}kbps",
"unlimitedKbps": "Unlimited",
"seconds": "{{value}} seconds"
},
"options": {
"maxBitrateWifi": {
"title": "Maximum bitrate (Wi-Fi)"
},
"maxBitrateMobile": {
"title": "Maximum bitrate (mobile)"
},
"minBuffer": {
"title": "Minimum buffer time"
},
"maxBuffer": {
"title": "Maximum buffer time"
}
}
},
"music": {
"name": "Music",
"options": {
"scrobble": {
"title": "Scrobble plays",
"descriptionOn": "Scrobble play history",
"descriptionOff": "Don't scrobble play history"
}
}
},
"reset": {
"name": "Reset",
"actions": {
"clearImageCache": "Clear Image Cache"
}
},
"about": {
"name": "About",
"version": "version {{version}}",
"actions": {
"projectHomepage": "Project Homepage",
"licenses": "Licenses"
}
}
}
}

View File

@@ -0,0 +1,152 @@
{
"resources": {
"album": {
"name": "Album",
"name_plural": "Albums",
"lists": {
"random": "Aléatoire",
"newest": "Récemment Ajouté",
"frequent": "Fréquemment Joué",
"recent": "Récemment Joué",
"alphabeticalByName": "Par Nom",
"byYear": "Par Année",
"alphabeticalByArtist": "Par Artiste",
"byGenre": "Par Genre",
"starred": "Favoris",
"sort": "Trier les albums"
},
"actions": {
"play": "Jouer l'album",
"view": "Voir l'album"
}
},
"song": {
"name": "Chanson",
"name_plural": "Chansons",
"lists": {
"artistTopSongs": "Meilleures Chansons"
}
},
"artist": {
"name": "Artiste",
"name_plural": "Artistes",
"lists": {
"random": "Aléatoire",
"starred": "Favoris",
"alphabeticalByName": "Par Nom",
"sort": "Trier les artistes"
},
"actions": {
"view": "Voir l'artiste"
}
},
"playlist": {
"actions": {
"play": "Lire la playlist"
},
"name": "Playlist",
"name_plural": "Playlists"
},
"queue": {
"name": "File d'attente",
"name_plural": "Files d'attente"
}
},
"settings": {
"network": {
"values": {
"seconds": "{{value}} secondes",
"unlimitedKbps": "Illimité",
"kbps": "{{value}}kbit/s"
},
"options": {
"maxBitrateWifi": {
"title": "Débit binaire maximum (Wi-Fi)"
},
"maxBitrateMobile": {
"title": "Débit binaire maximum (mobile)"
},
"maxBuffer": {
"title": "Temps maximum en mémoire tampon"
},
"minBuffer": {
"title": "Temps minimum en mémoire tampon"
}
},
"name": "Réseau"
},
"servers": {
"fields": {
"username": "Nom d'utilisateur",
"address": "Adresse",
"password": "Mot de passe"
},
"actions": {
"testConnection": "Tester la connexion",
"add": "Ajouter un serveur",
"delete": "Supprimer",
"save": "Sauvegarder",
"edit": "Modifier le serveur"
},
"name": "Serveurs",
"options": {
"forcePlaintextPassword": {
"title": "Forcer le mot de passe en texte clair",
"descriptionOn": "Envoyer le mot de passe en test clair (héritage, assurez-vous que la connexion est sécurisée !)",
"descriptionOff": "Envoyer le mot de passe sous forme de jeton + salage"
}
},
"messages": {
"connectionOk": "Connexion à {{address}} OK !",
"connectionFailed": "Échec de la connexion à {{address}}, vérifiez les paramètres ou le serveur"
}
},
"music": {
"name": "Musique",
"options": {
"scrobble": {
"descriptionOff": "Ne pas scrobbler l'historique de lecture",
"descriptionOn": "Scrobbler l'historique de lecture",
"title": "Scrobbler la lecture"
}
}
},
"about": {
"version": "version {{version}}",
"name": "À propos",
"actions": {
"licenses": "Licenses",
"projectHomepage": "Page d'accueil du projet"
}
},
"reset": {
"actions": {
"clearImageCache": "Vider le cache d'images"
},
"name": "Réinitialiser"
}
},
"navigation": {
"tabs": {
"library": "Bibliothèque",
"home": "Accueil",
"search": "Recherche",
"settings": "Paramètres"
}
},
"search": {
"headerTitle": "Recherche : {{query}}",
"inputPlaceholder": "Recherche",
"moreResults": "Plus…",
"nowPlayingContext": "Résultats de recherche"
},
"context": {
"actions": {
"star": "Mettre en favoris",
"unstar": "Enlever des favoris"
}
},
"messages": {
"nothingHere": "Rien ici…"
}
}

View File

@@ -0,0 +1,152 @@
{
"resources": {
"artist": {
"name": "Artista",
"name_plural": "Artisti",
"actions": {
"view": "Vedi artista"
},
"lists": {
"random": "Casuale",
"starred": "Preferiti",
"sort": "Ordina artisti",
"alphabeticalByName": "Per nome"
}
},
"song": {
"lists": {
"artistTopSongs": "Brani più popolari"
},
"name": "Brano",
"name_plural": "Brani"
},
"album": {
"name": "Album",
"name_plural": "Album",
"lists": {
"random": "Casuale",
"newest": "Aggiunti di recente",
"recent": "Ascoltati di recente",
"alphabeticalByName": "Per nome",
"alphabeticalByArtist": "Per artista",
"byYear": "Per anno",
"byGenre": "Per genere",
"sort": "Ordina album",
"frequent": "Ascoltati frequentemente",
"starred": "Preferiti"
},
"actions": {
"play": "Riproduci album",
"view": "Vedi album"
}
},
"playlist": {
"name": "Playlist",
"name_plural": "Playlist",
"actions": {
"play": "Riproduci playlist"
}
},
"queue": {
"name": "Coda",
"name_plural": "Code"
}
},
"settings": {
"servers": {
"fields": {
"password": "Password",
"address": "Indirizzo",
"username": "Nome utente"
},
"options": {
"forcePlaintextPassword": {
"title": "Forza password in chiaro",
"descriptionOn": "Invia password in chiaro (deprecato, assicurati che la tua connessione sia sicura!)",
"descriptionOff": "Invia la password come token + salt"
}
},
"actions": {
"delete": "Rimuovi",
"edit": "Modifica server",
"add": "Aggiungi server",
"save": "Salva",
"testConnection": "Prova connessione"
},
"name": "Server",
"messages": {
"connectionOk": "Connesso a {{address}} con successo!",
"connectionFailed": "Connessione a {{address}} fallita, controlla le impostazioni o il server"
}
},
"network": {
"name": "Rete",
"values": {
"kbps": "{{value}}kbps",
"unlimitedKbps": "Illimitato",
"seconds": "{{value}} secondi"
},
"options": {
"maxBitrateWifi": {
"title": "Bitrate massimo (Wi-Fi)"
},
"maxBitrateMobile": {
"title": "Bitrate massimo (rete dati)"
},
"minBuffer": {
"title": "Tempo di buffer minimo"
},
"maxBuffer": {
"title": "Tempo di buffer massimo"
}
}
},
"music": {
"name": "Musica",
"options": {
"scrobble": {
"title": "Scrobbling delle riproduzioni",
"descriptionOn": "Scrobbling della cronologia di ascolto",
"descriptionOff": "Non eseguire lo scrobbling della cronologia d'ascolto"
}
}
},
"reset": {
"name": "Reimposta",
"actions": {
"clearImageCache": "Pulisci la cache delle immagini"
}
},
"about": {
"name": "Informazioni",
"version": "versione {{version}}",
"actions": {
"projectHomepage": "Pagina principale del progetto",
"licenses": "Licenze"
}
}
},
"context": {
"actions": {
"star": "Aggiungi ai preferiti",
"unstar": "Rimuovi dai preferiti"
}
},
"navigation": {
"tabs": {
"home": "Home",
"library": "Libreria",
"search": "Cerca",
"settings": "Impostazioni"
}
},
"messages": {
"nothingHere": "Non c'è niente qui…"
},
"search": {
"inputPlaceholder": "Ricerca",
"headerTitle": "Ricerca: {{query}}",
"moreResults": "Mostra di più…",
"nowPlayingContext": "Risultati della ricerca"
}
}

View File

@@ -0,0 +1,55 @@
{
"resources": {
"album": {
"lists": {
"random": "ランダムアルバム",
"frequent": "よく聴くアルバム",
"recent": "最近再生した",
"starred": "星付きアルバム"
},
"name": "アルバム"
},
"song": {
"name": "歌",
"lists": {
"artistTopSongs": "人気曲"
}
},
"artist": {
"name": "アーティスト"
},
"playlist": {
"name": "プレイリスト"
}
},
"navigation": {
"tabs": {
"home": "ホーム",
"library": "ライブラリ",
"search": "検索",
"settings": "設定"
}
},
"search": {
"inputPlaceholder": "検索"
},
"settings": {
"servers": {
"name": "サーバ"
},
"network": {
"name": "ネット"
},
"music": {
"name": "音楽"
},
"reset": {
"name": "リセット"
},
"about": {
"actions": {
"projectHomepage": "ホームページ"
}
}
}
}

View File

@@ -0,0 +1,152 @@
{
"resources": {
"artist": {
"name": "Artist",
"name_plural": "Artister",
"lists": {
"sort": "Sorter artister",
"random": "Tilfeldig",
"starred": "Stjernemerket",
"alphabeticalByName": "Etter navn"
},
"actions": {
"view": "Vis artist"
}
},
"playlist": {
"name": "Spilleliste",
"name_plural": "Spillelister",
"actions": {
"play": "Spill av spilleliste"
}
},
"song": {
"lists": {
"artistTopSongs": "Toppspor"
},
"name": "Spor",
"name_plural": "Spor"
},
"album": {
"name": "Album",
"name_plural": "Album",
"lists": {
"sort": "Sorter album",
"random": "Tilfeldig",
"newest": "Nylig tillagt",
"frequent": "Ofte spilt",
"recent": "Nylig spilt",
"starred": "Stjernemerket",
"alphabeticalByName": "Etter navn",
"alphabeticalByArtist": "Etter artist",
"byYear": "Etter år",
"byGenre": "Etter sjanger"
},
"actions": {
"play": "Spill album",
"view": "Vis album"
}
},
"queue": {
"name": "Kø",
"name_plural": "Køer"
}
},
"settings": {
"servers": {
"actions": {
"add": "Legg til tjener",
"testConnection": "Test tilkobling",
"delete": "Slett",
"save": "Lagre",
"edit": "Rediger tjener"
},
"messages": {
"connectionOk": "Tilkobling til {{address}} OK.",
"connectionFailed": "Tilkobling til {{address}} mislyktes. Sjekk innstillingene eller tjeneren."
},
"name": "Tjenere",
"fields": {
"address": "Adresse",
"username": "Brukernavn",
"password": "Passord"
},
"options": {
"forcePlaintextPassword": {
"title": "Påtving klartekstspassord",
"descriptionOn": "Send passord i klartekst (Foreldet. Forsikre deg om at tilkoblingen er sikker.)",
"descriptionOff": "Send passord som symbol + salt"
}
}
},
"network": {
"name": "Nettverk",
"values": {
"kbps": "{{value}} kbps",
"unlimitedKbps": "Ubegrenset",
"seconds": "{{value}} sekunder"
},
"options": {
"maxBitrateWifi": {
"title": "Maksimal bitrate (Wi-Fi)"
},
"maxBitrateMobile": {
"title": "Maksimal bitrate (mobil)"
},
"minBuffer": {
"title": "Minimal mellomlagringstid"
},
"maxBuffer": {
"title": "Maksimal mellomlagringstid"
}
}
},
"music": {
"name": "Musikk",
"options": {
"scrobble": {
"title": "Sporinfodelingsavspillinger",
"descriptionOn": "Sporinfodelings-avspillinghistorikk",
"descriptionOff": "Ikke utfør sporinfodeling av avspillingshistorikk"
}
}
},
"reset": {
"name": "Tilbakestill",
"actions": {
"clearImageCache": "Tøm bildehurtiglager"
}
},
"about": {
"name": "Om",
"version": "versjon {{version}}",
"actions": {
"projectHomepage": "Prosjekthjemmeside",
"licenses": "Lisenser"
}
}
},
"context": {
"actions": {
"star": "Stjernemerk",
"unstar": "Fjern stjernemerking"
}
},
"navigation": {
"tabs": {
"home": "Hjem",
"library": "Bibliotek",
"search": "Søk",
"settings": "Innstillinger"
}
},
"search": {
"inputPlaceholder": "Søk",
"headerTitle": "Søk: {{query}}",
"moreResults": "Mer …",
"nowPlayingContext": "Søkeresultater"
},
"messages": {
"nothingHere": "Ingenting her …"
}
}

View File

@@ -0,0 +1,157 @@
{
"settings": {
"servers": {
"actions": {
"delete": "Удалить",
"add": "Добавить сервер",
"edit": "Редактировать сервер",
"testConnection": "Проверить подключение",
"save": "Сохранить"
},
"name": "Серверы",
"fields": {
"address": "Адрес",
"username": "Имя пользователя",
"password": "Пароль"
},
"options": {
"forcePlaintextPassword": {
"descriptionOn": "Отправить пароль в виде текста (устарело, убедитесь, что ваше соединение безопасно!)",
"descriptionOff": "Отправить пароль в виде токена",
"title": "Принудительный текстовый пароль"
}
},
"messages": {
"connectionOk": "Подключение к {{address}} установлено!",
"connectionFailed": "Не удалось подключиться к {{address}}, проверьте настройки или сервер"
}
},
"network": {
"name": "Сеть",
"values": {
"kbps": "{{value}} кбит/с",
"unlimitedKbps": "Без ограничений",
"seconds": "{{value}} секунд"
},
"options": {
"maxBitrateWifi": {
"title": "Максимальный битрейт (Wi-Fi)"
},
"maxBitrateMobile": {
"title": "Максимальный битрейт (мобильный интернет)"
},
"minBuffer": {
"title": "Минимальное время буферизации"
},
"maxBuffer": {
"title": "Максимальное время буферизации"
}
}
},
"music": {
"name": "Музыка",
"options": {
"scrobble": {
"title": "Синхронизация воспроизведения",
"descriptionOff": "Не синхронизировать историю воспроизведений",
"descriptionOn": "Синхронизация истории воспроизведения"
}
}
},
"reset": {
"name": "Сброс",
"actions": {
"clearImageCache": "Очистить кэш изображения"
}
},
"about": {
"name": "О Subtracks",
"version": "версия {{version}}",
"actions": {
"projectHomepage": "Сайт проекта",
"licenses": "Лицензии"
}
}
},
"resources": {
"album": {
"name_0": "Альбом",
"name_1": "Альбома",
"name_2": "Альбомов",
"lists": {
"sort": "Сортировка альбомов",
"random": "Случайно",
"newest": "Недавно добавленные",
"frequent": "Часто проигрываемые",
"recent": "Недавно проигранные",
"starred": "Избранные",
"alphabeticalByName": "По имени",
"alphabeticalByArtist": "По исполнителю",
"byYear": "По году",
"byGenre": "По жанру"
},
"actions": {
"play": "Воспроизвести альбом",
"view": "Посмотреть альбом"
}
},
"song": {
"name_0": "Трек",
"name_1": "Трека",
"name_2": "Треков",
"lists": {
"artistTopSongs": "Лучшие треки"
}
},
"artist": {
"name_0": "Исполнитель",
"name_1": "Исполнителя",
"name_2": "Исполнителей",
"lists": {
"sort": "Сортировать исполнителей",
"random": "Случайно",
"starred": "Избранные",
"alphabeticalByName": "По имени"
},
"actions": {
"view": "Посмотреть исполнителя"
}
},
"playlist": {
"name_0": "Плейлист",
"name_1": "Плейлиста",
"name_2": "Плейлистов",
"actions": {
"play": "Воспроизвести плейлист"
}
},
"queue": {
"name_0": "Очередь",
"name_1": "Очереди",
"name_2": "Очередей"
}
},
"context": {
"actions": {
"star": "Избранное",
"unstar": "Убрать из избранного"
}
},
"navigation": {
"tabs": {
"library": "Библиотека",
"search": "Поиск",
"settings": "Настройки",
"home": "Главная"
}
},
"messages": {
"nothingHere": "Здесь ничего нет…"
},
"search": {
"inputPlaceholder": "Поиск",
"headerTitle": "Поиск: {{query}}",
"moreResults": "Больше…",
"nowPlayingContext": "Результаты поиска"
}
}

View File

@@ -0,0 +1,147 @@
{
"context": {
"actions": {
"unstar": "移除收藏",
"star": "收藏"
}
},
"settings": {
"servers": {
"name": "服务器",
"messages": {
"connectionFailed": "连接到 {{address}} 失败,检查设置或服务器",
"connectionOk": "连接到 {{address}} 正常!"
},
"options": {
"forcePlaintextPassword": {
"title": "强制使用明文密码",
"descriptionOn": "密码以明文发送(不推荐,注意链接安全!)",
"descriptionOff": "密码以 token + salt 加密发送"
}
},
"actions": {
"add": "添加服务器",
"testConnection": "测试连接",
"save": "保存",
"edit": "编辑服务器",
"delete": "删除"
},
"fields": {
"password": "密码",
"username": "用户名",
"address": "地址"
}
},
"network": {
"name": "网络",
"values": {
"seconds": "{{value}} 秒",
"kbps": "{{value}}kbps",
"unlimitedKbps": "不限制"
},
"options": {
"maxBitrateMobile": {
"title": "最大比特率 (3G/4G/5G)"
},
"minBuffer": {
"title": "最小缓冲时间"
},
"maxBuffer": {
"title": "最大缓冲时间"
},
"maxBitrateWifi": {
"title": "最大比特率 (Wi-Fi)"
}
}
},
"music": {
"name": "音乐",
"options": {
"scrobble": {
"title": "Scrobble模式",
"descriptionOn": "Scrobble播放历史",
"descriptionOff": "不记录scrobble历史"
}
}
},
"reset": {
"name": "重置",
"actions": {
"clearImageCache": "清除图片缓存"
}
},
"about": {
"name": "关于",
"version": "版本 {{version}}",
"actions": {
"projectHomepage": "项目地址",
"licenses": "许可"
}
}
},
"resources": {
"album": {
"actions": {
"view": "查看专辑",
"play": "播放专辑"
},
"name": "专辑",
"lists": {
"newest": "最近添加",
"frequent": "播放最多",
"alphabeticalByName": "根据名称",
"alphabeticalByArtist": "根据歌手",
"byYear": "根据年份",
"random": "随机",
"sort": "专辑排序",
"recent": "最近播放",
"byGenre": "根据类型",
"starred": "已收藏"
}
},
"playlist": {
"actions": {
"play": "全部播放"
},
"name": "播放列表"
},
"song": {
"name": "歌曲",
"lists": {
"artistTopSongs": "热门歌曲"
}
},
"artist": {
"name": "歌手",
"lists": {
"starred": "已收藏",
"sort": "歌手排序",
"random": "随机",
"alphabeticalByName": "根据名称"
},
"actions": {
"view": "查看歌手"
}
},
"queue": {
"name": "队列"
}
},
"navigation": {
"tabs": {
"home": "首页",
"library": "所有",
"search": "搜索",
"settings": "设置"
}
},
"search": {
"inputPlaceholder": "搜索",
"headerTitle": "搜索: {{query}}",
"moreResults": "更多…",
"nowPlayingContext": "搜索结果"
},
"messages": {
"nothingHere": "什么都没有…"
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -14,6 +14,9 @@ public class MainActivity extends ReactActivity {
return "subtracks"; return "subtracks";
} }
// required by react-native-screens
// "This change is required to avoid crashes related to View state being not persisted consistently across Activity restarts."
// https://reactnavigation.org/docs/getting-started
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(null); super.onCreate(null);

View File

@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2014 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetLeft="@dimen/abc_edit_text_inset_horizontal_material"
android:insetRight="@dimen/abc_edit_text_inset_horizontal_material"
android:insetTop="@dimen/abc_edit_text_inset_top_material"
android:insetBottom="@dimen/abc_edit_text_inset_bottom_material">
<selector>
<!--
This file is a copy of abc_edit_text_material (https://bit.ly/3k8fX7I).
The item below with state_pressed="false" and state_focused="false" causes a NullPointerException.
NullPointerException:tempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)'
<item android:state_pressed="false" android:state_focused="false" android:drawable="@drawable/abc_textfield_default_mtrl_alpha"/>
For more info, see https://bit.ly/3CdLStv (react-native/pull/29452) and https://bit.ly/3nxOMoR.
-->
<item android:state_enabled="false" android:drawable="@drawable/abc_textfield_default_mtrl_alpha"/>
<item android:drawable="@drawable/abc_textfield_activated_mtrl_alpha"/>
</selector>
</inset>

View File

@@ -3,7 +3,7 @@
<!-- Base application theme. --> <!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar"> <style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
<!-- Customize your theme here. --> <!-- Customize your theme here. -->
<item name="android:textColor">#000000</item> <item name="android:editTextBackground">@drawable/rn_edit_text_material</item>
</style> </style>
</resources> </resources>

View File

@@ -2,24 +2,25 @@
buildscript { buildscript {
ext { ext {
buildToolsVersion = "30.0.3" buildToolsVersion = "30.0.2"
minSdkVersion = 21 minSdkVersion = 21
compileSdkVersion = 30 compileSdkVersion = 30
targetSdkVersion = 30 targetSdkVersion = 30
ndkVersion = "20.1.5948944" ndkVersion = "21.4.7075529"
// react-native-async-storage next // react-native-async-storage next
kotlinVersion = '1.4.21' kotlinVersion = '1.4.21'
} }
repositories { repositories {
google() google()
jcenter() mavenCentral()
// jcenter()
maven { maven {
url 'https://plugins.gradle.org/m2/' url 'https://plugins.gradle.org/m2/'
} }
} }
dependencies { dependencies {
classpath("com.android.tools.build:gradle:4.1.0") classpath("com.android.tools.build:gradle:4.2.2")
// NOTE: Do not place your application dependencies here; they belong // NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files // in the individual module build.gradle files
@@ -45,9 +46,24 @@ allprojects {
// Android JSC is installed from npm // Android JSC is installed from npm
url("$rootDir/../node_modules/jsc-android/dist") url("$rootDir/../node_modules/jsc-android/dist")
} }
mavenCentral {
// We don't want to fetch react-native from Maven Central as there are
// older versions over there.
content {
excludeGroup "com.facebook.react"
}
}
google() google()
jcenter()
maven { url 'https://www.jitpack.io' } maven { url 'https://www.jitpack.io' }
// remove jcenter once the following workarounds are no longer needed
jcenter() {
content {
// used by react-native-track-player, can remove once they use a newer exoplayer
includeGroup("com.linkedin.dexmaker")
// used by exoplayer
includeGroup("com.linkedin.dexmaker-mockito")
includeGroup("com.google.android.exoplayer")
}
}
} }
} }

View File

@@ -9,7 +9,7 @@
# Specifies the JVM arguments used for the daemon process. # Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings. # The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m # Default value: -Xmx1024m -XX:MaxPermSize=256m
org.gradle.jvmargs=-Xmx4g -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 org.gradle.jvmargs=-Xmx4g -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode. # When configured, Gradle will run in incubating parallel mode.
@@ -25,7 +25,7 @@ android.useAndroidX=true
android.enableJetifier=true android.enableJetifier=true
# Version of flipper SDK to use with React Native # Version of flipper SDK to use with React Native
FLIPPER_VERSION=0.75.1 FLIPPER_VERSION=0.99.0
# react-native-async-storage next # react-native-async-storage next
AsyncStorage_useNextStorage=true AsyncStorage_useNextStorage=true

View File

@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-all.zip
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists

View File

@@ -4,12 +4,18 @@
license: The Apache Software License, Version 2.0 license: The Apache Software License, Version 2.0
licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt
url: https://developer.android.com/jetpack/androidx url: https://developer.android.com/jetpack/androidx
- artifact: androidx.annotation:annotation-experimental:+
name: annotation-experimental
copyrightHolder: Original Author
license: The Apache Software License, Version 2.0
licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt
url: https://developer.android.com/jetpack/androidx/releases/annotation#1.1.0
- artifact: androidx.annotation:annotation:+ - artifact: androidx.annotation:annotation:+
name: annotation name: annotation
copyrightHolder: Original Author copyrightHolder: Original Author
license: The Apache Software License, Version 2.0 license: The Apache Software License, Version 2.0
licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt
url: http://developer.android.com/tools/extras/support-library.html url: https://developer.android.com/jetpack/androidx/releases/annotation#1.2.0
- artifact: androidx.appcompat:appcompat-resources:+ - artifact: androidx.appcompat:appcompat-resources:+
name: appcompat-resources name: appcompat-resources
copyrightHolder: Original Author copyrightHolder: Original Author
@@ -40,6 +46,12 @@
license: The Apache Software License, Version 2.0 license: The Apache Software License, Version 2.0
licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt
url: http://developer.android.com/tools/extras/support-library.html url: http://developer.android.com/tools/extras/support-library.html
- artifact: androidx.autofill:autofill:+
name: autofill
copyrightHolder: Original Author
license: The Apache Software License, Version 2.0
licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt
url: https://developer.android.com/jetpack/androidx/releases/autofill#1.1.0
- artifact: androidx.cardview:cardview:+ - artifact: androidx.cardview:cardview:+
name: cardview name: cardview
copyrightHolder: Original Author copyrightHolder: Original Author
@@ -58,6 +70,12 @@
license: The Apache Software License, Version 2.0 license: The Apache Software License, Version 2.0
licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt
url: https://developer.android.com/jetpack/androidx url: https://developer.android.com/jetpack/androidx
- artifact: androidx.core:core-ktx:+
name: core-ktx
copyrightHolder: Original Author
license: The Apache Software License, Version 2.0
licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt
url: https://developer.android.com/jetpack/androidx/releases/core#1.6.0
- artifact: androidx.core:core:+ - artifact: androidx.core:core:+
name: core name: core
copyrightHolder: Original Author copyrightHolder: Original Author
@@ -189,19 +207,19 @@
copyrightHolder: Original Author copyrightHolder: Original Author
license: The Apache Software License, Version 2.0 license: The Apache Software License, Version 2.0
licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt
url: https://developer.android.com/topic/libraries/architecture/index.html url: https://developer.android.com/jetpack/androidx/releases/room#2.3.0
- artifact: androidx.room:room-ktx:+ - artifact: androidx.room:room-ktx:+
name: room-ktx name: room-ktx
copyrightHolder: Original Author copyrightHolder: Original Author
license: The Apache Software License, Version 2.0 license: The Apache Software License, Version 2.0
licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt
url: https://developer.android.com/topic/libraries/architecture/index.html url: https://developer.android.com/jetpack/androidx/releases/room#2.3.0
- artifact: androidx.room:room-runtime:+ - artifact: androidx.room:room-runtime:+
name: room-runtime name: room-runtime
copyrightHolder: Original Author copyrightHolder: Original Author
license: The Apache Software License, Version 2.0 license: The Apache Software License, Version 2.0
licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt
url: https://developer.android.com/topic/libraries/architecture/index.html url: https://developer.android.com/jetpack/androidx/releases/room#2.3.0
- artifact: androidx.savedstate:savedstate:+ - artifact: androidx.savedstate:savedstate:+
name: savedstate name: savedstate
copyrightHolder: Original Author copyrightHolder: Original Author
@@ -301,62 +319,104 @@
- artifact: com.facebook.fresco:drawee:+ - artifact: com.facebook.fresco:drawee:+
name: drawee name: drawee
copyrightHolder: Original Author copyrightHolder: Original Author
license: MIT License license: MIT
licenseUrl: https://github.com/facebook/fresco/blob/master/LICENSE licenseUrl: https://github.com/facebook/fresco/blob/master/LICENSE
url: https://github.com/facebook/fresco url: https://github.com/facebook/fresco
- artifact: com.facebook.fresco:fbcore:+ - artifact: com.facebook.fresco:fbcore:+
name: fbcore name: fbcore
copyrightHolder: Original Author copyrightHolder: Original Author
license: MIT License license: MIT
licenseUrl: https://github.com/facebook/fresco/blob/master/LICENSE licenseUrl: https://github.com/facebook/fresco/blob/master/LICENSE
url: https://github.com/facebook/fresco url: https://github.com/facebook/fresco
- artifact: com.facebook.fresco:fresco:+ - artifact: com.facebook.fresco:fresco:+
name: fresco name: fresco
copyrightHolder: Original Author copyrightHolder: Original Author
license: MIT License license: MIT
licenseUrl: https://github.com/facebook/fresco/blob/master/LICENSE licenseUrl: https://github.com/facebook/fresco/blob/master/LICENSE
url: https://github.com/facebook/fresco url: https://github.com/facebook/fresco
- artifact: com.facebook.fresco:imagepipeline-base:+ - artifact: com.facebook.fresco:imagepipeline-base:+
name: imagepipeline-base name: imagepipeline-base
copyrightHolder: Original Author copyrightHolder: Original Author
license: MIT License license: MIT
licenseUrl: https://github.com/facebook/fresco/blob/master/LICENSE
url: https://github.com/facebook/fresco
- artifact: com.facebook.fresco:imagepipeline-native:+
name: imagepipeline-native
copyrightHolder: Original Author
license: MIT
licenseUrl: https://github.com/facebook/fresco/blob/master/LICENSE licenseUrl: https://github.com/facebook/fresco/blob/master/LICENSE
url: https://github.com/facebook/fresco url: https://github.com/facebook/fresco
- artifact: com.facebook.fresco:imagepipeline-okhttp3:+ - artifact: com.facebook.fresco:imagepipeline-okhttp3:+
name: imagepipeline-okhttp3 name: imagepipeline-okhttp3
copyrightHolder: Original Author copyrightHolder: Original Author
license: MIT License license: MIT
licenseUrl: https://github.com/facebook/fresco/blob/master/LICENSE licenseUrl: https://github.com/facebook/fresco/blob/master/LICENSE
url: https://github.com/facebook/fresco url: https://github.com/facebook/fresco
- artifact: com.facebook.fresco:imagepipeline:+ - artifact: com.facebook.fresco:imagepipeline:+
name: imagepipeline name: imagepipeline
copyrightHolder: Original Author copyrightHolder: Original Author
license: MIT License license: MIT
licenseUrl: https://github.com/facebook/fresco/blob/master/LICENSE
url: https://github.com/facebook/fresco
- artifact: com.facebook.fresco:memory-type-ashmem:+
name: memory-type-ashmem
copyrightHolder: Original Author
license: MIT
licenseUrl: https://github.com/facebook/fresco/blob/master/LICENSE
url: https://github.com/facebook/fresco
- artifact: com.facebook.fresco:memory-type-java:+
name: memory-type-java
copyrightHolder: Original Author
license: MIT
licenseUrl: https://github.com/facebook/fresco/blob/master/LICENSE
url: https://github.com/facebook/fresco
- artifact: com.facebook.fresco:memory-type-native:+
name: memory-type-native
copyrightHolder: Original Author
license: MIT
licenseUrl: https://github.com/facebook/fresco/blob/master/LICENSE
url: https://github.com/facebook/fresco
- artifact: com.facebook.fresco:middleware:+
name: middleware
copyrightHolder: Original Author
license: MIT
licenseUrl: https://github.com/facebook/fresco/blob/master/LICENSE licenseUrl: https://github.com/facebook/fresco/blob/master/LICENSE
url: https://github.com/facebook/fresco url: https://github.com/facebook/fresco
- artifact: com.facebook.fresco:nativeimagefilters:+ - artifact: com.facebook.fresco:nativeimagefilters:+
name: nativeimagefilters name: nativeimagefilters
copyrightHolder: Original Author copyrightHolder: Original Author
license: MIT License license: MIT
licenseUrl: https://github.com/facebook/fresco/blob/master/LICENSE licenseUrl: https://github.com/facebook/fresco/blob/master/LICENSE
url: https://github.com/facebook/fresco url: https://github.com/facebook/fresco
- artifact: com.facebook.fresco:nativeimagetranscoder:+ - artifact: com.facebook.fresco:nativeimagetranscoder:+
name: nativeimagetranscoder name: nativeimagetranscoder
copyrightHolder: Original Author copyrightHolder: Original Author
license: MIT License license: MIT
licenseUrl: https://github.com/facebook/fresco/blob/master/LICENSE
url: https://github.com/facebook/fresco
- artifact: com.facebook.fresco:soloader:+
name: soloader
copyrightHolder: Original Author
license: MIT
licenseUrl: https://github.com/facebook/fresco/blob/master/LICENSE
url: https://github.com/facebook/fresco
- artifact: com.facebook.fresco:ui-common:+
name: ui-common
copyrightHolder: Original Author
license: MIT
licenseUrl: https://github.com/facebook/fresco/blob/master/LICENSE licenseUrl: https://github.com/facebook/fresco/blob/master/LICENSE
url: https://github.com/facebook/fresco url: https://github.com/facebook/fresco
- artifact: com.facebook.infer.annotation:infer-annotation:+ - artifact: com.facebook.infer.annotation:infer-annotation:+
name: infer-annotation name: infer-annotation
copyrightHolder: Original Author copyrightHolder: Original Author
license: BSD license license: MIT license
licenseUrl: https://github.com/facebook/infer/blob/master/LICENSE licenseUrl: https://github.com/facebook/infer/blob/master/LICENSE
url: http://fbinfer.com/ url: http://fbinfer.com/
- artifact: com.facebook.react:react-native:+ - artifact: com.facebook.react:react-native:+
name: react-native name: react-native
copyrightHolder: Original Author copyrightHolder: Original Author
license: MIT License license: MIT License
licenseUrl: https://github.com/facebook/react-native/blob/master/LICENSE licenseUrl: https://github.com/facebook/react-native/blob/HEAD/LICENSE
url: https://github.com/facebook/react-native url: https://github.com/facebook/react-native
- artifact: com.facebook.soloader:annotation:+ - artifact: com.facebook.soloader:annotation:+
name: annotation name: annotation
@@ -494,21 +554,21 @@
- artifact: com.squareup.okhttp3:okhttp-urlconnection:+ - artifact: com.squareup.okhttp3:okhttp-urlconnection:+
name: okhttp-urlconnection name: okhttp-urlconnection
copyrightHolder: Original Author copyrightHolder: Original Author
license: Apache-2.0 License license: The Apache Software License, Version 2.0
licenseUrl: https://github.com/square/okhttp/blob/master/LICENSE.txt licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt
url: https://github.com/square/okhttp url: https://square.github.io/okhttp/
- artifact: com.squareup.okhttp3:okhttp:+ - artifact: com.squareup.okhttp3:okhttp:+
name: okhttp name: okhttp
copyrightHolder: Original Author copyrightHolder: Original Author
license: Apache-2.0 License license: The Apache Software License, Version 2.0
licenseUrl: https://github.com/square/okhttp/blob/master/LICENSE.txt licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt
url: https://github.com/square/okhttp url: https://square.github.io/okhttp/
- artifact: com.squareup.okio:okio:+ - artifact: com.squareup.okio:okio:+
name: okio name: okio
copyrightHolder: Original Author copyrightHolder: Original Author
license: Apache-2.0 License license: The Apache Software License, Version 2.0
licenseUrl: https://github.com/square/okio/blob/master/LICENSE.txt licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt
url: https://github.com/square/okio url: https://github.com/square/okio/
- artifact: javax.inject:javax.inject:+ - artifact: javax.inject:javax.inject:+
name: javax.inject name: javax.inject
copyrightHolder: Original Author copyrightHolder: Original Author
@@ -533,6 +593,12 @@
license: The Apache Software License, Version 2.0 license: The Apache Software License, Version 2.0
licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt
url: https://github.com/raphw/byte-buddy url: https://github.com/raphw/byte-buddy
- artifact: org.apache.commons:commons-lang3:+
name: commons-lang3
copyrightHolder: Original Author
license: The Apache Software License, Version 2.0
licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt
url: http://commons.apache.org/lang/
- artifact: org.checkerframework:checker-compat-qual:+ - artifact: org.checkerframework:checker-compat-qual:+
name: checker-compat-qual name: checker-compat-qual
copyrightHolder: Original Author copyrightHolder: Original Author
@@ -563,12 +629,30 @@
license: The Apache License, Version 2.0 license: The Apache License, Version 2.0
licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt
url: https://kotlinlang.org/ url: https://kotlinlang.org/
- artifact: org.jetbrains.kotlin:kotlin-reflect:+
name: kotlin-reflect
copyrightHolder: Original Author
license: The Apache License, Version 2.0
licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt
url: https://kotlinlang.org/
- artifact: org.jetbrains.kotlin:kotlin-stdlib-common:+ - artifact: org.jetbrains.kotlin:kotlin-stdlib-common:+
name: kotlin-stdlib-common name: kotlin-stdlib-common
copyrightHolder: Original Author copyrightHolder: Original Author
license: The Apache License, Version 2.0 license: The Apache License, Version 2.0
licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt
url: https://kotlinlang.org/ url: https://kotlinlang.org/
- artifact: org.jetbrains.kotlin:kotlin-stdlib-jdk7:+
name: kotlin-stdlib-jdk7
copyrightHolder: Original Author
license: The Apache License, Version 2.0
licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt
url: https://kotlinlang.org/
- artifact: org.jetbrains.kotlin:kotlin-stdlib-jdk8:+
name: kotlin-stdlib-jdk8
copyrightHolder: Original Author
license: The Apache License, Version 2.0
licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt
url: https://kotlinlang.org/
- artifact: org.jetbrains.kotlin:kotlin-stdlib:+ - artifact: org.jetbrains.kotlin:kotlin-stdlib:+
name: kotlin-stdlib name: kotlin-stdlib
copyrightHolder: Original Author copyrightHolder: Original Author

View File

@@ -2,22 +2,30 @@ import RootNavigator from '@app/navigation/RootNavigator'
import SplashPage from '@app/screens/SplashPage' import SplashPage from '@app/screens/SplashPage'
import colors from '@app/styles/colors' import colors from '@app/styles/colors'
import React from 'react' import React from 'react'
import { StatusBar, View, StyleSheet } from 'react-native' import { StatusBar, StyleSheet, View } from 'react-native'
import ProgressHook from './components/ProgressHook'
import { useStore } from './state/store'
import { selectTrackPlayer } from './state/trackplayer'
import { MenuProvider } from 'react-native-popup-menu' import { MenuProvider } from 'react-native-popup-menu'
import { QueryClientProvider } from 'react-query'
import ProgressHook from './components/ProgressHook'
import queryClient from './queryClient'
import { useStore } from './state/store'
const Debug = () => { const Debug = () => {
const currentTrack = useStore(selectTrackPlayer.currentTrack) const currentTrackTitle = useStore(store => store.currentTrack?.title)
console.log(currentTrack?.title) console.log('currentTrackTitle', currentTrackTitle)
return <></> return <></>
} }
const App = () => ( const App = () => {
return (
<QueryClientProvider client={queryClient}>
<MenuProvider backHandler={true}> <MenuProvider backHandler={true}>
<View style={styles.appContainer}> <View style={styles.appContainer}>
<StatusBar animated={true} backgroundColor={'rgba(0, 0, 0, 0.3)'} barStyle={'light-content'} translucent={true} /> <StatusBar
animated={true}
backgroundColor={'rgba(0, 0, 0, 0.3)'}
barStyle={'light-content'}
translucent={true}
/>
<SplashPage> <SplashPage>
<ProgressHook /> <ProgressHook />
<Debug /> <Debug />
@@ -25,7 +33,9 @@ const App = () => (
</SplashPage> </SplashPage>
</View> </View>
</MenuProvider> </MenuProvider>
) </QueryClientProvider>
)
}
const styles = StyleSheet.create({ const styles = StyleSheet.create({
appContainer: { appContainer: {

View File

@@ -37,7 +37,7 @@ function BackgroundHeaderFlatList<ItemT>(props: BackgroundHeaderFlatListProp<Ite
</props.BackgroundComponent> </props.BackgroundComponent>
} }
ListHeaderComponentStyle={[headerStyle]} ListHeaderComponentStyle={[headerStyle]}
ListEmptyComponent={<NothingHere style={styles.nothing} />} ListEmptyComponent={props.ListEmptyComponent || <NothingHere style={styles.nothing} />}
/> />
) )
} }

View File

@@ -16,7 +16,13 @@ const Button: React.FC<{
onPress={onPress} onPress={onPress}
disabled={disabled} disabled={disabled}
style={[styles.container, buttonStyle !== undefined ? styles[buttonStyle] : {}, style]}> style={[styles.container, buttonStyle !== undefined ? styles[buttonStyle] : {}, style]}>
{title ? <Text style={styles.text}>{title}</Text> : children} {title ? (
<Text style={styles.text} numberOfLines={2} adjustsFontSizeToFit={true}>
{title}
</Text>
) : (
children
)}
</PressableOpacity> </PressableOpacity>
) )
} }
@@ -26,6 +32,7 @@ const styles = StyleSheet.create({
backgroundColor: colors.accent, backgroundColor: colors.accent,
paddingHorizontal: 10, paddingHorizontal: 10,
minHeight: 42, minHeight: 42,
maxHeight: 42,
justifyContent: 'center', justifyContent: 'center',
borderRadius: 1000, borderRadius: 1000,
}, },
@@ -43,6 +50,7 @@ const styles = StyleSheet.create({
fontFamily: font.bold, fontFamily: font.bold,
color: colors.text.primary, color: colors.text.primary,
paddingHorizontal: 14, paddingHorizontal: 14,
textAlign: 'center',
}, },
}) })

View File

@@ -1,20 +1,19 @@
import PressableOpacity from '@app/components/PressableOpacity' import PressableOpacity from '@app/components/PressableOpacity'
import { useStarred } from '@app/hooks/music' import { useStar } from '@app/hooks/query'
import { AlbumListItem, Artist, Song, StarrableItemType } from '@app/models/music' import { StarrableItemType, Song, Artist, Album } from '@app/models/library'
import { selectMusic } from '@app/state/music'
import { useStore } from '@app/state/store'
import colors from '@app/styles/colors' import colors from '@app/styles/colors'
import font from '@app/styles/font' import font from '@app/styles/font'
import { NavigationProp, useNavigation } from '@react-navigation/native' import { NavigationProp, useNavigation } from '@react-navigation/native'
import { ReactComponentLike } from 'prop-types' import { ReactComponentLike } from 'prop-types'
import React from 'react' import React from 'react'
import { useTranslation } from 'react-i18next'
import { ScrollView, StyleProp, StyleSheet, Text, View, ViewStyle } from 'react-native' import { ScrollView, StyleProp, StyleSheet, Text, View, ViewStyle } from 'react-native'
import { Menu, MenuOption, MenuOptions, MenuTrigger, renderers } from 'react-native-popup-menu' import { Menu, MenuOption, MenuOptions, MenuTrigger, renderers } from 'react-native-popup-menu'
import IconFA from 'react-native-vector-icons/FontAwesome' import IconFA from 'react-native-vector-icons/FontAwesome'
import IconFA5 from 'react-native-vector-icons/FontAwesome5' import IconFA5 from 'react-native-vector-icons/FontAwesome5'
// import IconMat from 'react-native-vector-icons/MaterialIcons'
import CoverArt from './CoverArt' import CoverArt from './CoverArt'
import Star from './Star' import { Star } from './Star'
import { withSuspenseMemo } from './withSuspense'
const { SlideInMenu } = renderers const { SlideInMenu } = renderers
@@ -25,6 +24,7 @@ type ContextMenuProps = {
triggerTouchableStyle?: StyleProp<ViewStyle> triggerTouchableStyle?: StyleProp<ViewStyle>
onPress?: () => any onPress?: () => any
triggerOnLongPress?: boolean triggerOnLongPress?: boolean
disabled?: boolean
} }
type InternalContextMenuProps = ContextMenuProps & { type InternalContextMenuProps = ContextMenuProps & {
@@ -42,6 +42,7 @@ const ContextMenu: React.FC<InternalContextMenuProps> = ({
menuOptions, menuOptions,
children, children,
triggerOnLongPress, triggerOnLongPress,
disabled,
}) => { }) => {
menuStyle = menuStyle || { flex: 1 } menuStyle = menuStyle || { flex: 1 }
triggerWrapperStyle = triggerWrapperStyle || { flex: 1 } triggerWrapperStyle = triggerWrapperStyle || { flex: 1 }
@@ -50,11 +51,12 @@ const ContextMenu: React.FC<InternalContextMenuProps> = ({
return ( return (
<Menu renderer={SlideInMenu} style={menuStyle}> <Menu renderer={SlideInMenu} style={menuStyle}>
<MenuTrigger <MenuTrigger
disabled={disabled}
triggerOnLongPress={triggerOnLongPress === undefined ? true : triggerOnLongPress} triggerOnLongPress={triggerOnLongPress === undefined ? true : triggerOnLongPress}
customStyles={{ customStyles={{
triggerOuterWrapper: triggerOuterWrapperStyle, triggerOuterWrapper: triggerOuterWrapperStyle,
triggerWrapper: triggerWrapperStyle, triggerWrapper: triggerWrapperStyle,
triggerTouchable: { style: triggerTouchableStyle }, triggerTouchable: { style: triggerTouchableStyle, disabled },
TriggerTouchableComponent: PressableOpacity, TriggerTouchableComponent: PressableOpacity,
}} }}
onAlternativeAction={onPress}> onAlternativeAction={onPress}>
@@ -106,7 +108,9 @@ const ContextMenuIconTextOption = React.memo<ContextMenuIconTextOptionProps>(
return ( return (
<ContextMenuOption onSelect={onSelect}> <ContextMenuOption onSelect={onSelect}>
<View style={styles.icon}>{Icon}</View> <View style={styles.icon}>{Icon}</View>
<Text style={styles.optionText}>{text}</Text> <Text style={styles.optionText} numberOfLines={1} adjustsFontSizeToFit={true} minimumFontScale={0.6}>
{text}
</Text>
</ContextMenuOption> </ContextMenuOption>
) )
}, },
@@ -115,15 +119,50 @@ const ContextMenuIconTextOption = React.memo<ContextMenuIconTextOptionProps>(
const MenuHeader = React.memo<{ const MenuHeader = React.memo<{
coverArt?: string coverArt?: string
artistId?: string artistId?: string
albumId?: string
title: string title: string
subtitle?: string subtitle?: string
}>(({ coverArt, artistId, title, subtitle }) => ( }>(({ coverArt, artistId, albumId, title, subtitle }) => {
let CoverArtComponent = <></>
if (artistId) {
CoverArtComponent = (
<CoverArt
type="artist"
artistId={artistId}
style={styles.coverArt}
resizeMode="cover"
round={true}
size="thumbnail"
fadeDuration={0}
/>
)
} else if (albumId) {
CoverArtComponent = (
<CoverArt
type="album"
albumId={albumId}
style={styles.coverArt}
resizeMode="cover"
size="thumbnail"
fadeDuration={0}
/>
)
} else {
CoverArtComponent = (
<CoverArt
type="cover"
coverArt={coverArt}
style={styles.coverArt}
resizeMode="cover"
size="thumbnail"
fadeDuration={0}
/>
)
}
return (
<View style={styles.menuHeader}> <View style={styles.menuHeader}>
{artistId ? ( {CoverArtComponent}
<CoverArt type="artist" artistId={artistId} style={styles.coverArt} resizeMode={'cover'} round={true} />
) : (
<CoverArt type="cover" coverArt={coverArt} style={styles.coverArt} resizeMode={'cover'} />
)}
<View style={styles.menuHeaderText}> <View style={styles.menuHeaderText}>
<Text numberOfLines={1} style={styles.menuTitle}> <Text numberOfLines={1} style={styles.menuTitle}>
{title} {title}
@@ -137,30 +176,33 @@ const MenuHeader = React.memo<{
)} )}
</View> </View>
</View> </View>
)) )
})
const OptionStar = React.memo<{ const OptionStar = withSuspenseMemo<{
id: string id: string
type: StarrableItemType type: StarrableItemType
additionalText?: string additionalText?: string
}>(({ id, type, additionalText: text }) => { }>(({ id, type, additionalText: text }) => {
const starred = useStarred(id, type) const { query, toggle } = useStar(id, type)
const setStarred = useStore(selectMusic.starItem) const { t } = useTranslation()
return ( return (
<ContextMenuIconTextOption <ContextMenuIconTextOption
IconComponentRaw={<Star starred={starred} size={26} />} IconComponentRaw={<Star starred={!!query.data} size={26} />}
text={(starred ? 'Unstar' : 'Star') + (text ? ` ${text}` : '')} text={(query.data ? t('context.actions.unstar') : t('context.actions.star')) + (text ? ` ${text}` : '')}
onSelect={() => setStarred(id, type, starred)} onSelect={() => toggle.mutate()}
/> />
) )
}) })
const OptionViewArtist = React.memo<{ const OptionViewArtist = withSuspenseMemo<{
navigation: NavigationProp<any> navigation: NavigationProp<any>
artist?: string artist?: string
artistId?: string artistId?: string
}>(({ navigation, artist, artistId }) => { }>(({ navigation, artist, artistId }) => {
const { t } = useTranslation()
if (!artist || !artistId) { if (!artist || !artistId) {
return <></> return <></>
} }
@@ -170,17 +212,19 @@ const OptionViewArtist = React.memo<{
IconComponent={IconFA} IconComponent={IconFA}
name="microphone" name="microphone"
size={26} size={26}
text="View Artist" text={t('resources.artist.actions.view')}
onSelect={() => navigation.navigate('artist', { id: artistId, title: artist })} onSelect={() => navigation.navigate('artist', { id: artistId, title: artist })}
/> />
) )
}) })
const OptionViewAlbum = React.memo<{ const OptionViewAlbum = withSuspenseMemo<{
navigation: NavigationProp<any> navigation: NavigationProp<any>
album?: string album?: string
albumId?: string albumId?: string
}>(({ navigation, album, albumId }) => { }>(({ navigation, album, albumId }) => {
const { t } = useTranslation()
if (!album || !albumId) { if (!album || !albumId) {
return <></> return <></>
} }
@@ -190,7 +234,7 @@ const OptionViewAlbum = React.memo<{
IconComponent={IconFA5} IconComponent={IconFA5}
name="compact-disc" name="compact-disc"
size={26} size={26}
text="View Album" text={t('resources.album.actions.view')}
onSelect={() => navigation.navigate('album', { id: albumId, title: album })} onSelect={() => navigation.navigate('album', { id: albumId, title: album })}
/> />
) )
@@ -203,7 +247,7 @@ const OptionViewAlbum = React.memo<{
// )) // ))
export type AlbumContextPressableProps = ContextMenuProps & { export type AlbumContextPressableProps = ContextMenuProps & {
album: AlbumListItem album: Album
} }
export const AlbumContextPressable: React.FC<AlbumContextPressableProps> = props => { export const AlbumContextPressable: React.FC<AlbumContextPressableProps> = props => {
@@ -237,7 +281,7 @@ export const SongContextPressable: React.FC<SongContextPressableProps> = props =
return ( return (
<ContextMenu <ContextMenu
{...props} {...props}
menuHeader={<MenuHeader title={song.title} subtitle={song.artist} coverArt={song.coverArt} />} menuHeader={<MenuHeader title={song.title} subtitle={song.artist} albumId={song.albumId} />}
menuOptions={ menuOptions={
<> <>
<OptionStar id={song.id} type={song.itemType} /> <OptionStar id={song.id} type={song.itemType} />
@@ -284,7 +328,7 @@ export const NowPlayingContextPressable: React.FC<NowPlayingContextPressableProp
return ( return (
<ContextMenu <ContextMenu
{...props} {...props}
menuHeader={<MenuHeader title={song.title} subtitle={song.artist} coverArt={song.coverArt} />} menuHeader={<MenuHeader title={song.title} subtitle={song.artist} albumId={song.albumId} />}
menuOptions={ menuOptions={
<> <>
<OptionStar id={song.id} type={song.itemType} /> <OptionStar id={song.id} type={song.itemType} />
@@ -304,6 +348,8 @@ const styles = StyleSheet.create({
}, },
optionsWrapper: { optionsWrapper: {
// marginBottom: 10, // marginBottom: 10,
paddingHorizontal: 20,
// backgroundColor: 'purple',
}, },
menuHeader: { menuHeader: {
paddingTop: 14, paddingTop: 14,
@@ -334,9 +380,11 @@ const styles = StyleSheet.create({
}, },
option: { option: {
paddingVertical: 8, paddingVertical: 8,
paddingHorizontal: 20, // paddingHorizontal: 100,
flexDirection: 'row', flexDirection: 'row',
alignItems: 'center', alignItems: 'center',
// backgroundColor: 'blue',
overflow: 'hidden',
}, },
icon: { icon: {
marginRight: 10, marginRight: 10,

View File

@@ -1,5 +1,5 @@
import { useArtistArtFile, useCoverArtFile } from '@app/hooks/cache' import { useQueryAlbumCoverArtPath, useQueryArtistArtPath, useQueryCoverArtPath } from '@app/hooks/query'
import { CacheFile, CacheImageSize, CacheRequest } from '@app/models/cache' import { CacheImageSize } from '@app/models/cache'
import colors from '@app/styles/colors' import colors from '@app/styles/colors'
import React, { useState } from 'react' import React, { useState } from 'react'
import { import {
@@ -18,7 +18,8 @@ type BaseProps = {
imageStyle?: ImageStyle imageStyle?: ImageStyle
resizeMode?: ImageResizeMode resizeMode?: ImageResizeMode
round?: boolean round?: boolean
size?: CacheImageSize size: CacheImageSize
fadeDuration?: number
} }
type ArtistCoverArtProps = BaseProps & { type ArtistCoverArtProps = BaseProps & {
@@ -31,50 +32,68 @@ type CoverArtProps = BaseProps & {
coverArt?: string coverArt?: string
} }
const ImageSource = React.memo<{ cache?: { file?: CacheFile; request?: CacheRequest } } & BaseProps>( type AlbumIdProps = BaseProps & {
({ cache, style, imageStyle, resizeMode }) => { type: 'album'
albumId?: string
}
type ImageSourceProps = BaseProps & {
data?: string
isFetching: boolean
isExistingFetching: boolean
}
const ImageSource = React.memo<ImageSourceProps>(
({ style, imageStyle, resizeMode, data, isFetching, isExistingFetching, fadeDuration }) => {
const [error, setError] = useState(false) const [error, setError] = useState(false)
let source: ImageSourcePropType let source: ImageSourcePropType
if (!error && cache?.file && !cache?.request?.promise) { if (!error && data) {
source = { uri: `file://${cache.file.path}`, cache: 'reload' } source = { uri: `file://${data}` }
} else { } else {
source = require('@res/fallback.png') source = require('@res/fallback.png')
} }
return ( return (
<> <>
{isExistingFetching ? (
<View style={{ height: style?.height, width: style?.width }} />
) : (
<Image <Image
source={source} source={source}
fadeDuration={150} fadeDuration={fadeDuration === undefined ? 250 : fadeDuration}
resizeMode={resizeMode || 'contain'} resizeMode={resizeMode || 'contain'}
style={[{ height: style?.height, width: style?.width }, imageStyle]} style={[{ height: style?.height, width: style?.width }, imageStyle]}
onError={() => setError(true)} onError={() => setError(true)}
/> />
<ActivityIndicator )}
animating={!!cache?.request?.promise} {isFetching && (
size="large" <ActivityIndicator animating={true} size="large" color={colors.accent} style={styles.indicator} />
color={colors.accent} )}
style={styles.indicator}
/>
</> </>
) )
}, },
) )
const ArtistImage = React.memo<ArtistCoverArtProps>(props => { const ArtistImage = React.memo<ArtistCoverArtProps>(props => {
const cache = useArtistArtFile(props.artistId, props.size) const { data, isFetching, isExistingFetching } = useQueryArtistArtPath(props.artistId, props.size)
return <ImageSource cache={cache} {...props} imageStyle={{ ...styles.artistImage, ...props.imageStyle }} /> return <ImageSource data={data} isFetching={isFetching} isExistingFetching={isExistingFetching} {...props} />
}) })
const CoverArtImage = React.memo<CoverArtProps>(props => { const CoverArtImage = React.memo<CoverArtProps>(props => {
const cache = useCoverArtFile(props.coverArt, props.size) const { data, isFetching, isExistingFetching } = useQueryCoverArtPath(props.coverArt, props.size)
return <ImageSource cache={cache} {...props} /> return <ImageSource data={data} isFetching={isFetching} isExistingFetching={isExistingFetching} {...props} />
}) })
const CoverArt = React.memo<CoverArtProps | ArtistCoverArtProps>(props => { const AlbumIdIamge = React.memo<AlbumIdProps>(props => {
const { data, isFetching, isExistingFetching } = useQueryAlbumCoverArtPath(props.albumId, props.size)
return <ImageSource data={data} isFetching={isFetching} isExistingFetching={isExistingFetching} {...props} />
})
const CoverArt = React.memo<CoverArtProps | ArtistCoverArtProps | AlbumIdProps>(props => {
const viewStyles = [props.style] const viewStyles = [props.style]
if (props.round) { if (props.round) {
viewStyles.push(styles.round) viewStyles.push(styles.round)
@@ -85,6 +104,9 @@ const CoverArt = React.memo<CoverArtProps | ArtistCoverArtProps>(props => {
case 'artist': case 'artist':
imageComponent = <ArtistImage {...(props as ArtistCoverArtProps)} /> imageComponent = <ArtistImage {...(props as ArtistCoverArtProps)} />
break break
case 'album':
imageComponent = <AlbumIdIamge {...(props as AlbumIdProps)} />
break
default: default:
imageComponent = <CoverArtImage {...(props as CoverArtProps)} /> imageComponent = <CoverArtImage {...(props as CoverArtProps)} />
break break

View File

@@ -1,10 +1,13 @@
import colors from '@app/styles/colors' import colors from '@app/styles/colors'
import font from '@app/styles/font' import font from '@app/styles/font'
import React from 'react' import React from 'react'
import { Text, StyleSheet } from 'react-native' import { Text, StyleSheet, View } from 'react-native'
import { MenuOption, Menu, MenuTrigger, MenuOptions } from 'react-native-popup-menu' import { MenuOption, Menu, MenuTrigger, MenuOptions, renderers } from 'react-native-popup-menu'
import PressableOpacity from './PressableOpacity' import PressableOpacity from './PressableOpacity'
import Icon from 'react-native-vector-icons/MaterialCommunityIcons' import Icon from 'react-native-vector-icons/MaterialCommunityIcons'
import { ScrollView } from 'react-native-gesture-handler'
const { SlideInMenu } = renderers
export type OptionData = { export type OptionData = {
value: string value: string
@@ -17,12 +20,14 @@ const Option = React.memo<{
selected?: boolean selected?: boolean
}>(({ text, value, selected }) => ( }>(({ text, value, selected }) => (
<MenuOption style={styles.option} value={value}> <MenuOption style={styles.option} value={value}>
<Text style={styles.optionText}>{text}</Text>
{selected ? ( {selected ? (
<Icon name="checkbox-marked-circle" size={26} color={colors.accent} /> <Icon name="checkbox-marked-circle" size={32} color={colors.accent} style={styles.icon} />
) : ( ) : (
<Icon name="checkbox-blank-circle-outline" size={26} color={colors.text.secondary} /> <Icon name="checkbox-blank-circle-outline" size={32} color={colors.text.secondary} style={styles.icon} />
)} )}
<Text style={styles.optionText} numberOfLines={1} adjustsFontSizeToFit={true} minimumFontScale={0.6}>
{text}
</Text>
</MenuOption> </MenuOption>
)) ))
@@ -30,9 +35,10 @@ const FilterButton = React.memo<{
value?: string value?: string
data: OptionData[] data: OptionData[]
onSelect?: (selection: string) => void onSelect?: (selection: string) => void
}>(({ value, data, onSelect }) => { title: string
}>(({ value, data, onSelect, title }) => {
return ( return (
<Menu onSelect={onSelect}> <Menu onSelect={onSelect} renderer={SlideInMenu}>
<MenuTrigger <MenuTrigger
customStyles={{ customStyles={{
triggerOuterWrapper: styles.filterOuterWrapper, triggerOuterWrapper: styles.filterOuterWrapper,
@@ -40,16 +46,23 @@ const FilterButton = React.memo<{
triggerTouchable: { style: styles.filter }, triggerTouchable: { style: styles.filter },
TriggerTouchableComponent: PressableOpacity, TriggerTouchableComponent: PressableOpacity,
}}> }}>
<Icon name="filter-variant" color="white" size={30} style={styles.filterIcon} /> <Icon name="filter-variant" color="white" size={30} />
</MenuTrigger> </MenuTrigger>
<MenuOptions <MenuOptions
customStyles={{ customStyles={{
optionsWrapper: styles.optionsWrapper, optionsWrapper: styles.optionsWrapper,
optionsContainer: styles.optionsContainer, optionsContainer: styles.optionsContainer,
}}> }}>
<ScrollView style={styles.optionsScroll} overScrollMode="never">
<View style={styles.header}>
<Text style={styles.headerText} numberOfLines={2} ellipsizeMode="clip">
{title}
</Text>
</View>
{data.map(o => ( {data.map(o => (
<Option key={o.value} text={o.text} value={o.value} selected={o.value === value} /> <Option key={o.value} text={o.text} value={o.value} selected={o.value === value} />
))} ))}
</ScrollView>
</MenuOptions> </MenuOptions>
</Menu> </Menu>
) )
@@ -71,28 +84,45 @@ const styles = StyleSheet.create({
alignItems: 'center', alignItems: 'center',
backgroundColor: colors.accent, backgroundColor: colors.accent,
}, },
filterIcon: { optionsScroll: {
// top: 4, maxHeight: 260,
}, },
optionsWrapper: { optionsWrapper: {
maxWidth: 145, overflow: 'hidden',
}, },
optionsContainer: { optionsContainer: {
backgroundColor: colors.gradient.high, backgroundColor: 'rgba(45, 45, 45, 0.95)',
maxWidth: 145, },
header: {
paddingHorizontal: 20,
// paddingVertical: 10,
marginTop: 16,
marginBottom: 6,
},
headerText: {
fontFamily: font.bold,
fontSize: 20,
color: colors.text.primary,
}, },
option: { option: {
flexDirection: 'row',
paddingHorizontal: 12,
paddingVertical: 8, paddingVertical: 8,
justifyContent: 'center', paddingHorizontal: 20,
flexDirection: 'row',
alignItems: 'center', alignItems: 'center',
justifyContent: 'flex-start',
}, },
optionText: { optionText: {
color: colors.text.primary,
fontFamily: font.semiBold, fontFamily: font.semiBold,
fontSize: 16, fontSize: 16,
flex: 1, color: colors.text.primary,
},
icon: {
marginRight: 14,
width: 32,
height: 32,
justifyContent: 'center',
alignItems: 'center',
// backgroundColor: 'red',
}, },
}) })

View File

@@ -4,6 +4,7 @@ import dimensions from '@app/styles/dimensions'
import React, { ForwardedRef, PropsWithChildren } from 'react' import React, { ForwardedRef, PropsWithChildren } from 'react'
import { ScrollView, ScrollViewProps, useWindowDimensions } from 'react-native' import { ScrollView, ScrollViewProps, useWindowDimensions } from 'react-native'
import Animated from 'react-native-reanimated' import Animated from 'react-native-reanimated'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
export type GradientScrollViewProps = PropsWithChildren< export type GradientScrollViewProps = PropsWithChildren<
Animated.AnimateProps<ScrollViewProps> & { Animated.AnimateProps<ScrollViewProps> & {
@@ -13,8 +14,9 @@ export type GradientScrollViewProps = PropsWithChildren<
const GradientScrollView = React.forwardRef<ScrollView, GradientScrollViewProps>((props, ref) => { const GradientScrollView = React.forwardRef<ScrollView, GradientScrollViewProps>((props, ref) => {
const layout = useWindowDimensions() const layout = useWindowDimensions()
const paddingTop = useSafeAreaInsets().top
const minHeight = layout.height - (dimensions.top() + dimensions.bottom()) const minHeight = layout.height - (dimensions.header + paddingTop + dimensions.bottom())
return ( return (
<Animated.ScrollView <Animated.ScrollView

View File

@@ -1,17 +1,18 @@
import { Album, Song } from '@app/models/library'
import colors from '@app/styles/colors' import colors from '@app/styles/colors'
import dimensions from '@app/styles/dimensions' import dimensions from '@app/styles/dimensions'
import font from '@app/styles/font' import font from '@app/styles/font'
import { useNavigation } from '@react-navigation/core' import { useNavigation } from '@react-navigation/core'
import React, { useCallback } from 'react'
import { View, StatusBar, Text, StyleSheet, ViewStyle } from 'react-native'
import Animated from 'react-native-reanimated'
import PressableOpacity from './PressableOpacity'
import IconMat from 'react-native-vector-icons/MaterialIcons'
import { ReactComponentLike } from 'prop-types' import { ReactComponentLike } from 'prop-types'
import { AlbumListItem, Song } from '@app/models/music' import React, { useCallback } from 'react'
import { StyleSheet, Text, View, ViewStyle } from 'react-native'
import Animated from 'react-native-reanimated'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import IconMat from 'react-native-vector-icons/MaterialIcons'
import { AlbumContextPressable, NowPlayingContextPressable } from './ContextMenu' import { AlbumContextPressable, NowPlayingContextPressable } from './ContextMenu'
import PressableOpacity from './PressableOpacity'
export type HeaderContextItem = Song | AlbumListItem export type HeaderContextItem = Song | Album
const More = React.memo<{ contextItem?: HeaderContextItem }>(({ contextItem }) => { const More = React.memo<{ contextItem?: HeaderContextItem }>(({ contextItem }) => {
const moreIcon = <IconMat name="more-vert" color="white" size={25} /> const moreIcon = <IconMat name="more-vert" color="white" size={25} />
@@ -48,11 +49,12 @@ const More = React.memo<{ contextItem?: HeaderContextItem }>(({ contextItem }) =
const HeaderBar = React.memo<{ const HeaderBar = React.memo<{
title?: string title?: string
headerStyle?: Animated.AnimatedStyleProp<ViewStyle> | Animated.AnimatedStyleProp<ViewStyle>[] headerStyle?: Animated.AnimateStyle<ViewStyle> | Animated.AnimateStyle<ViewStyle>[]
HeaderCenter?: ReactComponentLike HeaderCenter?: ReactComponentLike
contextItem?: HeaderContextItem contextItem?: HeaderContextItem
}>(({ title, headerStyle, HeaderCenter, contextItem }) => { }>(({ title, headerStyle, HeaderCenter, contextItem }) => {
const navigation = useNavigation() const navigation = useNavigation()
const top = useSafeAreaInsets().top
const back = useCallback(() => { const back = useCallback(() => {
navigation.goBack() navigation.goBack()
@@ -61,7 +63,7 @@ const HeaderBar = React.memo<{
const _headerStyle = Array.isArray(headerStyle) ? headerStyle : [headerStyle] const _headerStyle = Array.isArray(headerStyle) ? headerStyle : [headerStyle]
return ( return (
<Animated.View style={[styles.container, ..._headerStyle]}> <Animated.View style={[styles.container, { paddingTop: top, height: dimensions.header + top }, ..._headerStyle]}>
<PressableOpacity onPress={back} style={styles.icons}> <PressableOpacity onPress={back} style={styles.icons}>
<IconMat name="arrow-back" color="white" size={25} /> <IconMat name="arrow-back" color="white" size={25} />
</PressableOpacity> </PressableOpacity>
@@ -81,8 +83,6 @@ const HeaderBar = React.memo<{
const styles = StyleSheet.create({ const styles = StyleSheet.create({
container: { container: {
height: dimensions.top(),
paddingTop: StatusBar.currentHeight,
backgroundColor: colors.gradient.high, backgroundColor: colors.gradient.high,
width: '100%', width: '100%',
flexDirection: 'row', flexDirection: 'row',

View File

@@ -3,11 +3,13 @@ import colors from '@app/styles/colors'
import dimensions from '@app/styles/dimensions' import dimensions from '@app/styles/dimensions'
import React from 'react' import React from 'react'
import { ScrollView, ScrollViewProps, useWindowDimensions } from 'react-native' import { ScrollView, ScrollViewProps, useWindowDimensions } from 'react-native'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
const ImageGradientScrollView: React.FC<ScrollViewProps & ImageGradientBackgroundProps> = props => { const ImageGradientScrollView: React.FC<ScrollViewProps & ImageGradientBackgroundProps> = props => {
const layout = useWindowDimensions() const layout = useWindowDimensions()
const paddingTop = useSafeAreaInsets().top
const minHeight = layout.height - (dimensions.top() + dimensions.bottom()) const minHeight = layout.height - (dimensions.header + paddingTop + dimensions.bottom())
return ( return (
<ScrollView <ScrollView

View File

@@ -1,8 +1,5 @@
import { useStarred } from '@app/hooks/music'
import { useIsPlaying } from '@app/hooks/trackplayer' import { useIsPlaying } from '@app/hooks/trackplayer'
import { AlbumListItem, Artist, ListableItem, Song } from '@app/models/music' import { Album, Artist, ListableItem, Song } from '@app/models/library'
import { selectMusic } from '@app/state/music'
import { useStore } from '@app/state/store'
import colors from '@app/styles/colors' import colors from '@app/styles/colors'
import font from '@app/styles/font' import font from '@app/styles/font'
import { useNavigation } from '@react-navigation/native' import { useNavigation } from '@react-navigation/native'
@@ -13,7 +10,8 @@ import IconMat from 'react-native-vector-icons/MaterialIcons'
import { AlbumContextPressable, ArtistContextPressable, SongContextPressable } from './ContextMenu' import { AlbumContextPressable, ArtistContextPressable, SongContextPressable } from './ContextMenu'
import CoverArt from './CoverArt' import CoverArt from './CoverArt'
import PressableOpacity from './PressableOpacity' import PressableOpacity from './PressableOpacity'
import Star from './Star' import { PressableStar } from './Star'
import equal from 'fast-deep-equal/es6/react'
const TitleTextSong = React.memo<{ const TitleTextSong = React.memo<{
contextId?: string contextId?: string
@@ -56,9 +54,9 @@ const ListItem: React.FC<{
listStyle?: 'big' | 'small' listStyle?: 'big' | 'small'
subtitle?: string subtitle?: string
style?: StyleProp<ViewStyle> style?: StyleProp<ViewStyle>
}> = ({ item, contextId, queueId, onPress, showArt, showStar, subtitle, listStyle, style }) => { disabled?: boolean
}> = ({ item, contextId, queueId, onPress, showArt, showStar, subtitle, listStyle, style, disabled }) => {
const navigation = useNavigation() const navigation = useNavigation()
const starred = useStarred(item.id, item.itemType)
showStar = showStar === undefined ? true : showStar showStar = showStar === undefined ? true : showStar
listStyle = listStyle || 'small' listStyle = listStyle || 'small'
@@ -68,13 +66,13 @@ const ListItem: React.FC<{
if (!onPress) { if (!onPress) {
switch (item.itemType) { switch (item.itemType) {
case 'album': case 'album':
onPress = () => navigation.navigate('album', { id: item.id, title: item.name }) onPress = () => navigation.navigate('album', { id: item.id, title: item.name, album: item })
break break
case 'artist': case 'artist':
onPress = () => navigation.navigate('artist', { id: item.id, title: item.name }) onPress = () => navigation.navigate('artist', { id: item.id, title: item.name })
break break
case 'playlist': case 'playlist':
onPress = () => navigation.navigate('playlist', { id: item.id, title: item.name }) onPress = () => navigation.navigate('playlist', { id: item.id, title: item.name, playlist: item })
break break
} }
} }
@@ -93,35 +91,43 @@ const ListItem: React.FC<{
const itemPressable = useCallback( const itemPressable = useCallback(
({ children }) => ( ({ children }) => (
<PressableOpacity onPress={onPress} style={styles.item}> <PressableOpacity onPress={onPress} style={styles.item} disabled={disabled}>
{children} {children}
</PressableOpacity> </PressableOpacity>
), ),
[onPress], [disabled, onPress],
) )
const albumPressable = useCallback( const albumPressable = useCallback(
({ children }) => ( ({ children }) => (
<AlbumContextPressable album={item as AlbumListItem} onPress={onPress} triggerWrapperStyle={styles.item}> <AlbumContextPressable
album={item as Album}
onPress={onPress}
triggerWrapperStyle={styles.item}
disabled={disabled}>
{children} {children}
</AlbumContextPressable> </AlbumContextPressable>
), ),
[item, onPress], [disabled, item, onPress],
) )
const songPressable = useCallback( const songPressable = useCallback(
({ children }) => ( ({ children }) => (
<SongContextPressable song={item as Song} onPress={onPress} triggerWrapperStyle={styles.item}> <SongContextPressable song={item as Song} onPress={onPress} triggerWrapperStyle={styles.item} disabled={disabled}>
{children} {children}
</SongContextPressable> </SongContextPressable>
), ),
[item, onPress], [disabled, item, onPress],
) )
const artistPressable = useCallback( const artistPressable = useCallback(
({ children }) => ( ({ children }) => (
<ArtistContextPressable artist={item as Artist} onPress={onPress} triggerWrapperStyle={styles.item}> <ArtistContextPressable
artist={item as Artist}
onPress={onPress}
triggerWrapperStyle={styles.item}
disabled={disabled}>
{children} {children}
</ArtistContextPressable> </ArtistContextPressable>
), ),
[item, onPress], [disabled, item, onPress],
) )
let PressableComponent = itemPressable let PressableComponent = itemPressable
@@ -133,13 +139,6 @@ const ListItem: React.FC<{
PressableComponent = artistPressable PressableComponent = artistPressable
} }
const starItem = useStore(selectMusic.starItem)
const toggleStarred = useCallback(() => {
if (item.itemType !== 'playlist') {
starItem(item.id, item.itemType, starred)
}
}, [item.id, item.itemType, starItem, starred])
let title = <></> let title = <></>
if (item.itemType === 'song' && queueId !== undefined) { if (item.itemType === 'song' && queueId !== undefined) {
title = <TitleTextSong contextId={contextId} queueId={queueId} title={item.title} /> title = <TitleTextSong contextId={contextId} queueId={queueId} title={item.title} />
@@ -151,9 +150,24 @@ const ListItem: React.FC<{
const resizeMode = 'cover' const resizeMode = 'cover'
let coverArt = <></> let coverArt = <></>
if (item.itemType === 'artist') { if (item.itemType === 'artist') {
coverArt = <CoverArt type="artist" artistId={item.id} round={true} style={artStyle} resizeMode={resizeMode} /> coverArt = (
<CoverArt
type="artist"
artistId={item.id}
round={true}
style={artStyle}
resizeMode={resizeMode}
size="thumbnail"
/>
)
} else if (item.itemType === 'song') {
coverArt = (
<CoverArt type="album" albumId={item.albumId} style={artStyle} resizeMode={resizeMode} size="thumbnail" />
)
} else { } else {
coverArt = <CoverArt type="cover" coverArt={item.coverArt} style={artStyle} resizeMode={resizeMode} /> coverArt = (
<CoverArt type="cover" coverArt={item.coverArt} style={artStyle} resizeMode={resizeMode} size="thumbnail" />
)
} }
return ( return (
@@ -178,10 +192,8 @@ const ListItem: React.FC<{
</View> </View>
</PressableComponent> </PressableComponent>
<View style={styles.controls}> <View style={styles.controls}>
{showStar && ( {showStar && item.itemType !== 'playlist' && (
<PressableOpacity onPress={toggleStarred} style={styles.controlItem}> <PressableStar id={item.id} type={item.itemType} size={26} style={styles.controlItem} disabled={disabled} />
<Star size={26} starred={starred} />
</PressableOpacity>
)} )}
</View> </View>
</View> </View>
@@ -259,4 +271,4 @@ const bigStyles = StyleSheet.create({
}, },
}) })
export default React.memo(ListItem) export default React.memo(ListItem, equal)

View File

@@ -1,23 +1,23 @@
import Button from '@app/components/Button' import Button from '@app/components/Button'
import { Song } from '@app/models/music' import { Song } from '@app/models/library'
import { useStore } from '@app/state/store'
import { QueueContextType, selectTrackPlayer } from '@app/state/trackplayer'
import colors from '@app/styles/colors' import colors from '@app/styles/colors'
import React, { useState } from 'react' import React, { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { StyleProp, StyleSheet, View, ViewStyle } from 'react-native' import { StyleProp, StyleSheet, View, ViewStyle } from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons' import Icon from 'react-native-vector-icons/Ionicons'
import IconMat from 'react-native-vector-icons/MaterialIcons' import IconMat from 'react-native-vector-icons/MaterialIcons'
import { withSuspenseMemo } from './withSuspense'
const ListPlayerControls = React.memo<{ const ListPlayerControls = withSuspenseMemo<{
songs: Song[] songs: Song[]
typeName: string listType: 'album' | 'playlist'
queueName: string
queueContextType: QueueContextType
queueContextId: string
style?: StyleProp<ViewStyle> style?: StyleProp<ViewStyle>
}>(({ songs, typeName, queueName, queueContextType, queueContextId, style }) => { play: () => void
shuffle: () => void
disabled?: boolean
}>(({ listType, style, play, shuffle, disabled }) => {
const [downloaded, setDownloaded] = useState(false) const [downloaded, setDownloaded] = useState(false)
const setQueue = useStore(selectTrackPlayer.setQueue) const { t } = useTranslation()
return ( return (
<View style={[styles.controls, style]}> <View style={[styles.controls, style]}>
@@ -34,13 +34,10 @@ const ListPlayerControls = React.memo<{
</Button> </Button>
</View> </View>
<View style={styles.controlsCenter}> <View style={styles.controlsCenter}>
<Button <Button title={t(`resources.${listType}.actions.play`)} disabled={disabled} onPress={play} />
title={`Play ${typeName}`}
onPress={() => setQueue(songs, queueName, queueContextType, queueContextId, undefined, false)}
/>
</View> </View>
<View style={styles.controlsSide}> <View style={styles.controlsSide}>
<Button onPress={() => setQueue(songs, queueName, queueContextType, queueContextId, undefined, true)}> <Button disabled={disabled} onPress={shuffle}>
<Icon name="shuffle" size={26} color="white" /> <Icon name="shuffle" size={26} color="white" />
</Button> </Button>
</View> </View>
@@ -61,6 +58,7 @@ const styles = StyleSheet.create({
flexDirection: 'row', flexDirection: 'row',
justifyContent: 'center', justifyContent: 'center',
alignItems: 'center', alignItems: 'center',
maxWidth: '65%',
}, },
}) })

View File

@@ -1,20 +1,25 @@
import font from '@app/styles/font' import font from '@app/styles/font'
import React from 'react' import React from 'react'
import { useTranslation } from 'react-i18next'
import { Text, View, StyleSheet, ViewStyle } from 'react-native' import { Text, View, StyleSheet, ViewStyle } from 'react-native'
import Icon from 'react-native-vector-icons/MaterialCommunityIcons' import Icon from 'react-native-vector-icons/MaterialCommunityIcons'
import { withSuspenseMemo } from './withSuspense'
const NothingHere = React.memo<{ const NothingHere = withSuspenseMemo<{
height?: number height?: number
width?: number width?: number
style?: ViewStyle style?: ViewStyle
}>(({ height, width, style }) => { }>(({ height, width, style }) => {
const { t } = useTranslation()
height = height || 200 height = height || 200
width = width || 200 width = width || 200
return ( return (
<View style={[styles.container, { height, width }, style]}> <View style={[styles.container, { height, width }, style]}>
<Icon name="music-rest-quarter" color={styles.text.color} size={width / 2} /> <Icon name="music-rest-quarter" color={styles.text.color} size={width / 2} />
<Text style={[styles.text, { fontSize: width / 8 }]}>Nothing here...</Text> <Text style={[styles.text, { fontSize: width / 8 }]} numberOfLines={3}>
{t('messages.nothingHere')}
</Text>
</View> </View>
) )
}) })

View File

@@ -2,7 +2,6 @@ import CoverArt from '@app/components/CoverArt'
import PressableOpacity from '@app/components/PressableOpacity' import PressableOpacity from '@app/components/PressableOpacity'
import { usePause, usePlay } from '@app/hooks/trackplayer' import { usePause, usePlay } from '@app/hooks/trackplayer'
import { useStore } from '@app/state/store' import { useStore } from '@app/state/store'
import { selectTrackPlayer } from '@app/state/trackplayer'
import colors from '@app/styles/colors' import colors from '@app/styles/colors'
import font from '@app/styles/font' import font from '@app/styles/font'
import { useNavigation } from '@react-navigation/native' import { useNavigation } from '@react-navigation/native'
@@ -12,7 +11,8 @@ import { State } from 'react-native-track-player'
import IconFA5 from 'react-native-vector-icons/FontAwesome5' import IconFA5 from 'react-native-vector-icons/FontAwesome5'
const ProgressBar = React.memo(() => { const ProgressBar = React.memo(() => {
const { position, duration } = useStore(selectTrackPlayer.progress) const position = useStore(store => store.progress.position)
const duration = useStore(store => store.progress.duration)
let progress = 0 let progress = 0
if (duration > 0) { if (duration > 0) {
@@ -41,7 +41,7 @@ const progressStyles = StyleSheet.create({
}) })
const Controls = React.memo(() => { const Controls = React.memo(() => {
const state = useStore(selectTrackPlayer.playerState) const state = useStore(store => store.playerState)
const play = usePlay() const play = usePlay()
const pause = usePause() const pause = usePause()
@@ -78,25 +78,30 @@ const Controls = React.memo(() => {
const NowPlayingBar = React.memo(() => { const NowPlayingBar = React.memo(() => {
const navigation = useNavigation() const navigation = useNavigation()
const track = useStore(selectTrackPlayer.currentTrack) const currentTrackExists = useStore(store => !!store.currentTrack)
const albumId = useStore(store => store.currentTrack?.albumId)
const title = useStore(store => store.currentTrack?.title)
const artist = useStore(store => store.currentTrack?.artist)
const displayStyle: ViewStyle = { display: track ? 'flex' : 'none' } const displayStyle: ViewStyle = { display: currentTrackExists ? 'flex' : 'none' }
return ( return (
<Pressable onPress={() => navigation.navigate('now-playing')} style={[styles.container, displayStyle]}> <Pressable onPress={() => navigation.navigate('now-playing')} style={[styles.container, displayStyle]}>
<ProgressBar /> <ProgressBar />
<View style={styles.subContainer}> <View style={styles.subContainer}>
<CoverArt <CoverArt
type="cover" type="album"
style={{ height: styles.subContainer.height, width: styles.subContainer.height }} style={{ height: styles.subContainer.height, width: styles.subContainer.height }}
coverArt={track?.coverArt} albumId={albumId}
size="thumbnail"
fadeDuration={0}
/> />
<View style={styles.detailsContainer}> <View style={styles.detailsContainer}>
<Text numberOfLines={1} style={styles.detailsTitle}> <Text numberOfLines={1} style={styles.detailsTitle}>
{track?.title} {title}
</Text> </Text>
<Text numberOfLines={1} style={styles.detailsAlbum}> <Text numberOfLines={1} style={styles.detailsAlbum}>
{track?.artist} {artist}
</Text> </Text>
</View> </View>
<Controls /> <Controls />

View File

@@ -1,5 +1,5 @@
import React, { useCallback, useEffect, useState } from 'react' import React, { useCallback, useState } from 'react'
import { GestureResponderEvent, LayoutRectangle, Pressable, PressableProps, ViewStyle, StyleSheet } from 'react-native' import { GestureResponderEvent, LayoutRectangle, Pressable, PressableProps, StyleSheet } from 'react-native'
type PressableOpacityProps = PressableProps & { type PressableOpacityProps = PressableProps & {
ripple?: boolean ripple?: boolean
@@ -9,13 +9,8 @@ type PressableOpacityProps = PressableProps & {
const PressableOpacity: React.FC<PressableOpacityProps> = props => { const PressableOpacity: React.FC<PressableOpacityProps> = props => {
const [opacity, setOpacity] = useState(1) const [opacity, setOpacity] = useState(1)
const [disabledStyle, setDisabledStyle] = useState<ViewStyle>({})
const [dimensions, setDimensions] = useState<LayoutRectangle | undefined>(undefined) const [dimensions, setDimensions] = useState<LayoutRectangle | undefined>(undefined)
useEffect(() => {
props.disabled === true ? setDisabledStyle({ opacity: 0.3 }) : setDisabledStyle({})
}, [props.disabled])
props = { props = {
...props, ...props,
unstable_pressDelay: props.unstable_pressDelay === undefined ? 60 : props.unstable_pressDelay, unstable_pressDelay: props.unstable_pressDelay === undefined ? 60 : props.unstable_pressDelay,
@@ -55,7 +50,8 @@ const PressableOpacity: React.FC<PressableOpacityProps> = props => {
return ( return (
<Pressable <Pressable
{...props} {...props}
style={[styles.pressable, props.style as any, { opacity }, disabledStyle]} // eslint-disable-next-line react-native/no-inline-styles
style={[styles.pressable, props.style as any, { opacity }, props.disabled ? { opacity: 0.3 } : {}]}
android_ripple={ android_ripple={
props.ripple props.ripple
? { ? {

View File

@@ -1,11 +1,10 @@
import { useStore } from '@app/state/store' import { useStore } from '@app/state/store'
import { selectTrackPlayer } from '@app/state/trackplayer'
import React, { useEffect } from 'react' import React, { useEffect } from 'react'
import { State, useProgress } from 'react-native-track-player' import { State, useProgress } from 'react-native-track-player'
const ProgressHook = () => { const ProgressHook = () => {
const playerState = useStore(selectTrackPlayer.playerState) const playerState = useStore(store => store.playerState)
const setProgress = useStore(selectTrackPlayer.setProgress) const setProgress = useStore(store => store.setProgress)
const progress = useProgress(250) const progress = useProgress(250)
useEffect(() => { useEffect(() => {

View File

@@ -1,8 +1,11 @@
import { useStar } from '@app/hooks/query'
import colors from '@app/styles/colors' import colors from '@app/styles/colors'
import React from 'react' import React from 'react'
import { PressableStateCallbackType, StyleProp, ViewStyle } from 'react-native'
import IconFA from 'react-native-vector-icons/FontAwesome' import IconFA from 'react-native-vector-icons/FontAwesome'
import PressableOpacity from './PressableOpacity'
const Star = React.memo<{ export const Star = React.memo<{
starred: boolean starred: boolean
size: number size: number
}>(({ starred, size }) => { }>(({ starred, size }) => {
@@ -11,4 +14,18 @@ const Star = React.memo<{
) )
}) })
export default Star export const PressableStar = React.memo<{
id: string
type: 'album' | 'artist' | 'song'
size: number
style?: StyleProp<ViewStyle> | ((state: PressableStateCallbackType) => StyleProp<ViewStyle>) | undefined
disabled?: boolean
}>(({ id, type, size, style, disabled }) => {
const { query, toggle } = useStar(id, type)
return (
<PressableOpacity onPress={() => toggle.mutate()} style={style} disabled={disabled}>
<Star size={size} starred={!!query.data} />
</PressableOpacity>
)
})

View File

@@ -0,0 +1,32 @@
import React, { ComponentType, FunctionComponent, Suspense, SuspenseProps } from 'react'
export function withSuspense<P extends string | number | object>(
WrappedComponent: ComponentType<P>,
fallback: SuspenseProps['fallback'] = null,
): FunctionComponent<P> {
function ComponentWithSuspense(props: P) {
return (
<Suspense fallback={fallback}>
<WrappedComponent {...props} />
</Suspense>
)
}
return ComponentWithSuspense
}
export function withSuspenseMemo<P extends string | number | object>(
WrappedComponent: ComponentType<P>,
fallback: SuspenseProps['fallback'] = null,
propsAreEqual?: Parameters<typeof React.memo>['1'],
) {
function ComponentWithSuspense(props: P) {
return (
<Suspense fallback={fallback}>
<WrappedComponent {...props} />
</Suspense>
)
}
return React.memo(ComponentWithSuspense, propsAreEqual)
}

View File

@@ -1,88 +0,0 @@
import { CacheImageSize, CacheItemTypeKey } from '@app/models/cache'
import { ArtistInfo } from '@app/models/music'
import { selectCache } from '@app/state/cache'
import { selectMusic } from '@app/state/music'
import { selectSettings } from '@app/state/settings'
import { useStore, Store } from '@app/state/store'
import { useCallback, useEffect } from 'react'
const useFileRequest = (key: CacheItemTypeKey, id: string) => {
const file = useStore(
useCallback(
(store: Store) => {
const activeServerId = store.settings.activeServer
if (!activeServerId) {
return
}
return store.cacheFiles[activeServerId][key][id]
},
[key, id],
),
)
const request = useStore(
useCallback(
(store: Store) => {
const activeServerId = store.settings.activeServer
if (!activeServerId) {
return
}
return store.cacheRequests[activeServerId][key][id]
},
[key, id],
),
)
return { file, request }
}
export const useCoverArtFile = (coverArt = '-1', size: CacheImageSize = 'thumbnail') => {
const type: CacheItemTypeKey = size === 'original' ? 'coverArt' : 'coverArtThumb'
const { file, request } = useFileRequest(type, coverArt)
const client = useStore(selectSettings.client)
const cacheItem = useStore(selectCache.cacheItem)
useEffect(() => {
if (!file && client) {
cacheItem(type, coverArt, () =>
client.getCoverArtUri({
id: coverArt,
size: type === 'coverArtThumb' ? '256' : undefined,
}),
)
}
// intentionally leaving file out so it doesn't re-render if the request fails
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [cacheItem, client, coverArt, type])
return { file, request }
}
export const useArtistArtFile = (artistId: string, size: CacheImageSize = 'thumbnail') => {
const type: CacheItemTypeKey = size === 'original' ? 'artistArt' : 'artistArtThumb'
const fetchArtistInfo = useStore(selectMusic.fetchArtistInfo)
const { file, request } = useFileRequest(type, artistId)
const cacheItem = useStore(selectCache.cacheItem)
useEffect(() => {
if (!file) {
cacheItem(type, artistId, async () => {
let artistInfo: ArtistInfo | undefined
const cachedArtistInfo = useStore.getState().artistInfo[artistId]
if (cachedArtistInfo) {
artistInfo = cachedArtistInfo
} else {
artistInfo = await fetchArtistInfo(artistId)
}
return type === 'artistArtThumb' ? artistInfo?.smallImageUrl : artistInfo?.largeImageUrl
})
}
// intentionally leaving file out so it doesn't re-render if the request fails
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [artistId, cacheItem, fetchArtistInfo, type])
return { file, request }
}

315
app/hooks/fetch.ts Normal file
View File

@@ -0,0 +1,315 @@
import { CacheItemTypeKey } from '@app/models/cache'
import { Album, Playlist, Song } from '@app/models/library'
import { mapAlbum, mapArtist, mapArtistInfo, mapPlaylist, mapSong } from '@app/models/map'
import queryClient from '@app/queryClient'
import { useStore } from '@app/state/store'
import { SubsonicApiClient } from '@app/subsonic/api'
import { GetAlbumList2TypeBase, Search3Params, StarParams } from '@app/subsonic/params'
import { cacheDir } from '@app/util/fs'
import { mapCollectionById } from '@app/util/state'
import userAgent from '@app/util/userAgent'
import cd from 'content-disposition'
import mime from 'mime-types'
import path from 'path'
import ReactNativeBlobUtil, { FetchBlobResponse } from 'react-native-blob-util'
import RNFS from 'react-native-fs'
import qk from './queryKeys'
export const useClient = () => {
const client = useStore(store => store.client)
return () => {
if (!client) {
throw new Error('no client!')
}
return client
}
}
function cacheStarredData<T extends { id: string; starred?: undefined | any }>(item: T) {
queryClient.setQueryData<boolean>(qk.starredItems(item.id), !!item.starred)
}
function cacheAlbumCoverArtData<T extends { id: string; coverArt?: string }>(item: T) {
queryClient.setQueryData<string | undefined>(qk.albumCoverArt(item.id), item.coverArt)
}
export const useFetchArtists = () => {
const client = useClient()
return async () => {
const res = await client().getArtists()
res.data.artists.forEach(cacheStarredData)
return mapCollectionById(res.data.artists, mapArtist)
}
}
export const useFetchArtist = () => {
const client = useClient()
return async (id: string) => {
const res = await client().getArtist({ id })
cacheStarredData(res.data.artist)
res.data.albums.forEach(cacheStarredData)
res.data.albums.forEach(cacheAlbumCoverArtData)
return {
artist: mapArtist(res.data.artist),
albums: res.data.albums.map(mapAlbum),
}
}
}
export const useFetchArtistInfo = () => {
const client = useClient()
return async (id: string) => {
const res = await client().getArtistInfo2({ id })
return mapArtistInfo(id, res.data.artistInfo)
}
}
export const useFetchArtistTopSongs = () => {
const client = useClient()
return async (artistName: string) => {
const res = await client().getTopSongs({ artist: artistName })
res.data.songs.forEach(cacheStarredData)
return res.data.songs.map(mapSong)
}
}
export const useFetchPlaylists = () => {
const client = useClient()
return async () => {
const res = await client().getPlaylists()
return mapCollectionById(res.data.playlists, mapPlaylist)
}
}
export const useFetchPlaylist = () => {
const client = useClient()
return async (id: string): Promise<{ playlist: Playlist; songs?: Song[] }> => {
const res = await client().getPlaylist({ id })
res.data.playlist.songs.forEach(cacheStarredData)
return {
playlist: mapPlaylist(res.data.playlist),
songs: res.data.playlist.songs.map(mapSong),
}
}
}
export async function fetchAlbum(id: string, client: SubsonicApiClient): Promise<{ album: Album; songs?: Song[] }> {
const res = await client.getAlbum({ id })
cacheStarredData(res.data.album)
res.data.songs.forEach(cacheStarredData)
cacheAlbumCoverArtData(res.data.album)
return {
album: mapAlbum(res.data.album),
songs: res.data.songs.map(mapSong),
}
}
export const useFetchAlbum = () => {
const client = useClient()
return async (id: string) => fetchAlbum(id, client())
}
export const useFetchAlbumList = () => {
const client = useClient()
return async (size: number, offset: number, type: GetAlbumList2TypeBase) => {
const res = await client().getAlbumList2({ size, offset, type })
res.data.albums.forEach(cacheStarredData)
res.data.albums.forEach(cacheAlbumCoverArtData)
return res.data.albums.map(mapAlbum)
}
}
export const useFetchSong = () => {
const client = useClient()
return async (id: string) => {
const res = await client().getSong({ id })
cacheStarredData(res.data.song)
return mapSong(res.data.song)
}
}
export const useFetchSearchResults = () => {
const client = useClient()
return async (params: Search3Params) => {
const res = await client().search3(params)
res.data.artists.forEach(cacheStarredData)
res.data.albums.forEach(cacheStarredData)
res.data.songs.forEach(cacheStarredData)
res.data.albums.forEach(cacheAlbumCoverArtData)
return {
artists: res.data.artists.map(mapArtist),
albums: res.data.albums.map(mapAlbum),
songs: res.data.songs.map(mapSong),
}
}
}
export const useFetchStar = () => {
const client = useClient()
return async (params: StarParams) => {
await client().star(params)
return
}
}
export const useFetchUnstar = () => {
const client = useClient()
return async (params: StarParams) => {
await client().unstar(params)
return
}
}
export type FetchExisingFileOptions = {
itemType: CacheItemTypeKey
itemId: string
}
export async function fetchExistingFile(
options: FetchExisingFileOptions,
serverId: string | undefined,
): Promise<string | undefined> {
const { itemType, itemId } = options
const fileDir = cacheDir(serverId, itemType, itemId)
try {
const dir = await RNFS.readDir(fileDir)
console.log('existing file:', dir[0].path)
return dir[0].path
} catch {}
}
export const useFetchExistingFile = () => {
const serverId = useStore(store => store.settings.activeServerId)
return async (options: FetchExisingFileOptions) => fetchExistingFile(options, serverId)
}
function assertMimeType(expected?: string, actual?: string) {
expected = expected?.toLowerCase()
actual = actual?.toLowerCase()
if (!expected || expected === actual) {
return
}
if (!expected.includes(';')) {
actual = actual?.split(';')[0]
}
if (!expected.includes('/')) {
actual = actual?.split('/')[0]
}
if (expected !== actual) {
throw new Error(`Request does not satisfy expected content type. Expected: ${expected} Actual: ${actual}`)
}
}
export type FetchFileOptions = FetchExisingFileOptions & {
fromUrl: string
useCacheBuster?: boolean
expectedContentType?: string
progress?: (received: number, total: number) => void
}
export async function fetchFile(options: FetchFileOptions, serverId: string | undefined): Promise<string> {
let { itemType, itemId, fromUrl, useCacheBuster, expectedContentType, progress } = options
useCacheBuster = useCacheBuster === undefined ? true : useCacheBuster
const fileDir = cacheDir(serverId, itemType, itemId)
const filePathNoExt = path.join(fileDir, useCacheBuster ? useStore.getState().settings.cacheBuster : itemType)
try {
await RNFS.unlink(fileDir)
} catch {}
const headers = { 'User-Agent': userAgent }
// we send a HEAD first for two reasons:
// 1. to follow any redirects and get the actual URL (DownloadManager does not support redirects)
// 2. to obtain the mime-type up front so we can use it for the file extension/validation
const headRes = await fetch(fromUrl, { method: 'HEAD', headers })
if (headRes.status > 399) {
throw new Error(`HTTP status error ${headRes.status}. File: ${itemType} ID: ${itemId}`)
}
const contentType = headRes.headers.get('content-type') || undefined
assertMimeType(expectedContentType, contentType)
const contentDisposition = headRes.headers.get('content-disposition') || undefined
const filename = contentDisposition ? cd.parse(contentDisposition).parameters.filename : undefined
let extension: string | undefined
if (filename) {
extension = path.extname(filename) || undefined
if (extension) {
extension = extension.substring(1)
}
} else if (contentType) {
extension = mime.extension(contentType) || undefined
}
const config = ReactNativeBlobUtil.config({
addAndroidDownloads: {
useDownloadManager: true,
notification: false,
mime: contentType,
description: 'subtracks',
path: extension ? `${filePathNoExt}.${extension}` : filePathNoExt,
},
})
const fetchParams: Parameters<typeof config['fetch']> = ['GET', headRes.url, headers]
let res: FetchBlobResponse
if (progress) {
res = await config.fetch(...fetchParams).progress(progress)
} else {
res = await config.fetch(...fetchParams)
}
const downloadPath = res.path()
queryClient.setQueryData<string>(qk.existingFiles(itemType, itemId), downloadPath)
console.log('downloaded file:', downloadPath)
return downloadPath
}
export const useFetchFile = () => {
const serverId = useStore(store => store.settings.activeServerId)
return async (options: FetchFileOptions) => fetchFile(options, serverId)
}

View File

@@ -1,77 +0,0 @@
import { useState, useCallback } from 'react'
import { useActiveServerRefresh } from './server'
export const useFetchList = <T>(fetchList: () => Promise<T[]>) => {
const [list, setList] = useState<T[]>([])
const [refreshing, setRefreshing] = useState(false)
const refresh = useCallback(() => {
setRefreshing(true)
fetchList().then(items => {
setList(items)
setRefreshing(false)
})
}, [fetchList])
const reset = useCallback(() => {
setList([])
refresh()
}, [refresh])
useActiveServerRefresh(
useCallback(() => {
reset()
}, [reset]),
)
return { list, refreshing, refresh, reset }
}
export const useFetchPaginatedList = <T>(
fetchList: (size?: number, offset?: number) => Promise<T[]>,
pageSize: number,
) => {
const [list, setList] = useState<T[]>([])
const [refreshing, setRefreshing] = useState(false)
const [offset, setOffset] = useState(0)
const refresh = useCallback(() => {
setOffset(0)
setRefreshing(true)
fetchList(pageSize, 0).then(firstPage => {
setList(firstPage)
setRefreshing(false)
})
}, [fetchList, pageSize])
const reset = useCallback(() => {
setList([])
refresh()
}, [refresh])
useActiveServerRefresh(
useCallback(() => {
reset()
}, [reset]),
)
const fetchNextPage = useCallback(() => {
const newOffset = offset + pageSize
setRefreshing(true)
fetchList(pageSize, newOffset).then(nextPage => {
setRefreshing(false)
if (nextPage.length === 0) {
return
}
setList([...list, ...nextPage])
setOffset(newOffset)
})
}, [offset, pageSize, fetchList, list])
return { list, refreshing, refresh, reset, fetchNextPage }
}

View File

@@ -1,62 +0,0 @@
import { selectMusic } from '@app/state/music'
import { Store, useStore } from '@app/state/store'
import { useCallback, useEffect } from 'react'
export const useArtistInfo = (id: string) => {
const artistInfo = useStore(useCallback((state: Store) => state.artistInfo[id], [id]))
const fetchArtistInfo = useStore(selectMusic.fetchArtistInfo)
useEffect(() => {
if (!artistInfo) {
fetchArtistInfo(id)
}
}, [artistInfo, fetchArtistInfo, id])
return artistInfo
}
export const useAlbumWithSongs = (id: string) => {
const album = useStore(useCallback((state: Store) => state.albumsWithSongs[id], [id]))
const fetchAlbum = useStore(selectMusic.fetchAlbumWithSongs)
useEffect(() => {
if (!album) {
fetchAlbum(id)
}
}, [album, fetchAlbum, id])
return album
}
export const usePlaylistWithSongs = (id: string) => {
const playlist = useStore(useCallback((state: Store) => state.playlistsWithSongs[id], [id]))
const fetchPlaylist = useStore(selectMusic.fetchPlaylistWithSongs)
useEffect(() => {
if (!playlist) {
fetchPlaylist(id)
}
}, [fetchPlaylist, id, playlist])
return playlist
}
export const useStarred = (id: string, type: string) => {
return useStore(
useCallback(
(state: Store) => {
switch (type) {
case 'song':
return state.starredSongs[id]
case 'album':
return state.starredAlbums[id]
case 'artist':
return state.starredArtists[id]
default:
return false
}
},
[type, id],
),
)
}

323
app/hooks/query.ts Normal file
View File

@@ -0,0 +1,323 @@
import { CacheImageSize, CacheItemTypeKey } from '@app/models/cache'
import { Album, Artist, Playlist, Song, StarrableItemType } from '@app/models/library'
import { CollectionById } from '@app/models/state'
import queryClient from '@app/queryClient'
import { useStore } from '@app/state/store'
import { GetAlbumList2TypeBase, Search3Params, StarParams } from '@app/subsonic/params'
import _ from 'lodash'
import { useInfiniteQuery, useMutation, useQueries, useQuery } from 'react-query'
import {
useFetchAlbum,
useFetchAlbumList,
useFetchArtist,
useFetchArtistInfo,
useFetchArtists,
useFetchArtistTopSongs,
useFetchExistingFile,
useFetchFile,
useFetchPlaylist,
useFetchPlaylists,
useFetchSearchResults,
useFetchSong,
useFetchStar,
useFetchUnstar,
} from './fetch'
import qk from './queryKeys'
export const useQueryArtists = () => useQuery(qk.artists, useFetchArtists())
export const useQueryArtist = (id: string) => {
const fetchArtist = useFetchArtist()
return useQuery(qk.artist(id), () => fetchArtist(id), {
placeholderData: () => {
const artist = queryClient.getQueryData<CollectionById<Artist>>(qk.artists)?.byId[id]
if (artist) {
return { artist, albums: [] }
}
},
})
}
export const useQueryArtistInfo = (id: string) => {
const fetchArtistInfo = useFetchArtistInfo()
return useQuery(qk.artistInfo(id), () => fetchArtistInfo(id))
}
export const useQueryArtistTopSongs = (artistName?: string) => {
const fetchArtistTopSongs = useFetchArtistTopSongs()
const query = useQuery(qk.artistTopSongs(artistName || ''), () => fetchArtistTopSongs(artistName as string), {
enabled: !!artistName,
retry: false,
staleTime: Infinity,
cacheTime: Infinity,
notifyOnChangeProps: ['data', 'isError', 'isFetched', 'isSuccess', 'isFetching'],
})
const querySuccess = query.isFetched && query.isSuccess && query.data && query.data.length > 0
const fetchSearchResults = useFetchSearchResults()
const [artistCount, albumCount, songCount] = [0, 0, 300]
const backupQuery = useQuery(
qk.search(artistName || '', artistCount, albumCount, songCount),
() => fetchSearchResults({ query: artistName as string, artistCount, albumCount, songCount }),
{
select: data => {
const artistNameLower = artistName?.toLowerCase()
const songs = data.songs.filter(s => s.artist?.toLowerCase() === artistNameLower)
// sortBy is a stable sort, so that this doesn't change order arbitrarily and re-render
return _.sortBy(songs, [
s => -(s.playCount || 0),
s => -(s.averageRating || 0),
s => -(s.userRating || 0),
]).slice(0, 50)
},
enabled: !!artistName && !query.isFetching && !querySuccess,
staleTime: Infinity,
cacheTime: Infinity,
notifyOnChangeProps: ['data', 'isError'],
},
)
return querySuccess ? query : backupQuery
}
export const useQueryPlaylists = () => useQuery(qk.playlists, useFetchPlaylists())
export const useQueryPlaylist = (id: string, placeholderPlaylist?: Playlist) => {
const fetchPlaylist = useFetchPlaylist()
const query = useQuery(qk.playlist(id), () => fetchPlaylist(id), {
placeholderData: () => {
if (placeholderPlaylist) {
return { playlist: placeholderPlaylist }
}
const playlist = queryClient.getQueryData<CollectionById<Playlist>>(qk.playlists)?.byId[id]
if (playlist) {
return { playlist, songs: [] }
}
},
})
return query
}
export const useQueryAlbum = (id: string, placeholderAlbum?: Album) => {
const fetchAlbum = useFetchAlbum()
const query = useQuery(qk.album(id), () => fetchAlbum(id), {
placeholderData: (): { album: Album; songs?: Song[] } | undefined =>
placeholderAlbum ? { album: placeholderAlbum } : undefined,
})
return query
}
export const useQueryAlbumList = (type: GetAlbumList2TypeBase, size: number) => {
const fetchAlbumList = useFetchAlbumList()
return useInfiniteQuery(
qk.albumList(type, size),
async context => {
return await fetchAlbumList(size, context.pageParam || 0, type)
},
{
getNextPageParam: (lastPage, allPages) => {
if (lastPage.length === 0) {
return
}
return allPages.length * size
},
cacheTime: 0,
},
)
}
export const useQuerySearchResults = (params: Search3Params) => {
const fetchSearchResults = useFetchSearchResults()
const query = useInfiniteQuery(
qk.search(params.query, params.artistCount, params.albumCount, params.songCount),
async context => {
return await fetchSearchResults({
...params,
artistOffset: context.pageParam?.artistOffset || 0,
albumOffset: context.pageParam?.albumOffset || 0,
songOffset: context.pageParam?.songOffset || 0,
})
},
{
getNextPageParam: (lastPage, allPages) => {
if (lastPage.albums.length + lastPage.artists.length + lastPage.songs.length === 0) {
return
}
return {
artistOffset: allPages.reduce((acc, val) => (acc += val.artists.length), 0),
albumOffset: allPages.reduce((acc, val) => (acc += val.albums.length), 0),
songOffset: allPages.reduce((acc, val) => (acc += val.songs.length), 0),
}
},
cacheTime: 1000 * 60,
enabled: !!params.query && params.query.length > 1,
},
)
return query
}
export const useQueryHomeLists = (types: GetAlbumList2TypeBase[], size: number) => {
const fetchAlbumList = useFetchAlbumList()
const listQueries = useQueries(
types.map(type => {
return {
queryKey: qk.albumList(type, size),
queryFn: async () => {
const albums = await fetchAlbumList(size, 0, type as GetAlbumList2TypeBase)
return { type, albums }
},
}
}),
)
return listQueries
}
export const useStar = (id: string, type: StarrableItemType) => {
const fetchStar = useFetchStar()
const fetchUnstar = useFetchUnstar()
const fetchSong = useFetchSong()
const fetchAlbum = useFetchAlbum()
const fetchArtist = useFetchArtist()
const query = useQuery(
qk.starredItems(id),
async () => {
switch (type) {
case 'album':
console.log('fetch album starred', id)
return !!(await fetchAlbum(id)).album.starred
case 'artist':
console.log('fetch artist starred', id)
return !!(await fetchArtist(id)).artist.starred
default:
console.log('fetch song starred', id)
return !!(await fetchSong(id)).starred
}
},
{
cacheTime: Infinity,
staleTime: Infinity,
},
)
const toggle = useMutation(
() => {
const params: StarParams = {
id: type === 'song' ? id : undefined,
albumId: type === 'album' ? id : undefined,
artistId: type === 'artist' ? id : undefined,
}
return !query.data ? fetchStar(params) : fetchUnstar(params)
},
{
onMutate: () => {
queryClient.setQueryData<boolean>(qk.starredItems(id), !query.data)
},
onSuccess: () => {
if (type === 'album') {
queryClient.invalidateQueries(qk.albumList('starred'))
}
},
},
)
return { query, toggle }
}
export const useQueryExistingFile = (itemType: CacheItemTypeKey, itemId: string) => {
const fetchExistingFile = useFetchExistingFile()
return useQuery(qk.existingFiles(itemType, itemId), () => fetchExistingFile({ itemType, itemId }), {
staleTime: Infinity,
cacheTime: Infinity,
notifyOnChangeProps: ['data', 'isFetched'],
})
}
export const useQueryCoverArtPath = (coverArt = '-1', size: CacheImageSize = 'thumbnail') => {
const fetchFile = useFetchFile()
const client = useStore(store => store.client)
const itemType: CacheItemTypeKey = size === 'original' ? 'coverArt' : 'coverArtThumb'
const existing = useQueryExistingFile(itemType, coverArt)
const query = useQuery(
qk.coverArt(coverArt, size),
async () => {
if (!client) {
return
}
const fromUrl = client.getCoverArtUri({ id: coverArt, size: itemType === 'coverArtThumb' ? '256' : undefined })
return await fetchFile({ itemType, itemId: coverArt, fromUrl, expectedContentType: 'image' })
},
{
enabled: existing.isFetched && !existing.data && !!client,
staleTime: Infinity,
cacheTime: Infinity,
},
)
return { ...query, data: existing.data || query.data, isExistingFetching: existing.isFetching }
}
export const useQueryArtistArtPath = (artistId: string, size: CacheImageSize = 'thumbnail') => {
const fetchFile = useFetchFile()
const client = useStore(store => store.client)
const { data: artistInfo } = useQueryArtistInfo(artistId)
const itemType: CacheItemTypeKey = size === 'original' ? 'artistArt' : 'artistArtThumb'
const existing = useQueryExistingFile(itemType, artistId)
const query = useQuery(
qk.artistArt(artistId, size),
async () => {
if (!client || !artistInfo?.smallImageUrl || !artistInfo?.largeImageUrl) {
return
}
const fromUrl = itemType === 'artistArtThumb' ? artistInfo.smallImageUrl : artistInfo.largeImageUrl
return await fetchFile({ itemType, itemId: artistId, fromUrl, expectedContentType: 'image' })
},
{
enabled:
existing.isFetched &&
!existing.data &&
!!client &&
(!!artistInfo?.smallImageUrl || !!artistInfo?.largeImageUrl),
staleTime: Infinity,
cacheTime: Infinity,
},
)
return { ...query, data: existing.data || query.data, isExistingFetching: existing.isFetching }
}
export const useQueryAlbumCoverArtPath = (albumId?: string, size: CacheImageSize = 'thumbnail') => {
const fetchAlbum = useFetchAlbum()
const query = useQuery(
qk.albumCoverArt(albumId || '-1'),
async () => (await fetchAlbum(albumId || '-1')).album.coverArt,
{
enabled: !!albumId,
staleTime: Infinity,
cacheTime: Infinity,
},
)
return useQueryCoverArtPath(query.data, size)
}

52
app/hooks/queryKeys.ts Normal file
View File

@@ -0,0 +1,52 @@
import { CacheImageSize, CacheItemTypeKey } from '@app/models/cache'
import { GetAlbumList2TypeBase } from '@app/subsonic/params'
const qk = {
starredItems: (id: string) => ['starredItems', id],
albumCoverArt: (id: string) => ['albumCoverArt', id],
artists: 'artists',
artist: (id: string) => ['artist', id],
artistInfo: (id: string) => ['artistInfo', id],
artistTopSongs: (artistName: string) => ['artistTopSongs', artistName],
playlists: 'playlists',
playlist: (id: string) => ['playlist', id],
album: (id: string) => ['album', id],
albumList: (type: GetAlbumList2TypeBase, size?: number) => {
const key: (string | number)[] = ['albumList', type]
size !== undefined && key.push(size)
return key
},
search: (query: string, artistCount?: number, albumCount?: number, songCount?: number) => [
'search',
query,
artistCount,
albumCount,
songCount,
],
coverArt: (coverArt?: string, size?: CacheImageSize) => {
const key: string[] = ['coverArt']
coverArt !== undefined && key.push(coverArt)
size !== undefined && key.push(size)
return key
},
artistArt: (artistId?: string, size?: CacheImageSize) => {
const key: string[] = ['artistArt']
artistId !== undefined && key.push(artistId)
size !== undefined && key.push(size)
return key
},
existingFiles: (type?: CacheItemTypeKey, itemId?: string) => {
const key: string[] = ['existingFiles']
type !== undefined && key.push(type)
itemId !== undefined && key.push(itemId)
return key
},
}
export default qk

View File

@@ -1,29 +0,0 @@
import { useReset } from '@app/hooks/trackplayer'
import { selectSettings } from '@app/state/settings'
import { useStore } from '@app/state/store'
import { useEffect } from 'react'
export const useSwitchActiveServer = () => {
const activeServer = useStore(selectSettings.activeServer)
const setActiveServer = useStore(selectSettings.setActiveServer)
const resetPlayer = useReset()
return async (id: string) => {
if (id === activeServer?.id) {
return
}
await resetPlayer()
setActiveServer(id)
}
}
export const useActiveServerRefresh = (refresh: () => void) => {
const activeServer = useStore(selectSettings.activeServer)
useEffect(() => {
if (activeServer) {
refresh()
}
}, [activeServer, refresh])
}

75
app/hooks/settings.ts Normal file
View File

@@ -0,0 +1,75 @@
import { useReset } from '@app/hooks/trackplayer'
import { CacheItemTypeKey } from '@app/models/cache'
import queryClient from '@app/queryClient'
import { useStore, useStoreDeep } from '@app/state/store'
import { cacheDir } from '@app/util/fs'
import RNFS from 'react-native-fs'
import qk from './queryKeys'
export const useSwitchActiveServer = () => {
const activeServerId = useStore(store => store.settings.activeServerId)
const setActiveServer = useStore(store => store.setActiveServer)
const resetPlayer = useReset()
return async (id: string) => {
if (id === activeServerId) {
return
}
await queryClient.cancelQueries(undefined, { active: true })
await resetPlayer()
queryClient.removeQueries()
setActiveServer(id)
}
}
export const useFirstRun = () => {
return useStore(store => Object.keys(store.settings.servers).length === 0)
}
export const useResetImageCache = () => {
const serverIds = useStoreDeep(store => Object.keys(store.settings.servers))
const changeCacheBuster = useStore(store => store.changeCacheBuster)
const setDisableMusicTabs = useStore(store => store.setDisableMusicTabs)
return async () => {
setDisableMusicTabs(true)
try {
// disable/invalidate queries
await Promise.all([
queryClient.cancelQueries(qk.artistArt(), { active: true }),
queryClient.cancelQueries(qk.coverArt(), { active: true }),
queryClient.cancelQueries(qk.existingFiles(), { active: true }),
queryClient.invalidateQueries(qk.artistArt(), { refetchActive: false }),
queryClient.invalidateQueries(qk.coverArt(), { refetchActive: false }),
queryClient.invalidateQueries(qk.existingFiles(), { refetchActive: false }),
])
// delete all images
const itemTypes: CacheItemTypeKey[] = ['artistArt', 'artistArtThumb', 'coverArt', 'coverArtThumb']
await Promise.all(
serverIds.flatMap(id =>
itemTypes.map(async type => {
const dir = cacheDir(id, type)
try {
await RNFS.unlink(dir)
} catch {}
}),
),
)
// change cacheBuster
changeCacheBuster()
} finally {
setDisableMusicTabs(false)
// enable queries
await Promise.all([
queryClient.refetchQueries(qk.existingFiles(), { active: true }),
queryClient.refetchQueries(qk.artistArt(), { active: true }),
queryClient.refetchQueries(qk.coverArt(), { active: true }),
])
}
}
}

View File

@@ -1,6 +1,12 @@
import { useStore } from '@app/state/store' import { Song } from '@app/models/library'
import { getQueue, selectTrackPlayer, trackPlayerCommands } from '@app/state/trackplayer' import { QueueContextType, TrackExt } from '@app/models/trackplayer'
import queryClient from '@app/queryClient'
import queueService from '@app/queueservice'
import { useStore, useStoreDeep } from '@app/state/store'
import { getQueue, SetQueueOptions, trackPlayerCommands } from '@app/state/trackplayer'
import userAgent from '@app/util/userAgent'
import TrackPlayer from 'react-native-track-player' import TrackPlayer from 'react-native-track-player'
import qk from './queryKeys'
export const usePlay = () => { export const usePlay = () => {
return () => trackPlayerCommands.enqueue(() => TrackPlayer.play()) return () => trackPlayerCommands.enqueue(() => TrackPlayer.play())
@@ -57,7 +63,7 @@ export const useSeekTo = () => {
} }
export const useReset = (enqueue = true) => { export const useReset = (enqueue = true) => {
const resetStore = useStore(selectTrackPlayer.resetTrackPlayerState) const resetStore = useStore(store => store.resetTrackPlayerState)
const reset = async () => { const reset = async () => {
await TrackPlayer.reset() await TrackPlayer.reset()
@@ -68,9 +74,9 @@ export const useReset = (enqueue = true) => {
} }
export const useIsPlaying = (contextId: string | undefined, track: number) => { export const useIsPlaying = (contextId: string | undefined, track: number) => {
const queueContextId = useStore(selectTrackPlayer.queueContextId) const queueContextId = useStore(store => store.queueContextId)
const currentTrackIdx = useStore(selectTrackPlayer.currentTrackIdx) const currentTrackIdx = useStore(store => store.currentTrackIdx)
const shuffleOrder = useStore(selectTrackPlayer.shuffleOrder) const shuffleOrder = useStoreDeep(store => store.shuffleOrder)
if (contextId === undefined) { if (contextId === undefined) {
return track === currentTrackIdx return track === currentTrackIdx
@@ -83,3 +89,51 @@ export const useIsPlaying = (contextId: string | undefined, track: number) => {
return contextId === queueContextId && track === currentTrackIdx return contextId === queueContextId && track === currentTrackIdx
} }
export function mapSongToTrackExt(song: Song): TrackExt {
return {
id: song.id,
title: song.title,
artist: song.artist || 'Unknown Artist',
album: song.album || 'Unknown Album',
url: useStore.getState().buildStreamUri(song.id),
artwork: require('@res/fallback.png'),
userAgent,
duration: song.duration,
artistId: song.artistId,
albumId: song.albumId,
track: song.track,
discNumber: song.discNumber,
}
}
export const useSetQueue = (type: QueueContextType, songs?: Song[]) => {
const _setQueue = useStore(store => store.setQueue)
const contextId = `${type}-${songs?.map(s => s.id).join('-')}`
const setQueue = async (options: SetQueueOptions) => {
if (!songs || songs.length === 0) {
return
}
const queue = songs.map(mapSongToTrackExt)
const first = queue[options.playTrack || 0]
if (!first.albumId) {
first.artwork = require('@res/fallback.png')
} else {
const albumCoverArt = queryClient.getQueryData<string>(qk.albumCoverArt(first.albumId))
const existingFile = queryClient.getQueryData<string>(qk.existingFiles('coverArtThumb', albumCoverArt))
const downloadFile = queryClient.getQueryData<string>(qk.coverArt(albumCoverArt, 'thumbnail'))
if (existingFile || downloadFile) {
first.artwork = `file://${existingFile || downloadFile}`
}
}
await _setQueue({ queue, type, contextId, ...options })
queueService.emit('set', { queue })
}
return { setQueue, contextId }
}

64
app/i18n.ts Normal file
View File

@@ -0,0 +1,64 @@
import { BackendModule, LanguageDetectorAsyncModule } from 'i18next'
import path from 'path'
import RNFS from 'react-native-fs'
import * as RNLocalize from 'react-native-localize'
import _ from 'lodash'
const I18N_ASSETS_DIR = path.join('custom', 'i18n')
const cache: {
[language: string]: {
[key: string]: any
}
} = {}
async function loadTranslation(language: string) {
const text = await RNFS.readFileAssets(path.join(I18N_ASSETS_DIR, `${language}.json`), 'utf8')
return JSON.parse(text)
}
async function readTranslation(language: string, namespace: string) {
if (!cache[language]) {
cache[language] = await loadTranslation(language)
}
return namespace === 'translation' ? cache[language] : _.get(cache[language], namespace)
}
export const backend = {
type: 'backend',
init: () => {},
read: async (language, namespace, callback) => {
try {
callback(null, await readTranslation(language, namespace))
} catch (err) {
callback(err as any, null)
}
},
} as BackendModule
export const languageDetector = {
type: 'languageDetector',
async: true,
detect: async callback => {
try {
const languageTags = (await RNFS.readDirAssets(I18N_ASSETS_DIR))
.map(f => f.name)
.filter(n => n.endsWith('.json'))
.map(n => n.slice(0, -5))
console.log('translations available:', languageTags)
console.log(
'locales list:',
RNLocalize.getLocales().map(l => l.languageTag),
)
console.log('best language:', RNLocalize.findBestAvailableLanguage(languageTags)?.languageTag)
callback(RNLocalize.findBestAvailableLanguage(languageTags)?.languageTag)
} catch {
callback(undefined)
}
},
init: () => {},
cacheUserLanguage: () => {},
} as LanguageDetectorAsyncModule

View File

@@ -1,11 +1,10 @@
import { Album, PlaylistListItem, Artist, Song } from './music' import { Album, Playlist, Artist, Song } from './library'
export enum CacheItemType { export enum CacheItemType {
coverArt = 'coverArt', coverArt = 'coverArt',
coverArtThumb = 'coverArtThumb', coverArtThumb = 'coverArtThumb',
artistArt = 'artistArt', artistArt = 'artistArt',
artistArtThumb = 'artistArtThumb', artistArtThumb = 'artistArtThumb',
song = 'song',
} }
export type CacheItemTypeKey = keyof typeof CacheItemType export type CacheItemTypeKey = keyof typeof CacheItemType
@@ -27,7 +26,7 @@ export type DownloadedAlbum = Album & {
songs: string[] songs: string[]
} }
export type DownloadedPlaylist = PlaylistListItem & { export type DownloadedPlaylist = Playlist & {
songs: string[] songs: string[]
} }

View File

@@ -2,43 +2,28 @@ export interface Artist {
itemType: 'artist' itemType: 'artist'
id: string id: string
name: string name: string
starred?: Date starred?: number
coverArt?: string coverArt?: string
} }
export interface ArtistInfo extends Artist { export interface ArtistInfo {
albums: Album[] id: string
smallImageUrl?: string smallImageUrl?: string
largeImageUrl?: string largeImageUrl?: string
topSongs: Song[]
} }
export interface AlbumListItem { export interface Album {
itemType: 'album' itemType: 'album'
id: string id: string
name: string name: string
artist?: string artist?: string
artistId?: string artistId?: string
starred?: Date starred?: number
coverArt?: string
}
export interface Album extends AlbumListItem {
coverArt?: string coverArt?: string
year?: number year?: number
} }
export interface AlbumWithSongs extends Album { export interface Playlist {
songs: Song[]
}
export interface SearchResults {
artists: Artist[]
albums: AlbumListItem[]
songs: Song[]
}
export interface PlaylistListItem {
itemType: 'playlist' itemType: 'playlist'
id: string id: string
name: string name: string
@@ -46,10 +31,6 @@ export interface PlaylistListItem {
coverArt?: string coverArt?: string
} }
export interface PlaylistWithSongs extends PlaylistListItem {
songs: Song[]
}
export interface Song { export interface Song {
itemType: 'song' itemType: 'song'
id: string id: string
@@ -61,14 +42,23 @@ export interface Song {
track?: number track?: number
discNumber?: number discNumber?: number
duration?: number duration?: number
starred?: Date starred?: number
playCount?: number
streamUri: string userRating?: number
coverArt?: string averageRating?: number
} }
export type ListableItem = Song | AlbumListItem | Artist | PlaylistListItem export interface SearchResults {
artists: Artist[]
albums: Album[]
songs: Song[]
}
export type HomeLists = { [key: string]: AlbumListItem[] } export type StarrableItemType = 'album' | 'song' | 'artist'
export type StarrableItemType = 'song' | 'album' | 'artist' export type ListableItem = Album | Song | Artist | Playlist
export interface AlbumCoverArt {
albumId: string
coverArt?: string
}

84
app/models/map.ts Normal file
View File

@@ -0,0 +1,84 @@
import {
AlbumID3Element,
ArtistID3Element,
ArtistInfo2Element,
ChildElement,
PlaylistElement,
} from '@app/subsonic/elements'
import { Album, Artist, ArtistInfo, Playlist, Song } from './library'
import { TrackExt } from './trackplayer'
export function mapArtist(artist: ArtistID3Element): Artist {
return {
itemType: 'artist',
id: artist.id,
name: artist.name,
starred: artist.starred?.getTime(),
coverArt: artist.coverArt,
}
}
export function mapArtistInfo(id: string, info: ArtistInfo2Element): ArtistInfo {
return {
id,
smallImageUrl: info.smallImageUrl,
largeImageUrl: info.largeImageUrl,
}
}
export function mapAlbum(album: AlbumID3Element): Album {
return {
itemType: 'album',
id: album.id,
name: album.name,
artist: album.artist,
artistId: album.artistId,
starred: album.starred?.getTime(),
coverArt: album.coverArt,
year: album.year,
}
}
export function mapPlaylist(playlist: PlaylistElement): Playlist {
return {
itemType: 'playlist',
id: playlist.id,
name: playlist.name,
comment: playlist.comment,
coverArt: playlist.coverArt,
}
}
export function mapSong(song: ChildElement): Song {
return {
itemType: 'song',
id: song.id,
album: song.album,
albumId: song.albumId,
artist: song.artist,
artistId: song.artistId,
title: song.title,
track: song.track,
discNumber: song.discNumber,
duration: song.duration,
starred: song.starred?.getTime(),
playCount: song.playCount,
averageRating: song.averageRating,
userRating: song.userRating,
}
}
export function mapTrackExtToSong(track: TrackExt): Song {
return {
itemType: 'song',
id: track.id,
title: track.title as string,
artist: track.artist,
album: track.album,
duration: track.duration,
artistId: track.artistId,
albumId: track.albumId,
track: track.track,
discNumber: track.discNumber,
}
}

View File

@@ -30,23 +30,3 @@ export type ArtistFilterType = 'random' | 'starred' | 'alphabeticalByName'
export interface ArtistFilterSettings { export interface ArtistFilterSettings {
type: ArtistFilterType type: ArtistFilterType
} }
export interface AppSettings {
servers: Server[]
screens: {
home: {
lists: string[]
}
library: {
albums: AlbumFilterSettings
artists: ArtistFilterSettings
}
}
activeServer?: string
scrobble: boolean
estimateContentLength: boolean
maxBitrateWifi: number
maxBitrateMobile: number
minBuffer: number
maxBuffer: number
}

19
app/models/state.ts Normal file
View File

@@ -0,0 +1,19 @@
export interface ById<T> {
[id: string]: T
}
export type OneToMany = ById<string[]>
export interface OrderedById<T> {
byId: ById<T>
allIds: string[]
}
export interface PaginatedList {
[offset: number]: string[]
}
export interface CollectionById<T extends { id: string }> {
byId: ById<T>
allIds: string[]
}

18
app/models/trackplayer.ts Normal file
View File

@@ -0,0 +1,18 @@
import { Track } from 'react-native-track-player'
export type TrackExt = Track & {
id: string
coverArt?: string
artistId?: string
albumId?: string
track?: number
discNumber?: number
}
export type Progress = {
position: number
duration: number
buffered: number
}
export type QueueContextType = 'album' | 'playlist' | 'song' | 'artist'

View File

@@ -1,7 +1,6 @@
import NowPlayingBar from '@app/components/NowPlayingBar' import NowPlayingBar from '@app/components/NowPlayingBar'
import PressableOpacity from '@app/components/PressableOpacity' import PressableOpacity from '@app/components/PressableOpacity'
import { selectSettings } from '@app/state/settings' import { useFirstRun } from '@app/hooks/settings'
import { useStore } from '@app/state/store'
import colors from '@app/styles/colors' import colors from '@app/styles/colors'
import dimensions from '@app/styles/dimensions' import dimensions from '@app/styles/dimensions'
import font from '@app/styles/font' import font from '@app/styles/font'
@@ -10,7 +9,7 @@ import { BottomTabBarProps } from '@react-navigation/bottom-tabs'
import { BottomTabNavigationEventMap } from '@react-navigation/bottom-tabs/lib/typescript/src/types' import { BottomTabNavigationEventMap } from '@react-navigation/bottom-tabs/lib/typescript/src/types'
import { NavigationHelpers, ParamListBase } from '@react-navigation/native' import { NavigationHelpers, ParamListBase } from '@react-navigation/native'
import React from 'react' import React from 'react'
import { StyleSheet, Text, View, Image, ImageStyle } from 'react-native' import { Image, ImageStyle, StyleSheet, Text, View } from 'react-native'
const BottomTabButton = React.memo<{ const BottomTabButton = React.memo<{
routeKey: string routeKey: string
@@ -19,10 +18,11 @@ const BottomTabButton = React.memo<{
isFocused: boolean isFocused: boolean
icon: OutlineFillIcon icon: OutlineFillIcon
navigation: NavigationHelpers<ParamListBase, BottomTabNavigationEventMap> navigation: NavigationHelpers<ParamListBase, BottomTabNavigationEventMap>
}>(({ routeKey, label, name, isFocused, icon, navigation }) => { disabled?: boolean
const firstRun = useStore(selectSettings.firstRun) }>(({ routeKey, label, name, isFocused, icon, navigation, disabled }) => {
const firstRun = useFirstRun()
const disabled = firstRun && name !== 'settings' disabled = !!disabled || (firstRun && name !== 'settings')
const onPress = () => { const onPress = () => {
const event = navigation.emit({ const event = navigation.emit({
@@ -48,7 +48,9 @@ const BottomTabButton = React.memo<{
return ( return (
<PressableOpacity onPress={onPress} style={styles.button} disabled={disabled}> <PressableOpacity onPress={onPress} style={styles.button} disabled={disabled}>
<Image source={imgSource} style={imgStyle} fadeDuration={0} /> <Image source={imgSource} style={imgStyle} fadeDuration={0} />
<Text style={textStyle}>{label}</Text> <Text style={textStyle} numberOfLines={1} ellipsizeMode="clip">
{label}
</Text>
</PressableOpacity> </PressableOpacity>
) )
}) })
@@ -66,6 +68,13 @@ const BottomTabBar: React.FC<BottomTabBarProps> = ({ state, descriptors, navigat
? options.title ? options.title
: route.name : route.name
let iconKey = route.name
let disabled = false
if (route.name.endsWith('-disabled')) {
iconKey = route.name.split('-')[0]
disabled = true
}
return ( return (
<BottomTabButton <BottomTabButton
key={route.key} key={route.key}
@@ -73,8 +82,9 @@ const BottomTabBar: React.FC<BottomTabBarProps> = ({ state, descriptors, navigat
label={label} label={label}
name={route.name} name={route.name}
isFocused={state.index === index} isFocused={state.index === index}
icon={bottomTabIcons[route.name]} icon={bottomTabIcons[iconKey]}
navigation={navigation} navigation={navigation}
disabled={disabled}
/> />
) )
})} })}
@@ -93,6 +103,7 @@ const styles = StyleSheet.create({
}, },
button: { button: {
alignItems: 'center', alignItems: 'center',
flexGrow: 1,
flex: 1, flex: 1,
height: '100%', height: '100%',
}, },

View File

@@ -1,3 +1,6 @@
import { withSuspense } from '@app/components/withSuspense'
import { useFirstRun } from '@app/hooks/settings'
import { Album, Playlist } from '@app/models/library'
import BottomTabBar from '@app/navigation/BottomTabBar' import BottomTabBar from '@app/navigation/BottomTabBar'
import LibraryTopTabNavigator from '@app/navigation/LibraryTopTabNavigator' import LibraryTopTabNavigator from '@app/navigation/LibraryTopTabNavigator'
import ArtistView from '@app/screens/ArtistView' import ArtistView from '@app/screens/ArtistView'
@@ -8,21 +11,21 @@ import ServerView from '@app/screens/ServerView'
import SettingsView from '@app/screens/Settings' import SettingsView from '@app/screens/Settings'
import SongListView from '@app/screens/SongListView' import SongListView from '@app/screens/SongListView'
import WebViewScreen from '@app/screens/WebViewScreen' import WebViewScreen from '@app/screens/WebViewScreen'
import { selectSettings } from '@app/state/settings'
import { useStore } from '@app/state/store' import { useStore } from '@app/state/store'
import colors from '@app/styles/colors' import colors from '@app/styles/colors'
import font from '@app/styles/font' import font from '@app/styles/font'
import { BottomTabNavigationProp, createBottomTabNavigator } from '@react-navigation/bottom-tabs' import { BottomTabNavigationProp, createBottomTabNavigator } from '@react-navigation/bottom-tabs'
import { RouteProp, StackActions } from '@react-navigation/native' import { RouteProp, StackActions } from '@react-navigation/native'
import React, { useEffect } from 'react' import React, { useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { StyleSheet } from 'react-native' import { StyleSheet } from 'react-native'
import { createNativeStackNavigator, NativeStackNavigationProp } from 'react-native-screens/native-stack' import { createNativeStackNavigator, NativeStackNavigationProp } from 'react-native-screens/native-stack'
type TabStackParamList = { type TabStackParamList = {
main: undefined main: undefined
album: { id: string; title: string } album: { id: string; title: string; album?: Album }
artist: { id: string; title: string } artist: { id: string; title: string }
playlist: { id: string; title: string } playlist: { id: string; title: string; playlist?: Playlist }
results: { query: string; type: 'album' | 'song' | 'artist' } results: { query: string; type: 'album' | 'song' | 'artist' }
} }
@@ -33,9 +36,7 @@ type AlbumScreenProps = {
navigation: AlbumScreenNavigationProp navigation: AlbumScreenNavigationProp
} }
const AlbumScreen: React.FC<AlbumScreenProps> = ({ route }) => ( const AlbumScreen: React.FC<AlbumScreenProps> = ({ route }) => <SongListView {...route.params} type="album" />
<SongListView id={route.params.id} title={route.params.title} type="album" />
)
type ArtistScreenNavigationProp = NativeStackNavigationProp<TabStackParamList, 'artist'> type ArtistScreenNavigationProp = NativeStackNavigationProp<TabStackParamList, 'artist'>
type ArtistScreenRouteProp = RouteProp<TabStackParamList, 'artist'> type ArtistScreenRouteProp = RouteProp<TabStackParamList, 'artist'>
@@ -44,9 +45,7 @@ type ArtistScreenProps = {
navigation: ArtistScreenNavigationProp navigation: ArtistScreenNavigationProp
} }
const ArtistScreen: React.FC<ArtistScreenProps> = ({ route }) => ( const ArtistScreen: React.FC<ArtistScreenProps> = ({ route }) => <ArtistView {...route.params} />
<ArtistView id={route.params.id} title={route.params.title} />
)
type PlaylistScreenNavigationProp = NativeStackNavigationProp<TabStackParamList, 'playlist'> type PlaylistScreenNavigationProp = NativeStackNavigationProp<TabStackParamList, 'playlist'>
type PlaylistScreenRouteProp = RouteProp<TabStackParamList, 'playlist'> type PlaylistScreenRouteProp = RouteProp<TabStackParamList, 'playlist'>
@@ -55,9 +54,7 @@ type PlaylistScreenProps = {
navigation: PlaylistScreenNavigationProp navigation: PlaylistScreenNavigationProp
} }
const PlaylistScreen: React.FC<PlaylistScreenProps> = ({ route }) => ( const PlaylistScreen: React.FC<PlaylistScreenProps> = ({ route }) => <SongListView {...route.params} type="playlist" />
<SongListView id={route.params.id} title={route.params.title} type="playlist" />
)
type ResultsScreenNavigationProp = NativeStackNavigationProp<TabStackParamList, 'results'> type ResultsScreenNavigationProp = NativeStackNavigationProp<TabStackParamList, 'results'>
type ResultsScreenRouteProp = RouteProp<TabStackParamList, 'results'> type ResultsScreenRouteProp = RouteProp<TabStackParamList, 'results'>
@@ -66,9 +63,7 @@ type ResultsScreenProps = {
navigation: ResultsScreenNavigationProp navigation: ResultsScreenNavigationProp
} }
const ResultsScreen: React.FC<ResultsScreenProps> = ({ route }) => ( const ResultsScreen: React.FC<ResultsScreenProps> = ({ route }) => <SearchResultsView {...route.params} />
<SearchResultsView query={route.params.query} type={route.params.type} />
)
const styles = StyleSheet.create({ const styles = StyleSheet.create({
stackheaderStyle: { stackheaderStyle: {
@@ -122,8 +117,8 @@ const SearchTab = createTabStackNavigator(Search)
type SettingsStackParamList = { type SettingsStackParamList = {
main: undefined main: undefined
server?: { id?: string } server?: { id?: string; title?: string }
web: { uri: string } web: { uri: string; title?: string }
} }
type ServerScreenNavigationProp = NativeStackNavigationProp<SettingsStackParamList, 'server'> type ServerScreenNavigationProp = NativeStackNavigationProp<SettingsStackParamList, 'server'>
@@ -132,7 +127,9 @@ type ServerScreenProps = {
route: ServerScreenRouteProp route: ServerScreenRouteProp
navigation: ServerScreenNavigationProp navigation: ServerScreenNavigationProp
} }
const ServerScreen: React.FC<ServerScreenProps> = ({ route }) => <ServerView id={route.params?.id} /> const ServerScreen: React.FC<ServerScreenProps> = ({ route }) => (
<ServerView id={route.params?.id} title={route.params?.title} />
)
type WebScreenNavigationProp = NativeStackNavigationProp<SettingsStackParamList, 'web'> type WebScreenNavigationProp = NativeStackNavigationProp<SettingsStackParamList, 'web'>
type WebScreenRouteProp = RouteProp<SettingsStackParamList, 'web'> type WebScreenRouteProp = RouteProp<SettingsStackParamList, 'web'>
@@ -140,7 +137,9 @@ type WebScreenProps = {
route: WebScreenRouteProp route: WebScreenRouteProp
navigation: WebScreenNavigationProp navigation: WebScreenNavigationProp
} }
const WebScreen: React.FC<WebScreenProps> = ({ route }) => <WebViewScreen uri={route.params.uri} /> const WebScreen: React.FC<WebScreenProps> = ({ route }) => (
<WebViewScreen uri={route.params.uri} title={route.params.title} />
)
const SettingsStack = createNativeStackNavigator() const SettingsStack = createNativeStackNavigator()
@@ -152,7 +151,6 @@ const SettingsTab = () => {
name="server" name="server"
component={ServerScreen} component={ServerScreen}
options={{ options={{
title: 'Edit Server',
headerStyle: styles.stackheaderStyle, headerStyle: styles.stackheaderStyle,
headerHideShadow: true, headerHideShadow: true,
headerTintColor: 'white', headerTintColor: 'white',
@@ -163,7 +161,6 @@ const SettingsTab = () => {
name="web" name="web"
component={WebScreen} component={WebScreen}
options={{ options={{
title: 'Web View',
headerStyle: styles.stackheaderStyle, headerStyle: styles.stackheaderStyle,
headerHideShadow: true, headerHideShadow: true,
headerTintColor: 'white', headerTintColor: 'white',
@@ -176,17 +173,37 @@ const SettingsTab = () => {
const Tab = createBottomTabNavigator() const Tab = createBottomTabNavigator()
const BottomTabNavigator = () => { const BottomTabNavigator = withSuspense(() => {
const firstRun = useStore(selectSettings.firstRun) const { t } = useTranslation()
const firstRun = useFirstRun()
const disableMusicTabs = useStore(store => store.disableMusicTabs)
return ( return (
<Tab.Navigator tabBar={BottomTabBar} initialRouteName={firstRun ? 'settings' : 'home'}> <Tab.Navigator tabBar={BottomTabBar} initialRouteName={firstRun ? 'settings' : 'home'}>
<Tab.Screen name="home" component={HomeTab} options={{ tabBarLabel: 'Home' }} /> {disableMusicTabs ? (
<Tab.Screen name="library" component={LibraryTab} options={{ tabBarLabel: 'Library' }} /> <>
<Tab.Screen name="search" component={SearchTab} options={{ tabBarLabel: 'Search' }} /> <Tab.Screen name="home-disabled" children={() => null} options={{ tabBarLabel: t('navigation.tabs.home') }} />
<Tab.Screen name="settings" component={SettingsTab} options={{ tabBarLabel: 'Settings' }} /> <Tab.Screen
name="library-disabled"
children={() => null}
options={{ tabBarLabel: t('navigation.tabs.library') }}
/>
<Tab.Screen
name="search-disabled"
children={() => null}
options={{ tabBarLabel: t('navigation.tabs.search') }}
/>
</>
) : (
<>
<Tab.Screen name="home" component={HomeTab} options={{ tabBarLabel: t('navigation.tabs.home') }} />
<Tab.Screen name="library" component={LibraryTab} options={{ tabBarLabel: t('navigation.tabs.library') }} />
<Tab.Screen name="search" component={SearchTab} options={{ tabBarLabel: t('navigation.tabs.search') }} />
</>
)}
<Tab.Screen name="settings" component={SettingsTab} options={{ tabBarLabel: t('navigation.tabs.settings') }} />
</Tab.Navigator> </Tab.Navigator>
) )
} })
export default BottomTabNavigator export default BottomTabNavigator

View File

@@ -1,3 +1,4 @@
import { withSuspense } from '@app/components/withSuspense'
import AlbumsTab from '@app/screens/LibraryAlbums' import AlbumsTab from '@app/screens/LibraryAlbums'
import ArtistsTab from '@app/screens/LibraryArtists' import ArtistsTab from '@app/screens/LibraryArtists'
import PlaylistsTab from '@app/screens/LibraryPlaylists' import PlaylistsTab from '@app/screens/LibraryPlaylists'
@@ -6,28 +7,46 @@ import dimensions from '@app/styles/dimensions'
import font from '@app/styles/font' import font from '@app/styles/font'
import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs' import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs'
import React from 'react' import React from 'react'
import { StatusBar, StyleSheet } from 'react-native' import { useTranslation } from 'react-i18next'
import { StyleSheet } from 'react-native'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
const Tab = createMaterialTopTabNavigator() const Tab = createMaterialTopTabNavigator()
const LibraryTopTabNavigator = () => ( const LibraryTopTabNavigator = withSuspense(() => {
const { t } = useTranslation()
const marginTop = useSafeAreaInsets().top
return (
<Tab.Navigator <Tab.Navigator
tabBarOptions={{ tabBarOptions={{
style: styles.tabBar, style: [styles.tabBar, { marginTop }],
labelStyle: styles.tablabelStyle, labelStyle: styles.tablabelStyle,
indicatorStyle: styles.tabindicatorStyle, indicatorStyle: styles.tabindicatorStyle,
}} }}
initialRouteName="albums"> initialRouteName="albums">
<Tab.Screen name="albums" component={AlbumsTab} options={{ tabBarLabel: 'Albums' }} /> <Tab.Screen
<Tab.Screen name="artists" component={ArtistsTab} options={{ tabBarLabel: 'Artists' }} /> name="albums"
<Tab.Screen name="playlists" component={PlaylistsTab} options={{ tabBarLabel: 'Playlists' }} /> component={AlbumsTab}
options={{ tabBarLabel: t('resources.album.name', { count: 2 }) }}
/>
<Tab.Screen
name="artists"
component={ArtistsTab}
options={{ tabBarLabel: t('resources.artist.name', { count: 2 }) }}
/>
<Tab.Screen
name="playlists"
component={PlaylistsTab}
options={{ tabBarLabel: t('resources.playlist.name', { count: 2 }) }}
/>
</Tab.Navigator> </Tab.Navigator>
) )
})
const styles = StyleSheet.create({ const styles = StyleSheet.create({
tabBar: { tabBar: {
height: dimensions.header, height: dimensions.header,
marginTop: StatusBar.currentHeight,
backgroundColor: colors.gradient.high, backgroundColor: colors.gradient.high,
elevation: 0, elevation: 0,
justifyContent: 'center', justifyContent: 'center',

View File

@@ -1,3 +1,4 @@
import { withSuspense } from '@app/components/withSuspense'
import BottomTabNavigator from '@app/navigation/BottomTabNavigator' import BottomTabNavigator from '@app/navigation/BottomTabNavigator'
import NowPlayingQueue from '@app/screens/NowPlayingQueue' import NowPlayingQueue from '@app/screens/NowPlayingQueue'
import NowPlayingView from '@app/screens/NowPlayingView' import NowPlayingView from '@app/screens/NowPlayingView'
@@ -5,18 +6,22 @@ import colors from '@app/styles/colors'
import font from '@app/styles/font' import font from '@app/styles/font'
import { DarkTheme, NavigationContainer } from '@react-navigation/native' import { DarkTheme, NavigationContainer } from '@react-navigation/native'
import React from 'react' import React from 'react'
import { useTranslation } from 'react-i18next'
import { createNativeStackNavigator } from 'react-native-screens/native-stack' import { createNativeStackNavigator } from 'react-native-screens/native-stack'
const NowPlayingStack = createNativeStackNavigator() const NowPlayingStack = createNativeStackNavigator()
const NowPlayingNavigator = () => ( const NowPlayingNavigator = withSuspense(() => {
const { t } = useTranslation()
return (
<NowPlayingStack.Navigator> <NowPlayingStack.Navigator>
<NowPlayingStack.Screen name="main" component={NowPlayingView} options={{ headerShown: false }} /> <NowPlayingStack.Screen name="main" component={NowPlayingView} options={{ headerShown: false }} />
<NowPlayingStack.Screen <NowPlayingStack.Screen
name="queue" name="queue"
component={NowPlayingQueue} component={NowPlayingQueue}
options={{ options={{
title: 'Queue', title: t('resources.queue.name', { count: 1 }),
headerStyle: { headerStyle: {
backgroundColor: colors.gradient.high, backgroundColor: colors.gradient.high,
}, },
@@ -30,7 +35,8 @@ const NowPlayingNavigator = () => (
}} }}
/> />
</NowPlayingStack.Navigator> </NowPlayingStack.Navigator>
) )
})
const RootStack = createNativeStackNavigator() const RootStack = createNativeStackNavigator()

View File

@@ -1,8 +1,14 @@
import { getCurrentTrack, getPlayerState, TrackExt, trackPlayerCommands } from '@app/state/trackplayer' import { getCurrentTrack, getPlayerState, trackPlayerCommands } from '@app/state/trackplayer'
import TrackPlayer, { Event, State } from 'react-native-track-player'
import { useStore } from './state/store'
import { unstable_batchedUpdates } from 'react-native'
import NetInfo, { NetInfoStateType } from '@react-native-community/netinfo' import NetInfo, { NetInfoStateType } from '@react-native-community/netinfo'
import _ from 'lodash'
import { unstable_batchedUpdates } from 'react-native'
import TrackPlayer, { Event, State } from 'react-native-track-player'
import { fetchAlbum, FetchExisingFileOptions, fetchExistingFile, fetchFile, FetchFileOptions } from './hooks/fetch'
import qk from './hooks/queryKeys'
import queryClient from './queryClient'
import queueService from './queueservice'
import { useStore } from './state/store'
import { ReturnedPromiseResolvedType } from './util/types'
const reset = () => { const reset = () => {
unstable_batchedUpdates(() => { unstable_batchedUpdates(() => {
@@ -28,9 +34,15 @@ const setNetState = (netState: 'mobile' | 'wifi') => {
}) })
} }
const rebuildQueue = () => { const rebuildQueue = (forcePlay?: boolean) => {
unstable_batchedUpdates(() => { unstable_batchedUpdates(() => {
useStore.getState().rebuildQueue(useStore.getState().playerState === State.Playing) useStore.getState().rebuildQueue(forcePlay)
})
}
const updateQueue = () => {
unstable_batchedUpdates(() => {
useStore.getState().updateQueue()
}) })
} }
@@ -40,17 +52,79 @@ const setDuckPaused = (duckPaused: boolean) => {
}) })
} }
const setQueryDataAlbum = (queryKey: any, data: ReturnedPromiseResolvedType<typeof fetchAlbum>) => {
unstable_batchedUpdates(() => {
queryClient.setQueryData(queryKey, data)
})
}
const setQueryDataExistingFiles = (queryKey: any, data: ReturnedPromiseResolvedType<typeof fetchExistingFile>) => {
unstable_batchedUpdates(() => {
queryClient.setQueryData(queryKey, data)
})
}
const setQueryDataCoverArt = (queryKey: any, data: ReturnedPromiseResolvedType<typeof fetchFile>) => {
unstable_batchedUpdates(() => {
queryClient.setQueryData(queryKey, data)
})
}
function getClient() {
const client = useStore.getState().client
if (!client) {
throw new Error('no client!')
}
return client
}
async function getAlbum(id: string) {
try {
const res = await fetchAlbum(id, getClient())
setQueryDataAlbum(qk.album(id), res)
return res
} catch {}
}
async function getCoverArtThumbExisting(coverArt: string) {
const serverId = useStore.getState().settings.activeServerId
const options: FetchExisingFileOptions = { itemType: 'coverArtThumb', itemId: coverArt }
try {
const res = await fetchExistingFile(options, serverId)
setQueryDataExistingFiles(qk.existingFiles(options.itemType, options.itemId), res)
return res
} catch {}
}
async function getCoverArtThumb(coverArt: string) {
const serverId = useStore.getState().settings.activeServerId
const fromUrl = getClient().getCoverArtUri({ id: coverArt, size: '256' })
const options: FetchFileOptions = {
itemType: 'coverArtThumb',
itemId: coverArt,
fromUrl,
expectedContentType: 'image',
}
try {
const res = await fetchFile(options, serverId)
setQueryDataCoverArt(qk.coverArt(coverArt, 'thumbnail'), res)
return res
} catch {}
}
let serviceCreated = false let serviceCreated = false
const createService = async () => { const createService = async () => {
useStore.subscribe( useStore.subscribe(
(currentTrack?: TrackExt) => { state => state.currentTrack?.id,
if (currentTrack) { (currentTrackId?: string) => {
useStore.getState().scrobbleTrack(currentTrack.id) if (currentTrackId) {
useStore.getState().scrobbleTrack(currentTrackId)
} }
}, },
state => state.currentTrack,
(prev, next) => prev?.id === next?.id,
) )
NetInfo.fetch().then(state => { NetInfo.fetch().then(state => {
@@ -140,9 +214,81 @@ const createService = async () => {
// fix for ExoPlayer aborting playback while esimating content length // fix for ExoPlayer aborting playback while esimating content length
if (code === 'playback-source' && message.includes('416')) { if (code === 'playback-source' && message.includes('416')) {
rebuildQueue() rebuildQueue(true)
} }
}) })
queueService.addListener('set', async ({ queue }) => {
const contextId = useStore.getState().queueContextId
const throwIfQueueChanged = () => {
if (contextId !== useStore.getState().queueContextId) {
throw 'queue-changed'
}
}
const albumIds = _.uniq(queue.map(s => s.albumId)).filter((id): id is string => id !== undefined)
const albumIdImagePath: { [albumId: string]: string | undefined } = {}
for (const albumId of albumIds) {
let coverArt = queryClient.getQueryData<string>(qk.albumCoverArt(albumId))
if (!coverArt) {
throwIfQueueChanged()
console.log('no cached coverArt for album', albumId, 'getting album...')
coverArt = (await getAlbum(albumId))?.album.coverArt
if (!coverArt) {
continue
}
}
let imagePath =
queryClient.getQueryData<string>(qk.existingFiles('coverArtThumb', coverArt)) ||
queryClient.getQueryData<string>(qk.coverArt(coverArt, 'thumbnail'))
if (!imagePath) {
throwIfQueueChanged()
console.log('no cached image for', coverArt, 'getting file...')
imagePath = (await getCoverArtThumbExisting(coverArt)) || (await getCoverArtThumb(coverArt))
if (!imagePath) {
continue
}
}
albumIdImagePath[albumId] = imagePath
}
for (let i = 0; i < queue.length; i++) {
const track = queue[i]
if (typeof track.artwork === 'string') {
continue
}
if (!track.albumId) {
continue
}
let imagePath = albumIdImagePath[track.albumId]
if (!imagePath) {
continue
}
try {
throwIfQueueChanged()
let trackIdx = i
const shuffleOrder = useStore.getState().shuffleOrder
if (shuffleOrder) {
trackIdx = shuffleOrder.indexOf(i)
}
await TrackPlayer.updateMetadataForTrack(trackIdx, { ...track, artwork: `file://${imagePath}` })
} catch {
break
}
}
await trackPlayerCommands.enqueue(async () => {
updateQueue()
})
})
} }
module.exports = async function () { module.exports = async function () {

5
app/queryClient.ts Normal file
View File

@@ -0,0 +1,5 @@
import { QueryClient } from 'react-query'
const client = new QueryClient()
export default client

18
app/queueservice.ts Normal file
View File

@@ -0,0 +1,18 @@
/* eslint-disable no-dupe-class-members */
import { EmitterSubscription, NativeEventEmitter } from 'react-native'
import { TrackExt } from './models/trackplayer'
class QueueService extends NativeEventEmitter {
addListener(eventType: 'set', listener: (event: { queue: TrackExt[] }) => void): EmitterSubscription
addListener(eventType: string, listener: (event: any) => void, context?: Object): EmitterSubscription {
return super.addListener(eventType, listener, context)
}
emit(eventType: 'set', event: { queue: TrackExt[] }): void
emit(eventType: string, ...params: any[]): void {
super.emit(eventType, ...params)
}
}
const queueService = new QueueService()
export default queueService

View File

@@ -5,16 +5,18 @@ import GradientScrollView from '@app/components/GradientScrollView'
import Header from '@app/components/Header' import Header from '@app/components/Header'
import HeaderBar from '@app/components/HeaderBar' import HeaderBar from '@app/components/HeaderBar'
import ListItem from '@app/components/ListItem' import ListItem from '@app/components/ListItem'
import { useArtistInfo } from '@app/hooks/music' import { withSuspenseMemo } from '@app/components/withSuspense'
import { Album, Song } from '@app/models/music' import { useQueryArtist, useQueryArtistTopSongs } from '@app/hooks/query'
import { useStore } from '@app/state/store' import { useSetQueue } from '@app/hooks/trackplayer'
import { selectTrackPlayer } from '@app/state/trackplayer' import { Album, Song } from '@app/models/library'
import colors from '@app/styles/colors' import colors from '@app/styles/colors'
import dimensions from '@app/styles/dimensions' import dimensions from '@app/styles/dimensions'
import font from '@app/styles/font' import font from '@app/styles/font'
import { useLayout } from '@react-native-community/hooks' import { useLayout } from '@react-native-community/hooks'
import { useNavigation } from '@react-navigation/native' import { useNavigation } from '@react-navigation/native'
import equal from 'fast-deep-equal/es6/react'
import React from 'react' import React from 'react'
import { useTranslation } from 'react-i18next'
import { ActivityIndicator, StyleSheet, Text, View } from 'react-native' import { ActivityIndicator, StyleSheet, Text, View } from 'react-native'
import { useAnimatedScrollHandler, useAnimatedStyle, useSharedValue } from 'react-native-reanimated' import { useAnimatedScrollHandler, useAnimatedStyle, useSharedValue } from 'react-native-reanimated'
@@ -32,40 +34,72 @@ const AlbumItem = React.memo<{
return ( return (
<AlbumContextPressable <AlbumContextPressable
album={album} album={album}
onPress={() => navigation.navigate('album', { id: album.id, title: album.name })} onPress={() => navigation.navigate('album', { id: album.id, title: album.name, album })}
menuStyle={[styles.albumItem, { width }]} menuStyle={[styles.albumItem, { width }]}
triggerOuterWrapperStyle={{ width }}> triggerOuterWrapperStyle={{ width }}>
<CoverArt type="cover" coverArt={album.coverArt} style={{ height, width }} resizeMode={'cover'} /> <CoverArt type="cover" coverArt={album.coverArt} style={{ height, width }} resizeMode="cover" size="thumbnail" />
<Text style={styles.albumTitle}>{album.name}</Text> <Text style={styles.albumTitle}>{album.name}</Text>
<Text style={styles.albumYear}> {album.year ? album.year : ''}</Text> <Text style={styles.albumYear}> {album.year ? album.year : ''}</Text>
</AlbumContextPressable> </AlbumContextPressable>
) )
}) }, equal)
const TopSongs = React.memo<{ const TopSongs = withSuspenseMemo<{
songs: Song[] songs: Song[]
name: string name: string
artistId: string }>(
}>(({ songs, name, artistId }) => { ({ songs, name }) => {
const setQueue = useStore(selectTrackPlayer.setQueue) const { setQueue, contextId } = useSetQueue('artist', songs)
const { t } = useTranslation()
return ( return (
<> <>
<Header>Top Songs</Header> <Header>{t('resources.song.lists.artistTopSongs')}</Header>
{songs.map((s, i) => ( {songs.slice(0, 5).map((s, i) => (
<ListItem <ListItem
key={i} key={i}
item={s} item={s}
contextId={artistId} contextId={contextId}
queueId={i} queueId={i}
showArt={true} showArt={true}
subtitle={s.album} subtitle={s.album}
onPress={() => setQueue(songs, name, 'artist', artistId, i)} onPress={() => setQueue({ title: name, playTrack: i })}
/> />
))} ))}
</> </>
) )
}) },
null,
equal,
)
const ArtistAlbums = withSuspenseMemo<{
albums: Album[]
}>(
({ albums }) => {
const albumsLayout = useLayout()
const { t } = useTranslation()
const sortedAlbums = [...albums]
.sort((a, b) => a.name.localeCompare(b.name))
.sort((a, b) => (b.year || 0) - (a.year || 0))
const albumSize = albumsLayout.width / 2 - styles.contentContainer.paddingHorizontal / 2
return (
<>
<Header>{t('resources.album.name', { count: 2 })}</Header>
<View style={styles.albums} onLayout={albumsLayout.onLayout}>
{sortedAlbums.map(a => (
<AlbumItem key={a.id} album={a} height={albumSize} width={albumSize} />
))}
</View>
</>
)
},
null,
equal,
)
const ArtistViewFallback = React.memo(() => ( const ArtistViewFallback = React.memo(() => (
<GradientBackground style={styles.fallback}> <GradientBackground style={styles.fallback}>
@@ -74,8 +108,9 @@ const ArtistViewFallback = React.memo(() => (
)) ))
const ArtistView = React.memo<{ id: string; title: string }>(({ id, title }) => { const ArtistView = React.memo<{ id: string; title: string }>(({ id, title }) => {
const artist = useArtistInfo(id) const { data: artistData } = useQueryArtist(id)
const albumsLayout = useLayout() const { data: topSongs, isError } = useQueryArtistTopSongs(artistData?.artist?.name)
const coverLayout = useLayout() const coverLayout = useLayout()
const headerOpacity = useSharedValue(0) const headerOpacity = useSharedValue(0)
@@ -91,15 +126,11 @@ const ArtistView = React.memo<{ id: string; title: string }>(({ id, title }) =>
} }
}) })
const albumSize = albumsLayout.width / 2 - styles.contentContainer.paddingHorizontal / 2 if (!artistData) {
if (!artist) {
return <ArtistViewFallback /> return <ArtistViewFallback />
} }
const _albums = [...artist.albums] const { artist, albums } = artistData
.sort((a, b) => a.name.localeCompare(b.name))
.sort((a, b) => (b.year || 0) - (a.year || 0))
return ( return (
<View style={styles.container}> <View style={styles.container}>
@@ -110,22 +141,23 @@ const ArtistView = React.memo<{ id: string; title: string }>(({ id, title }) =>
style={styles.scroll} style={styles.scroll}
contentContainerStyle={styles.scrollContent} contentContainerStyle={styles.scrollContent}
onScroll={onScroll}> onScroll={onScroll}>
<CoverArt type="artist" size="original" artistId={artist.id} style={styles.artistCover} resizeMode={'cover'} /> <CoverArt type="artist" size="original" artistId={artist.id} style={styles.artistCover} resizeMode="cover" />
<View style={styles.titleContainer}> <View style={styles.titleContainer}>
<Text style={styles.title}>{artist.name}</Text> <Text style={styles.title}>{artist.name}</Text>
</View> </View>
<View style={styles.contentContainer}> <View style={styles.contentContainer}>
{artist.topSongs.length > 0 ? ( {(topSongs || isError) && artist ? (
<TopSongs songs={artist.topSongs} name={artist.name} artistId={artist.id} /> topSongs && topSongs.length > 0 ? (
<>
<TopSongs songs={topSongs} name={artist.name} />
<ArtistAlbums albums={albums} />
</>
) : ( ) : (
<></> <ArtistAlbums albums={albums} />
)
) : (
<ActivityIndicator size="large" color={colors.accent} style={styles.loading} />
)} )}
<Header>Albums</Header>
<View style={styles.albums} onLayout={albumsLayout.onLayout}>
{_albums.map(a => (
<AlbumItem key={a.id} album={a} height={albumSize} width={albumSize} />
))}
</View>
</View> </View>
</GradientScrollView> </GradientScrollView>
</View> </View>
@@ -200,6 +232,9 @@ const styles = StyleSheet.create({
fontFamily: font.regular, fontFamily: font.regular,
textAlign: 'center', textAlign: 'center',
}, },
loading: {
marginTop: 30,
},
}) })
export default ArtistView export default ArtistView

View File

@@ -3,27 +3,22 @@ import CoverArt from '@app/components/CoverArt'
import GradientScrollView from '@app/components/GradientScrollView' import GradientScrollView from '@app/components/GradientScrollView'
import Header from '@app/components/Header' import Header from '@app/components/Header'
import NothingHere from '@app/components/NothingHere' import NothingHere from '@app/components/NothingHere'
import { useActiveServerRefresh } from '@app/hooks/server' import { withSuspenseMemo } from '@app/components/withSuspense'
import { AlbumListItem } from '@app/models/music' import { useQueryHomeLists } from '@app/hooks/query'
import { selectMusic } from '@app/state/music' import { Album } from '@app/models/library'
import { selectSettings } from '@app/state/settings' import { useStoreDeep } from '@app/state/store'
import { useStore } from '@app/state/store'
import colors from '@app/styles/colors' import colors from '@app/styles/colors'
import font from '@app/styles/font' import font from '@app/styles/font'
import { GetAlbumListType } from '@app/subsonic/params' import { GetAlbumList2TypeBase } from '@app/subsonic/params'
import { useNavigation } from '@react-navigation/native' import { useNavigation } from '@react-navigation/native'
import React, { useCallback } from 'react' import equal from 'fast-deep-equal/es6/react'
import { RefreshControl, ScrollView, StatusBar, StyleSheet, Text, View } from 'react-native' import React from 'react'
import { useTranslation } from 'react-i18next'
const titles: { [key in GetAlbumListType]?: string } = { import { RefreshControl, ScrollView, StyleSheet, Text, View } from 'react-native'
recent: 'Recently Played', import { useSafeAreaInsets } from 'react-native-safe-area-context'
random: 'Random Albums',
frequent: 'Frequently Played',
starred: 'Starred Albums',
}
const AlbumItem = React.memo<{ const AlbumItem = React.memo<{
album: AlbumListItem album: Album
}>(({ album }) => { }>(({ album }) => {
const navigation = useNavigation() const navigation = useNavigation()
@@ -31,12 +26,13 @@ const AlbumItem = React.memo<{
<AlbumContextPressable <AlbumContextPressable
album={album} album={album}
triggerWrapperStyle={styles.item} triggerWrapperStyle={styles.item}
onPress={() => navigation.navigate('album', { id: album.id, title: album.name })}> onPress={() => navigation.navigate('album', { id: album.id, title: album.name, album })}>
<CoverArt <CoverArt
type="cover" type="cover"
coverArt={album.coverArt} coverArt={album.coverArt}
style={{ height: styles.item.width, width: styles.item.width }} style={{ height: styles.item.width, width: styles.item.width }}
resizeMode={'cover'} resizeMode="cover"
size="thumbnail"
/> />
<Text style={styles.title} numberOfLines={1}> <Text style={styles.title} numberOfLines={1}>
{album.name} {album.name}
@@ -46,12 +42,18 @@ const AlbumItem = React.memo<{
</Text> </Text>
</AlbumContextPressable> </AlbumContextPressable>
) )
}, equal)
const CategoryHeader = withSuspenseMemo<{ type: string }>(({ type }) => {
const { t } = useTranslation()
console.log('type', type, t(`resources.album.lists.${type}`))
return <Header style={styles.header}>{t(`resources.album.lists.${type}`)}</Header>
}) })
const Category = React.memo<{ const Category = React.memo<{
name?: string type: string
data: AlbumListItem[] albums: Album[]
}>(({ name, data }) => { }>(({ type, albums }) => {
const Albums = () => ( const Albums = () => (
<ScrollView <ScrollView
horizontal={true} horizontal={true}
@@ -59,8 +61,8 @@ const Category = React.memo<{
overScrollMode={'never'} overScrollMode={'never'}
style={styles.artScroll} style={styles.artScroll}
contentContainerStyle={styles.artScrollContent}> contentContainerStyle={styles.artScrollContent}>
{data.map(album => ( {albums.map(a => (
<AlbumItem key={album.id} album={album} /> <AlbumItem key={a.id} album={a} />
))} ))}
</ScrollView> </ScrollView>
) )
@@ -73,42 +75,34 @@ const Category = React.memo<{
return ( return (
<View style={styles.category}> <View style={styles.category}>
<Header style={styles.header}>{name}</Header> <CategoryHeader type={type} />
{data.length > 0 ? <Albums /> : <Nothing />} {albums.length > 0 ? <Albums /> : <Nothing />}
</View> </View>
) )
}) }, equal)
const Home = () => { const Home = () => {
const types = useStore(selectSettings.homeLists) const types = useStoreDeep(store => store.settings.screens.home.listTypes)
const lists = useStore(selectMusic.homeLists) const listQueries = useQueryHomeLists(types as GetAlbumList2TypeBase[], 20)
const updating = useStore(selectMusic.homeListsUpdating) const paddingTop = useSafeAreaInsets().top
const update = useStore(selectMusic.fetchHomeLists)
const clear = useStore(selectMusic.clearHomeLists)
useActiveServerRefresh(
useCallback(() => {
clear()
update()
}, [clear, update]),
)
return ( return (
<GradientScrollView <GradientScrollView
style={styles.scroll} style={styles.scroll}
contentContainerStyle={styles.scrollContentContainer} contentContainerStyle={{ paddingTop }}
refreshControl={ refreshControl={
<RefreshControl <RefreshControl
refreshing={updating} refreshing={listQueries.some(q => q.isLoading)}
onRefresh={update} onRefresh={() => listQueries.forEach(q => q.refetch())}
colors={[colors.accent, colors.accentLow]} colors={[colors.accent, colors.accentLow]}
progressViewOffset={StatusBar.currentHeight} progressViewOffset={paddingTop}
/> />
}> }>
<View style={styles.content}> <View style={styles.content}>
{types.map(type => ( {types.map(type => {
<Category key={type} name={titles[type as GetAlbumListType]} data={type in lists ? lists[type] : []} /> const query = listQueries.find(list => list.data?.type === type)
))} return <Category key={type} type={type} albums={query?.data?.albums || []} />
})}
</View> </View>
</GradientScrollView> </GradientScrollView>
) )
@@ -118,9 +112,6 @@ const styles = StyleSheet.create({
scroll: { scroll: {
flex: 1, flex: 1,
}, },
scrollContentContainer: {
paddingTop: StatusBar.currentHeight,
},
content: { content: {
paddingBottom: 20, paddingBottom: 20,
}, },

View File

@@ -1,33 +1,44 @@
import { AlbumContextPressable } from '@app/components/ContextMenu' import { AlbumContextPressable } from '@app/components/ContextMenu'
import CoverArt from '@app/components/CoverArt' import CoverArt from '@app/components/CoverArt'
import FilterButton, { OptionData } from '@app/components/FilterButton' import FilterButton from '@app/components/FilterButton'
import GradientFlatList from '@app/components/GradientFlatList' import GradientFlatList from '@app/components/GradientFlatList'
import { useFetchPaginatedList } from '@app/hooks/list' import { withSuspenseMemo } from '@app/components/withSuspense'
import { Album, AlbumListItem } from '@app/models/music' import { useQueryAlbumList } from '@app/hooks/query'
import { selectMusic } from '@app/state/music' import { Album } from '@app/models/library'
import { selectSettings } from '@app/state/settings' import { useStore, useStoreDeep } from '@app/state/store'
import { useStore } from '@app/state/store'
import colors from '@app/styles/colors' import colors from '@app/styles/colors'
import font from '@app/styles/font' import font from '@app/styles/font'
import { GetAlbumList2Type } from '@app/subsonic/params' import { GetAlbumList2TypeBase } from '@app/subsonic/params'
import { useNavigation } from '@react-navigation/native' import { useNavigation } from '@react-navigation/native'
import React, { useEffect } from 'react' import equal from 'fast-deep-equal/es6/react'
import React from 'react'
import { useTranslation } from 'react-i18next'
import { StyleSheet, Text, useWindowDimensions, View } from 'react-native' import { StyleSheet, Text, useWindowDimensions, View } from 'react-native'
const AlbumItem = React.memo<{ const AlbumItem = React.memo<{
album: AlbumListItem album: Album
size: number size: number
height: number height: number
}>(({ album, size, height }) => { }>(({ album, size, height }) => {
const navigation = useNavigation() const navigation = useNavigation()
if (!album) {
return <></>
}
return ( return (
<AlbumContextPressable <AlbumContextPressable
album={album} album={album}
menuStyle={[styles.itemMenu, { width: size }]} menuStyle={[styles.itemMenu, { width: size }]}
triggerWrapperStyle={[styles.itemWrapper, { height }]} triggerWrapperStyle={[styles.itemWrapper, { height }]}
onPress={() => navigation.navigate('album', { id: album.id, title: album.name })}> onPress={() => navigation.navigate('album', { id: album.id, title: album.name, album })}>
<CoverArt type="cover" coverArt={album.coverArt} style={{ height: size, width: size }} resizeMode={'cover'} /> <CoverArt
type="cover"
coverArt={album.coverArt}
style={{ height: size, width: size }}
resizeMode="cover"
size="thumbnail"
/>
<View style={styles.itemDetails}> <View style={styles.itemDetails}>
<Text style={styles.title} numberOfLines={1}> <Text style={styles.title} numberOfLines={1}>
{album.name} {album.name}
@@ -38,62 +49,64 @@ const AlbumItem = React.memo<{
</View> </View>
</AlbumContextPressable> </AlbumContextPressable>
) )
}) }, equal)
const AlbumListRenderItem: React.FC<{ const AlbumListRenderItem: React.FC<{
item: { album: Album; size: number; height: number } item: { album: Album; size: number; height: number }
}> = ({ item }) => <AlbumItem album={item.album} size={item.size} height={item.height} /> }> = ({ item }) => <AlbumItem album={item.album} size={item.size} height={item.height} />
const filterOptions: OptionData[] = [ const filterValues: GetAlbumList2TypeBase[] = [
{ text: 'By Name', value: 'alphabeticalByName' }, 'alphabeticalByName', //
{ text: 'By Artist', value: 'alphabeticalByArtist' }, 'alphabeticalByArtist',
{ text: 'Newest', value: 'newest' }, 'newest',
{ text: 'Frequent', value: 'frequent' }, 'frequent',
{ text: 'Recent', value: 'recent' }, 'recent',
{ text: 'Starred', value: 'starred' }, 'starred',
{ text: 'Random', value: 'random' }, 'random',
// { text: 'By Year...', value: 'byYear' },
// { text: 'By Genre...', value: 'byGenre' },
] ]
const AlbumFilterButton = withSuspenseMemo(() => {
const { t } = useTranslation()
const filterType = useStoreDeep(store => store.settings.screens.library.albumsFilter.type)
const setFilterType = useStore(store => store.setLibraryAlbumFilterType)
return (
<FilterButton
data={filterValues.map(value => ({ value, text: t(`resources.album.lists.${value}`) }))}
value={filterType}
onSelect={selection => {
setFilterType(selection as GetAlbumList2TypeBase)
}}
title={t('resources.album.lists.sort')}
/>
)
})
const AlbumsList = () => { const AlbumsList = () => {
const fetchAlbums = useStore(selectMusic.fetchAlbums) const filterType = useStoreDeep(store => store.settings.screens.library.albumsFilter.type)
const { list, refreshing, refresh, reset, fetchNextPage } = useFetchPaginatedList(fetchAlbums, 300) const { isLoading, data, fetchNextPage, refetch } = useQueryAlbumList(filterType as GetAlbumList2TypeBase, 300)
const filter = useStore(selectSettings.libraryAlbumFilter)
const setFilter = useStore(selectSettings.setLibraryAlbumFilter)
const layout = useWindowDimensions() const layout = useWindowDimensions()
const size = layout.width / 3 - styles.itemWrapper.marginHorizontal * 2 const size = layout.width / 3 - styles.itemWrapper.marginHorizontal * 2
const height = size + 36 const height = size + 36
useEffect(() => reset(), [reset, filter])
return ( return (
<View style={styles.container}> <View style={styles.container}>
<GradientFlatList <GradientFlatList
data={list.map(album => ({ album, size, height }))} data={data ? data.pages.flatMap(albums => albums.map(album => ({ album, size, height }))) : []}
renderItem={AlbumListRenderItem} renderItem={AlbumListRenderItem}
keyExtractor={item => item.album.id} keyExtractor={item => item.album.id}
numColumns={3} numColumns={3}
removeClippedSubviews={true} removeClippedSubviews={true}
refreshing={refreshing} refreshing={isLoading}
onRefresh={refresh} onRefresh={refetch}
overScrollMode="never" overScrollMode="never"
onEndReached={fetchNextPage} onEndReached={() => fetchNextPage()}
onEndReachedThreshold={6} onEndReachedThreshold={6}
windowSize={5} windowSize={5}
/> />
<FilterButton <AlbumFilterButton />
data={filterOptions}
value={filter.type}
onSelect={selection => {
setFilter({
...filter,
type: selection as GetAlbumList2Type,
})
}}
/>
</View> </View>
) )
} }

View File

@@ -1,45 +1,68 @@
import FilterButton, { OptionData } from '@app/components/FilterButton' import FilterButton from '@app/components/FilterButton'
import GradientFlatList from '@app/components/GradientFlatList' import GradientFlatList from '@app/components/GradientFlatList'
import ListItem from '@app/components/ListItem' import ListItem from '@app/components/ListItem'
import { useFetchList } from '@app/hooks/list' import { withSuspenseMemo } from '@app/components/withSuspense'
import { Artist } from '@app/models/music' import { useQueryArtists } from '@app/hooks/query'
import { Artist } from '@app/models/library'
import { ArtistFilterType } from '@app/models/settings' import { ArtistFilterType } from '@app/models/settings'
import { selectMusic } from '@app/state/music' import { useStore, useStoreDeep } from '@app/state/store'
import { selectSettings } from '@app/state/settings'
import { useStore } from '@app/state/store'
import React, { useEffect, useState } from 'react' import React, { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { StyleSheet, View } from 'react-native' import { StyleSheet, View } from 'react-native'
const ArtistRenderItem: React.FC<{ item: Artist }> = ({ item }) => ( const ArtistRenderItem: React.FC<{ item: Artist }> = ({ item }) => (
<ListItem item={item} showArt={true} showStar={false} listStyle="big" style={styles.listItem} /> <ListItem item={item} showArt={true} showStar={false} listStyle="big" style={styles.listItem} />
) )
const filterOptions: OptionData[] = [ const filterValues: ArtistFilterType[] = [
{ text: 'By Name', value: 'alphabeticalByName' }, 'alphabeticalByName', //
{ text: 'Starred', value: 'starred' }, 'starred',
{ text: 'Random', value: 'random' }, 'random',
] ]
const ArtistFilterButton = withSuspenseMemo(() => {
const { t } = useTranslation()
const filterType = useStoreDeep(store => store.settings.screens.library.artistsFilter.type)
const setFilterType = useStore(store => store.setLibraryArtistFilterType)
return (
<FilterButton
data={filterValues.map(value => ({ value, text: t(`resources.artist.lists.${value}`) }))}
value={filterType}
onSelect={selection => setFilterType(selection as ArtistFilterType)}
title={t('resources.artist.lists.sort')}
/>
)
})
const ArtistsList = () => { const ArtistsList = () => {
const fetchArtists = useStore(selectMusic.fetchArtists) const filterType = useStore(store => store.settings.screens.library.artistsFilter.type)
const { list, refreshing, refresh } = useFetchList(fetchArtists)
const filter = useStore(selectSettings.libraryArtistFilter) const { isLoading, data, refetch } = useQueryArtists()
const setFilter = useStore(selectSettings.setLibraryArtistFiler)
const [sortedList, setSortedList] = useState<Artist[]>([]) const [sortedList, setSortedList] = useState<Artist[]>([])
useEffect(() => { useEffect(() => {
switch (filter.type) { if (!data) {
setSortedList([])
return
}
const list = Object.values(data.byId)
switch (filterType) {
case 'random': case 'random':
setSortedList([...list].sort(() => Math.random() - 0.5)) setSortedList([...list].sort(() => Math.random() - 0.5))
break break
case 'starred': case 'starred':
setSortedList([...list].filter(a => a.starred)) setSortedList([...list].filter(a => a.starred))
break break
case 'alphabeticalByName':
setSortedList(data.allIds.map(id => data.byId[id]))
break
default: default:
setSortedList([...list]) setSortedList([...list])
break break
} }
}, [list, filter]) }, [filterType, data])
return ( return (
<View style={styles.container}> <View style={styles.container}>
@@ -47,22 +70,13 @@ const ArtistsList = () => {
data={sortedList} data={sortedList}
renderItem={ArtistRenderItem} renderItem={ArtistRenderItem}
keyExtractor={item => item.id} keyExtractor={item => item.id}
onRefresh={refresh} onRefresh={refetch}
refreshing={refreshing} refreshing={isLoading}
overScrollMode="never" overScrollMode="never"
windowSize={3} windowSize={3}
contentMarginTop={6} contentMarginTop={6}
/> />
<FilterButton <ArtistFilterButton />
data={filterOptions}
value={filter.type}
onSelect={selection => {
setFilter({
...filter,
type: selection as ArtistFilterType,
})
}}
/>
</View> </View>
) )
} }

View File

@@ -1,27 +1,25 @@
import GradientFlatList from '@app/components/GradientFlatList' import GradientFlatList from '@app/components/GradientFlatList'
import ListItem from '@app/components/ListItem' import ListItem from '@app/components/ListItem'
import { useFetchList } from '@app/hooks/list' import { useQueryPlaylists } from '@app/hooks/query'
import { PlaylistListItem } from '@app/models/music' import { Playlist } from '@app/models/library'
import { selectMusic } from '@app/state/music' import { mapById } from '@app/util/state'
import { useStore } from '@app/state/store'
import React from 'react' import React from 'react'
import { StyleSheet } from 'react-native' import { StyleSheet } from 'react-native'
const PlaylistRenderItem: React.FC<{ item: PlaylistListItem }> = ({ item }) => ( const PlaylistRenderItem: React.FC<{ item: Playlist }> = ({ item }) => (
<ListItem item={item} showArt={true} showStar={false} listStyle="big" style={styles.listItem} /> <ListItem item={item} showArt={true} showStar={false} listStyle="big" style={styles.listItem} />
) )
const PlaylistsList = () => { const PlaylistsList = () => {
const fetchPlaylists = useStore(selectMusic.fetchPlaylists) const { isLoading, data, refetch } = useQueryPlaylists()
const { list, refreshing, refresh } = useFetchList(fetchPlaylists)
return ( return (
<GradientFlatList <GradientFlatList
data={list} data={data ? mapById(data?.byId, data?.allIds) : []}
renderItem={PlaylistRenderItem} renderItem={PlaylistRenderItem}
keyExtractor={item => item.id} keyExtractor={item => item.id}
onRefresh={refresh} onRefresh={refetch}
refreshing={refreshing} refreshing={isLoading}
overScrollMode="never" overScrollMode="never"
windowSize={5} windowSize={5}
contentMarginTop={6} contentMarginTop={6}

View File

@@ -2,10 +2,9 @@ import GradientFlatList from '@app/components/GradientFlatList'
import ListItem from '@app/components/ListItem' import ListItem from '@app/components/ListItem'
import NowPlayingBar from '@app/components/NowPlayingBar' import NowPlayingBar from '@app/components/NowPlayingBar'
import { useSkipTo } from '@app/hooks/trackplayer' import { useSkipTo } from '@app/hooks/trackplayer'
import { Song } from '@app/models/music' import { Song } from '@app/models/library'
import { useStore } from '@app/state/store' import { mapTrackExtToSong } from '@app/models/map'
import { selectTrackPlayer } from '@app/state/trackplayer' import { useStoreDeep } from '@app/state/store'
import { selectTrackPlayerMap } from '@app/state/trackplayermap'
import React from 'react' import React from 'react'
import { StyleSheet, View } from 'react-native' import { StyleSheet, View } from 'react-native'
@@ -27,8 +26,7 @@ const SongRenderItem: React.FC<{
) )
const NowPlayingQueue = React.memo<{}>(() => { const NowPlayingQueue = React.memo<{}>(() => {
const queue = useStore(selectTrackPlayer.queue) const queue = useStoreDeep(store => store.queue)
const mapTrackExtToSong = useStore(selectTrackPlayerMap.mapTrackExtToSong)
const skipTo = useSkipTo() const skipTo = useSkipTo()
return ( return (

View File

@@ -2,19 +2,19 @@ import CoverArt from '@app/components/CoverArt'
import HeaderBar from '@app/components/HeaderBar' import HeaderBar from '@app/components/HeaderBar'
import ImageGradientBackground from '@app/components/ImageGradientBackground' import ImageGradientBackground from '@app/components/ImageGradientBackground'
import PressableOpacity from '@app/components/PressableOpacity' import PressableOpacity from '@app/components/PressableOpacity'
import Star from '@app/components/Star' import { PressableStar } from '@app/components/Star'
import { useStarred } from '@app/hooks/music' import { withSuspenseMemo } from '@app/components/withSuspense'
import { useNext, usePause, usePlay, usePrevious, useSeekTo } from '@app/hooks/trackplayer' import { useNext, usePause, usePlay, usePrevious, useSeekTo } from '@app/hooks/trackplayer'
import { selectMusic } from '@app/state/music' import { mapTrackExtToSong } from '@app/models/map'
import { useStore } from '@app/state/store' import { TrackExt } from '@app/models/trackplayer'
import { QueueContextType, selectTrackPlayer, TrackExt } from '@app/state/trackplayer' import { useStore, useStoreDeep } from '@app/state/store'
import { selectTrackPlayerMap } from '@app/state/trackplayermap'
import colors from '@app/styles/colors' import colors from '@app/styles/colors'
import font from '@app/styles/font' import font from '@app/styles/font'
import formatDuration from '@app/util/formatDuration' import formatDuration from '@app/util/formatDuration'
import Slider from '@react-native-community/slider' import Slider from '@react-native-community/slider'
import { useNavigation } from '@react-navigation/native' import { useNavigation } from '@react-navigation/native'
import React, { useCallback, useEffect, useState } from 'react' import React, { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { ActivityIndicator, StyleSheet, Text, TextStyle, View } from 'react-native' import { ActivityIndicator, StyleSheet, Text, TextStyle, View } from 'react-native'
import { NativeStackScreenProps } from 'react-native-screens/native-stack' import { NativeStackScreenProps } from 'react-native-screens/native-stack'
import { RepeatMode, State } from 'react-native-track-player' import { RepeatMode, State } from 'react-native-track-player'
@@ -23,33 +23,29 @@ import IconFA5 from 'react-native-vector-icons/FontAwesome5'
import Icon from 'react-native-vector-icons/Ionicons' import Icon from 'react-native-vector-icons/Ionicons'
import IconMatCom from 'react-native-vector-icons/MaterialCommunityIcons' import IconMatCom from 'react-native-vector-icons/MaterialCommunityIcons'
function getContextName(type?: QueueContextType) { const NowPlayingHeader = withSuspenseMemo<{
switch (type) {
case 'album':
return 'Album'
case 'artist':
return 'Top Songs'
case 'playlist':
return 'Playlist'
case 'song':
return 'Search Results'
default:
return undefined
}
}
const NowPlayingHeader = React.memo<{
track?: TrackExt track?: TrackExt
}>(({ track }) => { }>(({ track }) => {
const queueName = useStore(selectTrackPlayer.queueName) const queueName = useStore(store => store.queueName)
const queueContextType = useStore(selectTrackPlayer.queueContextType) const queueContextType = useStore(store => store.queueContextType)
const mapTrackExtToSong = useStore(selectTrackPlayerMap.mapTrackExtToSong) const { t } = useTranslation()
console.log(t('resources.album.name', { count: 1 }))
if (!track) { if (!track) {
return <></> return <></>
} }
let contextName = getContextName(queueContextType) let contextName: string
if (queueContextType === 'album') {
contextName = t('resources.album.name', { count: 1 })
} else if (queueContextType === 'artist') {
contextName = t('resources.song.lists.artistTopSongs')
} else if (queueContextType === 'playlist') {
contextName = t('resources.playlist.name', { count: 1 })
} else if (queueContextType === 'song') {
contextName = t('search.nowPlayingContext')
}
return ( return (
<HeaderBar <HeaderBar
@@ -94,11 +90,11 @@ const headerStyles = StyleSheet.create({
}) })
const SongCoverArt = () => { const SongCoverArt = () => {
const track = useStore(selectTrackPlayer.currentTrack) const albumId = useStore(store => store.currentTrack?.albumId)
return ( return (
<View style={coverArtStyles.container}> <View style={coverArtStyles.container}>
<CoverArt type="cover" size="original" coverArt={track?.coverArt} style={coverArtStyles.image} /> <CoverArt type="album" size="original" albumId={albumId} style={coverArtStyles.image} />
</View> </View>
) )
} }
@@ -117,26 +113,22 @@ const coverArtStyles = StyleSheet.create({
}) })
const SongInfo = () => { const SongInfo = () => {
const track = useStore(selectTrackPlayer.currentTrack) const id = useStore(store => store.currentTrack?.id)
const id = track?.id || '-1' const artist = useStore(store => store.currentTrack?.artist)
const type = 'song' const title = useStore(store => store.currentTrack?.title)
const starred = useStarred(id, type)
const setStarred = useStore(selectMusic.starItem)
return ( return (
<View style={infoStyles.container}> <View style={infoStyles.container}>
<View style={infoStyles.details}> <View style={infoStyles.details}>
<Text numberOfLines={1} style={infoStyles.title}> <Text numberOfLines={1} style={infoStyles.title}>
{track?.title} {title}
</Text> </Text>
<Text numberOfLines={1} style={infoStyles.artist}> <Text numberOfLines={1} style={infoStyles.artist}>
{track?.artist} {artist}
</Text> </Text>
</View> </View>
<View style={infoStyles.controls}> <View style={infoStyles.controls}>
<PressableOpacity onPress={() => setStarred(id, type, starred)}> <PressableStar id={id || '-1'} type={'song'} size={32} />
<Star size={32} starred={starred} />
</PressableOpacity>
</View> </View>
</View> </View>
) )
@@ -170,7 +162,8 @@ const infoStyles = StyleSheet.create({
}) })
const SeekBar = () => { const SeekBar = () => {
const { position, duration } = useStore(selectTrackPlayer.progress) const position = useStore(store => store.progress.position)
const duration = useStore(store => store.progress.duration)
const seekTo = useSeekTo() const seekTo = useSeekTo()
const [value, setValue] = useState(0) const [value, setValue] = useState(0)
const [sliding, setSliding] = useState(false) const [sliding, setSliding] = useState(false)
@@ -262,15 +255,15 @@ const seekStyles = StyleSheet.create({
}) })
const PlayerControls = () => { const PlayerControls = () => {
const state = useStore(selectTrackPlayer.playerState) const state = useStore(store => store.playerState)
const play = usePlay() const play = usePlay()
const pause = usePause() const pause = usePause()
const next = useNext() const next = useNext()
const previous = usePrevious() const previous = usePrevious()
const shuffled = useStore(selectTrackPlayer.shuffled) const shuffled = useStore(store => !!store.shuffleOrder)
const toggleShuffle = useStore(selectTrackPlayer.toggleShuffle) const toggleShuffle = useStore(store => store.toggleShuffle)
const repeatMode = useStore(selectTrackPlayer.repeatMode) const repeatMode = useStore(store => store.repeatMode)
const toggleRepeat = useStore(selectTrackPlayer.toggleRepeatMode) const toggleRepeat = useStore(store => store.toggleRepeatMode)
const navigation = useNavigation() const navigation = useNavigation()
let playPauseIcon: string let playPauseIcon: string
@@ -392,7 +385,7 @@ type RootStackParamList = {
type NowPlayingProps = NativeStackScreenProps<RootStackParamList, 'main'> type NowPlayingProps = NativeStackScreenProps<RootStackParamList, 'main'>
const NowPlayingView: React.FC<NowPlayingProps> = ({ navigation }) => { const NowPlayingView: React.FC<NowPlayingProps> = ({ navigation }) => {
const track = useStore(selectTrackPlayer.currentTrack) const track = useStoreDeep(store => store.currentTrack)
useEffect(() => { useEffect(() => {
if (!track) { if (!track) {
@@ -404,7 +397,7 @@ const NowPlayingView: React.FC<NowPlayingProps> = ({ navigation }) => {
return ( return (
<View style={styles.container}> <View style={styles.container}>
<ImageGradientBackground imagePath={imagePath} /> <ImageGradientBackground imagePath={imagePath} height={'100%'} />
<NowPlayingHeader track={track} /> <NowPlayingHeader track={track} />
<View style={styles.content}> <View style={styles.content}>
<SongCoverArt /> <SongCoverArt />

View File

@@ -4,47 +4,51 @@ import Header from '@app/components/Header'
import ListItem from '@app/components/ListItem' import ListItem from '@app/components/ListItem'
import NothingHere from '@app/components/NothingHere' import NothingHere from '@app/components/NothingHere'
import TextInput from '@app/components/TextInput' import TextInput from '@app/components/TextInput'
import { useActiveServerRefresh } from '@app/hooks/server' import { withSuspense, withSuspenseMemo } from '@app/components/withSuspense'
import { ListableItem, SearchResults, Song } from '@app/models/music' import { useQuerySearchResults } from '@app/hooks/query'
import { selectMusic } from '@app/state/music' import { useSetQueue } from '@app/hooks/trackplayer'
import { useStore } from '@app/state/store' import { Album, Artist, SearchResults, Song } from '@app/models/library'
import { selectTrackPlayer } from '@app/state/trackplayer'
import colors from '@app/styles/colors' import colors from '@app/styles/colors'
import font from '@app/styles/font' import font from '@app/styles/font'
import { useFocusEffect, useNavigation } from '@react-navigation/native' import { useFocusEffect, useNavigation } from '@react-navigation/native'
import debounce from 'lodash.debounce' import equal from 'fast-deep-equal/es6/react'
import _ from 'lodash'
import React, { useCallback, useMemo, useRef, useState } from 'react' import React, { useCallback, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { import {
ActivityIndicator, ActivityIndicator,
InteractionManager, InteractionManager,
ScrollView, ScrollView,
StatusBar,
StyleSheet, StyleSheet,
TextInput as ReactTextInput, TextInput as ReactTextInput,
View, View,
} from 'react-native' } from 'react-native'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
const SongItem = React.memo<{ item: Song }>(({ item }) => { const SongItem = React.memo<{ item: Song }>(({ item }) => {
const setQueue = useStore(selectTrackPlayer.setQueue) const { setQueue, contextId } = useSetQueue('song', [item])
return ( return (
<ListItem <ListItem
item={item} item={item}
contextId={item.id} contextId={contextId}
queueId={0} queueId={0}
showArt={true} showArt={true}
showStar={false} showStar={false}
onPress={() => setQueue([item], item.title, 'song', item.id, 0)} onPress={() => setQueue({ title: item.title, playTrack: 0 })}
/> />
) )
}) }, equal)
const ResultsCategory = React.memo<{ const ResultsCategory = withSuspenseMemo<{
name: string name: string
query: string query: string
items: ListableItem[] items: (Artist | Album | Song)[]
}>(({ name, query, items }) => { type: 'artist' | 'album' | 'song'
}>(
({ name, query, type, items }) => {
const navigation = useNavigation() const navigation = useNavigation()
const { t } = useTranslation()
if (items.length === 0) { if (items.length === 0) {
return <></> return <></>
@@ -54,15 +58,15 @@ const ResultsCategory = React.memo<{
<> <>
<Header>{name}</Header> <Header>{name}</Header>
{items.map(a => {items.map(a =>
a.itemType === 'song' ? ( type === 'song' ? (
<SongItem key={a.id} item={a} /> <SongItem key={a.id} item={a as Song} />
) : ( ) : (
<ListItem key={a.id} item={a} showArt={true} showStar={false} /> <ListItem key={a.id} item={a} showArt={true} showStar={false} />
), ),
)} )}
{items.length === 5 && ( {items.length === 5 && (
<Button <Button
title="More..." title={t('search.moreResults')}
buttonStyle="hollow" buttonStyle="hollow"
style={styles.more} style={styles.more}
onPress={() => navigation.navigate('results', { query, type: items[0].itemType })} onPress={() => navigation.navigate('results', { query, type: items[0].itemType })}
@@ -70,101 +74,120 @@ const ResultsCategory = React.memo<{
)} )}
</> </>
) )
}) },
null,
equal,
)
const Results = React.memo<{ const Results = withSuspenseMemo<{
results: SearchResults results: SearchResults
query: string query: string
}>(({ results, query }) => { }>(
({ results, query }) => {
const { t } = useTranslation()
return ( return (
<> <>
<ResultsCategory name="Artists" query={query} items={results.artists} /> <ResultsCategory
<ResultsCategory name="Albums" query={query} items={results.albums} /> name={t('resources.artist.name', { count: 2 })}
<ResultsCategory name="Songs" query={query} items={results.songs} /> query={query}
type={'artist'}
items={results.artists}
/>
<ResultsCategory
name={t('resources.album.name', { count: 2 })}
query={query}
type={'album'}
items={results.albums}
/>
<ResultsCategory
name={t('resources.song.name', { count: 2 })}
query={query}
type={'song'}
items={results.songs}
/>
</> </>
) )
}) },
null,
equal,
)
const Search = withSuspense(() => {
const [query, setQuery] = useState('')
const { data, isLoading } = useQuerySearchResults({ query, albumCount: 5, artistCount: 5, songCount: 5 })
const { t } = useTranslation()
const Search = () => {
const fetchSearchResults = useStore(selectMusic.fetchSearchResults)
const [results, setResults] = useState<SearchResults>({ artists: [], albums: [], songs: [] })
const [refreshing, setRefreshing] = useState(false)
const [text, setText] = useState('') const [text, setText] = useState('')
const searchBarRef = useRef<ReactTextInput>(null) const searchBarRef = useRef<ReactTextInput>(null)
const scrollRef = useRef<ScrollView>(null) const scrollRef = useRef<ScrollView>(null)
const paddingTop = useSafeAreaInsets().top
useFocusEffect( useFocusEffect(
useCallback(() => { useCallback(() => {
const task = InteractionManager.runAfterInteractions(() => { const task = InteractionManager.runAfterInteractions(() => {
setTimeout(() => { setTimeout(() => {
if (text) {
return
}
setText('') setText('')
setResults({ artists: [], albums: [], songs: [] }) setQuery('')
searchBarRef.current?.focus() searchBarRef.current?.focus()
scrollRef.current?.scrollTo({ y: 0, animated: true }) scrollRef.current?.scrollTo({ y: 0, animated: true })
}, 50) }, 50)
}) })
return () => task.cancel() return () => task.cancel()
}, [searchBarRef, scrollRef]), }, [text]),
) )
useActiveServerRefresh( const debouncedSetQuery = useMemo(
useCallback(() => {
setText('')
setResults({ artists: [], albums: [], songs: [] })
}, []),
)
const debouncedonUpdateSearch = useMemo(
() => () =>
debounce(async (query: string) => { _.debounce((value: string) => {
setRefreshing(true) setQuery(value)
setResults(await fetchSearchResults(query))
setRefreshing(false)
}, 400), }, 400),
[fetchSearchResults], [],
) )
const onChangeText = useCallback( const onChangeText = useCallback(
(value: string) => { (value: string) => {
setText(value) setText(value)
debouncedonUpdateSearch(value) debouncedSetQuery(value)
}, },
[setText, debouncedonUpdateSearch], [setText, debouncedSetQuery],
) )
const resultsCount = results.albums.length + results.artists.length + results.songs.length const resultsCount =
(data ? data.pages.reduce((acc, val) => (acc += val.artists.length), 0) : 0) +
(data ? data.pages.reduce((acc, val) => (acc += val.albums.length), 0) : 0) +
(data ? data.pages.reduce((acc, val) => (acc += val.songs.length), 0) : 0)
return ( return (
<GradientScrollView ref={scrollRef} style={styles.scroll} contentContainerStyle={styles.scrollContentContainer}> <GradientScrollView ref={scrollRef} style={styles.scroll} contentContainerStyle={{ paddingTop }}>
<View style={styles.content}> <View style={styles.content}>
<View style={styles.inputBar}> <View style={styles.inputBar}>
<TextInput <TextInput
ref={searchBarRef} ref={searchBarRef}
style={styles.textInput} style={styles.textInput}
placeholder="Search" placeholder={t('search.inputPlaceholder')}
value={text} value={text}
onChangeText={onChangeText} onChangeText={onChangeText}
/> />
<ActivityIndicator <ActivityIndicator animating={isLoading} size="small" color={colors.text.secondary} style={styles.activity} />
animating={refreshing}
size="small"
color={colors.text.secondary}
style={styles.activity}
/>
</View> </View>
{resultsCount > 0 ? <Results results={results} query={text} /> : <NothingHere style={styles.noResults} />} {data !== undefined && resultsCount > 0 ? (
<Results results={data.pages[0]} query={text} />
) : (
<NothingHere style={styles.noResults} />
)}
</View> </View>
</GradientScrollView> </GradientScrollView>
) )
} })
const styles = StyleSheet.create({ const styles = StyleSheet.create({
scroll: { scroll: {
flex: 1, flex: 1,
}, },
scrollContentContainer: {
paddingTop: StatusBar.currentHeight,
},
content: { content: {
paddingHorizontal: 20, paddingHorizontal: 20,
paddingBottom: 20, paddingBottom: 20,

View File

@@ -1,24 +1,35 @@
import GradientFlatList from '@app/components/GradientFlatList' import GradientFlatList from '@app/components/GradientFlatList'
import ListItem from '@app/components/ListItem' import ListItem from '@app/components/ListItem'
import { useFetchPaginatedList } from '@app/hooks/list' import { withSuspense } from '@app/components/withSuspense'
import { AlbumListItem, Artist, Song } from '@app/models/music' import { useQuerySearchResults } from '@app/hooks/query'
import { selectMusic } from '@app/state/music' import { useSetQueue } from '@app/hooks/trackplayer'
import { useStore } from '@app/state/store' import { Album, Artist, Song } from '@app/models/library'
import { selectTrackPlayer } from '@app/state/trackplayer' import { Search3Params } from '@app/subsonic/params'
import { useNavigation } from '@react-navigation/native' import { useNavigation } from '@react-navigation/native'
import React, { useCallback, useEffect } from 'react' import React, { useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { StyleSheet } from 'react-native' import { StyleSheet } from 'react-native'
type SearchListItemType = AlbumListItem | Song | Artist type SearchListItemType = Album | Song | Artist
const ResultsListItem: React.FC<{ item: SearchListItemType }> = ({ item }) => { const SongResultsListItem: React.FC<{ item: Song }> = ({ item }) => {
const setQueue = useStore(selectTrackPlayer.setQueue) const { setQueue, contextId } = useSetQueue('song', [item])
let onPress return (
if (item.itemType === 'song') { <ListItem
onPress = () => setQueue([item], item.title, 'song', item.id, 0) item={item}
} contextId={contextId}
queueId={0}
showArt={true}
showStar={false}
listStyle="small"
onPress={() => setQueue({ title: item.title, playTrack: 0 })}
style={styles.listItem}
/>
)
}
const OtherResultsListItem: React.FC<{ item: SearchListItemType }> = ({ item }) => {
return ( return (
<ListItem <ListItem
item={item} item={item}
@@ -27,63 +38,73 @@ const ResultsListItem: React.FC<{ item: SearchListItemType }> = ({ item }) => {
showArt={true} showArt={true}
showStar={false} showStar={false}
listStyle="small" listStyle="small"
onPress={onPress}
style={styles.listItem} style={styles.listItem}
/> />
) )
} }
const ResultsListItem: React.FC<{ item: SearchListItemType }> = ({ item }) => {
if (item.itemType === 'song') {
return <SongResultsListItem item={item} />
} else {
return <OtherResultsListItem item={item} />
}
}
const SearchResultsRenderItem: React.FC<{ item: SearchListItemType }> = ({ item }) => <ResultsListItem item={item} /> const SearchResultsRenderItem: React.FC<{ item: SearchListItemType }> = ({ item }) => <ResultsListItem item={item} />
const SearchResultsView: React.FC<{ const SearchResultsView = withSuspense<{
query: string query: string
type: 'album' | 'artist' | 'song' type: 'album' | 'artist' | 'song'
}> = ({ query, type }) => { }>(({ query, type }) => {
const navigation = useNavigation() const navigation = useNavigation()
const fetchSearchResults = useStore(selectMusic.fetchSearchResults) const { t } = useTranslation()
const { list, refreshing, refresh, fetchNextPage } = useFetchPaginatedList<SearchListItemType>(
useCallback( const size = 100
(size, offset) => const params: Search3Params = { query }
fetchSearchResults(query, type, size, offset).then(results => {
switch (type) { if (type === 'album') {
case 'album': params.albumCount = size
return results.albums } else if (type === 'artist') {
case 'artist': params.artistCount = size
return results.artists } else {
case 'song': params.songCount = size
return results.songs }
default:
return [] const { data, isLoading, refetch, fetchNextPage } = useQuerySearchResults(params)
const items: (Artist | Album | Song)[] = []
if (type === 'album') {
data && items.push(...data.pages.flatMap(p => p.albums))
} else if (type === 'artist') {
data && items.push(...data.pages.flatMap(p => p.artists))
} else {
data && items.push(...data.pages.flatMap(p => p.songs))
} }
}),
[fetchSearchResults, query, type],
),
100,
)
useEffect(() => { useEffect(() => {
navigation.setOptions({ navigation.setOptions({
title: `Search: "${query}"`, title: t('search.headerTitle', { query }),
}) })
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, []) }, [])
return ( return (
<GradientFlatList <GradientFlatList
data={list} data={items}
renderItem={SearchResultsRenderItem} renderItem={SearchResultsRenderItem}
keyExtractor={(item, i) => i.toString()} keyExtractor={(item, i) => i.toString()}
onRefresh={refresh} onRefresh={refetch}
refreshing={refreshing} refreshing={isLoading}
overScrollMode="never" overScrollMode="never"
onEndReached={fetchNextPage} onEndReached={() => fetchNextPage}
removeClippedSubviews={true} removeClippedSubviews={true}
onEndReachedThreshold={2} onEndReachedThreshold={2}
contentMarginTop={6} contentMarginTop={6}
windowSize={5} windowSize={5}
/> />
) )
} })
const styles = StyleSheet.create({ const styles = StyleSheet.create({
listItem: { listItem: {

View File

@@ -1,31 +1,34 @@
import Button from '@app/components/Button' import Button from '@app/components/Button'
import GradientScrollView from '@app/components/GradientScrollView' import GradientScrollView from '@app/components/GradientScrollView'
import SettingsSwitch from '@app/components/SettingsSwitch'
import { withSuspense } from '@app/components/withSuspense'
import { Server } from '@app/models/settings' import { Server } from '@app/models/settings'
import { selectSettings } from '@app/state/settings' import { useStore, useStoreDeep } from '@app/state/store'
import { useStore } from '@app/state/store'
import colors from '@app/styles/colors' import colors from '@app/styles/colors'
import font from '@app/styles/font' import font from '@app/styles/font'
import toast from '@app/util/toast' import toast from '@app/util/toast'
import { useNavigation } from '@react-navigation/native' import { useNavigation } from '@react-navigation/native'
import md5 from 'md5' import md5 from 'md5'
import React, { useCallback, useState } from 'react' import React, { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { StyleSheet, Text, TextInput, View, ViewStyle } from 'react-native' import { StyleSheet, Text, TextInput, View, ViewStyle } from 'react-native'
import { v4 as uuidv4 } from 'uuid' import uuid from 'react-native-uuid'
import SettingsSwitch from '@app/components/SettingsSwitch'
const PASSWORD_PLACEHOLDER = 'PASSWORD_PLACEHOLDER' const PASSWORD_PLACEHOLDER = 'PASSWORD_PLACEHOLDER'
const ServerView: React.FC<{ const ServerView = withSuspense<{
id?: string id?: string
}> = ({ id }) => { title?: string
}>(({ id, title }) => {
const { t } = useTranslation()
const navigation = useNavigation() const navigation = useNavigation()
const activeServer = useStore(selectSettings.activeServer) const activeServerId = useStore(store => store.settings.activeServerId)
const servers = useStore(selectSettings.servers) const servers = useStoreDeep(store => store.settings.servers)
const addServer = useStore(selectSettings.addServer) const addServer = useStore(store => store.addServer)
const updateServer = useStore(selectSettings.updateServer) const updateServer = useStore(store => store.updateServer)
const removeServer = useStore(selectSettings.removeServer) const removeServer = useStore(store => store.removeServer)
const server = id ? servers.find(s => s.id === id) : undefined const server = id ? servers[id] : undefined
const pingServer = useStore(selectSettings.pingServer) const pingServer = useStore(store => store.pingServer)
const [address, setAddress] = useState(server?.address || '') const [address, setAddress] = useState(server?.address || '')
const [username, setUsername] = useState(server?.username || '') const [username, setUsername] = useState(server?.username || '')
@@ -36,16 +39,18 @@ const ServerView: React.FC<{
) )
const [testing, setTesting] = useState(false) const [testing, setTesting] = useState(false)
const [removing, setRemoving] = useState(false)
const [saving, setSaving] = useState(false) useEffect(() => {
navigation.setOptions({ title })
}, [navigation, title])
const validate = useCallback(() => { const validate = useCallback(() => {
return !!address && !!username && !!password return !!address && !!username && !!password
}, [address, username, password]) }, [address, username, password])
const canRemove = useCallback(() => { const canRemove = useCallback(() => {
return id && servers.length > 1 && activeServer?.id !== id return id && Object.keys(servers).length > 1 && activeServerId !== id
}, [id, servers, activeServer]) }, [id, servers, activeServerId])
const exit = useCallback(() => { const exit = useCallback(() => {
if (navigation.canGoBack()) { if (navigation.canGoBack()) {
@@ -58,7 +63,7 @@ const ServerView: React.FC<{
const createServer = useCallback<() => Server>(() => { const createServer = useCallback<() => Server>(() => {
if (usePlainPassword) { if (usePlainPassword) {
return { return {
id: server?.id || uuidv4(), id: server?.id || '',
usePlainPassword, usePlainPassword,
plainPassword: password, plainPassword: password,
address, address,
@@ -73,12 +78,12 @@ const ServerView: React.FC<{
salt = server.salt salt = server.salt
token = server.token token = server.token
} else { } else {
salt = uuidv4() salt = uuid.v4() as string
token = md5(password + salt) token = md5(password + salt)
} }
return { return {
id: server?.id || uuidv4(), id: server?.id || '',
address, address,
username, username,
usePlainPassword, usePlainPassword,
@@ -92,22 +97,15 @@ const ServerView: React.FC<{
return return
} }
setSaving(true)
const update = createServer() const update = createServer()
const waitForSave = async () => {
try {
if (id) { if (id) {
updateServer(update) updateServer(update)
} else { } else {
await addServer(update) addServer(update)
} }
exit() exit()
} catch (err) {
setSaving(false)
}
}
waitForSave()
}, [addServer, createServer, exit, id, updateServer, validate]) }, [addServer, createServer, exit, id, updateServer, validate])
const remove = useCallback(() => { const remove = useCallback(() => {
@@ -115,16 +113,8 @@ const ServerView: React.FC<{
return return
} }
setRemoving(true) removeServer(id as string)
const waitForRemove = async () => {
try {
await removeServer(id as string)
exit() exit()
} catch (err) {
setRemoving(false)
}
}
waitForRemove()
}, [canRemove, exit, id, removeServer]) }, [canRemove, exit, id, removeServer])
const togglePlainPassword = useCallback( const togglePlainPassword = useCallback(
@@ -152,19 +142,20 @@ const ServerView: React.FC<{
const ping = async () => { const ping = async () => {
const res = await pingServer(potential) const res = await pingServer(potential)
if (res) { toast(
toast(`Connection to ${potential.address} OK!`) t(`settings.servers.messages.${res ? 'connectionOk' : 'connectionFailed'}`, {
} else { address: potential.address,
toast(`Connection to ${potential.address} failed, check settings or server`) interpolation: { escapeValue: false },
} }),
)
setTesting(false) setTesting(false)
} }
ping() ping()
}, [createServer, pingServer]) }, [createServer, pingServer, t])
const disableControls = useCallback(() => { const disableControls = useCallback(() => {
return !validate() || testing || removing || saving return !validate() || testing
}, [validate, testing, removing, saving]) }, [validate, testing])
const formatAddress = useCallback(() => { const formatAddress = useCallback(() => {
let addressFormatted = address.trim() let addressFormatted = address.trim()
@@ -185,48 +176,54 @@ const ServerView: React.FC<{
} }
return ( return (
<GradientScrollView style={styles.scroll} contentContainerStyle={styles.scrollContentContainer}> <GradientScrollView style={styles.scroll}>
<View style={styles.content}> <View style={styles.content}>
<Text style={styles.inputTitle}>Address</Text> <Text style={styles.inputTitle}>{t('settings.servers.fields.address')}</Text>
<TextInput <TextInput
style={styles.input} style={styles.input}
placeholderTextColor="grey" placeholderTextColor="grey"
selectionColor={colors.text.secondary} selectionColor={colors.text.secondary}
textContentType="URL" textContentType="URL"
placeholder="http://demo.navidrome.org" placeholder="http://demo.navidrome.org"
autoCorrect={false}
autoCapitalize="none"
value={address} value={address}
onChangeText={setAddress} onChangeText={setAddress}
onBlur={formatAddress} onBlur={formatAddress}
/> />
<Text style={styles.inputTitle}>Username</Text> <Text style={styles.inputTitle}>{t('settings.servers.fields.username')}</Text>
<TextInput <TextInput
style={styles.input} style={styles.input}
placeholderTextColor="grey" placeholderTextColor="grey"
selectionColor={colors.text.secondary} selectionColor={colors.text.secondary}
textContentType="username" textContentType="username"
autoCompleteType="username" autoComplete="username"
importantForAutofill="yes"
autoCapitalize="none"
placeholder="demo" placeholder="demo"
value={username} value={username}
onChangeText={setUsername} onChangeText={setUsername}
/> />
<Text style={styles.inputTitle}>Password</Text> <Text style={styles.inputTitle}>{t('settings.servers.fields.password')}</Text>
<TextInput <TextInput
style={styles.input} style={styles.input}
placeholderTextColor="grey" placeholderTextColor="grey"
selectionColor={colors.text.secondary} selectionColor={colors.text.secondary}
textContentType="password" textContentType="password"
autoCompleteType="password" autoComplete="password"
autoCapitalize="none"
importantForAutofill="yes"
secureTextEntry={true} secureTextEntry={true}
placeholder="demo" placeholder="demo"
value={password} value={password}
onChangeText={setPassword} onChangeText={setPassword}
/> />
<SettingsSwitch <SettingsSwitch
title="Force plain text password" title={t('settings.servers.options.forcePlaintextPassword.title')}
subtitle={ subtitle={
usePlainPassword usePlainPassword
? 'Send password in plain text (legacy, make sure your connection is secure!)' ? t('settings.servers.options.forcePlaintextPassword.descriptionOn')
: 'Send password as token + salt' : t('settings.servers.options.forcePlaintextPassword.descriptionOff')
} }
value={usePlainPassword} value={usePlainPassword}
setValue={togglePlainPassword} setValue={togglePlainPassword}
@@ -234,29 +231,31 @@ const ServerView: React.FC<{
<Button <Button
disabled={disableControls()} disabled={disableControls()}
style={styles.button} style={styles.button}
title="Test Connection" title={t('settings.servers.actions.testConnection')}
buttonStyle="hollow" buttonStyle="hollow"
onPress={test} onPress={test}
/> />
<Button <Button
disabled={disableControls()} disabled={disableControls()}
style={[styles.button, styles.delete, deleteStyle]} style={[styles.button, styles.delete, deleteStyle]}
title="Delete" title={t('settings.servers.actions.delete')}
onPress={remove} onPress={remove}
/> />
<Button disabled={disableControls()} style={styles.button} title="Save" onPress={save} /> <Button
disabled={disableControls()}
style={styles.button}
title={t('settings.servers.actions.save')}
onPress={save}
/>
</View> </View>
</GradientScrollView> </GradientScrollView>
) )
} })
const styles = StyleSheet.create({ const styles = StyleSheet.create({
scroll: { scroll: {
flex: 1, flex: 1,
}, },
scrollContentContainer: {
// paddingTop: StatusBar.currentHeight,
},
content: { content: {
paddingHorizontal: 20, paddingHorizontal: 20,
}, },

View File

@@ -5,26 +5,28 @@ import PressableOpacity from '@app/components/PressableOpacity'
import SettingsItem from '@app/components/SettingsItem' import SettingsItem from '@app/components/SettingsItem'
import SettingsSwitch from '@app/components/SettingsSwitch' import SettingsSwitch from '@app/components/SettingsSwitch'
import TextInput from '@app/components/TextInput' import TextInput from '@app/components/TextInput'
import { useSwitchActiveServer } from '@app/hooks/server' import { withSuspenseMemo } from '@app/components/withSuspense'
import { useResetImageCache, useSwitchActiveServer } from '@app/hooks/settings'
import { Server } from '@app/models/settings' import { Server } from '@app/models/settings'
import { selectCache } from '@app/state/cache' import { useStore, useStoreDeep } from '@app/state/store'
import { selectSettings } from '@app/state/settings'
import { useStore } from '@app/state/store'
import colors from '@app/styles/colors' import colors from '@app/styles/colors'
import font from '@app/styles/font' import font from '@app/styles/font'
import { useNavigation } from '@react-navigation/core' import { useNavigation } from '@react-navigation/core'
import React, { useCallback, useState } from 'react' import React, { useCallback, useState } from 'react'
import { KeyboardTypeOptions, Linking, Modal, Pressable, StatusBar, StyleSheet, Text, View } from 'react-native' import { useTranslation } from 'react-i18next'
import { KeyboardTypeOptions, Linking, Modal, Pressable, StyleSheet, Text, View } from 'react-native'
import { ScrollView } from 'react-native-gesture-handler' import { ScrollView } from 'react-native-gesture-handler'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import Icon from 'react-native-vector-icons/MaterialCommunityIcons' import Icon from 'react-native-vector-icons/MaterialCommunityIcons'
import { version } from '../../package.json' import { version } from '../../package.json'
const ServerItem = React.memo<{ const ServerItem = withSuspenseMemo<{
server: Server server: Server
}>(({ server }) => { }>(({ server }) => {
const activeServer = useStore(selectSettings.activeServer) const activeServerId = useStore(store => store.settings.activeServerId)
const switchActiveServer = useSwitchActiveServer() const switchActiveServer = useSwitchActiveServer()
const navigation = useNavigation() const navigation = useNavigation()
const { t } = useTranslation()
const setActive = useCallback(() => { const setActive = useCallback(() => {
switchActiveServer(server.id) switchActiveServer(server.id)
@@ -34,9 +36,9 @@ const ServerItem = React.memo<{
<SettingsItem <SettingsItem
title={server.address} title={server.address}
subtitle={server.username} subtitle={server.username}
onPress={() => navigation.navigate('server', { id: server.id })}> onPress={() => navigation.navigate('server', { id: server.id, title: t('settings.servers.actions.edit') })}>
<PressableOpacity style={styles.serverActive} onPress={setActive}> <PressableOpacity style={styles.serverActive} onPress={setActive}>
{activeServer && activeServer.id === server.id ? ( {activeServerId === server.id ? (
<Icon name="checkbox-marked-circle" size={30} color={colors.accent} /> <Icon name="checkbox-marked-circle" size={30} color={colors.accent} />
) : ( ) : (
<Icon name="checkbox-blank-circle-outline" size={30} color={colors.text.secondary} /> <Icon name="checkbox-blank-circle-outline" size={30} color={colors.text.secondary} />
@@ -74,25 +76,27 @@ const ModalChoice = React.memo<{
) )
}) })
function bitrateString(bitrate: number): string { const BitrateModal = withSuspenseMemo<{
return bitrate === 0 ? 'Unlimited' : `${bitrate}kbps`
}
const BitrateModal = React.memo<{
title: string title: string
bitrate: number bitrate: number
setBitrate: (bitrate: number) => void setBitrate: (bitrate: number) => void
}>(({ title, bitrate, setBitrate }) => { }>(({ title, bitrate, setBitrate }) => {
const { t } = useTranslation()
const [visible, setVisible] = useState(false) const [visible, setVisible] = useState(false)
const toggleModal = useCallback(() => setVisible(!visible), [visible]) const toggleModal = useCallback(() => setVisible(!visible), [visible])
const bitrateText = useCallback(
(value: number) =>
value === 0 ? t('settings.network.values.unlimitedKbps') : t('settings.network.values.kbps', { value }),
[t],
)
const BitrateChoice: React.FC<{ value: number }> = useCallback( const BitrateChoice: React.FC<{ value: number }> = useCallback(
({ value }) => { ({ value }) => {
const text = bitrateString(value)
return ( return (
<ModalChoice <ModalChoice
text={text} text={bitrateText(value)}
value={value} value={value}
setValue={setBitrate} setValue={setBitrate}
closeModal={toggleModal} closeModal={toggleModal}
@@ -100,12 +104,12 @@ const BitrateModal = React.memo<{
/> />
) )
}, },
[bitrate, toggleModal, setBitrate], [bitrate, toggleModal, setBitrate, bitrateText],
) )
return ( return (
<> <>
<SettingsItem title={title} subtitle={bitrateString(bitrate)} onPress={toggleModal} /> <SettingsItem title={title} subtitle={bitrateText(bitrate)} onPress={toggleModal} />
<Modal animationType="fade" transparent={true} visible={visible} onRequestClose={toggleModal}> <Modal animationType="fade" transparent={true} visible={visible} onRequestClose={toggleModal}>
<Pressable style={styles.modalBackdrop} onPress={toggleModal}> <Pressable style={styles.modalBackdrop} onPress={toggleModal}>
<View style={styles.centeredView}> <View style={styles.centeredView}>
@@ -136,9 +140,9 @@ const SettingsTextModal = React.memo<{
title: string title: string
value: string value: string
setValue: (text: string) => void setValue: (text: string) => void
getUnit?: (text: string) => string subtitle: (value: string) => string
keyboardType?: KeyboardTypeOptions keyboardType?: KeyboardTypeOptions
}>(({ title, value, setValue, getUnit, keyboardType }) => { }>(({ title, value, setValue, subtitle, keyboardType }) => {
const [visible, setVisible] = useState(false) const [visible, setVisible] = useState(false)
const [inputText, setInputText] = useState(value) const [inputText, setInputText] = useState(value)
@@ -149,16 +153,9 @@ const SettingsTextModal = React.memo<{
toggleModal() toggleModal()
}, [inputText, setValue, toggleModal]) }, [inputText, setValue, toggleModal])
const getSubtitle = useCallback(() => {
if (!getUnit) {
return value
}
return value + ' ' + getUnit(value)
}, [getUnit, value])
return ( return (
<> <>
<SettingsItem title={title} subtitle={getSubtitle()} onPress={toggleModal} /> <SettingsItem title={title} subtitle={subtitle(value)} onPress={toggleModal} />
<Modal animationType="fade" transparent={true} visible={visible} onRequestClose={toggleModal}> <Modal animationType="fade" transparent={true} visible={visible} onRequestClose={toggleModal}>
<Pressable style={styles.modalBackdrop} onPress={toggleModal}> <Pressable style={styles.modalBackdrop} onPress={toggleModal}>
<View style={styles.centeredView}> <View style={styles.centeredView}>
@@ -184,124 +181,117 @@ const SettingsTextModal = React.memo<{
) )
}) })
function secondsUnit(seconds: string): string { const SettingsContent = withSuspenseMemo(() => {
const numberValue = parseFloat(seconds) const { t } = useTranslation()
if (Math.abs(numberValue) !== 1) {
return 'seconds'
}
return 'second'
}
const SettingsContent = React.memo(() => { const servers = useStoreDeep(store => store.settings.servers)
const servers = useStore(selectSettings.servers) const scrobble = useStore(store => store.settings.scrobble)
const scrobble = useStore(selectSettings.scrobble) const setScrobble = useStore(store => store.setScrobble)
const setScrobble = useStore(selectSettings.setScrobble)
// doesn't seem to ever be a case where we want this off const maxBitrateWifi = useStore(store => store.settings.maxBitrateWifi)
// will remove later if there isn't a use case for disabling const setMaxBitrateWifi = useStore(store => store.setMaxBitrateWifi)
// const estimateContentLength = useStore(selectSettings.estimateContentLength)
// const setEstimateContentLength = useStore(selectSettings.setEstimateContentLength)
const maxBitrateWifi = useStore(selectSettings.maxBitrateWifi) const maxBitrateMobile = useStore(store => store.settings.maxBitrateMobile)
const setMaxBitrateWifi = useStore(selectSettings.setMaxBitrateWifi) const setMaxBitrateMobile = useStore(store => store.setMaxBitrateMobile)
const maxBitrateMobile = useStore(selectSettings.maxBitrateMobile) const minBuffer = useStore(store => store.settings.minBuffer)
const setMaxBitrateMobile = useStore(selectSettings.setMaxBitrateMobile) const setMinBuffer = useStore(store => store.setMinBuffer)
const maxBuffer = useStore(store => store.settings.maxBuffer)
const setMaxBuffer = useStore(store => store.setMaxBuffer)
const minBuffer = useStore(selectSettings.minBuffer)
const setMinBuffer = useStore(selectSettings.setMinBuffer)
const maxBuffer = useStore(selectSettings.maxBuffer)
const setMaxBuffer = useStore(selectSettings.setMaxBuffer)
const clearImageCache = useStore(selectCache.clearImageCache)
const [clearing, setClearing] = useState(false) const [clearing, setClearing] = useState(false)
const resetImageCache = useResetImageCache()
const navigation = useNavigation() const navigation = useNavigation()
const clear = useCallback(() => { const clear = useCallback(async () => {
setClearing(true) setClearing(true)
await resetImageCache()
const waitForClear = async () => {
try {
await clearImageCache()
} catch (err) {
console.log(err)
} finally {
setClearing(false) setClearing(false)
} }, [resetImageCache])
}
waitForClear()
}, [clearImageCache])
const setMinBufferText = useCallback((text: string) => setMinBuffer(parseFloat(text)), [setMinBuffer]) const setMinBufferText = useCallback((text: string) => setMinBuffer(parseFloat(text)), [setMinBuffer])
const setMaxBufferText = useCallback((text: string) => setMaxBuffer(parseFloat(text)), [setMaxBuffer]) const setMaxBufferText = useCallback((text: string) => setMaxBuffer(parseFloat(text)), [setMaxBuffer])
const secondsText = useCallback((value: string) => t('settings.network.values.seconds', { value }), [t])
return ( return (
<View style={styles.content}> <View style={styles.content}>
<Header>Servers</Header> <Header>{t('settings.servers.name')}</Header>
{servers.map(s => ( {Object.values(servers).map(s => (
<ServerItem key={s.id} server={s} /> <ServerItem key={s.id} server={s} />
))} ))}
<Button <Button
style={styles.button} style={styles.button}
title="Add Server" title={t('settings.servers.actions.add')}
onPress={() => navigation.navigate('server')} onPress={() => navigation.navigate('server', { title: t('settings.servers.actions.add') })}
buttonStyle="hollow" buttonStyle="hollow"
/> />
<Header style={styles.header}>Network</Header> <Header style={styles.header}>{t('settings.network.name')}</Header>
<BitrateModal title="Maximum bitrate (Wi-Fi)" bitrate={maxBitrateWifi} setBitrate={setMaxBitrateWifi} /> <BitrateModal
<BitrateModal title="Maximum bitrate (mobile)" bitrate={maxBitrateMobile} setBitrate={setMaxBitrateMobile} /> title={t('settings.network.options.maxBitrateWifi.title')}
{/* <SettingsSwitch bitrate={maxBitrateWifi}
title="Estimate content length" setBitrate={setMaxBitrateWifi}
subtitle='Send the "estimateContentLength" flag when streaming. Helps fix issues with seeking when the server is transcoding songs.' />
value={estimateContentLength} <BitrateModal
setValue={setEstimateContentLength} title={t('settings.network.options.maxBitrateMobile.title')}
/> */} bitrate={maxBitrateMobile}
setBitrate={setMaxBitrateMobile}
/>
<SettingsTextModal <SettingsTextModal
title="Minimum buffer time" title={t('settings.network.options.minBuffer.title')}
value={minBuffer.toString()} value={minBuffer.toString()}
setValue={setMinBufferText} setValue={setMinBufferText}
getUnit={secondsUnit} subtitle={secondsText}
keyboardType="numeric" keyboardType="numeric"
/> />
<SettingsTextModal <SettingsTextModal
title="Maximum buffer time" title={t('settings.network.options.maxBuffer.title')}
value={maxBuffer.toString()} value={maxBuffer.toString()}
setValue={setMaxBufferText} setValue={setMaxBufferText}
getUnit={secondsUnit} subtitle={secondsText}
keyboardType="numeric" keyboardType="numeric"
/> />
<Header style={styles.header}>Music</Header> <Header style={styles.header}>{t('settings.music.name')}</Header>
<SettingsSwitch <SettingsSwitch
title="Scrobble plays" title={t('settings.music.options.scrobble.title')}
subtitle={scrobble ? 'Scrobble play history' : "Don't scrobble play history"} subtitle={
scrobble
? t('settings.music.options.scrobble.descriptionOn')
: t('settings.music.options.scrobble.descriptionOff')
}
value={scrobble} value={scrobble}
setValue={setScrobble} setValue={setScrobble}
/> />
<Header style={styles.header}>Reset</Header> <Header style={styles.header}>{t('settings.reset.name')}</Header>
<Button <Button
disabled={clearing} disabled={clearing}
style={styles.button} style={styles.button}
title="Clear Image Cache" title={t('settings.reset.actions.clearImageCache')}
onPress={clear} onPress={clear}
buttonStyle="hollow" buttonStyle="hollow"
/> />
<Header style={styles.header}>About</Header> <Header style={styles.header}>{t('settings.about.name')}</Header>
<Text style={styles.text}> <Text style={styles.text}>
<Text style={styles.bold}>Subtracks</Text> version {version} <Text style={styles.bold}>Subtracks</Text> {t('settings.about.version', { version })}
</Text> </Text>
<Button <Button
disabled={clearing} disabled={clearing}
style={styles.button} style={styles.button}
title="Project Homepage" title={t('settings.about.actions.projectHomepage')}
onPress={() => Linking.openURL('https://github.com/austinried/subtracks')} onPress={() => Linking.openURL('https://github.com/austinried/subtracks')}
buttonStyle="hollow" buttonStyle="hollow"
/> />
<Button <Button
disabled={clearing} disabled={clearing}
style={styles.button} style={styles.button}
title="Licenses" title={t('settings.about.actions.licenses')}
onPress={() => navigation.navigate('web', { uri: 'file:///android_asset/licenses.html' })} onPress={() =>
navigation.navigate('web', {
uri: 'file:///android_asset/licenses.html',
title: t('settings.about.actions.licenses'),
})
}
buttonStyle="hollow" buttonStyle="hollow"
/> />
</View> </View>
@@ -309,8 +299,10 @@ const SettingsContent = React.memo(() => {
}) })
const Settings = () => { const Settings = () => {
const paddingTop = useSafeAreaInsets().top
return ( return (
<GradientScrollView style={styles.scroll} contentContainerStyle={styles.scrollContentContainer}> <GradientScrollView style={styles.scroll} contentContainerStyle={{ paddingTop }}>
<SettingsContent /> <SettingsContent />
</GradientScrollView> </GradientScrollView>
) )
@@ -320,9 +312,6 @@ const styles = StyleSheet.create({
scroll: { scroll: {
flex: 1, flex: 1,
}, },
scrollContentContainer: {
paddingTop: StatusBar.currentHeight,
},
content: { content: {
paddingHorizontal: 20, paddingHorizontal: 20,
paddingBottom: 40, paddingBottom: 40,

View File

@@ -4,13 +4,13 @@ import HeaderBar from '@app/components/HeaderBar'
import ImageGradientFlatList from '@app/components/ImageGradientFlatList' import ImageGradientFlatList from '@app/components/ImageGradientFlatList'
import ListItem from '@app/components/ListItem' import ListItem from '@app/components/ListItem'
import ListPlayerControls from '@app/components/ListPlayerControls' import ListPlayerControls from '@app/components/ListPlayerControls'
import { useCoverArtFile } from '@app/hooks/cache' import NothingHere from '@app/components/NothingHere'
import { useAlbumWithSongs, usePlaylistWithSongs } from '@app/hooks/music' import { useQueryAlbum, useQueryCoverArtPath, useQueryPlaylist } from '@app/hooks/query'
import { AlbumWithSongs, PlaylistWithSongs, Song } from '@app/models/music' import { useSetQueue } from '@app/hooks/trackplayer'
import { useStore } from '@app/state/store' import { Album, Playlist, Song } from '@app/models/library'
import { selectTrackPlayer } from '@app/state/trackplayer'
import colors from '@app/styles/colors' import colors from '@app/styles/colors'
import font from '@app/styles/font' import font from '@app/styles/font'
import equal from 'fast-deep-equal/es6/react'
import React, { useState } from 'react' import React, { useState } from 'react'
import { ActivityIndicator, StyleSheet, Text, View } from 'react-native' import { ActivityIndicator, StyleSheet, Text, View } from 'react-native'
@@ -30,6 +30,7 @@ const SongRenderItem: React.FC<{
subtitle?: string subtitle?: string
onPress?: () => void onPress?: () => void
showArt?: boolean showArt?: boolean
disabled?: boolean
} }
}> = ({ item }) => ( }> = ({ item }) => (
<ListItem <ListItem
@@ -40,28 +41,23 @@ const SongRenderItem: React.FC<{
onPress={item.onPress} onPress={item.onPress}
showArt={item.showArt} showArt={item.showArt}
style={styles.listItem} style={styles.listItem}
disabled={item.disabled}
/> />
) )
const SongListDetails = React.memo<{ const SongListDetails = React.memo<{
title: string title: string
type: SongListType type: SongListType
songList?: AlbumWithSongs | PlaylistWithSongs songList?: Album | Playlist
songs?: Song[]
subtitle?: string subtitle?: string
}>(({ title, songList, subtitle, type }) => { }>(({ title, songList, songs, subtitle, type }) => {
const coverArtFile = useCoverArtFile(songList?.coverArt, 'thumbnail') const { data: coverArtPath } = useQueryCoverArtPath(songList?.coverArt, 'thumbnail')
const [headerColor, setHeaderColor] = useState<string | undefined>(undefined) const [headerColor, setHeaderColor] = useState<string | undefined>(undefined)
const setQueue = useStore(selectTrackPlayer.setQueue)
if (!songList) { const _songs = [...(songs || [])]
return <SongListDetailsFallback />
}
const _songs = [...songList.songs]
let typeName = ''
if (type === 'album') { if (type === 'album') {
typeName = 'Album'
if (_songs.some(s => s.track === undefined)) { if (_songs.some(s => s.track === undefined)) {
_songs.sort((a, b) => a.title.localeCompare(b.title)) _songs.sort((a, b) => a.title.localeCompare(b.title))
} else { } else {
@@ -71,10 +67,18 @@ const SongListDetails = React.memo<{
return aVal - bVal return aVal - bVal
}) })
} }
} else {
typeName = 'Playlist'
} }
const { setQueue, contextId } = useSetQueue(type, _songs)
if (!songList) {
return <SongListDetailsFallback />
}
const disabled = _songs.length === 0
const play = (track?: number, shuffle?: boolean) => () =>
setQueue({ title: songList.name, playTrack: track, shuffle })
return ( return (
<View style={styles.container}> <View style={styles.container}>
<HeaderBar <HeaderBar
@@ -85,74 +89,99 @@ const SongListDetails = React.memo<{
<ImageGradientFlatList <ImageGradientFlatList
data={_songs.map((s, i) => ({ data={_songs.map((s, i) => ({
song: s, song: s,
contextId: songList.id, contextId,
queueId: i, queueId: i,
subtitle: s.artist, subtitle: s.artist,
onPress: () => setQueue(_songs, songList.name, type, songList.id, i), onPress: play(i),
showArt: songList.itemType === 'playlist', showArt: songList.itemType === 'playlist',
disabled: disabled,
}))} }))}
renderItem={SongRenderItem} renderItem={SongRenderItem}
keyExtractor={(item, i) => i.toString()} keyExtractor={(item, i) => i.toString()}
backgroundProps={{ backgroundProps={{
imagePath: coverArtFile?.file?.path, imagePath: coverArtPath,
style: styles.container, style: styles.container,
onGetColor: setHeaderColor, onGetColor: setHeaderColor,
}} }}
overScrollMode="never" overScrollMode="never"
windowSize={7} windowSize={7}
contentMarginTop={26} contentMarginTop={26}
ListEmptyComponent={
songs ? (
<NothingHere style={styles.nothing} />
) : (
<ActivityIndicator size="large" color={colors.accent} style={styles.listLoading} />
)
}
ListHeaderComponent={ ListHeaderComponent={
<View style={styles.content}> <View style={styles.content}>
<CoverArt type="cover" size="original" coverArt={songList.coverArt} style={styles.cover} /> <CoverArt type="cover" size="original" coverArt={songList.coverArt} style={styles.cover} />
<Text style={styles.title}>{songList.name}</Text> <Text style={styles.title}>{songList.name}</Text>
{subtitle ? <Text style={styles.subtitle}>{subtitle}</Text> : <></>} {subtitle ? <Text style={styles.subtitle}>{subtitle}</Text> : <></>}
{songList.songs.length > 0 && (
<ListPlayerControls <ListPlayerControls
style={styles.controls} style={styles.controls}
songs={_songs} songs={_songs}
typeName={typeName} listType={type}
queueName={songList.name} play={play(undefined, false)}
queueContextId={songList.id} shuffle={play(undefined, true)}
queueContextType={type} disabled={disabled}
/> />
)}
</View> </View>
} }
/> />
</View> </View>
) )
}) }, equal)
const PlaylistView = React.memo<{ const PlaylistView = React.memo<{
id: string id: string
title: string title: string
}>(({ id, title }) => { playlist?: Playlist
const playlist = usePlaylistWithSongs(id) }>(({ id, title, playlist }) => {
return <SongListDetails title={title} songList={playlist} subtitle={playlist?.comment} type="playlist" /> const query = useQueryPlaylist(id, playlist)
})
return (
<SongListDetails
title={title}
songList={query.data?.playlist}
songs={query.data?.songs}
subtitle={query.data?.playlist?.comment}
type="playlist"
/>
)
}, equal)
const AlbumView = React.memo<{ const AlbumView = React.memo<{
id: string id: string
title: string title: string
}>(({ id, title }) => { album?: Album
const album = useAlbumWithSongs(id) }>(({ id, title, album }) => {
const query = useQueryAlbum(id, album)
return ( return (
<SongListDetails <SongListDetails
title={title} title={title}
songList={album} songList={query.data?.album}
subtitle={(album?.artist || '') + (album?.year ? ' • ' + album?.year : '')} songs={query.data?.songs}
subtitle={(query.data?.album?.artist || '') + (query.data?.album?.year ? ' • ' + query.data?.album?.year : '')}
type="album" type="album"
/> />
) )
}) }, equal)
const SongListView = React.memo<{ const SongListView = React.memo<{
id: string id: string
title: string title: string
type: SongListType type: SongListType
}>(({ id, title, type }) => { album?: Album
return type === 'album' ? <AlbumView id={id} title={title} /> : <PlaylistView id={id} title={title} /> playlist?: Playlist
}) }>(({ id, title, type, album, playlist }) => {
return type === 'album' ? (
<AlbumView id={id} title={title} album={album} />
) : (
<PlaylistView id={id} title={title} playlist={playlist} />
)
}, equal)
const styles = StyleSheet.create({ const styles = StyleSheet.create({
container: { container: {
@@ -196,6 +225,12 @@ const styles = StyleSheet.create({
listItem: { listItem: {
paddingHorizontal: 20, paddingHorizontal: 20,
}, },
nothing: {
width: '100%',
},
listLoading: {
marginTop: 10,
},
}) })
export default SongListView export default SongListView

View File

@@ -45,7 +45,7 @@ const SplashPage: React.FC<{}> = ({ children }) => {
const splash = ( const splash = (
<Animated.View style={[styles.splashContainer, animatedStyles]} pointerEvents="none"> <Animated.View style={[styles.splashContainer, animatedStyles]} pointerEvents="none">
<GradientBackground style={styles.background}> <GradientBackground style={styles.background} height="100%">
<View style={styles.logoContainer}> <View style={styles.logoContainer}>
<Image style={styles.image} source={require('@res/casette.png')} fadeDuration={0} /> <Image style={styles.image} source={require('@res/casette.png')} fadeDuration={0} />
<Text style={styles.text}>subtracks</Text> <Text style={styles.text}>subtracks</Text>

View File

@@ -1,9 +1,17 @@
import React from 'react' import { useNavigation } from '@react-navigation/native'
import React, { useEffect } from 'react'
import { WebView } from 'react-native-webview' import { WebView } from 'react-native-webview'
const WebViewScreen: React.FC<{ const WebViewScreen: React.FC<{
uri: string uri: string
}> = ({ uri }) => { title?: string
}> = ({ uri, title }) => {
const navigation = useNavigation()
useEffect(() => {
navigation.setOptions({ title })
}, [navigation, title])
return <WebView source={{ uri }} /> return <WebView source={{ uri }} />
} }

View File

@@ -1,293 +0,0 @@
import { CacheFile, CacheImageSize, CacheItemType, CacheItemTypeKey, CacheRequest } from '@app/models/cache'
import { mkdir, rmdir } from '@app/util/fs'
import PromiseQueue from '@app/util/PromiseQueue'
import produce from 'immer'
import RNFS from 'react-native-fs'
import { GetState, SetState } from 'zustand'
import { Store } from './store'
const queues: Record<CacheItemTypeKey, PromiseQueue> = {
coverArt: new PromiseQueue(5),
coverArtThumb: new PromiseQueue(50),
artistArt: new PromiseQueue(5),
artistArtThumb: new PromiseQueue(50),
song: new PromiseQueue(1),
}
export type CacheDownload = CacheFile & CacheRequest
export type CacheDirsByServer = Record<string, Record<CacheItemTypeKey, string>>
export type CacheFilesByServer = Record<string, Record<CacheItemTypeKey, Record<string, CacheFile>>>
export type CacheRequestsByServer = Record<string, Record<CacheItemTypeKey, Record<string, CacheRequest>>>
// export type DownloadedItemsByServer = Record<
// string,
// {
// songs: { [songId: string]: DownloadedSong }
// albums: { [albumId: string]: DownloadedAlbum }
// artists: { [songId: string]: DownloadedArtist }
// playlists: { [playlistId: string]: DownloadedPlaylist }
// }
// >
export type CacheSlice = {
cacheItem: (
key: CacheItemTypeKey,
itemId: string,
url: string | (() => string | Promise<string | undefined>),
) => Promise<void>
// cache: DownloadedItemsByServer
cacheDirs: CacheDirsByServer
cacheFiles: CacheFilesByServer
cacheRequests: CacheRequestsByServer
fetchCoverArtFilePath: (coverArt: string, size?: CacheImageSize) => Promise<string | undefined>
createCache: (serverId: string) => Promise<void>
prepareCache: (serverId: string) => void
pendingRemoval: Record<string, boolean>
removeCache: (serverId: string) => Promise<void>
clearImageCache: () => Promise<void>
}
export const selectCache = {
cacheItem: (store: CacheSlice) => store.cacheItem,
fetchCoverArtFilePath: (store: CacheSlice) => store.fetchCoverArtFilePath,
clearImageCache: (store: CacheSlice) => store.clearImageCache,
}
export const createCacheSlice = (set: SetState<Store>, get: GetState<Store>): CacheSlice => ({
// cache: {},
cacheDirs: {},
cacheFiles: {},
cacheRequests: {},
cacheItem: async (key, itemId, url) => {
const client = get().client
if (!client) {
return
}
const activeServerId = get().settings.activeServer
if (!activeServerId) {
return
}
if (get().pendingRemoval[activeServerId]) {
return
}
const inProgress = get().cacheRequests[activeServerId][key][itemId]
if (inProgress && inProgress.promise !== undefined) {
return await inProgress.promise
}
const existing = get().cacheFiles[activeServerId][key][itemId]
if (existing) {
return
}
const path = `${get().cacheDirs[activeServerId][key]}/${itemId}`
const promise = queues[key].enqueue(async () => {
const urlResult = typeof url === 'string' ? url : url()
const fromUrl = typeof urlResult === 'string' ? urlResult : await urlResult
try {
if (!fromUrl) {
throw new Error('cannot resolve url for cache request')
}
await RNFS.downloadFile({
fromUrl,
toFile: path,
// progressInterval: 100,
// progress: res => {
// set(
// produce<CacheSlice>(state => {
// state.cacheRequests[activeServerId][key][itemId].progress = Math.max(
// 1,
// res.bytesWritten / (res.contentLength || 1),
// )
// }),
// )
// },
}).promise
set(
produce<CacheSlice>(state => {
state.cacheRequests[activeServerId][key][itemId].progress = 1
delete state.cacheRequests[activeServerId][key][itemId].promise
}),
)
} catch {
set(
produce<CacheSlice>(state => {
delete state.cacheFiles[activeServerId][key][itemId]
delete state.cacheRequests[activeServerId][key][itemId]
}),
)
}
})
set(
produce<Store>(state => {
state.cacheFiles[activeServerId][key][itemId] = {
path,
date: Date.now(),
permanent: false,
}
state.cacheRequests[activeServerId][key][itemId] = {
progress: 0,
promise,
}
}),
)
return await promise
},
fetchCoverArtFilePath: async (coverArt, size = 'thumbnail') => {
const client = get().client
if (!client) {
return
}
const activeServerId = get().settings.activeServer
if (!activeServerId) {
return
}
const key: CacheItemTypeKey = size === 'thumbnail' ? 'coverArtThumb' : 'coverArt'
const existing = get().cacheFiles[activeServerId][key][coverArt]
const inProgress = get().cacheRequests[activeServerId][key][coverArt]
if (existing && inProgress) {
if (inProgress.promise) {
await inProgress.promise
}
return `file://${existing.path}`
}
await get().cacheItem(key, coverArt, () =>
client.getCoverArtUri({
id: coverArt,
size: size === 'thumbnail' ? '256' : undefined,
}),
)
return `file://${get().cacheFiles[activeServerId][key][coverArt].path}`
},
createCache: async serverId => {
for (const type in CacheItemType) {
await mkdir(`${RNFS.DocumentDirectoryPath}/servers/${serverId}/${type}`)
}
set(
produce<CacheSlice>(state => {
state.cacheFiles[serverId] = {
song: {},
coverArt: {},
coverArtThumb: {},
artistArt: {},
artistArtThumb: {},
}
}),
)
get().prepareCache(serverId)
},
prepareCache: serverId => {
set(
produce<CacheSlice>(state => {
if (!state.cacheDirs[serverId]) {
state.cacheDirs[serverId] = {
song: `${RNFS.DocumentDirectoryPath}/servers/${serverId}/song`,
coverArt: `${RNFS.DocumentDirectoryPath}/servers/${serverId}/coverArt`,
coverArtThumb: `${RNFS.DocumentDirectoryPath}/servers/${serverId}/coverArtThumb`,
artistArt: `${RNFS.DocumentDirectoryPath}/servers/${serverId}/artistArt`,
artistArtThumb: `${RNFS.DocumentDirectoryPath}/servers/${serverId}/artistArtThumb`,
}
}
if (!state.cacheRequests[serverId]) {
state.cacheRequests[serverId] = {
song: {},
coverArt: {},
coverArtThumb: {},
artistArt: {},
artistArtThumb: {},
}
}
}),
)
},
pendingRemoval: {},
removeCache: async serverId => {
set(
produce<CacheSlice>(state => {
state.pendingRemoval[serverId] = true
}),
)
const cacheRequests = get().cacheRequests[serverId]
const pendingRequests: Promise<void>[] = []
for (const type in CacheItemType) {
const requests = Object.values(cacheRequests[type as CacheItemTypeKey])
.filter(r => r.promise !== undefined)
.map(r => r.promise) as Promise<void>[]
pendingRequests.push(...requests)
}
await Promise.all(pendingRequests)
await rmdir(`${RNFS.DocumentDirectoryPath}/servers/${serverId}`)
set(
produce<CacheSlice>(state => {
delete state.pendingRemoval[serverId]
if (state.cacheDirs[serverId]) {
delete state.cacheDirs[serverId]
}
if (state.cacheFiles[serverId]) {
delete state.cacheFiles[serverId]
}
if (state.cacheRequests[serverId]) {
delete state.cacheRequests[serverId]
}
}),
)
},
clearImageCache: async () => {
const cacheRequests = get().cacheRequests
for (const serverId in cacheRequests) {
const coverArtRequests = cacheRequests[serverId].coverArt
const artstArtRequests = cacheRequests[serverId].artistArt
const requests = [...Object.values(coverArtRequests), ...Object.values(artstArtRequests)]
const pendingRequests = [
...(requests.filter(r => r.promise !== undefined).map(r => r.promise) as Promise<void>[]),
]
await Promise.all(pendingRequests)
await rmdir(get().cacheDirs[serverId].coverArt)
await mkdir(get().cacheDirs[serverId].coverArt)
await rmdir(get().cacheDirs[serverId].artistArt)
await mkdir(get().cacheDirs[serverId].artistArt)
set(
produce<CacheSlice>(state => {
state.cacheFiles[serverId].coverArt = {}
state.cacheFiles[serverId].coverArtThumb = {}
state.cacheFiles[serverId].artistArt = {}
state.cacheFiles[serverId].artistArtThumb = {}
}),
)
}
},
})

View File

@@ -1,11 +1,69 @@
const migrations: Array<(state: any) => any> = [ import { Server } from '@app/models/settings'
state => { import { ById } from '@app/models/state'
import { newCacheBuster } from './settings'
import RNFS from 'react-native-fs'
const migrations: Array<(state: any) => Promise<any>> = [
// 1
async state => {
for (let server of state.settings.servers) { for (let server of state.settings.servers) {
server.usePlainPassword = false server.usePlainPassword = false
} }
return state return state
}, },
// 2
async state => {
state.settings.servers = state.settings.servers.reduce((acc: ById<Server>, server: Server) => {
acc[server.id] = server
return acc
}, {} as ById<Server>)
state.settings.activeServerId = state.settings.activeServer
delete state.settings.activeServer
state.settings.screens.home.listTypes = [...state.settings.screens.home.lists]
delete state.settings.screens.home.lists
state.settings.screens.library.albumsFilter = { ...state.settings.screens.library.albums }
delete state.settings.screens.library.albums
state.settings.screens.library.artistsFilter = { ...state.settings.screens.library.artists }
delete state.settings.screens.library.artists
delete state.settings.estimateContentLength
return state
},
// 3
async state => {
state.settings.cacheBuster = newCacheBuster()
state.settings.servers = Object.values(state.settings.servers as Record<string, Server>).reduce(
(acc, server, i) => {
const newId = i.toString()
if (server.id === state.settings.activeServerId) {
state.settings.activeServerId = newId
}
server.id = newId
acc[newId] = server
return acc
},
{} as Record<string, Server>,
)
try {
await RNFS.unlink(`${RNFS.DocumentDirectoryPath}/servers`)
} catch (err) {
console.error(err)
}
return state
},
] ]
export default migrations export default migrations

View File

@@ -1,471 +0,0 @@
import {
AlbumListItem,
AlbumWithSongs,
Artist,
ArtistInfo,
HomeLists,
PlaylistListItem,
PlaylistWithSongs,
SearchResults,
StarrableItemType,
} from '@app/models/music'
import { Store } from '@app/state/store'
import { GetAlbumList2Params, GetAlbumList2TypeBase, Search3Params, StarParams } from '@app/subsonic/params'
import produce from 'immer'
import { GetState, SetState } from 'zustand'
export type MusicSlice = {
//
// family-style state
//
artistInfo: { [id: string]: ArtistInfo }
fetchArtistInfo: (id: string) => Promise<ArtistInfo | undefined>
albumsWithSongs: { [id: string]: AlbumWithSongs }
fetchAlbumWithSongs: (id: string) => Promise<AlbumWithSongs | undefined>
playlistsWithSongs: { [id: string]: PlaylistWithSongs }
fetchPlaylistWithSongs: (id: string) => Promise<PlaylistWithSongs | undefined>
//
// lists-style state
//
fetchArtists: (size?: number, offset?: number) => Promise<Artist[]>
fetchPlaylists: () => Promise<PlaylistListItem[]>
fetchAlbums: () => Promise<AlbumListItem[]>
fetchSearchResults: (
query: string,
type?: 'album' | 'song' | 'artist',
size?: number,
offset?: number,
) => Promise<SearchResults>
homeLists: HomeLists
homeListsUpdating: boolean
fetchHomeLists: () => Promise<void>
clearHomeLists: () => void
//
// actions, etc.
//
starredSongs: { [id: string]: boolean }
starredAlbums: { [id: string]: boolean }
starredArtists: { [id: string]: boolean }
starItem: (id: string, type: StarrableItemType, unstar?: boolean) => Promise<void>
albumIdCoverArt: { [id: string]: string | undefined }
albumIdCoverArtRequests: { [id: string]: Promise<void> }
fetchAlbumCoverArt: (id: string) => Promise<void>
getAlbumCoverArt: (id: string | undefined) => Promise<string | undefined>
}
export const selectMusic = {
fetchArtistInfo: (state: Store) => state.fetchArtistInfo,
fetchAlbumWithSongs: (state: Store) => state.fetchAlbumWithSongs,
fetchPlaylistWithSongs: (state: Store) => state.fetchPlaylistWithSongs,
fetchArtists: (store: MusicSlice) => store.fetchArtists,
fetchPlaylists: (store: MusicSlice) => store.fetchPlaylists,
fetchAlbums: (store: MusicSlice) => store.fetchAlbums,
fetchSearchResults: (store: MusicSlice) => store.fetchSearchResults,
homeLists: (store: MusicSlice) => store.homeLists,
homeListsUpdating: (store: MusicSlice) => store.homeListsUpdating,
fetchHomeLists: (store: MusicSlice) => store.fetchHomeLists,
clearHomeLists: (store: MusicSlice) => store.clearHomeLists,
starItem: (store: MusicSlice) => store.starItem,
}
function reduceStarred(
starredType: { [id: string]: boolean },
items: { id: string; starred?: Date | boolean }[],
): { [id: string]: boolean } {
return {
...starredType,
...items.reduce((acc, val) => {
acc[val.id] = !!val.starred
return acc
}, {} as { [id: string]: boolean }),
}
}
export const createMusicSlice = (set: SetState<Store>, get: GetState<Store>): MusicSlice => ({
artistInfo: {},
fetchArtistInfo: async id => {
const client = get().client
if (!client) {
return undefined
}
try {
const [artistResponse, artistInfoResponse] = await Promise.all([
client.getArtist({ id }),
client.getArtistInfo2({ id }),
])
const topSongsResponse = await client.getTopSongs({ artist: artistResponse.data.artist.name, count: 50 })
const artistInfo = await get().mapArtistInfo(
artistResponse.data,
artistInfoResponse.data.artistInfo,
topSongsResponse.data.songs,
)
set(
produce<MusicSlice>(state => {
state.artistInfo[id] = artistInfo
state.starredSongs = reduceStarred(state.starredSongs, artistInfo.topSongs)
state.starredArtists = reduceStarred(state.starredArtists, [artistInfo])
state.starredAlbums = reduceStarred(state.starredAlbums, artistInfo.albums)
}),
)
return artistInfo
} catch {
return undefined
}
},
albumsWithSongs: {},
fetchAlbumWithSongs: async id => {
const client = get().client
if (!client) {
return undefined
}
try {
const response = await client.getAlbum({ id })
const album = await get().mapAlbumID3WithSongstoAlbumWithSongs(response.data.album, response.data.songs)
set(
produce<MusicSlice>(state => {
state.albumsWithSongs[id] = album
state.starredSongs = reduceStarred(state.starredSongs, album.songs)
state.starredAlbums = reduceStarred(state.starredAlbums, [album])
}),
)
return album
} catch {
return undefined
}
},
playlistsWithSongs: {},
fetchPlaylistWithSongs: async id => {
const client = get().client
if (!client) {
return undefined
}
try {
const response = await client.getPlaylist({ id })
const playlist = await get().mapPlaylistWithSongs(response.data.playlist)
set(
produce<MusicSlice>(state => {
state.playlistsWithSongs[id] = playlist
state.starredSongs = reduceStarred(state.starredSongs, playlist.songs)
}),
)
return playlist
} catch {
return undefined
}
},
fetchArtists: async () => {
const client = get().client
if (!client) {
return []
}
try {
const response = await client.getArtists()
const artists = response.data.artists.map(get().mapArtistID3toArtist)
set(
produce<MusicSlice>(state => {
state.starredArtists = reduceStarred(state.starredArtists, artists)
}),
)
return artists
} catch {
return []
}
},
fetchPlaylists: async () => {
const client = get().client
if (!client) {
return []
}
try {
const response = await client.getPlaylists()
return response.data.playlists.map(get().mapPlaylistListItem)
} catch {
return []
}
},
fetchAlbums: async (size = 500, offset = 0) => {
const client = get().client
if (!client) {
return []
}
try {
const filter = get().settings.screens.library.albums
let params: GetAlbumList2Params
switch (filter.type) {
case 'byYear':
params = {
size,
offset,
type: filter.type,
fromYear: filter.fromYear,
toYear: filter.toYear,
}
break
case 'byGenre':
params = {
size,
offset,
type: filter.type,
genre: filter.genre,
}
break
default:
params = {
size,
offset,
type: filter.type,
}
break
}
const response = await client.getAlbumList2(params)
const albums = response.data.albums.map(get().mapAlbumID3toAlbumListItem)
set(
produce<MusicSlice>(state => {
state.starredAlbums = reduceStarred(state.starredAlbums, albums)
}),
)
return albums
} catch {
return []
}
},
fetchSearchResults: async (query, type, size, offset) => {
if (query.length < 2) {
return { artists: [], albums: [], songs: [] }
}
const client = get().client
if (!client) {
return { artists: [], albums: [], songs: [] }
}
try {
const params: Search3Params = { query }
if (type === 'album') {
params.albumCount = size
params.albumOffset = offset
} else if (type === 'artist') {
params.artistCount = size
params.artistOffset = offset
} else if (type === 'song') {
params.songCount = size
params.songOffset = offset
} else {
params.albumCount = 5
params.artistCount = 5
params.songCount = 5
}
const response = await client.search3(params)
const artists = response.data.artists.map(get().mapArtistID3toArtist)
const albums = response.data.albums.map(get().mapAlbumID3toAlbumListItem)
const songs = await get().mapChildrenToSongs(response.data.songs)
set(
produce<MusicSlice>(state => {
state.starredSongs = reduceStarred(state.starredSongs, songs)
state.starredArtists = reduceStarred(state.starredArtists, artists)
state.starredAlbums = reduceStarred(state.starredAlbums, albums)
}),
)
return { artists, albums, songs }
} catch {
return { artists: [], albums: [], songs: [] }
}
},
homeLists: {},
homeListsUpdating: false,
fetchHomeLists: async () => {
const client = get().client
if (!client) {
return
}
if (get().homeListsUpdating) {
return
}
set({ homeListsUpdating: true })
const types = get().settings.screens.home.lists
try {
const promises: Promise<any>[] = []
for (const type of types) {
promises.push(
client
.getAlbumList2({ type: type as GetAlbumList2TypeBase, size: 20 })
.then(response => {
const list = response.data.albums.map(get().mapAlbumID3toAlbumListItem)
set(
produce<MusicSlice>(state => {
state.homeLists[type] = list
state.starredAlbums = reduceStarred(state.starredAlbums, state.homeLists[type])
}),
)
})
.catch(() => {}),
)
}
await Promise.all(promises)
} finally {
set({ homeListsUpdating: false })
}
},
clearHomeLists: () => {
set({ homeLists: {} })
},
starredSongs: {},
starredAlbums: {},
starredArtists: {},
starItem: async (id, type, unstar = false) => {
const client = get().client
if (!client) {
return
}
let params: StarParams
let setStarred: (starred: boolean) => void
switch (type) {
case 'song':
params = { id }
setStarred = starred => {
set(
produce<MusicSlice>(state => {
state.starredSongs = reduceStarred(state.starredSongs, [{ id, starred }])
}),
)
}
break
case 'album':
params = { albumId: id }
setStarred = starred => {
set(
produce<MusicSlice>(state => {
state.starredAlbums = reduceStarred(state.starredAlbums, [{ id, starred }])
}),
)
}
break
case 'artist':
params = { artistId: id }
setStarred = starred => {
set(
produce<MusicSlice>(state => {
state.starredArtists = reduceStarred(state.starredArtists, [{ id, starred }])
}),
)
}
break
default:
return
}
try {
setStarred(!unstar)
if (unstar) {
await client.unstar(params)
} else {
await client.star(params)
}
} catch {
setStarred(unstar)
}
},
albumIdCoverArt: {},
albumIdCoverArtRequests: {},
fetchAlbumCoverArt: async id => {
const client = get().client
if (!client) {
return
}
const inProgress = get().albumIdCoverArtRequests[id]
if (inProgress !== undefined) {
return await inProgress
}
const promise = new Promise<void>(async resolve => {
try {
const response = await client.getAlbum({ id })
set(
produce<MusicSlice>(state => {
state.albumIdCoverArt[id] = response.data.album.coverArt
}),
)
} finally {
resolve()
}
}).then(() => {
set(
produce<MusicSlice>(state => {
delete state.albumIdCoverArtRequests[id]
}),
)
})
set(
produce<MusicSlice>(state => {
state.albumIdCoverArtRequests[id] = promise
}),
)
return await promise
},
getAlbumCoverArt: async id => {
if (!id) {
return
}
const existing = get().albumIdCoverArt[id]
if (existing) {
return existing
}
await get().fetchAlbumCoverArt(id)
return get().albumIdCoverArt[id]
},
})

View File

@@ -1,142 +0,0 @@
import {
AlbumListItem,
AlbumWithSongs,
Artist,
ArtistInfo,
PlaylistListItem,
PlaylistWithSongs,
Song,
} from '@app/models/music'
import {
AlbumID3Element,
ArtistID3Element,
ArtistInfo2Element,
ChildElement,
PlaylistElement,
PlaylistWithSongsElement,
} from '@app/subsonic/elements'
import { GetArtistResponse } from '@app/subsonic/responses'
import { GetState, SetState } from 'zustand'
import { Store } from './store'
export type MusicMapSlice = {
mapChildToSong: (child: ChildElement, coverArt?: string) => Promise<Song>
mapChildrenToSongs: (children: ChildElement[], coverArt?: string) => Promise<Song[]>
mapArtistID3toArtist: (artist: ArtistID3Element) => Artist
mapArtistInfo: (
artistResponse: GetArtistResponse,
info: ArtistInfo2Element,
topSongs: ChildElement[],
) => Promise<ArtistInfo>
mapAlbumID3toAlbumListItem: (album: AlbumID3Element) => AlbumListItem
mapAlbumID3toAlbum: (album: AlbumID3Element) => AlbumListItem
mapAlbumID3WithSongstoAlbumWithSongs: (album: AlbumID3Element, songs: ChildElement[]) => Promise<AlbumWithSongs>
mapPlaylistListItem: (playlist: PlaylistElement) => PlaylistListItem
mapPlaylistWithSongs: (playlist: PlaylistWithSongsElement) => Promise<PlaylistWithSongs>
}
export const createMusicMapSlice = (set: SetState<Store>, get: GetState<Store>): MusicMapSlice => ({
mapChildToSong: async (child, coverArt) => {
return {
itemType: 'song',
id: child.id,
album: child.album,
albumId: child.albumId,
artist: child.artist,
artistId: child.artistId,
title: child.title,
track: child.track,
discNumber: child.discNumber,
duration: child.duration,
starred: child.starred,
coverArt: coverArt || (await get().getAlbumCoverArt(child.albumId)),
streamUri: get().buildStreamUri(child.id),
}
},
mapChildrenToSongs: async (children, coverArt) => {
const albumIds = children.reduce((acc, val) => {
if (val.albumId && !(val.albumId in acc)) {
acc[val.albumId] = get().getAlbumCoverArt(val.albumId)
}
return acc
}, {} as Record<string, Promise<string | undefined>>)
await Promise.all(Object.values(albumIds))
const songs: Song[] = []
for (const child of children) {
songs.push(await get().mapChildToSong(child, coverArt || (await get().getAlbumCoverArt(child.albumId))))
}
return songs
},
mapArtistID3toArtist: artist => {
return {
itemType: 'artist',
id: artist.id,
name: artist.name,
starred: artist.starred,
coverArt: artist.coverArt,
}
},
mapArtistInfo: async (artistResponse, info, topSongs) => {
const { artist, albums } = artistResponse
const mappedAlbums = albums.map(get().mapAlbumID3toAlbum)
return {
...get().mapArtistID3toArtist(artist),
albums: mappedAlbums,
smallImageUrl: info.smallImageUrl,
largeImageUrl: info.largeImageUrl,
topSongs: (await get().mapChildrenToSongs(topSongs)).slice(0, 5),
}
},
mapAlbumID3toAlbumListItem: album => {
return {
itemType: 'album',
id: album.id,
name: album.name,
artist: album.artist,
artistId: album.artistId,
starred: album.starred,
coverArt: album.coverArt,
}
},
mapAlbumID3toAlbum: album => {
return {
...get().mapAlbumID3toAlbumListItem(album),
coverArt: album.coverArt,
year: album.year,
}
},
mapAlbumID3WithSongstoAlbumWithSongs: async (album, songs) => {
return {
...get().mapAlbumID3toAlbum(album),
songs: await get().mapChildrenToSongs(songs),
}
},
mapPlaylistListItem: playlist => {
return {
itemType: 'playlist',
id: playlist.id,
name: playlist.name,
comment: playlist.comment,
coverArt: playlist.coverArt,
}
},
mapPlaylistWithSongs: async playlist => {
return {
...get().mapPlaylistListItem(playlist),
songs: await get().mapChildrenToSongs(playlist.songs),
coverArt: playlist.coverArt,
}
},
})

View File

@@ -1,21 +1,44 @@
import { AppSettings, ArtistFilterSettings, AlbumFilterSettings, Server } from '@app/models/settings' import { AlbumFilterSettings, ArtistFilterSettings, ArtistFilterType, Server } from '@app/models/settings'
import { Store } from '@app/state/store' import { ById } from '@app/models/state'
import { GetStore, SetStore } from '@app/state/store'
import { SubsonicApiClient } from '@app/subsonic/api' import { SubsonicApiClient } from '@app/subsonic/api'
import produce from 'immer' import { GetAlbumList2TypeBase } from '@app/subsonic/params'
import { GetState, SetState } from 'zustand' import uuid from 'react-native-uuid'
export type SettingsSlice = { export type SettingsSlice = {
settings: AppSettings settings: {
servers: ById<Server>
activeServerId?: string
screens: {
home: {
listTypes: string[]
}
library: {
albumsFilter: AlbumFilterSettings
artistsFilter: ArtistFilterSettings
}
}
scrobble: boolean
maxBitrateWifi: number
maxBitrateMobile: number
minBuffer: number
maxBuffer: number
cacheBuster: string
}
client?: SubsonicApiClient client?: SubsonicApiClient
disableMusicTabs: boolean
setDisableMusicTabs: (value: boolean) => void
changeCacheBuster: () => void
setActiveServer: (id: string | undefined, force?: boolean) => Promise<void> setActiveServer: (id: string | undefined, force?: boolean) => Promise<void>
getActiveServer: () => Server | undefined addServer: (server: Server) => void
addServer: (server: Server) => Promise<void> removeServer: (id: string) => void
removeServer: (id: string) => Promise<void>
updateServer: (server: Server) => void updateServer: (server: Server) => void
setScrobble: (scrobble: boolean) => void setScrobble: (scrobble: boolean) => void
setEstimateContentLength: (estimateContentLength: boolean) => void
setMaxBitrateWifi: (maxBitrateWifi: number) => void setMaxBitrateWifi: (maxBitrateWifi: number) => void
setMaxBitrateMobile: (maxBitrateMobile: number) => void setMaxBitrateMobile: (maxBitrateMobile: number) => void
setMinBuffer: (minBuffer: number) => void setMinBuffer: (minBuffer: number) => void
@@ -23,84 +46,62 @@ export type SettingsSlice = {
pingServer: (server?: Server) => Promise<boolean> pingServer: (server?: Server) => Promise<boolean>
setLibraryAlbumFilter: (filter: AlbumFilterSettings) => void setLibraryAlbumFilterType: (type: GetAlbumList2TypeBase) => void
setLibraryArtistFiler: (filter: ArtistFilterSettings) => void setLibraryArtistFilterType: (type: ArtistFilterType) => void
} }
export const selectSettings = { export function newCacheBuster(): string {
client: (state: SettingsSlice) => state.client, return (uuid.v4() as string).split('-')[0]
firstRun: (state: SettingsSlice) => state.settings.servers.length === 0,
activeServer: (state: SettingsSlice) => state.settings.servers.find(s => s.id === state.settings.activeServer),
setActiveServer: (state: SettingsSlice) => state.setActiveServer,
servers: (state: SettingsSlice) => state.settings.servers,
addServer: (state: SettingsSlice) => state.addServer,
removeServer: (state: SettingsSlice) => state.removeServer,
updateServer: (state: SettingsSlice) => state.updateServer,
homeLists: (state: SettingsSlice) => state.settings.screens.home.lists,
scrobble: (state: SettingsSlice) => state.settings.scrobble,
setScrobble: (state: SettingsSlice) => state.setScrobble,
estimateContentLength: (state: SettingsSlice) => state.settings.estimateContentLength,
setEstimateContentLength: (state: SettingsSlice) => state.setEstimateContentLength,
maxBitrateWifi: (state: SettingsSlice) => state.settings.maxBitrateWifi,
setMaxBitrateWifi: (state: SettingsSlice) => state.setMaxBitrateWifi,
maxBitrateMobile: (state: SettingsSlice) => state.settings.maxBitrateMobile,
setMaxBitrateMobile: (state: SettingsSlice) => state.setMaxBitrateMobile,
minBuffer: (state: SettingsSlice) => state.settings.minBuffer,
setMinBuffer: (state: SettingsSlice) => state.setMinBuffer,
maxBuffer: (state: SettingsSlice) => state.settings.maxBuffer,
setMaxBuffer: (state: SettingsSlice) => state.setMaxBuffer,
pingServer: (state: SettingsSlice) => state.pingServer,
setLibraryAlbumFilter: (state: SettingsSlice) => state.setLibraryAlbumFilter,
libraryAlbumFilter: (state: SettingsSlice) => state.settings.screens.library.albums,
setLibraryArtistFiler: (state: SettingsSlice) => state.setLibraryArtistFiler,
libraryArtistFilter: (state: SettingsSlice) => state.settings.screens.library.artists,
} }
export const createSettingsSlice = (set: SetState<Store>, get: GetState<Store>): SettingsSlice => ({ export const createSettingsSlice = (set: SetStore, get: GetStore): SettingsSlice => ({
settings: { settings: {
servers: [], servers: {},
screens: { screens: {
home: { home: {
lists: ['frequent', 'recent', 'starred', 'random'], listTypes: ['frequent', 'recent', 'starred', 'random'],
}, },
library: { library: {
albums: { albumsFilter: {
type: 'alphabeticalByArtist', type: 'alphabeticalByArtist',
fromYear: 1, fromYear: 1,
toYear: 9999, toYear: 9999,
genre: '', genre: '',
}, },
artists: { artistsFilter: {
type: 'alphabeticalByName', type: 'alphabeticalByName',
}, },
}, },
}, },
scrobble: false, scrobble: false,
estimateContentLength: true,
maxBitrateWifi: 0, maxBitrateWifi: 0,
maxBitrateMobile: 192, maxBitrateMobile: 192,
minBuffer: 6, minBuffer: 6,
maxBuffer: 60, maxBuffer: 60,
cacheBuster: newCacheBuster(),
},
disableMusicTabs: false,
setDisableMusicTabs: value => {
set(store => {
store.disableMusicTabs = value
})
},
changeCacheBuster: () => {
set(store => {
store.settings.cacheBuster = newCacheBuster()
})
}, },
setActiveServer: async (id, force) => { setActiveServer: async (id, force) => {
const servers = get().settings.servers const servers = get().settings.servers
const currentActiveServerId = get().settings.activeServer const currentActiveServerId = get().settings.activeServerId
const newActiveServer = servers.find(s => s.id === id) const newActiveServer = id ? servers[id] : undefined
if (!newActiveServer) { if (!newActiveServer) {
set({ set(state => {
client: undefined, state.client = undefined
}) })
return return
} }
@@ -109,82 +110,60 @@ export const createSettingsSlice = (set: SetState<Store>, get: GetState<Store>):
return return
} }
get().prepareCache(newActiveServer.id) set(state => {
state.disableMusicTabs = true
})
set( set(state => {
produce<Store>(state => { state.settings.activeServerId = newActiveServer.id
state.settings.activeServer = newActiveServer.id
state.client = new SubsonicApiClient(newActiveServer) state.client = new SubsonicApiClient(newActiveServer)
}), })
)
set(state => {
state.disableMusicTabs = false
})
}, },
getActiveServer: () => get().settings.servers.find(s => s.id === get().settings.activeServer), addServer: server => {
const serverIds = Object.keys(get().settings.servers)
server.id =
serverIds.length === 0 ? '0' : (serverIds.map(i => parseInt(i, 10)).sort((a, b) => b - a)[0] + 1).toString()
addServer: async server => { set(state => {
await get().createCache(server.id) state.settings.servers[server.id] = server
})
set( if (Object.keys(get().settings.servers).length === 1) {
produce<SettingsSlice>(state => {
state.settings.servers.push(server)
}),
)
if (get().settings.servers.length === 1) {
get().setActiveServer(server.id) get().setActiveServer(server.id)
} }
}, },
removeServer: async id => { removeServer: id => {
await get().removeCache(id) set(state => {
delete state.settings.servers[id]
set( })
produce<SettingsSlice>(state => {
state.settings.servers = state.settings.servers.filter(s => s.id !== id)
}),
)
}, },
updateServer: server => { updateServer: server => {
set( set(state => {
produce<SettingsSlice>(state => { state.settings.servers[server.id] = server
state.settings.servers = replaceIndex( })
state.settings.servers,
state.settings.servers.findIndex(s => s.id === server.id),
server,
)
}),
)
if (get().settings.activeServer === server.id) { if (get().settings.activeServerId === server.id) {
get().setActiveServer(server.id, true) get().setActiveServer(server.id, true)
} }
}, },
setScrobble: scrobble => { setScrobble: scrobble => {
set( set(state => {
produce<SettingsSlice>(state => {
state.settings.scrobble = scrobble state.settings.scrobble = scrobble
}), })
)
},
setEstimateContentLength: estimateContentLength => {
set(
produce<SettingsSlice>(state => {
state.settings.estimateContentLength = estimateContentLength
}),
)
get().rebuildQueue()
}, },
setMaxBitrateWifi: maxBitrateWifi => { setMaxBitrateWifi: maxBitrateWifi => {
set( set(state => {
produce<SettingsSlice>(state => {
state.settings.maxBitrateWifi = maxBitrateWifi state.settings.maxBitrateWifi = maxBitrateWifi
}), })
)
if (get().netState === 'wifi') { if (get().netState === 'wifi') {
get().rebuildQueue() get().rebuildQueue()
@@ -192,11 +171,9 @@ export const createSettingsSlice = (set: SetState<Store>, get: GetState<Store>):
}, },
setMaxBitrateMobile: maxBitrateMobile => { setMaxBitrateMobile: maxBitrateMobile => {
set( set(state => {
produce<SettingsSlice>(state => {
state.settings.maxBitrateMobile = maxBitrateMobile state.settings.maxBitrateMobile = maxBitrateMobile
}), })
)
if (get().netState === 'mobile') { if (get().netState === 'mobile') {
get().rebuildQueue() get().rebuildQueue()
@@ -208,11 +185,9 @@ export const createSettingsSlice = (set: SetState<Store>, get: GetState<Store>):
return return
} }
set( set(state => {
produce<SettingsSlice>(state => {
state.settings.minBuffer = Math.max(1, Math.min(minBuffer, state.settings.maxBuffer / 2)) state.settings.minBuffer = Math.max(1, Math.min(minBuffer, state.settings.maxBuffer / 2))
}), })
)
get().rebuildQueue() get().rebuildQueue()
}, },
@@ -222,11 +197,9 @@ export const createSettingsSlice = (set: SetState<Store>, get: GetState<Store>):
return return
} }
set( set(state => {
produce<SettingsSlice>(state => {
state.settings.maxBuffer = Math.min(5 * 60, Math.max(maxBuffer, state.settings.minBuffer * 2)) state.settings.maxBuffer = Math.min(5 * 60, Math.max(maxBuffer, state.settings.minBuffer * 2))
}), })
)
get().rebuildQueue() get().rebuildQueue()
}, },
@@ -251,25 +224,15 @@ export const createSettingsSlice = (set: SetState<Store>, get: GetState<Store>):
} }
}, },
setLibraryAlbumFilter: filter => { setLibraryAlbumFilterType: type => {
set( set(state => {
produce<SettingsSlice>(state => { state.settings.screens.library.albumsFilter.type = type
state.settings.screens.library.albums = filter })
}),
)
}, },
setLibraryArtistFiler: filter => { setLibraryArtistFilterType: type => {
set( set(state => {
produce<SettingsSlice>(state => { state.settings.screens.library.artistsFilter.type = type
state.settings.screens.library.artists = filter })
}),
)
}, },
}) })
function replaceIndex<T>(array: T[], index: number, replacement: T): T[] {
const start = array.slice(0, index)
const end = array.slice(index + 1)
return [...start, replacement, ...end]
}

View File

@@ -1,79 +1,95 @@
import { createMusicSlice, MusicSlice } from '@app/state/music'
import { createSettingsSlice, SettingsSlice } from '@app/state/settings' import { createSettingsSlice, SettingsSlice } from '@app/state/settings'
import AsyncStorage from '@react-native-async-storage/async-storage' import AsyncStorage from '@react-native-async-storage/async-storage'
import create from 'zustand' import equal from 'fast-deep-equal'
import { persist, StateStorage } from 'zustand/middleware' import create, { GetState, Mutate, SetState, State, StateCreator, StateSelector, StoreApi } from 'zustand'
import { CacheSlice, createCacheSlice } from './cache' import { persist, subscribeWithSelector } from 'zustand/middleware'
import migrations from './migrations' import migrations from './migrations'
import { createMusicMapSlice, MusicMapSlice } from './musicmap'
import { createTrackPlayerSlice, TrackPlayerSlice } from './trackplayer' import { createTrackPlayerSlice, TrackPlayerSlice } from './trackplayer'
import { createTrackPlayerMapSlice, TrackPlayerMapSlice } from './trackplayermap' import produce, { Draft } from 'immer'
import { WritableDraft } from 'immer/dist/internal'
const DB_VERSION = migrations.length const DB_VERSION = migrations.length
export type Store = SettingsSlice & export type Store = SettingsSlice &
MusicSlice & TrackPlayerSlice & {
MusicMapSlice &
TrackPlayerSlice &
TrackPlayerMapSlice &
CacheSlice & {
hydrated: boolean hydrated: boolean
setHydrated: (hydrated: boolean) => void setHydrated: (hydrated: boolean) => void
} }
const storage: StateStorage = { // taken from zustand test examples:
getItem: async name => { // https://github.com/pmndrs/zustand/blob/v3.7.1/tests/middlewareTypes.test.tsx#L20
try { const immer =
return await AsyncStorage.getItem(name) <
} catch (err) { T extends State,
console.error(`getItem error (key: ${name})`, err) CustomSetState extends SetState<T>,
return null CustomGetState extends GetState<T>,
} CustomStoreApi extends StoreApi<T>,
>(
config: StateCreator<
T,
(partial: ((draft: Draft<T>) => void) | T, replace?: boolean) => void,
CustomGetState,
CustomStoreApi
>,
): StateCreator<T, CustomSetState, CustomGetState, CustomStoreApi> =>
(set, get, api) =>
config(
(partial, replace) => {
const nextState = typeof partial === 'function' ? produce(partial as (state: Draft<T>) => T) : (partial as T)
return set(nextState, replace)
}, },
setItem: async (name, item) => { get,
try { api,
await AsyncStorage.setItem(name, item) )
} catch (err) {
console.error(`setItem error (key: ${name})`, err)
}
},
}
export const useStore = create<Store>( export type SetStore = (partial: Store | ((draft: WritableDraft<Store>) => void), replace?: boolean | undefined) => void
export type GetStore = GetState<Store>
// types taken from zustand test examples:
// https://github.com/pmndrs/zustand/blob/v3.7.1/tests/middlewareTypes.test.tsx#L584
export const useStore = create<
Store,
SetState<Store>,
GetState<Store>,
Mutate<StoreApi<Store>, [['zustand/subscribeWithSelector', never], ['zustand/persist', Partial<Store>]]>
>(
subscribeWithSelector(
persist( persist(
(set, get) => ({ immer((set, get) => ({
...createSettingsSlice(set, get), ...createSettingsSlice(set, get),
...createMusicSlice(set, get),
...createMusicMapSlice(set, get),
...createTrackPlayerSlice(set, get), ...createTrackPlayerSlice(set, get),
...createTrackPlayerMapSlice(set, get),
...createCacheSlice(set, get),
hydrated: false, hydrated: false,
setHydrated: hydrated => set({ hydrated }), setHydrated: hydrated =>
set(state => {
state.hydrated = hydrated
}), }),
})),
{ {
name: '@appStore', name: '@appStore',
version: DB_VERSION, version: DB_VERSION,
getStorage: () => storage, getStorage: () => AsyncStorage,
whitelist: ['settings', 'cacheFiles'], partialize: state => ({ settings: state.settings }),
onRehydrateStorage: _preState => { onRehydrateStorage: _preState => {
return async (postState, _error) => { return async (postState, _error) => {
await postState?.setActiveServer(postState.settings.activeServer, true) await postState?.setActiveServer(postState.settings.activeServerId, true)
postState?.setHydrated(true) postState?.setHydrated(true)
} }
}, },
migrate: (persistedState, version) => { migrate: async (persistedState, version) => {
if (version > DB_VERSION) { if (version > DB_VERSION) {
throw new Error('cannot migrate db on a downgrade, delete all data first') throw new Error('cannot migrate db on a downgrade, delete all data first')
} }
for (let i = version; i < DB_VERSION; i++) { for (let i = version; i < DB_VERSION; i++) {
persistedState = migrations[i](persistedState) persistedState = await migrations[i](persistedState)
} }
return persistedState return persistedState
}, },
}, },
), ),
),
) )
export const useStoreDeep = <U>(stateSelector: StateSelector<Store, U>) => useStore(stateSelector, equal)

View File

@@ -1,28 +1,22 @@
import { NoClientError } from '@app/models/error' import { NoClientError } from '@app/models/error'
import { Song } from '@app/models/music' import { Progress, QueueContextType, TrackExt } from '@app/models/trackplayer'
import PromiseQueue from '@app/util/PromiseQueue' import PromiseQueue from '@app/util/PromiseQueue'
import produce from 'immer' import produce from 'immer'
import TrackPlayer, { PlayerOptions, RepeatMode, State, Track } from 'react-native-track-player' import TrackPlayer, { PlayerOptions, RepeatMode, State } from 'react-native-track-player'
import { GetState, SetState } from 'zustand' import { GetStore, SetStore } from './store'
import { Store } from './store'
export type TrackExt = Track & { export type SetQueueOptions = {
id: string title: string
coverArt?: string playTrack?: number
artistId?: string shuffle?: boolean
albumId?: string
track?: number
discNumber?: number
} }
export type Progress = { export type SetQueueOptionsInternal = SetQueueOptions & {
position: number queue: TrackExt[]
duration: number contextId: string
buffered: number type: QueueContextType
} }
export type QueueContextType = 'album' | 'playlist' | 'song' | 'artist'
export type TrackPlayerSlice = { export type TrackPlayerSlice = {
queueName?: string queueName?: string
setQueueName: (name?: string) => void setQueueName: (name?: string) => void
@@ -50,14 +44,7 @@ export type TrackPlayerSlice = {
setCurrentTrackIdx: (idx?: number) => void setCurrentTrackIdx: (idx?: number) => void
queue: TrackExt[] queue: TrackExt[]
setQueue: ( setQueue: (options: SetQueueOptionsInternal) => Promise<void>
songs: Song[],
name: string,
contextType: QueueContextType,
contextId: string,
playTrack?: number,
shuffle?: boolean,
) => Promise<void>
progress: Progress progress: Progress
setProgress: (progress: Progress) => void setProgress: (progress: Progress) => void
@@ -68,61 +55,33 @@ export type TrackPlayerSlice = {
setNetState: (netState: 'mobile' | 'wifi') => Promise<void> setNetState: (netState: 'mobile' | 'wifi') => Promise<void>
rebuildQueue: (forcePlay?: boolean) => Promise<void> rebuildQueue: (forcePlay?: boolean) => Promise<void>
updateQueue: () => Promise<void>
buildStreamUri: (id: string) => string buildStreamUri: (id: string) => string
resetTrackPlayerState: () => void resetTrackPlayerState: () => void
getPlayerOptions: () => PlayerOptions getPlayerOptions: () => PlayerOptions
} }
export const selectTrackPlayer = {
queueName: (store: TrackPlayerSlice) => store.queueName,
setQueueName: (store: TrackPlayerSlice) => store.setQueueName,
queueContextType: (store: TrackPlayerSlice) => store.queueContextType,
setQueueContextType: (store: TrackPlayerSlice) => store.setQueueContextType,
queueContextId: (store: TrackPlayerSlice) => store.queueContextId,
setQueueContextId: (store: TrackPlayerSlice) => store.setQueueContextId,
shuffleOrder: (store: TrackPlayerSlice) => store.shuffleOrder,
shuffled: (store: TrackPlayerSlice) => !!store.shuffleOrder,
toggleShuffle: (store: TrackPlayerSlice) => store.toggleShuffle,
repeatMode: (store: TrackPlayerSlice) => store.repeatMode,
toggleRepeatMode: (store: TrackPlayerSlice) => store.toggleRepeatMode,
playerState: (store: TrackPlayerSlice) => store.playerState,
setPlayerState: (store: TrackPlayerSlice) => store.setPlayerState,
currentTrack: (store: TrackPlayerSlice) => store.currentTrack,
currentTrackIdx: (store: TrackPlayerSlice) => store.currentTrackIdx,
setCurrentTrackIdx: (store: TrackPlayerSlice) => store.setCurrentTrackIdx,
queue: (store: TrackPlayerSlice) => store.queue,
setQueue: (store: TrackPlayerSlice) => store.setQueue,
progress: (store: TrackPlayerSlice) => store.progress,
setProgress: (store: TrackPlayerSlice) => store.setProgress,
scrobbleTrack: (store: TrackPlayerSlice) => store.scrobbleTrack,
setNetState: (store: TrackPlayerSlice) => store.setNetState,
buildStreamUri: (store: TrackPlayerSlice) => store.buildStreamUri,
resetTrackPlayerState: (store: TrackPlayerSlice) => store.resetTrackPlayerState,
}
export const trackPlayerCommands = new PromiseQueue(1) export const trackPlayerCommands = new PromiseQueue(1)
export const createTrackPlayerSlice = (set: SetState<Store>, get: GetState<Store>): TrackPlayerSlice => ({ export const createTrackPlayerSlice = (set: SetStore, get: GetStore): TrackPlayerSlice => ({
queueName: undefined, queueName: undefined,
setQueueName: name => set({ queueName: name }), setQueueName: name =>
set(state => {
state.queueName = name
}),
queueContextType: undefined, queueContextType: undefined,
setQueueContextType: queueContextType => set({ queueContextType }), setQueueContextType: queueContextType =>
set(state => {
state.queueContextType = queueContextType
}),
queueContextId: undefined, queueContextId: undefined,
setQueueContextId: queueContextId => set({ queueContextId }), setQueueContextId: queueContextId =>
set(state => {
state.queueContextId = queueContextId
}),
shuffleOrder: undefined, shuffleOrder: undefined,
toggleShuffle: async () => { toggleShuffle: async () => {
@@ -140,7 +99,9 @@ export const createTrackPlayerSlice = (set: SetState<Store>, get: GetState<Store
} }
await TrackPlayer.add(tracks) await TrackPlayer.add(tracks)
set({ shuffleOrder }) set(state => {
state.shuffleOrder = shuffleOrder
})
} else { } else {
const tracks = unshuffleTracks(queue, queueShuffleOrder) const tracks = unshuffleTracks(queue, queueShuffleOrder)
@@ -155,11 +116,18 @@ export const createTrackPlayerSlice = (set: SetState<Store>, get: GetState<Store
await TrackPlayer.add(tracks) await TrackPlayer.add(tracks)
} }
set({ shuffleOrder: undefined }) set(state => {
state.shuffleOrder = undefined
})
} }
set({ queue: await getQueue() }) const newQueue = await getQueue()
get().setCurrentTrackIdx(await getCurrentTrack()) const newCurrentTrackIdx = await getCurrentTrack()
set(state => {
state.queue = newQueue
})
get().setCurrentTrackIdx(newCurrentTrackIdx)
}) })
}, },
@@ -182,12 +150,17 @@ export const createTrackPlayerSlice = (set: SetState<Store>, get: GetState<Store
} }
await TrackPlayer.setRepeatMode(nextMode) await TrackPlayer.setRepeatMode(nextMode)
set({ repeatMode: nextMode }) set(state => {
state.repeatMode = nextMode
})
}) })
}, },
playerState: State.None, playerState: State.None,
setPlayerState: playerState => set({ playerState }), setPlayerState: playerState =>
set(state => {
state.playerState = playerState
}),
currentTrack: undefined, currentTrack: undefined,
currentTrackIdx: undefined, currentTrackIdx: undefined,
@@ -201,47 +174,44 @@ export const createTrackPlayerSlice = (set: SetState<Store>, get: GetState<Store
}, },
duckPaused: false, duckPaused: false,
setDuckPaused: duckPaused => set({ duckPaused }), setDuckPaused: duckPaused =>
set(state => {
state.duckPaused = duckPaused
}),
queue: [], queue: [],
setQueue: async (songs, name, contextType, contextId, playTrack, shuffle) => { setQueue: async ({ queue, title, type, contextId, playTrack, shuffle }) => {
return trackPlayerCommands.enqueue(async () => { return trackPlayerCommands.enqueue(async () => {
const shuffled = shuffle !== undefined ? shuffle : !!get().shuffleOrder const shuffled = shuffle !== undefined ? shuffle : !!get().shuffleOrder
await TrackPlayer.setupPlayer(get().getPlayerOptions()) await TrackPlayer.setupPlayer(get().getPlayerOptions())
await TrackPlayer.reset() await TrackPlayer.reset()
if (songs.length === 0) { if (queue.length === 0) {
return
}
let queue = await get().mapSongstoTrackExts(songs)
try {
for (const t of queue) {
t.url = get().buildStreamUri(t.id)
}
} catch {
return return
} }
if (shuffled) { if (shuffled) {
const { tracks, shuffleOrder } = shuffleTracks(queue, playTrack) const { tracks, shuffleOrder } = shuffleTracks(queue, playTrack)
set({ shuffleOrder }) set(state => {
state.shuffleOrder = shuffleOrder
})
queue = tracks queue = tracks
playTrack = 0 playTrack = 0
} else { } else {
set({ shuffleOrder: undefined }) set(state => {
state.shuffleOrder = undefined
})
} }
playTrack = playTrack || 0 playTrack = playTrack || 0
try { try {
set({ set(state => {
queue, state.queue = queue
queueName: name, state.queueName = title
queueContextType: contextType, state.queueContextType = type
queueContextId: contextId, state.queueContextId = contextId
}) })
get().setCurrentTrackIdx(playTrack) get().setCurrentTrackIdx(playTrack)
@@ -264,7 +234,10 @@ export const createTrackPlayerSlice = (set: SetState<Store>, get: GetState<Store
}, },
progress: { position: 0, duration: 0, buffered: 0 }, progress: { position: 0, duration: 0, buffered: 0 },
setProgress: progress => set({ progress }), setProgress: progress =>
set(state => {
state.progress = progress
}),
scrobbleTrack: async id => { scrobbleTrack: async id => {
const client = get().client const client = get().client
@@ -286,7 +259,9 @@ export const createTrackPlayerSlice = (set: SetState<Store>, get: GetState<Store
if (netState === get().netState) { if (netState === get().netState) {
return return
} }
set({ netState }) set(state => {
state.netState = netState
})
get().rebuildQueue() get().rebuildQueue()
}, },
@@ -298,8 +273,9 @@ export const createTrackPlayerSlice = (set: SetState<Store>, get: GetState<Store
} }
const currentTrack = await getCurrentTrack() const currentTrack = await getCurrentTrack()
const state = await getPlayerState() const playerState = await getPlayerState()
const position = (await TrackPlayer.getPosition()) || 0 const position = (await TrackPlayer.getPosition()) || 0
const repeatMode = await getRepeatMode()
const queueName = get().queueName const queueName = get().queueName
const queueContextId = get().queueContextId const queueContextId = get().queueContextId
@@ -316,11 +292,11 @@ export const createTrackPlayerSlice = (set: SetState<Store>, get: GetState<Store
return return
} }
set({ set(state => {
queue, state.queue = queue
queueName, state.queueName = queueName
queueContextId, state.queueContextType = queueContextType
queueContextType, state.queueContextId = queueContextId
}) })
get().setCurrentTrackIdx(currentTrack) get().setCurrentTrackIdx(currentTrack)
@@ -330,14 +306,26 @@ export const createTrackPlayerSlice = (set: SetState<Store>, get: GetState<Store
await TrackPlayer.skip(currentTrack) await TrackPlayer.skip(currentTrack)
} }
await TrackPlayer.setRepeatMode(repeatMode)
await TrackPlayer.seekTo(position) await TrackPlayer.seekTo(position)
if (state === State.Playing || forcePlay) { if (playerState === State.Playing || forcePlay) {
await TrackPlayer.play() await TrackPlayer.play()
} }
}) })
}, },
updateQueue: async () => {
const newQueue = await getQueue()
const currentTrack = await getCurrentTrack()
set(state => {
state.queue = newQueue
if (currentTrack !== undefined) {
state.currentTrack = newQueue[currentTrack]
}
})
},
buildStreamUri: id => { buildStreamUri: id => {
const client = get().client const client = get().client
if (!client) { if (!client) {
@@ -346,23 +334,23 @@ export const createTrackPlayerSlice = (set: SetState<Store>, get: GetState<Store
return client.streamUri({ return client.streamUri({
id, id,
estimateContentLength: get().settings.estimateContentLength, estimateContentLength: true,
maxBitRate: get().netState === 'mobile' ? get().settings.maxBitrateMobile : get().settings.maxBitrateWifi, maxBitRate: get().netState === 'mobile' ? get().settings.maxBitrateMobile : get().settings.maxBitrateWifi,
}) })
}, },
resetTrackPlayerState: () => { resetTrackPlayerState: () => {
set({ set(state => {
queueName: undefined, state.queueName = undefined
queueContextType: undefined, state.queueContextType = undefined
queueContextId: undefined, state.queueContextId = undefined
shuffleOrder: undefined, state.shuffleOrder = undefined
repeatMode: RepeatMode.Off, state.repeatMode = RepeatMode.Off
playerState: State.None, state.playerState = State.None
currentTrack: undefined, state.currentTrack = undefined
currentTrackIdx: undefined, state.currentTrackIdx = undefined
queue: [], state.queue = []
progress: { position: 0, duration: 0, buffered: 0 }, state.progress = { position: 0, duration: 0, buffered: 0 }
}) })
}, },

View File

@@ -1,64 +0,0 @@
import { Song } from '@app/models/music'
import userAgent from '@app/util/userAgent'
import { GetState, SetState } from 'zustand'
import { Store } from './store'
import { TrackExt } from './trackplayer'
export type TrackPlayerMapSlice = {
mapSongtoTrackExt: (song: Song) => Promise<TrackExt>
mapSongstoTrackExts: (songs: Song[]) => Promise<TrackExt[]>
mapTrackExtToSong: (song: TrackExt) => Song
}
export const selectTrackPlayerMap = {
mapTrackExtToSong: (store: TrackPlayerMapSlice) => store.mapTrackExtToSong,
}
export const createTrackPlayerMapSlice = (set: SetState<Store>, get: GetState<Store>): TrackPlayerMapSlice => ({
mapSongtoTrackExt: async song => {
let artwork = require('@res/fallback.png')
if (song.coverArt) {
const filePath = await get().fetchCoverArtFilePath(song.coverArt)
if (filePath) {
artwork = filePath
}
}
return {
id: song.id,
title: song.title,
artist: song.artist || 'Unknown Artist',
album: song.album || 'Unknown Album',
url: song.streamUri,
userAgent,
artwork,
coverArt: song.coverArt,
duration: song.duration,
artistId: song.artistId,
albumId: song.albumId,
track: song.track,
discNumber: song.discNumber,
}
},
mapSongstoTrackExts: async songs => {
return await Promise.all(songs.map(get().mapSongtoTrackExt))
},
mapTrackExtToSong: track => {
return {
itemType: 'song',
id: track.id,
title: track.title as string,
artist: track.artist,
album: track.album,
streamUri: track.url as string,
coverArt: track.coverArt,
duration: track.duration,
artistId: track.artistId,
albumId: track.albumId,
track: track.track,
discNumber: track.discNumber,
}
},
})

View File

@@ -1,14 +1,10 @@
import { StatusBar } from 'react-native'
const header = 56 const header = 56
const tabBar = 54 const tabBar = 54
const top = () => header + (StatusBar.currentHeight || 0)
const bottom = () => tabBar const bottom = () => tabBar
export default { export default {
header, header,
tabBar, tabBar,
top,
bottom, bottom,
} }

Some files were not shown because too many files have changed in this diff Show More