Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d9a2571d63 | ||
|
|
2a7e1722dc | ||
|
|
7674bcd99f | ||
|
|
82a31acd8c | ||
|
|
9ff5c92650 | ||
|
|
f83f020d71 | ||
|
|
30daf267a0 | ||
|
|
5597c4c235 | ||
|
|
d65db50bd6 | ||
|
|
ed39d0c2a8 | ||
|
|
33ab0c8a66 | ||
|
|
ecdd9abc7f | ||
|
|
6e6b260020 | ||
|
|
461a3cf4d4 | ||
|
|
35702ba820 | ||
|
|
2127c48cc9 | ||
|
|
1253b266ea | ||
|
|
aa06b6896e | ||
|
|
39e61d33a6 | ||
|
|
9f1b045ead | ||
|
|
4848e6bed6 | ||
|
|
07e12eec6a | ||
|
|
b3a65d1612 | ||
|
|
05c90c03df | ||
|
|
250e721fea |
No files matched your search
@@ -0,0 +1,61 @@
|
|||||||
|
# Unit tests, Android Lint and debug builds of both apps on every push to main and every PR.
|
||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
check:
|
||||||
|
runs-on: mac-mini
|
||||||
|
# Ubuntu with Node, git and curl, which the setup actions need.
|
||||||
|
container:
|
||||||
|
image: gitea/runner-images:ubuntu-24.04
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: 21
|
||||||
|
|
||||||
|
# Accepts the SDK licenses, so AGP can fetch the build tools it wants on its own.
|
||||||
|
- uses: android-actions/setup-android@v3
|
||||||
|
with:
|
||||||
|
packages: platform-tools platforms;android-37.0
|
||||||
|
|
||||||
|
# The mac-mini runner's containers are arm64, while AGP's aapt2 is built for x86-64 only.
|
||||||
|
# OrbStack runs it through Rosetta, once the x86-64 glibc it links against is installed.
|
||||||
|
- name: Install the x86-64 glibc
|
||||||
|
run: |
|
||||||
|
if [ "$(uname -m)" != aarch64 ]; then exit 0; fi
|
||||||
|
# Ubuntu serves amd64 packages from a different archive than arm64 ones.
|
||||||
|
sed -i '/^URIs:/a Architectures: arm64' /etc/apt/sources.list.d/ubuntu.sources
|
||||||
|
cat > /etc/apt/sources.list.d/amd64.sources <<EOF
|
||||||
|
Types: deb
|
||||||
|
URIs: http://archive.ubuntu.com/ubuntu/
|
||||||
|
Suites: noble noble-updates noble-security
|
||||||
|
Components: main
|
||||||
|
Architectures: amd64
|
||||||
|
Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg
|
||||||
|
EOF
|
||||||
|
dpkg --add-architecture amd64
|
||||||
|
# apt only warns when a lookup fails, and the runner's DNS sometimes does.
|
||||||
|
for attempt in 1 2 3 4 5; do
|
||||||
|
apt-get update -qq && apt-cache show libc6:amd64 > /dev/null 2>&1 && break
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
apt-get install -y -qq --no-install-recommends libc6:amd64
|
||||||
|
|
||||||
|
- run: ./gradlew testDebugUnitTest lint assembleDebug
|
||||||
|
|
||||||
|
# Gitea's artifact backend speaks the v3 protocol only.
|
||||||
|
- if: failure()
|
||||||
|
uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
name: reports
|
||||||
|
path: |
|
||||||
|
*/build/reports/
|
||||||
|
*/build/test-results/
|
||||||
|
if-no-files-found: ignore
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
# Pushing a tag v<phone>-tv<tv> builds both apps signed with the release key and publishes them
|
||||||
|
# on the tag's release, creating it if it doesn't exist yet. Run by hand, it's a dry run: it
|
||||||
|
# builds and checks the signatures, then keeps the APKs as run artifacts instead of publishing.
|
||||||
|
name: Release
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags: ['v*']
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
env:
|
||||||
|
# The start of the release key's SHA-256 certificate digest, as apksigner prints it.
|
||||||
|
RELEASE_CERT: df4c799f
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
release:
|
||||||
|
runs-on: mac-mini
|
||||||
|
container:
|
||||||
|
image: gitea/runner-images:ubuntu-24.04
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
# The whole history and tags, for the changes since the last release.
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: 21
|
||||||
|
|
||||||
|
- uses: android-actions/setup-android@v3
|
||||||
|
with:
|
||||||
|
packages: platform-tools platforms;android-37.0
|
||||||
|
|
||||||
|
# aapt2 is x86-64 only, see ci.yml.
|
||||||
|
- name: Install the x86-64 glibc
|
||||||
|
run: |
|
||||||
|
if [ "$(uname -m)" != aarch64 ]; then exit 0; fi
|
||||||
|
sed -i '/^URIs:/a Architectures: arm64' /etc/apt/sources.list.d/ubuntu.sources
|
||||||
|
cat > /etc/apt/sources.list.d/amd64.sources <<EOF
|
||||||
|
Types: deb
|
||||||
|
URIs: http://archive.ubuntu.com/ubuntu/
|
||||||
|
Suites: noble noble-updates noble-security
|
||||||
|
Components: main
|
||||||
|
Architectures: amd64
|
||||||
|
Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg
|
||||||
|
EOF
|
||||||
|
dpkg --add-architecture amd64
|
||||||
|
for attempt in 1 2 3 4 5; do
|
||||||
|
apt-get update -qq && apt-cache show libc6:amd64 > /dev/null 2>&1 && break
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
apt-get install -y -qq --no-install-recommends libc6:amd64
|
||||||
|
|
||||||
|
- name: Read versions
|
||||||
|
id: versions
|
||||||
|
run: |
|
||||||
|
name() { sed -nE 's/^[[:space:]]*versionName = "(.*)"/\1/p' "$1/build.gradle.kts"; }
|
||||||
|
code() { sed -nE 's/^[[:space:]]*versionCode = ([0-9]+)/\1/p' "$1/build.gradle.kts"; }
|
||||||
|
{
|
||||||
|
echo "tv_name=$(name tv)"
|
||||||
|
echo "tv_code=$(code tv)"
|
||||||
|
echo "phone_name=$(name mobile)"
|
||||||
|
echo "phone_code=$(code mobile)"
|
||||||
|
echo "tag=v$(name mobile)-tv$(name tv)"
|
||||||
|
} >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
- name: Check the tag matches the versions
|
||||||
|
if: gitea.event_name == 'push'
|
||||||
|
env:
|
||||||
|
TAG: ${{ gitea.ref_name }}
|
||||||
|
EXPECTED: ${{ steps.versions.outputs.tag }}
|
||||||
|
run: |
|
||||||
|
if [ "$TAG" != "$EXPECTED" ]; then
|
||||||
|
echo "::error::Tag $TAG doesn't match the app versions, which want $EXPECTED"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Write keystore.properties
|
||||||
|
env:
|
||||||
|
KEYSTORE_BASE64: ${{ secrets.RELEASE_KEYSTORE_BASE64 }}
|
||||||
|
STORE_PASSWORD: ${{ secrets.RELEASE_STORE_PASSWORD }}
|
||||||
|
KEY_ALIAS: ${{ secrets.RELEASE_KEY_ALIAS }}
|
||||||
|
KEY_PASSWORD: ${{ secrets.RELEASE_KEY_PASSWORD }}
|
||||||
|
run: |
|
||||||
|
# Without these the build would quietly sign with a debug key.
|
||||||
|
for secret in KEYSTORE_BASE64 STORE_PASSWORD KEY_ALIAS KEY_PASSWORD; do
|
||||||
|
if [ -z "${!secret}" ]; then
|
||||||
|
echo "::error::The RELEASE_$secret secret isn't set"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
umask 077
|
||||||
|
echo "$KEYSTORE_BASE64" | base64 -d > "$RUNNER_TEMP/musyx.keystore"
|
||||||
|
# Properties files treat a backslash as an escape.
|
||||||
|
escape() { printf '%s' "${1//\\/\\\\}"; }
|
||||||
|
{
|
||||||
|
echo "storeFile=$(escape "$RUNNER_TEMP/musyx.keystore")"
|
||||||
|
echo "storePassword=$(escape "$STORE_PASSWORD")"
|
||||||
|
echo "keyAlias=$(escape "$KEY_ALIAS")"
|
||||||
|
echo "keyPassword=$(escape "$KEY_PASSWORD")"
|
||||||
|
} > keystore.properties
|
||||||
|
|
||||||
|
- run: ./gradlew :tv:assembleRelease :mobile:assembleRelease
|
||||||
|
|
||||||
|
- name: Check the signatures
|
||||||
|
run: |
|
||||||
|
apksigner="$(ls -d "$ANDROID_HOME"/build-tools/* | sort -V | tail -1)/apksigner"
|
||||||
|
for apk in tv/build/outputs/apk/release/tv-release.apk mobile/build/outputs/apk/release/mobile-release.apk; do
|
||||||
|
if ! "$apksigner" verify --print-certs "$apk" | grep -q "SHA-256 digest: $RELEASE_CERT"; then
|
||||||
|
echo "::error::$apk isn't signed with the release key"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
- name: Keep the APKs
|
||||||
|
if: gitea.event_name == 'workflow_dispatch'
|
||||||
|
uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
name: apks
|
||||||
|
path: |
|
||||||
|
tv/build/outputs/apk/release/tv-release.apk
|
||||||
|
mobile/build/outputs/apk/release/mobile-release.apk
|
||||||
|
|
||||||
|
- name: Publish the release
|
||||||
|
if: gitea.event_name == 'push'
|
||||||
|
env:
|
||||||
|
TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||||
|
API: ${{ gitea.server_url }}/api/v1/repos/${{ gitea.repository }}
|
||||||
|
TAG: ${{ gitea.ref_name }}
|
||||||
|
TV_NAME: ${{ steps.versions.outputs.tv_name }}
|
||||||
|
TV_CODE: ${{ steps.versions.outputs.tv_code }}
|
||||||
|
PHONE_NAME: ${{ steps.versions.outputs.phone_name }}
|
||||||
|
PHONE_CODE: ${{ steps.versions.outputs.phone_code }}
|
||||||
|
run: |
|
||||||
|
api() { curl -sSf -H "Authorization: token $TOKEN" "$@"; }
|
||||||
|
json() { python3 -c "import json, sys; d = json.load(sys.stdin); $1"; }
|
||||||
|
|
||||||
|
# A release made by hand for the tag keeps its notes; otherwise write them.
|
||||||
|
if release=$(api "$API/releases/tags/$TAG" 2>/dev/null); then
|
||||||
|
id=$(echo "$release" | json 'print(d["id"])')
|
||||||
|
else
|
||||||
|
previous=$(git describe --tags --abbrev=0 --match 'v*' "$TAG^" 2>/dev/null || true)
|
||||||
|
changes=$(git log --no-merges --format='- %s' "${previous:+$previous..}$TAG" | grep -v '^- Bump ' || true)
|
||||||
|
cat > "$RUNNER_TEMP/notes.md" <<EOF
|
||||||
|
Android TV app **$TV_NAME** (build $TV_CODE) and phone app **$PHONE_NAME** (build $PHONE_CODE).
|
||||||
|
|
||||||
|
- \`tv-release.apk\` — Android TV
|
||||||
|
- \`mobile-release.apk\` — phone, with Android Auto
|
||||||
|
|
||||||
|
### Recent changes
|
||||||
|
$changes
|
||||||
|
EOF
|
||||||
|
id=$(python3 -c 'import json, os, sys; e = os.environ; print(json.dumps({
|
||||||
|
"tag_name": e["TAG"],
|
||||||
|
"name": "TV " + e["TV_NAME"] + " · Phone " + e["PHONE_NAME"],
|
||||||
|
"body": open(sys.argv[1]).read(),
|
||||||
|
}))' "$RUNNER_TEMP/notes.md" \
|
||||||
|
| api -X POST -H 'Content-Type: application/json' --data @- "$API/releases" \
|
||||||
|
| json 'print(d["id"])')
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Replace any earlier upload of the same APKs.
|
||||||
|
api "$API/releases/$id/assets" \
|
||||||
|
| json 'print("\n".join(str(a["id"]) for a in d if a["name"] in ("tv-release.apk", "mobile-release.apk")))' \
|
||||||
|
| while read -r asset; do
|
||||||
|
if [ -n "$asset" ]; then api -X DELETE "$API/releases/$id/assets/$asset"; fi
|
||||||
|
done
|
||||||
|
for apk in tv/build/outputs/apk/release/tv-release.apk mobile/build/outputs/apk/release/mobile-release.apk; do
|
||||||
|
api -X POST -F "attachment=@$apk" "$API/releases/$id/assets?name=$(basename "$apk")" > /dev/null
|
||||||
|
done
|
||||||
|
echo "Published $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/releases/tag/$TAG"
|
||||||
|
|
||||||
|
- name: Remove the key
|
||||||
|
if: always()
|
||||||
|
run: rm -f keystore.properties "$RUNNER_TEMP/musyx.keystore"
|
||||||
@@ -82,6 +82,31 @@ changing the sources:
|
|||||||
- `python3 tool/make_icon.py assets/icon/musyx.png` redraws the icon itself.
|
- `python3 tool/make_icon.py assets/icon/musyx.png` redraws the icon itself.
|
||||||
- The fonts are copied by hand from `assets/fonts` to `res/font` (lower-case names).
|
- The fonts are copied by hand from `assets/fonts` to `res/font` (lower-case names).
|
||||||
|
|
||||||
|
### CI and releases
|
||||||
|
|
||||||
|
Gitea Actions runs `.gitea/workflows/ci.yml` on every push to `main` and every pull request:
|
||||||
|
the unit tests, Lint and debug builds of both apps. A failed run keeps the reports as an
|
||||||
|
artifact.
|
||||||
|
|
||||||
|
To release, bump `versionName` and `versionCode` in `tv/build.gradle.kts` and/or
|
||||||
|
`mobile/build.gradle.kts`, commit, and push a tag named `v<phone>-tv<tv>`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git tag v0.1.3-tv0.1.8 && git push origin v0.1.3-tv0.1.8
|
||||||
|
```
|
||||||
|
|
||||||
|
`.gitea/workflows/release.yml` then checks that the tag matches the versions, builds both
|
||||||
|
apps signed with the release key, and attaches `tv-release.apk` and `mobile-release.apk` to
|
||||||
|
the tag's release. It creates the release if there isn't one yet, with the commit subjects
|
||||||
|
since the previous tag as its notes; a release written by hand beforehand keeps its notes.
|
||||||
|
Running the workflow by hand from the Actions tab is a dry run that keeps the signed APKs as
|
||||||
|
an artifact instead of publishing.
|
||||||
|
|
||||||
|
The key comes from four repository secrets (Settings, Actions, Secrets):
|
||||||
|
`RELEASE_KEYSTORE_BASE64` (the keystore, from `base64 -i musyx-key.keystore`),
|
||||||
|
`RELEASE_STORE_PASSWORD`, `RELEASE_KEY_ALIAS` and `RELEASE_KEY_PASSWORD`, the same values
|
||||||
|
`keystore.properties` holds locally.
|
||||||
|
|
||||||
## Layout
|
## Layout
|
||||||
|
|
||||||
- `core/`: what the apps share (`it.panov.musyx`), under `core/src/main/java/it/panov/musyx`:
|
- `core/`: what the apps share (`it.panov.musyx`), under `core/src/main/java/it/panov/musyx`:
|
||||||
|
|||||||
@@ -239,15 +239,15 @@ class YmClient private constructor(
|
|||||||
return WaveSettings.from(first["settings2"] ?: first["settings"])
|
return WaveSettings.from(first["settings2"] ?: first["settings"])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** `settings3` takes JSON only: a form body gets `415 unsupported-media-type`. */
|
||||||
suspend fun setWaveSettings(station: String, settings: WaveSettings) {
|
suspend fun setWaveSettings(station: String, settings: WaveSettings) {
|
||||||
val result = http.postForm(
|
val body = buildJsonObject {
|
||||||
"/rotor/station/$station/settings3",
|
put("moodEnergy", settings.mood.api ?: "all")
|
||||||
Params()
|
put("diversity", settings.character.api ?: "default")
|
||||||
.add("moodEnergy", settings.mood.api ?: "all")
|
put("language", settings.language.api ?: "any")
|
||||||
.add("diversity", settings.character.api ?: "default")
|
put("type", "rotor")
|
||||||
.add("type", "rotor")
|
}
|
||||||
.add("language", settings.language.api ?: "any"),
|
val result = http.postJson("/rotor/station/$station/settings3", body)
|
||||||
)
|
|
||||||
requireAck(result, "station settings")
|
requireAck(result, "station settings")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -86,7 +86,7 @@ class Downloads(
|
|||||||
private val coverSizes: List<Int> = emptyList(),
|
private val coverSizes: List<Int> = emptyList(),
|
||||||
) {
|
) {
|
||||||
private val dir = File(context.filesDir, "offline")
|
private val dir = File(context.filesDir, "offline")
|
||||||
private val coverDir = File(dir, "covers")
|
private val coverDir = coverDir(context)
|
||||||
private val indexFile = File(dir, "index.json")
|
private val indexFile = File(dir, "index.json")
|
||||||
|
|
||||||
/** Writes the index one at a time, in the order asked. */
|
/** Writes the index one at a time, in the order asked. */
|
||||||
@@ -502,6 +502,11 @@ class Downloads(
|
|||||||
|
|
||||||
internal fun coverName(url: String): String = sha1(url).take(24) + ".img"
|
internal fun coverName(url: String): String = sha1(url).take(24) + ".img"
|
||||||
|
|
||||||
|
private fun coverDir(context: Context) = File(context.filesDir, "offline/covers")
|
||||||
|
|
||||||
|
/** The kept copy of a cover, found without reading the downloads, e.g. for the car. */
|
||||||
|
fun coverFile(context: Context, url: String): File? = File(coverDir(context), coverName(url)).takeIf { it.isFile }
|
||||||
|
|
||||||
private fun sha1(s: String): String =
|
private fun sha1(s: String): String =
|
||||||
MessageDigest.getInstance("SHA-1").digest(s.toByteArray()).joinToString("") { "%02x".format(it) }
|
MessageDigest.getInstance("SHA-1").digest(s.toByteArray()).joinToString("") { "%02x".format(it) }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -54,6 +54,11 @@ class PlaybackController(
|
|||||||
/** A downloaded track's file as a stream, or null. */
|
/** A downloaded track's file as a stream, or null. */
|
||||||
private val local: (trackId: String) -> Stream?,
|
private val local: (trackId: String) -> Stream?,
|
||||||
buffering: Buffering,
|
buffering: Buffering,
|
||||||
|
/**
|
||||||
|
* A track couldn't be fetched or played, or a station's next tracks couldn't be fetched;
|
||||||
|
* heard before the player moves on.
|
||||||
|
*/
|
||||||
|
private val onTrackFailed: () -> Unit = {},
|
||||||
) : EngineEvents {
|
) : EngineEvents {
|
||||||
private val core = PlayerCore()
|
private val core = PlayerCore()
|
||||||
private val engine = ExoEngine(context, token, this, buffering)
|
private val engine = ExoEngine(context, token, this, buffering)
|
||||||
@@ -140,7 +145,10 @@ class PlaybackController(
|
|||||||
|
|
||||||
override fun ended(generation: Long) = update { core.onEnded(generation) }
|
override fun ended(generation: Long) = update { core.onEnded(generation) }
|
||||||
|
|
||||||
override fun failed(generation: Long, reason: String) = update { core.onFailed(generation, reason) }
|
override fun failed(generation: Long, reason: String) {
|
||||||
|
if (generation == core.generation) onTrackFailed()
|
||||||
|
update { core.onFailed(generation, reason) }
|
||||||
|
}
|
||||||
|
|
||||||
override fun playingChanged(generation: Long, playing: Boolean) {
|
override fun playingChanged(generation: Long, playing: Boolean) {
|
||||||
core.onPlayingChanged(generation, playing)
|
core.onPlayingChanged(generation, playing)
|
||||||
@@ -157,20 +165,25 @@ class PlaybackController(
|
|||||||
// Downloaded tracks play without a session, so these go ahead offline too.
|
// Downloaded tracks play without a session, so these go ahead offline too.
|
||||||
is Effect.Fetch -> scope.launch {
|
is Effect.Fetch -> scope.launch {
|
||||||
val result = runCatching { resolve(api, effect.trackId) }
|
val result = runCatching { resolve(api, effect.trackId) }
|
||||||
|
// Heard first, so that if the connection is gone the next track is looked for offline.
|
||||||
|
result.exceptionOrNull()?.let { if (it !is NotDownloaded) onTrackFailed() }
|
||||||
update { core.fetched(effect.generation, result) }
|
update { core.fetched(effect.generation, result) }
|
||||||
}
|
}
|
||||||
is Effect.Prefetch -> scope.launch {
|
is Effect.Prefetch -> scope.launch {
|
||||||
val result = runCatching { resolve(api, effect.trackId) }
|
val result = runCatching { resolve(api, effect.trackId) }
|
||||||
core.prefetched(effect.trackId, result)
|
core.prefetched(effect.trackId, result)
|
||||||
}
|
}
|
||||||
is Effect.WaveFetch -> api?.let { c ->
|
is Effect.WaveFetch -> {
|
||||||
// My Wave's settings ride along as seeds when a session starts.
|
// My Wave's settings ride along as seeds when a session starts.
|
||||||
val settings = if (effect.station == MY_WAVE) waveSettings() else null
|
val settings = if (effect.station == MY_WAVE) waveSettings() else null
|
||||||
scope.launch {
|
scope.launch {
|
||||||
val result = runCatching {
|
val result = runCatching {
|
||||||
|
// Offline a station has nothing to play: failing says so rather than waiting.
|
||||||
|
val c = api ?: throw YmError.Network("offline")
|
||||||
val session = effect.sessionId
|
val session = effect.sessionId
|
||||||
if (session != null) c.waveMore(session, effect.queue) else c.waveStart(effect.station, settings)
|
if (session != null) c.waveMore(session, effect.queue) else c.waveStart(effect.station, settings)
|
||||||
}
|
}
|
||||||
|
if (api != null && result.isFailure) onTrackFailed()
|
||||||
update { core.waveBatch(effect.station, effect.epoch, result) }
|
update { core.waveBatch(effect.station, effect.epoch, result) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -191,7 +204,7 @@ class PlaybackController(
|
|||||||
|
|
||||||
/** A downloaded file when there is one, else a link from Yandex. */
|
/** A downloaded file when there is one, else a link from Yandex. */
|
||||||
private suspend fun resolve(c: YmClient?, trackId: String): Stream =
|
private suspend fun resolve(c: YmClient?, trackId: String): Stream =
|
||||||
local(trackId) ?: resolveStream(c ?: throw YmError.Network("offline"), trackId, quality())
|
local(trackId) ?: resolveStream(c ?: throw NotDownloaded(trackId), trackId, quality())
|
||||||
|
|
||||||
private companion object {
|
private companion object {
|
||||||
const val TAG = "Musyx"
|
const val TAG = "Musyx"
|
||||||
|
|||||||
@@ -36,8 +36,13 @@ sealed interface Notice {
|
|||||||
data object StationDry : Notice
|
data object StationDry : Notice
|
||||||
data object TooManyFailures : Notice
|
data object TooManyFailures : Notice
|
||||||
data class Skipped(val title: String) : Notice
|
data class Skipped(val title: String) : Notice
|
||||||
|
/** Offline, and nothing in the queue is downloaded. */
|
||||||
|
data object NothingDownloaded : Notice
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A track that isn't on the device, wanted with no connection to fetch it. */
|
||||||
|
class NotDownloaded(trackId: String) : Exception("not downloaded: $trackId")
|
||||||
|
|
||||||
/** Work the app has to do on the player's behalf. */
|
/** Work the app has to do on the player's behalf. */
|
||||||
sealed interface Effect {
|
sealed interface Effect {
|
||||||
data class Fetch(val generation: Long, val trackId: String) : Effect
|
data class Fetch(val generation: Long, val trackId: String) : Effect
|
||||||
@@ -99,6 +104,8 @@ class PlayerCore(private val random: Random = Random.Default) {
|
|||||||
private var prefetched: Pair<String, Stream>? = null
|
private var prefetched: Pair<String, Stream>? = null
|
||||||
internal var skips: Int = 0
|
internal var skips: Int = 0
|
||||||
private set
|
private set
|
||||||
|
/** Tracks passed over offline since one last played; the whole queue is the limit. */
|
||||||
|
private var missing = 0
|
||||||
var notice: Notice? = null
|
var notice: Notice? = null
|
||||||
private set
|
private set
|
||||||
private var wave: Wave? = null
|
private var wave: Wave? = null
|
||||||
@@ -127,6 +134,7 @@ class PlayerCore(private val random: Random = Random.Default) {
|
|||||||
currentTrackId = null
|
currentTrackId = null
|
||||||
prefetched = null
|
prefetched = null
|
||||||
skips = 0
|
skips = 0
|
||||||
|
missing = 0
|
||||||
notice = null
|
notice = null
|
||||||
wave = null
|
wave = null
|
||||||
started = null
|
started = null
|
||||||
@@ -141,6 +149,7 @@ class PlayerCore(private val random: Random = Random.Default) {
|
|||||||
wave = null
|
wave = null
|
||||||
queue = Queue.of(tracks, first, this.shuffle, random)
|
queue = Queue.of(tracks, first, this.shuffle, random)
|
||||||
skips = 0
|
skips = 0
|
||||||
|
missing = 0
|
||||||
notice = null
|
notice = null
|
||||||
effects += loadCurrent()
|
effects += loadCurrent()
|
||||||
return effects
|
return effects
|
||||||
@@ -166,6 +175,7 @@ class PlayerCore(private val random: Random = Random.Default) {
|
|||||||
stream = null
|
stream = null
|
||||||
currentTrackId = null
|
currentTrackId = null
|
||||||
skips = 0
|
skips = 0
|
||||||
|
missing = 0
|
||||||
notice = null
|
notice = null
|
||||||
status = Status.Loading
|
status = Status.Loading
|
||||||
engine?.stop()
|
engine?.stop()
|
||||||
@@ -274,6 +284,8 @@ class PlayerCore(private val random: Random = Random.Default) {
|
|||||||
onSuccess = { loadStream(it, play = !holdPaused) },
|
onSuccess = { loadStream(it, play = !holdPaused) },
|
||||||
onFailure = { e ->
|
onFailure = { e ->
|
||||||
if (e is YmError.Unauthorized) return listOf(Effect.SignedOut)
|
if (e is YmError.Unauthorized) return listOf(Effect.SignedOut)
|
||||||
|
// Offline, the queue is searched for what's downloaded; that's no failure.
|
||||||
|
if (e is NotDownloaded) return skipMissing()
|
||||||
android.util.Log.w("Musyx", "fetch: $e")
|
android.util.Log.w("Musyx", "fetch: $e")
|
||||||
return skipUnplayable()
|
return skipUnplayable()
|
||||||
},
|
},
|
||||||
@@ -296,6 +308,7 @@ class PlayerCore(private val random: Random = Random.Default) {
|
|||||||
if (durationMs != null && durationMs > 0) this.durationMs = durationMs
|
if (durationMs != null && durationMs > 0) this.durationMs = durationMs
|
||||||
status = if (holdPaused) Status.Paused else Status.Playing
|
status = if (holdPaused) Status.Paused else Status.Playing
|
||||||
skips = 0
|
skips = 0
|
||||||
|
missing = 0
|
||||||
val effects = mutableListOf<Effect>()
|
val effects = mutableListOf<Effect>()
|
||||||
val t = track
|
val t = track
|
||||||
if (t != null) {
|
if (t != null) {
|
||||||
@@ -480,4 +493,18 @@ class PlayerCore(private val random: Random = Random.Default) {
|
|||||||
notice = Notice.Skipped(title)
|
notice = Notice.Skipped(title)
|
||||||
return step(user = true, finished = false)
|
return step(user = true, finished = false)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Offline: moves past a track that isn't downloaded, until the whole queue has been tried. */
|
||||||
|
private fun skipMissing(): List<Effect> {
|
||||||
|
missing += 1
|
||||||
|
stream = null
|
||||||
|
currentTrackId = null
|
||||||
|
if (missing >= (queue?.size ?: 0)) {
|
||||||
|
engine?.pause()
|
||||||
|
status = Status.Paused
|
||||||
|
notice = Notice.NothingDownloaded
|
||||||
|
return emptyList()
|
||||||
|
}
|
||||||
|
return step(user = true, finished = false)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -90,7 +90,10 @@ class AppState(
|
|||||||
buffering: Buffering = Buffering.Default,
|
buffering: Buffering = Buffering.Default,
|
||||||
/** Cover sizes the interface shows, kept with downloads so they appear offline. */
|
/** Cover sizes the interface shows, kept with downloads so they appear offline. */
|
||||||
coverSizes: List<Int> = emptyList(),
|
coverSizes: List<Int> = emptyList(),
|
||||||
/** Whether the device has any connection; without one, sign-in isn't attempted. */
|
/**
|
||||||
|
* Whether the device has any connection; without one, sign-in isn't attempted, and a track
|
||||||
|
* that fails to play switches the app to its downloads.
|
||||||
|
*/
|
||||||
private val online: () -> Boolean = { true },
|
private val online: () -> Boolean = { true },
|
||||||
) {
|
) {
|
||||||
var session: Session by mutableStateOf(Session.Restoring)
|
var session: Session by mutableStateOf(Session.Restoring)
|
||||||
@@ -165,6 +168,7 @@ class AppState(
|
|||||||
onSignedOut = ::signOut,
|
onSignedOut = ::signOut,
|
||||||
local = downloads::stream,
|
local = downloads::stream,
|
||||||
buffering = buffering,
|
buffering = buffering,
|
||||||
|
onTrackFailed = ::trackFailed,
|
||||||
)
|
)
|
||||||
|
|
||||||
val client: YmClient? get() = (session as? Session.SignedIn)?.client
|
val client: YmClient? get() = (session as? Session.SignedIn)?.client
|
||||||
@@ -225,10 +229,36 @@ class AppState(
|
|||||||
|
|
||||||
private fun unreachable() {
|
private fun unreachable() {
|
||||||
// Downloads are what's left to play; the phone shows them.
|
// Downloads are what's left to play; the phone shows them.
|
||||||
nav.reset(Route.Downloads())
|
startOver(Route.Downloads())
|
||||||
session = Session.Unreachable
|
session = Session.Unreachable
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A track or a station's next tracks couldn't be fetched, or a track couldn't play. With the
|
||||||
|
* connection gone, carry on offline: the player looks for downloaded tracks in the queue, or,
|
||||||
|
* for a station, which has nothing more offline, plays all of them. The network callback
|
||||||
|
* reconnects later.
|
||||||
|
*/
|
||||||
|
private fun trackFailed() {
|
||||||
|
if (session !is Session.SignedIn || online()) return
|
||||||
|
Log.i(TAG, "connection lost: playing downloads")
|
||||||
|
unreachable()
|
||||||
|
val downloaded = downloads.doneTracks
|
||||||
|
if (playback.state.waveStation != null && downloaded.isNotEmpty()) {
|
||||||
|
toast(UiText.Res(R.string.toast_offline_station))
|
||||||
|
playTracks(downloaded, 0, shuffle = true)
|
||||||
|
} else {
|
||||||
|
toast(UiText.Res(R.string.toast_offline))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Navigation starts again at `start`; Now Playing stays open over it if it was. */
|
||||||
|
private fun startOver(start: Route) {
|
||||||
|
val playing = nav.current == Route.NowPlaying
|
||||||
|
nav.reset(start)
|
||||||
|
if (playing) nav.go(Route.NowPlaying)
|
||||||
|
}
|
||||||
|
|
||||||
/** Makes `creds` the session's, persisting each renewal while it still is. */
|
/** Makes `creds` the session's, persisting each renewal while it still is. */
|
||||||
private fun keep(creds: Credentials): Tokens {
|
private fun keep(creds: Credentials): Tokens {
|
||||||
lateinit var kept: Tokens
|
lateinit var kept: Tokens
|
||||||
@@ -277,7 +307,7 @@ class AppState(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun signedIn(client: YmClient, account: Account) {
|
private fun signedIn(client: YmClient, account: Account) {
|
||||||
nav.reset(Route.Home)
|
startOver(Route.Home)
|
||||||
session = Session.SignedIn(client, account)
|
session = Session.SignedIn(client, account)
|
||||||
downloads.attach(account.uid)
|
downloads.attach(account.uid)
|
||||||
// Liked tracks drive the hearts; playlists feed "Add to playlist"; Home is the first page.
|
// Liked tracks drive the hearts; playlists feed "Add to playlist"; Home is the first page.
|
||||||
|
|||||||
@@ -57,6 +57,8 @@
|
|||||||
<string name="toast_download_removed">«%1$s» удалено с устройства</string>
|
<string name="toast_download_removed">«%1$s» удалено с устройства</string>
|
||||||
<string name="toast_liked_download_removed">«Мне нравится» удалено с устройства</string>
|
<string name="toast_liked_download_removed">«Мне нравится» удалено с устройства</string>
|
||||||
<string name="toast_downloads_cleared">Все загрузки удалены</string>
|
<string name="toast_downloads_cleared">Все загрузки удалены</string>
|
||||||
|
<string name="toast_offline">Нет интернета, поэтому играют только загрузки</string>
|
||||||
|
<string name="toast_offline_station">Нет интернета, поэтому вместо станции играют ваши загрузки</string>
|
||||||
<plurals name="toast_playing_similar">
|
<plurals name="toast_playing_similar">
|
||||||
<item quantity="one">Играем %1$d трек в духе «%2$s»</item>
|
<item quantity="one">Играем %1$d трек в духе «%2$s»</item>
|
||||||
<item quantity="few">Играем %1$d трека в духе «%2$s»</item>
|
<item quantity="few">Играем %1$d трека в духе «%2$s»</item>
|
||||||
|
|||||||
@@ -57,6 +57,8 @@
|
|||||||
<string name="toast_download_removed">Removed “%1$s” from the device</string>
|
<string name="toast_download_removed">Removed “%1$s” from the device</string>
|
||||||
<string name="toast_liked_download_removed">Removed Liked tracks from the device</string>
|
<string name="toast_liked_download_removed">Removed Liked tracks from the device</string>
|
||||||
<string name="toast_downloads_cleared">All downloads removed</string>
|
<string name="toast_downloads_cleared">All downloads removed</string>
|
||||||
|
<string name="toast_offline">No connection, so only downloads play</string>
|
||||||
|
<string name="toast_offline_station">No connection, so your downloads play instead of the station</string>
|
||||||
<plurals name="toast_playing_similar">
|
<plurals name="toast_playing_similar">
|
||||||
<item quantity="one">Playing %1$d track like “%2$s”</item>
|
<item quantity="one">Playing %1$d track like “%2$s”</item>
|
||||||
<item quantity="other">Playing %1$d tracks like “%2$s”</item>
|
<item quantity="other">Playing %1$d tracks like “%2$s”</item>
|
||||||
|
|||||||
@@ -109,6 +109,35 @@ class PlayerCoreTest {
|
|||||||
assertEquals(Notice.TooManyFailures, p.notice)
|
assertEquals(Notice.TooManyFailures, p.notice)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun offlineSkipsToTheNextDownloadedTrack() {
|
||||||
|
val p = playing(6, 0)
|
||||||
|
p.next()
|
||||||
|
// Tracks 1 to 4 aren't on the phone: more in a row than the failures given up after.
|
||||||
|
for (id in 1..4) {
|
||||||
|
assertEquals("$id", p.track!!.id)
|
||||||
|
p.fetched(p.generation, Result.failure(NotDownloaded("$id")))
|
||||||
|
}
|
||||||
|
assertEquals("5", p.track!!.id)
|
||||||
|
assertEquals(Status.Loading, p.status)
|
||||||
|
assertEquals(0, p.skips)
|
||||||
|
assertNull(p.notice)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun offlineWithNothingDownloadedStopsAfterOneRound() {
|
||||||
|
val p = playing(3, 0)
|
||||||
|
p.cycleRepeat()
|
||||||
|
var effects = p.next()
|
||||||
|
repeat(3) {
|
||||||
|
val gen = effects.fetchGeneration() ?: return@repeat
|
||||||
|
effects = p.fetched(gen, Result.failure(NotDownloaded(p.track!!.id)))
|
||||||
|
}
|
||||||
|
assertTrue(effects.none { it is Effect.Fetch })
|
||||||
|
assertEquals(Status.Paused, p.status)
|
||||||
|
assertEquals(Notice.NothingDownloaded, p.notice)
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun expiredTokenSignsOut() {
|
fun expiredTokenSignsOut() {
|
||||||
val p = PlayerCore()
|
val p = PlayerCore()
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ android {
|
|||||||
applicationId = "it.panov.musyx"
|
applicationId = "it.panov.musyx"
|
||||||
minSdk = 23
|
minSdk = 23
|
||||||
targetSdk = 37
|
targetSdk = 37
|
||||||
versionCode = 3
|
versionCode = 7
|
||||||
versionName = "0.1.2"
|
versionName = "0.1.6"
|
||||||
}
|
}
|
||||||
|
|
||||||
// The same keystore.properties as the TV app; without one, release builds use the debug key.
|
// The same keystore.properties as the TV app; without one, release builds use the debug key.
|
||||||
|
|||||||
@@ -1,13 +1,16 @@
|
|||||||
// Covers for Android Auto. Auto loads browse artwork only from content:// URIs, so each https
|
// Covers for Android Auto. Auto loads browse artwork only from content:// URIs, so each https
|
||||||
// cover is fetched once into the cache and served from there.
|
// cover is fetched once into the cache and served from there, as are the app's own icons.
|
||||||
package it.panov.musyx.mobile
|
package it.panov.musyx.mobile
|
||||||
|
|
||||||
import android.content.ContentProvider
|
import android.content.ContentProvider
|
||||||
import android.content.ContentValues
|
import android.content.ContentValues
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.database.Cursor
|
import android.database.Cursor
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.Canvas
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.os.ParcelFileDescriptor
|
import android.os.ParcelFileDescriptor
|
||||||
|
import it.panov.musyx.data.Downloads
|
||||||
import okhttp3.OkHttpClient
|
import okhttp3.OkHttpClient
|
||||||
import okhttp3.Request
|
import okhttp3.Request
|
||||||
import java.io.File
|
import java.io.File
|
||||||
@@ -20,10 +23,15 @@ class ArtworkProvider : ContentProvider() {
|
|||||||
override fun onCreate(): Boolean = true
|
override fun onCreate(): Boolean = true
|
||||||
|
|
||||||
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor {
|
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor {
|
||||||
|
if (uri.lastPathSegment == SHUFFLE) return ParcelFileDescriptor.open(icon(R.drawable.ic_shuffle, "shuffle"), ParcelFileDescriptor.MODE_READ_ONLY)
|
||||||
val url = uri.lastPathSegment?.let(Uri::parse) ?: throw FileNotFoundException("$uri")
|
val url = uri.lastPathSegment?.let(Uri::parse) ?: throw FileNotFoundException("$uri")
|
||||||
// Exported for the car, so it fetches only Yandex covers, never an arbitrary URL.
|
// Exported for the car, so it fetches only Yandex covers, never an arbitrary URL.
|
||||||
val host = url.host.orEmpty()
|
val host = url.host.orEmpty()
|
||||||
if (url.scheme != "https" || !(host == "yandex.net" || host.endsWith(".yandex.net"))) throw FileNotFoundException("$uri")
|
if (url.scheme != "https" || !(host == "yandex.net" || host.endsWith(".yandex.net"))) throw FileNotFoundException("$uri")
|
||||||
|
// Covers kept with downloads show offline too.
|
||||||
|
Downloads.coverFile(requireNotNull(context), url.toString())?.let {
|
||||||
|
return ParcelFileDescriptor.open(it, ParcelFileDescriptor.MODE_READ_ONLY)
|
||||||
|
}
|
||||||
val file = File(requireNotNull(context).cacheDir, "artwork/${sha1(url.toString())}")
|
val file = File(requireNotNull(context).cacheDir, "artwork/${sha1(url.toString())}")
|
||||||
if (!file.exists()) fetch(url.toString(), file)
|
if (!file.exists()) fetch(url.toString(), file)
|
||||||
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
|
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
|
||||||
@@ -45,7 +53,23 @@ class ArtworkProvider : ContentProvider() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun getType(uri: Uri): String = "image/jpeg"
|
/** A white icon on clear ground, drawn once into the cache as a PNG; the car can't draw vectors. */
|
||||||
|
private fun icon(id: Int, name: String): File {
|
||||||
|
val file = File(requireNotNull(context).cacheDir, "artwork/icon-$name.png")
|
||||||
|
if (file.exists()) return file
|
||||||
|
val drawable = requireNotNull(requireNotNull(context).getDrawable(id))
|
||||||
|
val bitmap = Bitmap.createBitmap(ICON_PX, ICON_PX, Bitmap.Config.ARGB_8888)
|
||||||
|
val inset = ICON_PX / 5
|
||||||
|
drawable.setBounds(inset, inset, ICON_PX - inset, ICON_PX - inset)
|
||||||
|
drawable.draw(Canvas(bitmap))
|
||||||
|
file.parentFile?.mkdirs()
|
||||||
|
val part = File(file.path + ".part")
|
||||||
|
part.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
|
||||||
|
if (!part.renameTo(file)) throw FileNotFoundException(file.path)
|
||||||
|
return file
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getType(uri: Uri): String = if (uri.lastPathSegment == SHUFFLE) "image/png" else "image/jpeg"
|
||||||
|
|
||||||
override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? = null
|
override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? = null
|
||||||
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
|
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
|
||||||
@@ -53,6 +77,10 @@ class ArtworkProvider : ContentProvider() {
|
|||||||
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int = 0
|
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int = 0
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
/** The path of the Shuffle row's icon, in place of a cover's URL. */
|
||||||
|
const val SHUFFLE = "icon:shuffle"
|
||||||
|
private const val ICON_PX = 192
|
||||||
|
|
||||||
/** The content URI the car loads `url` from. */
|
/** The content URI the car loads `url` from. */
|
||||||
fun uri(context: Context, url: String): Uri =
|
fun uri(context: Context, url: String): Uri =
|
||||||
Uri.Builder().scheme("content").authority("${context.packageName}.artwork").appendPath(url).build()
|
Uri.Builder().scheme("content").authority("${context.packageName}.artwork").appendPath(url).build()
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
// The media library Android Auto browses: My Wave and stations, picks from Home, and the
|
// The media library Android Auto browses: My Wave and stations, picks from Home, the
|
||||||
// collection. Playing an item starts it through PlayerCore, like a tap in the app would.
|
// collection and downloads; offline, just the downloads. Playing an item starts it through
|
||||||
|
// PlayerCore, like a tap in the app would.
|
||||||
package it.panov.musyx.mobile
|
package it.panov.musyx.mobile
|
||||||
|
|
||||||
import android.app.PendingIntent
|
import android.app.PendingIntent
|
||||||
@@ -37,6 +38,8 @@ import it.panov.musyx.api.SearchKind
|
|||||||
import it.panov.musyx.api.Station
|
import it.panov.musyx.api.Station
|
||||||
import it.panov.musyx.api.Track
|
import it.panov.musyx.api.Track
|
||||||
import it.panov.musyx.api.YmClient
|
import it.panov.musyx.api.YmClient
|
||||||
|
import it.panov.musyx.data.OfflineSet
|
||||||
|
import it.panov.musyx.mobile.ui.components.COVER_LARGE
|
||||||
import it.panov.musyx.state.AppState
|
import it.panov.musyx.state.AppState
|
||||||
import it.panov.musyx.state.Liked
|
import it.panov.musyx.state.Liked
|
||||||
import it.panov.musyx.state.Session
|
import it.panov.musyx.state.Session
|
||||||
@@ -57,7 +60,7 @@ private const val RECENT_SHOWN = 30
|
|||||||
private const val RESTORE_MS = 20_000L
|
private const val RESTORE_MS = 20_000L
|
||||||
|
|
||||||
// Media ids. Folders are plain names or `kind:id`; a playable track is `t|<folder>|<index>`,
|
// Media ids. Folders are plain names or `kind:id`; a playable track is `t|<folder>|<index>`,
|
||||||
// so playing it can queue the rest of its folder.
|
// so playing it can queue the rest of its folder, and `s|<folder>` plays the folder shuffled.
|
||||||
private const val ROOT = "root"
|
private const val ROOT = "root"
|
||||||
private const val WAVE = "wave"
|
private const val WAVE = "wave"
|
||||||
private const val HOME = "home"
|
private const val HOME = "home"
|
||||||
@@ -69,11 +72,18 @@ private const val PLAYLISTS = "playlists"
|
|||||||
private const val ALBUMS = "albums"
|
private const val ALBUMS = "albums"
|
||||||
private const val STATION = "station|"
|
private const val STATION = "station|"
|
||||||
private const val TRACK = "t|"
|
private const val TRACK = "t|"
|
||||||
|
private const val SHUFFLE = "s|"
|
||||||
private const val SEARCH = "search:"
|
private const val SEARCH = "search:"
|
||||||
|
private const val DOWNLOADS = "downloads"
|
||||||
|
/** Every downloaded track. */
|
||||||
|
private const val OFFLINE_ALL = "offline"
|
||||||
|
/** A downloaded album, playlist or Liked tracks, by its [it.panov.musyx.data.OfflineSet] key. */
|
||||||
|
private const val OFFLINE = "offline:"
|
||||||
|
|
||||||
// The buttons beside the car's transport: the heart, and "don't recommend".
|
// The buttons beside the car's transport: the heart, "don't recommend", and shuffle.
|
||||||
private val LIKE = SessionCommand("it.panov.musyx.LIKE", Bundle.EMPTY)
|
private val LIKE = SessionCommand("it.panov.musyx.LIKE", Bundle.EMPTY)
|
||||||
private val DISLIKE = SessionCommand("it.panov.musyx.DISLIKE", Bundle.EMPTY)
|
private val DISLIKE = SessionCommand("it.panov.musyx.DISLIKE", Bundle.EMPTY)
|
||||||
|
private val SHUFFLE_MODE = SessionCommand("it.panov.musyx.SHUFFLE", Bundle.EMPTY)
|
||||||
|
|
||||||
@OptIn(UnstableApi::class)
|
@OptIn(UnstableApi::class)
|
||||||
class Library(private val context: Context, private val state: AppState, private val scope: CoroutineScope) :
|
class Library(private val context: Context, private val state: AppState, private val scope: CoroutineScope) :
|
||||||
@@ -85,9 +95,9 @@ class Library(private val context: Context, private val state: AppState, private
|
|||||||
private val searches = HashMap<String, List<MediaItem>>()
|
private val searches = HashMap<String, List<MediaItem>>()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Has the car reload whenever someone signs in or out, so it never keeps showing "Sign in"
|
* Has the car reload whenever someone signs in or out, or the app goes offline or back, so
|
||||||
* (or someone else's music), and keeps the heart in step with the track. Returns what
|
* it never keeps showing "Sign in" (or someone else's music, or music it can't reach), and
|
||||||
* stops watching.
|
* keeps the heart and shuffle in step with the player. Returns what stops watching.
|
||||||
*/
|
*/
|
||||||
fun watch(session: MediaLibrarySession): () -> Unit {
|
fun watch(session: MediaLibrarySession): () -> Unit {
|
||||||
// snapshotFlow hears about changes through Compose's apply notifications, which only the
|
// snapshotFlow hears about changes through Compose's apply notifications, which only the
|
||||||
@@ -103,7 +113,8 @@ class Library(private val context: Context, private val state: AppState, private
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
val job = scope.launch {
|
val job = scope.launch {
|
||||||
snapshotFlow { state.session is Session.SignedIn }
|
// The tree comes from the account, from the downloads, or from neither.
|
||||||
|
snapshotFlow { state.client ?: state.session.takeIf { it == Session.Unreachable } }
|
||||||
.distinctUntilChanged()
|
.distinctUntilChanged()
|
||||||
.drop(1)
|
.drop(1)
|
||||||
.collect {
|
.collect {
|
||||||
@@ -114,8 +125,9 @@ class Library(private val context: Context, private val state: AppState, private
|
|||||||
}
|
}
|
||||||
val buttons = scope.launch {
|
val buttons = scope.launch {
|
||||||
snapshotFlow {
|
snapshotFlow {
|
||||||
val track = state.playback.state.track
|
val p = state.playback.state
|
||||||
Triple(track?.id, track?.let { state.liked.contains(it.id) }, track?.let { it.id in state.likes.dislikedTracks })
|
val track = p.track
|
||||||
|
listOf(track?.id, track?.let { state.liked.contains(it.id) }, track?.let { it.id in state.likes.dislikedTracks }, p.shuffle, p.waveStation)
|
||||||
}
|
}
|
||||||
.distinctUntilChanged()
|
.distinctUntilChanged()
|
||||||
.collect { session.setMediaButtonPreferences(buttons()) }
|
.collect { session.setMediaButtonPreferences(buttons()) }
|
||||||
@@ -127,7 +139,7 @@ class Library(private val context: Context, private val state: AppState, private
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Every controller may like and dislike, and starts with the buttons for what's playing. */
|
/** Every controller may like, dislike and shuffle, and starts with the buttons for what's playing. */
|
||||||
override fun onConnect(session: MediaSession, controller: MediaSession.ControllerInfo): MediaSession.ConnectionResult {
|
override fun onConnect(session: MediaSession, controller: MediaSession.ControllerInfo): MediaSession.ConnectionResult {
|
||||||
// The library commands must stay: without "get root" a car's browser connection is refused.
|
// The library commands must stay: without "get root" a car's browser connection is refused.
|
||||||
val library = if (controller.isTrusted) {
|
val library = if (controller.isTrusted) {
|
||||||
@@ -136,7 +148,7 @@ class Library(private val context: Context, private val state: AppState, private
|
|||||||
MediaSession.ConnectionResult.DEFAULT_UNTRUSTED_SESSION_AND_LIBRARY_COMMANDS
|
MediaSession.ConnectionResult.DEFAULT_UNTRUSTED_SESSION_AND_LIBRARY_COMMANDS
|
||||||
}
|
}
|
||||||
return MediaSession.ConnectionResult.AcceptedResultBuilder(session)
|
return MediaSession.ConnectionResult.AcceptedResultBuilder(session)
|
||||||
.setAvailableSessionCommands(library.buildUpon().add(LIKE).add(DISLIKE).build())
|
.setAvailableSessionCommands(library.buildUpon().add(LIKE).add(DISLIKE).add(SHUFFLE_MODE).build())
|
||||||
.setMediaButtonPreferences(buttons())
|
.setMediaButtonPreferences(buttons())
|
||||||
.build()
|
.build()
|
||||||
}
|
}
|
||||||
@@ -153,32 +165,38 @@ class Library(private val context: Context, private val state: AppState, private
|
|||||||
LIKE.customAction -> state.likeTrack(track, !state.liked.contains(track.id))
|
LIKE.customAction -> state.likeTrack(track, !state.liked.contains(track.id))
|
||||||
// Disliking the playing track also skips it, as from the app's menu.
|
// Disliking the playing track also skips it, as from the app's menu.
|
||||||
DISLIKE.customAction -> state.dislikeTrack(track, track.id !in state.likes.dislikedTracks)
|
DISLIKE.customAction -> state.dislikeTrack(track, track.id !in state.likes.dislikedTracks)
|
||||||
|
SHUFFLE_MODE.customAction -> state.playback.toggleShuffle()
|
||||||
else -> return Futures.immediateFuture(SessionResult(SessionError.ERROR_NOT_SUPPORTED))
|
else -> return Futures.immediateFuture(SessionResult(SessionError.ERROR_NOT_SUPPORTED))
|
||||||
}
|
}
|
||||||
return Futures.immediateFuture(SessionResult(SessionResult.RESULT_SUCCESS))
|
return Futures.immediateFuture(SessionResult(SessionResult.RESULT_SUCCESS))
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The heart and "don't recommend" for what's playing, asked for right after next; previous
|
* The heart, "don't recommend" and shuffle for what's playing, asked for right after next;
|
||||||
* and next keep their slots. Android Auto ignores the slot and puts them at the right edge.
|
* previous and next keep their slots. Android Auto ignores the slot and puts them at the
|
||||||
* Speech has nothing to recommend.
|
* right edge. Speech has nothing to recommend, and a station decides its own order.
|
||||||
*/
|
*/
|
||||||
private fun buttons(): List<CommandButton> {
|
private fun buttons(): List<CommandButton> {
|
||||||
val track = state.playback.state.track ?: return emptyList()
|
val p = state.playback.state
|
||||||
|
val track = p.track ?: return emptyList()
|
||||||
val liked = state.liked.contains(track.id)
|
val liked = state.liked.contains(track.id)
|
||||||
val heart = CommandButton.Builder(if (liked) CommandButton.ICON_HEART_FILLED else CommandButton.ICON_HEART_UNFILLED)
|
val heart = CommandButton.Builder(if (liked) CommandButton.ICON_HEART_FILLED else CommandButton.ICON_HEART_UNFILLED)
|
||||||
.setDisplayName(context.getString(if (liked) R.string.menu_unlike else R.string.menu_like))
|
.setDisplayName(context.getString(if (liked) R.string.menu_unlike else R.string.menu_like))
|
||||||
.setSessionCommand(LIKE)
|
.setSessionCommand(LIKE)
|
||||||
.setSlots(CommandButton.SLOT_FORWARD_SECONDARY, CommandButton.SLOT_OVERFLOW)
|
.setSlots(CommandButton.SLOT_FORWARD_SECONDARY, CommandButton.SLOT_OVERFLOW)
|
||||||
.build()
|
.build()
|
||||||
if (track.spoken) return listOf(heart)
|
|
||||||
val disliked = track.id in state.likes.dislikedTracks
|
val disliked = track.id in state.likes.dislikedTracks
|
||||||
val block = CommandButton.Builder(CommandButton.ICON_BLOCK)
|
val block = if (track.spoken) null else CommandButton.Builder(CommandButton.ICON_BLOCK)
|
||||||
.setDisplayName(context.getString(if (disliked) R.string.menu_undislike else R.string.menu_dislike))
|
.setDisplayName(context.getString(if (disliked) R.string.menu_undislike else R.string.menu_dislike))
|
||||||
.setSessionCommand(DISLIKE)
|
.setSessionCommand(DISLIKE)
|
||||||
.setSlots(CommandButton.SLOT_FORWARD_SECONDARY, CommandButton.SLOT_OVERFLOW)
|
.setSlots(CommandButton.SLOT_FORWARD_SECONDARY, CommandButton.SLOT_OVERFLOW)
|
||||||
.build()
|
.build()
|
||||||
return listOf(heart, block)
|
val shuffle = if (p.waveStation != null) null else CommandButton.Builder(if (p.shuffle) CommandButton.ICON_SHUFFLE_ON else CommandButton.ICON_SHUFFLE_OFF)
|
||||||
|
.setDisplayName(context.getString(if (p.shuffle) R.string.action_shuffle_off else R.string.action_shuffle))
|
||||||
|
.setSessionCommand(SHUFFLE_MODE)
|
||||||
|
.setSlots(CommandButton.SLOT_FORWARD_SECONDARY, CommandButton.SLOT_OVERFLOW)
|
||||||
|
.build()
|
||||||
|
return listOfNotNull(heart, block, shuffle)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onGetLibraryRoot(
|
override fun onGetLibraryRoot(
|
||||||
@@ -203,8 +221,16 @@ class Library(private val context: Context, private val state: AppState, private
|
|||||||
pageSize: Int,
|
pageSize: Int,
|
||||||
params: LibraryParams?,
|
params: LibraryParams?,
|
||||||
): ListenableFuture<LibraryResult<ImmutableList<MediaItem>>> = future {
|
): ListenableFuture<LibraryResult<ImmutableList<MediaItem>>> = future {
|
||||||
val client = client() ?: return@future signedOut()
|
val client = client()
|
||||||
val items = children(client, parentId) ?: return@future LibraryResult.ofError(SessionError.ERROR_BAD_VALUE)
|
val items = when {
|
||||||
|
client != null -> children(client, parentId)
|
||||||
|
!offline() -> return@future signedOut()
|
||||||
|
state.downloads.doneTracks.isEmpty() -> return@future nothingOffline()
|
||||||
|
// Out of reach: what's on the phone is all there is.
|
||||||
|
parentId == ROOT -> listOf(folder(DOWNLOADS, context.getString(R.string.downloads_title), browsable = MediaConstants.EXTRAS_VALUE_CONTENT_STYLE_LIST_ITEM))
|
||||||
|
parentId == DOWNLOADS -> downloads()
|
||||||
|
else -> offlineTracks(parentId)?.let { tracks -> trackItems(parentId, tracks) }
|
||||||
|
} ?: return@future LibraryResult.ofError(SessionError.ERROR_BAD_VALUE)
|
||||||
LibraryResult.ofItemList(items.page(page, pageSize), params)
|
LibraryResult.ofItemList(items.page(page, pageSize), params)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -223,8 +249,12 @@ class Library(private val context: Context, private val state: AppState, private
|
|||||||
query: String,
|
query: String,
|
||||||
params: LibraryParams?,
|
params: LibraryParams?,
|
||||||
): ListenableFuture<LibraryResult<Void>> = future {
|
): ListenableFuture<LibraryResult<Void>> = future {
|
||||||
val client = client() ?: return@future signedOut()
|
val client = client()
|
||||||
val tracks = client.search(query, SearchKind.Tracks, 0).tracks
|
val tracks = when {
|
||||||
|
client != null -> client.search(query, SearchKind.Tracks, 0).tracks
|
||||||
|
offline() -> findDownloaded(state, query)
|
||||||
|
else -> return@future signedOut()
|
||||||
|
}
|
||||||
val folder = SEARCH + query
|
val folder = SEARCH + query
|
||||||
shown[folder] = tracks
|
shown[folder] = tracks
|
||||||
searches[query] = tracks.mapIndexed { i, t -> track(folder, i, t) }
|
searches[query] = tracks.mapIndexed { i, t -> track(folder, i, t) }
|
||||||
@@ -243,8 +273,8 @@ class Library(private val context: Context, private val state: AppState, private
|
|||||||
Futures.immediateFuture(LibraryResult.ofItemList(searches[query].orEmpty().page(page, pageSize), params))
|
Futures.immediateFuture(LibraryResult.ofItemList(searches[query].orEmpty().page(page, pageSize), params))
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Plays what the car picked: a station, a track with the rest of its folder, or, for a
|
* Plays what the car picked: a station, a track with the rest of its folder, a folder
|
||||||
* spoken request, the best tracks for it (My Wave when nothing was named).
|
* shuffled, or, for a spoken request, the best tracks for it (My Wave when nothing was named).
|
||||||
*/
|
*/
|
||||||
override fun onSetMediaItems(
|
override fun onSetMediaItems(
|
||||||
mediaSession: MediaSession,
|
mediaSession: MediaSession,
|
||||||
@@ -260,9 +290,10 @@ class Library(private val context: Context, private val state: AppState, private
|
|||||||
id.startsWith(STATION) -> state.playWave(id.removePrefix(STATION))
|
id.startsWith(STATION) -> state.playWave(id.removePrefix(STATION))
|
||||||
id.startsWith(TRACK) -> {
|
id.startsWith(TRACK) -> {
|
||||||
val (folder, index) = id.removePrefix(TRACK).let { it.substringBeforeLast('|') to it.substringAfterLast('|').toIntOrNull() }
|
val (folder, index) = id.removePrefix(TRACK).let { it.substringBeforeLast('|') to it.substringAfterLast('|').toIntOrNull() }
|
||||||
val tracks = shown[folder] ?: client()?.let { tracks(it, folder) }
|
val tracks = folderTracks(folder)
|
||||||
if (tracks != null && index != null && index in tracks.indices) state.playTracks(tracks, index)
|
if (tracks != null && index != null && index in tracks.indices) state.playTracks(tracks, index)
|
||||||
}
|
}
|
||||||
|
id.startsWith(SHUFFLE) -> folderTracks(id.removePrefix(SHUFFLE))?.takeIf { it.isNotEmpty() }?.let { state.playTracks(it, 0, shuffle = true) }
|
||||||
id.isEmpty() -> playFromSearch(state, query)
|
id.isEmpty() -> playFromSearch(state, query)
|
||||||
}
|
}
|
||||||
MediaItemsWithStartPosition(mediaItems, startIndex, C.TIME_UNSET)
|
MediaItemsWithStartPosition(mediaItems, startIndex, C.TIME_UNSET)
|
||||||
@@ -289,21 +320,57 @@ class Library(private val context: Context, private val state: AppState, private
|
|||||||
folder(CHART, context.getString(R.string.section_chart), home.chart.firstOrNull()?.track?.coverUrl(ART_SIZE)),
|
folder(CHART, context.getString(R.string.section_chart), home.chart.firstOrNull()?.track?.coverUrl(ART_SIZE)),
|
||||||
) + home.personal.map { playlist(it.playlist) }
|
) + home.personal.map { playlist(it.playlist) }
|
||||||
}
|
}
|
||||||
COLLECTION -> listOf(
|
COLLECTION -> listOfNotNull(
|
||||||
folder(LIKED, context.getString(R.string.tab_liked_tracks)),
|
folder(LIKED, context.getString(R.string.tab_liked_tracks)),
|
||||||
folder(PLAYLISTS, context.getString(R.string.tab_playlists)),
|
folder(PLAYLISTS, context.getString(R.string.tab_playlists)),
|
||||||
folder(ALBUMS, context.getString(R.string.tab_albums)),
|
folder(ALBUMS, context.getString(R.string.tab_albums)),
|
||||||
|
// Music on the phone plays without using data, or a signal.
|
||||||
|
if (state.downloads.doneTracks.isEmpty()) null
|
||||||
|
else folder(DOWNLOADS, context.getString(R.string.downloads_title), browsable = MediaConstants.EXTRAS_VALUE_CONTENT_STYLE_LIST_ITEM),
|
||||||
)
|
)
|
||||||
PLAYLISTS -> client.libraryPlaylists().let { it.own + it.liked }.map(::playlist)
|
PLAYLISTS -> client.libraryPlaylists().let { it.own + it.liked }.map(::playlist)
|
||||||
ALBUMS -> client.likedAlbums().filter { !it.isPodcast }.map(::album)
|
ALBUMS -> client.likedAlbums().filter { !it.isPodcast }.map(::album)
|
||||||
else -> tracks(client, parent)?.let { tracks ->
|
DOWNLOADS -> downloads()
|
||||||
shown[parent] = tracks
|
else -> tracks(client, parent)?.let { tracks -> trackItems(parent, tracks) }
|
||||||
tracks.mapIndexed { i, t -> track(parent, i, t) }
|
}
|
||||||
|
|
||||||
|
/** A folder's tracks; the collection's and the downloads' start with Shuffle, as in the app. */
|
||||||
|
private fun trackItems(folder: String, tracks: List<Track>): List<MediaItem> {
|
||||||
|
shown[folder] = tracks
|
||||||
|
val rows = tracks.mapIndexed { i, t -> track(folder, i, t) }
|
||||||
|
return if (shuffles(folder) && tracks.size > 1) listOf(shuffle(folder)) + rows else rows
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Liked tracks, albums, playlists and downloads; not the recent, the chart or search results. */
|
||||||
|
private fun shuffles(folder: String): Boolean =
|
||||||
|
folder == LIKED || folder == OFFLINE_ALL || folder.startsWith(OFFLINE) || folder.startsWith("album:") || folder.startsWith("playlist:")
|
||||||
|
|
||||||
|
/** A folder's tracks as last shown, or fetched again when the car plays it cold. */
|
||||||
|
private suspend fun folderTracks(folder: String): List<Track>? = shown[folder] ?: offlineTracks(folder) ?: client()?.let { tracks(it, folder) }
|
||||||
|
|
||||||
|
/** Every downloaded track, then the albums and playlists with any of theirs on the phone. */
|
||||||
|
private fun downloads(): List<MediaItem> {
|
||||||
|
val d = state.downloads
|
||||||
|
val all = d.doneTracks
|
||||||
|
val sets = d.sets.filter { set -> set.trackIds.any(d::isDone) }.map { set ->
|
||||||
|
val title = if (set.kind == OfflineSet.Kind.Liked) context.getString(R.string.tab_liked_tracks) else set.title
|
||||||
|
folder(OFFLINE + set.key, title, set.cover, browsable = MediaConstants.EXTRAS_VALUE_CONTENT_STYLE_LIST_ITEM)
|
||||||
|
}
|
||||||
|
return listOf(folder(OFFLINE_ALL, context.getString(R.string.downloads_tracks), all.firstOrNull()?.coverUrl(COVER_LARGE))) + sets
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The tracks of a downloads folder that are on the phone; null for any other folder. */
|
||||||
|
private fun offlineTracks(folder: String): List<Track>? {
|
||||||
|
val d = state.downloads
|
||||||
|
return when {
|
||||||
|
folder == OFFLINE_ALL -> d.doneTracks
|
||||||
|
folder.startsWith(OFFLINE) -> d.set(folder.removePrefix(OFFLINE))?.let { set -> d.tracksOf(set).filter { d.isDone(it.id) } }
|
||||||
|
else -> null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The tracks of a track folder; null for anything else. */
|
/** The tracks of a track folder; null for anything else. */
|
||||||
private suspend fun tracks(client: YmClient, folder: String): List<Track>? = when {
|
private suspend fun tracks(client: YmClient, folder: String): List<Track>? = offlineTracks(folder) ?: when {
|
||||||
folder == LIKED -> (state.liked as? Liked.Loaded)?.tracks ?: client.likedTracks()
|
folder == LIKED -> (state.liked as? Liked.Loaded)?.tracks ?: client.likedTracks()
|
||||||
folder == RECENT -> client.recentlyPlayed(RECENT_SHOWN)
|
folder == RECENT -> client.recentlyPlayed(RECENT_SHOWN)
|
||||||
folder == CHART -> client.chart().map { it.track }
|
folder == CHART -> client.chart().map { it.track }
|
||||||
@@ -354,6 +421,20 @@ class Library(private val context: Context, private val state: AppState, private
|
|||||||
)
|
)
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
|
private fun shuffle(folder: String) = MediaItem.Builder()
|
||||||
|
.setMediaId(SHUFFLE + folder)
|
||||||
|
.setMediaMetadata(
|
||||||
|
MediaMetadata.Builder()
|
||||||
|
.setTitle(context.getString(R.string.action_shuffle))
|
||||||
|
// Without an icon the row reads as a heading.
|
||||||
|
.setArtworkUri(ArtworkProvider.uri(context, ArtworkProvider.SHUFFLE))
|
||||||
|
.setIsBrowsable(false)
|
||||||
|
.setIsPlayable(true)
|
||||||
|
.setMediaType(MediaMetadata.MEDIA_TYPE_PLAYLIST)
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
|
.build()
|
||||||
|
|
||||||
private fun track(folder: String, index: Int, t: Track) = MediaItem.Builder()
|
private fun track(folder: String, index: Int, t: Track) = MediaItem.Builder()
|
||||||
.setMediaId("$TRACK$folder|$index")
|
.setMediaId("$TRACK$folder|$index")
|
||||||
.setMediaMetadata(
|
.setMediaMetadata(
|
||||||
@@ -361,7 +442,8 @@ class Library(private val context: Context, private val state: AppState, private
|
|||||||
.setTitle(t.fullTitle)
|
.setTitle(t.fullTitle)
|
||||||
.setArtist(t.artistLine)
|
.setArtist(t.artistLine)
|
||||||
.setAlbumTitle(t.album?.title)
|
.setAlbumTitle(t.album?.title)
|
||||||
.setArtworkUri(artwork(t.coverUrl(ART_SIZE)))
|
// Downloaded tracks keep their covers at this size, so they show offline.
|
||||||
|
.setArtworkUri(artwork(t.coverUrl(if (state.downloads.isDone(t.id)) COVER_LARGE else ART_SIZE)))
|
||||||
.setDurationMs(t.durationMs)
|
.setDurationMs(t.durationMs)
|
||||||
.setIsBrowsable(false)
|
.setIsBrowsable(false)
|
||||||
.setIsPlayable(t.available)
|
.setIsPlayable(t.available)
|
||||||
@@ -376,6 +458,13 @@ class Library(private val context: Context, private val state: AppState, private
|
|||||||
|
|
||||||
private suspend fun client(): YmClient? = awaitClient(state)
|
private suspend fun client(): YmClient? = awaitClient(state)
|
||||||
|
|
||||||
|
/** Signed in, but Yandex is out of reach: the downloads stand in. */
|
||||||
|
private fun offline(): Boolean = state.session == Session.Unreachable
|
||||||
|
|
||||||
|
/** Offline with nothing on the phone to play. */
|
||||||
|
private fun <V : Any> nothingOffline(): LibraryResult<V> =
|
||||||
|
LibraryResult.ofError(SessionError(SessionError.ERROR_IO, context.getString(R.string.auto_offline)))
|
||||||
|
|
||||||
/** Signed out: the car shows why, with a button that opens the app's sign-in. */
|
/** Signed out: the car shows why, with a button that opens the app's sign-in. */
|
||||||
private fun <V : Any> signedOut(): LibraryResult<V> {
|
private fun <V : Any> signedOut(): LibraryResult<V> {
|
||||||
val open = PendingIntent.getActivity(
|
val open = PendingIntent.getActivity(
|
||||||
@@ -426,9 +515,26 @@ internal suspend fun awaitClient(state: AppState): YmClient? {
|
|||||||
return state.client
|
return state.client
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A spoken request ("play … on Musyx"): the best tracks for `query`, or My Wave when nothing was named. */
|
/**
|
||||||
|
* A spoken request ("play … on Musyx"): the best tracks for `query`, or My Wave when nothing
|
||||||
|
* was named. Offline, the downloads that match, or all of them shuffled.
|
||||||
|
*/
|
||||||
internal suspend fun playFromSearch(state: AppState, query: String?) {
|
internal suspend fun playFromSearch(state: AppState, query: String?) {
|
||||||
|
val client = awaitClient(state)
|
||||||
|
if (client == null && state.session == Session.Unreachable) {
|
||||||
|
if (query.isNullOrBlank()) return state.playTracks(state.downloads.doneTracks, 0, shuffle = true)
|
||||||
|
return state.playTracks(findDownloaded(state, query), 0)
|
||||||
|
}
|
||||||
if (query.isNullOrBlank()) return state.playWave(MY_WAVE)
|
if (query.isNullOrBlank()) return state.playWave(MY_WAVE)
|
||||||
val tracks = awaitClient(state)?.search(query, SearchKind.Tracks, 0)?.tracks.orEmpty()
|
val tracks = client?.search(query, SearchKind.Tracks, 0)?.tracks.orEmpty()
|
||||||
if (tracks.isNotEmpty()) state.playTracks(tracks, 0)
|
if (tracks.isNotEmpty()) state.playTracks(tracks, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Downloaded tracks whose title, artists or album hold every word of `query`. */
|
||||||
|
internal fun findDownloaded(state: AppState, query: String): List<Track> {
|
||||||
|
val words = query.lowercase().split(' ').filter { it.isNotBlank() }
|
||||||
|
return state.downloads.doneTracks.filter { t ->
|
||||||
|
val text = listOfNotNull(t.fullTitle, t.artistLine, t.album?.title).joinToString(" ").lowercase()
|
||||||
|
words.all { it in text }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -82,6 +82,7 @@ internal fun noticeText(notice: Notice): String = when (notice) {
|
|||||||
Notice.StationDry -> stringResource(R.string.notice_station_dry)
|
Notice.StationDry -> stringResource(R.string.notice_station_dry)
|
||||||
Notice.TooManyFailures -> stringResource(R.string.notice_too_many)
|
Notice.TooManyFailures -> stringResource(R.string.notice_too_many)
|
||||||
is Notice.Skipped -> stringResource(R.string.notice_skipped, notice.title)
|
is Notice.Skipped -> stringResource(R.string.notice_skipped, notice.title)
|
||||||
|
Notice.NothingDownloaded -> stringResource(R.string.notice_nothing_downloaded)
|
||||||
}
|
}
|
||||||
|
|
||||||
private enum class Panel { Queue, Lyrics }
|
private enum class Panel { Queue, Lyrics }
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!-- The aubergine gradient behind the launcher icon's waves. -->
|
||||||
|
<shape xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<gradient
|
||||||
|
android:angle="270"
|
||||||
|
android:endColor="#1C1A22"
|
||||||
|
android:startColor="#353042" />
|
||||||
|
</shape>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!-- Full-bleed layers, so launchers fill their icon shape instead of framing
|
||||||
|
the legacy PNG. Drawn by tool/make_icon.py in foreground mode. -->
|
||||||
|
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<background android:drawable="@drawable/ic_launcher_background" />
|
||||||
|
<foreground android:drawable="@mipmap/ic_launcher_foreground" />
|
||||||
|
<monochrome android:drawable="@mipmap/ic_launcher_foreground" />
|
||||||
|
</adaptive-icon>
|
||||||
|
Before Width: | Height: | Size: 6.1 KiB After Width: | Height: | Size: 4.7 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 3.3 KiB After Width: | Height: | Size: 2.6 KiB |
|
After Width: | Height: | Size: 7.0 KiB |
|
Before Width: | Height: | Size: 9.3 KiB After Width: | Height: | Size: 7.1 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 36 KiB |
|
Before Width: | Height: | Size: 23 KiB After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 56 KiB |
@@ -25,6 +25,7 @@
|
|||||||
<string name="signin_token_placeholder">Вставьте OAuth-токен</string>
|
<string name="signin_token_placeholder">Вставьте OAuth-токен</string>
|
||||||
<string name="action_play">Слушать</string>
|
<string name="action_play">Слушать</string>
|
||||||
<string name="action_shuffle">Вперемешку</string>
|
<string name="action_shuffle">Вперемешку</string>
|
||||||
|
<string name="action_shuffle_off">Выключить перемешивание</string>
|
||||||
<string name="action_pause">Пауза</string>
|
<string name="action_pause">Пауза</string>
|
||||||
<string name="action_resume">Продолжить</string>
|
<string name="action_resume">Продолжить</string>
|
||||||
<string name="action_try_again">Повторить</string>
|
<string name="action_try_again">Повторить</string>
|
||||||
@@ -179,6 +180,7 @@
|
|||||||
<string name="notice_station_dry">Не удалось загрузить продолжение станции. Проверьте подключение и попробуйте ещё раз.</string>
|
<string name="notice_station_dry">Не удалось загрузить продолжение станции. Проверьте подключение и попробуйте ещё раз.</string>
|
||||||
<string name="notice_too_many">Несколько треков подряд не удалось воспроизвести. Проверьте подключение и попробуйте ещё раз.</string>
|
<string name="notice_too_many">Несколько треков подряд не удалось воспроизвести. Проверьте подключение и попробуйте ещё раз.</string>
|
||||||
<string name="notice_skipped">Не удалось воспроизвести «%1$s», трек пропущен.</string>
|
<string name="notice_skipped">Не удалось воспроизвести «%1$s», трек пропущен.</string>
|
||||||
|
<string name="notice_nothing_downloaded">Ни один трек в очереди не загружен. Подключитесь к интернету, чтобы их послушать.</string>
|
||||||
<string name="menu_next_track">Следующий трек</string>
|
<string name="menu_next_track">Следующий трек</string>
|
||||||
<string name="menu_play_next">Играть следующим</string>
|
<string name="menu_play_next">Играть следующим</string>
|
||||||
<string name="menu_add_to_queue">Добавить в очередь</string>
|
<string name="menu_add_to_queue">Добавить в очередь</string>
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
<string name="signin_open_page">Открыть страницу входа Яндекса</string>
|
<string name="signin_open_page">Открыть страницу входа Яндекса</string>
|
||||||
<string name="signin_phone_hint">Код копируется, когда открывается страница. Вставьте его там, подтвердите вход и вернитесь сюда — дальше всё произойдёт само.</string>
|
<string name="signin_phone_hint">Код копируется, когда открывается страница. Вставьте его там, подтвердите вход и вернитесь сюда — дальше всё произойдёт само.</string>
|
||||||
<string name="auto_sign_in">Войдите в Musyx, чтобы ваша музыка появилась здесь.</string>
|
<string name="auto_sign_in">Войдите в Musyx, чтобы ваша музыка появилась здесь.</string>
|
||||||
|
<string name="auto_offline">Нет интернета, а загруженной музыки нет.</string>
|
||||||
<!-- Офлайн. -->
|
<!-- Офлайн. -->
|
||||||
<string name="downloads_title">Загрузки</string>
|
<string name="downloads_title">Загрузки</string>
|
||||||
<string name="downloads_empty">Здесь пока пусто. Скачайте альбом, плейлист или «Мне нравится» кнопкой загрузки на их странице, а трек — через его меню, и они будут играть без интернета.</string>
|
<string name="downloads_empty">Здесь пока пусто. Скачайте альбом, плейлист или «Мне нравится» кнопкой загрузки на их странице, а трек — через его меню, и они будут играть без интернета.</string>
|
||||||
|
|||||||
@@ -26,6 +26,7 @@
|
|||||||
<string name="signin_token_placeholder">Paste OAuth token</string>
|
<string name="signin_token_placeholder">Paste OAuth token</string>
|
||||||
<string name="action_play">Play</string>
|
<string name="action_play">Play</string>
|
||||||
<string name="action_shuffle">Shuffle</string>
|
<string name="action_shuffle">Shuffle</string>
|
||||||
|
<string name="action_shuffle_off">Turn off shuffle</string>
|
||||||
<string name="action_pause">Pause</string>
|
<string name="action_pause">Pause</string>
|
||||||
<string name="action_resume">Resume</string>
|
<string name="action_resume">Resume</string>
|
||||||
<string name="action_try_again">Try again</string>
|
<string name="action_try_again">Try again</string>
|
||||||
@@ -180,6 +181,7 @@
|
|||||||
<string name="notice_station_dry">Couldn\'t load more of this station. Check your connection and try again.</string>
|
<string name="notice_station_dry">Couldn\'t load more of this station. Check your connection and try again.</string>
|
||||||
<string name="notice_too_many">Several tracks in a row couldn\'t be played. Check your connection and try again.</string>
|
<string name="notice_too_many">Several tracks in a row couldn\'t be played. Check your connection and try again.</string>
|
||||||
<string name="notice_skipped">Couldn\'t play “%1$s”, so it was skipped.</string>
|
<string name="notice_skipped">Couldn\'t play “%1$s”, so it was skipped.</string>
|
||||||
|
<string name="notice_nothing_downloaded">None of the queued tracks are downloaded. Connect to the internet to play them.</string>
|
||||||
<string name="menu_next_track">Next track</string>
|
<string name="menu_next_track">Next track</string>
|
||||||
<string name="menu_play_next">Play next</string>
|
<string name="menu_play_next">Play next</string>
|
||||||
<string name="menu_add_to_queue">Add to queue</string>
|
<string name="menu_add_to_queue">Add to queue</string>
|
||||||
|
|||||||
@@ -6,6 +6,8 @@
|
|||||||
<string name="signin_phone_hint">Opening the page copies the code. Paste it there, confirm, and come back: sign-in finishes on its own.</string>
|
<string name="signin_phone_hint">Opening the page copies the code. Paste it there, confirm, and come back: sign-in finishes on its own.</string>
|
||||||
<!-- Shown in the car (Android Auto or Automotive) when nobody is signed in. -->
|
<!-- Shown in the car (Android Auto or Automotive) when nobody is signed in. -->
|
||||||
<string name="auto_sign_in">Sign in to Musyx to see your music here.</string>
|
<string name="auto_sign_in">Sign in to Musyx to see your music here.</string>
|
||||||
|
<!-- Shown in the car when Yandex Music can\'t be reached and nothing is downloaded. -->
|
||||||
|
<string name="auto_offline">No connection, and nothing is downloaded to play.</string>
|
||||||
<!-- Offline listening. -->
|
<!-- Offline listening. -->
|
||||||
<string name="downloads_title">Downloads</string>
|
<string name="downloads_title">Downloads</string>
|
||||||
<string name="downloads_empty">Nothing downloaded yet. Use the download button on an album, a playlist or Liked tracks, or Download in a track\'s menu, and it plays without a connection.</string>
|
<string name="downloads_empty">Nothing downloaded yet. Use the download button on an album, a playlist or Liked tracks, or Download in a track\'s menu, and it plays without a connection.</string>
|
||||||
|
|||||||
@@ -3,6 +3,16 @@
|
|||||||
|
|
||||||
Aubergine squircle with amber wave lines, matching the My Wave hero.
|
Aubergine squircle with amber wave lines, matching the My Wave hero.
|
||||||
Usage: python3 tool/make_icon.py assets/icon/musyx.png
|
Usage: python3 tool/make_icon.py assets/icon/musyx.png
|
||||||
|
|
||||||
|
With --foreground it draws the adaptive icon's foreground instead: the waves
|
||||||
|
alone on a transparent, full-bleed 108dp canvas, laid out so the launcher's
|
||||||
|
mask (the middle 72dp) shows what the squircle does. The background layer is
|
||||||
|
the gradient in res/drawable/ic_launcher_background.xml.
|
||||||
|
|
||||||
|
With --square it draws the legacy res/mipmap-*/ic_launcher.png: the artwork as
|
||||||
|
an opaque, full-bleed square. Anything that still loads the legacy icon on a
|
||||||
|
newer Android (Android Auto's media header does) wraps it in a shape, and any
|
||||||
|
transparent margin left in it shows there as a white frame.
|
||||||
"""
|
"""
|
||||||
import math
|
import math
|
||||||
import struct
|
import struct
|
||||||
@@ -12,6 +22,12 @@ import zlib
|
|||||||
SIZE = 1024
|
SIZE = 1024
|
||||||
# macOS icon grid: the body is 824px, centred, with a ~185px corner radius.
|
# macOS icon grid: the body is 824px, centred, with a ~185px corner radius.
|
||||||
BODY, RADIUS = 824, 185
|
BODY, RADIUS = 824, 185
|
||||||
|
FOREGROUND = "--foreground" in sys.argv
|
||||||
|
SQUARE = "--square" in sys.argv
|
||||||
|
if FOREGROUND:
|
||||||
|
BODY = SIZE * 72 / 108
|
||||||
|
if SQUARE:
|
||||||
|
BODY = SIZE
|
||||||
OFF = (SIZE - BODY) / 2
|
OFF = (SIZE - BODY) / 2
|
||||||
TOP, BOTTOM = (0x35, 0x30, 0x42), (0x1C, 0x1A, 0x22)
|
TOP, BOTTOM = (0x35, 0x30, 0x42), (0x1C, 0x1A, 0x22)
|
||||||
AMBER = (0xF0, 0xB2, 0x3E)
|
AMBER = (0xF0, 0xB2, 0x3E)
|
||||||
@@ -51,22 +67,27 @@ def main(out):
|
|||||||
t = y / SIZE
|
t = y / SIZE
|
||||||
bg = tuple(round(TOP[i] + (BOTTOM[i] - TOP[i]) * t) for i in range(3))
|
bg = tuple(round(TOP[i] + (BOTTOM[i] - TOP[i]) * t) for i in range(3))
|
||||||
for x in range(SIZE):
|
for x in range(SIZE):
|
||||||
cover = rounded_alpha(x, y)
|
cover = 1.0 if FOREGROUND or SQUARE else rounded_alpha(x, y)
|
||||||
if cover == 0.0:
|
if cover == 0.0:
|
||||||
row += b"\x00\x00\x00\x00"
|
row += b"\x00\x00\x00\x00"
|
||||||
continue
|
continue
|
||||||
r, g, b = bg
|
r, g, b = bg
|
||||||
|
clear = 1.0 # how much of the background the lines leave showing
|
||||||
for k in range(LINES):
|
for k in range(LINES):
|
||||||
cy, slope = curves[k][x]
|
cy, slope = curves[k][x]
|
||||||
dist = abs(y + 0.5 - cy) / math.sqrt(1 + slope * slope)
|
dist = abs(y + 0.5 - cy) / math.sqrt(1 + slope * slope)
|
||||||
width = 4.0 + k * 0.9
|
width = (4.0 + k * 0.9) * BODY / 824
|
||||||
a = min(max(width / 2 - dist + 0.5, 0.0), 1.0)
|
a = min(max(width / 2 - dist + 0.5, 0.0), 1.0)
|
||||||
if a:
|
if a:
|
||||||
a *= 0.18 + 0.82 * (k / (LINES - 1))
|
a *= 0.18 + 0.82 * (k / (LINES - 1))
|
||||||
|
clear *= 1 - a
|
||||||
r = r + (AMBER[0] - r) * a
|
r = r + (AMBER[0] - r) * a
|
||||||
g = g + (AMBER[1] - g) * a
|
g = g + (AMBER[1] - g) * a
|
||||||
b = b + (AMBER[2] - b) * a
|
b = b + (AMBER[2] - b) * a
|
||||||
row += bytes((round(r), round(g), round(b), round(cover * 255)))
|
if FOREGROUND:
|
||||||
|
row += bytes((*AMBER, round((1 - clear) * 255)))
|
||||||
|
else:
|
||||||
|
row += bytes((round(r), round(g), round(b), round(cover * 255)))
|
||||||
rows.append(bytes(row))
|
rows.append(bytes(row))
|
||||||
|
|
||||||
def chunk(kind, data):
|
def chunk(kind, data):
|
||||||
@@ -81,4 +102,5 @@ def main(out):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main(sys.argv[1] if len(sys.argv) > 1 else "musyx.png")
|
args = [a for a in sys.argv[1:] if not a.startswith("--")]
|
||||||
|
main(args[0] if args else "musyx.png")
|
||||||
@@ -14,8 +14,8 @@ android {
|
|||||||
// Compose (and so Compose for TV) needs API 23.
|
// Compose (and so Compose for TV) needs API 23.
|
||||||
minSdk = 23
|
minSdk = 23
|
||||||
targetSdk = 37
|
targetSdk = 37
|
||||||
versionCode = 8
|
versionCode = 13
|
||||||
versionName = "0.1.7"
|
versionName = "0.1.12"
|
||||||
}
|
}
|
||||||
|
|
||||||
// A release key comes from keystore.properties (gitignored): storeFile, storePassword,
|
// A release key comes from keystore.properties (gitignored): storeFile, storePassword,
|
||||||
|
|||||||
@@ -36,8 +36,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
|
|
||||||
/** The interface language follows the setting, not only the system. */
|
/** The interface language follows the setting, not only the system. */
|
||||||
override fun attachBaseContext(newBase: Context) {
|
override fun attachBaseContext(newBase: Context) {
|
||||||
val tag = SettingsStore(newBase).language().tag
|
val tag = SettingsStore(newBase).language().tag ?: return super.attachBaseContext(newBase)
|
||||||
if (tag == null) return super.attachBaseContext(newBase)
|
|
||||||
val config = Configuration(newBase.resources.configuration)
|
val config = Configuration(newBase.resources.configuration)
|
||||||
val locale = Locale.forLanguageTag(tag)
|
val locale = Locale.forLanguageTag(tag)
|
||||||
Locale.setDefault(locale)
|
Locale.setDefault(locale)
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ import it.panov.musyx.api.PlaylistId
|
|||||||
import it.panov.musyx.api.Track
|
import it.panov.musyx.api.Track
|
||||||
import it.panov.musyx.state.AppState
|
import it.panov.musyx.state.AppState
|
||||||
import it.panov.musyx.state.PlaylistSlot
|
import it.panov.musyx.state.PlaylistSlot
|
||||||
|
import it.panov.musyx.state.Route
|
||||||
import it.panov.musyx.state.Sheet
|
import it.panov.musyx.state.Sheet
|
||||||
import it.panov.musyx.tv.ui.artistsOrUnknown
|
import it.panov.musyx.tv.ui.artistsOrUnknown
|
||||||
import it.panov.musyx.tv.ui.clock
|
import it.panov.musyx.tv.ui.clock
|
||||||
@@ -190,6 +191,19 @@ fun ShiftMarker(shift: Int) {
|
|||||||
Text(glyph, style = MusyxTheme.type.small, color = colour, modifier = Modifier.width(18.dp), textAlign = TextAlign.Center)
|
Text(glyph, style = MusyxTheme.type.small, color = colour, modifier = Modifier.width(18.dp), textAlign = TextAlign.Center)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Plays a whole list from the top and opens the player, as Play and Shuffle do. */
|
||||||
|
fun AppState.playTracksOpen(tracks: List<Track>, shuffle: Boolean = false) {
|
||||||
|
if (tracks.isEmpty()) return
|
||||||
|
playTracks(tracks, 0, shuffle)
|
||||||
|
navigate(Route.NowPlaying)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Starts a wave and opens the player, so tuning in lands on the full-screen view. */
|
||||||
|
fun AppState.playWaveOpen(station: String) {
|
||||||
|
playWave(station)
|
||||||
|
navigate(Route.NowPlaying)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Play and Shuffle, then any page actions (the heart), then a summary. Shared by every page
|
* Play and Shuffle, then any page actions (the heart), then a summary. Shared by every page
|
||||||
* with tracks.
|
* with tracks.
|
||||||
@@ -211,14 +225,14 @@ fun PlayBar(
|
|||||||
) {
|
) {
|
||||||
PrimaryButton(
|
PrimaryButton(
|
||||||
stringResource(R.string.action_play),
|
stringResource(R.string.action_play),
|
||||||
onClick = { state.playTracks(tracks, 0) },
|
onClick = { state.playTracksOpen(tracks) },
|
||||||
icon = R.drawable.ic_play_fill,
|
icon = R.drawable.ic_play_fill,
|
||||||
enabled = tracks.isNotEmpty(),
|
enabled = tracks.isNotEmpty(),
|
||||||
modifier = Modifier.entry(entry),
|
modifier = Modifier.entry(entry),
|
||||||
)
|
)
|
||||||
GhostButton(
|
GhostButton(
|
||||||
stringResource(R.string.action_shuffle),
|
stringResource(R.string.action_shuffle),
|
||||||
onClick = { state.playTracks(tracks, 0, shuffle = true) },
|
onClick = { state.playTracksOpen(tracks, shuffle = true) },
|
||||||
icon = R.drawable.ic_shuffle,
|
icon = R.drawable.ic_shuffle,
|
||||||
enabled = tracks.isNotEmpty(),
|
enabled = tracks.isNotEmpty(),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -53,6 +53,7 @@ import it.panov.musyx.tv.ui.components.ShelfRow
|
|||||||
import it.panov.musyx.tv.ui.components.ChoiceRow
|
import it.panov.musyx.tv.ui.components.ChoiceRow
|
||||||
import coil3.compose.AsyncImage
|
import coil3.compose.AsyncImage
|
||||||
import it.panov.musyx.tv.ui.components.FocusEntry
|
import it.panov.musyx.tv.ui.components.FocusEntry
|
||||||
|
import it.panov.musyx.tv.ui.components.playWaveOpen
|
||||||
import it.panov.musyx.tv.ui.components.Focusable
|
import it.panov.musyx.tv.ui.components.Focusable
|
||||||
import it.panov.musyx.tv.ui.components.Note
|
import it.panov.musyx.tv.ui.components.Note
|
||||||
import it.panov.musyx.tv.ui.components.PrimaryButton
|
import it.panov.musyx.tv.ui.components.PrimaryButton
|
||||||
@@ -147,7 +148,7 @@ fun WaveHero(state: AppState, big: Boolean, entry: FocusEntry?) {
|
|||||||
}
|
}
|
||||||
val (label, icon, action) = when (status) {
|
val (label, icon, action) = when (status) {
|
||||||
Status.Playing, Status.Loading -> Triple(R.string.action_pause, R.drawable.ic_pause_fill) { state.playback.toggle() }
|
Status.Playing, Status.Loading -> Triple(R.string.action_pause, R.drawable.ic_pause_fill) { state.playback.toggle() }
|
||||||
null -> Triple(R.string.wave_play, R.drawable.ic_play_fill) { state.playWave(MY_WAVE) }
|
null -> Triple(R.string.wave_play, R.drawable.ic_play_fill) { state.playWaveOpen(MY_WAVE) }
|
||||||
else -> Triple(R.string.action_resume, R.drawable.ic_play_fill) { state.playback.toggle() }
|
else -> Triple(R.string.action_resume, R.drawable.ic_play_fill) { state.playback.toggle() }
|
||||||
}
|
}
|
||||||
val shape = RoundedCornerShape(MusyxTheme.radius.hero)
|
val shape = RoundedCornerShape(MusyxTheme.radius.hero)
|
||||||
@@ -282,7 +283,7 @@ fun WaveScreen(state: AppState, entry: FocusEntry) {
|
|||||||
item(key = "stations-row") {
|
item(key = "stations-row") {
|
||||||
ShelfRow { first ->
|
ShelfRow { first ->
|
||||||
itemsIndexed(others, key = { _, s -> s.id }) { i, s ->
|
itemsIndexed(others, key = { _, s -> s.id }) { i, s ->
|
||||||
StationTile(s, playing = state.playback.state.waveStation == s.id, if (i == 0) first else Modifier) { state.playWave(s.id) }
|
StationTile(s, playing = state.playback.state.waveStation == s.id, if (i == 0) first else Modifier) { state.playWaveOpen(s.id) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import it.panov.musyx.tv.ui.components.CardGrid
|
|||||||
import it.panov.musyx.tv.ui.components.Chip
|
import it.panov.musyx.tv.ui.components.Chip
|
||||||
import it.panov.musyx.tv.ui.components.Failure
|
import it.panov.musyx.tv.ui.components.Failure
|
||||||
import it.panov.musyx.tv.ui.components.FocusEntry
|
import it.panov.musyx.tv.ui.components.FocusEntry
|
||||||
|
import it.panov.musyx.tv.ui.components.playWaveOpen
|
||||||
import it.panov.musyx.tv.ui.components.Note
|
import it.panov.musyx.tv.ui.components.Note
|
||||||
import it.panov.musyx.tv.ui.components.PlayBar
|
import it.panov.musyx.tv.ui.components.PlayBar
|
||||||
import it.panov.musyx.tv.ui.components.PrimaryButton
|
import it.panov.musyx.tv.ui.components.PrimaryButton
|
||||||
@@ -191,7 +192,7 @@ fun GenreScreen(state: AppState, index: Int, entry: FocusEntry) {
|
|||||||
Box(Modifier.weight(1f)) { ScreenTitle(genre.title) }
|
Box(Modifier.weight(1f)) { ScreenTitle(genre.title) }
|
||||||
PrimaryButton(
|
PrimaryButton(
|
||||||
stringResource(R.string.action_play_radio),
|
stringResource(R.string.action_play_radio),
|
||||||
onClick = { state.playWave("genre:${genre.id}") },
|
onClick = { state.playWaveOpen("genre:${genre.id}") },
|
||||||
icon = R.drawable.ic_audio_lines,
|
icon = R.drawable.ic_audio_lines,
|
||||||
modifier = Modifier.entry(entry),
|
modifier = Modifier.entry(entry),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -92,6 +92,7 @@ import it.panov.musyx.tv.ui.components.FocusEntry
|
|||||||
import it.panov.musyx.tv.ui.components.Focusable
|
import it.panov.musyx.tv.ui.components.Focusable
|
||||||
import it.panov.musyx.tv.ui.components.IconButton
|
import it.panov.musyx.tv.ui.components.IconButton
|
||||||
import it.panov.musyx.tv.ui.components.MusyxIcon
|
import it.panov.musyx.tv.ui.components.MusyxIcon
|
||||||
|
import it.panov.musyx.tv.ui.components.Note
|
||||||
import it.panov.musyx.tv.ui.components.PrimaryButton
|
import it.panov.musyx.tv.ui.components.PrimaryButton
|
||||||
import it.panov.musyx.tv.ui.components.Tab
|
import it.panov.musyx.tv.ui.components.Tab
|
||||||
import it.panov.musyx.tv.ui.components.TabBar
|
import it.panov.musyx.tv.ui.components.TabBar
|
||||||
@@ -108,6 +109,7 @@ internal fun noticeText(notice: Notice): String = when (notice) {
|
|||||||
Notice.StationDry -> stringResource(R.string.notice_station_dry)
|
Notice.StationDry -> stringResource(R.string.notice_station_dry)
|
||||||
Notice.TooManyFailures -> stringResource(R.string.notice_too_many)
|
Notice.TooManyFailures -> stringResource(R.string.notice_too_many)
|
||||||
is Notice.Skipped -> stringResource(R.string.notice_skipped, notice.title)
|
is Notice.Skipped -> stringResource(R.string.notice_skipped, notice.title)
|
||||||
|
Notice.NothingDownloaded -> stringResource(R.string.notice_nothing_downloaded)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The cover on the stage: as large as the stage's height allows under the transport. */
|
/** The cover on the stage: as large as the stage's height allows under the transport. */
|
||||||
@@ -122,6 +124,11 @@ fun NowPlayingScreen(state: AppState, entry: FocusEntry) {
|
|||||||
val c = MusyxTheme.colors
|
val c = MusyxTheme.colors
|
||||||
val space = MusyxTheme.space
|
val space = MusyxTheme.space
|
||||||
val track = p.track
|
val track = p.track
|
||||||
|
// A wave fetches its first track after the player opens: say so rather than "nothing".
|
||||||
|
if (track == null && p.status == Status.Loading) {
|
||||||
|
Note(stringResource(R.string.loading_wave), Modifier.padding(vertical = space.safeY))
|
||||||
|
return
|
||||||
|
}
|
||||||
if (track == null) {
|
if (track == null) {
|
||||||
Column(
|
Column(
|
||||||
Modifier.fillMaxSize().padding(horizontal = space.safeX, vertical = space.safeY),
|
Modifier.fillMaxSize().padding(horizontal = space.safeX, vertical = space.safeY),
|
||||||
|
|||||||
@@ -211,7 +211,8 @@ private fun ScreenSaver(state: AppState, track: Track, galleries: MutableMap<Lon
|
|||||||
)
|
)
|
||||||
// The caption changes sides with each photo, so nothing sits still on the panel.
|
// The caption changes sides with each photo, so nothing sits still on the panel.
|
||||||
// The lyrics ride with it, stacked right above the song name over a shade of their own.
|
// The lyrics ride with it, stacked right above the song name over a shade of their own.
|
||||||
Crossfade(slide.n % 2 == 0, animationSpec = tween(PHOTO_FADE_MS), label = "caption") { left ->
|
// always align right
|
||||||
|
Crossfade(/*slide.n % 2 == 0*/ false, animationSpec = tween(PHOTO_FADE_MS), label = "caption") { left ->
|
||||||
Box(Modifier.fillMaxSize()) {
|
Box(Modifier.fillMaxSize()) {
|
||||||
if (lyrics != null) {
|
if (lyrics != null) {
|
||||||
val shade = Color.Black.copy(alpha = 0.6f)
|
val shade = Color.Black.copy(alpha = 0.6f)
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!-- The aubergine gradient behind the launcher icon's waves. -->
|
||||||
|
<shape xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<gradient
|
||||||
|
android:angle="270"
|
||||||
|
android:endColor="#1C1A22"
|
||||||
|
android:startColor="#353042" />
|
||||||
|
</shape>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!-- Full-bleed layers, so launchers fill their icon shape instead of framing
|
||||||
|
the legacy PNG. Drawn by tool/make_icon.py in foreground mode. -->
|
||||||
|
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<background android:drawable="@drawable/ic_launcher_background" />
|
||||||
|
<foreground android:drawable="@mipmap/ic_launcher_foreground" />
|
||||||
|
<monochrome android:drawable="@mipmap/ic_launcher_foreground" />
|
||||||
|
</adaptive-icon>
|
||||||
|
Before Width: | Height: | Size: 6.1 KiB After Width: | Height: | Size: 4.7 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 3.3 KiB After Width: | Height: | Size: 2.6 KiB |
|
After Width: | Height: | Size: 7.0 KiB |
|
Before Width: | Height: | Size: 9.3 KiB After Width: | Height: | Size: 7.1 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 36 KiB |
|
Before Width: | Height: | Size: 23 KiB After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 56 KiB |
@@ -88,6 +88,7 @@
|
|||||||
<string name="loading_playlist">Загружаем плейлист…</string>
|
<string name="loading_playlist">Загружаем плейлист…</string>
|
||||||
<string name="loading_wave_settings">Загружаем настройки…</string>
|
<string name="loading_wave_settings">Загружаем настройки…</string>
|
||||||
<string name="loading_stations">Загружаем станции…</string>
|
<string name="loading_stations">Загружаем станции…</string>
|
||||||
|
<string name="loading_wave">Настраиваемся на волну…</string>
|
||||||
<string name="what_home">главную страницу</string>
|
<string name="what_home">главную страницу</string>
|
||||||
<string name="what_chart">чарт</string>
|
<string name="what_chart">чарт</string>
|
||||||
<string name="what_genres">жанры</string>
|
<string name="what_genres">жанры</string>
|
||||||
@@ -211,6 +212,7 @@
|
|||||||
<string name="notice_station_dry">Не удалось загрузить продолжение станции. Проверьте подключение и попробуйте ещё раз.</string>
|
<string name="notice_station_dry">Не удалось загрузить продолжение станции. Проверьте подключение и попробуйте ещё раз.</string>
|
||||||
<string name="notice_too_many">Несколько треков подряд не удалось воспроизвести. Проверьте подключение и попробуйте ещё раз.</string>
|
<string name="notice_too_many">Несколько треков подряд не удалось воспроизвести. Проверьте подключение и попробуйте ещё раз.</string>
|
||||||
<string name="notice_skipped">Не удалось воспроизвести «%1$s», трек пропущен.</string>
|
<string name="notice_skipped">Не удалось воспроизвести «%1$s», трек пропущен.</string>
|
||||||
|
<string name="notice_nothing_downloaded">Ни один трек в очереди не загружен. Подключитесь к интернету, чтобы их послушать.</string>
|
||||||
|
|
||||||
<string name="menu_next_track">Следующий трек</string>
|
<string name="menu_next_track">Следующий трек</string>
|
||||||
<string name="menu_play_next">Играть следующим</string>
|
<string name="menu_play_next">Играть следующим</string>
|
||||||
|
|||||||
@@ -95,6 +95,7 @@
|
|||||||
<string name="loading_playlist">Loading the playlist…</string>
|
<string name="loading_playlist">Loading the playlist…</string>
|
||||||
<string name="loading_wave_settings">Loading your settings…</string>
|
<string name="loading_wave_settings">Loading your settings…</string>
|
||||||
<string name="loading_stations">Loading stations…</string>
|
<string name="loading_stations">Loading stations…</string>
|
||||||
|
<string name="loading_wave">Tuning in…</string>
|
||||||
<string name="what_home">your home page</string>
|
<string name="what_home">your home page</string>
|
||||||
<string name="what_chart">the chart</string>
|
<string name="what_chart">the chart</string>
|
||||||
<string name="what_genres">genres</string>
|
<string name="what_genres">genres</string>
|
||||||
@@ -225,6 +226,7 @@
|
|||||||
<string name="notice_station_dry">Couldn\'t load more of this station. Check your connection and try again.</string>
|
<string name="notice_station_dry">Couldn\'t load more of this station. Check your connection and try again.</string>
|
||||||
<string name="notice_too_many">Several tracks in a row couldn\'t be played. Check your connection and try again.</string>
|
<string name="notice_too_many">Several tracks in a row couldn\'t be played. Check your connection and try again.</string>
|
||||||
<string name="notice_skipped">Couldn\'t play “%1$s”, so it was skipped.</string>
|
<string name="notice_skipped">Couldn\'t play “%1$s”, so it was skipped.</string>
|
||||||
|
<string name="notice_nothing_downloaded">None of the queued tracks are downloaded. Connect to the internet to play them.</string>
|
||||||
|
|
||||||
<!-- Track menu and dialogs -->
|
<!-- Track menu and dialogs -->
|
||||||
<string name="menu_next_track">Next track</string>
|
<string name="menu_next_track">Next track</string>
|
||||||
|
|||||||