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 image

@@ -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>() {}.type - val hasSynced: Boolean get() = prefs.getString(KEY_CURSOR, null) != null + private fun key(value: String, namespace: String? = profileStore.namespace()): String = + namespace?.let { "profile_${it}__$value" } ?: value + + val hasSynced: Boolean get() = prefs.getString(key(KEY_CURSOR), null) != null suspend fun sync(): Boolean = mutex.withLock { withContext(Dispatchers.IO) { - val cursor = prefs.getString(KEY_CURSOR, null) - val tombstones = readTombstones() - + val captured = profileStore.snapshot() + val revision = captured.revision + val profile = captured.profile + val namespace = profile?.localNamespace + val storage = local.snapshot(namespace) + fun scoped(value: String) = key(value, namespace) + var cursor = prefs.getString(scoped(KEY_CURSOR), null) + val needsMigration = prefs.getInt(scoped(KEY_IDENTITY_VERSION), 0) < IDENTITY_VERSION + val requestScope = com.saikou.sozo_tv.data.remote.profiles.ProfileRequestScope(profile?.id) + // Pull retained tombstones before replaying old rows under a canonical name. A null + // cursor omits tombstones on the API; epoch explicitly requests them during migration. + if (needsMigration) { + if (revision != profileStore.revision) return@withContext false + when (val pull = client.sync(emptyList(), isoOf(0), requestScope)) { + is ApiResult.Ok -> { + if (revision != profileStore.revision) return@withContext false + applyRemote(pull.body.items, storage, namespace) + cursor = pull.body.serverTime ?: cursor + } + else -> return@withContext false + } + } + val tombstones = readTombstones(namespace) + val remoteDeleted = readDeleted(namespace) val outgoing = buildList { - val floor = prefs.getLong(KEY_PUSHED_AT, 0L) - local.getAllHistory() - .filter { it.watchedAt > floor } + val floor = if (needsMigration) 0L else prefs.getLong(scoped(KEY_PUSHED_AT), 0L) + storage.getAllHistory().groupBy { it.syncKey() }.values + .filter { it.size == 1 }.map { it.single() } + .filter { it.watchedAt > floor && it.watchedAt > (it.syncKey()?.let(remoteDeleted::get) ?: 0L) } .forEach { add(it.toSyncItem()) } tombstones.forEach { (key, deletedAt) -> add(HistorySyncItem(provider = "", key = key, deletedAt = deletedAt, watchedAt = deletedAt)) } } - when (val result = client.sync(outgoing, cursor)) { + if (revision != profileStore.revision) return@withContext false + when (val result = client.sync(outgoing, cursor, requestScope)) { is ApiResult.Ok -> { - applyRemote(result.body.items) + // Sign-out/profile switch invalidates this response; retry from its old cursor later. + if (revision != profileStore.revision) return@withContext false + applyRemote(result.body.items, storage, namespace) prefs.edit() - .putString(KEY_CURSOR, result.body.serverTime ?: cursor) - .putLong(KEY_PUSHED_AT, outgoing.maxOfOrNull { parseIso(it.watchedAt) } ?: prefs.getLong(KEY_PUSHED_AT, 0L)) - .remove(KEY_TOMBSTONES) + .putString(scoped(KEY_CURSOR), result.body.serverTime ?: cursor) + .putInt(scoped(KEY_IDENTITY_VERSION), IDENTITY_VERSION) + .putLong(scoped(KEY_PUSHED_AT), outgoing.maxOfOrNull { parseIso(it.watchedAt) } ?: prefs.getLong(scoped(KEY_PUSHED_AT), 0L)) + .remove(scoped(KEY_TOMBSTONES)) .apply() true } @@ -69,16 +107,22 @@ class WatchHistorySyncRepository( fun syncAsync(): Job = scope.launch { runCatching { sync() } } suspend fun rememberDeleted(entity: WatchHistoryEntity) { - val key = entity.syncKey() ?: return - mutex.withLock { writeTombstone(key) } + val namespace = profileStore.namespace() + val keys = entity.syncKeys() + if (keys.isEmpty()) return + mutex.withLock { + val now = nowIso() + writeTombstones(readTombstones(namespace) + keys.associateWith { now }, namespace) + } } suspend fun rememberClearedAll() { - val keys = local.getAllHistory().mapNotNull { it.syncKey() } + val namespace = profileStore.namespace() + val keys = local.snapshot(namespace).getAllHistory().flatMap { it.syncKeys() } if (keys.isEmpty()) return mutex.withLock { val now = nowIso() - writeTombstones(readTombstones() + keys.associateWith { now }) + writeTombstones(readTombstones(namespace) + keys.associateWith { now }, namespace) } } @@ -90,64 +134,77 @@ class WatchHistorySyncRepository( * scope because sign-out relaunches the task and tears down the caller's ViewModel. */ fun forgetAccount(): Job { + val storage = local.snapshot(profileStore.namespace()) clear() return scope.launch { - mutex.withLock { runCatching { local.clearAllHistory() } } + mutex.withLock { runCatching { storage.clearAllHistory() } } } } - private suspend fun applyRemote(items: List) { - for (item in items) { - val key = item.key ?: continue - val session = item.extra?.get(EXTRA_SESSION) as? String - - if (item.deletedAt != null) { - session?.let { local.removeHistory(it) } - continue + private suspend fun applyRemote(items: List, storage: WatchHistoryRepository, namespace: String?) { + val deleted = readDeleted(namespace).toMutableMap() + // Local pending deletes also block an old live alias until the server acknowledges them. + readTombstones(namespace).forEach { (legacy, at) -> + val key = HistoryIdentity.canonicalKey(legacy) + deleted[key] = maxOf(deleted[key] ?: 0L, parseIso(at)) + } + items.filter { it.deletedAt != null }.forEach { item -> + item.key?.let(HistoryIdentity::canonicalKey)?.let { key -> + deleted[key] = maxOf(deleted[key] ?: 0L, parseIso(item.deletedAt)) } - - val existing = session?.let { local.getWatchHistoryById(it) } - ?: findByKey(key) - - when { - existing != null -> { - if (item.watchedAtMillis() > existing.watchedAt) { - local.addHistory( - existing.copy( - lastPosition = item.positionMs, - totalDuration = if (item.durationMs > 0) item.durationMs else existing.totalDuration, - watchedAt = item.watchedAtMillis(), - ) - ) - } - } - item.extra != null && session != null -> { - item.toEntity(session)?.let { local.addHistory(it) } - } - else -> Unit + } + // Delete before processing live rows, and retain the deletion watermark across later pulls. + for ((key, at) in deleted) { + findByKey(key, storage)?.takeIf { it.watchedAt <= at }?.let { storage.removeHistory(it.session) } + } + for (item in items.filter { it.deletedAt == null }) { + val key = item.key?.let(HistoryIdentity::canonicalKey) ?: continue + if (parseIso(item.watchedAt) <= (deleted[key] ?: -1L)) continue + val matches = storage.getAllHistory().filter { it.syncKey() == key } + // A key without season cannot identify one of two season-reset episodes safely. + if (matches.size > 1) continue + val existing = matches.singleOrNull() + if (existing != null) { + if (item.watchedAtMillis() > existing.watchedAt) storage.addHistory(existing.copy( + lastPosition = item.positionMs, + totalDuration = if (item.durationMs > 0) item.durationMs else existing.totalDuration, + watchedAt = item.watchedAtMillis(), + )) + } else { + // Phone-only rows carry no resolvable TV episode reference; never invent one. + val session = item.extra?.get(EXTRA_SESSION) as? String ?: continue + val restored = item.toEntity(session) ?: continue + if (restored.syncKey() == key && storage.getWatchHistoryById(session) == null) + storage.addHistory(restored) } } + val bounded = deleted.entries.sortedByDescending { it.value }.take(300).associate { it.toPair() } + prefs.edit().putString(key(KEY_REMOTE_DELETED, namespace), gson.toJson(bounded)).apply() } - private suspend fun findByKey(key: String): WatchHistoryEntity? = - local.getAllHistory().firstOrNull { it.syncKey() == key } + private suspend fun findByKey(key: String, storage: WatchHistoryRepository): WatchHistoryEntity? = + storage.getAllHistory().filter { it.syncKey() == HistoryIdentity.canonicalKey(key) }.singleOrNull() - private fun readTombstones(): Map { - val raw = prefs.getString(KEY_TOMBSTONES, null) ?: return emptyMap() + private fun readDeleted(namespace: String?): Map { + val raw = prefs.getString(key(KEY_REMOTE_DELETED, namespace), null) ?: return emptyMap() + val type = object : TypeToken>() {}.type + return runCatching { gson.fromJson>(raw, type) }.getOrNull().orEmpty() + } + + private fun readTombstones(namespace: String?): Map { + val raw = prefs.getString(key(KEY_TOMBSTONES, namespace), null) ?: return emptyMap() return runCatching { gson.fromJson>(raw, tombstoneType) } .getOrNull() ?: emptyMap() } - private fun writeTombstone(key: String) = writeTombstones(readTombstones() + (key to nowIso())) - - private fun writeTombstones(all: Map) { - prefs.edit().putString(KEY_TOMBSTONES, gson.toJson(all)).apply() + private fun writeTombstones(all: Map, namespace: String?) { + prefs.edit().putString(key(KEY_TOMBSTONES, namespace), gson.toJson(all)).apply() } private fun WatchHistoryEntity.toSyncItem() = HistorySyncItem( - provider = syncProvider(), - contentId = categoryid, - contentUrl = videoUrl, + provider = syncContent().provider, + contentId = syncContent().content, + contentUrl = if (syncContent().migrated) syncContent().content else videoUrl, title = mediaName.ifBlank { title }, thumbnail = image, isSerial = isSeries, @@ -232,15 +289,15 @@ class WatchHistorySyncRepository( return (part - 1) * ExtensionParser.EPISODE_PAGE_SIZE + epIndex + 1 } - private fun WatchHistoryEntity.syncKey(): String? { - val provider = syncProvider() - val base = (categoryid?.takeIf { it.isNotBlank() } ?: videoUrl).trim() - if (base.isEmpty()) return null - val head = "$provider|$base" - if (!isSeries) return head - val episode = absoluteEpisode() ?: return head - return "$head|e$episode" - } + private fun WatchHistoryEntity.syncContent() = HistoryIdentity.content(syncProvider(), + categoryid?.takeIf { it.isNotBlank() } ?: videoUrl) + + private fun WatchHistoryEntity.syncKey(): String? = HistoryIdentity.key(syncProvider(), + categoryid?.takeIf { it.isNotBlank() } ?: videoUrl, isSeries, absoluteEpisode()) + + private fun WatchHistoryEntity.syncKeys(): Set = setOfNotNull(syncKey(), + HistoryIdentity.legacyKey(syncProvider(), categoryid?.takeIf { it.isNotBlank() } ?: videoUrl, + isSeries, absoluteEpisode())) private companion object { const val FILE = "sozo_history_sync" @@ -248,6 +305,9 @@ class WatchHistorySyncRepository( const val KEY_PUSHED_AT = "pushed_at" const val KEY_TOMBSTONES = "tombstones" const val EXTRA_SESSION = "session" + const val KEY_IDENTITY_VERSION = "identity_version" + const val KEY_REMOTE_DELETED = "remote_deleted" + const val IDENTITY_VERSION = 1 private fun formatter() = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US) .apply { timeZone = TimeZone.getTimeZone("UTC") } diff --git a/app/src/main/java/com/saikou/sozo_tv/di/koinModule.kt b/app/src/main/java/com/saikou/sozo_tv/di/koinModule.kt index 9e216311..108e75c6 100644 --- a/app/src/main/java/com/saikou/sozo_tv/di/koinModule.kt +++ b/app/src/main/java/com/saikou/sozo_tv/di/koinModule.kt @@ -1,11 +1,10 @@ package com.saikou.sozo_tv.di -import androidx.room.Room import com.google.firebase.database.FirebaseDatabase import com.saikou.sozo_tv.data.repository.AnilistRepository import com.saikou.sozo_tv.presentation.viewmodel.AnilistViewModel -import com.saikou.sozo_tv.data.local.database.AppDatabase -import com.saikou.sozo_tv.data.local.database.MIGRATION_1_2 +import com.saikou.sozo_tv.data.local.database.ProfileDatabaseProvider +import com.saikou.sozo_tv.data.local.pref.ActiveProfileStore import com.saikou.sozo_tv.data.local.pref.PreferenceManager import com.saikou.sozo_tv.data.repository.CategoriesRepositoryImpl import com.saikou.sozo_tv.data.repository.CharacterBookmarkRepositoryImpl @@ -52,16 +51,12 @@ import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val koinModule = module { - single { - Room.databaseBuilder( - androidApplication(), AppDatabase::class.java, "movie_database" - ).addMigrations(MIGRATION_1_2).build() - } - single { get().movieDao() } - single { get().tvDao() } - single { get().watchHistoryDao() } - single { get().characterDao() } - single { PreferenceManager() } + single { ProfileDatabaseProvider(androidApplication(), get()) } + factory { get().movieDao() } + factory { get().channelDao() } + factory { get().historyDao() } + factory { get().characterDao() } + single { PreferenceManager(profileStore = get()) } single { HomeRepositoryImpl(engine = get()) } @@ -75,15 +70,15 @@ val koinModule = module { ImdbHomeRepositoryImpl(engine = get()) } single { - MovieBookmarkRepositoryImpl(dao = get()) + MovieBookmarkRepositoryImpl(databases = get()) } single { - WatchHistoryRepositoryImpl(watchHistoryDao = get()) + WatchHistoryRepositoryImpl(databases = get()) } single { - CharacterBookmarkRepositoryImpl(dao = get()) + CharacterBookmarkRepositoryImpl(databases = get()) } single { SearchRepositoryImpl(engine = get()) @@ -102,7 +97,7 @@ val koinModule = module { viewModel { UpdateViewModel() } viewModel { AnilistViewModel(repository = get()) } viewModel { ViewAllViewModel(get()) } - viewModel { SettingsViewModel(get(), profileRepo = get(), deviceAuth = get(), userLists = get(), historySync = get(), anilist = get(), mal = get(), history = get(), bookmarks = get()) } + viewModel { SettingsViewModel(get(), profileRepo = get(), deviceAuth = get(), userLists = get(), historySync = get(), anilist = get(), mal = get(), history = get(), bookmarks = get(), householdProfiles = get()) } viewModel { LiveTvViewModel(dao = get()) } viewModel { SplashViewModel(appVersionClient = get()) } viewModel { PlayAnimeViewModel(watchHistoryRepository = get(), historySync = get()) } @@ -126,4 +121,4 @@ val firebaseModule = module { FirebaseDatabase.getInstance("https://sozo-app-a36e6-default-rtdb.asia-southeast1.firebasedatabase.app/") } single { FirebaseService(get()) } -} \ No newline at end of file +} diff --git a/app/src/main/java/com/saikou/sozo_tv/di/networkModule.kt b/app/src/main/java/com/saikou/sozo_tv/di/networkModule.kt index c74b030c..a5ebdff2 100644 --- a/app/src/main/java/com/saikou/sozo_tv/di/networkModule.kt +++ b/app/src/main/java/com/saikou/sozo_tv/di/networkModule.kt @@ -4,6 +4,7 @@ import com.google.gson.Gson import com.google.gson.GsonBuilder import com.saikou.sozo_tv.BuildConfig import com.saikou.sozo_tv.data.local.pref.DeviceSessionStore +import com.saikou.sozo_tv.data.local.pref.ActiveProfileStore import com.saikou.sozo_tv.data.extensions.ExtensionEngine import com.saikou.sozo_tv.data.remote.anilist.AnilistGraphQlClient import com.saikou.sozo_tv.data.remote.anilist.AnilistLinkClient @@ -29,6 +30,8 @@ import com.saikou.sozo_tv.data.remote.remote.RemoteControlClient import com.saikou.sozo_tv.data.repository.RemoteControlManager import com.saikou.sozo_tv.data.repository.UserListsRepository import com.saikou.sozo_tv.data.repository.WatchHistorySyncRepository +import com.saikou.sozo_tv.data.remote.profiles.ProfilesClient +import com.saikou.sozo_tv.data.repository.HouseholdProfileRepository import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor @@ -43,6 +46,7 @@ val NetworkModule = module { single { ExtensionEngine.shared } single { GsonBuilder().create() } + single { ActiveProfileStore(androidContext(), get()) } // Device sign-in. Deliberately on its OWN client — see createAuthOkHttpClient(). single { DeviceSessionStore(androidContext()) } @@ -58,6 +62,16 @@ val NetworkModule = module { }, ) } + // Account APIs see the household member selected on this TV. Device-auth + // endpoints intentionally keep using authOkHttp without this header. + single(named("profileOkHttp")) { + createAuthOkHttpClient( + authenticator = DeviceTokenAuthenticator( + apiHost = BuildConfig.SOZO_API_BASE_URL.toHttpUrlOrNull()?.host, + ) { get().refreshNow() }, + profileIdProvider = { get().profileId() }, + ) + } // Third-party APIs that carry their own tokens (AniList, MyAnimeList). Same platform TLS as // the auth client, but no Sozo authenticator: their 401s are not ours to answer. single(named("trackerOkHttp")) { createAuthOkHttpClient() } @@ -69,6 +83,19 @@ val NetworkModule = module { ) } single { DeviceAuthRepository(client = get(), store = get()) } + single { + ProfilesClient( + client = get(named("profileOkHttp")), + gson = get(), + baseUrl = BuildConfig.SOZO_API_BASE_URL, + tokenProvider = { get().accessToken() }, + ) + } + single { + HouseholdProfileRepository( + context = androidContext(), client = get(), activeStore = get(), gson = get(), databases = get(), + ) + } // Curated lists (Watch Later / Watched) — the first authenticated API the TV // calls. Shares the auth client (platform TLS, no body logging) because it @@ -76,19 +103,19 @@ val NetworkModule = module { // DeviceAuthRepository so refreshes are picked up mid-session. single { UserListsClient( - okHttpClient = get(named("authOkHttp")), + okHttpClient = get(named("profileOkHttp")), gson = get(), baseUrl = BuildConfig.SOZO_API_BASE_URL, tokenProvider = { get().accessToken() }, ) } - single { UserListsRepository(context = androidContext(), client = get()) } + single { UserListsRepository(context = androidContext(), client = get(), profileStore = get()) } // The phone's remote. Same auth client and per-request token as the other // authenticated APIs, so a mid-session refresh is picked up on reconnect. single { RemoteControlClient( - okHttpClient = get(named("authOkHttp")), + okHttpClient = get(named("profileOkHttp")), gson = get(), baseUrl = BuildConfig.SOZO_API_BASE_URL, tokenProvider = { get().accessToken() }, @@ -98,7 +125,7 @@ val NetworkModule = module { single { WatchHistorySyncClient( - okHttpClient = get(named("authOkHttp")), + okHttpClient = get(named("profileOkHttp")), gson = get(), baseUrl = BuildConfig.SOZO_API_BASE_URL, tokenProvider = { get().accessToken() }, @@ -109,12 +136,13 @@ val NetworkModule = module { context = androidContext(), client = get(), local = get(), + profileStore = get(), ) } single { AnilistLinkClient( - okHttpClient = get(named("authOkHttp")), + okHttpClient = get(named("profileOkHttp")), gson = get(), baseUrl = BuildConfig.SOZO_API_BASE_URL, tokenProvider = { get().accessToken() }, @@ -135,7 +163,7 @@ val NetworkModule = module { // twice, which is also matched wrong twice. single { MalLinkClient( - okHttpClient = get(named("authOkHttp")), + okHttpClient = get(named("profileOkHttp")), gson = get(), baseUrl = BuildConfig.SOZO_API_BASE_URL, tokenProvider = { get().accessToken() }, @@ -171,7 +199,7 @@ val NetworkModule = module { } single { SubtitleTranslationClient( - okHttpClient = get(named("authOkHttp")), + okHttpClient = get(named("profileOkHttp")), gson = get(), baseUrl = BuildConfig.SOZO_API_BASE_URL, tokenProvider = { get().accessToken() }, @@ -188,7 +216,10 @@ val NetworkModule = module { * Read timeout sits above the server's own 15s request timeout so a 504 arrives as a real * response (retryable) rather than as a client-side abort. */ -fun createAuthOkHttpClient(authenticator: Authenticator? = null): OkHttpClient { +fun createAuthOkHttpClient( + authenticator: Authenticator? = null, + profileIdProvider: (() -> String?)? = null, +): OkHttpClient { val loggingInterceptor = HttpLoggingInterceptor().apply { level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BASIC else HttpLoggingInterceptor.Level.NONE @@ -200,8 +231,12 @@ fun createAuthOkHttpClient(authenticator: Authenticator? = null): OkHttpClient { .writeTimeout(20, TimeUnit.SECONDS) .callTimeout(25, TimeUnit.SECONDS) .addInterceptor(loggingInterceptor) + .apply { + if (profileIdProvider != null) addInterceptor( + com.saikou.sozo_tv.data.remote.profiles.ProfileHeaderInterceptor(profileIdProvider) + ) + } .retryOnConnectionFailure(true) .apply { if (authenticator != null) authenticator(authenticator) } .build() } - diff --git a/app/src/main/java/com/saikou/sozo_tv/domain/model/HouseholdProfile.kt b/app/src/main/java/com/saikou/sozo_tv/domain/model/HouseholdProfile.kt new file mode 100644 index 00000000..efc2d9ec --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/domain/model/HouseholdProfile.kt @@ -0,0 +1,13 @@ +package com.saikou.sozo_tv.domain.model + +data class HouseholdProfile( + val id: String, + val name: String, + val avatar: String? = null, + val color: String? = null, + val isKids: Boolean = false, + val isDefault: Boolean = false, +) { + /** The original database stays the default profile's home. */ + val localNamespace: String? get() = if (isDefault) null else id +} diff --git a/app/src/main/java/com/saikou/sozo_tv/domain/player/ExternalPlaybackRules.kt b/app/src/main/java/com/saikou/sozo_tv/domain/player/ExternalPlaybackRules.kt new file mode 100644 index 00000000..d2a72725 --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/domain/player/ExternalPlaybackRules.kt @@ -0,0 +1,17 @@ +package com.saikou.sozo_tv.domain.player + +import java.net.URI + +object ExternalPlaybackRules { + fun isPlayerPackage(packageName: String): Boolean = + packageName.isNotBlank() && packageName != "com.android.tv.frameworkpackagestubs" + + fun canOpen(url: String, drm: String?, requiresProxy: Boolean): Boolean { + if (!drm.isNullOrBlank() || requiresProxy) return false + val uri = runCatching { URI(url) }.getOrNull() ?: return false + return uri.scheme in setOf("http", "https") && !uri.host.isNullOrBlank() && + uri.host.lowercase() !in setOf("127.0.0.1", "localhost", "::1", "[::1]") + } + /** Alternating header names and values is the external player's headers intent convention. */ + fun headerArray(headers: Map): Array = headers.flatMap { listOf(it.key, it.value) }.toTypedArray() +} diff --git a/app/src/main/java/com/saikou/sozo_tv/domain/player/HistoryIdentity.kt b/app/src/main/java/com/saikou/sozo_tv/domain/player/HistoryIdentity.kt new file mode 100644 index 00000000..76c960cb --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/domain/player/HistoryIdentity.kt @@ -0,0 +1,36 @@ +package com.saikou.sozo_tv.domain.player + +/** Only explicit server-provider envelopes are portable; plugin identities stay opaque. */ +object HistoryIdentity { + data class Content(val provider: String, val content: String, val migrated: Boolean) + fun content(provider: String, content: String): Content { + val p = provider.trim() + val c = content.trim() + val prefix = "$p\u0001" + if (p.startsWith("sv:") && p.length > 3 && c.startsWith(prefix)) { + val raw = c.removePrefix(prefix) + if (raw.isNotBlank() && '\u0001' !in raw) return Content(p.removePrefix("sv:"), raw, true) + } + return Content(p, c, false) + } + + fun canonicalKey(key: String): String { + val split = key.indexOf('|') + if (split < 0) return key + val value = content(key.substring(0, split), key.substring(split + 1)) + return if (value.migrated) "${value.provider}|${value.content}" else key + } + + fun key(provider: String, content: String, isSeries: Boolean, episode: Int?): String? { + val value = content(provider, content) + if (value.content.isBlank()) return null + val base = "${value.provider}|${value.content}" + return if (isSeries && episode != null) "$base|e$episode" else base + } + + fun legacyKey(provider: String, content: String, isSeries: Boolean, episode: Int?): String? { + if (content.isBlank()) return null + val base = "${provider.trim()}|${content.trim()}" + return if (isSeries && episode != null) "$base|e$episode" else base + } +} diff --git a/app/src/main/java/com/saikou/sozo_tv/domain/player/SourceSelection.kt b/app/src/main/java/com/saikou/sozo_tv/domain/player/SourceSelection.kt new file mode 100644 index 00000000..7e919d89 --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/domain/player/SourceSelection.kt @@ -0,0 +1,44 @@ +package com.saikou.sozo_tv.domain.player + +import com.saikou.sozo_tv.parser.models.VideoOption + +/** Stable preferences and a finite fallback ladder, independent of provider ordering. */ +object SourceSelection { + fun label(option: VideoOption) = "${option.fansub}|${option.resolution}|${option.quality}" + fun initial(options: List, preferred: String?, legacyIndex: Int, maxHeight: Int? = null): Int { + if (maxHeight == -1) return options.indices.filter { VideoOptionGroups.resolutionOf(options[it]) != null } + .minByOrNull { VideoOptionGroups.resolutionOf(options[it])!! } ?: legacyIndex.coerceIn(0, (options.size - 1).coerceAtLeast(0)) + val candidates = options.indices.filter { i -> + maxHeight == null || (VideoOptionGroups.resolutionOf(options[i]) ?: 0) <= maxHeight + }.ifEmpty { options.indices.toList() } + candidates.firstOrNull { label(options[it]) == preferred }?.let { return it } + // The same server at whatever resolutions this episode has: a server can be an audio + // language (Sub / Dub), and the next episode must not fall back to the other one. + val server = preferred?.substringBefore('|') + if (!server.isNullOrBlank()) { + val same = candidates.filter { options[it].fansub == server } + if (same.isNotEmpty() && same.size < candidates.size) { + val resolution = preferred.split('|').getOrNull(1) + same.firstOrNull { options[it].resolution == resolution }?.let { return it } + return same.maxByOrNull { VideoOptionGroups.resolutionOf(options[it]) ?: 0 } ?: same.first() + } + } + val resolution = preferred?.split('|')?.getOrNull(1) + if (!resolution.isNullOrBlank()) candidates.firstOrNull { options[it].resolution == resolution }?.let { return it } + if (maxHeight != null) return candidates.maxByOrNull { VideoOptionGroups.resolutionOf(options[it]) ?: 0 } ?: 0 + return legacyIndex.coerceIn(0, (options.size - 1).coerceAtLeast(0)) + } + fun next(options: List, current: Int, failedUrls: Set, codecFailure: Boolean): Int? { + val currentHeight = options.getOrNull(current)?.let { VideoOptionGroups.resolutionOf(it) } + return options.indices.filter { it != current && options[it].videoUrl !in failedUrls } + .sortedWith(compareBy { + val option = options[it] + // Prefer compatible codecs after a decoder failure, using only explicit hints. + if (codecFailure && Regex("hevc|h\\.?265|av1", RegexOption.IGNORE_CASE) + .containsMatchIn(option.fullText + " " + option.quality)) 1 else 0 + }.thenBy { if (VideoOptionGroups.resolutionOf(options[it]) == currentHeight) 0 else 1 } + .thenBy { if (options[it].useWebViewSniff) 1 else 0 } + .thenBy { kotlin.math.abs(it - current) }) + .firstOrNull() + } +} diff --git a/app/src/main/java/com/saikou/sozo_tv/domain/player/SubtitleCipher.kt b/app/src/main/java/com/saikou/sozo_tv/domain/player/SubtitleCipher.kt new file mode 100644 index 00000000..eeb4e93a --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/domain/player/SubtitleCipher.kt @@ -0,0 +1,80 @@ +package com.saikou.sozo_tv.domain.player + +import okio.ByteString.Companion.decodeBase64 +import org.json.JSONObject +import java.io.IOException +import java.nio.ByteBuffer +import java.nio.charset.CodingErrorAction +import javax.crypto.Cipher +import javax.crypto.spec.IvParameterSpec +import javax.crypto.spec.SecretKeySpec + +/** + * Some sources (KissKH's `.txt1` files) ship an ordinary SRT whose cue text lines are + * each AES-encrypted; the backend tags such a subtitle with the key to open them. + */ +data class SubtitleCipher( + val alg: String, + val key: String, + val iv: String, + val scope: String = SCOPE, + val encoding: String = ENCODING, +) { + + /** Decrypts every cue text line; indices, timing lines and blanks pass through. */ + fun decrypt(body: String): String { + if (!alg.equals(ALG, true) || !scope.equals(SCOPE, true) || !encoding.equals(ENCODING, true)) { + throw IOException("unsupported subtitle cipher $alg/$scope/$encoding") + } + val keyBytes = key.toByteArray(Charsets.UTF_8) + val ivBytes = iv.toByteArray(Charsets.UTF_8) + if (keyBytes.size != 16 || ivBytes.size != 16) throw IOException("bad subtitle cipher key") + val aes = Cipher.getInstance("AES/CBC/PKCS5Padding") + val secret = SecretKeySpec(keyBytes, "AES") + + var encrypted = 0 + var opened = 0 + val out = body.split('\n').map { line -> + val text = line.trim() + if (!isCueText(text)) return@map line + encrypted++ + val plain = runCatching { + aes.init(Cipher.DECRYPT_MODE, secret, IvParameterSpec(ivBytes)) + val bytes = text.decodeBase64() ?: return@runCatching null + strictUtf8(aes.doFinal(bytes.toByteArray())) + }.getOrNull() ?: return@map line + opened++ + if (line.endsWith('\r')) "$plain\r" else plain + } + // A wrong key still yields valid padding now and then, so a few opened lines prove nothing. + if (encrypted > 0 && opened * 2 < encrypted) throw IOException("subtitle cipher opened $opened of $encrypted cues") + return out.joinToString("\n") + } + + private fun strictUtf8(bytes: ByteArray): String = + Charsets.UTF_8.newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)).toString() + + private fun isCueText(line: String): Boolean = + line.isNotEmpty() && !line.contains("-->") && !line.all { it.isDigit() } && line != "WEBVTT" + + companion object { + private const val ALG = "aes-128-cbc" + private const val SCOPE = "cue-text" + private const val ENCODING = "base64" + + fun from(o: JSONObject?): SubtitleCipher? { + o ?: return null + val alg = o.optString("alg").ifEmpty { return null } + val key = o.optString("key").ifEmpty { return null } + val iv = o.optString("iv").ifEmpty { return null } + return SubtitleCipher( + alg, key, iv, + o.optString("scope").ifEmpty { SCOPE }, + o.optString("encoding").ifEmpty { ENCODING }, + ) + } + } +} diff --git a/app/src/main/java/com/saikou/sozo_tv/domain/repository/WatchHistoryRepository.kt b/app/src/main/java/com/saikou/sozo_tv/domain/repository/WatchHistoryRepository.kt index e5e3f7ff..bd82d953 100644 --- a/app/src/main/java/com/saikou/sozo_tv/domain/repository/WatchHistoryRepository.kt +++ b/app/src/main/java/com/saikou/sozo_tv/domain/repository/WatchHistoryRepository.kt @@ -4,6 +4,9 @@ import com.saikou.sozo_tv.data.local.entity.WatchHistoryEntity interface WatchHistoryRepository { + /** Pin storage before suspending so profile switches cannot redirect in-flight writes. */ + fun snapshot(namespace: String?): WatchHistoryRepository = this + suspend fun addHistory(history: WatchHistoryEntity) suspend fun removeHistory(videoUrl: String) diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/aniyomi/AniyomiHost.kt b/app/src/main/java/com/saikou/sozo_tv/engine/aniyomi/AniyomiHost.kt index 9ff7e5f6..f12bf5af 100644 --- a/app/src/main/java/com/saikou/sozo_tv/engine/aniyomi/AniyomiHost.kt +++ b/app/src/main/java/com/saikou/sozo_tv/engine/aniyomi/AniyomiHost.kt @@ -10,7 +10,7 @@ import eu.kanade.tachiyomi.animesource.model.AnimeFilterList import eu.kanade.tachiyomi.animesource.model.SAnime import eu.kanade.tachiyomi.animesource.model.SAnimeImpl import eu.kanade.tachiyomi.animesource.model.SEpisodeImpl -import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.CancellationException import org.json.JSONArray import org.json.JSONObject import java.io.File @@ -117,6 +117,7 @@ class AniyomiHost(private val context: Context) { conn.inputStream.use { input -> FileOutputStream(file).use { input.copyTo(it) } } file } catch (t: Throwable) { + if (t is CancellationException) throw t; Log.e(TAG, "apk download failed: ${t.message}"); null } } @@ -141,13 +142,13 @@ class AniyomiHost(private val context: Context) { private fun newAnime(url: String) = SAnimeImpl().apply { this.url = url; title = "" } - fun getMainPageJson(id: String, page: Int): String { + suspend fun getMainPageJson(id: String, page: Int): String { val src = sourceFor(id) val sections = JSONArray() val banner = JSONArray() if (src != null) { try { - val pop = runBlocking { src.getPopularAnime(page) } + val pop = run { src.getPopularAnime(page) } pop.animes.firstOrNull()?.let { val t = runCatching { it.title }.getOrDefault("") Log.i(TAG, "popular[0] title='$t' url='${it.url}'") @@ -163,10 +164,11 @@ class AniyomiHost(private val context: Context) { put("items", items) }) } - } catch (t: Throwable) { Log.e(TAG, "getPopular $id: ${t.message}") } + } catch (t: Throwable) { + if (t is CancellationException) throw t; Log.e(TAG, "getPopular $id: ${t.message}") } try { if (src.supportsLatest) { - val lat = runBlocking { src.getLatestUpdates(page) } + val lat = run { src.getLatestUpdates(page) } val items = JSONArray() for (a in lat.animes.take(30)) items.put(cardJson(a, id)) if (items.length() > 0) sections.put(JSONObject().apply { @@ -175,41 +177,41 @@ class AniyomiHost(private val context: Context) { put("items", items) }) } - } catch (t: Throwable) { Log.e(TAG, "getLatest $id: ${t.message}") } + } catch (t: Throwable) { + if (t is CancellationException) throw t; Log.e(TAG, "getLatest $id: ${t.message}") } } return JSONObject().apply { put("provider", "an:$id"); put("banner", banner); put("sections", sections) }.toString() } - fun getSectionJson(id: String, data: String, page: Int): String { + suspend fun getSectionJson(id: String, data: String, page: Int): String { val src = sourceFor(id) val items = JSONArray() var hasNext = false if (src != null) try { - val pg = runBlocking { + val pg = run { if (data == "latest" && src.supportsLatest) src.getLatestUpdates(page) else src.getPopularAnime(page) } for (a in pg.animes) items.put(cardJson(a, id)) hasNext = pg.hasNextPage - } catch (t: Throwable) { Log.e(TAG, "getSection $id: ${t.message}") } + } catch (t: Throwable) { + if (t is CancellationException) throw t; Log.e(TAG, "getSection $id: ${t.message}") } return JSONObject().apply { put("provider", "an:$id"); put("items", items); put("page", page) put("totalPages", if (hasNext) page + 1 else page) }.toString() } - fun searchJson(id: String, query: String): String { - val src = sourceFor(id) + suspend fun searchJson(id: String, query: String): String { + val src = sourceFor(id) ?: error("Aniyomi source '$id' is unavailable") + val page = src.getSearchAnime(1, query, AnimeFilterList()) val items = JSONArray() - if (src != null) try { - val pg = runBlocking { src.getSearchAnime(1, query, AnimeFilterList()) } - for (a in pg.animes) items.put(cardJson(a, id)) - } catch (t: Throwable) { Log.e(TAG, "search $id: ${t.message}") } + for (anime in page.animes) items.put(cardJson(anime, id)) return JSONObject().apply { put("provider", "an:$id"); put("items", items) - put("query", query); put("page", 1); put("totalPages", 1) + put("query", query); put("page", 1); put("totalPages", if (page.hasNextPage) 2 else 1) }.toString() } @@ -225,13 +227,15 @@ class AniyomiHost(private val context: Context) { else -> null } - fun loadJson(id: String, url: String): String { + suspend fun loadJson(id: String, url: String): String { val src = sourceFor(id) ?: return "{}" val anime = newAnime(url) - val details = try { runBlocking { src.getAnimeDetails(anime) } } - catch (t: Throwable) { Log.e(TAG, "details $id: ${t.message}"); anime } - val eps = try { runBlocking { src.getEpisodeList(anime) } } - catch (t: Throwable) { Log.e(TAG, "episodes $id: ${t.message}"); emptyList() } + val details = try { run { src.getAnimeDetails(anime) } } + catch (t: Throwable) { + if (t is CancellationException) throw t; Log.e(TAG, "details $id: ${t.message}"); anime } + val eps = try { run { src.getEpisodeList(anime) } } + catch (t: Throwable) { + if (t is CancellationException) throw t; Log.e(TAG, "episodes $id: ${t.message}"); emptyList() } // A single-episode entry is a movie; multiple episodes is a series. val isMovie = eps.size <= 1 val episodes = JSONArray() @@ -260,14 +264,15 @@ class AniyomiHost(private val context: Context) { try { val q = title.replace(Regex("\\(.*?\\)"), "").trim() if (q.length >= 2) { - val results = runBlocking { src.getSearchAnime(1, q, AnimeFilterList()) } + val results = run { src.getSearchAnime(1, q, AnimeFilterList()) } for (a in results.animes) { if (a.url == url) continue related.put(cardJson(a, id)) if (related.length() >= 20) break } } - } catch (t: Throwable) { Log.e(TAG, "related $id: ${t.message}") } + } catch (t: Throwable) { + if (t is CancellationException) throw t; Log.e(TAG, "related $id: ${t.message}") } return JSONObject().apply { put("provider", "an:$id") put("contentId", url); put("contentUrl", url) @@ -286,9 +291,9 @@ class AniyomiHost(private val context: Context) { }.toString() } - fun loadLinksJson(id: String, data: String): String { - val meta = meta(id) - val src = sourceFor(id) + suspend fun loadLinksJson(id: String, data: String): String { + val meta = meta(id) ?: error("Aniyomi source '$id' is unavailable") + val src = sourceFor(id) ?: error("Aniyomi source '$id' could not load") val videoSources = JSONArray() val subs = JSONArray() val seen = HashSet() @@ -299,14 +304,14 @@ class AniyomiHost(private val context: Context) { // User-Agent / Referer the CDN gates on). Many extensions don't repeat these on // each Video, so without this fallback the player's own client gets a 403. val baseHeaders = (src as? AnimeHttpSource)?.headers - val videos = try { runBlocking { src.getVideoList(episode) } } - catch (t: Throwable) { Log.e(TAG, "videos $id: ${t.message}"); emptyList() } + val videos = src.getVideoList(episode) for (v in videos) { var vu = v.videoUrl if (vu.isNullOrEmpty()) { vu = try { - runBlocking { (src as? AnimeHttpSource)?.getVideoUrl(v) } + run { (src as? AnimeHttpSource)?.getVideoUrl(v) } } catch (t: Throwable) { + if (t is CancellationException) throw t; Log.e(TAG, "getVideoUrl $id: ${t.message}"); null } } @@ -315,19 +320,30 @@ class AniyomiHost(private val context: Context) { val headers = JSONObject() baseHeaders?.forEach { (k, value) -> headers.put(k, value) } v.headers?.forEach { (k, value) -> headers.put(k, value) } - val isHls = vu.contains(".m3u8") + val path = vu.substringBefore('?').lowercase() + val type = when { + path.endsWith(".m3u8") || v.quality.contains("hls", true) -> "hls" + path.endsWith(".mpd") -> "dash" + else -> "http" + } videoSources.put(JSONObject().apply { put("quality", v.quality.ifEmpty { "Source" }) put("videoUrl", vu) - put("type", if (isHls) "hls" else "http") + put("type", type) put("host", meta.name) put("isDefault", videoSources.length() == 0) put("accessible", true) put("headers", headers) + if (v.audioTracks.isNotEmpty()) put("audioTracks", JSONArray().apply { + v.audioTracks.filter { it.url.startsWith("http", true) }.forEach { track -> + put(JSONObject().put("url", track.url).put("headers", headers)) + } + }) }) for (t in v.subtitleTracks) { if (t.url.isNotEmpty() && seenSub.add(t.url)) subs.put(JSONObject().apply { put("label", t.lang); put("file", t.url); put("default", false) + put("headers", headers) }) } } diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/cloudstream/CloudStreamLinkQuality.kt b/app/src/main/java/com/saikou/sozo_tv/engine/cloudstream/CloudStreamLinkQuality.kt new file mode 100644 index 00000000..81916585 --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/engine/cloudstream/CloudStreamLinkQuality.kt @@ -0,0 +1,11 @@ +package com.saikou.sozo_tv.engine.cloudstream + +/** CloudStream's Unknown sentinel is 400, not a pixel height. */ +internal object CloudStreamLinkQuality { + fun isKnown(height: Int): Boolean = height in 144..4320 && height != 400 + fun rank(height: Int, type: String): Int = when { + isKnown(height) -> height + type == "hls" || type == "dash" -> 1000 + else -> 0 + } +} diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/cloudstream/CsStreamProxy.kt b/app/src/main/java/com/saikou/sozo_tv/engine/cloudstream/CsStreamProxy.kt new file mode 100644 index 00000000..538dde14 --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/engine/cloudstream/CsStreamProxy.kt @@ -0,0 +1,218 @@ +package com.saikou.sozo_tv.engine.cloudstream + +import android.util.Log +import fi.iki.elonen.NanoHTTPD +import okhttp3.Interceptor +import okhttp3.OkHttpClient +import okhttp3.Request +import java.net.URI +import java.security.SecureRandom +import java.util.concurrent.TimeUnit + +/** + * Plays a CloudStream link through the plugin's own [Interceptor]. + * + * `MainAPI.getVideoInterceptor` is how a plugin keeps a stream playable after + * it has handed the link over: NetMirror adds the hotlink cookie and Origin to + * every segment request, KissKH decrypts its `.txt` subtitles on the way in. + * CloudStream's player builds its data source on an OkHttp client with that + * interceptor added. Ours plays through ExoPlayer or mpv on the Dart side, + * which cannot run Kotlin, so without this those sources opened the playlist + * and then failed on the first segment, or showed ciphertext as captions. + * + * So a link that comes with an interceptor is served from here instead: + * `http://127.0.0.1:/p////?`. + * The path keeps the upstream structure, so relative URIs inside a playlist + * resolve back into the proxy by themselves; absolute ones are rewritten in + * HLS playlists and DASH manifests. Bodies stream through with their status, + * length and range, so seeking works. + * + * Bound to loopback only: it fetches with a plugin's cookies and must not be + * reachable from the network. + */ +object CsStreamProxy { + private const val TAG = "CsStreamProxy" + private const val MAX_ENTRIES = 256 + private const val ENTRY_TTL_MS = 6 * 60 * 60 * 1000L + + private class Entry( + val client: OkHttpClient, + val headers: Map, + val createdAt: Long, + ) + + private val entries = object : LinkedHashMap(64, 0.75f, true) { + override fun removeEldestEntry(eldest: MutableMap.MutableEntry?) = + size > MAX_ENTRIES + } + private val random = SecureRandom() + + @Volatile + private var server: Server? = null + + /** + * Registers a stream and returns the token its URLs carry. [base] is the + * client the plugin's own requests use, so cookies, DNS and timeouts match + * what produced the link. + */ + fun register(base: OkHttpClient, interceptor: Interceptor, headers: Map): String? { + val srv = ensureServer() ?: return null + val client = base.newBuilder() + .addInterceptor(interceptor) + .readTimeout(30, TimeUnit.SECONDS) + .build() + val token = ByteArray(12).also(random::nextBytes) + .joinToString("") { "%02x".format(it) } + synchronized(entries) { entries[token] = Entry(client, headers, System.currentTimeMillis()) } + Log.i(TAG, "registered stream on port ${srv.listeningPort}") + return token + } + + /** The loopback URL for [target] under [token]; null when [target] is not http(s). */ + fun urlFor(token: String, target: String, headers: Map = emptyMap()): String? { + if (headers.isNotEmpty()) { + val parent = entry(token) ?: return null + val child = ByteArray(12).also(random::nextBytes).joinToString("") { "%02x".format(it) } + synchronized(entries) { entries[child] = Entry(parent.client, parent.headers + headers, System.currentTimeMillis()) } + return urlFor(child, target) + } + val port = server?.listeningPort ?: return null + val uri = try { URI(target) } catch (_: Exception) { return null } + val scheme = uri.scheme?.lowercase() ?: return null + if (scheme != "http" && scheme != "https") return null + val authority = uri.rawAuthority ?: return null + val path = uri.rawPath?.ifEmpty { "/" } ?: "/" + val query = uri.rawQuery?.let { "?$it" } ?: "" + return "http://127.0.0.1:$port/p/$token/$scheme/$authority$path$query" + } + + private fun ensureServer(): Server? { + server?.let { if (it.isAlive) return it } + synchronized(this) { + server?.let { if (it.isAlive) return it } + return try { + Server().also { + it.start(NanoHTTPD.SOCKET_READ_TIMEOUT, true) + server = it + } + } catch (t: Throwable) { + Log.e(TAG, "could not start: ${t.message}") + null + } + } + } + + private fun entry(token: String): Entry? = synchronized(entries) { + val e = entries[token] ?: return null + if (System.currentTimeMillis() - e.createdAt > ENTRY_TTL_MS) { + entries.remove(token) + return null + } + e + } + + private class Server : NanoHTTPD("127.0.0.1", 0) { + override fun serve(session: IHTTPSession): Response { + // /p//// + val parts = session.uri.removePrefix("/").split('/', limit = 5) + if (parts.size < 4 || parts[0] != "p") return notFound() + val token = parts[1] + val e = entry(token) ?: return notFound() + val scheme = parts[2] + if (scheme != "http" && scheme != "https") return notFound() + val authority = parts[3] + val rest = if (parts.size == 5) "/" + parts[4] else "/" + val query = session.queryParameterString?.takeIf { it.isNotEmpty() }?.let { "?$it" } ?: "" + val target = "$scheme://$authority$rest$query" + + val req = Request.Builder().url(target).get() + e.headers.forEach { (k, v) -> req.header(k, v) } + session.headers["range"]?.let { req.header("Range", it) } + + return try { + val resp = e.client.newCall(req.build()).execute() + val body = resp.body + val type = resp.header("Content-Type") ?: "" + val status = statusOf(resp.code) + if (isPlaylist(target, type)) { + val text = body.string() + val out = when { + text.trimStart().startsWith("#EXTM3U") -> rewriteHls(text, resp.request.url.toString(), token) + text.contains(" rewriteDash(text, resp.request.url.toString(), token) + else -> text + } + newFixedLengthResponse(status, type.ifEmpty { "application/vnd.apple.mpegurl" }, out) + .also { it.addHeader("Access-Control-Allow-Origin", "*") } + } else { + val length = resp.header("Content-Length")?.toLongOrNull() ?: -1L + val stream = body.byteStream() + val r = if (length >= 0) { + newFixedLengthResponse(status, type.ifEmpty { "application/octet-stream" }, stream, length) + } else { + newChunkedResponse(status, type.ifEmpty { "application/octet-stream" }, stream) + } + resp.header("Content-Range")?.let { r.addHeader("Content-Range", it) } + resp.header("Accept-Ranges")?.let { r.addHeader("Accept-Ranges", it) } + r + } + } catch (t: Throwable) { + Log.w(TAG, "fetch failed: ${t.javaClass.simpleName}: ${t.message}") + newFixedLengthResponse(statusOf(502), "text/plain", "upstream failed") + } + } + + private fun notFound() = + newFixedLengthResponse(Response.Status.NOT_FOUND, "text/plain", "not found") + + /** The upstream status as it was; NanoHTTPD's enum lacks several of them. */ + private fun statusOf(code: Int): Response.IStatus = + Response.Status.lookup(code) ?: object : Response.IStatus { + override fun getDescription() = "$code" + override fun getRequestStatus() = code + } + } + + private fun isPlaylist(url: String, contentType: String): Boolean { + val t = contentType.lowercase() + if (t.contains("mpegurl") || t.contains("dash+xml")) return true + val path = url.substringBefore('?').lowercase() + return path.endsWith(".m3u8") || path.endsWith(".m3u") || path.endsWith(".mpd") + } + + /** Absolute URIs in an HLS playlist, as lines and as `URI="…"`, into the proxy. */ + internal fun rewriteHls(text: String, base: String, token: String): String { + val baseUri = try { URI(base) } catch (_: Exception) { return text } + val attr = Regex("URI=\"([^\"]+)\"") + return text.lineSequence().joinToString("\n") { raw -> + val line = raw.trim() + when { + line.isEmpty() -> raw + line.startsWith("#") -> attr.replace(raw) { m -> + val abs = absolute(baseUri, m.groupValues[1]) + "URI=\"${abs?.let { urlFor(token, it) } ?: m.groupValues[1]}\"" + } + else -> absolute(baseUri, line)?.let { urlFor(token, it) } ?: raw + } + } + } + + /** Absolute URLs in the parts of a DASH manifest that locate media. */ + internal fun rewriteDash(text: String, base: String, token: String): String { + val baseUri = try { URI(base) } catch (_: Exception) { return text } + val baseUrlTag = Regex("(]*>)([^<]+)()") + val mediaAttrs = Regex("\\b(media|initialization|sourceURL)=\"(https?://[^\"]+)\"") + val withBase = baseUrlTag.replace(text) { m -> + val abs = absolute(baseUri, m.groupValues[2].trim()) + m.groupValues[1] + (abs?.let { urlFor(token, it) } ?: m.groupValues[2]) + m.groupValues[3] + } + return mediaAttrs.replace(withBase) { m -> + "${m.groupValues[1]}=\"${urlFor(token, m.groupValues[2]) ?: m.groupValues[2]}\"" + } + } + + /** [ref] made absolute only when it names its own host; relative refs stay relative. */ + private fun absolute(base: URI, ref: String): String? { + return try { base.resolve(ref).takeIf { it.scheme == "http" || it.scheme == "https" }?.toString() } + catch (_: Exception) { null } + } +} diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/cloudstream/PluginHost.kt b/app/src/main/java/com/saikou/sozo_tv/engine/cloudstream/PluginHost.kt index d797a9b6..32b4778d 100644 --- a/app/src/main/java/com/saikou/sozo_tv/engine/cloudstream/PluginHost.kt +++ b/app/src/main/java/com/saikou/sozo_tv/engine/cloudstream/PluginHost.kt @@ -26,6 +26,10 @@ import dalvik.system.PathClassLoader import org.json.JSONArray import org.json.JSONObject import java.io.File +import kotlinx.coroutines.launch +import com.lagradost.cloudstream3.LiveStreamLoadResponse +import com.lagradost.cloudstream3.TorrentLoadResponse +import kotlin.uuid.ExperimentalUuidApi /** * CloudStream plugin host (Android-only). @@ -49,26 +53,33 @@ class PluginHost(private val appContext: Context) { companion object { private const val TAG = "CloudStreamHost" + private const val UNKNOWN_QUALITY = 400 + private const val LINK_CACHE_MS = 20 * 60 * 1000L + private const val LINK_CACHE_ENTRIES = 40 + private const val GOOD_LINK_GRACE_MS = 2500L + private const val ANY_LINK_GRACE_MS = 6000L + private const val WAIT_CAP_MS = 90_000L + private const val COLLECT_CAP_MS = 120_000L } init { // Lenient TLS for CloudStream's own client, as the CloudStream app does: plugins scrape // arbitrary hosts with broken chains, and this client never carries a Sozo token. runCatching { - app.baseClient = app.baseClient.newBuilder().ignoreAllSSLErrors().build() + app.baseClient = app.baseClient.newBuilder().dns(com.saikou.sozo_tv.engine.network.ExtensionDns.dns).ignoreAllSSLErrors().build() } } - private val loaded = HashMap() + private val loaded = java.util.concurrent.ConcurrentHashMap() // Plugins that threw during load(). Remember them: without this, every apiByName() retries // the DexClassLoader and reprints the stack trace. - private val failed = HashSet() + private val failed = java.util.concurrent.ConcurrentHashMap.newKeySet() // internalName -> why it failed, in one line the Sources screen can show. See loadCs3. - private val lastErrors = LinkedHashMap() + private val lastErrors = java.util.concurrent.ConcurrentHashMap() // internalName -> the MainAPI provider names it registered (for unload + dedup). - private val pluginProviders = HashMap>() + private val pluginProviders = java.util.concurrent.ConcurrentHashMap>() // MainAPI.name -> plugin iconUrl (from plugins.json) for nicer provider icons. - private val providerIcons = HashMap() + private val providerIcons = java.util.concurrent.ConcurrentHashMap() // Lazy-load registry: providerName -> where to load it from. Populated cheaply // on startup (no DexClassLoader) so the provider list is instant; the actual @@ -76,15 +87,16 @@ class PluginHost(private val appContext: Context) { data class Meta( val provider: String, val icon: String?, val internalName: String, val cs3Path: String, val repo: String? = null, + val lang: String? = null, val nsfw: Boolean = false, ) - private val metas = LinkedHashMap() + private val metas = java.util.Collections.synchronizedMap(LinkedHashMap()) /** Register provider metadata WITHOUT loading the plugin (startup path). */ fun registerMeta( provider: String, icon: String?, internalName: String, - cs3Path: String, repo: String? = null, + cs3Path: String, repo: String? = null, lang: String? = null, nsfw: Boolean = false, ) { - metas[provider] = Meta(provider, icon, internalName, cs3Path, repo) + metas[provider] = Meta(provider, icon, internalName, cs3Path, repo, lang, nsfw) if (!icon.isNullOrEmpty()) providerIcons[provider] = icon } @@ -93,7 +105,7 @@ class PluginHost(private val appContext: Context) { val m = metas[provider] ?: return if (loaded.containsKey(m.internalName)) return val f = File(m.cs3Path) - if (f.exists()) loadCs3(f, m.internalName, m.icon) + if (f.exists()) loadCs3(f, m.internalName, m.icon, m.repo, m.lang, m.nsfw) } private data class Manifest( @@ -140,7 +152,7 @@ class PluginHost(private val appContext: Context) { * Plugin loading is a handful of seconds once per process, so a lock costs * nothing that matters and is the only way that diff can be correct. */ - fun loadCs3(file: File, internalName: String, iconUrl: String? = null, repo: String? = null): List { + fun loadCs3(file: File, internalName: String, iconUrl: String? = null, repo: String? = null, lang: String? = null, nsfw: Boolean = false): List { // Already loaded this process → don't register twice (avoids duplicates). loaded[internalName]?.let { return pluginProviders[internalName] ?: emptyList() } if (internalName in failed) return emptyList() @@ -187,7 +199,10 @@ class PluginHost(private val appContext: Context) { APIHolder.allProviders.map { it.name } }.filter { it !in before } pluginProviders[internalName] = added - added.forEach { metas[it] = Meta(it, iconUrl, internalName, file.absolutePath, repo) } + added.forEach { name -> + val api = synchronized(APIHolder.allProviders) { APIHolder.allProviders.first { it.name == name } } + metas[name] = Meta(name, iconUrl, internalName, file.absolutePath, repo, lang?.takeIf { it.isNotBlank() } ?: api.lang, nsfw || api.supportedTypes.any { it.name.equals("NSFW", true) }) + } if (!iconUrl.isNullOrEmpty()) added.forEach { providerIcons[it] = iconUrl } Log.i(TAG, "loaded ${file.name}: providers=$added") added @@ -216,7 +231,7 @@ class PluginHost(private val appContext: Context) { * plugin's providers are taken out of the registry first so the new load registers — and * reports — them again. */ - fun reloadCs3(file: File, internalName: String, iconUrl: String? = null, repo: String? = null): List { + fun reloadCs3(file: File, internalName: String, iconUrl: String? = null, repo: String? = null, lang: String? = null, nsfw: Boolean = false): List { synchronized(loadLock) { val old = pluginProviders[internalName].orEmpty().toSet() if (old.isNotEmpty()) { @@ -226,13 +241,18 @@ class PluginHost(private val appContext: Context) { } } } + synchronized(linkCollections) { + linkCollections.keys.filter { key -> old.any { key.startsWith("$it\u0000") } }.forEach { + linkCollections.remove(it)?.job?.cancel() + } + } loaded.remove(internalName) pluginProviders.remove(internalName) failed.remove(internalName) lastErrors.remove(internalName) CsPluginManager.forget(internalName) } - return loadCs3(file, internalName, iconUrl, repo) + return loadCs3(file, internalName, iconUrl, repo, lang, nsfw) } /** Every plugin that failed to load this session: internalName -> one-line reason. */ @@ -294,10 +314,12 @@ class PluginHost(private val appContext: Context) { /** Provider list for Flutter — from lazy metadata (no plugins loaded yet). */ fun providersJson(): String { val arr = JSONArray() - for (m in metas.values) { + for (m in synchronized(metas) { metas.values.toList() }) { arr.put(JSONObject().apply { put("id", "cs:${m.provider}") put("name", m.provider) + put("lang", m.lang) + put("nsfw", m.nsfw) m.icon?.let { put("icon", it) } m.repo?.let { if (it.isNotEmpty()) put("repo", it) } }) @@ -305,6 +327,10 @@ class PluginHost(private val appContext: Context) { return arr.toString() } + fun providerMetadata(name: String): JSONObject = metas[name]?.let { + JSONObject().put("lang", it.lang).put("nsfw", it.nsfw) + } ?: JSONObject() + /** * "Genres" for the home chip row = the provider's MainPageData categories. * `slug` carries the MainPageData.data so a tap re-uses getSectionJson (the @@ -375,6 +401,8 @@ class PluginHost(private val appContext: Context) { put("items", items) }) } + } catch (c: kotlinx.coroutines.CancellationException) { + throw c } catch (t: Throwable) { // Log (don't swallow) — most empty-home failures are a plugin // referencing an app-module class our embedded `library` lacks @@ -400,7 +428,11 @@ class PluginHost(private val appContext: Context) { if (resp != null) { for (list in resp.items) for (sr in list.list) items.put(cardJson(sr, api.name)) } - } catch (_: Throwable) { } + } catch (c: kotlinx.coroutines.CancellationException) { + throw c + } catch (t: Throwable) { + throw IllegalStateException("${api.name}: could not load this section", t) + } } return JSONObject().apply { put("provider", providerName) @@ -442,12 +474,8 @@ class PluginHost(private val appContext: Context) { } suspend fun loadJson(providerName: String, url: String): String { - val api = apiByName(providerName) ?: run { - Log.e(TAG, "load: provider '$providerName' not found"); return "{}" - } - val resp = try { api.load(url) } catch (t: Throwable) { - Log.e(TAG, "load ${api.name}: ${t.javaClass.simpleName}: ${t.message}"); null - } ?: return "{}" + val api = apiByName(providerName) ?: error("CloudStream provider '$providerName' is unavailable") + val resp = api.load(url) ?: error("${api.name}: the provider returned no details") val episodes = JSONArray() var isSerial = false when (resp) { @@ -457,7 +485,7 @@ class PluginHost(private val appContext: Context) { } is AnimeLoadResponse -> { isSerial = true - val list = resp.episodes.values.firstOrNull() ?: emptyList() + val list = resp.episodes.values.maxByOrNull { it.size } ?: emptyList() list.forEachIndexed { i, e -> episodes.put(episodeJson(e, i)) } } is MovieLoadResponse -> { @@ -468,6 +496,19 @@ class PluginHost(private val appContext: Context) { put("episode", 1); put("label", "Play"); put("mediaRef", ref) }) } + is LiveStreamLoadResponse -> { + episodes.put(JSONObject().apply { + put("episode", 1); put("label", "Watch live") + put("mediaRef", resp.dataUrl.ifEmpty { resp.url }) + }) + } + is TorrentLoadResponse -> { + val ref = resp.magnet ?: resp.torrent + require(!ref.isNullOrBlank()) { "This torrent entry has no magnet or torrent link" } + episodes.put(JSONObject().apply { + put("episode", 1); put("label", "Play"); put("mediaRef", ref) + }) + } } val syncIds = JSONObject() runCatching { @@ -523,113 +564,334 @@ class PluginHost(private val appContext: Context) { }.toString() } + /** The library's shared client, the one plugins' own requests go through. */ + private fun libraryClient(): okhttp3.OkHttpClient? = try { + val requests = Class.forName("com.lagradost.cloudstream3.MainActivityKt") + .getDeclaredMethod("getApp").invoke(null) + requests?.javaClass?.methods + ?.firstOrNull { it.name == "getBaseClient" && it.parameterTypes.isEmpty() } + ?.invoke(requests) as? okhttp3.OkHttpClient + } catch (_: Throwable) { + null + } + + /** + * One episode's links, gathered as the plugin produces them. + * + * Extractors call back as they finish, and a plugin that tries a WebView + * sniff last can take a minute to return. Waiting for the whole call is + * what made CloudStream episodes sit on a spinner long after a playable + * link had arrived — CloudStream's own player starts on the first good link + * and keeps collecting. So the collection runs on its own, and the call + * that asked for it returns as soon as there is something worth playing. + */ + private class LinkCollection(val startedAt: Long) { + var job: kotlinx.coroutines.Job? = null + val sources = ArrayList>() + val subs = ArrayList() + val seenUrls = HashSet() + val seenSubs = HashSet() + var firstLinkAt = 0L + var bestRank = -1 + var interceptorToken: String? = null + @Volatile var done = false + @Volatile var error: String? = null + } + + private val linkScope = kotlinx.coroutines.CoroutineScope( + kotlinx.coroutines.SupervisorJob() + kotlinx.coroutines.Dispatchers.IO, + ) + private val linkCollections = LinkedHashMap() + // AudioFile is @Prerelease in the CloudStream library; the annotation is an // IDE hint with BINARY retention, so reading the list a plugin may have filled // costs nothing at runtime and is empty for every plugin that sets none. @OptIn(com.lagradost.cloudstream3.Prerelease::class) suspend fun loadLinksJson(providerName: String, data: String): String { + if (data.startsWith("magnet:", true) || data.substringBefore('?').endsWith(".torrent", true)) { + return JSONObject().put("videoSources", JSONArray().put(JSONObject() + .put("videoUrl", data).put("type", "torrent").put("quality", "Torrent") + .put("isDefault", true))).put("subtitles", JSONArray()).toString() + } val api = apiByName(providerName) - // (quality, source) pairs so the list can be ordered before it is emitted. - val collected = ArrayList>() - val subs = JSONArray() - val seenUrls = HashSet() - val seenSubs = HashSet() - // Extractors run in parallel and call back from their own threads, so every write to the - // collections above goes through this one lock. - val lock = Any() - if (api != null) { - try { - api.loadLinks( - data = data, - isCasting = false, - subtitleCallback = { sf: com.lagradost.cloudstream3.SubtitleFile -> synchronized(lock) { - if (sf.url.isNotEmpty() && seenSubs.add(sf.url)) { - subs.put(JSONObject().apply { - put("label", sf.lang); put("file", sf.url); put("default", false) - // A subtitle is fetched on its own, so it inherits none of - // the stream's headers. Plenty of CloudStream sources hand - // out tracks that 403 without the Referer the extractor - // set, and SubtitleFile has carried those headers since - // v4.7 — dropping them is why a provider could return - // subtitles and the player still show none. - sf.headers?.takeIf { it.isNotEmpty() }?.let { - put("headers", JSONObject(it as Map<*, *>)) - } - }) - } - } }, - callback = { link: ExtractorLink -> synchronized(lock) { - // Torrents and magnets are not streams. Passed through as an - // ordinary source they reached the player as a bare "Source - // error"; the honest thing is to not offer them. Relative urls - // ("dl.php?id=…") go for the same reason — ExoPlayer resolves - // those as a local file path. - val streamable = link.type != ExtractorLinkType.TORRENT && - link.type != ExtractorLinkType.MAGNET - if (streamable && link.url.startsWith("http", ignoreCase = true) && - seenUrls.add(link.url) - ) { - // getAllHeaders() folds in the referer exactly the way - // CloudStream's own player does, instead of us overwriting a - // Referer an extractor had deliberately set. - val headers = JSONObject(link.getAllHeaders() as Map<*, *>) - // quality is a resolution int (e.g. 1080) or a Qualities - // sentinel; build a readable, distinct " · p". - val q = link.quality - val res = if (q in 144..4320) "${q}p" else null - val nm = link.name.ifBlank { "Source" } - val label = if (res != null) "$nm · $res" else nm - collected.add((if (q in 144..4320) q else 0) to JSONObject().apply { - put("quality", label) - put("videoUrl", link.url) - // DASH used to fall into the `else` branch and be handed - // over as a plain progressive file, so every .mpd source - // failed to open. - put("type", when (link.type) { - ExtractorLinkType.M3U8 -> "hls" - ExtractorLinkType.DASH -> "dash" - else -> "http" - }) - put("host", link.name) - put("accessible", true) - put("headers", headers) - // Separate audio renditions the extractor says belong with - // this video. A dual-audio release puts its dub here rather - // than in the manifest, so discarding them left the player - // with one track and nothing to switch to. - if (link.audioTracks.isNotEmpty()) { - put("audioTracks", JSONArray().apply { - link.audioTracks.forEach { a -> - put(JSONObject().apply { - put("url", a.url) - a.headers?.takeIf { it.isNotEmpty() }?.let { - put("headers", JSONObject(it as Map<*, *>)) - } - }) - } - }) - } - }) - } - } } + ?: return JSONObject().apply { + put("videoSources", JSONArray()) + put("subtitles", JSONArray()) + put("error", "$providerName: " + + (metas[providerName.removePrefix("cs:")]?.internalName?.let { lastErrors[it] } ?: "provider not loaded: $providerName")) + }.toString() + + // Reopening an episode, a retry, the next visit within twenty minutes: + // the links are already known, as CloudStream's own player keeps them. + val key = "${api.name}\u0000$data" + val now = System.currentTimeMillis() + val collection = synchronized(linkCollections) { + linkCollections[key]?.takeIf { + now - it.startedAt < LINK_CACHE_MS && synchronized(it) { !it.done || it.sources.isNotEmpty() } + } ?: LinkCollection(now).also { + linkCollections[key] = it + while (linkCollections.size > LINK_CACHE_ENTRIES) { + linkCollections.remove(linkCollections.keys.first())?.job?.cancel() + } + startCollecting(api, data, it) + } + } + + // Wait for the first good link rather than for the last extractor: + // once a high or adaptive link is in, a short grace lets a better one + // that is about to land win; a lesser one gets a little longer; and the + // whole wait is bounded, because a plugin that never returns used to + // leave the player on a spinner for good. + while (true) { + val (done, count, firstAt, best) = synchronized(collection) { + listOf( + if (collection.done) 1L else 0L, + collection.sources.size.toLong(), + collection.firstLinkAt, + collection.bestRank.toLong(), ) + } + if (done == 1L) break + val t = System.currentTimeMillis() + if (count > 0) { + val since = t - firstAt + if (best >= 1000 && since >= GOOD_LINK_GRACE_MS) break + if (since >= ANY_LINK_GRACE_MS) break + } + if (t - collection.startedAt >= WAIT_CAP_MS) break + kotlinx.coroutines.delay(150) + } + return buildLinksJson(api, collection) + } + + @OptIn(com.lagradost.cloudstream3.Prerelease::class) + private fun startCollecting(api: MainAPI, data: String, c: LinkCollection) { + c.job = linkScope.launch { + try { + kotlinx.coroutines.withTimeoutOrNull(COLLECT_CAP_MS) { + api.loadLinks( + data = data, + isCasting = false, + subtitleCallback = { sf -> + synchronized(c) { + if (sf.url.isNotEmpty() && c.seenSubs.add(sf.url)) c.subs.add(sf) + } + }, + callback = { link -> collectLink(api, link, c) }, + ) + } ?: run { c.error = "timed out after ${COLLECT_CAP_MS / 1000}s" } } catch (t: Throwable) { - Log.e(TAG, "loadLinks ${api.name}: ${t.javaClass.simpleName}: ${t.message}") + c.error = "${t.javaClass.simpleName}: ${t.message ?: "failed"}" + Log.e(TAG, "loadLinks ${api.name}", t) + } finally { + c.done = true + // With the elapsed time, because the two ways of getting zero + // look identical in a log and nothing like each other in cause: + // a fast empty answer is a title with no mirrors, and a + // sixty-second one is WebViewResolver polling out its timeout. + Log.i( + TAG, + "loadLinks ${api.name}: ${c.sources.size} source(s), " + + "${c.subs.size} sub(s) in ${System.currentTimeMillis() - c.startedAt}ms", + ) + } + } + } + + @OptIn(com.lagradost.cloudstream3.Prerelease::class) + private fun collectLink(api: MainAPI, link: ExtractorLink, c: LinkCollection) { + // Torrents and magnets are passed through tagged as "torrent": the app + // embeds a torrent server and the player turns such a link into a local + // HTTP stream (see core/torrent/ and player_page.media.dart). + // + // Relative urls ("dl.php?id=…") are still dropped — ExoPlayer resolves + // those as a local file path. So is a multi-part ExtractorLinkPlayList, + // whose url is empty: its parts are separate files the player cannot + // join, and offering only the first part would stop mid-film. + val isTorrent = link.type == ExtractorLinkType.TORRENT || + link.type == ExtractorLinkType.MAGNET + val addressable = link.url.startsWith("http", ignoreCase = true) || + (isTorrent && link.url.startsWith("magnet:", ignoreCase = true)) + if (!addressable) return + synchronized(c) { if (!c.seenUrls.add(link.url)) return } + + // getAllHeaders() folds in the referer exactly the way CloudStream's + // own player does. The User-Agent it falls back to is the library's, + // not ours: the extractor fetched the page, and often a signed URL, + // under that agent, and a CDN that binds its token to the agent 403s + // the stream when the player presents a different one. + val headers = LinkedHashMap(link.getAllHeaders()) + if (headers.keys.none { it.equals("User-Agent", ignoreCase = true) }) { + headers["User-Agent"] = com.lagradost.cloudstream3.USER_AGENT + } + + // A plugin that needs to touch every request — cookies on segments, + // decrypting subtitles — says so through getVideoInterceptor, and the + // stream then plays through [CsStreamProxy], which applies it. + var videoUrl = link.url + var proxied = false + var streamToken: String? = null + if (!isTorrent) { + val interceptor = try { api.getVideoInterceptor(link) } catch (_: Throwable) { null } + val base = if (interceptor != null) libraryClient() else null + if (interceptor != null && base != null) { + val token = CsStreamProxy.register(base, interceptor, headers) + val url = token?.let { CsStreamProxy.urlFor(it, link.url) } + if (token != null && url != null) { + videoUrl = url + streamToken = token + proxied = true + synchronized(c) { if (c.interceptorToken == null) c.interceptorToken = token } + } + } + } + + // quality is a resolution int (e.g. 1080) or a Qualities sentinel. + // Qualities.Unknown is 400, and it is what every link built without a + // quality carries — most HLS masters. Read as a resolution it labelled + // them "400p" and sorted an adaptive stream below a 480p file. + val q = link.quality + val known = CloudStreamLinkQuality.isKnown(q) + val res = when { + !known -> null + q >= 2160 -> "4K" + else -> "${q}p" + } + val nm = link.name.ifBlank { "Source" } + val label = if (res != null) "$nm · $res" else nm + val path = link.url.substringBefore('?').lowercase() + val type = when { + link.type == ExtractorLinkType.M3U8 -> "hls" + link.type == ExtractorLinkType.DASH -> "dash" + isTorrent -> "torrent" + // An old-style link built without a type still says what it is. + path.endsWith(".m3u8") -> "hls" + path.endsWith(".mpd") -> "dash" + else -> "http" + } + // An adaptive master of unknown height usually tops out at 1080p: + // ahead of a fixed 720p file, behind a stated 1080p. + val rank = CloudStreamLinkQuality.rank(q, type) + + val json = JSONObject().apply { + put("quality", label) + put("videoUrl", videoUrl) + put("type", type) + put("host", link.name) + put("accessible", true) + // The proxy sends the plugin's headers itself. + put("headers", if (proxied) JSONObject() else JSONObject(headers as Map<*, *>)) + if (proxied) put("useLocalProxy", false) + drmJson(link, headers)?.let { put("drm", it) } + // Separate audio renditions the extractor says belong with this + // video; a dual-audio release puts its dub here rather than in the + // manifest. + if (link.audioTracks.isNotEmpty()) { + put("audioTracks", JSONArray().apply { + link.audioTracks.forEach { a -> + put(JSONObject().apply { + put("url", streamToken?.let { CsStreamProxy.urlFor(it, a.url, a.headers.orEmpty()) } ?: a.url) + a.headers?.takeIf { it.isNotEmpty() }?.let { + put("headers", JSONObject(it as Map<*, *>)) + } + }) + } + }) + } + } + synchronized(c) { + c.sources.add(rank to json) + if (c.firstLinkAt == 0L) c.firstLinkAt = System.currentTimeMillis() + if (rank > c.bestRank) c.bestRank = rank + } + } + + /** + * A DrmExtractorLink in the shape the player's DrmConfig reads. + * + * The player already plays ClearKey and Widevine channels; CloudStream + * links that carried their keys were handed over as plain streams and + * decoded to a black screen. ClearKey material arrives as base64url, the + * EME form, and the player takes hex, which is how keys are published. + */ + @OptIn(ExperimentalUuidApi::class) + private fun drmJson(link: ExtractorLink, headers: Map): JSONObject? { + val drm = link as? com.lagradost.cloudstream3.utils.DrmExtractorLink ?: return null + val scheme = when (drm.uuid.toString().lowercase()) { + "e2719d58-a985-b3c9-781a-b030af78d30e", "1077efec-c0b2-4d02-ace3-3c1e52e2fb4b" -> "clearkey" + "edef8ba9-79d6-4ace-a3c8-27dcd51d21ed" -> "widevine" + "9a04f079-9840-4286-ab92-e65be0885f95" -> "playready" + else -> return null + } + return JSONObject().apply { + put("scheme", scheme) + put("licenseUrl", drm.licenseUrl ?: "") + put("licenseHeaders", JSONObject(headers as Map<*, *>)) + if (scheme == "clearkey") { + val kid = drm.kid?.let(::b64UrlToHex) + val k = drm.key?.let(::b64UrlToHex) + if (kid != null && k != null) put("clearKeys", JSONObject().apply { put(kid, k) }) } - Log.i(TAG, "loadLinks ${api.name}: ${collected.size} source(s), ${subs.length()} sub(s)") - } - // Best first. Extractors call back in whatever order they finish, so the - // default source used to be a race: a 360p mirror that resolved quickly - // won over a 1080p one that took a moment longer. CloudStream's own - // player orders by quality for the same reason. The sort is stable, so - // sources of equal quality keep the order the provider produced them in. - synchronized(lock) { collected.sortByDescending { it.first } } + } + } + + @Suppress("DEPRECATION") + private fun htmlText(s: String): String = + if (android.os.Build.VERSION.SDK_INT >= 24) { + android.text.Html.fromHtml(s, android.text.Html.FROM_HTML_MODE_LEGACY).toString() + } else { + android.text.Html.fromHtml(s).toString() + } + + private fun b64UrlToHex(value: String): String? { + val v = value.trim() + if (v.matches(Regex("^[0-9a-fA-F]{32}$"))) return v.lowercase() + return try { + android.util.Base64.decode( + v, android.util.Base64.URL_SAFE or android.util.Base64.NO_PADDING or android.util.Base64.NO_WRAP, + ).joinToString("") { "%02x".format(it) } + } catch (_: Throwable) { + null + } + } + + private fun buildLinksJson(api: MainAPI, c: LinkCollection): String { + val (sources, subsSnapshot, token, done, error) = synchronized(c) { + listOf(ArrayList(c.sources), ArrayList(c.subs), c.interceptorToken, c.done, c.error) + } + @Suppress("UNCHECKED_CAST") + val collected = sources as ArrayList> + @Suppress("UNCHECKED_CAST") + val subFiles = subsSnapshot as ArrayList + collected.sortByDescending { it.first } val videoSources = JSONArray() collected.forEachIndexed { i, entry -> - entry.second.put("isDefault", i == 0) - videoSources.put(entry.second) + val o = JSONObject(entry.second.toString()) + o.put("isDefault", i == 0) + videoSources.put(o) } - // Shape matches MediaResolveModel.fromJson (videoUrl/type/headers + videoSources + subtitles). + + val subs = JSONArray() + val nameCounts = HashMap() + for (sf in subFiles) { + val base = htmlText(sf.lang).trim().ifEmpty { "Subtitle" } + val n = (nameCounts[base] ?: 0) + 1 + nameCounts[base] = n + val subHeaders = LinkedHashMap(sf.headers ?: emptyMap()) + if (subHeaders.isNotEmpty() && subHeaders.keys.none { it.equals("User-Agent", true) }) { + subHeaders["User-Agent"] = com.lagradost.cloudstream3.USER_AGENT + } + val proxiedUrl = (token as String?)?.let { CsStreamProxy.urlFor(it, sf.url, subHeaders) } + subs.put(JSONObject().apply { + put("label", if (n == 1) base else "$base $n") + put("file", proxiedUrl ?: sf.url) + put("default", false) + if (proxiedUrl == null && subHeaders.isNotEmpty()) { + put("headers", JSONObject(subHeaders as Map<*, *>)) + } + }) + } + val first = if (videoSources.length() > 0) videoSources.getJSONObject(0) else null return JSONObject().apply { put("videoUrl", first?.optString("videoUrl")) @@ -637,6 +899,11 @@ class PluginHost(private val appContext: Context) { put("headers", first?.optJSONObject("headers") ?: JSONObject()) put("videoSources", videoSources) put("subtitles", subs) + if (done != true) put("partial", true) + if (videoSources.length() == 0) { + put("error", "${api.name}: " + + ((error as String?) ?: "the provider returned no mirrors for this episode")) + } }.toString() } } diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/cloudstream/RepoManager.kt b/app/src/main/java/com/saikou/sozo_tv/engine/cloudstream/RepoManager.kt index e50d9767..51a9a3e1 100644 --- a/app/src/main/java/com/saikou/sozo_tv/engine/cloudstream/RepoManager.kt +++ b/app/src/main/java/com/saikou/sozo_tv/engine/cloudstream/RepoManager.kt @@ -28,6 +28,7 @@ class RepoManager(private val context: Context, private val host: PluginHost) { /** One `plugins.json` entry, reduced to what installing it needs. */ internal data class PluginRef( val url: String, val internalName: String, val version: Int, val iconUrl: String?, + val lang: String = "", val nsfw: Boolean = false, ) /** A `repo.json`, reduced to a display name and the plugin lists it points at. */ @@ -94,6 +95,10 @@ class RepoManager(private val context: Context, private val host: PluginHost) { internalName = internalName, version = p.optInt("version", 0), iconUrl = p.optString("iconUrl").ifEmpty { null }, + lang = p.optString("language"), + nsfw = p.optJSONArray("tvTypes")?.let { types -> + (0 until types.length()).any { types.optString(it).equals("NSFW", true) } + } ?: false, ) ) } @@ -172,7 +177,7 @@ class RepoManager(private val context: Context, private val host: PluginHost) { e.optString("icon").ifEmpty { null }, e.optString("internalName"), e.optString("cs3Path"), - repoName, + repoName, e.optString("lang").ifBlank { null }, e.optBoolean("nsfw", false), ) } } @@ -390,10 +395,13 @@ class RepoManager(private val context: Context, private val host: PluginHost) { pluginCount++ // Load now to discover provider names (one-time on add); persist // metadata so future launches can lazy-load without this cost. - host.loadCs3(file, ref.internalName, ref.iconUrl, repoName).forEach { name -> + host.loadCs3(file, ref.internalName, ref.iconUrl, repoName, ref.lang, ref.nsfw).forEach { name -> providers.put(name) metaEntries.put(JSONObject().apply { put("provider", name) + val properties = host.providerMetadata(name) + put("lang", properties.optString("lang")) + put("nsfw", properties.optBoolean("nsfw")) if (ref.iconUrl != null) put("icon", ref.iconUrl) put("internalName", ref.internalName) put("cs3Path", file.absolutePath) @@ -452,6 +460,8 @@ class RepoManager(private val context: Context, private val host: PluginHost) { val ref = latest[internalName] ?: continue val installedVer = e.optString("cs3Path") .substringAfterLast('@', "").substringBefore(".cs3").toIntOrNull() ?: 0 + e.put("lang", ref.lang).put("nsfw", ref.nsfw) + host.registerMeta(e.optString("provider"), ref.iconUrl, internalName, e.optString("cs3Path"), repoName, ref.lang, ref.nsfw) if (ref.version <= installedVer) continue val file = if (downloaded.add(internalName)) { downloadCs3(ref.internalName, ref.version, ref.url) @@ -460,7 +470,7 @@ class RepoManager(private val context: Context, private val host: PluginHost) { } if (file != null) { e.put("cs3Path", file.absolutePath) - host.reloadCs3(file, ref.internalName, ref.iconUrl, repoName) + host.reloadCs3(file, ref.internalName, ref.iconUrl, repoName, ref.lang, ref.nsfw) updated.put(e.optString("provider")) } } @@ -470,9 +480,12 @@ class RepoManager(private val context: Context, private val host: PluginHost) { for (ref in latest.values) { if (ref.internalName in installed) continue val file = downloadCs3(ref.internalName, ref.version, ref.url) ?: continue - host.loadCs3(file, ref.internalName, ref.iconUrl, repoName).forEach { name -> + host.loadCs3(file, ref.internalName, ref.iconUrl, repoName, ref.lang, ref.nsfw).forEach { name -> entries.put(JSONObject().apply { put("provider", name) + val properties = host.providerMetadata(name) + put("lang", properties.optString("lang")) + put("nsfw", properties.optBoolean("nsfw")) if (ref.iconUrl != null) put("icon", ref.iconUrl) put("internalName", ref.internalName) put("cs3Path", file.absolutePath) diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/download/DownloadMetadata.kt b/app/src/main/java/com/saikou/sozo_tv/engine/download/DownloadMetadata.kt new file mode 100644 index 00000000..9cf2b862 --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/engine/download/DownloadMetadata.kt @@ -0,0 +1,51 @@ +package com.saikou.sozo_tv.engine.download + +import org.json.JSONObject +import java.net.URI +import java.security.MessageDigest + +internal data class DownloadMetadata( + val title: String, + val owner: String, + val url: String, + val mime: String, + val headers: Map, + val localProxy: String? = null, + val transform: String? = null, +) { + fun encode(): ByteArray = JSONObject().apply { + put("title", title); put("owner", owner); put("url", url); put("mime", mime) + put("headers", JSONObject(headers)); put("localProxy", localProxy); put("transform", transform) + }.toString().toByteArray(Charsets.UTF_8) + + companion object { + fun decode(data: ByteArray): DownloadMetadata { + val json = JSONObject(String(data, Charsets.UTF_8)) + val headers = json.optJSONObject("headers") ?: JSONObject() + return DownloadMetadata(json.getString("title"), json.getString("owner"), + json.getString("url"), json.getString("mime"), + headers.keys().asSequence().associateWith { headers.getString(it) }, + json.optString("localProxy").takeIf { it.isNotEmpty() && it != "null" }, + json.optString("transform").takeIf { it.isNotEmpty() && it != "null" }) + } + } +} + +internal object DownloadRules { + fun id(owner: String, url: String): String = MessageDigest.getInstance("SHA-256") + .digest("$owner\n$url".toByteArray(Charsets.UTF_8)) + .joinToString("") { "%02x".format(it) } + + fun rejectReason(url: String, drm: String?, separateAudio: Boolean): String? { + if (!drm.isNullOrBlank()) return "This source requires an offline DRM license. Choose an unprotected source." + if (separateAudio) return "This source has separate audio. Choose a source with audio included for offline playback." + val uri = runCatching { URI(url) }.getOrNull() + if (uri?.scheme !in setOf("http", "https") || uri?.host.isNullOrBlank()) { + return "Only direct video, HLS and DASH sources can be downloaded." + } + if (uri!!.host.lowercase() in setOf("localhost", "127.0.0.1", "::1", "[::1]")) { + return "This source uses a temporary player session. Choose another source for offline playback." + } + return null + } +} diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/download/TvDownloadService.kt b/app/src/main/java/com/saikou/sozo_tv/engine/download/TvDownloadService.kt new file mode 100644 index 00000000..17893519 --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/engine/download/TvDownloadService.kt @@ -0,0 +1,27 @@ +package com.saikou.sozo_tv.engine.download + +import android.app.Notification +import android.app.PendingIntent +import android.content.Intent +import androidx.media3.common.util.UnstableApi +import androidx.media3.exoplayer.offline.Download +import androidx.media3.exoplayer.offline.DownloadManager +import androidx.media3.exoplayer.offline.DownloadNotificationHelper +import androidx.media3.exoplayer.offline.DownloadService +import androidx.media3.exoplayer.scheduler.Scheduler +import com.saikou.sozo_tv.R +import com.saikou.sozo_tv.presentation.activities.DownloadsActivity + +@UnstableApi +class TvDownloadService : DownloadService(7301, DEFAULT_FOREGROUND_NOTIFICATION_UPDATE_INTERVAL, + "tv_downloads", R.string.tv_downloads_title, 0) { + override fun getDownloadManager(): DownloadManager = TvDownloads.manager(this) + override fun getScheduler(): Scheduler? = null + override fun getForegroundNotification(downloads: MutableList, notMetRequirements: Int): Notification { + val pendingIntent = PendingIntent.getActivity(this, 0, Intent(this, DownloadsActivity::class.java), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) + return DownloadNotificationHelper(this, "tv_downloads").buildProgressNotification( + this, android.R.drawable.stat_sys_download, pendingIntent, getString(R.string.tv_downloads_title), + downloads, notMetRequirements) + } +} diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/download/TvDownloads.kt b/app/src/main/java/com/saikou/sozo_tv/engine/download/TvDownloads.kt new file mode 100644 index 00000000..6f3cf1e6 --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/engine/download/TvDownloads.kt @@ -0,0 +1,222 @@ +package com.saikou.sozo_tv.engine.download + +import android.content.Context +import android.net.Uri +import android.util.Base64 +import androidx.media3.common.MediaItem +import androidx.media3.common.MimeTypes +import androidx.media3.common.TrackSelectionParameters +import androidx.media3.common.util.UnstableApi +import androidx.media3.database.StandaloneDatabaseProvider +import androidx.media3.datasource.DataSource +import androidx.media3.datasource.DataSpec +import androidx.media3.datasource.ResolvingDataSource +import androidx.media3.datasource.cache.CacheDataSource +import androidx.media3.datasource.cache.CacheKeyFactory +import androidx.media3.datasource.cache.NoOpCacheEvictor +import androidx.media3.datasource.cache.SimpleCache +import androidx.media3.datasource.okhttp.OkHttpDataSource +import androidx.media3.exoplayer.DefaultRenderersFactory +import androidx.media3.exoplayer.offline.* +import com.saikou.sozo_tv.data.local.pref.ActiveProfileStore +import com.saikou.sozo_tv.data.model.VodMovieResponse +import com.saikou.sozo_tv.engine.player.LocalHlsProxy +import com.saikou.sozo_tv.engine.player.StreamHttp +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout +import okhttp3.OkHttpClient +import org.json.JSONObject +import org.koin.core.context.GlobalContext +import java.io.File +import java.io.IOException +import java.util.concurrent.Executors +import kotlin.coroutines.resume +import kotlin.coroutines.resumeWithException + +/** Download state and bytes belong to Media3, so queues survive process death and can resume. */ +@UnstableApi +object TvDownloads { + private var manager: DownloadManager? = null + private var cache: SimpleCache? = null + private val executor = Executors.newFixedThreadPool(2) + + fun ownerToken(): Pair { + val snapshot = GlobalContext.get().get().snapshot() + return (snapshot.profile?.id ?: "guest") to snapshot.revision + } + fun owner(): String = ownerToken().first + + @Synchronized + private fun cache(context: Context): SimpleCache = cache ?: SimpleCache( + File(context.applicationContext.filesDir, "offline-media"), NoOpCacheEvictor(), + StandaloneDatabaseProvider(context.applicationContext), + ).also { cache = it } + + @Synchronized + fun manager(context: Context): DownloadManager = manager ?: run { + val app = context.applicationContext + val index = DefaultDownloadIndex(StandaloneDatabaseProvider(app), "tv_offline") + DownloadManager(app, index, DownloaderFactory { request -> + val metadata = DownloadMetadata.decode(request.data) + val upstream = DownloadUpstream(app, metadata) + val delegate = DefaultDownloaderFactory( + cacheFactory(app, request.id).setUpstreamDataSourceFactory(upstream.factory), executor, + ).createDownloader(request) + object : Downloader { + override fun download(listener: Downloader.ProgressListener?) { + try { delegate.download(listener) } finally { upstream.close() } + } + override fun cancel() { delegate.cancel(); upstream.close() } + override fun remove() { try { delegate.remove() } finally { upstream.close() } } + } + }).apply { + maxParallelDownloads = 2 + minRetryCount = 2 + resumeDownloads() + }.also { manager = it } + } + + fun cacheFactory(context: Context, id: String): CacheDataSource.Factory = CacheDataSource.Factory() + .setCache(cache(context)).setCacheKeyFactory(CacheKeyFactory { spec -> + "$id:${LocalHlsProxy.canonicalUpstreamUrl(spec.uri.toString()) ?: spec.uri}" + }).setFlags(CacheDataSource.FLAG_BLOCK_ON_CACHE) + + /** A completed item plays exclusively from disk, never silently switching back to the network. */ + fun offlineFactory(context: Context, id: String): DataSource.Factory = + cacheFactory(context, id).setUpstreamDataSourceFactory(null) + + suspend fun enqueue(context: Context, title: String, vod: VodMovieResponse): String = withContext(Dispatchers.Main) { + DownloadRules.rejectReason(vod.urlobj, vod.drm, vod.audioTracks.isNotEmpty())?.let { + throw IllegalArgumentException(it) + } + require(context.filesDir.usableSpace > 128L * 1024 * 1024) { "Not enough free space for a download." } + val mime = when (vod.type.lowercase()) { + "hls", "m3u8", MimeTypes.APPLICATION_M3U8 -> MimeTypes.APPLICATION_M3U8 + "dash", "mpd", MimeTypes.APPLICATION_MPD -> MimeTypes.APPLICATION_MPD + else -> if (Uri.parse(vod.urlobj).path.orEmpty().endsWith(".m3u8")) MimeTypes.APPLICATION_M3U8 + else if (Uri.parse(vod.urlobj).path.orEmpty().endsWith(".mpd")) MimeTypes.APPLICATION_MPD else "video/mp4" + } + val ownerAtStart = ownerToken() + val metadata = DownloadMetadata(title, ownerAtStart.first, vod.urlobj, mime, vod.header.toMap(), + vod.localProxyJson, vod.requestTransformJson) + val id = DownloadRules.id(metadata.owner, metadata.url) + withContext(Dispatchers.IO) { cache(context) } + val index = manager(context).downloadIndex + val existing = withContext(Dispatchers.IO) { index.getDownload(id) } + check(ownerToken() == ownerAtStart) { "Profile changed. Start the download again." } + if (existing?.state == Download.STATE_COMPLETED) return@withContext id + val upstream = DownloadUpstream(context.applicationContext, metadata) + val pref = context.getSharedPreferences("playback_quality", Context.MODE_PRIVATE) + .getString("preferred_resolution", "auto") + val parameters = TrackSelectionParameters.Builder(context) + .setForceHighestSupportedBitrate(pref != "lowest") + .setForceLowestBitrate(pref == "lowest") + .apply { pref?.toIntOrNull()?.takeIf { it > 0 }?.let { setMaxVideoSize(Int.MAX_VALUE, it) } } + .build() + val item = MediaItem.Builder().setUri(metadata.url).setMimeType(mime).build() + val helper = DownloadHelper.forMediaItem(item, parameters, DefaultRenderersFactory(context), + cacheFactory(context, id).setUpstreamDataSourceFactory(upstream.factory)) + try { + val request = withTimeout(30_000) { + suspendCancellableCoroutine { continuation -> + helper.prepare(object : DownloadHelper.Callback { + override fun onPrepared(helper: DownloadHelper, tracksInfoAvailable: Boolean) { + if (continuation.isActive) continuation.resume(helper.getDownloadRequest(id, metadata.encode())) + } + override fun onPrepareError(helper: DownloadHelper, error: IOException) { + if (continuation.isActive) continuation.resumeWithException(error) + } + }) + } + } + // Profile switch while resolving must never queue this under another household member. + check(ownerToken() == ownerAtStart) { "Profile changed. Start the download again in the selected profile." } + DownloadService.sendAddDownload(context, TvDownloadService::class.java, request, true) + DownloadService.sendResumeDownloads(context, TvDownloadService::class.java, true) + id + } finally { helper.release(); upstream.close() } + } + + suspend fun list(context: Context): List { + withContext(Dispatchers.IO) { cache(context) } + val index = withContext(Dispatchers.Main) { manager(context).downloadIndex } + val owner = ownerToken() + val result = withContext(Dispatchers.IO) { + index.getDownloads().use { cursor -> + buildList { + while (cursor.moveToNext()) { + val download = cursor.download + if (runCatching { DownloadMetadata.decode(download.request.data).owner == owner.first }.getOrDefault(false)) add(download) + } + } + } + } + return if (ownerToken() == owner) result else emptyList() + } + + fun title(download: Download): String = runCatching { + DownloadMetadata.decode(download.request.data).title + }.getOrDefault("Download") + + private suspend fun ownedDownload(context: Context, id: String): Download { + val owner = ownerToken() + val index = withContext(Dispatchers.Main) { manager(context).downloadIndex } + val download = withContext(Dispatchers.IO) { index.getDownload(id) } + check(download != null && DownloadMetadata.decode(download.request.data).owner == owner.first && ownerToken() == owner) { + "This download is not available in the selected profile." + } + return download + } + + suspend fun pause(context: Context, id: String, pause: Boolean) = withContext(Dispatchers.Main) { + ownedDownload(context, id) + DownloadService.sendSetStopReason(context, TvDownloadService::class.java, id, if (pause) 1 else 0, true) + if (!pause) DownloadService.sendResumeDownloads(context, TvDownloadService::class.java, true) + } + + suspend fun retry(context: Context, id: String) = withContext(Dispatchers.Main) { + val download = ownedDownload(context, id) + DownloadService.sendAddDownload(context, TvDownloadService::class.java, download.request, true) + DownloadService.sendResumeDownloads(context, TvDownloadService::class.java, true) + } + + suspend fun remove(context: Context, id: String) = withContext(Dispatchers.Main) { + ownedDownload(context, id) + DownloadService.sendRemoveDownload(context, TvDownloadService::class.java, id, false) + } + + private class DownloadUpstream(context: Context, private val metadata: DownloadMetadata) { + private val client: OkHttpClient = StreamHttp(context).proxyClient.newBuilder() + .addInterceptor { chain -> + val response = chain.proceed(chain.request()) + val type = response.header("Content-Type").orEmpty() + val prefix = response.peekBody(512).string().trimStart().lowercase() + if (type.contains("text/html", true) || prefix.startsWith(") { + cloudflare( + "cloudflare", + "https://cloudflare-dns.com/dns-query", + listOf("1.1.1.1", "1.0.0.1", "2606:4700:4700::1111", "2606:4700:4700::1001"), + ), + google( + "google", + "https://dns.google/dns-query", + listOf("8.8.8.8", "8.8.4.4", "2001:4860:4860::8888", "2001:4860:4860::8844"), + ), + ; + + companion object { + fun byId(id: String?): Provider? = + entries.firstOrNull { it.id == id?.trim()?.lowercase() } + } + } + + /** + * Null means the system resolver, which is the default and the right answer + * for most people. + */ + @Volatile + private var resolver: Dns? = null + + @Volatile + private var selected: String = "" + + /** What the app last applied, for the settings screen to read back. */ + fun current(): String = selected + + fun initialize(context: Context) { + apply(context, context.getSharedPreferences("extension_network", Context.MODE_PRIVATE).getString("dns", "")) + } + + fun set(context: Context, id: String?): String = apply(context, id).also { + context.getSharedPreferences("extension_network", Context.MODE_PRIVATE).edit().putString("dns", it).apply() + } + + /** + * Points every extension runtime at [id], or back at the system resolver + * when it names no provider we know. + * + * Returns the id actually in force, so a stored value from a newer build — + * or a typo — reports itself rather than silently doing nothing. + */ + @Synchronized + fun apply(context: Context, id: String?): String { + val provider = Provider.byId(id) + if (provider == null) { + resolver = null + selected = "" + Log.i(TAG, "using the system resolver") + return "" + } + resolver = try { + build(context, provider) + } catch (t: Throwable) { + // A resolver we cannot construct must not take name resolution down + // with it: the system one still works, and the alternative is an app + // that cannot reach anything at all. + Log.e(TAG, "could not build ${provider.id}, falling back to the system resolver", t) + null + } + selected = if (resolver == null) "" else provider.id + Log.i(TAG, "resolver=${selected.ifEmpty { "system" }}") + return selected + } + + /** + * The [Dns] the runtimes install. + * + * Reads [resolver] on every lookup rather than capturing it, so changing the + * setting takes effect on the next request instead of on the next launch — + * the clients are built once, behind a `lazy`, and are not rebuilt. + */ + val dns: Dns = Dns { hostname -> + val active = resolver + if (active == null) { + Dns.SYSTEM.lookup(hostname) + } else { + try { + active.lookup(hostname) + } catch (t: Throwable) { + // One failed DoH lookup is not a reason to fail the request. + // The endpoint may be blocked exactly where the user needs it + // least, and the system resolver is still there. + Log.w(TAG, "doh lookup failed for $hostname: ${t.javaClass.simpleName}") + Dns.SYSTEM.lookup(hostname) + } + } + } + + private var bootstrapClient: OkHttpClient? = null + + private fun build(context: Context, provider: Provider): Dns { + // Its own client, and a plain one. A DoH resolver has to reach its own + // endpoint, and giving that client the same resolver is a loop. + val bootstrap = bootstrapClient ?: OkHttpClient.Builder() + .cache( + Cache( + directory = File(context.cacheDir, "doh_cache"), + maxSize = 5L * 1024 * 1024, + ), + ) + .connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS) + .readTimeout(5, java.util.concurrent.TimeUnit.SECONDS) + .callTimeout(8, java.util.concurrent.TimeUnit.SECONDS) + .build().also { bootstrapClient = it } + return DnsOverHttps.Builder() + .client(bootstrap) + .url(provider.url.toHttpUrl()) + // The endpoint's own addresses, so the first lookup does not need + // the resolver it is trying to replace. + .bootstrapDnsHosts(provider.ips.mapNotNull { hostAddress(it) }) + .includeIPv6(true) + .build() + } + + private fun hostAddress(ip: String): InetAddress? = try { + InetAddress.getByName(ip) + } catch (_: Throwable) { + null + } +} diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/player/DashManifestRewriter.kt b/app/src/main/java/com/saikou/sozo_tv/engine/player/DashManifestRewriter.kt new file mode 100644 index 00000000..70eb4b6f --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/engine/player/DashManifestRewriter.kt @@ -0,0 +1,62 @@ +package com.saikou.sozo_tv.engine.player + +import org.w3c.dom.Element +import java.io.StringReader +import java.io.StringWriter +import javax.xml.parsers.DocumentBuilderFactory +import javax.xml.transform.TransformerFactory +import javax.xml.transform.dom.DOMSource +import javax.xml.transform.stream.StreamResult +import org.xml.sax.InputSource + +/** Resolves each DASH hierarchy level before replacing URLs; template tokens stay visible. */ +object DashManifestRewriter { + fun rewrite(xml: String, manifestUrl: String, proxy: (String) -> String): String { + require(!Regex("() + val protected = Regex("\\$[^$]+\\$").replace(path) { + tokens.add(it.value); "SOZODASHTOKEN${tokens.lastIndex}END" + } + var url = StreamRequestRules.resolve(base, protected) + tokens.forEachIndexed { i, token -> url = url.replace("SOZODASHTOKEN${i}END", token) } + return url + } + fun walk(node: Element, inherited: String, inheritedTemplate: Element? = null) { + val ownTemplates = (0 until node.childNodes.length).mapNotNull { node.childNodes.item(it) as? Element } + .filter { (it.localName ?: it.tagName) == "SegmentTemplate" } + if ((node.localName ?: node.tagName) == "Representation" && ownTemplates.isEmpty() && inheritedTemplate != null) + node.appendChild(inheritedTemplate.cloneNode(true)) + val template = ownTemplates.firstOrNull()?.cloneNode(true) as? Element ?: inheritedTemplate + val children = (0 until node.childNodes.length).mapNotNull { node.childNodes.item(it) as? Element } + val bases = children.filter { it.localName == "BaseURL" || it.tagName == "BaseURL" } + val base = bases.firstOrNull()?.textContent?.trim()?.takeIf { it.isNotEmpty() } + ?.let { resolve(inherited, it) } ?: inherited + val hasSegments = node.getElementsByTagNameNS("*", "SegmentTemplate").length > 0 || + node.getElementsByTagNameNS("*", "SegmentList").length > 0 + if (hasSegments) bases.forEach { node.removeChild(it) } + else bases.forEach { it.textContent = proxy(resolve(inherited, it.textContent.trim())) } + val attrs = when (node.localName ?: node.tagName) { + "SegmentTemplate" -> listOf("media", "initialization", "index", "bitstreamSwitching") + "SegmentURL" -> listOf("media", "index") + "Initialization", "RepresentationIndex" -> listOf("sourceURL") + else -> emptyList() + } + attrs.forEach { attr -> if (node.hasAttribute(attr)) node.setAttribute(attr, proxy(resolve(base, node.getAttribute(attr)))) } + children.filterNot { it in bases }.forEach { walk(it, base, template) } + } + walk(doc.documentElement, manifestUrl) + return StringWriter().also { TransformerFactory.newInstance().newTransformer() + .transform(DOMSource(doc), StreamResult(it)) }.toString() + } +} diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/player/HlsSegmentFilter.kt b/app/src/main/java/com/saikou/sozo_tv/engine/player/HlsSegmentFilter.kt new file mode 100644 index 00000000..5dcd3a67 --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/engine/player/HlsSegmentFilter.kt @@ -0,0 +1,51 @@ +package com.saikou.sozo_tv.engine.player + +/** + * Takes the segments a source's `dropSegments` rule matches out of a media playlist, with their + * timing. Port of the phone app's hls_segment_filter.dart. + * + * Some catalogues (kkphim) splice an ad into every stream as ordinary segments between two + * discontinuities; only the path gives it away. The two discontinuities around it become one, + * since the film's timestamps still jump there. A master playlist, or one the rule would empty, + * comes back as it is. + */ +object HlsSegmentFilter { + + /** The server's rule, or null when there is none or it does not compile. */ + fun ruleFrom(pattern: String?): Regex? { + if (pattern.isNullOrEmpty()) return null + return runCatching { Regex(pattern) }.getOrNull() + } + + fun drop(playlist: String, drop: Regex): String { + if (playlist.contains("#EXT-X-STREAM-INF")) return playlist + val out = mutableListOf() + // From an #EXTINF up to its uri, which decides whether they stay. + val pending = mutableListOf() + var discontinuity = false + var kept = 0 + var dropped = 0 + for (line in playlist.split('\n')) { + val s = line.trim() + when { + s == "#EXT-X-DISCONTINUITY" -> discontinuity = true + s.startsWith("#EXTINF") || pending.isNotEmpty() && s.startsWith("#") -> pending.add(line) + s.isEmpty() || s.startsWith("#") -> out.add(line) + drop.containsMatchIn(s) -> { + pending.clear() + dropped++ + } + else -> { + if (discontinuity) out.add("#EXT-X-DISCONTINUITY") + discontinuity = false + out.addAll(pending) + out.add(line) + pending.clear() + kept++ + } + } + } + if (dropped == 0 || kept == 0) return playlist + return out.joinToString("\n") + } +} diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/player/LocalHlsProxy.kt b/app/src/main/java/com/saikou/sozo_tv/engine/player/LocalHlsProxy.kt index 18b684bb..657afd6f 100644 --- a/app/src/main/java/com/saikou/sozo_tv/engine/player/LocalHlsProxy.kt +++ b/app/src/main/java/com/saikou/sozo_tv/engine/player/LocalHlsProxy.kt @@ -19,11 +19,30 @@ import java.util.concurrent.ConcurrentHashMap * variant playlists, segments, keys — through the same OkHttp client (which shares the WebView * cookie jar), so IP + cookies + signed headers match end to end. * - * Activates only when a source arrives with `useLocalProxy: true`. For uzmovi it also applies the + * Activates when a source arrives with `useLocalProxy: true`, or with a `dropSegments` rule whose + * ad segments it takes out of each media playlist. For uzmovi it also applies the * `uzmovi-rc4-v1` request transform (RC4-signed X-ATT-DeviceId / X-Match / X-Path + randomized URL). */ class LocalHlsProxy(private val client: OkHttpClient) { + companion object { + /** Stable cache identity across local proxy restarts; never decode arbitrary remote URLs. */ + fun canonicalUpstreamUrl(url: String): String? = runCatching { + val uri = URI(url) + if (uri.host !in setOf("127.0.0.1", "localhost", "::1")) return null + val parts = uri.path.split('/').drop(1) + if (parts.size < 3 || !parts[1].matches(Regex("[a-f0-9]+"))) return null + fun decode(value: String) = String(Base64.decode(value, Base64.URL_SAFE), Charsets.UTF_8) + val target = when (parts[0]) { + "hls" -> if (parts.size == 3) decode(parts[2]) else return null + "dash" -> parts.drop(2).mapIndexed { index, value -> if (index % 2 == 0) decode(value) else value }.joinToString("") + else -> return null + } + val parsed = URI(target) + target.takeIf { parsed.scheme in setOf("https", "http") && parsed.host != null } + }.getOrNull() + } + private var server: ProxyServer? = null private var port: Int = 0 private val sessions = ConcurrentHashMap() @@ -63,115 +82,88 @@ class LocalHlsProxy(private val client: OkHttpClient) { headers: Map, localProxy: JSONObject, requestTransform: JSONObject, + dropSegments: String? = null, ): String { ensureStarted() val id = randomId() val parsed = URI(upstreamUrl) - val fullPath = parsed.rawPath ?: "/" // encoded — used to build the loopback URL below - // basePath must be DECODED to match NanoHTTPD's decoded session.uri in handle(). Using the - // encoded rawPath here made startsWith() fail on paths with %20/spaces, doubling the path - // and corrupting the RC4 X-Match signature (uzdown then returns an empty 200 body). - val decodedPath = parsed.path ?: "/" - val ls = decodedPath.lastIndexOf('/') - val basePath = if (ls >= 0) decodedPath.substring(0, ls) else "" - sessions[id] = Session( - origin = "${parsed.scheme}://${parsed.authority}", - basePath = basePath, - cdnQuery = parsed.rawQuery ?: "", - headers = HashMap(headers), + require(parsed.scheme in setOf("http", "https") && parsed.host != null) + sessions[id] = Session(headers = HashMap(headers), transform = RequestTransform.fromMaps(localProxy, requestTransform), - ) - val query = parsed.rawQuery?.let { "?$it" } ?: "" - return "http://127.0.0.1:$port/hls/$id$fullPath$query" + dropSegments = HlsSegmentFilter.ruleFrom(dropSegments)) + return "http://127.0.0.1:$port/hls/$id/${b64UrlEncode(upstreamUrl)}" } private fun handle(session: NanoHTTPD.IHTTPSession): NanoHTTPD.Response { - val path = session.uri ?: "" - val match = Regex("^/hls/([a-f0-9]+)(/.*)$").find(path) ?: return error(404) - val sid = match.groupValues[1] - var cdnPath = match.groupValues[2] + if (session.method != NanoHTTPD.Method.GET && session.method != NanoHTTPD.Method.HEAD) return error(405) + val path = session.uri.orEmpty() + val parts = path.split('/').drop(1) + if (parts.size < 3 || parts[0] !in setOf("hls", "dash")) return error(404) + val sid = parts[1] val sess = sessions[sid] ?: return error(410) - - var origin = sess.origin - val hMatch = Regex("^/_h/([A-Za-z0-9_-]+)(/.*)$").find(cdnPath) - if (hMatch != null) { - try { - origin = "https://${b64UrlDecode(hMatch.groupValues[1])}" - cdnPath = hMatch.groupValues[2] - } catch (_: Exception) { - return error(400) - } - } - - val resolved = if (cdnPath.startsWith(sess.basePath) || origin != sess.origin) cdnPath - else "${sess.basePath}$cdnPath" - val incomingQuery = session.queryParameterString - val queryString = when { - !incomingQuery.isNullOrEmpty() -> "?$incomingQuery" - origin == sess.origin && sess.cdnQuery.isNotEmpty() -> "?${sess.cdnQuery}" - else -> "" - } - val upstreamUrl = "$origin$resolved$queryString" - + val upstreamUrl = runCatching { + if (parts[0] == "hls") b64UrlDecode(parts[2]) + else parts.drop(2).mapIndexed { i, value -> + if (i % 2 == 0) b64UrlDecode(value) else value + }.joinToString("") + }.getOrNull() ?: return error(400) + val uri = runCatching { URI(upstreamUrl) }.getOrNull() ?: return error(400) + if (uri.scheme !in setOf("http", "https") || uri.host == null) return error(400) + val origin = "${uri.scheme}://${uri.rawAuthority}" val upstreamHeaders = LinkedHashMap() - val keepOrigin = sess.transform?.keepsOriginHeaders == true - sess.headers.forEach { (k, v) -> - val lower = k.lowercase() - if (lower == "host" || lower == "content-length" || - (!keepOrigin && (lower == "origin" || lower == "referer")) - ) return@forEach - upstreamHeaders[k] = v - } - session.headers["range"]?.takeIf { it.isNotEmpty() }?.let { upstreamHeaders["Range"] = it } - session.headers["if-range"]?.takeIf { it.isNotEmpty() }?.let { upstreamHeaders["If-Range"] = it } - upstreamHeaders.putIfAbsent("Accept-Encoding", "identity") - if (upstreamHeaders.keys.none { it.equals("User-Agent", true) }) { - upstreamHeaders["User-Agent"] = SOZO_USER_AGENT - } - - val transformed = sess.transform?.apply(origin, resolved, upstreamHeaders) - val requestUrl = transformed?.url ?: upstreamUrl - val requestHeaders = transformed?.headers ?: upstreamHeaders - - val reqBuilder = Request.Builder().url(requestUrl) - requestHeaders.forEach { (k, v) -> runCatching { reqBuilder.header(k, v) } } - val resp = client.newCall(reqBuilder.build()).execute() - val status = resp.code - if (status >= 400) { - android.util.Log.w("HlsProxy", "upstream $status: $upstreamUrl") - resp.close() - return error(status) - } - val contentType = (resp.header("content-type") ?: "").lowercase() - val isManifest = contentType.contains("mpegurl") || contentType.contains("m3u8") || - resolved.endsWith(".m3u8") - - if (isManifest) { - val bytes = resp.body?.bytes() ?: ByteArray(0) // reads + closes - if (origin == sess.origin) { - val ls = resolved.lastIndexOf('/') - if (ls >= 0) sess.basePath = resolved.substring(0, ls) + sess.headers.filterKeys { it.lowercase() !in setOf("host", "content-length", "accept-encoding") } + .forEach { (k, v) -> upstreamHeaders[k] = v } + session.headers["range"]?.let { upstreamHeaders["Range"] = it } + session.headers["if-range"]?.let { upstreamHeaders["If-Range"] = it } + upstreamHeaders["Accept-Encoding"] = "identity" + if (upstreamHeaders.keys.none { it.equals("User-Agent", true) }) upstreamHeaders["User-Agent"] = SOZO_USER_AGENT + val transformed = sess.transform?.apply(origin, uri.path, upstreamHeaders) + val relay = StreamRequestRules.segmentRelay(upstreamUrl, + com.saikou.sozo_tv.BuildConfig.SOZO_API_BASE_URL.trimEnd('/') + "/contents/media-segment") + val requestUrl = relay ?: transformed?.url ?: upstreamUrl + // Never leak a provider's cookies or authorization into our segment relay. + val requestHeaders = if (relay != null) emptyMap() else transformed?.headers ?: upstreamHeaders + val request = Request.Builder().url(requestUrl).apply { + requestHeaders.forEach { (k, v) -> header(k, v) } + if (session.method == NanoHTTPD.Method.HEAD) head() + }.build() + val resp = client.newCall(request).execute() + if (!resp.isSuccessful) { val code = resp.code; resp.close(); return error(code) } + val contentType = resp.header("content-type").orEmpty().lowercase() + val effectiveUrl = resp.request.url.toString() + val isManifest = contentType.contains("mpegurl") || uri.path.endsWith(".m3u8") || + resp.body?.source()?.peek()?.let { it.request(7) && it.readUtf8(7) == "#EXTM3U" } == true + val isDash = contentType.contains("dash+xml") || uri.path.endsWith(".mpd") + if ((isManifest || isDash) && session.method != NanoHTTPD.Method.HEAD) { + val text = resp.use { it.body?.string().orEmpty() } + val rewritten = if (isDash) DashManifestRewriter.rewrite(text, effectiveUrl) { target -> + // Literal chunks are opaque; Media3 must still see and expand DASH $tokens$. + val token = Regex("\\$[^$]+\\$") + if (!token.containsMatchIn(target)) "/hls/$sid/${b64UrlEncode(target)}" + else { + var end = 0 + val chunks = mutableListOf() + token.findAll(target).forEach { match -> + chunks.add(b64UrlEncode(target.substring(end, match.range.first))) + chunks.add(match.value) + end = match.range.last + 1 + } + chunks.add(b64UrlEncode(target.substring(end))) + "/dash/$sid/" + chunks.joinToString("/") + } + } else { + if (!text.trimStart().startsWith("#EXTM3U")) return error(502) + rewriteM3u8(sess.dropSegments?.let { HlsSegmentFilter.drop(text, it) } ?: text, "/hls/$sid", effectiveUrl) } - val text = String(bytes, Charsets.UTF_8) - val rewritten = runCatching { rewriteM3u8(text, "/hls/$sid", sess.origin, upstreamUrl) } - .getOrDefault(text) - return NanoHTTPD.newFixedLengthResponse( - statusOf(200), "application/vnd.apple.mpegurl", rewritten, - ) + return NanoHTTPD.newFixedLengthResponse(statusOf(200), + if (isDash) "application/dash+xml" else "application/vnd.apple.mpegurl", rewritten) } - - val len = resp.body?.contentLength() ?: -1L - val stream = resp.body?.byteStream() // closed by NanoHTTPD when done → releases the response - val out = if (len >= 0) { - NanoHTTPD.newFixedLengthResponse(statusOf(status), contentType.ifEmpty { "application/octet-stream" }, stream, len) - } else { - NanoHTTPD.newChunkedResponse(statusOf(status), contentType.ifEmpty { "application/octet-stream" }, stream) - } - copyHeader(resp, out, "content-range") - copyHeader(resp, out, "accept-ranges") - copyHeader(resp, out, "cache-control") - copyHeader(resp, out, "etag") - copyHeader(resp, out, "last-modified") + val body = resp.body ?: run { resp.close(); return error(502) } + val len = body.contentLength() + val out = if (len >= 0) NanoHTTPD.newFixedLengthResponse(statusOf(resp.code), + contentType.ifEmpty { "application/octet-stream" }, body.byteStream(), len) + else NanoHTTPD.newChunkedResponse(statusOf(resp.code), contentType.ifEmpty { "application/octet-stream" }, body.byteStream()) + listOf("content-range", "accept-ranges", "cache-control", "etag", "last-modified").forEach { copyHeader(resp, out, it) } return out } @@ -189,50 +181,18 @@ class LocalHlsProxy(private val client: OkHttpClient) { override fun getRequestStatus(): Int = code } - private fun rewriteM3u8(content: String, base: String, sessionOrigin: String, upstreamUrl: String): String { - // String-based (NOT java.net.URI, which throws on the raw spaces uzmovi segment paths - // contain). Encodes spaces in the output so the rewritten loopback URLs stay valid. - val sessionAuthority = sessionOrigin.substringAfter("://") - val upstreamDir = upstreamUrl.substringBefore('?').substringBeforeLast('/', upstreamUrl.substringBefore('?')) - - fun enc(s: String) = s.replace(" ", "%20") - - fun rewriteUrl(raw: String): String { - val t = raw.trim() - if (t.isEmpty()) return raw - return when { - t.startsWith("http://", true) || t.startsWith("https://", true) -> { - val schemeEnd = t.indexOf("://") + 3 - val slash = t.indexOf('/', schemeEnd).let { if (it < 0) t.length else it } - val authority = t.substring(schemeEnd, slash) - val rest = enc(t.substring(slash)) - if (authority == sessionAuthority) "$base$rest" - else "$base/_h/${b64UrlEncode(authority)}$rest" - } - t.startsWith("//") -> { - val slash = t.indexOf('/', 2).let { if (it < 0) t.length else it } - val authority = t.substring(2, slash) - val rest = enc(t.substring(slash)) - if (authority == sessionAuthority) "$base$rest" - else "$base/_h/${b64UrlEncode(authority)}$rest" - } - t.startsWith("/") -> "$base${enc(t)}" // absolute path, same authority - else -> { // relative to the manifest dir - val abs = "$upstreamDir/$t" - val schemeEnd = abs.indexOf("://").let { if (it < 0) 0 else it + 3 } - val slash = abs.indexOf('/', schemeEnd).let { if (it < 0) abs.length else it } - "$base${enc(abs.substring(slash))}" - } - } + private fun rewriteM3u8(content: String, base: String, upstreamUrl: String): String { + fun rewrite(raw: String): String { + val absolute = StreamRequestRules.resolve(upstreamUrl, raw) + if (!absolute.startsWith("http://") && !absolute.startsWith("https://")) return raw + return "$base/${b64UrlEncode(absolute)}" } - - val keyAttr = Regex("URI=\"([^\"]+)\"") - return content.split("\n").joinToString("\n") { line -> - val stripped = line.trim() + val attributes = Regex("URI=\"([^\"]+)\"") + return content.lines().joinToString("\n") { line -> when { - stripped.isEmpty() -> line - stripped.startsWith("#") -> keyAttr.replace(line) { m -> "URI=\"${rewriteUrl(m.groupValues[1])}\"" } - else -> rewriteUrl(line) + line.isBlank() -> line + line.trimStart().startsWith("#") -> attributes.replace(line) { "URI=\"${rewrite(it.groupValues[1])}\"" } + else -> rewrite(line.trim()) } } } @@ -248,13 +208,7 @@ class LocalHlsProxy(private val client: OkHttpClient) { private fun b64UrlDecode(s: String): String = String(Base64.decode(s, Base64.URL_SAFE), Charsets.UTF_8) - private class Session( - val origin: String, - @Volatile var basePath: String, - val cdnQuery: String, - val headers: Map, - val transform: RequestTransform?, - ) + private class Session(val headers: Map, val transform: RequestTransform?, val dropSegments: Regex?) private class TransformedRequest(val url: String, val headers: Map) diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/player/StreamDrm.kt b/app/src/main/java/com/saikou/sozo_tv/engine/player/StreamDrm.kt new file mode 100644 index 00000000..63394d71 --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/engine/player/StreamDrm.kt @@ -0,0 +1,58 @@ +package com.saikou.sozo_tv.engine.player + +import androidx.media3.common.C +import androidx.media3.common.MediaItem +import androidx.media3.exoplayer.drm.DefaultDrmSessionManager +import androidx.media3.exoplayer.drm.FrameworkMediaDrm +import androidx.media3.exoplayer.drm.LocalMediaDrmCallback +import androidx.media3.exoplayer.source.DefaultMediaSourceFactory +import org.json.JSONArray +import org.json.JSONObject +import okio.ByteString.Companion.decodeBase64 +import okio.ByteString.Companion.decodeHex + +/** Carries extractor DRM into both the media item and ClearKey session manager. */ +@androidx.media3.common.util.UnstableApi +object StreamDrm { + fun configure(item: MediaItem.Builder, json: String?): MediaItem.Builder { + if (json.isNullOrBlank()) return item + val obj = JSONObject(json) + val scheme = when (obj.optString("scheme").lowercase()) { + "widevine", "com.widevine.alpha" -> C.WIDEVINE_UUID + "clearkey", "org.w3.clearkey" -> C.CLEARKEY_UUID + "playready", "com.microsoft.playready" -> C.PLAYREADY_UUID + else -> throw IllegalArgumentException("Unsupported DRM scheme") + } + val headers = obj.optJSONObject("licenseHeaders") ?: JSONObject() + val config = MediaItem.DrmConfiguration.Builder(scheme) + .setLicenseRequestHeaders(headers.keys().asSequence().associateWith { headers.getString(it) }) + obj.optString("licenseUrl").takeIf { it.isNotBlank() }?.let { config.setLicenseUri(it) } + return item.setDrmConfiguration(config.build()) + } + + fun configure(factory: DefaultMediaSourceFactory, json: String?): DefaultMediaSourceFactory { + if (json.isNullOrBlank()) return factory + val obj = JSONObject(json) + val keys = obj.optJSONObject("clearKeys") ?: return factory + if (keys.length() == 0) return factory + val response = clearKeyResponse(keys).toByteArray(Charsets.UTF_8) + return factory.setDrmSessionManagerProvider { + DefaultDrmSessionManager.Builder() + .setUuidAndExoMediaDrmProvider(C.CLEARKEY_UUID, FrameworkMediaDrm.DEFAULT_PROVIDER) + .build(LocalMediaDrmCallback(response)) + } + } + + internal fun clearKeyResponse(keys: JSONObject): String { + fun encode(value: String): String { + val raw = if (value.length % 2 == 0 && value.matches(Regex("[0-9a-fA-F]+"))) + value.decodeHex() + else requireNotNull(value.decodeBase64()) { "Invalid ClearKey encoding" } + return raw.base64Url().trimEnd('=') + } + val values = JSONArray() + keys.keys().forEach { id -> values.put(JSONObject().put("kty", "oct") + .put("kid", encode(id)).put("k", encode(keys.getString(id)))) } + return JSONObject().put("keys", values).put("type", "temporary").toString() + } +} diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/player/StreamHttp.kt b/app/src/main/java/com/saikou/sozo_tv/engine/player/StreamHttp.kt index f8090ea4..be6c16e3 100644 --- a/app/src/main/java/com/saikou/sozo_tv/engine/player/StreamHttp.kt +++ b/app/src/main/java/com/saikou/sozo_tv/engine/player/StreamHttp.kt @@ -1,5 +1,6 @@ package com.saikou.sozo_tv.engine.player +import com.saikou.sozo_tv.engine.network.ExtensionDns import android.content.Context import android.util.Log import androidx.media3.common.util.UnstableApi @@ -27,6 +28,7 @@ class StreamHttp(context: Context) { // Lenient TLS on purpose: this carries only third-party stream traffic, whose CDNs often serve // incomplete chains (no AIA fetch on Android), and never a Sozo token. val client: OkHttpClient = OkHttpClient.Builder() + .dns(ExtensionDns.dns) .followRedirects(true).followSslRedirects(true) .connectionSpecs( listOf(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS, ConnectionSpec.CLEARTEXT) @@ -54,6 +56,11 @@ class StreamHttp(context: Context) { val dataSourceFactory: DataSource.Factory = DefaultDataSource.Factory(appContext, OkHttpDataSource.Factory(client)) + /** Independent rendition headers must not be overwritten by the video's mutable headers. */ + fun dataSourceFactoryFor(requestHeaders: Map): DataSource.Factory = + DefaultDataSource.Factory(appContext, OkHttpDataSource.Factory(proxyClient) + .setDefaultRequestProperties(requestHeaders)) + val subtitleClient: OkHttpClient by lazy { client.newBuilder() .apply { networkInterceptors().clear() } @@ -64,6 +71,7 @@ class StreamHttp(context: Context) { val proxyClient: OkHttpClient by lazy { OkHttpClient.Builder() + .dns(ExtensionDns.dns) .followRedirects(true).followSslRedirects(true) .cookieJar(AndroidCookieJar()) .addInterceptor(cloudflare) diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/player/StreamRequestRules.kt b/app/src/main/java/com/saikou/sozo_tv/engine/player/StreamRequestRules.kt new file mode 100644 index 00000000..21b7a669 --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/engine/player/StreamRequestRules.kt @@ -0,0 +1,53 @@ +package com.saikou.sozo_tv.engine.player + +import java.net.URI +import java.net.URLEncoder + +/** Shared by WebView capture and the proxy; no Android runtime required. */ +object StreamRequestRules { + private val dropped = setOf("range", "accept-encoding", "host", "content-length", "connection", + "sec-fetch-dest", "sec-fetch-mode", "sec-fetch-site", "sec-fetch-user", + "upgrade-insecure-requests", "x-requested-with") + + fun headers(page: Map, captured: Map, frameUrl: String, + userAgent: String, cookie: String? = null): Map { + val out = linkedMapOf() + fun put(name: String, value: String) { + if (name.lowercase() in dropped) return + out.keys.firstOrNull { it.equals(name, true) }?.let { out.remove(it) } + out[name] = value + } + // A page's Referer/Origin identifies its parent, not the frame requesting media. + page.filterKeys { !it.equals("Referer", true) && !it.equals("Origin", true) } + .forEach { (k, v) -> put(k, v) } + val frame = URI(frameUrl) + put("Referer", frameUrl) + put("Origin", "${frame.scheme}://${frame.rawAuthority}") + put("User-Agent", out.entries.firstOrNull { it.key.equals("User-Agent", true) }?.value ?: userAgent) + captured.forEach { (k, v) -> put(k, v) } + if (!cookie.isNullOrBlank() && out.keys.none { it.equals("Cookie", true) }) put("Cookie", cookie) + return out + } + + fun playType(url: String): String = when { + url.substringBefore('?').contains(".mpd", true) -> "dash" + url.substringBefore('?').contains(".mp4", true) -> "mp4" + else -> "hls" + } + + fun needsManifestProxy(url: String): Boolean = runCatching { + val path = URI(url).path.orEmpty() + path.startsWith("/stream/") && path.endsWith(".m3u8") + }.getOrDefault(false) + + fun segmentRelay(url: String, endpoint: String): String? = runCatching { + val uri = URI(url) + if (uri.scheme != "https" || uri.userInfo != null || (uri.port != -1 && uri.port != 443) || + !Regex("p(?:16|19)-ad-site-sign-sg\\.tiktokcdn\\.com").matches(uri.host.orEmpty()) || + !uri.path.startsWith("/ad-site-i18n-sg/") || !uri.path.endsWith(".image")) null + else "$endpoint?url=${URLEncoder.encode(url, "UTF-8")}" + }.getOrNull() + + fun resolve(base: String, relative: String): String = URI(base.replace(" ", "%20")) + .resolve(relative.trim().replace(" ", "%20")).normalize().toASCIIString() +} diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/player/SubtitleSideloader.kt b/app/src/main/java/com/saikou/sozo_tv/engine/player/SubtitleSideloader.kt index 81944ce3..7452226b 100644 --- a/app/src/main/java/com/saikou/sozo_tv/engine/player/SubtitleSideloader.kt +++ b/app/src/main/java/com/saikou/sozo_tv/engine/player/SubtitleSideloader.kt @@ -69,7 +69,8 @@ class SubtitleSideloader( ?: retryReferer?.let { fetch(chosen, referer = it) } ?: throw IOException("subtitle host refused the request") - val body = SubtitleBody.decode(bytes, chosen.label) + val decoded = SubtitleBody.decode(bytes, chosen.label) + val body = chosen.cipher?.decrypt(decoded) ?: decoded cached = chosen.file to body return body } diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/player/UrlSigner.kt b/app/src/main/java/com/saikou/sozo_tv/engine/player/UrlSigner.kt new file mode 100644 index 00000000..d9f2df88 --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/engine/player/UrlSigner.kt @@ -0,0 +1,107 @@ +package com.saikou.sozo_tv.engine.player + +import com.saikou.sozo_tv.engine.network.ExtensionDns +import com.saikou.sozo_tv.utils.SOZO_USER_AGENT +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.OkHttpClient +import okhttp3.Request +import org.json.JSONArray +import org.json.JSONObject +import org.json.JSONTokener +import java.net.URLDecoder +import java.util.concurrent.TimeUnit + +/** + * A source's file that the device has to sign for itself before playing. Port of the phone app's + * url_signer.dart. + * + * asilmedia's fayllar1 hands out a file only through a signed URL whose token is bound to the + * User-Agent and IP that asked for it, so the server cannot sign on the TV's behalf. It sends + * where to ask, under which query parameter the file goes, and with what headers; the answer is + * a JSON map from the file as sent to its signed URL. + */ +class UrlSigner( + val url: String, + val param: String, + val headers: Map = emptyMap(), +) { + + /** + * The signed URL for [file], asked with [playerHeaders]' User-Agent, which the token is bound + * to. Null when the host would not sign it; the caller then plays the file as it was. + */ + fun sign(file: String, playerHeaders: Map, client: OkHttpClient = defaultClient): String? { + val ua = playerHeaders.entries.firstOrNull { it.key.equals("User-Agent", true) }?.value + ?: SOZO_USER_AGENT + val key = "$file\u0000$ua" + val now = System.currentTimeMillis() + synchronized(cache) { + cache[key]?.takeIf { now - it.second < KEEP_MS }?.let { return it.first } + } + return runCatching { + val request = Request.Builder().url(requestUrl(file)).apply { + headers.forEach { (k, v) -> header(k, v) } + header("User-Agent", ua) + }.build() + client.newCall(request).execute().use { res -> + if (res.code != 200) return null + signedUrlFrom(res.body?.string().orEmpty()) + } + }.getOrNull()?.also { signed -> + synchronized(cache) { + if (cache.size > 64) cache.clear() + cache[key] = signed to now + } + } + } + + /** Sent decoded, as the page itself sends it: the host keys its answer by the file as asked. */ + internal fun requestUrl(file: String): String = + url.toHttpUrl().newBuilder() + .setQueryParameter(param, URLDecoder.decode(file.replace("+", "%2B"), "UTF-8")) + .build().toString() + + companion object { + private const val KEEP_MS = 20 * 60 * 1000L + + // Tokens expire, so a retry after that must ask again. + private val cache = HashMap>() + + private val defaultClient: OkHttpClient by lazy { + OkHttpClient.Builder() + .dns(ExtensionDns.dns) + .callTimeout(8, TimeUnit.SECONDS) + .build() + } + + /** [file] signed by the source's [signerJson], or [file] itself. Blocking. */ + fun signedOrSelf(signerJson: String?, file: String, playerHeaders: Map): String = + fromJson(signerJson)?.sign(file, playerHeaders) ?: file + + fun fromJson(json: String?): UrlSigner? { + if (json.isNullOrBlank()) return null + val o = runCatching { JSONObject(json) }.getOrNull() ?: return null + val url = o.opt("url") as? String + val param = o.opt("param") as? String + if (url.isNullOrEmpty() || param.isNullOrEmpty()) return null + val raw = o.optJSONObject("headers") + val headers = raw?.keys()?.asSequence() + ?.filter { !raw.isNull(it) } + ?.associateWith { raw.get(it).toString() } + .orEmpty() + return UrlSigner(url, param, headers) + } + + internal fun signedUrlFrom(body: String): String? { + val signed = when (val v = runCatching { JSONTokener(body).nextValue() }.getOrNull()) { + is JSONObject -> v.keys().asSequence().map { v.opt(it) }.filterIsInstance().firstOrNull() + is JSONArray -> (0 until v.length()).map { v.opt(it) }.filterIsInstance().firstOrNull() + is String -> v + else -> null + } + return signed?.takeIf { it.startsWith("http") } + } + + internal fun clearCache() = synchronized(cache) { cache.clear() } + } +} diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/player/WebViewStreamExtractor.kt b/app/src/main/java/com/saikou/sozo_tv/engine/player/WebViewStreamExtractor.kt index fa36c74c..b6e05bab 100644 --- a/app/src/main/java/com/saikou/sozo_tv/engine/player/WebViewStreamExtractor.kt +++ b/app/src/main/java/com/saikou/sozo_tv/engine/player/WebViewStreamExtractor.kt @@ -1,183 +1,142 @@ package com.saikou.sozo_tv.engine.player -import com.saikou.sozo_tv.utils.SOZO_USER_AGENT import android.content.Context -import android.net.Uri import android.os.Handler import android.os.Looper -import android.view.View import android.webkit.CookieManager +import android.webkit.JavascriptInterface import android.webkit.WebResourceRequest import android.webkit.WebResourceResponse import android.webkit.WebView import android.webkit.WebViewClient +import androidx.webkit.WebViewCompat +import androidx.webkit.WebViewFeature +import com.saikou.sozo_tv.utils.SOZO_USER_AGENT import kotlinx.coroutines.suspendCancellableCoroutine +import org.json.JSONArray +import org.json.JSONObject import java.io.ByteArrayInputStream +import java.net.URI import kotlin.coroutines.resume -data class ExtractedStream( - val url: String, - val headers: Map, - val playType: String, // "hls" | "mp4" -) +data class ExtractedStream(val url: String, val headers: Map, val playType: String) -/** - * Headless-WebView stream sniffer — Kotlin port of soplay's webview_stream_extractor.dart. - * - * Some "Cloud" providers (e.g. asilmedia) resolve to an HTML content page, not a direct stream. - * ExoPlayer can't play a page. This loads the page in a hidden WebView and intercepts its network - * traffic (shouldInterceptRequest) to capture the first real .m3u8/.mp4/.mpd the page fires, plus - * that request's headers — then playback uses THAT url. The page's own JS builds the signed stream - * url, which is exactly what we need. - */ +/** Capture before sending the media request: signed manifests can be single use. */ object WebViewStreamExtractor { - - private val MOBILE_UA get() = SOZO_USER_AGENT - - private const val SETTLE_MS = 3_000L - - // Direct-media extensions that mean "already a stream, no extraction needed". - private val DIRECT_EXT = listOf(".m3u8", ".mpd", ".mp4", ".mkv", ".webm") - - // What we sniff for in the WebView's network traffic (first match wins). - private val STREAM_PATS = listOf(".m3u8", ".mpd", ".mp4") - - private val DROP_HEADERS = setOf( - "range", "accept-encoding", "host", "content-length", "connection", - "sec-fetch-dest", "sec-fetch-mode", "sec-fetch-site", "sec-fetch-user", - "upgrade-insecure-requests", "x-requested-with", - ) - - // Tracker/ad noise to swallow so the page settles faster. - private val BLOCK = listOf( - "mc.yandex.ru", "yastatic.net", "yandex.net", "google-analytics.com", - "googletagmanager.com", "doubleclick.net", "googlesyndication.com", "adservice", - ) - - // Player-page path segments. An /embed/ url carries no extension, so the - // suffix checks below cannot see it. Kept deliberately narrow — a short alias - // like "/e/" also appears mid-path on plain CDNs, and a false positive here - // costs a 20s WebView on a url ExoPlayer could have played directly. - private val PAGE_SEGMENTS = listOf("/embed/", "/player/") - - /** True when [url] is an HTML page we must open in a WebView to discover the real stream. */ + private val patterns = listOf(".m3u8", ".mpd", ".mp4") fun needsExtraction(url: String): Boolean { - val path = url.substringBefore('?').lowercase() - // Already a direct stream/file → no extraction. - if (DIRECT_EXT.any { path.contains(it) }) return false - if (PAGE_SEGMENTS.any { path.contains(it) }) return true - // Only clear content pages need sniffing. Extensionless/query endpoints are usually - // already-direct streams — don't spend a 20s WebView on them (false positive penalty). - return path.endsWith(".html") || path.endsWith(".htm") || - path.endsWith(".php") || path.endsWith("/") + val path = runCatching { URI(url).path.orEmpty().lowercase() }.getOrDefault("") + if (listOf(".m3u8", ".mpd", ".mp4", ".mkv", ".webm").any { path.endsWith(it) }) return false + return listOf("/embed/", "/player/", "/e/").any { path.startsWith(it) } || + listOf(".html", ".htm", ".php", "/").any { path.endsWith(it) } } - /** - * Loads [pageUrl] in a hidden WebView with [pageHeaders] (Referer/UA) and returns the first - * .m3u8/.mp4/.mpd request it fires, merging that request's headers over the page headers. - * Returns null on timeout. Suspends; the WebView is created/destroyed on the main thread. - */ - suspend fun extract( - context: Context, - pageUrl: String, - pageHeaders: Map = emptyMap(), - timeoutMs: Long = 20_000L, - patterns: List = STREAM_PATS, - blockHosts: List = emptyList(), - ): ExtractedStream? = suspendCancellableCoroutine { cont -> - val main = Handler(Looper.getMainLooper()) - var webView: WebView? = null - val settled = java.util.concurrent.atomic.AtomicBoolean(false) - val hit = java.util.concurrent.atomic.AtomicReference(null) - // Position in [pats] of the current hit. Patterns are PRIORITY-ordered, so a - // late .m3u8 still displaces an .mp4 ad creative that arrived first. - val hitRank = java.util.concurrent.atomic.AtomicInteger(Int.MAX_VALUE) - - val pats = patterns.ifEmpty { STREAM_PATS }.map { it.lowercase() } - val block = BLOCK + blockHosts.map { it.lowercase() } + private class CaptureBridge(private val receive: (String) -> Unit) { + @JavascriptInterface fun capture(payload: String) = receive(payload) + } - val cleanup = { + suspend fun extract(context: Context, pageUrl: String, pageHeaders: Map = emptyMap(), + timeoutMs: Long = 20_000L, patterns: List = this.patterns, + blockHosts: List = emptyList()): ExtractedStream? = suspendCancellableCoroutine { cont -> + val main = Handler(Looper.getMainLooper()) + var view: WebView? = null + var found: ExtractedStream? = null + var bestRank = Int.MAX_VALUE + var finished = false + val pats = patterns.ifEmpty { this.patterns }.map { it.lowercase() } + val blocked = blockHosts + listOf("doubleclick.net", "google-analytics.com", "googlesyndication.com") + fun finish(result: ExtractedStream?) { + if (finished) return + finished = true + main.removeCallbacksAndMessages(null) + view?.let { it.stopLoading(); it.removeJavascriptInterface("SozoCapture"); it.destroy() } + view = null + if (cont.isActive) cont.resume(result) + } + fun rank(url: String) = pats.indexOfFirst { url.substringBefore('?').lowercase().contains(it) } + fun capture(url: String, headers: Map, frame: String) { main.post { - runCatching { webView?.stopLoading(); webView?.destroy() } - webView = null + if (finished || !cont.isActive) return@post + val uri = runCatching { URI(url) }.getOrNull() ?: return@post + if (uri.scheme !in setOf("https", "http") || uri.host == null) return@post + val r = rank(url) + if (r < 0 || r >= bestRank) return@post + val first = found == null + val merged = runCatching { + StreamRequestRules.headers(pageHeaders, headers, frame, SOZO_USER_AGENT, + CookieManager.getInstance().getCookie(url)) + }.getOrNull() ?: return@post + found = ExtractedStream(url, merged, StreamRequestRules.playType(url)) + bestRank = r + if (r == 0) finish(found) + else if (first) main.postDelayed({ finish(found) }, 2500) } } - val uri = Uri.parse(pageUrl) - val referer = pageHeaders.entries.firstOrNull { it.key.equals("Referer", true) }?.value - ?: "${uri.scheme}://${uri.host}/" - - val streamReferer = pageUrl - val streamOrigin = "${uri.scheme}://${uri.host}" - - android.util.Log.i("StreamExtract", "sniffing page: $pageUrl") - main.post { + if (!cont.isActive) return@post val wv = WebView(context).apply { settings.javaScriptEnabled = true settings.domStorageEnabled = true settings.mediaPlaybackRequiresUserGesture = false - settings.loadsImagesAutomatically = false - settings.blockNetworkImage = true - settings.userAgentString = pageHeaders["User-Agent"] ?: MOBILE_UA - visibility = View.GONE + settings.userAgentString = pageHeaders.entries.firstOrNull { it.key.equals("User-Agent", true) }?.value ?: SOZO_USER_AGENT + // Keep a viewport for player overlays that require a center click. + layout(0, 0, 1280, 720) } - webView = wv - - val timeout = Runnable { - if (settled.compareAndSet(false, true)) { - android.util.Log.w("StreamExtract", "timeout, no stream captured for $pageUrl") - cleanup(); if (cont.isActive) cont.resume(null) + view = wv + wv.addJavascriptInterface(CaptureBridge { raw -> + runCatching { + val obj = JSONObject(raw) + val h = obj.optJSONObject("headers") ?: JSONObject() + capture(obj.getString("url"), h.keys().asSequence().associateWith { h.getString(it) }, obj.optString("frame", pageUrl)) } + }, "SozoCapture") + val script = captureScript(pats) + if (WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) { + WebViewCompat.addDocumentStartJavaScript(wv, script, setOf("*")) } - main.postDelayed(timeout, timeoutMs) - - val settle = Runnable { - if (!settled.compareAndSet(false, true)) return@Runnable - main.removeCallbacks(timeout) - runCatching { CookieManager.getInstance().flush() } - val found = hit.get() - android.util.Log.i("StreamExtract", "settled on: ${found?.url}") - cleanup() - if (cont.isActive) cont.resume(found) - } - wv.webViewClient = object : WebViewClient() { - override fun shouldInterceptRequest( - view: WebView, request: WebResourceRequest, - ): WebResourceResponse? { + override fun onPageFinished(v: WebView, url: String) { v.evaluateJavascript(script, null) } + override fun shouldInterceptRequest(v: WebView, request: WebResourceRequest): WebResourceResponse? { val url = request.url.toString() - val lower = url.lowercase() - - if (block.any { lower.contains(it) }) { - return WebResourceResponse("text/plain", "utf-8", ByteArrayInputStream(ByteArray(0))) - } - if (settled.get()) return null - val bare = lower.substringBefore('?') - val rank = pats.indexOfFirst { bare.contains(it) } - if (rank < 0 || rank >= hitRank.get()) return null - - val headers = buildMap { - request.requestHeaders - ?.filterKeys { it.lowercase() !in DROP_HEADERS } - ?.forEach { (k, v) -> put(k, v) } - pageHeaders.forEach { (k, v) -> putIfAbsent(k, v) } - putIfAbsent("User-Agent", MOBILE_UA) - put("Referer", streamReferer) - putIfAbsent("Origin", streamOrigin) - } - val playType = if (bare.contains(".mp4")) "mp4" else "hls" - android.util.Log.i("StreamExtract", "captured $playType: $url") - android.util.Log.i("StreamExtract", "replaying headers: ${headers.keys.sorted()}") - - val isFirst = hitRank.getAndSet(rank) == Int.MAX_VALUE - hit.set(ExtractedStream(url, headers, playType)) - if (isFirst) main.postDelayed(settle, SETTLE_MS) - return null + val host = request.url.host.orEmpty().lowercase() + if (blocked.any { host == it || host.endsWith(".$it") }) return empty() + if (rank(url) < 0) return null + val h = request.requestHeaders.orEmpty() + capture(url, h, h.entries.firstOrNull { it.key.equals("Referer", true) }?.value ?: pageUrl) + return empty() } } - - wv.loadUrl(pageUrl, mapOf("Referer" to referer)) + main.postDelayed({ finish(found) }, timeoutMs) + wv.loadUrl(pageUrl, pageHeaders) } - cont.invokeOnCancellation { cleanup() } + cont.invokeOnCancellation { main.post { finish(null) } } } + + private fun empty() = WebResourceResponse("text/plain", "utf-8", ByteArrayInputStream(byteArrayOf())) + + internal fun captureScript(patterns: List): String = """ + (function(){ + if(window.__sozoCaptureInstalled)return; window.__sozoCaptureInstalled=true; + var pats=${JSONArray(patterns)}; + function report(u,h){try{ + u=new URL(u,location.href).href; + if(!pats.some(function(p){return u.split('?')[0].toLowerCase().indexOf(p)>=0;}))return false; + var headers=Object.assign({Referer:location.href,Origin:location.origin},h||{}); + SozoCapture.capture(JSON.stringify({url:u,headers:headers,frame:location.href}));return true; + }catch(e){return false;}} + var open=XMLHttpRequest.prototype.open,set=XMLHttpRequest.prototype.setRequestHeader,send=XMLHttpRequest.prototype.send; + XMLHttpRequest.prototype.open=function(m,u){this.__sozoUrl=u;this.__sozoHeaders={};return open.apply(this,arguments);}; + XMLHttpRequest.prototype.setRequestHeader=function(k,v){this.__sozoHeaders[k]=String(v);return set.apply(this,arguments);}; + XMLHttpRequest.prototype.send=function(){if(report(this.__sozoUrl,this.__sozoHeaders))return;return send.apply(this,arguments);}; + var fetch=window.fetch; + if(fetch)window.fetch=function(input,init){var h={};try{new Headers((init&&init.headers)||(input&&input.headers)||{}).forEach(function(v,k){h[k]=v;});}catch(e){} + if(report(typeof input==='string'?input:input.url,h))return new Promise(function(){});return fetch.apply(this,arguments);}; + window.open=function(){return null;}; + var tries=0,t=setInterval(function(){if(++tries>12){clearInterval(t);return;} + try{var v=document.querySelector('video');if(v){v.muted=true;var p=v.play();if(p)p.catch(function(){});} + var e=document.querySelector('.vjs-big-play-button,.jw-icon-playback,[aria-label="Play"],.plyr__control--overlaid')||document.elementFromPoint(innerWidth/2,innerHeight/2); + if(e&&e.tagName!=='A'&&e.tagName!=='IFRAME')e.dispatchEvent(new MouseEvent('click',{bubbles:true,cancelable:true,view:window})); + }catch(e){}},1000); + })(); + """.trimIndent() } diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/server/ApisozoClient.kt b/app/src/main/java/com/saikou/sozo_tv/engine/server/ApisozoClient.kt index 50467cd7..d17ea667 100644 --- a/app/src/main/java/com/saikou/sozo_tv/engine/server/ApisozoClient.kt +++ b/app/src/main/java/com/saikou/sozo_tv/engine/server/ApisozoClient.kt @@ -3,28 +3,15 @@ package com.saikou.sozo_tv.engine.server import com.saikou.sozo_tv.utils.SOZO_USER_AGENT import android.net.Uri import com.saikou.sozo_tv.BuildConfig -import java.net.HttpURLConnection -import java.net.URL class ApisozoClient(private val baseUrl: String = BuildConfig.APISOZO_BASE_URL) { fun get(path: String, query: Map = emptyMap()): String? { val url = buildUrl(path, query) return try { - val conn = (URL(url).openConnection() as HttpURLConnection).apply { - requestMethod = "GET" - instanceFollowRedirects = true - connectTimeout = 20000 - readTimeout = 30000 - setRequestProperty("User-Agent", UA) - setRequestProperty("Accept", "application/json") - } - val code = conn.responseCode - if (code in 200..299) { - conn.inputStream.bufferedReader().use { it.readText() } - } else { - runCatching { conn.errorStream?.close() } - null + client.newCall(okhttp3.Request.Builder().url(url).header("User-Agent", UA) + .header("Accept", "application/json").build()).execute().use { response -> + if (response.isSuccessful) response.body?.string() else null } } catch (t: Throwable) { // Failure breadcrumb. Carry the message and the root cause: the exception type alone @@ -50,5 +37,11 @@ class ApisozoClient(private val baseUrl: String = BuildConfig.APISOZO_BASE_URL) companion object { private val UA get() = SOZO_USER_AGENT + private val client = okhttp3.OkHttpClient.Builder() + .dns(com.saikou.sozo_tv.engine.network.ExtensionDns.dns) + .connectTimeout(20, java.util.concurrent.TimeUnit.SECONDS) + .readTimeout(30, java.util.concurrent.TimeUnit.SECONDS) + .callTimeout(45, java.util.concurrent.TimeUnit.SECONDS) + .build() } } diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/server/MediaLanguages.kt b/app/src/main/java/com/saikou/sozo_tv/engine/server/MediaLanguages.kt new file mode 100644 index 00000000..4d39092a --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/engine/server/MediaLanguages.kt @@ -0,0 +1,70 @@ +package com.saikou.sozo_tv.engine.server + +import org.json.JSONArray +import org.json.JSONObject + +/** The audio languages a server provider offers per episode, and one payload holding them all. */ +internal object MediaLanguages { + + private val QUALITY = Regex("""(?i)(\d{3,4}p?|4k|hd|fhd|sd|auto)""") + + /** + * An episode's `availableLangs`: "sub" first, as the phone app does, then the provider's + * order. Some providers (uzmovi) list their servers' qualities there instead; those are + * left out, so such an episode is resolved once, as before. + */ + fun of(episode: JSONObject): List { + val arr = episode.optJSONArray("availableLangs") ?: return emptyList() + val langs = (0 until arr.length()).map { arr.optString(it).trim() } + .filter { it.isNotEmpty() && it != "null" && !QUALITY.matches(it) } + .distinct() + return langs.sortedBy { if (it.equals("sub", ignoreCase = true)) 0 else 1 } + } + + fun label(lang: String): String = when (lang.lowercase()) { + "sub" -> "Sub" + "dub" -> "Dub" + "softsub" -> "Softsub" + "hardsub" -> "Hardsub" + "raw" -> "Raw" + else -> lang + } + + /** + * One media payload holding every language's sources, each tagged with its language as the + * server name. [resolved] pairs a label with an already translated payload, first language + * first. That payload supplies the media-level fields, so its headers are copied onto each + * source: the player applies only the first payload's. + */ + fun merge(resolved: List>): String { + val base = JSONObject(resolved.first().second) + val sources = JSONArray() + val subtitles = JSONArray() + val subtitleFiles = mutableSetOf() + for ((index, entry) in resolved.withIndex()) { + val (label, payload) = entry + val media = JSONObject(payload) + val mediaHeaders = media.optJSONObject("headers") ?: JSONObject() + val srcs = media.optJSONArray("videoSources") ?: JSONArray() + for (i in 0 until srcs.length()) { + val s = srcs.optJSONObject(i) ?: continue + val headers = JSONObject(mediaHeaders.toString()) + s.optJSONObject("headers")?.let { own -> own.keys().forEach { headers.put(it, own.get(it)) } } + s.put("headers", headers) + s.put("host", label) + s.put("isDefault", index == 0 && s.optBoolean("isDefault", i == 0)) + sources.put(s) + } + val subs = media.optJSONArray("subtitles") ?: JSONArray() + for (i in 0 until subs.length()) { + val t = subs.optJSONObject(i) ?: continue + if (!subtitleFiles.add(t.optString("file"))) continue + // Only the first language's subtitles may switch themselves on; a dub must + // not start with another language's captions over it. + if (index > 0) t.put("default", false) + subtitles.put(t) + } + } + return base.put("videoSources", sources).put("subtitles", subtitles).toString() + } +} diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/server/ServerHost.kt b/app/src/main/java/com/saikou/sozo_tv/engine/server/ServerHost.kt index 9bd5c059..55196e45 100644 --- a/app/src/main/java/com/saikou/sozo_tv/engine/server/ServerHost.kt +++ b/app/src/main/java/com/saikou/sozo_tv/engine/server/ServerHost.kt @@ -2,6 +2,9 @@ package com.saikou.sozo_tv.engine.server import android.content.Context import com.saikou.sozo_tv.engine.webjs.WebJsRuntime +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.withTimeoutOrNull import org.json.JSONArray import org.json.JSONObject @@ -22,6 +25,16 @@ class ServerHost( // only, so a concurrent map is all the ordering this needs. private val meta = java.util.concurrent.ConcurrentHashMap() + /** + * The audio languages each episode offers (`availableLangs` from the episodes response), + * keyed by its mediaRef. loadLinks gets only the mediaRef, which a watch party also sends + * between devices, so the languages travel beside it rather than inside it. + */ + private val episodeLangs = object : LinkedHashMap>(64, 0.75f, true) { + override fun removeEldestEntry(eldest: MutableMap.MutableEntry>?) = + size > MAX_REMEMBERED_EPISODES + } + fun ensureLoaded() { if (meta.isEmpty()) runCatching { providersJson() } } @@ -231,18 +244,46 @@ class ServerHost( ensureMeta() val m = meta[b] android.util.Log.i("ServerHost", "loadLinks $b via ${if (usesJsResolve(m)) "JS(${m?.extractorName})" else "REST"}") - val soplay = if (usesJsResolve(m)) { + val langs = synchronized(episodeLangs) { episodeLangs[data] }.orEmpty() + if (langs.size < 2) return translateMedia(resolve(b, m, data, langs.firstOrNull() ?: "sub")) + + // A dub, or another voice, used to be unreachable: every episode was asked for "sub". + // Each language is resolved and offered as its own server, so the server picker is + // where the audio language is changed, and the pick is remembered like any server. + val picked = langs.take(MAX_LANGS) + val results = coroutineScope { + picked.mapIndexed { i, lang -> + async { + runCatching { + // The first language plays first; a slow extra one is dropped instead + // of holding the episode back. + if (i == 0) resolve(b, m, data, lang) + else withTimeoutOrNull(EXTRA_LANG_TIMEOUT_MS) { resolve(b, m, data, lang) } + } + } + }.map { it.await() } + } + val resolved = picked.indices.mapNotNull { i -> + results[i].getOrNull()?.let { MediaLanguages.label(picked[i]) to translateMedia(it) } + } + if (resolved.isEmpty()) { + results.firstNotNullOfOrNull { it.exceptionOrNull() }?.let { throw it } + return translateMedia(null) + } + return MediaLanguages.merge(resolved) + } + + private suspend fun resolve(b: String, m: Meta?, data: String, lang: String): String? = + if (usesJsResolve(m)) { webjs.callProvider( m!!.extractorName!!, m.extractorVersion, "resolveMedia", - JSONArray().put(data).put(JSONObject().put("lang", "sub")), + JSONArray().put(data).put(JSONObject().put("lang", lang)), ) } else { - client.get("/contents/media", mapOf("provider" to b, "ref" to data, "lang" to "sub")) + client.get("/contents/media", mapOf("provider" to b, "ref" to data, "lang" to lang)) } - return translateMedia(soplay) - } private fun usesJsCatalog(m: Meta?) = m?.scope == "all" && !m.extractorName.isNullOrEmpty() @@ -271,13 +312,11 @@ class ServerHost( val s = sectionsIn.optJSONObject(i) ?: continue val items = cards(s.optJSONArray("items"), bareProvider) if (items.length() == 0) continue - val va = s.optJSONObject("viewAll") - val type = va?.optString("type").orEmpty() - val slug = va?.optString("slug").orEmpty() + val viewAll = viewAllSlug(s.optJSONObject("viewAll")) sectionsOut.put(JSONObject().apply { put("key", s.optString("key")) put("label", s.optString("label")) - put("viewAll", JSONObject().put("slug", "$type::$slug")) + if (viewAll != null) put("viewAll", JSONObject().put("slug", viewAll)) put("items", items) }) } @@ -310,10 +349,20 @@ class ServerHost( val epsOut = JSONArray() for (i in 0 until epsIn.length()) { val e = epsIn.optJSONObject(i) ?: continue + val ref = str(e, "mediaRef") + val langs = MediaLanguages.of(e) + // A movie in more than one language is resolved per language from its own ref: + // the streams already in the response are only the first language's. + val direct = movieSources?.takeUnless { langs.size > 1 && ref.isNotEmpty() } + if (direct == null && ref.isNotEmpty()) { + synchronized(episodeLangs) { + if (langs.isNotEmpty()) episodeLangs[ref] = langs else episodeLangs.remove(ref) + } + } epsOut.put(JSONObject().apply { put("episode", e.optInt("episode", i + 1)) put("label", str(e, "label")) - put("mediaRef", movieSources ?: str(e, "mediaRef")) + put("mediaRef", direct ?: ref) put("image", str(e, "image")) put("overview", str(e, "overview")) put("airdate", str(e, "airdate")) @@ -362,7 +411,7 @@ class ServerHost( }.toString() } - private fun translateMedia(soplay: String?): String { + internal fun translateMedia(soplay: String?): String { val o = parseObject(soplay ?: return "{}") val srcIn = o.optJSONArray("videoSources") ?: JSONArray() val srcOut = JSONArray() @@ -380,6 +429,8 @@ class ServerHost( if (s.optBoolean("useLocalProxy", false)) put("useLocalProxy", true) s.optJSONObject("localProxy")?.let { put("localProxy", it) } s.optJSONObject("requestTransform")?.let { put("requestTransform", it) } + (s.opt("dropSegments") as? String)?.takeIf { it.isNotEmpty() }?.let { put("dropSegments", it) } + s.optJSONObject("signer")?.let { put("signer", it) } // Headless-WebView sniff directive (embed pages whose manifest is // only produced by the page's own JS) — forward raw, per source // or inherited from the media level. @@ -398,6 +449,8 @@ class ServerHost( put("label", firstNonEmpty(s, "label", "lang", "language") ?: "Subtitle") put("file", file) put("default", s.optBoolean("default", s.optBoolean("isDefault", false))) + s.optJSONObject("headers")?.let { put("headers", it) } + s.optJSONObject("cipher")?.let { put("cipher", it) } }) } return JSONObject().apply { @@ -478,5 +531,17 @@ class ServerHost( private companion object { const val EPISODE_PAGE_SIZE = 100 const val MAX_EPISODE_PAGES = 30 + const val MAX_REMEMBERED_EPISODES = 2000 + /** Some providers list a dozen voices; more than this would hold the episode up. */ + const val MAX_LANGS = 6 + const val EXTRA_LANG_TIMEOUT_MS = 20_000L } } + +/** A section without a viewAll target would page "/contents/" or getCategory(""), so it gets none. */ +internal fun viewAllSlug(viewAll: JSONObject?): String? { + if (viewAll == null) return null + val type = if (viewAll.isNull("type")) "" else viewAll.optString("type") + val slug = if (viewAll.isNull("slug")) "" else viewAll.optString("slug") + return if (type.isEmpty() && slug.isEmpty()) null else "$type::$slug" +} diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/torrent/TorrentEngine.kt b/app/src/main/java/com/saikou/sozo_tv/engine/torrent/TorrentEngine.kt new file mode 100644 index 00000000..0e2c0d0f --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/engine/torrent/TorrentEngine.kt @@ -0,0 +1,114 @@ +package com.saikou.sozo_tv.engine.torrent + +import android.content.Context +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.net.URLEncoder +import java.util.concurrent.TimeUnit +import torrServer.TorrServer + +/** Process-wide native server, with bounded disk cache and cancellable metadata waiting. */ +class TorrentEngine(context: Context) { + private val context = context.applicationContext + data class ResolvedTorrent(val url: String, val hash: String) + companion object { + private val startLock = Mutex() + @Volatile private var port = 0 + private val client = OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS) + .readTimeout(15, TimeUnit.SECONDS).callTimeout(20, TimeUnit.SECONDS).build() + } + + private suspend fun ensureStarted(): Int = startLock.withLock { + if (port > 0) return@withLock port + withContext(Dispatchers.IO) { + val dir = File(context.cacheDir, "torrent_tmp") + dir.deleteRecursively() + check(dir.mkdirs() || dir.isDirectory) { "Could not create torrent cache" } + go.Seq.load() + val started = TorrServer.startTorrentServer(dir.absolutePath, 0L).toInt() + check(started > 0) { "Torrent server did not start" } + port = started + // These are the same cache settings as mobile. Never stop Go via os.Exit. + runCatching { + val settings = post("settings", JSONObject().put("action", "get")) + settings.put("UseDisk", true).put("CacheSize", 128 * 1024 * 1024) + .put("PreloadCache", 12).put("ConnectionsLimit", 100) + .put("RemoveCacheOnDrop", true).put("TorrentsSavePath", dir.absolutePath) + post("settings", JSONObject().put("action", "set").put("sets", settings)) + } + started + } + } + + suspend fun resolve(link: String, episodeNumber: Int? = null): ResolvedTorrent = withContext(Dispatchers.IO) { + val localPort = ensureStarted() + val added = post("torrents", JSONObject().put("action", "add").put("link", link).put("save_to_db", false)) + val hash = added.optString("hash").also { check(it.isNotBlank()) { "Torrent server rejected the link" } } + try { + val file = withTimeout(60_000) { + var status = added + while (true) { + val files = TorrentFiles.parse(status.optJSONArray("file_stats")) + if ((status.optJSONArray("file_stats")?.length() ?: 0) > 0) return@withTimeout TorrentFiles.select(files, episodeNumber) + check(status.optInt("stat", -1) != 4) { "Torrent closed before metadata arrived" } + delay(700) + status = post("torrents", JSONObject().put("action", "get").put("hash", hash)) + } + @Suppress("UNREACHABLE_CODE") error("No torrent metadata") + } + val name = URLEncoder.encode(file.path.substringAfterLast('/'), "UTF-8").replace("+", "%20") + val encodedHash = URLEncoder.encode(hash, "UTF-8") + ResolvedTorrent("http://127.0.0.1:$localPort/stream/$name?link=$encodedHash&index=${file.id}&play", hash) + } catch (t: Throwable) { + withContext(kotlinx.coroutines.NonCancellable) { drop(hash) } + throw t + } + } + + suspend fun drop(hash: String) = withContext(Dispatchers.IO) { + if (port > 0) runCatching { post("torrents", JSONObject().put("action", "drop").put("hash", hash)) } + Unit + } + + private fun post(path: String, body: JSONObject): JSONObject { + val request = Request.Builder().url("http://127.0.0.1:$port/$path") + .post(body.toString().toRequestBody("application/json".toMediaType())).build() + return client.newCall(request).execute().use { response -> + check(response.isSuccessful) { "Torrent server returned HTTP ${response.code}" } + response.body?.string()?.takeIf { it.isNotBlank() }?.let(::JSONObject) ?: JSONObject() + } + } +} + +internal object TorrentFiles { + data class Entry(val id: Int, val path: String, val size: Long) + private val formats = setOf("mkv", "mp4", "avi", "webm", "mov", "m4v", "ts", "m2ts", "flv", "wmv", "ogv") + fun parse(arr: JSONArray?): List = (0 until (arr?.length() ?: 0)).mapNotNull { index -> + val value = arr?.optJSONObject(index) ?: return@mapNotNull null + val id = value.optInt("id", -1) + val path = value.optString("path") + if (id <= 0 || path.substringAfterLast('.', "").lowercase() !in formats) return@mapNotNull null + Entry(id, path, value.optLong("length")) + } + fun select(files: List, episodeNumber: Int?): Entry { + val candidates = files.filterNot { it.path.contains("sample", true) }.ifEmpty { files } + check(candidates.isNotEmpty()) { "This torrent contains no playable video" } + if (episodeNumber != null) { + val episode = Regex("(?i)(?:s\\d{1,2}e|episode[ ._-]*|\\be)0*${episodeNumber}(?!\\d)") + candidates.filter { episode.containsMatchIn(it.path) }.maxByOrNull { it.size }?.let { return it } + check(candidates.size == 1) { "This torrent contains several videos; no matching episode $episodeNumber was found" } + } + return candidates.maxBy { it.size } + } +} diff --git a/app/src/main/java/com/saikou/sozo_tv/engine/webjs/NativeFetch.kt b/app/src/main/java/com/saikou/sozo_tv/engine/webjs/NativeFetch.kt index 7fb84459..7b4331e6 100644 --- a/app/src/main/java/com/saikou/sozo_tv/engine/webjs/NativeFetch.kt +++ b/app/src/main/java/com/saikou/sozo_tv/engine/webjs/NativeFetch.kt @@ -25,6 +25,7 @@ class NativeFetch(context: Context) { private val cookieJar = AndroidCookieJar() private val client = OkHttpClient.Builder() + .dns(com.saikou.sozo_tv.engine.network.ExtensionDns.dns) .followRedirects(true) .followSslRedirects(true) .connectTimeout(20, TimeUnit.SECONDS) diff --git a/app/src/main/java/com/saikou/sozo_tv/parser/models/ShowResponse.kt b/app/src/main/java/com/saikou/sozo_tv/parser/models/ShowResponse.kt index 9adbd8a4..6ae80eb3 100644 --- a/app/src/main/java/com/saikou/sozo_tv/parser/models/ShowResponse.kt +++ b/app/src/main/java/com/saikou/sozo_tv/parser/models/ShowResponse.kt @@ -30,10 +30,14 @@ data class VideoOption( var useLocalProxy: Boolean = false, var localProxy: String? = null, var requestTransform: String? = null, + var dropSegments: String? = null, + var signer: String? = null, var useWebViewSniff: Boolean = false, var sniff: String? = null, /** Separate audio renditions merged into playback alongside [videoUrl]. */ var audioTracks: List = emptyList(), + val drm: String? = null, + val streamType: String? = null, ) diff --git a/app/src/main/java/com/saikou/sozo_tv/parser/sources/ExtensionParser.kt b/app/src/main/java/com/saikou/sozo_tv/parser/sources/ExtensionParser.kt index cbfc6b5d..3faaef11 100644 --- a/app/src/main/java/com/saikou/sozo_tv/parser/sources/ExtensionParser.kt +++ b/app/src/main/java/com/saikou/sozo_tv/parser/sources/ExtensionParser.kt @@ -32,6 +32,12 @@ class ExtensionParser : BaseParser() { override val name: String = "Extensions" + data class ContentKind(val isSeries: Boolean, val isAnime: Boolean) + private val contentKinds = object : LinkedHashMap(64, 0.75f, true) { + override fun removeEldestEntry(eldest: MutableMap.MutableEntry?): Boolean = size > 64 + } + fun contentKind(id: String): ContentKind? = synchronized(contentKinds) { contentKinds[id] } + private val engine get() = ExtensionEngine.shared private fun activeProvider(): String? = engine.getActiveProvider() @@ -59,6 +65,9 @@ class ExtensionParser : BaseParser() { val (encoded, url) = untag(id) val p = encoded ?: activeProvider() ?: return null val detail = engine.load(p, url) ?: return null + synchronized(contentKinds) { + contentKinds[id] = ContentKind(detail.isSerial, p.startsWith("an:") || detail.type?.contains("anime", true) == true) + } // Paged here, not by the source. The engine hands over the whole list — // a long-running series is a thousand episodes — and returning it as one // page meant the screen hid its part tabs (`last_page = 1`) and left the @@ -98,10 +107,12 @@ class ExtensionParser : BaseParser() { val (encoded, mediaRef) = untag(epId) val p = encoded ?: activeProvider() ?: return emptyList() val media = engine.loadLinks(p, mediaRef) - val tracks = media.subtitles.map { MegaTrack(it.file, it.label, "captions", it.headers) } + val tracks = media.subtitles.map { MegaTrack(it.file, it.label, "captions", it.headers, it.cipher) } return media.sources.map { s -> VideoOption( videoUrl = s.videoUrl, + drm = s.drm, + streamType = s.type, fansub = s.host ?: "", resolution = s.quality, audioType = AudioType.SUB, @@ -125,6 +136,8 @@ class ExtensionParser : BaseParser() { useLocalProxy = s.useLocalProxy, localProxy = s.localProxy, requestTransform = s.requestTransform, + dropSegments = s.dropSegments, + signer = s.signer, useWebViewSniff = s.useWebViewSniff, sniff = s.sniff, audioTracks = s.audioTracks.map { AudioTrackRef(it.url, media.headers + it.headers) }, diff --git a/app/src/main/java/com/saikou/sozo_tv/presentation/activities/DeviceLoginActivity.kt b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/DeviceLoginActivity.kt index 38d87444..ee7d567e 100644 --- a/app/src/main/java/com/saikou/sozo_tv/presentation/activities/DeviceLoginActivity.kt +++ b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/DeviceLoginActivity.kt @@ -44,7 +44,7 @@ class DeviceLoginActivity : AppCompatActivity() { super.onCreate(savedInstanceState) _binding = ActivityDeviceLoginBinding.inflate(layoutInflater) setContentView(binding.root) - AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) + AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) // A TV screensaver kicking in mid-pairing would strand the user on a dead code. window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) diff --git a/app/src/main/java/com/saikou/sozo_tv/presentation/activities/DownloadsActivity.kt b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/DownloadsActivity.kt new file mode 100644 index 00000000..0a9a09fa --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/DownloadsActivity.kt @@ -0,0 +1,157 @@ +package com.saikou.sozo_tv.presentation.activities + +import android.content.Intent +import android.graphics.Color +import android.os.Bundle +import android.view.Gravity +import android.view.View +import android.view.ViewGroup +import android.widget.LinearLayout +import android.widget.TextView +import android.widget.Toast +import androidx.appcompat.app.AlertDialog +import androidx.appcompat.app.AppCompatActivity +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle +import androidx.media3.common.util.UnstableApi +import androidx.media3.exoplayer.offline.Download +import androidx.recyclerview.widget.DiffUtil +import androidx.recyclerview.widget.ListAdapter +import androidx.recyclerview.widget.RecyclerView +import androidx.recyclerview.widget.LinearLayoutManager +import com.saikou.sozo_tv.R +import com.saikou.sozo_tv.engine.download.TvDownloads +import com.saikou.sozo_tv.utils.applyTvFocusScale +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import java.util.Locale + +/** Per-household offline library. Completed rows use the disk-only player. */ +@UnstableApi +class DownloadsActivity : AppCompatActivity() { + private val adapter = DownloadAdapter { row -> showActions(row) } + private val entries = mutableMapOf() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val layout = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + setPadding(dp(40), dp(24), dp(40), dp(24)) + setBackgroundColor(Color.rgb(20, 20, 20)) + } + val title = TextView(this).apply { + text = getString(R.string.tv_downloads_title) + textSize = 28f; setTextColor(Color.WHITE) + } + val back = TextView(this).apply { + text = getString(R.string.tv_downloads_back) + textSize = 18f; setTextColor(Color.WHITE) + setPadding(dp(12), dp(12), dp(12), dp(12)) + isFocusable = true; setBackgroundResource(R.drawable.background_button) + setOnClickListener { finish() } + } + val status = TextView(this).apply { + textSize = 16f; setTextColor(Color.LTGRAY) + setPadding(0, dp(12), 0, dp(12)) + } + val list = RecyclerView(this).apply { + layoutManager = LinearLayoutManager(this@DownloadsActivity) + adapter = this@DownloadsActivity.adapter + clipToPadding = false + itemAnimator = null + } + layout.addView(title); layout.addView(back); layout.addView(status) + layout.addView(list, LinearLayout.LayoutParams(-1, 0, 1f)) + setContentView(layout) + back.requestFocus() + lifecycleScope.launch { + repeatOnLifecycle(Lifecycle.State.STARTED) { + while (true) { + runCatching { TvDownloads.list(this@DownloadsActivity) }.onSuccess { downloads -> + entries.clear(); downloads.forEach { entries[it.request.id] = it } + status.text = if (downloads.isEmpty()) getString(R.string.tv_downloads_empty) + else getString(R.string.tv_downloads_count, downloads.size) + adapter.submitList(downloads.map { download -> + Row(download.request.id, TvDownloads.title(download), description(download), download.state) + }) + }.onFailure { status.text = it.message ?: getString(R.string.tv_downloads_failed) } + delay(1000) + } + } + } + } + + private fun description(download: Download): String { + val size = String.format(Locale.ROOT, "%.1f MB", download.bytesDownloaded / 1_048_576.0) + return when (download.state) { + Download.STATE_COMPLETED -> getString(R.string.tv_downloads_ready, size) + Download.STATE_FAILED -> getString(R.string.tv_downloads_failed) + Download.STATE_STOPPED -> getString(R.string.tv_downloads_paused, size) + Download.STATE_REMOVING -> getString(R.string.tv_downloads_removing) + Download.STATE_DOWNLOADING -> { + val percent = download.percentDownloaded + if (percent >= 0) "${percent.toInt()}% · $size" else size + } + else -> getString(R.string.tv_downloads_queued, size) + } + } + + private fun showActions(row: Row) { + val download = entries[row.id] ?: return + val actions = buildList Unit>> { + if (download.state == Download.STATE_COMPLETED) { + add(getString(R.string.tv_downloads_play) to { + startActivity(Intent(this@DownloadsActivity, OfflinePlayerActivity::class.java).putExtra("download_id", row.id)) + }) + } else if (download.state != Download.STATE_REMOVING) { + val resume = download.state == Download.STATE_STOPPED || download.state == Download.STATE_FAILED + add(getString(if (resume) R.string.tv_downloads_resume else R.string.tv_downloads_pause) to { + runAction { + if (download.state == Download.STATE_FAILED) TvDownloads.retry(this@DownloadsActivity, row.id) + else TvDownloads.pause(this@DownloadsActivity, row.id, !resume) + } + }) + } + add(getString(R.string.tv_downloads_delete) to { + AlertDialog.Builder(this@DownloadsActivity).setTitle(R.string.tv_downloads_delete) + .setMessage(row.title).setNegativeButton(android.R.string.cancel, null) + .setPositiveButton(R.string.tv_downloads_delete) { _, _ -> runAction { TvDownloads.remove(this@DownloadsActivity, row.id) } }.show() + }) + } + AlertDialog.Builder(this).setTitle(row.title) + .setItems(actions.map { it.first }.toTypedArray()) { _, index -> + runCatching { actions[index].second() }.onFailure { + Toast.makeText(this, it.message, Toast.LENGTH_LONG).show() + } + }.show() + } + + private fun runAction(action: suspend () -> Unit) { + lifecycleScope.launch { + runCatching { action() }.onFailure { Toast.makeText(this@DownloadsActivity, it.message, Toast.LENGTH_LONG).show() } + } + } + + private data class Row(val id: String, val title: String, val status: String, val state: Int) + private class DownloadAdapter(private val click: (Row) -> Unit) : ListAdapter(object : DiffUtil.ItemCallback() { + override fun areItemsTheSame(oldItem: Row, newItem: Row) = oldItem.id == newItem.id + override fun areContentsTheSame(oldItem: Row, newItem: Row) = oldItem == newItem + }) { + class Holder(val label: TextView) : RecyclerView.ViewHolder(label) + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder = Holder(TextView(parent.context).apply { + layoutParams = RecyclerView.LayoutParams(-1, -2).apply { bottomMargin = 12 } + isFocusable = true; isClickable = true + textSize = 18f; setTextColor(Color.WHITE) + setPadding(24, 20, 24, 20); minHeight = 96; gravity = Gravity.CENTER_VERTICAL + setBackgroundResource(R.drawable.background_button) + applyTvFocusScale(scale = 1.02f) + }) + override fun onBindViewHolder(holder: Holder, position: Int) { + val row = getItem(position) + holder.label.text = "${row.title}\n${row.status}" + holder.label.setOnClickListener { click(row) } + } + } + private fun dp(value: Int): Int = (resources.displayMetrics.density * value).toInt() +} diff --git a/app/src/main/java/com/saikou/sozo_tv/presentation/activities/LiveTvActivity.kt b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/LiveTvActivity.kt index df584349..ac4902a7 100644 --- a/app/src/main/java/com/saikou/sozo_tv/presentation/activities/LiveTvActivity.kt +++ b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/LiveTvActivity.kt @@ -45,7 +45,7 @@ class LiveTvActivity : AppCompatActivity() { binding = ActivityLiveTvBinding.inflate(layoutInflater) enableEdgeToEdge() setContentView(binding.root) - AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) + AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) val title = intent.getStringExtra("title") ?: "" val data = intent.getSerializableExtra("data") as Channel @@ -234,4 +234,4 @@ class LiveTvActivity : AppCompatActivity() { } -} \ No newline at end of file +} diff --git a/app/src/main/java/com/saikou/sozo_tv/presentation/activities/LoginActivity.kt b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/LoginActivity.kt index 07ebc70b..2703b802 100644 --- a/app/src/main/java/com/saikou/sozo_tv/presentation/activities/LoginActivity.kt +++ b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/LoginActivity.kt @@ -14,6 +14,6 @@ class LoginActivity : AppCompatActivity() { super.onCreate(savedInstanceState) viewBinding = ActivityLoginBinding.inflate(layoutInflater) setContentView(viewBinding.root) - AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) + AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) } -} \ No newline at end of file +} diff --git a/app/src/main/java/com/saikou/sozo_tv/presentation/activities/MainActivity.kt b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/MainActivity.kt index 12c6be70..4bc6136e 100644 --- a/app/src/main/java/com/saikou/sozo_tv/presentation/activities/MainActivity.kt +++ b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/MainActivity.kt @@ -28,6 +28,8 @@ import com.saikou.sozo_tv.data.extensions.ExtensionContentRegistry import com.saikou.sozo_tv.data.extensions.ExtensionEngine import com.saikou.sozo_tv.data.remote.remote.RemoteCommand import com.saikou.sozo_tv.data.repository.RemoteControlManager +import com.saikou.sozo_tv.data.repository.HouseholdProfileRepository +import com.saikou.sozo_tv.presentation.profiles.ProfileAvatarResources import kotlinx.coroutines.launch import org.koin.android.ext.android.inject import org.koin.androidx.viewmodel.ext.android.viewModel @@ -39,6 +41,7 @@ class MainActivity : AppCompatActivity() { private val model: SettingsViewModel by viewModel() private val remote: RemoteControlManager by inject() private val engine: ExtensionEngine by inject() + private val householdProfiles: HouseholdProfileRepository by inject() private var _binding: ActivityMainBinding? = null private var headerBinding: ContentHeaderMenuMainTvBinding? = null private val binding get() = _binding!! @@ -47,7 +50,7 @@ class MainActivity : AppCompatActivity() { super.onCreate(savedInstanceState) _binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) - AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) + AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) model.loadProfile() setupNavigation() setupBackBehaviour() @@ -245,13 +248,26 @@ class MainActivity : AppCompatActivity() { } private fun handleUserDataState(header: ContentHeaderMenuMainTvBinding) { - model.profileData.observe(this) { profile -> - header.tvNavigationHeaderTitle.text = profile.name - // A guest has no avatar, and loadImage() falls back to the 404 wallpaper for a blank - // URL — leave the tinted placeholder icon in place instead. - if (profile.avatarUrl.isNullOrBlank()) return@observe - ImageViewCompat.setImageTintList(header.ivNavigationHeaderIcon, null) - header.ivNavigationHeaderIcon.loadImage(profile.avatarUrl) + model.profileData.observe(this) { account -> + if (householdProfiles.state.value.active == null) { + header.tvNavigationHeaderTitle.text = account.name + if (!account.avatarUrl.isNullOrBlank()) { + ImageViewCompat.setImageTintList(header.ivNavigationHeaderIcon, null) + header.ivNavigationHeaderIcon.loadImage(account.avatarUrl) + } + } + } + lifecycleScope.launch { + repeatOnLifecycle(Lifecycle.State.STARTED) { + householdProfiles.state.collect { state -> + val profile = state.active ?: return@collect + header.tvNavigationHeaderTitle.text = profile.name + ProfileAvatarResources.drawable(profile.avatar)?.let { drawable -> + ImageViewCompat.setImageTintList(header.ivNavigationHeaderIcon, null) + header.ivNavigationHeaderIcon.setImageResource(drawable) + } + } + } } } @@ -279,4 +295,4 @@ class MainActivity : AppCompatActivity() { const val EXTRA_SEARCH_QUERY = "sozo.extra.SEARCH_QUERY" } -} \ No newline at end of file +} diff --git a/app/src/main/java/com/saikou/sozo_tv/presentation/activities/OfflinePlayerActivity.kt b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/OfflinePlayerActivity.kt new file mode 100644 index 00000000..cdb2363f --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/OfflinePlayerActivity.kt @@ -0,0 +1,76 @@ +package com.saikou.sozo_tv.presentation.activities + +import android.os.Bundle +import android.view.ViewGroup +import android.view.WindowManager +import android.widget.Toast +import androidx.appcompat.app.AppCompatActivity +import androidx.lifecycle.lifecycleScope +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 com.saikou.sozo_tv.components.PlayerTvView +import com.saikou.sozo_tv.engine.download.TvDownloads +import kotlinx.coroutines.launch +import kotlinx.coroutines.Job + +@UnstableApi +class OfflinePlayerActivity : AppCompatActivity() { + private var player: ExoPlayer? = null + private var view: PlayerTvView? = null + private var position = 0L + private var playWhenReady = true + private var loadJob: Job? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + position = savedInstanceState?.getLong("position") ?: 0L + window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + view = PlayerTvView(this).also { + setContentView(it, ViewGroup.LayoutParams(-1, -1)) + it.requestFocus() + } + } + + override fun onStart() { + super.onStart() + loadJob?.cancel() + loadJob = lifecycleScope.launch { + val ownerAtStart = TvDownloads.ownerToken() + val id = intent.getStringExtra("download_id") ?: return@launch finish() + val download = TvDownloads.list(this@OfflinePlayerActivity).firstOrNull { it.request.id == id && it.state == Download.STATE_COMPLETED } + if (download == null) { + Toast.makeText(this@OfflinePlayerActivity, "This download is not available in this profile.", Toast.LENGTH_LONG).show() + finish(); return@launch + } + if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.STARTED) || TvDownloads.ownerToken() != ownerAtStart) return@launch + player = ExoPlayer.Builder(this@OfflinePlayerActivity).build().also { p -> + view?.player = p + p.addListener(object : Player.Listener { + override fun onPlayerError(error: PlaybackException) { + Toast.makeText(this@OfflinePlayerActivity, "Offline playback failed: ${error.errorCodeName}", Toast.LENGTH_LONG).show() + } + }) + p.setMediaSource(DownloadHelper.createMediaSource(download.request, + TvDownloads.offlineFactory(this@OfflinePlayerActivity, id))) + p.seekTo(position); p.prepare(); p.playWhenReady = playWhenReady + } + } + } + + override fun onStop() { + loadJob?.cancel() + loadJob = null + player?.let { position = it.currentPosition; playWhenReady = it.playWhenReady; it.release() } + player = null; view?.player = null + super.onStop() + } + + override fun onSaveInstanceState(outState: Bundle) { + outState.putLong("position", player?.currentPosition ?: position) + super.onSaveInstanceState(outState) + } +} diff --git a/app/src/main/java/com/saikou/sozo_tv/presentation/activities/PlayerActivity.kt b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/PlayerActivity.kt index 1d2fb7ac..068cde62 100644 --- a/app/src/main/java/com/saikou/sozo_tv/presentation/activities/PlayerActivity.kt +++ b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/PlayerActivity.kt @@ -23,7 +23,7 @@ class PlayerActivity : AppCompatActivity() { enableEdgeToEdge() binding = ActivityPlayerBinding.inflate(layoutInflater) setContentView(binding.root) - AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) + AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) val navController = (supportFragmentManager.findFragmentById(R.id.nav_main_fragment) as NavHostFragment).navController categoryDetails = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { @@ -82,4 +82,4 @@ class PlayerActivity : AppCompatActivity() { } -} \ No newline at end of file +} diff --git a/app/src/main/java/com/saikou/sozo_tv/presentation/activities/ProfileActivity.kt b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/ProfileActivity.kt index e1b40ad9..152076c1 100644 --- a/app/src/main/java/com/saikou/sozo_tv/presentation/activities/ProfileActivity.kt +++ b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/ProfileActivity.kt @@ -44,7 +44,7 @@ class ProfileActivity : AppCompatActivity(), MyAccountPage.AuthNavigator { super.onCreate(savedInstanceState) viewBinding = ActivityProfileBinding.inflate(layoutInflater) setContentView(viewBinding.root) - AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) + AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) model.loadProfile() // Deliberately NOT `navProfile.isFocusedByDefault = true`. This screen is a @@ -164,6 +164,9 @@ class ProfileActivity : AppCompatActivity(), MyAccountPage.AuthNavigator { recyclerView = viewBinding.profileRv, isSignedIn = isSignedIn ).also { viewBinding.profileRv.adapter = it } + profileAdapter.setOnAccountClickListener { + startActivity(Intent(this, ProfilePickerActivity::class.java)) + } // One placement, not two. Each branch used to run this AND an inline // `profileRv.post { ... }` doing the same thing, and the inline copy read @@ -273,4 +276,4 @@ class ProfileActivity : AppCompatActivity(), MyAccountPage.AuthNavigator { val intent = Intent(this, DeviceLoginActivity::class.java) startActivity(intent) } -} \ No newline at end of file +} diff --git a/app/src/main/java/com/saikou/sozo_tv/presentation/activities/ProfileEditorActivity.kt b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/ProfileEditorActivity.kt new file mode 100644 index 00000000..070f678e --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/ProfileEditorActivity.kt @@ -0,0 +1,101 @@ +package com.saikou.sozo_tv.presentation.activities + +import android.os.Bundle +import android.view.View +import android.widget.Toast +import androidx.appcompat.app.AlertDialog +import androidx.appcompat.app.AppCompatActivity +import androidx.lifecycle.lifecycleScope +import androidx.recyclerview.widget.GridLayoutManager +import com.saikou.sozo_tv.R +import com.saikou.sozo_tv.data.repository.HouseholdProfileRepository +import com.saikou.sozo_tv.databinding.ActivityProfileEditorBinding +import com.saikou.sozo_tv.presentation.profiles.AvatarChoiceAdapter +import com.saikou.sozo_tv.presentation.profiles.ProfileAvatarResources +import kotlinx.coroutines.launch +import org.koin.android.ext.android.inject + +class ProfileEditorActivity : AppCompatActivity() { + private lateinit var binding: ActivityProfileEditorBinding + private val profiles: HouseholdProfileRepository by inject() + private var profileId: String? = null + private var avatar: String = ProfileAvatarResources.selectableIds.first() + private var saving = false + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = ActivityProfileEditorBinding.inflate(layoutInflater) + setContentView(binding.root) + profileId = intent.getStringExtra(EXTRA_PROFILE_ID) + val original = profiles.state.value.profiles.firstOrNull { it.id == profileId } + avatar = original?.avatar?.takeIf { ProfileAvatarResources.drawable(it) != null } + ?: ProfileAvatarResources.selectableIds.first() + binding.title.setText(if (original == null) R.string.profile_create_title else R.string.profile_edit_title) + binding.name.text = original?.name.orEmpty() + binding.kids.isChecked = original?.isKids == true + binding.delete.visibility = if (original != null && !original.isDefault) View.VISIBLE else View.GONE + binding.avatars.layoutManager = GridLayoutManager(this, 6) + binding.avatars.adapter = AvatarChoiceAdapter(avatar) { avatar = it } + bindKeyboard() + binding.save.setOnClickListener { save() } + binding.delete.setOnClickListener { confirmDelete() } + binding.avatars.post { + binding.avatars.findViewHolderForAdapterPosition( + ProfileAvatarResources.selectableIds.indexOf(avatar).coerceAtLeast(0) + )?.itemView?.requestFocus() + } + } + + private fun bindKeyboard() = with(binding.keyboard) { + setOnKeyClickListener { if (binding.name.text.length < 30) binding.name.append(it) } + setOnBackspaceClickListener { + if (binding.name.text.isNotEmpty()) binding.name.text = binding.name.text.dropLast(1) + } + setOnClearClickListener { binding.name.text = "" } + } + + private fun save() { + val name = binding.name.text.toString().trim() + if (name.isBlank()) { + Toast.makeText(this, R.string.profile_name_required, Toast.LENGTH_SHORT).show() + return + } + if (saving) return + saving = true + binding.save.isEnabled = false + lifecycleScope.launch { + val id = profileId + val ok = if (id == null) { + profiles.create(name, avatar, null, binding.kids.isChecked) + } else { + profiles.update(id, mapOf( + "name" to name, + "avatar" to avatar, + "isKids" to binding.kids.isChecked, + )) + } + if (ok) finish() else { + saving = false + binding.save.isEnabled = true + Toast.makeText(this@ProfileEditorActivity, profiles.state.value.error, Toast.LENGTH_LONG).show() + } + } + } + + private fun confirmDelete() { + val id = profileId ?: return + AlertDialog.Builder(this) + .setMessage(R.string.profile_delete_confirm) + .setNegativeButton(android.R.string.cancel, null) + .setPositiveButton(R.string.profile_delete) { _, _ -> + lifecycleScope.launch { + if (profiles.delete(id)) finish() + else Toast.makeText(this@ProfileEditorActivity, profiles.state.value.error, Toast.LENGTH_LONG).show() + } + }.show() + } + + companion object { + const val EXTRA_PROFILE_ID = "sozo.extra.PROFILE_ID" + } +} diff --git a/app/src/main/java/com/saikou/sozo_tv/presentation/activities/ProfilePickerActivity.kt b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/ProfilePickerActivity.kt new file mode 100644 index 00000000..847a9678 --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/ProfilePickerActivity.kt @@ -0,0 +1,97 @@ +package com.saikou.sozo_tv.presentation.activities + +import android.content.Intent +import android.os.Bundle +import android.view.View +import androidx.appcompat.app.AppCompatActivity +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle +import androidx.recyclerview.widget.LinearLayoutManager +import com.saikou.sozo_tv.data.repository.DeviceAuthRepository +import com.saikou.sozo_tv.data.repository.HouseholdProfileRepository +import com.saikou.sozo_tv.databinding.ActivityProfilePickerBinding +import com.saikou.sozo_tv.domain.model.HouseholdProfile +import com.saikou.sozo_tv.presentation.profiles.HouseholdProfileAdapter +import kotlinx.coroutines.launch +import org.koin.android.ext.android.inject + +class ProfilePickerActivity : AppCompatActivity() { + private lateinit var binding: ActivityProfilePickerBinding + private val profiles: HouseholdProfileRepository by inject() + private val auth: DeviceAuthRepository by inject() + private lateinit var adapter: HouseholdProfileAdapter + private var startup = false + private var manageMode = false + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = ActivityProfilePickerBinding.inflate(layoutInflater) + setContentView(binding.root) + startup = intent.getBooleanExtra(EXTRA_STARTUP, false) + adapter = HouseholdProfileAdapter { profile -> + if (manageMode) openEditor(profile.id) else activate(profile) + } + binding.profiles.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) + binding.profiles.adapter = adapter + binding.addProfile.setOnClickListener { openEditor(null) } + binding.manageProfiles.setOnClickListener { toggleManageMode() } + + lifecycleScope.launch { + repeatOnLifecycle(Lifecycle.State.STARTED) { + profiles.state.collect { state -> + adapter.submit(state.profiles) + binding.loading.visibility = if (state.loading) View.VISIBLE else View.GONE + binding.error.visibility = if (state.error == null) View.GONE else View.VISIBLE + binding.error.text = state.error + val canManage = state.active?.isKids != true + binding.addProfile.visibility = if (canManage && state.profiles.size < state.max) View.VISIBLE else View.GONE + binding.manageProfiles.visibility = if (canManage && state.profiles.isNotEmpty()) View.VISIBLE else View.GONE + if (state.profiles.isNotEmpty()) binding.profiles.post { + if (!binding.profiles.hasFocus()) binding.profiles.findViewHolderForAdapterPosition(0)?.itemView?.requestFocus() + } + } + } + } + lifecycleScope.launch { + if (!auth.isSignedIn()) return@launch enterApp() + val ok = profiles.refresh() + val list = profiles.state.value.profiles + if (startup && (list.size <= 1 || !ok && list.isEmpty())) { + list.firstOrNull()?.let(profiles::activate) + enterApp() + } + } + } + + private fun activate(profile: HouseholdProfile) { + profiles.activate(profile) + enterApp() + } + + private fun openEditor(id: String?) { + startActivity(Intent(this, ProfileEditorActivity::class.java).apply { + putExtra(ProfileEditorActivity.EXTRA_PROFILE_ID, id) + }) + } + + private fun toggleManageMode() { + manageMode = !manageMode + binding.manageProfiles.setText( + if (manageMode) com.saikou.sozo_tv.R.string.profile_done + else com.saikou.sozo_tv.R.string.profile_manage + ) + binding.profiles.announceForAccessibility(binding.manageProfiles.text) + } + + private fun enterApp() { + startActivity(Intent(this, MainActivity::class.java).apply { + flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK + }) + finish() + } + + companion object { + const val EXTRA_STARTUP = "sozo.extra.PROFILE_STARTUP" + } +} diff --git a/app/src/main/java/com/saikou/sozo_tv/presentation/activities/UpdateActivity.kt b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/UpdateActivity.kt index ff07a89a..4ae79a93 100644 --- a/app/src/main/java/com/saikou/sozo_tv/presentation/activities/UpdateActivity.kt +++ b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/UpdateActivity.kt @@ -87,7 +87,7 @@ class UpdateActivity : AppCompatActivity() { super.onCreate(savedInstanceState) binding = ActivityUpdateBinding.inflate(layoutInflater) setContentView(binding.root) - AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) + AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) binding.progressView1.apply { min = PV_MIN max = PV_MAX diff --git a/app/src/main/java/com/saikou/sozo_tv/presentation/activities/WatchPartyActivity.kt b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/WatchPartyActivity.kt new file mode 100644 index 00000000..c549dfb7 --- /dev/null +++ b/app/src/main/java/com/saikou/sozo_tv/presentation/activities/WatchPartyActivity.kt @@ -0,0 +1,300 @@ +package com.saikou.sozo_tv.presentation.activities + +import android.graphics.Color +import android.os.Bundle +import android.os.SystemClock +import android.view.Gravity +import android.view.View +import android.view.WindowManager +import android.widget.* +import androidx.appcompat.app.AppCompatActivity +import androidx.lifecycle.lifecycleScope +import androidx.media3.common.* +import androidx.media3.exoplayer.ExoPlayer +import androidx.media3.exoplayer.source.DefaultMediaSourceFactory +import androidx.media3.ui.PlayerView +import com.saikou.sozo_tv.data.extensions.* +import com.saikou.sozo_tv.data.local.pref.ActiveProfileStore +import com.saikou.sozo_tv.data.local.pref.DeviceSessionStore +import com.saikou.sozo_tv.data.remote.party.* +import com.saikou.sozo_tv.data.repository.DeviceAuthRepository +import com.saikou.sozo_tv.engine.player.* +import com.saikou.sozo_tv.engine.torrent.TorrentEngine +import kotlinx.coroutines.* +import okhttp3.OkHttpClient +import org.json.JSONObject +import org.koin.android.ext.android.get +import org.koin.core.qualifier.named +import kotlin.math.abs + +/** A room resolves identity independently on this TV; no signed stream URL leaves the device. */ +@androidx.media3.common.util.UnstableApi +class WatchPartyActivity : AppCompatActivity() { + private lateinit var status: TextView + private lateinit var roomTitle: TextView + private lateinit var chatLine: TextView + private lateinit var lobby: LinearLayout + private lateinit var roomControls: LinearLayout + private lateinit var playerView: PlayerView + private lateinit var client: WatchPartyClient + private lateinit var player: ExoPlayer + private val streamHttp by lazy { StreamHttp(this) } + private val proxy by lazy { LocalHlsProxy(streamHttp.proxyClient) } + private val torrent by lazy { TorrentEngine(this) } + private var torrentHash: String? = null + private var room = JSONObject() + private var contentKey = "" + private var sourceIndex = 0 + private var sources: List = emptyList() + private var media: ExtMedia? = null + private var playback = PartyPlayback(0, false, 1f, 0) + private var resolveJob: Job? = null + private var heartbeat: Job? = null + private var generation = 0 + private var stopped = false + private var incomingContent: JSONObject? = null + private var sentIncoming = false + private val controlButtons = mutableListOf