diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2ccda069..609c16a8 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1,17 +1,55 @@
-# The TV app had no CI at all — only a release workflow — so a broken string
-# resource reached a device before anyone saw it. This is the cheap half of a
-# build: it runs in seconds and catches the failure that is invisible in review.
name: CI
+# The TV app had no CI at all — only a release workflow — so a broken string
+# resource reached a device before anyone saw it.
+#
+# It then had half a CI: a string check and a debug assemble. `app/src/test`
+# holds 218 unit tests across 36 files — the watch-party wire format, the
+# CloudStream extension parsing, the AniList matching, the history sync — and
+# not one of them was run by this pipeline. A green check on a pull request
+# said the resources merged and the app compiled, which is a much smaller claim
+# than anyone reading it took it to be. This now has the same shape as the
+# phone app's ci.yml: a string check, a TEST GATE, and a compile.
+#
+# `push` is the default branch only, with `pull_request` alongside it, which is
+# the pairing the phone app settled on: a branch with a pull request open is
+# covered by `pull_request`, a push straight to the default branch by `push`,
+# and nothing is covered twice.
+
on:
push:
branches: [master]
+ paths-ignore: ['apple-tv/**', 'webos/**', '.github/workflows/webos*.yml']
pull_request:
+ paths-ignore: ['apple-tv/**', 'webos/**', '.github/workflows/webos*.yml']
+ # release.yml runs the same gates before it builds; it skips the debug
+ # assemble because it builds a release APK right after.
+ workflow_call:
+ inputs:
+ skip_assemble:
+ type: boolean
+ default: false
+
+# A new push to a branch makes the run already in flight worthless, and these
+# jobs are not short — the Gradle ones were measured at five to six minutes.
+# Without this, pushing three times in ten minutes queues three full builds and
+# waits for all of them.
+#
+# github.workflow is the caller's name when release.yml calls this, so a push
+# to master cannot cancel the tests a release is waiting on.
+concurrency:
+ group: ci-${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+permissions:
+ contents: read
jobs:
strings:
name: Translated strings
runs-on: ubuntu-latest
+ # Seconds in practice; this is the hang budget, not the expected cost.
+ timeout-minutes: 10
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
@@ -22,9 +60,54 @@ jobs:
- name: Check the string resources
run: python3 tools/check_strings.py
+ # The gate the phone app has and this repo did not. Its own job, not a step
+ # inside the assemble, so that the check list on a pull request names "test"
+ # and a reader can see that the suite passed instead of inferring it from a
+ # job titled after a build.
+ #
+ # It is also the cheap half of the pair: `testDebugUnitTest` ran in 28 seconds
+ # here against a warm Gradle cache, against five to six minutes for the
+ # assemble, and the two run side by side — so a failing test is reported
+ # minutes before the compile it would otherwise have waited behind.
+ test:
+ name: Unit tests
+ runs-on: ubuntu-latest
+ timeout-minutes: 25
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-java@v4
+ with:
+ # app/build.gradle.kts compiles against JavaVersion.VERSION_17 and
+ # targets jvmTarget 17; this is read from the project, not chosen.
+ distribution: temurin
+ java-version: '17'
+ # Caching is left entirely to this action. setup-java can cache ~/.gradle
+ # too, and using both is explicitly discouraged because they manage the
+ # same directory and fight over it — so the dependency and build caches
+ # come from here, which is also what release.yml in this repo already
+ # relies on successfully.
+ - uses: gradle/actions/setup-gradle@v4
+ - name: Unit tests
+ run: ./gradlew :app:testDebugUnitTest --no-daemon
+ # The failure a test report gives you and the console does not: which
+ # assertion, with what values. Uploaded on failure only, because nobody
+ # opens it when the job is green.
+ - name: Keep the test report when something fails
+ if: failure()
+ uses: actions/upload-artifact@v4
+ with:
+ name: tv-unit-test-report
+ path: |
+ app/build/reports/tests/testDebugUnitTest
+ app/build/test-results/testDebugUnitTest
+ if-no-files-found: warn
+ retention-days: 14
+
build:
name: Assemble debug
+ if: ${{ !inputs.skip_assemble }}
runs-on: ubuntu-latest
+ timeout-minutes: 35
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
@@ -33,6 +116,9 @@ jobs:
java-version: '17'
- uses: gradle/actions/setup-gradle@v4
# `mergeDebugResources` is where a duplicate or badly named string
- # resource fails, and it fails for every locale at once.
+ # resource fails, and it fails for every locale at once. The unit tests
+ # above do not compile the Android resources at all, so this is still the
+ # only thing that catches a broken Gradle file, a missing native symbol
+ # or a plugin that will not build.
- name: Build
run: ./gradlew :app:assembleDebug --no-daemon
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index acd42c2f..aa30cf21 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -1,32 +1,28 @@
name: Release → Telegram
run-name: >-
- Release ${{ inputs.version != '' && inputs.version || inputs.bump || github.ref_name }}
+ Release ${{ inputs.version != '' && inputs.version || inputs.bump }}
-# Builds a signed Android TV APK and hands it to Telegram.
+# Builds a signed Android TV APK, then records it in git, uploads it to the
+# CDN, optionally offers it to the in-app updater, and sends it to Telegram.
+# Runs only from Actions → this workflow → Run workflow, on the default branch.
#
-# It NEVER touches GitHub Releases — cut those yourself if you want them. It runs
-# only when you ask:
-# * Actions → this workflow → Run workflow (pick how to raise the version)
-# * or on a version tag: git tag v11.0.0 && git push origin v11.0.0
+# Order: version + guard → tests → APK → bump commit, tag, GitHub Release →
+# CDN + updater → Telegram. Nothing is pushed or published until the APK built.
#
-# Required repo secrets (Settings → Secrets and variables → Actions):
+# Secrets:
# ANDROID_TV_KEYSTORE_B64 base64 of the release keystore (.jks)
-# ANDROID_TV_KEY_PROPERTIES contents of key.properties — storeFile,
-# storePassword, keyAlias, keyPassword
+# ANDROID_TV_KEY_PROPERTIES key.properties: storeFile, storePassword, keyAlias, keyPassword
+# RELEASE_PAT fine-grained PAT, Contents: read and write; the default
+# branch blocks direct pushes from GITHUB_TOKEN
+# SOZO_RELEASE_TOKEN backend release token (X-Release-Token); without it the
+# CDN upload and updater are skipped with a warning
# TELEGRAM_BOT_TOKEN bot token from @BotFather
-# RELEASE_PAT fine-grained PAT with Contents: read and write.
-# Required because the default branch blocks direct
-# pushes and GITHUB_TOKEN is not an admin.
-# TELEGRAM_CHAT_IDS comma-separated NUMERIC chat ids. The Bot API
-# cannot message a person by @username; each
-# recipient must press Start on the bot once.
+# TELEGRAM_CHAT_IDS comma-separated numeric chat ids
+# Optional variable: SOZO_API_BASE_URL overrides the API address baked into the app.
#
# The signing key was replaced on 22 Aug 2026 because the original was lost, and
-# the version line restarted at 1.0.0 with it. A different certificate cannot be
-# installed over an existing copy: anyone still running a pre-1.0.0 build gets
-# "package conflicts with an existing package" and has to uninstall first. The
-# build still verifies the fingerprint and refuses to ship anything signed by
-# another key — see EXPECTED_CERT_SHA256 below.
+# the version line restarted at 1.0.0 with it. Builds signed by any other key are
+# refused — see EXPECTED_CERT_SHA256 below.
on:
workflow_dispatch:
@@ -46,32 +42,56 @@ on:
type: string
required: false
notes:
- description: 'Release notes for the Telegram message'
+ description: 'Release notes (Telegram, CDN, updater, GitHub Release)'
type: string
required: false
- push:
- tags: ['v*']
+ updater:
+ description: 'Offer this build to the in-app updater'
+ type: choice
+ default: skip
+ options: [skip, publish]
+ github_release:
+ description: 'GitHub Release for the tag'
+ type: choice
+ default: draft
+ options: [draft, publish, skip]
+ skip_version_guard:
+ description: 'Proceed if the published version cannot be read (a readable one is always enforced)'
+ type: boolean
+ default: false
concurrency:
group: release-${{ github.ref }}
- cancel-in-progress: true
+ cancel-in-progress: false
+
+permissions:
+ contents: read
+
+env:
+ APK_CONTENT_TYPE: application/vnd.android.package-archive
jobs:
version:
runs-on: ubuntu-latest
+ timeout-minutes: 10
outputs:
name: ${{ steps.resolve.outputs.name }}
code: ${{ steps.resolve.outputs.code }}
tag: ${{ steps.resolve.outputs.tag }}
- sha: ${{ steps.sha.outputs.sha }}
+ bumped: ${{ steps.resolve.outputs.bumped }}
steps:
- - uses: actions/checkout@v4
+ - name: Refuse anything but the default branch
+ env:
+ DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
+ run: |
+ if [ "${GITHUB_REF}" != "refs/heads/${DEFAULT_BRANCH}" ]; then
+ echo "::error title=Wrong branch::Releases run only from ${DEFAULT_BRANCH}; this run was started from ${GITHUB_REF}."
+ exit 1
+ fi
+
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
- fetch-depth: 0
- # RELEASE_PAT is an admin token. The default GITHUB_TOKEN is not an
- # admin, so the version-bump push below is rejected by the branch
- # ruleset that blocks direct pushes to the default branch.
- token: ${{ secrets.RELEASE_PAT || github.token }}
+ persist-credentials: false
- name: Resolve version
id: resolve
@@ -91,41 +111,47 @@ jobs:
if [ -z "${NAME}" ]; then
echo "::error title=Malformed versionName::could not read it from ${GRADLE}"; exit 1
fi
-
echo "::notice title=Current version::${NAME} (versionCode ${CODE})"
- if [ "${GITHUB_EVENT_NAME}" != "workflow_dispatch" ]; then
- echo "Tag build — using the committed version verbatim."
- NEW_NAME="${NAME}"
- NEW_CODE="${CODE}"
- BUMPED=no
- else
- IFS=. read -r MA MI PA <<< "${NAME}"
- MA="${MA:-0}"; MI="${MI:-0}"; PA="${PA:-0}"
- NEW_CODE="$((CODE + 1))"
-
- if [ -n "${EXPLICIT}" ]; then
- case "${EXPLICIT}" in
- *[!0-9.]*) echo "::error title=Bad version::'${EXPLICIT}' must be digits and dots only, e.g. 11.0.0"; exit 1 ;;
- esac
- NEW_NAME="${EXPLICIT}"
- BUMPED=yes
- else
- case "${BUMP}" in
- patch) NEW_NAME="${MA}.${MI}.$((PA + 1))"; BUMPED=yes ;;
- minor) NEW_NAME="${MA}.$((MI + 1)).0"; BUMPED=yes ;;
- major) NEW_NAME="$((MA + 1)).0.0"; BUMPED=yes ;;
- code-only) NEW_NAME="${NAME}"; BUMPED=yes ;;
- none) NEW_NAME="${NAME}"; NEW_CODE="${CODE}"; BUMPED=no ;;
- *) echo "::error title=Unknown bump::'${BUMP}'"; exit 1 ;;
- esac
+ IFS=. read -r MA MI PA <<< "${NAME}"
+ MA="${MA:-0}"; MI="${MI:-0}"; PA="${PA:-0}"
+ NEW_CODE="$((CODE + 1))"
+ BUMPED=yes
+
+ if [ -n "${EXPLICIT}" ]; then
+ if ! [[ "${EXPLICIT}" =~ ^[0-9]+(\.[0-9]+){0,3}$ ]]; then
+ echo "::error title=Bad version::'${EXPLICIT}' must be numbers separated by dots, e.g. 11.0.0"; exit 1
fi
+ NEW_NAME="${EXPLICIT}"
+ else
+ case "${BUMP}" in
+ patch) NEW_NAME="${MA}.${MI}.$((PA + 1))" ;;
+ minor) NEW_NAME="${MA}.$((MI + 1)).0" ;;
+ major) NEW_NAME="$((MA + 1)).0.0" ;;
+ code-only) NEW_NAME="${NAME}" ;;
+ none) NEW_NAME="${NAME}"; NEW_CODE="${CODE}"; BUMPED=no ;;
+ *) echo "::error title=Unknown bump::'${BUMP}'"; exit 1 ;;
+ esac
+ fi
+
+ TAG="v${NEW_NAME}"
+ # Same name, new versionCode (code-only, or none after a hand-edited
+ # code): the plain name tag is taken, so the code goes into the tag.
+ if [ "${NEW_NAME}" = "${NAME}" ] \
+ && git ls-remote --exit-code --tags origin "refs/tags/${TAG}" >/dev/null 2>&1; then
+ TAG="v${NEW_NAME}-${NEW_CODE}"
+ fi
+ if git ls-remote --exit-code --tags origin "refs/tags/${TAG}" >/dev/null 2>&1; then
+ echo "::error title=Tag exists::${TAG} is already published. Pick a different bump, or delete the tag first."
+ exit 1
fi
- echo "name=${NEW_NAME}" >> "$GITHUB_OUTPUT"
- echo "code=${NEW_CODE}" >> "$GITHUB_OUTPUT"
- echo "tag=v${NEW_NAME}" >> "$GITHUB_OUTPUT"
- echo "bumped=${BUMPED}" >> "$GITHUB_OUTPUT"
+ {
+ echo "name=${NEW_NAME}"
+ echo "code=${NEW_CODE}"
+ echo "tag=${TAG}"
+ echo "bumped=${BUMPED}"
+ } >> "$GITHUB_OUTPUT"
{
echo "### Release version"
echo ""
@@ -133,126 +159,86 @@ jobs:
echo "|---|---|---|"
echo "| was | \`${NAME}\` | \`${CODE}\` |"
echo "| now | \`${NEW_NAME}\` | \`${NEW_CODE}\` |"
- echo ""
- echo "Publish \`versionCode ${NEW_CODE}\` on the admin panel under platform **androidtv** for the in-app updater to offer it."
} >> "$GITHUB_STEP_SUMMARY"
-
echo "::notice title=Releasing::${NEW_NAME} (versionCode ${NEW_CODE})"
- - name: Commit and tag
- id: commit
- if: steps.resolve.outputs.bumped == 'yes'
+ # Devices only install an update whose versionCode is higher than what
+ # they run, so shipping one that is not higher than the published row
+ # is a release nobody receives.
+ - name: Check versionCode against the published one
env:
- NAME: ${{ steps.resolve.outputs.name }}
- CODE: ${{ steps.resolve.outputs.code }}
- TAG: ${{ steps.resolve.outputs.tag }}
+ NEW_CODE: ${{ steps.resolve.outputs.code }}
+ SKIP_GUARD: ${{ inputs.skip_version_guard }}
+ SOZO_API_BASE_URL: ${{ vars.SOZO_API_BASE_URL }}
run: |
set -euo pipefail
-
- if git rev-parse -q --verify "refs/tags/${TAG}" >/dev/null || \
- git ls-remote --exit-code --tags origin "${TAG}" >/dev/null 2>&1; then
- echo "::error title=Tag exists::${TAG} is already published. Pick a different bump, or delete the tag first."
+ API="$(python3 tools/release/api_base.py)" || API=""
+ if [ -z "${API}" ]; then
+ if [ "${SKIP_GUARD}" = true ]; then
+ echo "::warning title=Version guard skipped::Could not work out the API base; continuing because skip_version_guard is set."
+ exit 0
+ fi
+ echo "::error title=Version guard::Could not work out the API base from app/build.gradle.kts or vars.SOZO_API_BASE_URL."
exit 1
fi
+ echo "::add-mask::${API}"
+
+ HTTP="$(curl -sS --max-time 20 --retry 3 --retry-all-errors \
+ -A 'sozo-tv-release' -o version.json -w '%{http_code}' \
+ "${API}/app-version?platform=androidtv")" || HTTP=000
+ PUBLISHED=""
+ if [ "${HTTP}" = 200 ]; then
+ PUBLISHED="$(jq -er '.version // 0' version.json 2>/dev/null)" || PUBLISHED=""
+ fi
+ case "${PUBLISHED}" in
+ ''|*[!0-9]*)
+ if [ "${SKIP_GUARD}" = true ]; then
+ echo "::warning title=Version guard skipped::Could not read the published Android TV version (HTTP ${HTTP}); continuing because skip_version_guard is set."
+ exit 0
+ fi
+ echo "::error title=Version guard::Could not read the published Android TV version (GET /api/app-version?platform=androidtv, HTTP ${HTTP}). Re-run with skip_version_guard only if you know versionCode ${NEW_CODE} is higher than the published one."
+ exit 1
+ ;;
+ esac
- python3 - "${NAME}" "${CODE}" <<'PY'
- import re, sys
- name, code = sys.argv[1], sys.argv[2]
- path = 'app/build.gradle.kts'
- src = open(path, encoding='utf-8').read()
- src, n1 = re.subn(r'(?m)^(\s*versionCode\s*=\s*)\d+', rf'\g<1>{code}', src, count=1)
- src, n2 = re.subn(r'(?m)^(\s*versionName\s*=\s*)"[^"]*"', rf'\g<1>"{name}"', src, count=1)
- if n1 != 1 or n2 != 1:
- sys.exit(f'expected one versionCode and one versionName, replaced {n1}/{n2}')
- open(path, 'w', encoding='utf-8').write(src)
- PY
- grep -E '^\s*version(Code|Name)\s*=' app/build.gradle.kts
-
- git config user.name "${GITHUB_ACTOR}"
- git config user.email "${GITHUB_ACTOR}@users.noreply.github.com"
- git commit -am "chore: ${NAME} (${CODE})"
- git tag "${TAG}"
-
- # A rejected push must not cancel the release.
- #
- # The default branch is protected and GITHUB_TOKEN is not an admin, so
- # without a RELEASE_PAT this push is refused — and refusing to build
- # because a bookkeeping commit could not land is the wrong trade. The
- # version is already resolved and already written into the working
- # tree, so the build below ships exactly the version it says it does.
- # What is lost is the record in git, which is worth a loud warning and
- # nothing more.
- if git push origin HEAD:"${GITHUB_REF_NAME}"; then
- git push origin "${TAG}" || echo "::warning title=Tag not pushed::${TAG} could not be pushed."
- echo "pushed=yes" >> "$GITHUB_OUTPUT"
- else
- git tag -d "${TAG}" || true
- echo "pushed=no" >> "$GITHUB_OUTPUT"
- echo "::warning title=Version bump not committed::The default branch is protected and this run is not an admin, so ${NAME} was NOT written back to git — this build still ships as ${NAME}, but the repo still says the old one. Add a RELEASE_PAT secret (fine-grained PAT, Contents: read and write) to close the gap."
- {
- echo "### ⚠️ Version bump was not committed"
- echo ""
- echo "This build ships as **${NAME}**, but the repository still records the previous version."
- echo "Add a \`RELEASE_PAT\` secret (fine-grained PAT with **Contents: read and write**) so the bump can land."
- } >> "$GITHUB_STEP_SUMMARY"
- fi
-
- # The build must check out a commit the remote actually has.
- #
- # When the bump could not be pushed, the commit exists only on this
- # runner — checking it out in the next job fails with "reference is not a
- # tree", which is a far more confusing failure than the rejected push it
- # came from. So: the pushed commit when there is one, otherwise the commit
- # the run started from, and the build applies the version itself.
- - name: Record the commit the build job will use
- id: sha
- run: |
- set -euo pipefail
- if [ "${{ steps.commit.outputs.pushed }}" = "yes" ]; then
- echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
- else
- echo "sha=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
+ if [ "${NEW_CODE}" -le "${PUBLISHED}" ]; then
+ echo "::error title=versionCode not higher::This build would be versionCode ${NEW_CODE}, but ${PUBLISHED} is already published. Devices would never be offered it. Commit a higher versionCode in app/build.gradle.kts first."
+ exit 1
fi
+ echo "::notice title=Version guard::versionCode ${NEW_CODE} > published ${PUBLISHED}"
- apk:
+ ci:
needs: version
+ uses: ./.github/workflows/ci.yml
+ with:
+ skip_assemble: true
+
+ apk:
+ needs: [version, ci]
runs-on: ubuntu-latest
timeout-minutes: 60
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
- ref: ${{ needs.version.outputs.sha }}
+ persist-credentials: false
- # Applied here rather than trusted from the checkout. When the bump could
- # not be committed, the checked-out tree still carries the OLD version —
- # and an apk whose versionCode disagrees with the release it was cut as is
- # invisible to the in-app updater. Idempotent: a no-op when the commit did
- # land.
+ # The bump is committed only after this build succeeds, so the checkout
+ # still carries the old version; the git job applies the same stamp.
- name: Stamp the resolved version into the build
env:
NAME: ${{ needs.version.outputs.name }}
CODE: ${{ needs.version.outputs.code }}
run: |
set -euo pipefail
- python3 - "$NAME" "$CODE" <<'PY'
- import re, sys
- name, code = sys.argv[1], sys.argv[2]
- path = 'app/build.gradle.kts'
- src = open(path, encoding='utf-8').read()
- src, n1 = re.subn(r'(?m)^(\s*versionCode\s*=\s*)\d+', rf'\g<1>{code}', src, count=1)
- src, n2 = re.subn(r'(?m)^(\s*versionName\s*=\s*)"[^"]*"', rf'\g<1>"{name}"', src, count=1)
- if n1 != 1 or n2 != 1:
- sys.exit(f'expected one versionCode and one versionName, replaced {n1}/{n2}')
- open(path, 'w', encoding='utf-8').write(src)
- PY
+ python3 tools/release/stamp_version.py "${NAME}" "${CODE}"
grep -E '^\s*version(Code|Name)\s*=' app/build.gradle.kts
- - uses: actions/setup-java@v4
+ - uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1
with:
distribution: temurin
java-version: '17'
- - uses: gradle/actions/setup-gradle@v4
+ - uses: gradle/actions/setup-gradle@ed408507eac070d1f99cc633dbcf757c94c7933a # v4.4.3
- name: Restore signing key
env:
@@ -277,7 +263,7 @@ jobs:
run: |
set -euo pipefail
APKSIGNER="$(find "${ANDROID_HOME:-$ANDROID_SDK_ROOT}/build-tools" -name apksigner | sort | tail -1)"
- APK="$(ls app/build/outputs/apk/release/*.apk | head -1)"
+ APK="$(find app/build/outputs/apk/release -name '*.apk' | head -1)"
CERTS="$("$APKSIGNER" verify --print-certs "$APK")"
echo "$CERTS"
@@ -292,14 +278,14 @@ jobs:
fi
echo "::notice title=Signature::matches the certificate already on devices"
- - name: Report the version inside the APK
+ - name: Check the version inside the APK
env:
EXPECTED_CODE: ${{ needs.version.outputs.code }}
EXPECTED_NAME: ${{ needs.version.outputs.name }}
run: |
set -euo pipefail
AAPT="$(find "${ANDROID_HOME:-$ANDROID_SDK_ROOT}/build-tools" -name aapt2 | sort | tail -1)"
- APK="$(ls app/build/outputs/apk/release/*.apk | head -1)"
+ APK="$(find app/build/outputs/apk/release -name '*.apk' | head -1)"
LINE="$("$AAPT" dump badging "$APK" | head -1)"
CODE="$(echo "$LINE" | grep -oE "versionCode='[0-9]+'" | grep -oE '[0-9]+')"
NAME="$(echo "$LINE" | grep -oE "versionName='[^']*'" | cut -d"'" -f2)"
@@ -315,47 +301,303 @@ jobs:
echo "- signature verified against the certificate already on devices"
} >> "$GITHUB_STEP_SUMMARY"
- - name: Name the APK after its version
+ - name: Name the APK after its version and checksum it
env:
NAME: ${{ needs.version.outputs.name }}
CODE: ${{ needs.version.outputs.code }}
run: |
set -euo pipefail
mkdir -p dist
- cp "$(ls app/build/outputs/apk/release/*.apk | head -1)" \
+ cp "$(find app/build/outputs/apk/release -name '*.apk' | head -1)" \
"dist/sozo-tv-${NAME}-${CODE}.apk"
+ (cd dist && sha256sum ./*.apk | sed 's# \./# #' > SHA256SUMS)
+ cat dist/SHA256SUMS
ls -lh dist
- - uses: actions/upload-artifact@v4
+ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: sozo-tv-apk
- path: dist/*.apk
+ path: |
+ dist/*.apk
+ dist/SHA256SUMS
if-no-files-found: error
- deliver:
+ git:
+ name: Commit, tag and GitHub Release
needs: [version, apk]
- # Always, even when the build failed. A release that goes quiet is
- # indistinguishable from one nobody started, and the whole point of this job
- # is that somebody finds out.
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ permissions:
+ contents: write
+ outputs:
+ sha: ${{ steps.tag.outputs.sha }}
+ release: ${{ steps.release.outputs.status }}
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
+ with:
+ fetch-depth: 0
+ token: ${{ secrets.RELEASE_PAT || github.token }}
+
+ - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
+ with:
+ name: sozo-tv-apk
+ path: dist
+
+ - name: Commit the bump and push the tag
+ id: tag
+ env:
+ NAME: ${{ needs.version.outputs.name }}
+ CODE: ${{ needs.version.outputs.code }}
+ TAG: ${{ needs.version.outputs.tag }}
+ BUMPED: ${{ needs.version.outputs.bumped }}
+ DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
+ run: |
+ set -euo pipefail
+
+ # A re-run of this job after the tag already landed reuses it.
+ if git ls-remote --exit-code --tags origin "refs/tags/${TAG}" >/dev/null 2>&1; then
+ git fetch -q origin "refs/tags/${TAG}:refs/tags/${TAG}"
+ echo "sha=$(git rev-parse "${TAG}^{commit}")" >> "$GITHUB_OUTPUT"
+ echo "::notice title=Tag already pushed::${TAG} exists; reusing it."
+ exit 0
+ fi
+
+ git config user.name "${GITHUB_ACTOR}"
+ git config user.email "${GITHUB_ACTOR}@users.noreply.github.com"
+ if [ "${BUMPED}" = yes ]; then
+ python3 tools/release/stamp_version.py "${NAME}" "${CODE}"
+ git commit -m "chore: ${NAME} (${CODE})" -- app/build.gradle.kts
+ fi
+ git tag "${TAG}"
+ SHA="$(git rev-parse HEAD)"
+
+ # The tag carries the exact tree that was built, so it is the record
+ # that must land. The branch may have moved since the run started.
+ git push origin "refs/tags/${TAG}"
+ echo "sha=${SHA}" >> "$GITHUB_OUTPUT"
+
+ if [ "${BUMPED}" = yes ]; then
+ if git push origin "HEAD:refs/heads/${DEFAULT_BRANCH}"; then
+ echo "::notice title=Version bump committed::${NAME} (${CODE}) on ${DEFAULT_BRANCH}"
+ else
+ echo "::warning title=Version bump not on ${DEFAULT_BRANCH}::The push was rejected (branch moved, or no RELEASE_PAT). ${TAG} records the build, but ${DEFAULT_BRANCH} still has the old versionCode; commit ${CODE} or higher before the next release, or the version guard will stop it."
+ fi
+ fi
+
+ - name: GitHub Release
+ id: release
+ env:
+ GH_TOKEN: ${{ github.token }}
+ GH_REPO: ${{ github.repository }}
+ MODE: ${{ inputs.github_release }}
+ NAME: ${{ needs.version.outputs.name }}
+ CODE: ${{ needs.version.outputs.code }}
+ TAG: ${{ needs.version.outputs.tag }}
+ SHA: ${{ steps.tag.outputs.sha }}
+ NOTES: ${{ inputs.notes }}
+ run: |
+ set -euo pipefail
+ if [ "${MODE}" = skip ]; then
+ echo "status=skipped" >> "$GITHUB_OUTPUT"
+ exit 0
+ fi
+
+ FILES=(dist/*.apk dist/SHA256SUMS)
+ if gh release view "${TAG}" >/dev/null 2>&1; then
+ gh release upload "${TAG}" "${FILES[@]}" --clobber
+ else
+ ARGS=(--target "${SHA}" --title "Sozo TV ${NAME}" --notes "${NOTES:-Sozo TV ${NAME} (versionCode ${CODE})}")
+ if [ "${MODE}" = draft ]; then
+ ARGS+=(--draft)
+ fi
+ gh release create "${TAG}" "${FILES[@]}" "${ARGS[@]}"
+ fi
+ if [ "${MODE}" = draft ]; then
+ echo "status=draft" >> "$GITHUB_OUTPUT"
+ else
+ echo "status=published" >> "$GITHUB_OUTPUT"
+ fi
+
+ publish:
+ name: CDN and in-app updater
+ needs: [version, apk, git]
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ outputs:
+ cdn: ${{ steps.cdn.outputs.status }}
+ cdn_url: ${{ steps.cdn.outputs.url }}
+ updater: ${{ steps.updater.outputs.status }}
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
+ with:
+ persist-credentials: false
+ sparse-checkout: |
+ tools/release
+ app/build.gradle.kts
+ sparse-checkout-cone-mode: false
+
+ - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
+ with:
+ name: sozo-tv-apk
+ path: dist
+
+ # Not idempotent: re-running this job after the download row was created
+ # uploads again and adds a second active androidtv row; switch the extra
+ # one off in the admin panel.
+ - name: Upload to the CDN
+ id: cdn
+ env:
+ SOZO_RELEASE_TOKEN: ${{ secrets.SOZO_RELEASE_TOKEN }}
+ SOZO_API_BASE_URL: ${{ vars.SOZO_API_BASE_URL }}
+ NAME: ${{ needs.version.outputs.name }}
+ NOTES: ${{ inputs.notes }}
+ run: |
+ set -euo pipefail
+ if [ -z "${SOZO_RELEASE_TOKEN}" ]; then
+ echo "status=skipped" >> "$GITHUB_OUTPUT"
+ echo "::warning title=CDN skipped::SOZO_RELEASE_TOKEN is not set, so the APK was not uploaded to the CDN and the updater was not touched."
+ exit 0
+ fi
+ API="$(python3 tools/release/api_base.py)"
+ echo "::add-mask::${API}"
+
+ APK="$(find dist -name '*.apk' | head -1)"
+ SIZE="$(stat -c%s "${APK}")"
+
+ jq -n --arg filename "$(basename "${APK}")" --arg ct "${APK_CONTENT_TYPE}" \
+ --arg version "${NAME}" --argjson size "${SIZE}" \
+ '{platform: "androidtv", filename: $filename, contentType: $ct,
+ size: $size, version: $version, arch: "universal"}' > presign-req.json
+ HTTP="$(curl -sS --max-time 30 -X POST "${API}/admin/downloads/upload-url" \
+ -H "X-Release-Token: ${SOZO_RELEASE_TOKEN}" -H 'Content-Type: application/json' \
+ --data @presign-req.json -o presign.json -w '%{http_code}')" || HTTP=000
+ if [ "${HTTP}" != 200 ]; then
+ echo "::error title=CDN upload URL::POST /admin/downloads/upload-url returned HTTP ${HTTP}: $(head -c 300 presign.json 2>/dev/null)"
+ exit 1
+ fi
+ UPLOAD_URL="$(jq -er .uploadUrl presign.json)"
+ echo "::add-mask::${UPLOAD_URL}"
+ KEY="$(jq -er .key presign.json)"
+ PUBLIC_URL="$(jq -er .publicUrl presign.json)"
+
+ # Content-Type is part of the signature: it must match what was presigned.
+ HTTP="$(curl -sS --max-time 900 --upload-file "${APK}" \
+ -H "Content-Type: ${APK_CONTENT_TYPE}" \
+ -o put.txt -w '%{http_code}' "${UPLOAD_URL}")" || HTTP=000
+ if [ "${HTTP}" != 200 ]; then
+ echo "::error title=CDN upload::PUT to R2 returned HTTP ${HTTP}: $(head -c 300 put.txt 2>/dev/null)"
+ exit 1
+ fi
+
+ jq -n --arg version "${NAME}" --arg url "${PUBLIC_URL}" --arg key "${KEY}" \
+ --argjson size "${SIZE}" --arg notes "${NOTES}" \
+ '{platform: "androidtv", version: $version, arch: "universal", format: "apk",
+ fileUrl: $url, fileKey: $key, fileSize: $size, releaseNotes: $notes,
+ isBeta: false, active: true}' > download-req.json
+ HTTP="$(curl -sS --max-time 30 -X POST "${API}/admin/downloads" \
+ -H "X-Release-Token: ${SOZO_RELEASE_TOKEN}" -H 'Content-Type: application/json' \
+ --data @download-req.json -o download.json -w '%{http_code}')" || HTTP=000
+ if [ "${HTTP}" != 201 ]; then
+ echo "::error title=Download row::POST /admin/downloads returned HTTP ${HTTP}: $(head -c 300 download.json 2>/dev/null). The file is on the CDN at ${PUBLIC_URL} but not listed."
+ exit 1
+ fi
+
+ {
+ echo "status=uploaded"
+ echo "url=${PUBLIC_URL}"
+ } >> "$GITHUB_OUTPUT"
+ echo "### CDN" >> "$GITHUB_STEP_SUMMARY"
+ echo "- ${PUBLIC_URL}" >> "$GITHUB_STEP_SUMMARY"
+
+ # The PUT replaces the whole row, so the current row is read first and
+ # only version, downloadUrl and releaseNotes change.
+ - name: Publish to the in-app updater
+ id: updater
+ env:
+ MODE: ${{ inputs.updater }}
+ CDN: ${{ steps.cdn.outputs.status }}
+ URL: ${{ steps.cdn.outputs.url }}
+ CODE: ${{ needs.version.outputs.code }}
+ NOTES: ${{ inputs.notes }}
+ SOZO_RELEASE_TOKEN: ${{ secrets.SOZO_RELEASE_TOKEN }}
+ SOZO_API_BASE_URL: ${{ vars.SOZO_API_BASE_URL }}
+ run: |
+ set -euo pipefail
+ if [ "${MODE}" != publish ]; then
+ echo "status=skipped" >> "$GITHUB_OUTPUT"
+ exit 0
+ fi
+ if [ "${CDN}" != uploaded ]; then
+ echo "status=skipped (no CDN upload)" >> "$GITHUB_OUTPUT"
+ echo "::warning title=Updater skipped::updater=publish needs the CDN upload, which did not happen (SOZO_RELEASE_TOKEN missing)."
+ exit 0
+ fi
+ API="$(python3 tools/release/api_base.py)"
+ echo "::add-mask::${API}"
+
+ HTTP="$(curl -sS --max-time 30 "${API}/admin/app-versions/androidtv" \
+ -H "X-Release-Token: ${SOZO_RELEASE_TOKEN}" \
+ -o current.json -w '%{http_code}')" || HTTP=000
+ case "${HTTP}" in
+ 200) ;;
+ 404) echo '{"minVersion": 1, "forceUpdate": false, "active": true}' > current.json ;;
+ *)
+ echo "::error title=Updater read::GET /admin/app-versions/androidtv returned HTTP ${HTTP}: $(head -c 300 current.json 2>/dev/null)"
+ exit 1
+ ;;
+ esac
+
+ jq --argjson code "${CODE}" --arg url "${URL}" --arg notes "${NOTES}" \
+ '{version: $code,
+ minVersion: (.minVersion // 1),
+ downloadUrl: $url,
+ storeUrl: null, # the backend refuses a storeUrl from the release token
+ releaseNotes: $notes,
+ forceUpdate: (.forceUpdate // false),
+ active: (.active != false)}' current.json > updater-req.json
+ if [ "$(jq -r .active updater-req.json)" != true ]; then
+ echo "::warning title=Updater row inactive::The androidtv row is switched off in the admin panel and stays off; devices will not be offered ${CODE} until it is switched on."
+ fi
+
+ HTTP="$(curl -sS --max-time 30 -X PUT "${API}/admin/app-versions/androidtv" \
+ -H "X-Release-Token: ${SOZO_RELEASE_TOKEN}" -H 'Content-Type: application/json' \
+ --data @updater-req.json -o updated.json -w '%{http_code}')" || HTTP=000
+ if [ "${HTTP}" != 200 ]; then
+ echo "::error title=Updater write::PUT /admin/app-versions/androidtv returned HTTP ${HTTP}: $(head -c 300 updated.json 2>/dev/null)"
+ exit 1
+ fi
+ echo "status=published" >> "$GITHUB_OUTPUT"
+ echo "::notice title=Updater::androidtv now offers versionCode ${CODE}"
+
+ deliver:
+ needs: [version, apk, git, publish]
+ # Always, even when something failed: a release that goes quiet is
+ # indistinguishable from one nobody started.
if: ${{ always() && !cancelled() }}
runs-on: ubuntu-latest
+ timeout-minutes: 15
steps:
# Not fatal: when the build failed there is no artifact, and the message
- # saying so is exactly what this job now exists to send.
- - uses: actions/download-artifact@v4
+ # saying so is what this job is for.
+ - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
continue-on-error: true
with:
name: sozo-tv-apk
path: dist
- name: Send to Telegram
- if: always()
env:
TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
TELEGRAM_CHAT_IDS: ${{ secrets.TELEGRAM_CHAT_IDS }}
VERSION_NAME: ${{ needs.version.outputs.name }}
VERSION_CODE: ${{ needs.version.outputs.code }}
RELEASE_NOTES: ${{ inputs.notes }}
+ GIT_RESULT: ${{ needs.git.result }}
+ PUBLISH_RESULT: ${{ needs.publish.result }}
+ CDN_STATUS: ${{ needs.publish.outputs.cdn }}
+ CDN_URL: ${{ needs.publish.outputs.cdn_url }}
+ UPDATER_STATUS: ${{ needs.publish.outputs.updater }}
+ RELEASE_STATUS: ${{ needs.git.outputs.release }}
run: |
set -uo pipefail
@@ -367,13 +609,11 @@ jobs:
API="https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}"
MAX=$((49 * 1024 * 1024)) # Bot API sendDocument limit is 50 MB
RUN_URL="${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}"
+ IFS=',' read -ra CHATS <<< "${TELEGRAM_CHAT_IDS}"
- # Nothing built. Say that, rather than announcing a version that does
- # not exist and attaching nothing to it.
if ! ls dist/*.apk >/dev/null 2>&1; then
MSG="$(printf '⚠️ Sozo TV %s — release YIQILDI, APK chiqmadi.\n\n🔎 %s' \
"${VERSION_NAME:-?}" "${RUN_URL}")"
- IFS=',' read -ra CHATS <<< "${TELEGRAM_CHAT_IDS}"
for raw in "${CHATS[@]}"; do
chat="$(echo "${raw}" | xargs)"
[ -z "${chat}" ] && continue
@@ -386,16 +626,36 @@ jobs:
exit 0
fi
+ if [ "${PUBLISH_RESULT}" = success ]; then
+ case "${CDN_STATUS}" in
+ uploaded) CDN_LINE="⬇️ CDN: ${CDN_URL}" ;;
+ *) CDN_LINE="⬇️ CDN: o'tkazib yuborildi (SOZO_RELEASE_TOKEN yo'q)" ;;
+ esac
+ case "${UPDATER_STATUS}" in
+ published) UPD_LINE="🔄 Updater: versionCode ${VERSION_CODE} e'lon qilindi" ;;
+ *) UPD_LINE="🔄 Updater: e'lon qilinmadi (${UPDATER_STATUS:-skipped})" ;;
+ esac
+ else
+ CDN_LINE="⚠️ CDN/updater: bajarilmadi (${PUBLISH_RESULT})"
+ UPD_LINE=""
+ fi
+ if [ "${GIT_RESULT}" = success ]; then
+ GH_LINE="🏷 GitHub Release: ${RELEASE_STATUS:-skipped}"
+ else
+ GH_LINE="⚠️ Tag/GitHub Release: bajarilmadi (${GIT_RESULT})"
+ fi
+
HEAD="$(printf '📺 Sozo TV %s (versionCode %s)' "${VERSION_NAME}" "${VERSION_CODE}")"
if [ -n "${RELEASE_NOTES}" ]; then
HEAD="$(printf '%s\n\n📝 %s' "${HEAD}" "${RELEASE_NOTES}")"
fi
- HEAD="$(printf '%s\n\n⚙️ Ichki updater buni ko'"'"'rishi uchun admin panelda platforma **androidtv** ostida versionCode %s ni e'"'"'lon qiling.' \
- "${HEAD}" "${VERSION_CODE}")"
- HEAD="$(printf '%s\n\n🧰 Run: %s' "${HEAD}" "${RUN_URL}")"
+ HEAD="$(printf '%s\n\n%s' "${HEAD}" "${CDN_LINE}")"
+ if [ -n "${UPD_LINE}" ]; then
+ HEAD="$(printf '%s\n%s' "${HEAD}" "${UPD_LINE}")"
+ fi
+ HEAD="$(printf '%s\n%s\n\n🧰 Run: %s' "${HEAD}" "${GH_LINE}" "${RUN_URL}")"
fail=0
- IFS=',' read -ra CHATS <<< "${TELEGRAM_CHAT_IDS}"
for raw in "${CHATS[@]}"; do
chat="$(echo "${raw}" | xargs)"
[ -z "${chat}" ] && continue
diff --git a/.github/workflows/tvos-ci.yml b/.github/workflows/tvos-ci.yml
new file mode 100644
index 00000000..c664215a
--- /dev/null
+++ b/.github/workflows/tvos-ci.yml
@@ -0,0 +1,97 @@
+name: Apple TV CI
+
+# `push` is the default branch only. It had no branch filter, and with
+# `pull_request` alongside it every push to a branch with a pull request open
+# ran this whole thing TWICE. On 2 Nov that was runs 41400668675 (push) and
+# 41400672636 (pull_request) on the same commit, 21 and 18 minutes — and this
+# job is on `macos-26`, which GitHub bills at TEN TIMES the Linux rate. So one
+# push to this branch cost about 390 billed minutes where 210 would have done,
+# and did it by booting a tvOS simulator and running the identical suite twice.
+#
+# The pair still covers everything between them: a branch with a pull request
+# is covered by `pull_request`, a push straight to the default branch by
+# `push`. A branch with no pull request yet now gets no Apple TV CI, which is
+# the state where nobody is waiting on a verdict — and `workflow_dispatch`
+# below is there for when somebody is.
+on:
+ push:
+ branches: [master]
+ paths: ['apple-tv/**', '.github/workflows/tvos-*.yml']
+ pull_request:
+ paths: ['apple-tv/**', '.github/workflows/tvos-*.yml']
+ workflow_dispatch:
+ inputs:
+ xcode_version:
+ description: 'Xcode on the runner: exact (26.1) or newest of a major (26)'
+ default: '26'
+ type: string
+ workflow_call:
+ inputs:
+ xcode_version:
+ default: '26'
+ type: string
+permissions:
+ contents: read
+concurrency:
+ group: tvos-ci-${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+jobs:
+ verify:
+ name: tvOS Foundation, remote UI and signed Release
+ runs-on: macos-26
+ timeout-minutes: 45
+ env:
+ HOMEBREW_NO_AUTO_UPDATE: '1'
+ HOMEBREW_NO_INSTALL_CLEANUP: '1'
+ HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK: '1'
+ SOZO_BREW_TOOLS: xcodegen ffmpeg actionlint shellcheck
+ steps:
+ - uses: actions/checkout@v4
+ # push/pull_request runs have no inputs; '26' must match the input defaults above.
+ - name: Select Xcode
+ env:
+ XCODE_VERSION: ${{ inputs.xcode_version || '26' }}
+ run: apple-tv/scripts/select-xcode.sh "${XCODE_VERSION}"
+ - name: Locate Homebrew download cache
+ id: brew
+ run: |
+ echo "cache=$(brew --cache)" >> "$GITHUB_OUTPUT"
+ echo "key=$(date +%Y-%m)-${SOZO_BREW_TOOLS// /-}" >> "$GITHUB_OUTPUT"
+ - name: Restore Homebrew downloads
+ uses: actions/cache@v4
+ with:
+ path: ${{ steps.brew.outputs.cache }}
+ key: brew-${{ runner.os }}-${{ runner.arch }}-${{ steps.brew.outputs.key }}
+ restore-keys: brew-${{ runner.os }}-${{ runner.arch }}-
+ - name: Install build and fixture tools
+ run: |
+ # shellcheck disable=SC2086
+ brew install $SOZO_BREW_TOOLS
+ - name: Validate workflow and shell scripts
+ run: |
+ actionlint .github/workflows/tvos-ci.yml .github/workflows/tvos-release.yml
+ shellcheck apple-tv/scripts/*.sh
+ # SozoTV.xcodeproj is gitignored, so the committed outputs of project.yml
+ # are what can drift: Info.plist and anything else xcodegen writes.
+ - name: Check xcodegen output matches the committed files
+ working-directory: apple-tv
+ run: |
+ xcodegen generate
+ git diff --exit-code -- . || { echo "::error::Run xcodegen generate in apple-tv/ and commit the result. CI has xcodegen $(xcodegen --version), unpinned; the committed files were made with 2.46.0, so a version change alone can cause this diff."; exit 1; }
+ untracked="$(git ls-files --others --exclude-standard -- .)"
+ if [ -n "$untracked" ]; then echo "::error::xcodegen created untracked files: $untracked"; exit 1; fi
+ - name: Run the same checks as local development
+ run: apple-tv/scripts/ci.sh
+ - name: Save logs, screenshots, results and simulator app
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: tvos-verification-${{ github.run_id }}-${{ github.run_attempt }}
+ path: |
+ apple-tv/build/ci/*.log
+ apple-tv/build/ci/*.json
+ apple-tv/build/ci/*.txt
+ apple-tv/build/ci/*.zip
+ apple-tv/build/ci/*.xcresult
+ if-no-files-found: warn
+ retention-days: 14
diff --git a/.github/workflows/tvos-release.yml b/.github/workflows/tvos-release.yml
new file mode 100644
index 00000000..320f1bfe
--- /dev/null
+++ b/.github/workflows/tvos-release.yml
@@ -0,0 +1,257 @@
+name: Apple TV Release
+run-name: >-
+ Apple TV ${{ inputs.version }} (build ${{ inputs.build_number || 'auto' }})${{ inputs.upload_testflight && ', TestFlight upload' || ', archive only' }}
+on:
+ workflow_dispatch:
+ inputs:
+ version:
+ description: 'Marketing version, e.g. 1.0.0'
+ required: true
+ default: '1.0.0'
+ type: string
+ build_number:
+ description: 'Build number override (1–9999). Empty = latest TestFlight build + 1'
+ required: false
+ default: ''
+ type: string
+ upload_testflight:
+ description: 'Upload to App Store Connect for TestFlight processing'
+ default: false
+ type: boolean
+ wait_for_processing:
+ description: 'After upload, wait until App Store Connect finishes processing'
+ default: true
+ type: boolean
+ testflight_group:
+ description: 'Internal TestFlight group to add the processed build to (empty = none)'
+ required: false
+ default: ''
+ type: string
+ xcode_version:
+ description: 'Xcode on the runner: exact (26.1) or newest of a major (26)'
+ default: '26'
+ type: string
+permissions:
+ contents: read
+concurrency:
+ group: tvos-release
+ cancel-in-progress: false
+jobs:
+ # Linux, and before the macOS gate, so missing secrets cost seconds, not macOS minutes.
+ preflight:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ environment: apple-tv
+ steps:
+ - uses: actions/checkout@v4
+ - name: Check secrets and inputs
+ env:
+ SOZO_TV_VERSION: ${{ inputs.version }}
+ SOZO_TV_BUILD_NUMBER: ${{ inputs.build_number }}
+ SOZO_TV_UPLOAD_TESTFLIGHT: ${{ inputs.upload_testflight }}
+ SOZO_TV_WAIT_PROCESSING: ${{ inputs.upload_testflight && inputs.wait_for_processing }}
+ SOZO_TV_TESTFLIGHT_GROUP: ${{ inputs.testflight_group }}
+ APPLE_TV_TEAM_ID: ${{ secrets.APPLE_TV_TEAM_ID }}
+ APPLE_TV_CERTIFICATE_P12_BASE64: ${{ secrets.APPLE_TV_CERTIFICATE_P12_BASE64 }}
+ APPLE_TV_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_TV_CERTIFICATE_PASSWORD }}
+ APPLE_TV_PROFILE_BASE64: ${{ secrets.APPLE_TV_PROFILE_BASE64 }}
+ ASC_API_KEY_P8_BASE64: ${{ secrets.ASC_API_KEY_P8_BASE64 }}
+ ASC_API_KEY_ID: ${{ secrets.ASC_API_KEY_ID }}
+ ASC_API_ISSUER_ID: ${{ secrets.ASC_API_ISSUER_ID }}
+ TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
+ TELEGRAM_CHAT_IDS: ${{ secrets.TELEGRAM_CHAT_IDS }}
+ run: apple-tv/scripts/preflight.sh
+ - name: Refuse a build number that is already tagged
+ if: inputs.build_number != '' && inputs.build_number != 'auto'
+ env:
+ TAG: tvos-${{ inputs.version }}-${{ inputs.build_number }}
+ run: |
+ if git ls-remote --exit-code --tags origin "refs/tags/${TAG}" >/dev/null; then
+ echo "::error title=Tag exists::${TAG} was already uploaded. Use a higher build number or leave it empty."
+ exit 1
+ fi
+ - name: Refuse a build number App Store Connect already passed
+ if: inputs.build_number != '' && inputs.build_number != 'auto'
+ env:
+ ASC_API_KEY_P8_BASE64: ${{ secrets.ASC_API_KEY_P8_BASE64 }}
+ ASC_API_KEY_ID: ${{ secrets.ASC_API_KEY_ID }}
+ ASC_API_ISSUER_ID: ${{ secrets.ASC_API_ISSUER_ID }}
+ VERSION: ${{ inputs.version }}
+ BUILD: ${{ inputs.build_number }}
+ run: |
+ if [ -z "${ASC_API_KEY_P8_BASE64}" ] || [ -z "${ASC_API_KEY_ID}" ] || [ -z "${ASC_API_ISSUER_ID}" ]; then
+ echo 'No App Store Connect key; skipping.'; exit 0
+ fi
+ umask 077
+ export ASC_API_KEY_PATH="${RUNNER_TEMP}/AuthKey.p8"
+ trap 'rm -f "${ASC_API_KEY_PATH}"' EXIT
+ printf '%s' "${ASC_API_KEY_P8_BASE64}" | tr -d '[:space:]' | base64 -d > "${ASC_API_KEY_PATH}"
+ python3 apple-tv/scripts/asc.py check-build "${VERSION}" "${BUILD}"
+
+ verify:
+ needs: preflight
+ uses: ./.github/workflows/tvos-ci.yml
+ with:
+ xcode_version: ${{ inputs.xcode_version }}
+
+ distribute:
+ needs: verify
+ runs-on: macos-26
+ timeout-minutes: 40
+ environment: apple-tv
+ permissions:
+ contents: write
+ outputs:
+ build_number: ${{ steps.release.outputs.build_number }}
+ uploaded: ${{ steps.release.outputs.uploaded }}
+ env:
+ HOMEBREW_NO_AUTO_UPDATE: '1'
+ HOMEBREW_NO_INSTALL_CLEANUP: '1'
+ HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK: '1'
+ steps:
+ - uses: actions/checkout@v4
+ - name: Select Xcode
+ env:
+ XCODE_VERSION: ${{ inputs.xcode_version }}
+ run: apple-tv/scripts/select-xcode.sh "${XCODE_VERSION}"
+ - name: Locate Homebrew download cache
+ id: brew
+ run: |
+ echo "cache=$(brew --cache)" >> "$GITHUB_OUTPUT"
+ echo "key=$(date +%Y-%m)-xcodegen" >> "$GITHUB_OUTPUT"
+ - name: Restore Homebrew downloads
+ uses: actions/cache@v4
+ with:
+ path: ${{ steps.brew.outputs.cache }}
+ key: brew-${{ runner.os }}-${{ runner.arch }}-${{ steps.brew.outputs.key }}
+ restore-keys: brew-${{ runner.os }}-${{ runner.arch }}-
+ - name: Install project generator
+ run: brew install xcodegen
+ - name: Archive and export; upload only when requested
+ id: release
+ env:
+ SOZO_TV_VERSION: ${{ inputs.version }}
+ SOZO_TV_BUILD_NUMBER: ${{ inputs.build_number }}
+ SOZO_TV_BUILD_NUMBER_FALLBACK: ${{ github.run_number }}
+ SOZO_TV_UPLOAD_TESTFLIGHT: ${{ inputs.upload_testflight }}
+ APPLE_TV_TEAM_ID: ${{ secrets.APPLE_TV_TEAM_ID }}
+ APPLE_TV_CERTIFICATE_P12_BASE64: ${{ secrets.APPLE_TV_CERTIFICATE_P12_BASE64 }}
+ APPLE_TV_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_TV_CERTIFICATE_PASSWORD }}
+ APPLE_TV_PROFILE_BASE64: ${{ secrets.APPLE_TV_PROFILE_BASE64 }}
+ ASC_API_KEY_P8_BASE64: ${{ secrets.ASC_API_KEY_P8_BASE64 }}
+ ASC_API_KEY_ID: ${{ secrets.ASC_API_KEY_ID }}
+ ASC_API_ISSUER_ID: ${{ secrets.ASC_API_ISSUER_ID }}
+ run: apple-tv/scripts/release.sh
+ # The build number is spent once App Store Connect has it, so tag even if a later step fails.
+ - name: Tag the uploaded build
+ if: always() && steps.release.outputs.uploaded == 'true'
+ env:
+ TAG: tvos-${{ inputs.version }}-${{ steps.release.outputs.build_number }}
+ run: |
+ git tag "${TAG}" "${GITHUB_SHA}"
+ if git push origin "refs/tags/${TAG}"; then
+ echo "::notice title=Tagged::${TAG}"
+ else
+ echo "::warning title=Tag not pushed::${TAG} could not be pushed; the upload itself succeeded."
+ fi
+ - name: Save distribution artifacts and diagnostics
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: tvos-release-${{ inputs.version }}-${{ steps.release.outputs.build_number || 'unresolved' }}-${{ github.run_attempt }}
+ path: apple-tv/build/release/
+ if-no-files-found: warn
+ retention-days: 14
+
+ # Polling App Store Connect is plain HTTPS, so it waits on Linux at a tenth of the macOS rate.
+ testflight:
+ needs: distribute
+ if: >-
+ always() && needs.distribute.outputs.uploaded == 'true' &&
+ (inputs.wait_for_processing || inputs.testflight_group != '')
+ runs-on: ubuntu-latest
+ timeout-minutes: 75
+ environment: apple-tv
+ outputs:
+ processed: ${{ steps.wait.outputs.processed }}
+ grouped: ${{ steps.group.outputs.grouped }}
+ steps:
+ - uses: actions/checkout@v4
+ - name: Wait for App Store Connect processing
+ id: wait
+ env:
+ ASC_API_KEY_P8_BASE64: ${{ secrets.ASC_API_KEY_P8_BASE64 }}
+ ASC_API_KEY_ID: ${{ secrets.ASC_API_KEY_ID }}
+ ASC_API_ISSUER_ID: ${{ secrets.ASC_API_ISSUER_ID }}
+ VERSION: ${{ inputs.version }}
+ BUILD: ${{ needs.distribute.outputs.build_number }}
+ run: |
+ umask 077
+ export ASC_API_KEY_PATH="${RUNNER_TEMP}/AuthKey.p8"
+ printf '%s' "${ASC_API_KEY_P8_BASE64}" | tr -d '[:space:]' | base64 -d > "${ASC_API_KEY_PATH}"
+ build_id="$(python3 apple-tv/scripts/asc.py wait "${VERSION}" "${BUILD}" 60)"
+ echo "build_id=${build_id}" >> "$GITHUB_OUTPUT"
+ echo 'processed=true' >> "$GITHUB_OUTPUT"
+ - name: Add to internal TestFlight group
+ id: group
+ if: inputs.testflight_group != ''
+ env:
+ ASC_API_KEY_ID: ${{ secrets.ASC_API_KEY_ID }}
+ ASC_API_ISSUER_ID: ${{ secrets.ASC_API_ISSUER_ID }}
+ BUILD_ID: ${{ steps.wait.outputs.build_id }}
+ GROUP: ${{ inputs.testflight_group }}
+ run: |
+ ASC_API_KEY_PATH="${RUNNER_TEMP}/AuthKey.p8" python3 apple-tv/scripts/asc.py add-to-group "${BUILD_ID}" "${GROUP}"
+ echo 'grouped=true' >> "$GITHUB_OUTPUT"
+ - name: Remove the API key
+ if: always()
+ run: rm -f "${RUNNER_TEMP}/AuthKey.p8"
+
+ notify:
+ needs: [preflight, verify, distribute, testflight]
+ if: always() && !cancelled()
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - name: Send to Telegram
+ env:
+ TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
+ TELEGRAM_CHAT_IDS: ${{ secrets.TELEGRAM_CHAT_IDS }}
+ VERSION: ${{ inputs.version }}
+ BUILD: ${{ needs.distribute.outputs.build_number }}
+ UPLOAD_REQUESTED: ${{ inputs.upload_testflight }}
+ UPLOADED: ${{ needs.distribute.outputs.uploaded }}
+ PROCESSED: ${{ needs.testflight.outputs.processed }}
+ GROUPED: ${{ needs.testflight.outputs.grouped }}
+ GROUP: ${{ inputs.testflight_group }}
+ RESULTS: >-
+ preflight=${{ needs.preflight.result }} verify=${{ needs.verify.result }}
+ distribute=${{ needs.distribute.result }} testflight=${{ needs.testflight.result }}
+ run: |
+ set -uo pipefail
+ if [ -z "${TELEGRAM_BOT_TOKEN}" ] || [ -z "${TELEGRAM_CHAT_IDS}" ]; then
+ echo "::warning title=Telegram skipped::TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_IDS not set."
+ exit 0
+ fi
+ RUN_URL="${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}"
+ if [ "${UPLOADED}" = true ]; then
+ MSG="Sozo Apple TV ${VERSION} (${BUILD}) uploaded to TestFlight."
+ if [ "${PROCESSED}" = true ]; then MSG="${MSG} Processing finished."; fi
+ if [ "${GROUPED}" = true ]; then MSG="${MSG} Added to group \"${GROUP}\"."; fi
+ if [[ "${RESULTS}" == *failure* ]]; then MSG="${MSG} A later step failed: ${RESULTS}."; fi
+ elif [ "${UPLOAD_REQUESTED}" = true ] || [[ "${RESULTS}" == *failure* ]]; then
+ MSG="Sozo Apple TV ${VERSION} release FAILED, nothing uploaded. ${RESULTS}."
+ else
+ MSG="Sozo Apple TV ${VERSION} (${BUILD:-?}) archived and signed; upload was not requested."
+ fi
+ MSG="$(printf '%s\n\n%s' "${MSG}" "${RUN_URL}")"
+ IFS=',' read -ra CHATS <<< "${TELEGRAM_CHAT_IDS}"
+ for raw in "${CHATS[@]}"; do
+ chat="$(echo "${raw}" | xargs)"
+ [ -z "${chat}" ] && continue
+ curl -sS --fail-with-body -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
+ --data-urlencode "chat_id=${chat}" \
+ --data-urlencode "text=${MSG}" \
+ --data "disable_web_page_preview=true" -o /dev/null \
+ || echo "::warning::Telegram sendMessage to one chat failed."
+ done
diff --git a/.github/workflows/webos-release.yml b/.github/workflows/webos-release.yml
new file mode 100644
index 00000000..4d84c9e9
--- /dev/null
+++ b/.github/workflows/webos-release.yml
@@ -0,0 +1,60 @@
+name: webOS release
+
+# Run by hand from the Actions tab. The version comes from webos/appinfo.json,
+# so raise it there first. CI artifacts expire; a release keeps the ipk.
+on:
+ workflow_dispatch:
+ inputs:
+ prerelease:
+ description: 'Mark as a pre-release (keep on until it has run on a real TV)'
+ type: boolean
+ default: true
+
+concurrency:
+ group: webos-release
+ cancel-in-progress: false
+
+permissions:
+ contents: write
+
+jobs:
+ release:
+ name: Test, package and publish the ipk
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ defaults:
+ run:
+ working-directory: webos
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: '22'
+ cache: npm
+ cache-dependency-path: webos/package-lock.json
+ - name: Install
+ run: npm ci --ignore-scripts
+ - name: Unit and ES5 checks
+ run: npm test
+ - name: Build the ipk
+ run: npm run package
+ - name: Publish
+ env:
+ GH_TOKEN: ${{ github.token }}
+ PRERELEASE: ${{ inputs.prerelease }}
+ run: |
+ set -euo pipefail
+ version=$(node -p "require('./appinfo.json').version")
+ tag="webos-v$version"
+ if gh release view "$tag" >/dev/null 2>&1; then
+ echo "::error::$tag already exists. Raise the version in webos/appinfo.json."
+ exit 1
+ fi
+ cd dist/ipk
+ ipk=$(ls ./*.ipk)
+ sha256sum "$ipk" > "$ipk.sha256"
+ flag=()
+ if [ "$PRERELEASE" = true ]; then flag=(--prerelease); fi
+ gh release create "$tag" "$ipk" "$ipk.sha256" \
+ --target "$GITHUB_SHA" --title "Sozo for LG webOS $version" \
+ --notes "Install steps: webos/README.md." --latest=false "${flag[@]}"
diff --git a/.github/workflows/webos.yml b/.github/workflows/webos.yml
new file mode 100644
index 00000000..3b78e484
--- /dev/null
+++ b/.github/workflows/webos.yml
@@ -0,0 +1,48 @@
+name: webOS CI
+
+# `push` is the default branch only, with `pull_request` alongside it, for the
+# reason given in ci.yml: nothing is covered twice.
+on:
+ push:
+ branches: [master]
+ paths: ['webos/**', '.github/workflows/webos*.yml']
+ pull_request:
+ paths: ['webos/**', '.github/workflows/webos*.yml']
+
+concurrency:
+ group: webos-ci-${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+permissions:
+ contents: read
+
+jobs:
+ verify:
+ name: Unit tests, ES5 checks and ipk
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ defaults:
+ run:
+ working-directory: webos
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: '22'
+ cache: npm
+ cache-dependency-path: webos/package-lock.json
+ - name: Install
+ run: npm ci --ignore-scripts
+ # Includes the ES5 parse and the API and CSS lint in test/compat.test.js.
+ - name: Unit and ES5 checks
+ run: npm test
+ # Fails if the ipk holds anything but the shipped files, byte for byte.
+ - name: Build the ipk
+ run: npm run package
+ - name: Keep the ipk
+ uses: actions/upload-artifact@v4
+ with:
+ name: sozo-webos-ipk
+ path: webos/dist/ipk/*.ipk
+ if-no-files-found: error
+ retention-days: 14
diff --git a/.gitignore b/.gitignore
index 97aca38e..b12df39f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,12 +1,6 @@
*.iml
.gradle
/local.properties
-/.idea/caches
-/.idea/libraries
-/.idea/modules.xml
-/.idea/workspace.xml
-/.idea/navEditor.xml
-/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
@@ -25,3 +19,25 @@ key.properties
# Internal docs — audits, plans, notes. This repository is public; these stay
# on the developer's machine and are never published.
/docs/
+
+# Native Apple TV generated project, build artifacts and distribution secrets.
+/apple-tv/build/
+/apple-tv/SozoTV.xcodeproj/
+*.xcarchive
+*.xcresult
+*.ipa
+*.p12
+*.mobileprovision
+AuthKey_*.p8
+
+# Build output, IDE state and stray working files. The release APK is built by
+# CI (release.yml); nothing under app/release/ belongs in the repository.
+/app/release/
+*.apk
+*.aab
+!**/src/test/resources/**/*.apk
+# The shared code style stays tracked; the rest of .idea is per-machine.
+/.idea/*
+!/.idea/codeStyles/
+.idea_backup/
+/*.srt
diff --git a/.idea/.gitignore b/.idea/.gitignore
deleted file mode 100644
index 26d33521..00000000
--- a/.idea/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-# Default ignored files
-/shelf/
-/workspace.xml
diff --git a/.idea/.name b/.idea/.name
deleted file mode 100644
index 583c3340..00000000
--- a/.idea/.name
+++ /dev/null
@@ -1 +0,0 @@
-tv
\ No newline at end of file
diff --git a/.idea/AICommit.xml b/.idea/AICommit.xml
deleted file mode 100644
index a341857a..00000000
--- a/.idea/AICommit.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/AndroidProjectSystem.xml b/.idea/AndroidProjectSystem.xml
deleted file mode 100644
index 4a53bee8..00000000
--- a/.idea/AndroidProjectSystem.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/appInsightsSettings.xml b/.idea/appInsightsSettings.xml
deleted file mode 100644
index 3665e83b..00000000
--- a/.idea/appInsightsSettings.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml
index 7643783a..9c3d95a7 100644
--- a/.idea/codeStyles/Project.xml
+++ b/.idea/codeStyles/Project.xml
@@ -1,5 +1,39 @@
+
+
+
diff --git a/.idea/compiler.xml b/.idea/compiler.xml
deleted file mode 100644
index b86273d9..00000000
--- a/.idea/compiler.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/copilot.data.migration.agent.xml b/.idea/copilot.data.migration.agent.xml
deleted file mode 100644
index 4ea72a91..00000000
--- a/.idea/copilot.data.migration.agent.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/copilot.data.migration.ask2agent.xml b/.idea/copilot.data.migration.ask2agent.xml
deleted file mode 100644
index 1f2ea11e..00000000
--- a/.idea/copilot.data.migration.ask2agent.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/deploymentTargetSelector.xml b/.idea/deploymentTargetSelector.xml
deleted file mode 100644
index 2cffa89a..00000000
--- a/.idea/deploymentTargetSelector.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/deviceManager.xml b/.idea/deviceManager.xml
deleted file mode 100644
index 91f95584..00000000
--- a/.idea/deviceManager.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/gradle.xml b/.idea/gradle.xml
deleted file mode 100644
index d124cf2a..00000000
--- a/.idea/gradle.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/graphql-settings.xml b/.idea/graphql-settings.xml
deleted file mode 100644
index 16a2ce78..00000000
--- a/.idea/graphql-settings.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml
deleted file mode 100644
index c8f004d7..00000000
--- a/.idea/inspectionProfiles/Project_Default.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/kotlinc.xml b/.idea/kotlinc.xml
deleted file mode 100644
index fdf8d994..00000000
--- a/.idea/kotlinc.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/markdown.xml b/.idea/markdown.xml
deleted file mode 100644
index c61ea334..00000000
--- a/.idea/markdown.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/migrations.xml b/.idea/migrations.xml
deleted file mode 100644
index f8051a6f..00000000
--- a/.idea/migrations.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/misc.xml b/.idea/misc.xml
deleted file mode 100644
index d4c59c8c..00000000
--- a/.idea/misc.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/runConfigurations.xml b/.idea/runConfigurations.xml
deleted file mode 100644
index 16660f1d..00000000
--- a/.idea/runConfigurations.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
deleted file mode 100644
index 35eb1ddf..00000000
--- a/.idea/vcs.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea_backup/.gitignore b/.idea_backup/.gitignore
deleted file mode 100644
index 26d33521..00000000
--- a/.idea_backup/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-# Default ignored files
-/shelf/
-/workspace.xml
diff --git a/.idea_backup/copilot.data.migration.ask2agent.xml b/.idea_backup/copilot.data.migration.ask2agent.xml
deleted file mode 100644
index 1f2ea11e..00000000
--- a/.idea_backup/copilot.data.migration.ask2agent.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea_backup/markdown.xml b/.idea_backup/markdown.xml
deleted file mode 100644
index c61ea334..00000000
--- a/.idea_backup/markdown.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea_backup/misc.xml b/.idea_backup/misc.xml
deleted file mode 100644
index 1945ce5f..00000000
--- a/.idea_backup/misc.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea_backup/modules.xml b/.idea_backup/modules.xml
deleted file mode 100644
index f7d34f0b..00000000
--- a/.idea_backup/modules.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea_backup/vcs.xml b/.idea_backup/vcs.xml
deleted file mode 100644
index 35eb1ddf..00000000
--- a/.idea_backup/vcs.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/README.md b/README.md
index 647a1f75..25555e5b 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,4 @@
-
-# Sozo Tv
+# Sozo TV
@@ -8,17 +7,66 @@
-Sozo is crafted with a perfect blend of simplicity and state-of-the-art elegance. It is designed as an Anilist only client, offering users the ability to stream and download their favorite Anime & Manga.
+Sozo TV is the big-screen companion to the Sozo phone app: browse the catalogue, pick a
+source and watch on a television with a remote. This repository holds three apps that talk to
+the same Sozo backend (`apisozo`):
-The name Sozo (meaning "creation" or "imagination" in Japanese) represents innovation and artistry in the anime world. While we think this is the best open-source anime app for Android, we encourage you to try it out yourself and decide!
+| App | Path | Stack |
+| --- | --- | --- |
+| Android TV | `app/` | Kotlin, Leanback launcher, Media3 ExoPlayer, min SDK 24. Also runs CloudStream (`.cs3`) and Aniyomi (`.apk`) extensions and an embedded torrent server. |
+| Apple TV | `apple-tv/` | Native SwiftUI + AVKit, generated with XcodeGen. Uses only server-provided sources; see [`apple-tv/README.md`](apple-tv/README.md) for what it leaves out on purpose. |
+| LG webOS TV | `webos/` | Plain ES5 web app with no build step, for webOS TV 4.x and newer. **Not yet run on a real TV**; see [`webos/README.md`](webos/README.md). |
-## Note
-Due to **DMCA restrictions**, we cannot host the APK file directly in this repository. Instead, you can download the latest release from our **official Telegram channel**:
-
-
-
+The Android TV and Apple TV apps have household profiles, continue watching, search and localized UI.
+The webOS app has no login or profiles, and keeps continue watching on the TV.
+
+## Download
+
+Release APKs are not kept in this repository. Get the latest Android TV build from the
+**official Telegram channel** ([t.me/sozoapp](https://t.me/sozoapp)).
+
+## Building
+
+**Android TV** needs JDK 17 and the Android SDK:
+
+```sh
+./gradlew :app:assembleDebug # debug APK in app/build/outputs/apk/debug/
+./gradlew :app:testDebugUnitTest # unit tests
+python3 tools/check_strings.py # translated strings vs. English
+```
+
+Release signing reads `key.properties` and a keystore, which are never committed. The two
+vendored AARs in `app/libs/` are described in [`app/libs/README.md`](app/libs/README.md).
-Stay updated with the newest versions, announcements, and fixes by following our channel. 🚀
+**Apple TV** needs Xcode and `xcodegen`:
+
+```sh
+cd apple-tv && xcodegen generate && open SozoTV.xcodeproj
+```
+
+Full verification, including simulator UI tests, is `apple-tv/scripts/ci.sh`; details are in
+[`apple-tv/README.md`](apple-tv/README.md).
+
+**LG webOS TV** needs Node.js 20 or newer:
+
+```sh
+cd webos && npm ci --ignore-scripts && npm test && npm run package # ipk in dist/ipk/
+```
+
+Installing on a TV is described in [`webos/README.md`](webos/README.md).
+
+## CI and releases
+
+| Workflow | Runs on | Does |
+| --- | --- | --- |
+| `ci.yml` | PRs, pushes to `master` | String check, unit tests, debug build of the Android TV app |
+| `release.yml` | Manual, or a `v*` tag | Bumps the version, builds and verifies the signed APK, sends it to Telegram |
+| `tvos-ci.yml` | PRs, pushes to `master`, manual | Apple TV build and simulator tests |
+| `tvos-release.yml` | Manual | Signs an Apple TV archive and optionally uploads it to TestFlight |
+| `webos.yml` | PRs and pushes to `master` that touch `webos/` | webOS unit and ES5 checks, builds the ipk and keeps it as an artifact |
+| `webos-release.yml` | By hand | Tests, builds the ipk and publishes it as a `webos-v` pre-release |
+
+The required secrets are listed at the top of each workflow and in `apple-tv/README.md`.
### Official Discord Server
@@ -48,4 +96,3 @@ Stay updated with the newest versions, announcements, and fixes by following our
## License
[MIT](https://choosealicense.com/licenses/mit/)
-
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 649067c5..f35fb771 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -1,5 +1,5 @@
import java.util.Base64
-import org.jetbrains.kotlin.konan.properties.Properties
+import java.util.Properties
import java.io.FileInputStream
plugins {
@@ -8,7 +8,7 @@ plugins {
id("kotlin-parcelize")
id("androidx.navigation.safeargs.kotlin")
id("kotlin-kapt")
- id("org.jetbrains.kotlin.plugin.serialization") version "1.9.24"
+ id("org.jetbrains.kotlin.plugin.serialization") version "2.2.20"
id("com.google.gms.google-services")
}
val localProps = Properties()
@@ -50,7 +50,7 @@ val hasReleaseKeystore = keystorePropertiesFile.exists() &&
android {
namespace = "com.saikou.sozo_tv"
- compileSdk = 35
+ compileSdk = 36
kapt {
correctErrorTypes = true
useBuildCache = true
@@ -62,8 +62,8 @@ android {
minSdk = 24
//noinspection OldTargetApi
targetSdk = 35
- versionCode = 1
- versionName = "1.0.0"
+ versionCode = 3
+ versionName = "1.0.3"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
@@ -114,7 +114,7 @@ android {
jvmTarget = "17"
// Vendored Aniyomi OkHttpExtensions.parseAs uses context receivers.
// Skip-metadata: the CloudStream `library` + serialization runtime are
- // built with a newer Kotlin than this module (1.9) — read their metadata.
+ // may carry newer Kotlin metadata than this compiler — read their metadata.
freeCompilerArgs += listOf("-Xcontext-receivers", "-Xskip-metadata-version-check")
}
buildFeatures {
@@ -150,42 +150,16 @@ android {
}
}
-// The CloudStream runtime drags kotlin-stdlib up to 2.3.0 (metadata 2.3.0), which
-// the Room/kapt annotation processor can't read (and which is newer than this
-// module's Kotlin 1.9 compiler). Pin the whole kotlin-stdlib family back to 1.9.x
+// Keep plugin runtime ABI current and the Kotlin compiler/runtime aligned.
configurations.all {
- // Compile against 1.7.3, SHIP 1.11.0.
- //
- // Plugins built against a current CloudStream call `BuildersKt.runBlockingK`,
- // which is simply what `runBlocking` is named on the JVM from coroutines
- // 1.11.0 onward. With 1.7.3 in the APK that symbol does not exist, so those
- // plugins died in their MainAPI constructor with NoSuchMethodError, went
- // into PluginHost's `failed` set, and never got retried — 18 of the 79
- // providers were dead for the life of the process, silently.
- //
- // The compile classpath cannot follow: 1.11.0 ships Kotlin metadata 2.2,
- // which this module's Kotlin 1.9.24 compiler (held there by Room/kapt)
- // cannot read. What lands in the APK comes from the *RuntimeClasspath
- // configurations, so versioning by configuration name gives each side what
- // it needs. The one stdlib-2.x class 1.11.0 reaches for, SpillingKt, is
- // already shimmed in app/src/main/java/kotlin/coroutines/jvm/internal.
- //
- // An in-app shim is not an option here: kotlinx-coroutines-core-jvm already
- // defines kotlinx.coroutines.BuildersKt, so a second copy is a D8 duplicate.
- val coroutinesVersion = if (name.endsWith("RuntimeClasspath")) "1.11.0" else "1.7.3"
+ exclude(group = "com.github.recloudstream", module = "torrentserver")
resolutionStrategy.eachDependency {
- // The CloudStream runtime drags kotlin-stdlib up to 2.3.0 (metadata 2.3.0),
- // which the Room/kapt annotation processor can't read. kotlin-reflect rides
- // along for the same reason.
if (requested.group == "org.jetbrains.kotlin" &&
- (requested.name.startsWith("kotlin-stdlib") || requested.name == "kotlin-reflect")
- ) {
- useVersion("1.9.24")
+ (requested.name.startsWith("kotlin-stdlib") || requested.name == "kotlin-reflect")) {
+ useVersion("2.2.20")
}
- if (requested.group == "org.jetbrains.kotlinx" &&
- requested.name.startsWith("kotlinx-coroutines")
- ) {
- useVersion(coroutinesVersion)
+ if (requested.group == "org.jetbrains.kotlinx" && requested.name.startsWith("kotlinx-coroutines")) {
+ useVersion("1.11.0")
}
}
}
@@ -272,8 +246,7 @@ dependencies {
"org.kamranzafar:jtar:2.0.1"
)
- val dialogx_version = "0.0.49"
- implementation("com.kongzue.dialogx:DialogX:${dialogx_version}")
+ implementation("com.kongzue.dialogx:DialogX:0.0.49")
implementation("org.apache.commons:commons-compress:1.21")
implementation("com.bugsnag:bugsnag-android:6.+")
implementation("com.bugsnag:bugsnag-android-performance:1.+")
@@ -298,23 +271,21 @@ dependencies {
// ---- Extension engine (Aniyomi .apk + CloudStream .cs3 runtime) ----
// CloudStream provider runtime: MainAPI/APIHolder/`app` HTTP/extractors/BasePlugin.
- // Held at v4.7.0. v4.8.0 is what plugins calling `MainAPIKt.getJson()` need
- // (five of the six unblocked by the coroutines change below will hit that
- // next), but its manifest requires compileSdk 36, which in turn needs an AGP
- // and Gradle upgrade — a build-infrastructure change, not a dependency bump.
- implementation("com.github.recloudstream.cloudstream:library:v4.7.0")
+ // Match the mobile plugin ABI, including getJson and DrmExtractorLink.
+ implementation("com.github.recloudstream.cloudstream:library:v4.8.0")
+ implementation("androidx.webkit:webkit:1.12.1")
+ implementation("com.squareup.okhttp3:okhttp-dnsoverhttps:4.12.0")
+ implementation(files("libs/torrentserver-7861970-16k.aar"))
// Plugins are compiled against the full CloudStream app, which carries Ktor; the
// `library` artifact does not. Without it a plugin that touches io.ktor.http dies with
// NoClassDefFoundError the moment load() runs (AllMovieLand, among others).
implementation("io.ktor:ktor-http:2.3.12")
- // Declared at 1.7.3 because that is what this module COMPILES against; the
- // resolutionStrategy above ships 1.11.0. See the comment there.
- implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")
+ implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.11.0")
// compileOnly: our clean-room CloudflareKiller implements okhttp3.Interceptor;
// okhttp itself is supplied at runtime by the CloudStream `library`.
compileOnly("com.squareup.okhttp3:okhttp:4.12.0")
// Aniyomi extension runtime supplied to DexClassLoader at load time.
- implementation("org.jetbrains.kotlin:kotlin-reflect:1.9.24")
+ implementation("org.jetbrains.kotlin:kotlin-reflect:2.2.20")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json-okio:1.7.3")
implementation("io.reactivex:rxjava:1.3.8")
// JS engine for Aniyomi extractors that deobfuscate links (QuickJS).
diff --git a/app/libs/README.md b/app/libs/README.md
new file mode 100644
index 00000000..a8dcbe37
--- /dev/null
+++ b/app/libs/README.md
@@ -0,0 +1,14 @@
+# Vendored AARs
+
+Both are real dependencies (`implementation(files(...))` in `app/build.gradle.kts`) and are
+byte-identical to the phone app's `android/app/libs`. Each is the published library with its
+native code rebuilt 16 KB page-aligned, because Android 15+ devices with 16 KB pages refuse to
+load the upstream 4 KB-aligned `.so` files. `configurations.all` excludes the published
+artifacts so they cannot come back transitively.
+
+| File | Origin | SHA-256 |
+| --- | --- | --- |
+| `torrentserver-7861970-16k.aar` | [recloudstream/torrentserver](https://github.com/recloudstream/torrentserver) at `7861970` (TorrServer via torrentserver-aniyomi). Published `classes.jar` unchanged; `libgojni.so` for all four ABIs rebuilt with Go 1.23.5, gomobile `cd096645`, NDK r28. Used by `engine/torrent/TorrentEngine.kt`. | `cfaa598c97dae34d45849951759682b1f015b58c128e9c5db9871509297e5e40` |
+| `quickjs-android-0.9.2-16k.aar` | `app.cash.quickjs:quickjs-android:0.9.2` (cashapp/zipline `a738129cc4`). Published `classes.jar` unchanged; `libquickjs.so` rebuilt with NDK r28 and `-Wl,-z,max-page-size=16384`. | `fdade24d05289ef32058324627b95a89c34504f76b6f24bf5da14da014fb1155` |
+
+Check with `shasum -a 256 app/libs/*.aar`. Replace both here and in the phone app together.
diff --git a/app/libs/torrentserver-7861970-16k.aar b/app/libs/torrentserver-7861970-16k.aar
new file mode 100644
index 00000000..6a3a2f7e
Binary files /dev/null and b/app/libs/torrentserver-7861970-16k.aar differ
diff --git a/app/release/app-release.apk b/app/release/app-release.apk
deleted file mode 100644
index a908f8b4..00000000
Binary files a/app/release/app-release.apk and /dev/null differ
diff --git a/app/release/output-metadata.json b/app/release/output-metadata.json
deleted file mode 100644
index 8e896f2b..00000000
--- a/app/release/output-metadata.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "version": 3,
- "artifactType": {
- "type": "APK",
- "kind": "Directory"
- },
- "applicationId": "com.saikou.sozo_tv",
- "variantName": "release",
- "elements": [
- {
- "type": "SINGLE",
- "filters": [],
- "attributes": [],
- "versionCode": 10,
- "versionName": "10.0",
- "outputFile": "app-release.apk"
- }
- ],
- "elementType": "File"
-}
\ No newline at end of file
diff --git a/app/src/debug/AndroidManifest.xml b/app/src/debug/AndroidManifest.xml
new file mode 100644
index 00000000..51eab9e8
--- /dev/null
+++ b/app/src/debug/AndroidManifest.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
diff --git a/app/src/debug/java/com/saikou/sozo_tv/debug/CloudStreamProbeInstrumentation.kt b/app/src/debug/java/com/saikou/sozo_tv/debug/CloudStreamProbeInstrumentation.kt
new file mode 100644
index 00000000..e2cc486e
--- /dev/null
+++ b/app/src/debug/java/com/saikou/sozo_tv/debug/CloudStreamProbeInstrumentation.kt
@@ -0,0 +1,43 @@
+package com.saikou.sozo_tv.debug
+
+import android.app.Instrumentation
+import android.content.Intent
+import android.os.Bundle
+import com.saikou.sozo_tv.data.extensions.ExtensionEngine
+import com.saikou.sozo_tv.presentation.activities.MainActivity
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withTimeout
+import org.json.JSONArray
+import org.json.JSONObject
+
+/** Debug-only real plugin runtime search/detail probe, with no credential or signed URL output. */
+class CloudStreamProbeInstrumentation : Instrumentation() {
+ private var arguments = Bundle()
+ override fun onCreate(arguments: Bundle?) { this.arguments = arguments ?: Bundle(); super.onCreate(arguments); start() }
+ override fun onStart() {
+ val activity = startActivitySync(Intent(targetContext, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
+ val results = JSONArray()
+ runBlocking {
+ for (provider in arguments.getString("providers", "StreamPlay,Anikage,IPTV Player").split(',')) {
+ val start = System.currentTimeMillis()
+ val result = JSONObject().put("provider", provider)
+ try {
+ withTimeout(45_000) {
+ val page = ExtensionEngine.shared.search("cs:$provider", arguments.getString("query", "Avatar"))
+ result.put("items", page?.items?.size ?: 0)
+ result.put("status", "SEARCH_OK")
+ if (arguments.getString("detail", "false") == "true") {
+ val first = page?.items?.firstOrNull() ?: error("No results")
+ val detail = ExtensionEngine.shared.load("cs:$provider", first.contentUrl) ?: error("No details")
+ result.put("episodes", detail.episodes.size).put("type", detail.type)
+ }
+ }
+ } catch (t: Throwable) { result.put("status", "FAIL").put("error", "${t.javaClass.simpleName}: ${t.message}") }
+ result.put("ms", System.currentTimeMillis() - start); results.put(result)
+ }
+ }
+ runOnMainSync { activity.finish() }
+ targetContext.filesDir.resolve("cloudstream-probe.json").writeText(results.toString(2))
+ finish(0, Bundle().apply { putString("result", results.toString()) })
+ }
+}
diff --git a/app/src/debug/java/com/saikou/sozo_tv/debug/OfflineProbeInstrumentation.kt b/app/src/debug/java/com/saikou/sozo_tv/debug/OfflineProbeInstrumentation.kt
new file mode 100644
index 00000000..dfe1050f
--- /dev/null
+++ b/app/src/debug/java/com/saikou/sozo_tv/debug/OfflineProbeInstrumentation.kt
@@ -0,0 +1,75 @@
+package com.saikou.sozo_tv.debug
+
+import android.app.Instrumentation
+import android.content.Intent
+import android.os.Bundle
+import androidx.media3.common.PlaybackException
+import androidx.media3.common.Player
+import androidx.media3.common.util.UnstableApi
+import androidx.media3.exoplayer.ExoPlayer
+import androidx.media3.exoplayer.offline.Download
+import androidx.media3.exoplayer.offline.DownloadHelper
+import androidx.media3.exoplayer.video.PlaceholderSurface
+import com.saikou.sozo_tv.data.model.VodMovieResponse
+import com.saikou.sozo_tv.engine.download.TvDownloads
+import com.saikou.sozo_tv.presentation.activities.DownloadsActivity
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withContext
+
+/** Debug only. Download, then run mode=play in a fresh process with the fixture server stopped. */
+@UnstableApi
+class OfflineProbeInstrumentation : Instrumentation() {
+ private var args = Bundle()
+ override fun onCreate(arguments: Bundle?) { args = arguments ?: Bundle(); super.onCreate(arguments); start() }
+ override fun onStart() {
+ val result = runCatching { runBlocking {
+ if (args.getString("mode", "download") == "download") {
+ startActivitySync(Intent(targetContext, DownloadsActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
+ val id = TvDownloads.enqueue(targetContext, "Offline verification", VodMovieResponse("", emptyMap(),
+ urlobj = requireNotNull(args.getString("url")), type = args.getString("type", "hls")))
+ repeat(180) {
+ val download = withContext(Dispatchers.Main) { TvDownloads.list(targetContext).find { it.request.id == id } }
+ if (download?.state == Download.STATE_FAILED) error("Download failed")
+ if (download?.state == Download.STATE_COMPLETED) {
+ targetContext.filesDir.resolve("offline-probe-id.txt").writeText(id)
+ return@runBlocking "PASS downloaded bytes=${download.bytesDownloaded} id=$id streamKeys=${download.request.streamKeys}"
+ }
+ delay(500)
+ }
+ error("Download timed out")
+ } else {
+ val id = args.getString("id") ?: targetContext.filesDir.resolve("offline-probe-id.txt").readText().trim()
+ val download = withContext(Dispatchers.Main) { TvDownloads.list(targetContext).first { it.request.id == id } }
+ check(download.state == Download.STATE_COMPLETED)
+ var player: ExoPlayer? = null
+ var surface: PlaceholderSurface? = null
+ var failure: Throwable? = null
+ var width = 0; var height = 0; var position = 0L
+ try {
+ runOnMainSync {
+ surface = PlaceholderSurface.newInstance(targetContext, false)
+ player = ExoPlayer.Builder(targetContext).build().apply {
+ setVideoSurface(surface)
+ addListener(object : Player.Listener { override fun onPlayerError(error: PlaybackException) { failure = error } })
+ setMediaSource(DownloadHelper.createMediaSource(download.request, TvDownloads.offlineFactory(targetContext, id)))
+ prepare(); play()
+ }
+ }
+ repeat(80) {
+ delay(250)
+ runOnMainSync { player?.let { width = it.videoSize.width; height = it.videoSize.height; position = it.currentPosition } }
+ failure?.let { throw it }
+ if (width > 0 && height > 0 && position >= 1500) return@runBlocking "PASS disk-only playback ${width}x$height position=$position id=$id"
+ }
+ error("Disk-only playback timed out width=$width height=$height position=$position")
+ } finally { runOnMainSync { player?.release(); surface?.release() } }
+ }
+ } }
+ val text = result.fold({ it }, { "FAIL ${it.stackTraceToString()}" })
+ android.util.Log.i("SozoOfflineProbe", text)
+ targetContext.filesDir.resolve("offline-probe.txt").writeText(text)
+ finish(if (result.isSuccess) 0 else 1, Bundle().apply { putString("result", text) })
+ }
+}
diff --git a/app/src/debug/java/com/saikou/sozo_tv/debug/PlayerProbeInstrumentation.kt b/app/src/debug/java/com/saikou/sozo_tv/debug/PlayerProbeInstrumentation.kt
new file mode 100644
index 00000000..41d54eb3
--- /dev/null
+++ b/app/src/debug/java/com/saikou/sozo_tv/debug/PlayerProbeInstrumentation.kt
@@ -0,0 +1,69 @@
+package com.saikou.sozo_tv.debug
+
+import android.app.Instrumentation
+import android.os.Bundle
+import androidx.media3.common.MediaItem
+import androidx.media3.common.MimeTypes
+import androidx.media3.common.PlaybackException
+import androidx.media3.common.Player
+import androidx.media3.exoplayer.ExoPlayer
+import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
+import androidx.media3.exoplayer.video.PlaceholderSurface
+import com.saikou.sozo_tv.engine.player.LocalHlsProxy
+import com.saikou.sozo_tv.engine.player.StreamHttp
+import com.saikou.sozo_tv.engine.player.WebViewStreamExtractor
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.runBlocking
+import org.json.JSONObject
+
+/** Debug APK only. Runs unattended extraction + real decoder/progress checks on a TV emulator. */
+@androidx.media3.common.util.UnstableApi
+class PlayerProbeInstrumentation : Instrumentation() {
+ private var arguments = Bundle()
+ override fun onCreate(arguments: Bundle?) { this.arguments = arguments ?: Bundle(); super.onCreate(arguments); start() }
+ override fun onStart() {
+ val result = runCatching { runBlocking {
+ val input = requireNotNull(arguments.getString("url"))
+ val expectedHeight = arguments.getString("height")?.toIntOrNull() ?: 0
+ val extracted = WebViewStreamExtractor.extract(targetContext, input,
+ mapOf("Referer" to arguments.getString("referer", "https://primesrc.me/")), timeoutMs = 35000)
+ ?: error("No media captured")
+ val http = StreamHttp(targetContext)
+ http.headers = extracted.headers
+ val proxy = LocalHlsProxy(http.proxyClient)
+ val url = proxy.register(extracted.url, extracted.headers, JSONObject(), JSONObject())
+ var player: ExoPlayer? = null
+ var surface: PlaceholderSurface? = null
+ var failure: Throwable? = null
+ var width = 0
+ var height = 0
+ var position = 0L
+ try {
+ runOnMainSync {
+ surface = PlaceholderSurface.newInstance(targetContext, false)
+ player = ExoPlayer.Builder(targetContext).build().apply {
+ setVideoSurface(surface)
+ addListener(object : Player.Listener { override fun onPlayerError(error: PlaybackException) { failure = error } })
+ val mime = if (extracted.playType == "dash") MimeTypes.APPLICATION_MPD else if (extracted.playType == "mp4") MimeTypes.VIDEO_MP4 else MimeTypes.APPLICATION_M3U8
+ setMediaSource(DefaultMediaSourceFactory(http.dataSourceFactory).createMediaSource(MediaItem.Builder().setUri(url).setMimeType(mime).build()))
+ prepare(); play()
+ }
+ }
+ repeat(120) {
+ delay(500)
+ runOnMainSync { player?.let { p -> width = p.videoSize.width; height = p.videoSize.height; position = p.currentPosition } }
+ failure?.let { throw it }
+ if (width > 0 && height >= expectedHeight && position >= 1500) return@runBlocking "PASS ${width}x$height position=$position type=${extracted.playType} headers=${extracted.headers.keys}"
+ }
+ error("Playback timed out ${width}x$height position=$position")
+ } finally {
+ runOnMainSync { player?.release(); surface?.release() }
+ proxy.stop()
+ }
+ } }
+ val text = result.fold({ it }, { "FAIL ${it.stackTraceToString()}" })
+ android.util.Log.i("SozoPlayerProbe", text)
+ targetContext.filesDir.resolve("player-probe.txt").writeText(text)
+ finish(if (result.isSuccess) 0 else 1, Bundle().apply { putString("result", text) })
+ }
+}
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index a757d238..ff1caf39 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -7,9 +7,15 @@
+
+
+
+
+
+
@@ -53,6 +59,20 @@
android:usesCleartextTraffic="true">
+
+
+
+
+
+
+
+
+
+
+
-
\ No newline at end of file
+
diff --git a/app/src/main/java/com/lagradost/cloudstream3/utils/AppModuleClasses.kt b/app/src/main/java/com/lagradost/cloudstream3/utils/AppModuleClasses.kt
index 89a91406..c4f35ab1 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/utils/AppModuleClasses.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/utils/AppModuleClasses.kt
@@ -73,17 +73,7 @@ open class UiText(private val value: String = "") {
override fun toString(): String = value
}
-/**
- * CloudStream's thread-safe list. `APIHolder.allProviders` is one upstream, so a plugin that
- * walks the provider list names this type in its own signatures.
- *
- * Backed by a synchronized list rather than a no-op: a plugin that adds to one expects to read
- * back what it added, and an always-empty collection would be a silent wrong answer rather than
- * a missing feature.
- */
-class AtomicMutableList(
- initial: Collection = emptyList(),
-) : MutableList by java.util.Collections.synchronizedList(ArrayList(initial))
+// AtomicMutableList is supplied by CloudStream library v4.8.0.
object AppContextUtils {
/**
diff --git a/app/src/main/java/com/saikou/sozo_tv/adapters/CastAdapter.kt b/app/src/main/java/com/saikou/sozo_tv/adapters/CastAdapter.kt
index 36f82bf4..918f6a06 100644
--- a/app/src/main/java/com/saikou/sozo_tv/adapters/CastAdapter.kt
+++ b/app/src/main/java/com/saikou/sozo_tv/adapters/CastAdapter.kt
@@ -12,50 +12,50 @@ import com.saikou.sozo_tv.utils.applyTvFocusScale
import com.saikou.sozo_tv.utils.loadImage
class CastAdapter : RecyclerView.Adapter() {
- private val castList = ArrayList()
+ lateinit var itemClickkedListener: (Cast) -> Unit
+ var list = ArrayList()
+
+ override fun onCreateViewHolder(
+ p0: ViewGroup,
+ p1: Int
+ ): CastVh {
+ return CastVh(ItemCastBinding.inflate(LayoutInflater.from(p0.context), p0, false))
+ }
- private lateinit var itemClickkedListener: (Cast) -> Unit
fun setOnItemClickListener(listener: (Cast) -> Unit) {
itemClickkedListener = listener
}
- inner class CastVh(private val binding: ItemCastBinding) :
- RecyclerView.ViewHolder(binding.root) {
- fun onBind(cast: Cast) {
- binding.userNameTxt.text = cast.name
- // Most sources send no role at all, and an empty line under every face read as a
- // half-loaded row.
- binding.characterTxt.isVisible = cast.role.isNotBlank()
- binding.characterTxt.text = cast.role
- binding.accountImg.loadImage(cast.image)
- // Making the card unfocusable to keep it out of a dead person-detail screen turned
- // the whole row into a D-pad dead zone: the names and roles were on screen and
- // could not be reached, let alone scrolled. Keep it reachable, and send a press
- // somewhere that actually resolves - a search for the person across sources.
- binding.root.isFocusable = true
- binding.root.isClickable = true
- binding.root.setOnClickListener {
- if (::itemClickkedListener.isInitialized) itemClickkedListener(cast)
- }
- }
- }
-
- override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CastVh {
- return CastVh(ItemCastBinding.inflate(LayoutInflater.from(parent.context), parent, false))
+ override fun onBindViewHolder(
+ p0: CastVh,
+ p1: Int
+ ) {
+ p0.onBind(list[p1])
}
override fun getItemCount(): Int {
- return castList.size
+ return list.size
}
- override fun onBindViewHolder(holder: CastVh, position: Int) {
- holder.onBind(castList[position])
+ inner class CastVh(val binding: ItemCastBinding) : RecyclerView.ViewHolder(binding.root) {
+ fun onBind(item: Cast) {
+ binding.apply {
+ binding.userNameTxt.text = item.name
+ binding.characterTxt.text = item.role
+ binding.accountImg.loadImage(item.image)
+ binding.root.isFocusable = true
+ binding.root.isClickable = true
+ binding.root.setOnClickListener {
+ if (::itemClickkedListener.isInitialized) itemClickkedListener(item)
+ }
+ }
+ }
}
- fun submitCast(cast: List) {
- castList.clear()
- castList.addAll(cast)
+ fun submitList(newList: ArrayList) {
+ list.clear()
+ list.addAll(newList)
notifyDataSetChanged()
}
}
\ No newline at end of file
diff --git a/app/src/main/java/com/saikou/sozo_tv/adapters/EpisodePlayerAdapter.kt b/app/src/main/java/com/saikou/sozo_tv/adapters/EpisodePlayerAdapter.kt
index ce4b9c56..19babed9 100644
--- a/app/src/main/java/com/saikou/sozo_tv/adapters/EpisodePlayerAdapter.kt
+++ b/app/src/main/java/com/saikou/sozo_tv/adapters/EpisodePlayerAdapter.kt
@@ -4,6 +4,8 @@ import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
+import androidx.recyclerview.widget.AsyncListDiffer
+import androidx.recyclerview.widget.DiffUtil
import com.saikou.sozo_tv.R
import com.saikou.sozo_tv.databinding.EpisodeItemLittleBinding
import com.saikou.sozo_tv.parser.models.Data
@@ -17,7 +19,13 @@ class EpisodePlayerAdapter(
var defaultImg: String,
) : RecyclerView.Adapter() {
- private val list = ArrayList()
+ private val differ = AsyncListDiffer(this, object : DiffUtil.ItemCallback() {
+ override fun areItemsTheSame(oldItem: Data, newItem: Data) =
+ oldItem.session == newItem.session && oldItem.episode == newItem.episode &&
+ oldItem.season == newItem.season && oldItem.serverId == newItem.serverId
+ override fun areContentsTheSame(oldItem: Data, newItem: Data) = oldItem == newItem
+ })
+ private val list get() = differ.currentList
private var progress: Map> = emptyMap()
private lateinit var onEpisodeClick: (position: Int, data: Data) -> Unit
fun setOnEpisodeClick(listener: (position: Int, data: Data) -> Unit) {
@@ -29,52 +37,52 @@ class EpisodePlayerAdapter(
@SuppressLint("SetTextI18n")
fun onBind(data: Data, position: Int) {
- itemBinding.apply {
- if (position == currentIndex) {
- itemBinding.nowPlayingBadge.visible()
- } else {
- itemBinding.nowPlayingBadge.gone()
- }
-
- itemBinding.itemImg.loadImage(data.snapshot ?: defaultImg)
-
- val number = data.episode?.takeIf { it > 0 } ?: (position + 1)
- topContainer.text = root.context.getString(R.string.episode_n, number)
+ bindState(data, position)
+ itemBinding.itemImg.loadImage(data.snapshot ?: defaultImg)
+ val number = data.episode?.takeIf { it > 0 } ?: (position + 1)
+ itemBinding.topContainer.text = itemBinding.root.context.getString(R.string.episode_n, number)
+ itemBinding.root.setOnClickListener {
+ val selected = bindingAdapterPosition
+ if (selected == RecyclerView.NO_POSITION) return@setOnClickListener
+ selectEpisode(selected)
+ onEpisodeClick(selected, list[selected])
+ }
+ }
+ fun bindState(data: Data, position: Int) {
+ itemBinding.apply {
+ if (position == currentIndex) nowPlayingBadge.visible() else nowPlayingBadge.gone()
val watched = data.session?.let { progress[it] }
- if (watched != null) {
- val percent = (watched.first * 100 / watched.second).toInt().coerceIn(1, 100)
+ val percent = episodeProgressPercent(watched)
+ if (percent != null) {
progressBar.progress = percent
progressBar.visible()
- timeStr.text =
- root.context.getString(R.string.episode_stopped_at, stamp(watched.first))
+ timeStr.text = root.context.getString(R.string.episode_stopped_at, stamp(watched!!.first))
timeStr.visible()
} else {
progressBar.gone()
timeStr.gone()
}
- root.setOnClickListener {
- val previousIndex = currentIndex
- currentIndex = position
- notifyItemChanged(previousIndex)
- notifyItemChanged(currentIndex)
- onEpisodeClick(position, data)
- }
}
}
}
fun setProgress(next: Map>) {
- progress = next
- notifyDataSetChanged()
+ val previous = progress
+ progress = next.toMap()
+ list.forEachIndexed { index, episode ->
+ if (previous[episode.session] != progress[episode.session]) {
+ notifyItemChanged(index, STATE_PAYLOAD)
+ }
+ }
}
fun selectEpisode(index: Int) {
if (index == currentIndex) return
val previous = currentIndex
currentIndex = index
- if (previous in list.indices) notifyItemChanged(previous)
- if (index in list.indices) notifyItemChanged(index)
+ if (previous in list.indices) notifyItemChanged(previous, STATE_PAYLOAD)
+ if (index in list.indices) notifyItemChanged(index, STATE_PAYLOAD)
}
private fun stamp(ms: Long): String {
@@ -87,9 +95,7 @@ class EpisodePlayerAdapter(
}
fun submitList(newList: List) {
- list.clear()
- list.addAll(newList)
- notifyDataSetChanged()
+ differ.submitList(newList.toList())
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EpisodePlayerViewHolder {
@@ -102,6 +108,16 @@ class EpisodePlayerAdapter(
override fun getItemCount(): Int = list.size
+ override fun onBindViewHolder(holder: EpisodePlayerViewHolder, position: Int, payloads: MutableList) {
+ if (payloads.isNotEmpty() && payloads.all { it == STATE_PAYLOAD }) {
+ holder.bindState(list[position], position)
+ } else holder.onBind(list[position], position)
+ }
+
+ private companion object {
+ const val STATE_PAYLOAD = "episode-state"
+ }
+
override fun onBindViewHolder(holder: EpisodePlayerViewHolder, position: Int) {
holder.onBind(list[position], position)
}
diff --git a/app/src/main/java/com/saikou/sozo_tv/adapters/EpisodeProgress.kt b/app/src/main/java/com/saikou/sozo_tv/adapters/EpisodeProgress.kt
new file mode 100644
index 00000000..50aef4f7
--- /dev/null
+++ b/app/src/main/java/com/saikou/sozo_tv/adapters/EpisodeProgress.kt
@@ -0,0 +1,6 @@
+package com.saikou.sozo_tv.adapters
+
+internal fun episodeProgressPercent(watched: Pair?): Int? {
+ if (watched == null || watched.second <= 0L) return null
+ return (watched.first.toDouble() / watched.second * 100).toInt().coerceIn(0, 100)
+}
diff --git a/app/src/main/java/com/saikou/sozo_tv/adapters/HistoryAdapter.kt b/app/src/main/java/com/saikou/sozo_tv/adapters/HistoryAdapter.kt
index 1ed5aacd..8c335100 100644
--- a/app/src/main/java/com/saikou/sozo_tv/adapters/HistoryAdapter.kt
+++ b/app/src/main/java/com/saikou/sozo_tv/adapters/HistoryAdapter.kt
@@ -5,6 +5,8 @@ import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
+import androidx.recyclerview.widget.AsyncListDiffer
+import androidx.recyclerview.widget.DiffUtil
import com.saikou.sozo_tv.R
import com.saikou.sozo_tv.data.local.entity.WatchHistoryEntity
import com.saikou.sozo_tv.databinding.ItemMovieHistoryBinding
@@ -12,17 +14,20 @@ import com.saikou.sozo_tv.utils.loadImage
import java.util.concurrent.TimeUnit
class HistoryAdapter : RecyclerView.Adapter() {
- private val list = ArrayList()
+ private val differ = AsyncListDiffer(this, object : DiffUtil.ItemCallback() {
+ override fun areItemsTheSame(oldItem: WatchHistoryEntity, newItem: WatchHistoryEntity) =
+ oldItem.session == newItem.session
+ override fun areContentsTheSame(oldItem: WatchHistoryEntity, newItem: WatchHistoryEntity) =
+ oldItem == newItem
+ })
+ private val list get() = differ.currentList
private lateinit var setItemHistoryListener: (WatchHistoryEntity) -> Unit
fun setItemHistoryListener(listener: (WatchHistoryEntity) -> Unit) {
setItemHistoryListener = listener
}
- @SuppressLint("NotifyDataSetChanged")
fun submitList(newList: List) {
- this.list.clear()
- this.list.addAll(newList)
- notifyDataSetChanged()
+ differ.submitList(newList.map { it.copy() })
}
inner class HistoryViewHolder(private val itemBinding: ItemMovieHistoryBinding) :
diff --git a/app/src/main/java/com/saikou/sozo_tv/adapters/ProfileAdapter.kt b/app/src/main/java/com/saikou/sozo_tv/adapters/ProfileAdapter.kt
index f7f6bfd6..894c2452 100644
--- a/app/src/main/java/com/saikou/sozo_tv/adapters/ProfileAdapter.kt
+++ b/app/src/main/java/com/saikou/sozo_tv/adapters/ProfileAdapter.kt
@@ -35,6 +35,7 @@ class ProfileAdapter(
// fetch has wired this up (the OK handler below is immediate, not debounced), and
// a bare lateinit turns that into a crash rather than a no-op.
private var onSectionClick: ((SectionItem, Int) -> Unit)? = null
+ private var accountClickListener: (() -> Unit)? = null
private var selectedSectionIndex: Int = RecyclerView.NO_POSITION
@@ -58,6 +59,10 @@ class ProfileAdapter(
onSectionClick = listener
}
+ fun setOnAccountClickListener(listener: () -> Unit) {
+ accountClickListener = listener
+ }
+
companion object {
private const val VIEW_TYPE_BACK_BUTTON = 0
@@ -102,6 +107,7 @@ class ProfileAdapter(
binding.phoneTxt.alpha = 0.85f
binding.root.isFocusable = true
binding.root.isFocusableInTouchMode = true
+ binding.root.setOnClickListener { accountClickListener?.invoke() }
}
}
diff --git a/app/src/main/java/com/saikou/sozo_tv/adapters/SearchAdapter.kt b/app/src/main/java/com/saikou/sozo_tv/adapters/SearchAdapter.kt
index b5883d4b..570d322b 100644
--- a/app/src/main/java/com/saikou/sozo_tv/adapters/SearchAdapter.kt
+++ b/app/src/main/java/com/saikou/sozo_tv/adapters/SearchAdapter.kt
@@ -8,6 +8,7 @@ import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
+import androidx.recyclerview.widget.AsyncListDiffer
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
@@ -18,7 +19,8 @@ import com.saikou.sozo_tv.domain.model.SearchModel
class SearchAdapter :
RecyclerView.Adapter() {
- private var movieList = ArrayList()
+ private val differ = AsyncListDiffer(this, SearchResultDiff)
+ private val movieList get() = differ.currentList
var query: String = ""
/** Only meaningful when results span providers; a single-source search knows. */
@@ -26,7 +28,7 @@ class SearchAdapter :
set(value) {
if (field == value) return
field = value
- notifyItemRangeChanged(0, movieList.size)
+ notifyItemRangeChanged(0, movieList.size, TEXT_PAYLOAD)
}
private lateinit var itemClickeddListener: (movie: SearchModel) -> Unit
@@ -42,7 +44,7 @@ class SearchAdapter :
inner class MovieViewHolder(private val binding: SearchItemBinding) :
RecyclerView.ViewHolder(binding.root) {
@SuppressLint("SetTextI18n", "NewApi")
- fun bind(movie: SearchModel) {
+ fun bindText(movie: SearchModel) {
// Which source found this. In an all-sources search the same title
// comes back from several, and without this the duplicates look
// like a bug rather than a choice of where to play from.
@@ -54,14 +56,6 @@ class SearchAdapter :
binding.movieSource.isVisible = showSource && source != null
binding.movieSource.text = source.orEmpty()
- binding.root.setOnClickListener {
- itemClickeddListener.invoke(movie)
- }
- binding.root.setOnLongClickListener {
- itemLongClickListener?.invoke(movie)
- itemLongClickListener != null
- }
-
val mainText = movie.title ?: "Unknown Title"
val spannableString = SpannableString(mainText)
@@ -82,6 +76,18 @@ class SearchAdapter :
binding.movieTitle.text = spannableString
+ }
+
+ fun bind(movie: SearchModel) {
+ bindText(movie)
+ binding.root.setOnClickListener {
+ itemClickeddListener.invoke(movie)
+ }
+ binding.root.setOnLongClickListener {
+ itemLongClickListener?.invoke(movie)
+ itemLongClickListener != null
+ }
+
val imageUrl = movie.image ?: ""
Glide.with(binding.root.context)
.load(imageUrl)
@@ -103,17 +109,30 @@ class SearchAdapter :
holder.bind(movieList[position])
}
+ override fun onBindViewHolder(holder: MovieViewHolder, position: Int, payloads: MutableList) {
+ if (payloads.isNotEmpty() && payloads.all { it == TEXT_PAYLOAD }) {
+ holder.bindText(movieList[position])
+ } else {
+ holder.bind(movieList[position])
+ }
+ }
+
+ private companion object {
+ const val TEXT_PAYLOAD = "search-text"
+ }
+
override fun getItemCount(): Int = movieList.size
fun updateData(newMovies: List) {
- movieList.clear()
- movieList.addAll(newMovies)
- notifyDataSetChanged()
+ // Each arriving provider used to invalidate every visible poster and focus holder.
+ // Immutable snapshots + background diff keep unchanged cards attached.
+ differ.submitList(newMovies.toList())
}
fun setQueryText(query: String) {
+ if (this.query == query) return
this.query = query
- notifyDataSetChanged()
+ notifyItemRangeChanged(0, movieList.size, TEXT_PAYLOAD)
}
diff --git a/app/src/main/java/com/saikou/sozo_tv/adapters/SearchResultDiff.kt b/app/src/main/java/com/saikou/sozo_tv/adapters/SearchResultDiff.kt
new file mode 100644
index 00000000..9f28af7f
--- /dev/null
+++ b/app/src/main/java/com/saikou/sozo_tv/adapters/SearchResultDiff.kt
@@ -0,0 +1,14 @@
+package com.saikou.sozo_tv.adapters
+
+import androidx.recyclerview.widget.DiffUtil
+import com.saikou.sozo_tv.domain.model.SearchModel
+
+/** Null IDs are not an identity: unrelated cards must never inherit each other's focus. */
+internal object SearchResultDiff : DiffUtil.ItemCallback() {
+ override fun areItemsTheSame(oldItem: SearchModel, newItem: SearchModel): Boolean =
+ if (oldItem.id != null && newItem.id != null) oldItem.id == newItem.id
+ else oldItem == newItem
+
+ override fun areContentsTheSame(oldItem: SearchModel, newItem: SearchModel): Boolean =
+ oldItem == newItem
+}
diff --git a/app/src/main/java/com/saikou/sozo_tv/adapters/SeriesPageAdapter.kt b/app/src/main/java/com/saikou/sozo_tv/adapters/SeriesPageAdapter.kt
index b692925f..32019454 100644
--- a/app/src/main/java/com/saikou/sozo_tv/adapters/SeriesPageAdapter.kt
+++ b/app/src/main/java/com/saikou/sozo_tv/adapters/SeriesPageAdapter.kt
@@ -3,7 +3,7 @@ package com.saikou.sozo_tv.adapters
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
-import android.view.animation.AnimationUtils
+import com.saikou.sozo_tv.utils.applyTvFocusScale
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.saikou.sozo_tv.R
@@ -96,19 +96,7 @@ class SeriesPageAdapter(
} else {
topContainer.text = data.title
}
- binding.root.setOnFocusChangeListener { _, hasFocus ->
- val animation = when {
- hasFocus -> AnimationUtils.loadAnimation(
- binding.root.context, R.anim.zoom_in
- )
-
- else -> AnimationUtils.loadAnimation(
- binding.root.context, R.anim.zoom_out
- )
- }
- binding.root.startAnimation(animation)
- animation.fillAfter = true
- }
+ root.applyTvFocusScale()
itemImg.loadImage(data.snapshot ?: LocalData.anime404)
}
diff --git a/app/src/main/java/com/saikou/sozo_tv/app/MyApp.kt b/app/src/main/java/com/saikou/sozo_tv/app/MyApp.kt
index 7a2c9a71..60946be3 100644
--- a/app/src/main/java/com/saikou/sozo_tv/app/MyApp.kt
+++ b/app/src/main/java/com/saikou/sozo_tv/app/MyApp.kt
@@ -38,6 +38,7 @@ class MyApp : Application() {
instance = this
initSozoUserAgent(this)
+ com.saikou.sozo_tv.engine.network.ExtensionDns.initialize(this)
Bugsnag.start(this)
AndroidThreeTen.init(this)
FirebaseApp.initializeApp(this)
diff --git a/app/src/main/java/com/saikou/sozo_tv/components/PlayerTvView.kt b/app/src/main/java/com/saikou/sozo_tv/components/PlayerTvView.kt
index b57860fc..ffc89232 100644
--- a/app/src/main/java/com/saikou/sozo_tv/components/PlayerTvView.kt
+++ b/app/src/main/java/com/saikou/sozo_tv/components/PlayerTvView.kt
@@ -34,16 +34,7 @@ class PlayerTvView @JvmOverloads constructor(
var onNextEpisode: (() -> Unit)? = null
var onPreviousEpisode: (() -> Unit)? = null
- private var seekRunDirection = 0
- private var seekRunCount = 0
- private var seekRunLastAt = 0L
-
- private companion object {
- const val SEEK_STEP_MS = 10_000L
-
- val SEEK_LADDER_MS = longArrayOf(10_000L, 30_000L, 60_000L, 120_000L)
- const val SEEK_RUN_GAP_MS = 700L
- }
+ private val seekSteps = RemoteSeekSteps()
@OptIn(UnstableApi::class)
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
@@ -113,7 +104,7 @@ class PlayerTvView @JvmOverloads constructor(
return when (event.keyCode) {
KeyEvent.KEYCODE_DPAD_LEFT,
KeyEvent.KEYCODE_MEDIA_REWIND -> {
- seekByAndReveal(-stepFor(-1))
+ seekByAndReveal(stepFor(-1))
true
}
@@ -177,15 +168,7 @@ class PlayerTvView @JvmOverloads constructor(
}
private fun stepFor(direction: Int): Long {
- val now = android.os.SystemClock.uptimeMillis()
- if (direction != seekRunDirection || now - seekRunLastAt > SEEK_RUN_GAP_MS) {
- seekRunDirection = direction
- seekRunCount = 0
- }
- seekRunLastAt = now
- val step = SEEK_LADDER_MS[seekRunCount.coerceAtMost(SEEK_LADDER_MS.lastIndex)]
- seekRunCount++
- return step * direction
+ return seekSteps.next(direction, android.os.SystemClock.uptimeMillis())
}
private fun seekByAndReveal(deltaMs: Long) {
diff --git a/app/src/main/java/com/saikou/sozo_tv/components/RemoteSeekSteps.kt b/app/src/main/java/com/saikou/sozo_tv/components/RemoteSeekSteps.kt
new file mode 100644
index 00000000..7d1c3da5
--- /dev/null
+++ b/app/src/main/java/com/saikou/sozo_tv/components/RemoteSeekSteps.kt
@@ -0,0 +1,24 @@
+package com.saikou.sozo_tv.components
+
+/** Signed seek deltas for a run of remote key presses; changing direction resets acceleration. */
+internal class RemoteSeekSteps {
+ private var direction = 0
+ private var count = 0
+ private var lastAt = 0L
+
+ fun next(direction: Int, nowMs: Long): Long {
+ require(direction == -1 || direction == 1)
+ if (direction != this.direction || nowMs - lastAt > 700L || nowMs < lastAt) {
+ this.direction = direction
+ count = 0
+ }
+ lastAt = nowMs
+ val step = STEPS[count.coerceAtMost(STEPS.lastIndex)]
+ count = (count + 1).coerceAtMost(STEPS.lastIndex)
+ return direction * step
+ }
+
+ private companion object {
+ val STEPS = longArrayOf(10_000L, 30_000L, 60_000L, 120_000L)
+ }
+}
diff --git a/app/src/main/java/com/saikou/sozo_tv/components/SeasonalBackgroundLayout.kt b/app/src/main/java/com/saikou/sozo_tv/components/SeasonalBackgroundLayout.kt
index c39c2278..8f0d417c 100644
--- a/app/src/main/java/com/saikou/sozo_tv/components/SeasonalBackgroundLayout.kt
+++ b/app/src/main/java/com/saikou/sozo_tv/components/SeasonalBackgroundLayout.kt
@@ -36,11 +36,13 @@ class SeasonalBackgroundLayout @JvmOverloads constructor(
fun setTheme(theme: SeasonalTheme) {
if (theme == SeasonalTheme.WINTER) {
if (snow == null) snow = SnowRenderer(context)
+ snow?.onSizeChanged(width, height)
} else {
snow = null
festive = null
}
- startAnim()
+ if (hasEffects()) startAnim() else stopAnim()
+ invalidate()
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
@@ -58,7 +60,7 @@ class SeasonalBackgroundLayout @JvmOverloads constructor(
}
private fun startAnim() {
- if (animator != null) return
+ if (animator != null || !isAttachedToWindow || !hasEffects()) return
lastFrame = SystemClock.uptimeMillis()
animator = ValueAnimator.ofFloat(0f, 1f).apply {
@@ -72,9 +74,26 @@ class SeasonalBackgroundLayout @JvmOverloads constructor(
snow?.update(dt)
festive?.update(dt)
- postInvalidateOnAnimation()
+ if (hasEffects()) postInvalidateOnAnimation()
}
start()
}
}
+
+ private fun hasEffects() = snow != null || festive != null
+
+ private fun stopAnim() {
+ animator?.cancel()
+ animator = null
+ }
+
+ override fun onAttachedToWindow() {
+ super.onAttachedToWindow()
+ if (hasEffects()) startAnim()
+ }
+
+ override fun onDetachedFromWindow() {
+ stopAnim()
+ super.onDetachedFromWindow()
+ }
}
diff --git a/app/src/main/java/com/saikou/sozo_tv/data/extensions/ExtMappers.kt b/app/src/main/java/com/saikou/sozo_tv/data/extensions/ExtMappers.kt
index 3a0fb2dd..fbedc665 100644
--- a/app/src/main/java/com/saikou/sozo_tv/data/extensions/ExtMappers.kt
+++ b/app/src/main/java/com/saikou/sozo_tv/data/extensions/ExtMappers.kt
@@ -135,7 +135,7 @@ fun ExtMedia.toVod(thumbnail: String = "", language: String = ""): VodMovieRespo
return VodMovieResponse(
authInfo = "",
header = chosen?.headers ?: headers,
- subtitleList = subtitles.map { SubTitle(file = it.file, label = it.label, headers = it.headers) },
+ subtitleList = subtitles.map { SubTitle(file = it.file, label = it.label, headers = it.headers, cipher = it.cipher) },
urlobj = url,
type = mime,
thumbnail = thumbnail,
diff --git a/app/src/main/java/com/saikou/sozo_tv/data/extensions/ExtModels.kt b/app/src/main/java/com/saikou/sozo_tv/data/extensions/ExtModels.kt
index 93c46789..f417380b 100644
--- a/app/src/main/java/com/saikou/sozo_tv/data/extensions/ExtModels.kt
+++ b/app/src/main/java/com/saikou/sozo_tv/data/extensions/ExtModels.kt
@@ -1,6 +1,7 @@
package com.saikou.sozo_tv.data.extensions
import android.util.Log
+import com.saikou.sozo_tv.domain.player.SubtitleCipher
import org.json.JSONArray
import org.json.JSONObject
@@ -135,6 +136,10 @@ data class ExtVideoSource(
val sniff: String? = null, // raw JSON: patterns/timeoutMs/headers/blockHosts
/** Separate audio renditions that belong with this video (CloudStream `audioTracks`). */
val audioTracks: List = emptyList(),
+ val drm: String? = null,
+ /** Regex for ad segments the local proxy takes out of the playlist. */
+ val dropSegments: String? = null,
+ val signer: String? = null, // raw JSON, see UrlSigner
)
data class ExtAudioTrack(
@@ -153,6 +158,7 @@ data class ExtSubtitle(
val file: String,
val default: Boolean,
val headers: Map = emptyMap(),
+ val cipher: SubtitleCipher? = null,
)
data class ExtMedia(
@@ -347,11 +353,15 @@ internal object ExtParser {
fun media(json: String): ExtMedia {
val o = runCatching { JSONObject(json) }.getOrNull() ?: JSONObject()
val srcArr = o.optJSONArray("videoSources")
+ if ((srcArr == null || srcArr.length() == 0) && !o.strOrNull("error").isNullOrBlank()) {
+ error(o.optString("error"))
+ }
val sources = if (srcArr == null) emptyList() else (0 until srcArr.length()).mapNotNull { i ->
val s = srcArr.optJSONObject(i) ?: return@mapNotNull null
val url = s.optString("videoUrl").ifEmpty { return@mapNotNull null }
ExtVideoSource(
quality = s.optString("quality").ifEmpty { "Source" },
+ drm = (s.optJSONObject("drm") ?: o.optJSONObject("drm"))?.toString(),
videoUrl = url,
type = s.optString("type").ifEmpty { "hls" },
host = s.strOrNull("host"),
@@ -364,6 +374,8 @@ internal object ExtParser {
sniff = (s.optJSONObject("sniff") ?: o.optJSONObject("sniff"))?.toString(),
localProxy = s.optJSONObject("localProxy")?.toString(),
requestTransform = s.optJSONObject("requestTransform")?.toString(),
+ dropSegments = s.strOrNull("dropSegments"),
+ signer = s.optJSONObject("signer")?.toString(),
// PluginHost emits these for dual-audio releases; dropping them here left the
// player with one track and nothing to switch to.
audioTracks = s.optJSONArray("audioTracks")?.let { arr ->
@@ -384,6 +396,7 @@ internal object ExtParser {
file,
s.optBoolean("default", false),
s.headersMap("headers"),
+ SubtitleCipher.from(s.optJSONObject("cipher")),
)
}
// Seek-preview thumbnails: soplay emits a bare VTT url String or a {url,type,template,...}
diff --git a/app/src/main/java/com/saikou/sozo_tv/data/local/database/ProfileDatabaseProvider.kt b/app/src/main/java/com/saikou/sozo_tv/data/local/database/ProfileDatabaseProvider.kt
new file mode 100644
index 00000000..f8aedb06
--- /dev/null
+++ b/app/src/main/java/com/saikou/sozo_tv/data/local/database/ProfileDatabaseProvider.kt
@@ -0,0 +1,62 @@
+package com.saikou.sozo_tv.data.local.database
+
+import android.content.Context
+import androidx.room.Room
+import com.saikou.sozo_tv.data.local.pref.ActiveProfileStore
+import java.security.MessageDigest
+import java.util.concurrent.ConcurrentHashMap
+import com.saikou.sozo_tv.domain.model.HouseholdProfile
+
+/**
+ * Opens one Room database per household profile. The default profile keeps the
+ * legacy filename, so existing history and bookmarks migrate without copying.
+ * At most four profile databases can exist, therefore retaining the open Room
+ * instances is both cheap and safer than closing a database under an in-flight
+ * player/history write during a profile switch.
+ */
+class ProfileDatabaseProvider(
+ private val context: Context,
+ private val profiles: ActiveProfileStore,
+) {
+ private val databases = ConcurrentHashMap()
+
+ fun database(namespace: String? = profiles.namespace()): AppDatabase {
+ val name = namespace?.let { "movie_database_${safeKey(it)}" } ?: DEFAULT_DATABASE
+ return databases.computeIfAbsent(name) {
+ Room.databaseBuilder(context, AppDatabase::class.java, name)
+ .addMigrations(MIGRATION_1_2)
+ .build()
+ }
+ }
+
+ fun movieDao() = database().movieDao()
+ fun channelDao() = database().tvDao()
+ fun characterDao() = database().characterDao()
+ fun historyDao() = database().watchHistoryDao()
+
+ @Synchronized
+ fun delete(profile: HouseholdProfile) {
+ val name = profile.localNamespace?.let { "movie_database_${safeKey(it)}" } ?: DEFAULT_DATABASE
+ databases.remove(name)?.close()
+ context.deleteDatabase(name)
+ }
+
+ /** Sign-out removes every household member's private local library. */
+ @Synchronized
+ fun deleteAll(profiles: List) {
+ (profiles + listOfNotNull(this.profiles.current()))
+ .distinctBy { it.id }
+ .forEach(::delete)
+ databases.remove(DEFAULT_DATABASE)?.close()
+ context.deleteDatabase(DEFAULT_DATABASE)
+ }
+
+ private fun safeKey(raw: String): String = MessageDigest.getInstance("SHA-256")
+ .digest(raw.toByteArray())
+ .take(10)
+ .joinToString("") { "%02x".format(it) }
+
+ private companion object {
+ const val DEFAULT_DATABASE = "movie_database"
+ }
+}
diff --git a/app/src/main/java/com/saikou/sozo_tv/data/local/pref/ActiveProfileStore.kt b/app/src/main/java/com/saikou/sozo_tv/data/local/pref/ActiveProfileStore.kt
new file mode 100644
index 00000000..8dc4e398
--- /dev/null
+++ b/app/src/main/java/com/saikou/sozo_tv/data/local/pref/ActiveProfileStore.kt
@@ -0,0 +1,57 @@
+package com.saikou.sozo_tv.data.local.pref
+
+import android.content.Context
+import com.google.gson.Gson
+import com.saikou.sozo_tv.domain.model.HouseholdProfile
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+
+/**
+ * Device-local source of truth for the household member this TV is acting as.
+ * It is deliberately separate from the account token: switching profiles must
+ * never rotate or duplicate the device session.
+ */
+class ActiveProfileStore internal constructor(
+ private val prefs: android.content.SharedPreferences,
+ private val gson: Gson,
+) {
+ constructor(context: Context, gson: Gson) : this(
+ context.getSharedPreferences(FILE, Context.MODE_PRIVATE), gson,
+ )
+ private val _active = MutableStateFlow(read())
+
+ val active: StateFlow get() = _active
+ fun current(): HouseholdProfile? = _active.value
+ fun profileId(): String? = _active.value?.id
+ fun namespace(): String? = _active.value?.localNamespace
+ fun isKids(): Boolean = _active.value?.isKids == true
+
+ @Volatile var revision: Long = 0
+ private set
+
+ data class Snapshot(val profile: HouseholdProfile?, val revision: Long)
+
+ @Synchronized
+ fun snapshot() = Snapshot(_active.value, revision)
+
+ @Synchronized
+ fun set(profile: HouseholdProfile?) {
+ revision++
+ if (profile == null) prefs.edit().remove(KEY_ACTIVE).commit()
+ else prefs.edit().putString(KEY_ACTIVE, gson.toJson(profile)).commit()
+ _active.value = profile
+ }
+
+ fun clear() = set(null)
+
+ private fun read(): HouseholdProfile? = runCatching {
+ prefs.getString(KEY_ACTIVE, null)?.let {
+ gson.fromJson(it, HouseholdProfile::class.java)
+ }
+ }.getOrNull()
+
+ private companion object {
+ const val FILE = "sozo_household_profile"
+ const val KEY_ACTIVE = "active"
+ }
+}
diff --git a/app/src/main/java/com/saikou/sozo_tv/data/local/pref/PreferenceManager.kt b/app/src/main/java/com/saikou/sozo_tv/data/local/pref/PreferenceManager.kt
index 07a5dcdc..a4bf613b 100644
--- a/app/src/main/java/com/saikou/sozo_tv/data/local/pref/PreferenceManager.kt
+++ b/app/src/main/java/com/saikou/sozo_tv/data/local/pref/PreferenceManager.kt
@@ -11,7 +11,12 @@ import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
-class PreferenceManager(context: Context = MyApp.context) {
+class PreferenceManager(
+ context: Context = MyApp.context,
+ private val profileStore: ActiveProfileStore? = runCatching {
+ org.koin.core.context.GlobalContext.get().get()
+ }.getOrNull(),
+) {
private val prefs: SharedPreferences =
context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
@@ -45,13 +50,17 @@ class PreferenceManager(context: Context = MyApp.context) {
private const val KEY_DEMO_THEME_LEGACY = "demo_theme"
}
- fun isModeAnimeEnabled() = prefs.getBoolean(KEY_MODE_ANIME_ENABLED, true)
+ /** Viewer-facing preferences are isolated between household profiles. */
+ private fun scoped(key: String): String =
+ profileStore?.namespace()?.let { "profile_${it}__$key" } ?: key
+
+ fun isModeAnimeEnabled() = prefs.getBoolean(scoped(KEY_MODE_ANIME_ENABLED), true)
fun setModeAnime(enabled: Boolean) =
- prefs.edit().putBoolean(KEY_MODE_ANIME_ENABLED, enabled).apply()
+ prefs.edit().putBoolean(scoped(KEY_MODE_ANIME_ENABLED), enabled).apply()
- fun isSkipIntroEnabled() = prefs.getBoolean(KEY_SKIP_INTRO_ENABLED, false)
+ fun isSkipIntroEnabled() = prefs.getBoolean(scoped(KEY_SKIP_INTRO_ENABLED), false)
fun setSkipIntroEnabled(enabled: Boolean) =
- prefs.edit().putBoolean(KEY_SKIP_INTRO_ENABLED, enabled).apply()
+ prefs.edit().putBoolean(scoped(KEY_SKIP_INTRO_ENABLED), enabled).apply()
/**
* The audio language the viewer last chose, as an ISO code — null until they pick one.
@@ -59,37 +68,39 @@ class PreferenceManager(context: Context = MyApp.context) {
* Persisted because the track objects cannot be: they belong to the stream that declared
* them, so every new episode rebuilt them from scratch and the choice was silently lost.
*/
- fun getAudioLanguage(): String? = prefs.getString(KEY_AUDIO_LANGUAGE, null)
+ fun getAudioLanguage(): String? = prefs.getString(scoped(KEY_AUDIO_LANGUAGE), null)
fun setAudioLanguage(code: String?) = prefs.edit().apply {
- if (code.isNullOrBlank()) remove(KEY_AUDIO_LANGUAGE) else putString(KEY_AUDIO_LANGUAGE, code)
+ val key = scoped(KEY_AUDIO_LANGUAGE)
+ if (code.isNullOrBlank()) remove(key) else putString(key, code)
}.apply()
- fun getPlaybackSpeed(): Float = prefs.getFloat(KEY_PLAYBACK_SPEED, 1f)
- fun setPlaybackSpeed(speed: Float) = prefs.edit().putFloat(KEY_PLAYBACK_SPEED, speed).apply()
+ fun getPlaybackSpeed(): Float = prefs.getFloat(scoped(KEY_PLAYBACK_SPEED), 1f)
+ fun setPlaybackSpeed(speed: Float) = prefs.edit().putFloat(scoped(KEY_PLAYBACK_SPEED), speed).apply()
- fun getResizeModeIndex(): Int = prefs.getInt(KEY_RESIZE_MODE, 0)
- fun setResizeModeIndex(index: Int) = prefs.edit().putInt(KEY_RESIZE_MODE, index).apply()
+ fun getResizeModeIndex(): Int = prefs.getInt(scoped(KEY_RESIZE_MODE), 0)
+ fun setResizeModeIndex(index: Int) = prefs.edit().putInt(scoped(KEY_RESIZE_MODE), index).apply()
- fun isSubtitlesEnabled(): Boolean = prefs.getBoolean(KEY_SUBTITLES_ENABLED, true)
+ fun isSubtitlesEnabled(): Boolean = prefs.getBoolean(scoped(KEY_SUBTITLES_ENABLED), true)
fun setSubtitlesEnabled(enabled: Boolean) =
- prefs.edit().putBoolean(KEY_SUBTITLES_ENABLED, enabled).apply()
+ prefs.edit().putBoolean(scoped(KEY_SUBTITLES_ENABLED), enabled).apply()
- fun getSubtitleLabel(): String? = prefs.getString(KEY_SUBTITLE_LABEL, null)
+ fun getSubtitleLabel(): String? = prefs.getString(scoped(KEY_SUBTITLE_LABEL), null)
fun setSubtitleLabel(label: String?) = prefs.edit().apply {
- if (label.isNullOrBlank()) remove(KEY_SUBTITLE_LABEL) else putString(KEY_SUBTITLE_LABEL, label)
+ val key = scoped(KEY_SUBTITLE_LABEL)
+ if (label.isNullOrBlank()) remove(key) else putString(key, label)
}.apply()
- fun isNsfwEnabled() = prefs.getBoolean(KEY_NSFW_ENABLED, false)
+ fun isNsfwEnabled() = profileStore?.isKids() != true && prefs.getBoolean(scoped(KEY_NSFW_ENABLED), false)
fun setNsfwEnabled(enabled: Boolean) =
- prefs.edit().putBoolean(KEY_NSFW_ENABLED, enabled).apply()
+ prefs.edit().putBoolean(scoped(KEY_NSFW_ENABLED), enabled).apply()
- fun isHistoryEnabled() = prefs.getBoolean("history_enabled", true)
+ fun isHistoryEnabled() = prefs.getBoolean(scoped("history_enabled"), true)
fun setHistoryEnabled(enabled: Boolean) =
- prefs.edit().putBoolean("history_enabled", enabled).apply()
+ prefs.edit().putBoolean(scoped("history_enabled"), enabled).apply()
- fun isChannelEnabled() = prefs.getBoolean(KEY_CHANNEL_ENABLED, false)
+ fun isChannelEnabled() = prefs.getBoolean(scoped(KEY_CHANNEL_ENABLED), false)
fun setChannelEnabled(enabled: Boolean) =
- prefs.edit().putBoolean(KEY_CHANNEL_ENABLED, enabled).apply()
+ prefs.edit().putBoolean(scoped(KEY_CHANNEL_ENABLED), enabled).apply()
// ===== Subtitle Style =====
data class SubtitleStyle(
@@ -111,25 +122,27 @@ class PreferenceManager(context: Context = MyApp.context) {
fun getSubtitleStyle(): SubtitleStyle {
return SubtitleStyle(
- font = Font.valueOf(prefs.getString(KEY_SUBTITLE_FONT, Font.DEFAULT.name)!!),
- color = prefs.getInt(KEY_SUBTITLE_COLOR, Color.WHITE),
- sizeSp = prefs.getInt(KEY_SUBTITLE_SIZE, 16),
- background = prefs.getBoolean(KEY_SUBTITLE_BG, false),
- outline = prefs.getBoolean(KEY_SUBTITLE_OUTLINE, true)
+ font = runCatching {
+ Font.valueOf(prefs.getString(scoped(KEY_SUBTITLE_FONT), Font.DEFAULT.name)!!)
+ }.getOrDefault(Font.DEFAULT),
+ color = prefs.getInt(scoped(KEY_SUBTITLE_COLOR), Color.WHITE),
+ sizeSp = prefs.getInt(scoped(KEY_SUBTITLE_SIZE), 16),
+ background = prefs.getBoolean(scoped(KEY_SUBTITLE_BG), false),
+ outline = prefs.getBoolean(scoped(KEY_SUBTITLE_OUTLINE), true)
)
}
fun isSubtitleCustom(): Boolean =
- prefs.getBoolean(KEY_SUBTITLE_CUSTOM, false)
+ prefs.getBoolean(scoped(KEY_SUBTITLE_CUSTOM), false)
fun saveSubtitleStyle(style: SubtitleStyle) {
prefs.edit()
- .putBoolean(KEY_SUBTITLE_CUSTOM, !style.isDefault())
- .putString(KEY_SUBTITLE_FONT, style.font.name)
- .putInt(KEY_SUBTITLE_COLOR, style.color)
- .putInt(KEY_SUBTITLE_SIZE, style.sizeSp)
- .putBoolean(KEY_SUBTITLE_BG, style.background)
- .putBoolean(KEY_SUBTITLE_OUTLINE, style.outline)
+ .putBoolean(scoped(KEY_SUBTITLE_CUSTOM), !style.isDefault())
+ .putString(scoped(KEY_SUBTITLE_FONT), style.font.name)
+ .putInt(scoped(KEY_SUBTITLE_COLOR), style.color)
+ .putInt(scoped(KEY_SUBTITLE_SIZE), style.sizeSp)
+ .putBoolean(scoped(KEY_SUBTITLE_BG), style.background)
+ .putBoolean(scoped(KEY_SUBTITLE_OUTLINE), style.outline)
.apply()
}
@@ -178,17 +191,17 @@ class PreferenceManager(context: Context = MyApp.context) {
}.distinctUntilChanged()
fun isAppearanceExpanded(): Boolean =
- prefs.getBoolean(KEY_APPEARANCE_EXPANDED, true)
+ prefs.getBoolean(scoped(KEY_APPEARANCE_EXPANDED), true)
fun setAppearanceExpanded(expanded: Boolean) {
- prefs.edit().putBoolean(KEY_APPEARANCE_EXPANDED, expanded).apply()
+ prefs.edit().putBoolean(scoped(KEY_APPEARANCE_EXPANDED), expanded).apply()
}
fun isContentControlsExpanded(): Boolean =
- prefs.getBoolean(KEY_CONTENT_CONTROLS_EXPANDED, false)
+ prefs.getBoolean(scoped(KEY_CONTENT_CONTROLS_EXPANDED), false)
fun setContentControlsExpanded(expanded: Boolean) {
- prefs.edit().putBoolean(KEY_CONTENT_CONTROLS_EXPANDED, expanded).apply()
+ prefs.edit().putBoolean(scoped(KEY_CONTENT_CONTROLS_EXPANDED), expanded).apply()
}
@Deprecated("Theme UI removed. Use getSeasonalTheme()/setSeasonalTheme() or observeSeasonalTheme().")
@@ -225,7 +238,7 @@ class PreferenceManager(context: Context = MyApp.context) {
fun observeModeAnimeEnabled(): Flow = callbackFlow {
val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
- if (key == KEY_MODE_ANIME_ENABLED) trySend(isModeAnimeEnabled())
+ if (key == scoped(KEY_MODE_ANIME_ENABLED)) trySend(isModeAnimeEnabled())
}
trySend(isModeAnimeEnabled())
prefs.registerOnSharedPreferenceChangeListener(listener)
diff --git a/app/src/main/java/com/saikou/sozo_tv/data/model/VodMovieResponse.kt b/app/src/main/java/com/saikou/sozo_tv/data/model/VodMovieResponse.kt
index 22b34904..1a199b56 100644
--- a/app/src/main/java/com/saikou/sozo_tv/data/model/VodMovieResponse.kt
+++ b/app/src/main/java/com/saikou/sozo_tv/data/model/VodMovieResponse.kt
@@ -1,6 +1,7 @@
package com.saikou.sozo_tv.data.model
import androidx.media3.common.MimeTypes
+import com.saikou.sozo_tv.domain.player.SubtitleCipher
import java.io.Serializable
data class VodMovieResponse(
@@ -15,8 +16,12 @@ data class VodMovieResponse(
val useLocalProxy: Boolean = false,
val localProxyJson: String? = null,
val requestTransformJson: String? = null,
+ val dropSegments: String? = null,
+ /** [urlobj] is the unsigned file; this signs it each time it is opened. See UrlSigner. */
+ val signerJson: String? = null,
/** Separate audio renditions the player merges in alongside [urlobj]. */
val audioTracks: List = emptyList(),
+ val drm: String? = null,
) : Serializable
data class AudioTrackRef(
@@ -31,4 +36,5 @@ data class SubTitle(
val flag: String = "",
/** Headers for the subtitle request itself; empty for sources that need none. */
val headers: Map = emptyMap(),
+ val cipher: SubtitleCipher? = null,
)
\ No newline at end of file
diff --git a/app/src/main/java/com/saikou/sozo_tv/data/model/hianime/MegaSource.kt b/app/src/main/java/com/saikou/sozo_tv/data/model/hianime/MegaSource.kt
index b46e4277..1a0f735e 100644
--- a/app/src/main/java/com/saikou/sozo_tv/data/model/hianime/MegaSource.kt
+++ b/app/src/main/java/com/saikou/sozo_tv/data/model/hianime/MegaSource.kt
@@ -10,6 +10,7 @@ data class MegaTrack(
val kind: String,
/** Headers for fetching this track — see [com.saikou.sozo_tv.data.extensions.ExtSubtitle]. */
val headers: Map = emptyMap(),
+ val cipher: com.saikou.sozo_tv.domain.player.SubtitleCipher? = null,
)
data class MegaResponse(
val sources: List,
diff --git a/app/src/main/java/com/saikou/sozo_tv/data/remote/history/WatchHistorySyncClient.kt b/app/src/main/java/com/saikou/sozo_tv/data/remote/history/WatchHistorySyncClient.kt
index 5f8b7970..6db9ebd6 100644
--- a/app/src/main/java/com/saikou/sozo_tv/data/remote/history/WatchHistorySyncClient.kt
+++ b/app/src/main/java/com/saikou/sozo_tv/data/remote/history/WatchHistorySyncClient.kt
@@ -52,7 +52,7 @@ class WatchHistorySyncClient(
private val tokenProvider: suspend () -> String?,
) {
- suspend fun sync(items: List, since: String?): ApiResult =
+ suspend fun sync(items: List, since: String?, profile: com.saikou.sozo_tv.data.remote.profiles.ProfileRequestScope? = null): ApiResult =
withContext(Dispatchers.IO) {
val token = runCatching { tokenProvider() }.getOrNull()
?: return@withContext ApiResult.Http(401, "Not signed in", null)
@@ -61,6 +61,7 @@ class WatchHistorySyncClient(
val payload = gson.toJson(SyncRequest(items, since)).toRequestBody(JSON)
val request = Request.Builder()
.url("${baseUrl.trimEnd('/')}$PATH")
+ .tag(com.saikou.sozo_tv.data.remote.profiles.ProfileRequestScope::class.java, profile)
.addHeader("Authorization", "Bearer $token")
.addHeader("Accept", "application/json")
.addHeader("Content-Type", "application/json")
diff --git a/app/src/main/java/com/saikou/sozo_tv/data/remote/lists/UserListsClient.kt b/app/src/main/java/com/saikou/sozo_tv/data/remote/lists/UserListsClient.kt
index 5b80b421..56bc13ac 100644
--- a/app/src/main/java/com/saikou/sozo_tv/data/remote/lists/UserListsClient.kt
+++ b/app/src/main/java/com/saikou/sozo_tv/data/remote/lists/UserListsClient.kt
@@ -1,5 +1,6 @@
package com.saikou.sozo_tv.data.remote.lists
+import com.saikou.sozo_tv.data.remote.profiles.ProfileRequestScope
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
import com.saikou.sozo_tv.data.remote.device.ApiResult
@@ -55,22 +56,22 @@ class UserListsClient(
private val tokenProvider: suspend () -> String?,
) {
- suspend fun get(kind: UserListKind): ApiResult> =
- request(kind, "GET", null, UserListResponse::class.java)
+ suspend fun get(kind: UserListKind, profile: ProfileRequestScope? = null): ApiResult> =
+ request(kind, "GET", null, UserListResponse::class.java, profile)
.map { it.items.orEmpty().filter { i -> !i.contentUrl.isNullOrBlank() } }
- suspend fun add(kind: UserListKind, item: UserListItem): ApiResult {
+ suspend fun add(kind: UserListKind, item: UserListItem, profile: ProfileRequestScope? = null): ApiResult {
val provider = item.provider ?: return ApiResult.Http(400, "provider required", null)
val contentUrl = item.contentUrl ?: return ApiResult.Http(400, "contentUrl required", null)
return request(
kind, "POST",
AddRequest(provider, contentUrl, item.title, item.thumbnail),
- ApiMessage::class.java,
+ ApiMessage::class.java, profile,
).map { }
}
- suspend fun remove(kind: UserListKind, contentUrl: String): ApiResult =
- request(kind, "DELETE", RemoveRequest(contentUrl), ApiMessage::class.java).map { }
+ suspend fun remove(kind: UserListKind, contentUrl: String, profile: ProfileRequestScope? = null): ApiResult =
+ request(kind, "DELETE", RemoveRequest(contentUrl), ApiMessage::class.java, profile).map { }
private inline fun ApiResult.map(transform: (T) -> R): ApiResult = when (this) {
is ApiResult.Ok -> ApiResult.Ok(transform(body))
@@ -83,6 +84,7 @@ class UserListsClient(
method: String,
body: Any?,
type: Class,
+ profile: ProfileRequestScope?,
): ApiResult = withContext(Dispatchers.IO) {
// No token => not signed in. Reported as 401 so callers branch on the
// code, never on message text (the server's errors are bare strings).
@@ -93,6 +95,7 @@ class UserListsClient(
val payload = body?.let { gson.toJson(it).toRequestBody(JSON) }
val builder = Request.Builder()
.url("${baseUrl.trimEnd('/')}$PATH/${kind.slug}")
+ .tag(ProfileRequestScope::class.java, profile)
.addHeader("Authorization", "Bearer $token")
.addHeader("Accept", "application/json")
when (method) {
diff --git a/app/src/main/java/com/saikou/sozo_tv/data/remote/party/PartyWire.kt b/app/src/main/java/com/saikou/sozo_tv/data/remote/party/PartyWire.kt
new file mode 100644
index 00000000..036cf717
--- /dev/null
+++ b/app/src/main/java/com/saikou/sozo_tv/data/remote/party/PartyWire.kt
@@ -0,0 +1,41 @@
+package com.saikou.sozo_tv.data.remote.party
+
+import org.json.JSONArray
+import org.json.JSONObject
+
+/** Text-only subset used by the backend: Engine.IO4 websocket + Socket.IO /watch. */
+internal object PartyWire {
+ fun authenticate(token: String) = "40/watch," + JSONObject().put("token", token)
+ fun event(name: String, payload: JSONObject) = "42/watch," + JSONArray().put(name).put(payload)
+ fun decode(message: String): Pair? {
+ if (!message.startsWith("42/watch,")) return null
+ val data = runCatching { JSONArray(message.substringAfter("42/watch,")) }.getOrNull() ?: return null
+ val event = data.optString(0)
+ val payload = data.optJSONObject(1) ?: return null
+ return event.takeIf { it.startsWith("party:") }?.let { it to payload }
+ }
+ fun normalizeCode(code: String): String = code.trim().uppercase(java.util.Locale.ROOT).also {
+ require(it.matches(Regex("[A-Z0-9]{4,12}"))) { "Enter the room code (4–12 letters or numbers)" }
+ }
+}
+
+/** Position uses a monotonic local receipt clock, never the server wall clock. */
+data class PartyPlayback(val positionMs: Long, val playing: Boolean, val rate: Float, val receivedMs: Long) {
+ fun expected(nowMs: Long): Long = (positionMs + if (playing) ((nowMs - receivedMs).coerceAtLeast(0) * rate).toLong() else 0).coerceAtLeast(0)
+ companion object {
+ fun parse(value: JSONObject, nowMs: Long) = PartyPlayback(
+ (value.optDouble("positionSec", 0.0).takeIf { it.isFinite() }?.times(1000)?.toLong() ?: 0).coerceAtLeast(0),
+ value.optBoolean("isPlaying"), value.optDouble("rate", 1.0).toFloat().takeIf { it.isFinite() }?.coerceIn(.25f, 3f) ?: 1f, nowMs)
+ }
+}
+
+/** Local direct payloads contain signed URLs; share their catalog identity instead. */
+internal object PartyIdentity {
+ fun reference(mediaRef: String, contentUrl: String?): String {
+ require(mediaRef.isNotBlank()) { "This video has no shareable episode reference" }
+ val result = if (mediaRef.startsWith("direct::")) contentUrl?.takeIf { it.isNotBlank() && !it.startsWith("direct::") }
+ ?: error("This video has no shareable catalog identity") else mediaRef
+ require(result.length <= 500) { "This provider's episode reference is too long for watch parties" }
+ return result
+ }
+}
diff --git a/app/src/main/java/com/saikou/sozo_tv/data/remote/party/WatchPartyClient.kt b/app/src/main/java/com/saikou/sozo_tv/data/remote/party/WatchPartyClient.kt
new file mode 100644
index 00000000..ca0f7a78
--- /dev/null
+++ b/app/src/main/java/com/saikou/sozo_tv/data/remote/party/WatchPartyClient.kt
@@ -0,0 +1,108 @@
+package com.saikou.sozo_tv.data.remote.party
+
+import com.saikou.sozo_tv.BuildConfig
+import kotlinx.coroutines.*
+import okhttp3.*
+import okhttp3.HttpUrl.Companion.toHttpUrl
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.RequestBody.Companion.toRequestBody
+import org.json.JSONObject
+import java.util.concurrent.TimeUnit
+
+/** Authenticated room transport. Its client retains platform TLS and never carries source cookies. */
+class WatchPartyClient(private val tokenProvider: suspend (Boolean) -> String?, http: OkHttpClient,
+ private val scope: CoroutineScope, private val onEvent: (String, JSONObject) -> Unit,
+ private val onStatus: (String) -> Unit, baseUrl: String = BuildConfig.SOZO_API_BASE_URL) {
+ private val rest = http
+ private val socketClient = http.newBuilder().readTimeout(0, TimeUnit.MILLISECONDS).callTimeout(0, TimeUnit.MILLISECONDS).build()
+ private var socket: WebSocket? = null
+ private var connectJob: Job? = null
+ private var retry = 0
+ private var generation = 0
+ private var closed = true
+ private var connected = false
+ var code: String? = null
+ private set
+ private val base = baseUrl.trimEnd('/')
+
+ suspend fun create(content: JSONObject): String {
+ val response = request("POST", "/watch-party", JSONObject().put("content", content))
+ return response.getString("code").also(::join)
+ }
+ fun join(raw: String) {
+ val normalized = PartyWire.normalizeCode(raw)
+ leave()
+ code = normalized; closed = false; retry = 0
+ reconnect(false)
+ }
+ private fun reconnect(refresh: Boolean) {
+ if (closed) return
+ connectJob?.cancel()
+ val current = ++generation
+ connected = false
+ socket?.cancel()
+ connectJob = scope.launch {
+ if (retry > 0) delay((1000L shl retry.coerceAtMost(4)).coerceAtMost(15_000))
+ try {
+ val token = tokenProvider(refresh) ?: error("Sign in to join a watch party")
+ if (current != generation || closed) return@launch
+ onStatus(if (retry > 0) "Reconnecting…" else "Connecting…")
+ val origin = base.toHttpUrl().newBuilder().encodedPath("/socket.io/")
+ .query("EIO=4&transport=websocket").build()
+ socket = socketClient.newWebSocket(Request.Builder().url(origin).build(), object : WebSocketListener() {
+ override fun onMessage(ws: WebSocket, text: String) {
+ scope.launch {
+ if (current != generation || closed) return@launch
+ when {
+ text.startsWith("0{") -> ws.send(PartyWire.authenticate(token))
+ text == "2" -> ws.send("3")
+ text.startsWith("40/watch,") -> {
+ connected = true; retry = 0
+ emit("party:join", JSONObject()); onStatus("Joining room…")
+ }
+ text.startsWith("44/watch,") -> {
+ if (!refresh) reconnect(true) else { onStatus("Sign in again to join this room"); leave() }
+ }
+ else -> PartyWire.decode(text)?.let { (event, payload) -> onEvent(event, payload) }
+ }
+ }
+ }
+ override fun onFailure(ws: WebSocket, t: Throwable, response: Response?) = lost(current)
+ override fun onClosed(ws: WebSocket, code: Int, reason: String) = lost(current)
+ override fun onClosing(ws: WebSocket, code: Int, reason: String) { ws.close(code, reason) }
+ })
+ delay(15_000)
+ if (current == generation && !connected && !closed) { onStatus("Room connection timed out"); lost(current) }
+ } catch (c: CancellationException) { throw c }
+ catch (e: Exception) { onStatus(e.message ?: "Could not connect"); lost(current) }
+ }
+ }
+ private fun lost(current: Int) {
+ scope.launch {
+ if (current != generation || closed) return@launch
+ connected = false; retry++
+ if (retry > 6) { onStatus("Connection lost. Leave and join the room again."); return@launch }
+ reconnect(false)
+ }
+ }
+ fun emit(event: String, payload: JSONObject) {
+ val room = code ?: return
+ if (connected) socket?.send(PartyWire.event(event, JSONObject(payload.toString()).put("code", room)))
+ }
+ suspend fun closeRoom() { code?.let { request("DELETE", "/watch-party/$it", null) }; leave() }
+ fun leave() {
+ emit("party:leave", JSONObject())
+ closed = true; connected = false; generation++; connectJob?.cancel()
+ socket?.close(1000, "Leaving room"); socket = null; code = null
+ }
+ private suspend fun request(method: String, path: String, payload: JSONObject?): JSONObject = withContext(Dispatchers.IO) {
+ val token = tokenProvider(false) ?: error("Sign in to use watch parties")
+ val body = payload?.toString()?.toRequestBody("application/json".toMediaType())
+ rest.newCall(Request.Builder().url(base + path).header("Authorization", "Bearer $token")
+ .method(method, body).build()).execute().use { response ->
+ val data = runCatching { JSONObject(response.body?.string().orEmpty()) }.getOrDefault(JSONObject())
+ check(response.isSuccessful) { data.optString("message").ifBlank { "Room request failed (HTTP ${response.code})" } }
+ data
+ }
+ }
+}
diff --git a/app/src/main/java/com/saikou/sozo_tv/data/remote/profiles/ProfileRequestScope.kt b/app/src/main/java/com/saikou/sozo_tv/data/remote/profiles/ProfileRequestScope.kt
new file mode 100644
index 00000000..4c4cb7c2
--- /dev/null
+++ b/app/src/main/java/com/saikou/sozo_tv/data/remote/profiles/ProfileRequestScope.kt
@@ -0,0 +1,19 @@
+package com.saikou.sozo_tv.data.remote.profiles
+
+import okhttp3.Interceptor
+import okhttp3.Response
+
+/** An explicit null means the captured legacy/default profile, never the current profile. */
+data class ProfileRequestScope(val id: String?)
+
+class ProfileHeaderInterceptor(private val activeProfile: () -> String?) : Interceptor {
+ override fun intercept(chain: Interceptor.Chain): Response {
+ val request = chain.request()
+ val scope = request.tag(ProfileRequestScope::class.java)
+ val id = if (scope != null) scope.id else activeProfile()
+ val next = request.newBuilder().removeHeader("X-Sozo-Profile").apply {
+ if (!id.isNullOrBlank()) header("X-Sozo-Profile", id)
+ }.build()
+ return chain.proceed(next)
+ }
+}
diff --git a/app/src/main/java/com/saikou/sozo_tv/data/remote/profiles/ProfilesClient.kt b/app/src/main/java/com/saikou/sozo_tv/data/remote/profiles/ProfilesClient.kt
new file mode 100644
index 00000000..ed0e7cbb
--- /dev/null
+++ b/app/src/main/java/com/saikou/sozo_tv/data/remote/profiles/ProfilesClient.kt
@@ -0,0 +1,104 @@
+package com.saikou.sozo_tv.data.remote.profiles
+
+import com.google.gson.Gson
+import com.saikou.sozo_tv.data.remote.device.ApiResult
+import com.saikou.sozo_tv.domain.model.HouseholdProfile
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.RequestBody.Companion.toRequestBody
+
+data class ProfilesListing(
+ val profiles: List,
+ val activeProfileId: String?,
+ val max: Int,
+)
+
+private data class ProfileDto(
+ val id: String?, val name: String?, val avatar: String?, val color: String?,
+ val isKids: Boolean = false, val isDefault: Boolean = false,
+) {
+ fun domain() = HouseholdProfile(
+ id = id.orEmpty(), name = name.orEmpty(), avatar = avatar, color = color,
+ isKids = isKids, isDefault = isDefault,
+ )
+}
+
+private data class ListingDto(
+ val profiles: List = emptyList(),
+ val activeProfileId: String? = null,
+ val max: Int = 4,
+)
+private data class ProfileEnvelope(val profile: ProfileDto?)
+private data class ErrorEnvelope(val message: String?, val code: String?)
+
+class ProfilesClient(
+ private val client: OkHttpClient,
+ private val gson: Gson,
+ private val baseUrl: String,
+ private val tokenProvider: suspend () -> String?,
+) {
+ suspend fun list(): ApiResult = call("/auth/profiles", "GET") { raw ->
+ val body = gson.fromJson(raw, ListingDto::class.java)
+ ProfilesListing(body.profiles.map(ProfileDto::domain), body.activeProfileId, body.max.coerceAtMost(4))
+ }
+
+ suspend fun create(name: String, avatar: String?, color: String?, isKids: Boolean) =
+ mutate("/auth/profiles", "POST", mapOf(
+ "name" to name, "avatar" to avatar, "color" to color, "isKids" to isKids,
+ ))
+
+ suspend fun update(id: String, changes: Map) =
+ mutate("/auth/profiles/$id", "PATCH", changes)
+
+ suspend fun delete(id: String): ApiResult =
+ call("/auth/profiles/$id", "DELETE", emptyMap()) { Unit }
+
+ private suspend fun mutate(path: String, method: String, body: Any): ApiResult =
+ call(path, method, body) { raw ->
+ gson.fromJson(raw, ProfileEnvelope::class.java).profile?.domain()
+ ?: throw IllegalStateException("Profile response was empty")
+ }
+
+ private suspend fun call(
+ path: String,
+ method: String,
+ body: Any? = null,
+ decode: (String) -> T,
+ ): ApiResult = withContext(Dispatchers.IO) {
+ val token = runCatching { tokenProvider() }.getOrNull()
+ ?: return@withContext ApiResult.Http(401, "Not signed in", null)
+ try {
+ val requestBody = body?.let { gson.toJson(it).toRequestBody(JSON) }
+ val request = Request.Builder()
+ .url(baseUrl.trimEnd('/') + path)
+ .addHeader("Authorization", "Bearer $token")
+ .addHeader("Accept", "application/json")
+ .apply {
+ when (method) {
+ "GET" -> get()
+ "POST" -> post(requireNotNull(requestBody))
+ "PATCH" -> patch(requireNotNull(requestBody))
+ "DELETE" -> delete(requestBody)
+ }
+ }
+ .build()
+ client.newCall(request).execute().use { response ->
+ val raw = response.body.string()
+ if (!response.isSuccessful) {
+ val error = runCatching { gson.fromJson(raw, ErrorEnvelope::class.java) }.getOrNull()
+ return@use ApiResult.Http(response.code, error?.message ?: error?.code, null)
+ }
+ ApiResult.Ok(decode(raw))
+ }
+ } catch (t: Throwable) {
+ ApiResult.Network(t)
+ }
+ }
+
+ private companion object {
+ val JSON = "application/json; charset=utf-8".toMediaType()
+ }
+}
diff --git a/app/src/main/java/com/saikou/sozo_tv/data/repository/CharacterBookmarkRepositoryImpl.kt b/app/src/main/java/com/saikou/sozo_tv/data/repository/CharacterBookmarkRepositoryImpl.kt
index dbabb9da..21eff79a 100644
--- a/app/src/main/java/com/saikou/sozo_tv/data/repository/CharacterBookmarkRepositoryImpl.kt
+++ b/app/src/main/java/com/saikou/sozo_tv/data/repository/CharacterBookmarkRepositoryImpl.kt
@@ -1,10 +1,11 @@
package com.saikou.sozo_tv.data.repository
-import com.saikou.sozo_tv.data.local.dao.CharacterDao
+import com.saikou.sozo_tv.data.local.database.ProfileDatabaseProvider
import com.saikou.sozo_tv.data.local.entity.CharacterEntity
import com.saikou.sozo_tv.domain.repository.CharacterBookmarkRepository
-class CharacterBookmarkRepositoryImpl(private val dao: CharacterDao) : CharacterBookmarkRepository {
+class CharacterBookmarkRepositoryImpl(private val databases: ProfileDatabaseProvider) : CharacterBookmarkRepository {
+ private val dao get() = databases.characterDao()
override suspend fun addBookmark(movie: CharacterEntity) {
dao.insertBookmark(movie)
}
@@ -24,4 +25,4 @@ class CharacterBookmarkRepositoryImpl(private val dao: CharacterDao) : Character
override suspend fun clearAllBookmarks() {
dao.clearAllBookmarks()
}
-}
\ No newline at end of file
+}
diff --git a/app/src/main/java/com/saikou/sozo_tv/data/repository/HouseholdProfileRepository.kt b/app/src/main/java/com/saikou/sozo_tv/data/repository/HouseholdProfileRepository.kt
new file mode 100644
index 00000000..99805f43
--- /dev/null
+++ b/app/src/main/java/com/saikou/sozo_tv/data/repository/HouseholdProfileRepository.kt
@@ -0,0 +1,130 @@
+package com.saikou.sozo_tv.data.repository
+
+import android.content.Context
+import com.google.gson.Gson
+import com.google.gson.reflect.TypeToken
+import com.saikou.sozo_tv.data.local.pref.ActiveProfileStore
+import com.saikou.sozo_tv.data.local.database.ProfileDatabaseProvider
+import com.saikou.sozo_tv.data.remote.device.ApiResult
+import com.saikou.sozo_tv.data.remote.profiles.ProfilesClient
+import com.saikou.sozo_tv.domain.model.HouseholdProfile
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+
+data class HouseholdProfilesState(
+ val profiles: List = emptyList(),
+ val active: HouseholdProfile? = null,
+ val max: Int = 4,
+ val loading: Boolean = false,
+ val error: String? = null,
+)
+
+/** Owns list/selection/cache semantics; screens only render [state] and call commands. */
+class HouseholdProfileRepository(
+ context: Context,
+ private val client: ProfilesClient,
+ private val activeStore: ActiveProfileStore,
+ private val gson: Gson,
+ private val databases: ProfileDatabaseProvider,
+) {
+ private val prefs = context.getSharedPreferences(FILE, Context.MODE_PRIVATE)
+ private val _state = MutableStateFlow(readCache())
+ val state: StateFlow get() = _state
+
+ suspend fun refresh(): Boolean {
+ _state.value = _state.value.copy(loading = true, error = null)
+ return when (val result = client.list()) {
+ is ApiResult.Ok -> {
+ val profiles = result.body.profiles.filter { it.id.isNotBlank() }
+ val stored = activeStore.current()
+ val active = profiles.firstOrNull { it.id == stored?.id }
+ ?: profiles.firstOrNull { it.id == result.body.activeProfileId }
+ ?: profiles.firstOrNull { it.isDefault }
+ ?: profiles.firstOrNull()
+ activeStore.set(active)
+ _state.value = HouseholdProfilesState(profiles, active, result.body.max)
+ persist(profiles, result.body.max)
+ true
+ }
+ is ApiResult.Http -> fail(result.message ?: "Profiles could not be loaded")
+ is ApiResult.Network -> fail(result.cause.message ?: "Network error")
+ }
+ }
+
+ fun activate(profile: HouseholdProfile) {
+ activeStore.set(profile)
+ _state.value = _state.value.copy(active = profile, error = null)
+ }
+
+ suspend fun create(name: String, avatar: String?, color: String?, kids: Boolean): Boolean =
+ when (val result = client.create(name.trim(), avatar, color, kids)) {
+ is ApiResult.Ok -> {
+ val list = _state.value.profiles + result.body
+ _state.value = _state.value.copy(profiles = list, error = null)
+ persist(list, _state.value.max)
+ true
+ }
+ is ApiResult.Http -> fail(result.message ?: "Profile could not be created")
+ is ApiResult.Network -> fail(result.cause.message ?: "Network error")
+ }
+
+ suspend fun update(id: String, changes: Map): Boolean =
+ when (val result = client.update(id, changes)) {
+ is ApiResult.Ok -> {
+ val list = _state.value.profiles.map { if (it.id == id) result.body else it }
+ if (_state.value.active?.id == id) activeStore.set(result.body)
+ _state.value = _state.value.copy(
+ profiles = list,
+ active = if (_state.value.active?.id == id) result.body else _state.value.active,
+ error = null,
+ )
+ persist(list, _state.value.max)
+ true
+ }
+ is ApiResult.Http -> fail(result.message ?: "Profile could not be updated")
+ is ApiResult.Network -> fail(result.cause.message ?: "Network error")
+ }
+
+ suspend fun delete(id: String): Boolean = when (val result = client.delete(id)) {
+ is ApiResult.Ok -> {
+ _state.value.profiles.firstOrNull { it.id == id }?.let(databases::delete)
+ val list = _state.value.profiles.filterNot { it.id == id }
+ val active = if (_state.value.active?.id == id) list.firstOrNull { it.isDefault } else _state.value.active
+ if (_state.value.active?.id == id) activeStore.set(active)
+ _state.value = _state.value.copy(profiles = list, active = active, error = null)
+ persist(list, _state.value.max)
+ true
+ }
+ is ApiResult.Http -> fail(result.message ?: "Profile could not be deleted")
+ is ApiResult.Network -> fail(result.cause.message ?: "Network error")
+ }
+
+ fun clear() {
+ databases.deleteAll(_state.value.profiles)
+ prefs.edit().clear().apply()
+ activeStore.clear()
+ _state.value = HouseholdProfilesState()
+ }
+
+ private fun fail(message: String): Boolean {
+ _state.value = _state.value.copy(loading = false, error = message)
+ return false
+ }
+
+ private fun persist(profiles: List, max: Int) {
+ prefs.edit().putString(KEY_LIST, gson.toJson(profiles)).putInt(KEY_MAX, max).apply()
+ }
+
+ private fun readCache(): HouseholdProfilesState = runCatching {
+ val type = object : TypeToken>() {}.type
+ val list: List = gson.fromJson(prefs.getString(KEY_LIST, "[]"), type)
+ val active = activeStore.current()?.let { a -> list.firstOrNull { it.id == a.id } ?: a }
+ HouseholdProfilesState(list, active, prefs.getInt(KEY_MAX, 4))
+ }.getOrDefault(HouseholdProfilesState(active = activeStore.current()))
+
+ private companion object {
+ const val FILE = "sozo_household_profiles"
+ const val KEY_LIST = "profiles"
+ const val KEY_MAX = "max"
+ }
+}
diff --git a/app/src/main/java/com/saikou/sozo_tv/data/repository/MovieBookmarkRepositoryImpl.kt b/app/src/main/java/com/saikou/sozo_tv/data/repository/MovieBookmarkRepositoryImpl.kt
index fee03b81..34f737cb 100644
--- a/app/src/main/java/com/saikou/sozo_tv/data/repository/MovieBookmarkRepositoryImpl.kt
+++ b/app/src/main/java/com/saikou/sozo_tv/data/repository/MovieBookmarkRepositoryImpl.kt
@@ -1,10 +1,12 @@
package com.saikou.sozo_tv.data.repository
-import com.saikou.sozo_tv.data.local.dao.MovieDao
+import com.saikou.sozo_tv.data.local.database.ProfileDatabaseProvider
import com.saikou.sozo_tv.data.local.entity.AnimeBookmark
import com.saikou.sozo_tv.domain.repository.MovieBookmarkRepository
-class MovieBookmarkRepositoryImpl(private val dao: MovieDao) : MovieBookmarkRepository {
+class MovieBookmarkRepositoryImpl(private val databases: ProfileDatabaseProvider) : MovieBookmarkRepository {
+
+ private val dao get() = databases.movieDao()
override suspend fun addBookmark(movie: AnimeBookmark) {
dao.insertBookmark(movie)
diff --git a/app/src/main/java/com/saikou/sozo_tv/data/repository/UserListsRepository.kt b/app/src/main/java/com/saikou/sozo_tv/data/repository/UserListsRepository.kt
index 418a4f34..dbc995b2 100644
--- a/app/src/main/java/com/saikou/sozo_tv/data/repository/UserListsRepository.kt
+++ b/app/src/main/java/com/saikou/sozo_tv/data/repository/UserListsRepository.kt
@@ -7,8 +7,12 @@ import com.saikou.sozo_tv.data.remote.device.ApiResult
import com.saikou.sozo_tv.data.remote.lists.UserListItem
import com.saikou.sozo_tv.data.remote.lists.UserListKind
import com.saikou.sozo_tv.data.remote.lists.UserListsClient
+import com.saikou.sozo_tv.data.local.pref.ActiveProfileStore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import java.util.concurrent.atomic.AtomicLong
/**
* Cache-first, server-authoritative — the same contract the Flutter client uses,
@@ -19,27 +23,37 @@ import kotlinx.coroutines.withContext
* missing migration is a crash-on-launch for every existing install. These lists
* are small, bounded server-side at 500, and only ever read whole.
*/
-class UserListsRepository(
- context: Context,
+class UserListsRepository internal constructor(
+ private val prefs: android.content.SharedPreferences,
private val client: UserListsClient,
+ private val profileStore: ActiveProfileStore,
private val gson: Gson = Gson(),
) {
- private val prefs = context.getSharedPreferences(FILE, Context.MODE_PRIVATE)
+ constructor(context: Context, client: UserListsClient, profileStore: ActiveProfileStore, gson: Gson = Gson()) :
+ this(context.getSharedPreferences(FILE, Context.MODE_PRIVATE), client, profileStore, gson)
+ private val mutations = Mutex()
+ private val cacheGuard = Any()
+ private val accountGeneration = AtomicLong()
private val itemsType = object : TypeToken>() {}.type
- fun cached(kind: UserListKind): List {
- val raw = prefs.getString(kind.slug, null) ?: return emptyList()
+ fun cached(kind: UserListKind): List = cached(kind, profileStore.namespace())
+
+ private fun cached(kind: UserListKind, namespace: String?): List {
+ val raw = prefs.getString(key(kind, namespace), null) ?: return emptyList()
return runCatching { gson.fromJson>(raw, itemsType) }
.getOrNull()
?.filter { !it.contentUrl.isNullOrBlank() }
?: emptyList()
}
- private fun store(kind: UserListKind, items: List) {
- prefs.edit().putString(kind.slug, gson.toJson(items)).apply()
+ private fun store(kind: UserListKind, items: List, namespace: String?) {
+ prefs.edit().putString(key(kind, namespace), gson.toJson(items)).apply()
}
+ private fun key(kind: UserListKind, namespace: String?): String =
+ namespace?.let { "profile_${it}__${kind.slug}" } ?: kind.slug
+
fun contains(kind: UserListKind, contentUrl: String): Boolean =
cached(kind).any { it.contentUrl == contentUrl }
@@ -48,37 +62,63 @@ class UserListsRepository(
* a curated list going blank because the network blinked is worse than a
* slightly stale one.
*/
- suspend fun refresh(kind: UserListKind): List = withContext(Dispatchers.IO) {
- when (val r = client.get(kind)) {
- is ApiResult.Ok -> r.body.also { store(kind, it) }
- else -> cached(kind)
- }
+ suspend fun refresh(kind: UserListKind): List {
+ val captured = profileStore.snapshot()
+ val generation = accountGeneration.get()
+ return mutations.withLock { withContext(Dispatchers.IO) {
+ val profile = captured.profile
+ val namespace = profile?.localNamespace
+ if (captured.revision != profileStore.revision || generation != accountGeneration.get()) return@withContext emptyList()
+ val result = client.get(kind, com.saikou.sozo_tv.data.remote.profiles.ProfileRequestScope(profile?.id))
+ synchronized(cacheGuard) {
+ if (captured.revision != profileStore.revision || generation != accountGeneration.get()) return@withContext emptyList()
+ when (val r = result) {
+ is ApiResult.Ok -> r.body.also { store(kind, it, namespace) }
+ else -> cached(kind, namespace)
+ }
+ }
+ } }
}
- /** Optimistic: the cache (and therefore the button) updates before the call. */
- suspend fun add(kind: UserListKind, item: UserListItem) = withContext(Dispatchers.IO) {
- val url = item.contentUrl ?: return@withContext
- store(kind, listOf(item) + cached(kind).filterNot { it.contentUrl == url })
- // Mirror the server's rule locally: Watched evicts from Watch Later,
- // or that tab keeps showing the title until the next refresh.
- if (kind == UserListKind.WATCHED) {
- store(
- UserListKind.WATCH_LATER,
- cached(UserListKind.WATCH_LATER).filterNot { it.contentUrl == url },
- )
- }
- client.add(kind, item)
- Unit
+ /** Optimistic cache updates are serialized with refresh and bound to the profile at the tap. */
+ suspend fun add(kind: UserListKind, item: UserListItem) {
+ val captured = profileStore.snapshot()
+ val generation = accountGeneration.get()
+ mutations.withLock { withContext(Dispatchers.IO) {
+ val profile = captured.profile
+ val namespace = profile?.localNamespace
+ val url = item.contentUrl ?: return@withContext
+ synchronized(cacheGuard) {
+ if (captured.revision != profileStore.revision || generation != accountGeneration.get()) return@withContext
+ store(kind, listOf(item) + cached(kind, namespace).filterNot { it.contentUrl == url }, namespace)
+ if (kind == UserListKind.WATCHED) {
+ store(UserListKind.WATCH_LATER,
+ cached(UserListKind.WATCH_LATER, namespace).filterNot { it.contentUrl == url }, namespace)
+ }
+ }
+ if (captured.revision != profileStore.revision || generation != accountGeneration.get()) return@withContext
+ client.add(kind, item, com.saikou.sozo_tv.data.remote.profiles.ProfileRequestScope(profile?.id))
+ } }
}
- suspend fun remove(kind: UserListKind, contentUrl: String) = withContext(Dispatchers.IO) {
- store(kind, cached(kind).filterNot { it.contentUrl == contentUrl })
- client.remove(kind, contentUrl)
- Unit
+ suspend fun remove(kind: UserListKind, contentUrl: String) {
+ val captured = profileStore.snapshot()
+ val generation = accountGeneration.get()
+ mutations.withLock { withContext(Dispatchers.IO) {
+ val profile = captured.profile
+ val namespace = profile?.localNamespace
+ synchronized(cacheGuard) {
+ if (captured.revision != profileStore.revision || generation != accountGeneration.get()) return@withContext
+ store(kind, cached(kind, namespace).filterNot { it.contentUrl == contentUrl }, namespace)
+ }
+ if (captured.revision != profileStore.revision || generation != accountGeneration.get()) return@withContext
+ client.remove(kind, contentUrl, com.saikou.sozo_tv.data.remote.profiles.ProfileRequestScope(profile?.id))
+ } }
}
/** Sign-out must not leave another account's lists on the box. */
- fun clear() {
+ fun clear() = synchronized(cacheGuard) {
+ accountGeneration.incrementAndGet()
prefs.edit().clear().apply()
}
diff --git a/app/src/main/java/com/saikou/sozo_tv/data/repository/WatchHistoryRepositoryImpl.kt b/app/src/main/java/com/saikou/sozo_tv/data/repository/WatchHistoryRepositoryImpl.kt
index 9b170ece..c8752129 100644
--- a/app/src/main/java/com/saikou/sozo_tv/data/repository/WatchHistoryRepositoryImpl.kt
+++ b/app/src/main/java/com/saikou/sozo_tv/data/repository/WatchHistoryRepositoryImpl.kt
@@ -1,13 +1,21 @@
package com.saikou.sozo_tv.data.repository
-import com.saikou.sozo_tv.data.local.dao.WatchHistoryDao
+import com.saikou.sozo_tv.data.local.database.ProfileDatabaseProvider
import com.saikou.sozo_tv.data.local.entity.WatchHistoryEntity
import com.saikou.sozo_tv.domain.repository.WatchHistoryRepository
-class WatchHistoryRepositoryImpl(private val watchHistoryDao: WatchHistoryDao) :
+class WatchHistoryRepositoryImpl(
+ private val databases: ProfileDatabaseProvider,
+ private val pinnedDao: com.saikou.sozo_tv.data.local.dao.WatchHistoryDao? = null,
+) :
WatchHistoryRepository {
+ private val watchHistoryDao get() = pinnedDao ?: databases.historyDao()
+
+ override fun snapshot(namespace: String?): WatchHistoryRepository =
+ WatchHistoryRepositoryImpl(databases, databases.database(namespace).watchHistoryDao())
+
override suspend fun addHistory(history: WatchHistoryEntity) {
watchHistoryDao.insertOrUpdate(history)
}
diff --git a/app/src/main/java/com/saikou/sozo_tv/data/repository/WatchHistorySyncRepository.kt b/app/src/main/java/com/saikou/sozo_tv/data/repository/WatchHistorySyncRepository.kt
index 234a222b..292c40ab 100644
--- a/app/src/main/java/com/saikou/sozo_tv/data/repository/WatchHistorySyncRepository.kt
+++ b/app/src/main/java/com/saikou/sozo_tv/data/repository/WatchHistorySyncRepository.kt
@@ -5,10 +5,12 @@ import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.saikou.sozo_tv.data.local.entity.WatchHistoryEntity
import com.saikou.sozo_tv.data.remote.device.ApiResult
+import com.saikou.sozo_tv.data.local.pref.ActiveProfileStore
import com.saikou.sozo_tv.data.remote.history.HistorySyncItem
import com.saikou.sozo_tv.data.remote.history.WatchHistorySyncClient
import com.saikou.sozo_tv.domain.repository.WatchHistoryRepository
import com.saikou.sozo_tv.parser.sources.ExtensionParser
+import com.saikou.sozo_tv.domain.player.HistoryIdentity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
@@ -22,42 +24,78 @@ import java.util.Date
import java.util.Locale
import java.util.TimeZone
-class WatchHistorySyncRepository(
- context: Context,
+class WatchHistorySyncRepository internal constructor(
+ private val prefs: android.content.SharedPreferences,
private val client: WatchHistorySyncClient,
private val local: WatchHistoryRepository,
+ private val profileStore: ActiveProfileStore,
private val gson: Gson = Gson(),
) {
- private val prefs = context.getSharedPreferences(FILE, Context.MODE_PRIVATE)
+ constructor(
+ context: Context,
+ client: WatchHistorySyncClient,
+ local: WatchHistoryRepository,
+ profileStore: ActiveProfileStore,
+ gson: Gson = Gson(),
+ ) : this(context.getSharedPreferences(FILE, Context.MODE_PRIVATE), client, local, profileStore, gson)
private val mutex = Mutex()
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val tombstoneType = object : TypeToken