diff --git a/.github/locales.py b/.github/locales.py
index 6127d9d80..a74d72588 100644
--- a/.github/locales.py
+++ b/.github/locales.py
@@ -1,13 +1,14 @@
import re
import glob
import requests
+import os
import lxml.etree as ET # builtin library doesn't preserve comments
SETTINGS_PATH = "app/src/main/java/com/lagradost/cloudstream3/ui/settings/SettingsGeneral.kt"
START_MARKER = "/* begin language list */"
END_MARKER = "/* end language list */"
-XML_NAME = "app/src/main/res/values-b+"
+XML_NAME = "app/src/main/res/values-"
ISO_MAP_URL = "https://raw.githubusercontent.com/haliaeetus/iso-639/master/data/iso_639-1.min.json"
INDENT = " "*4
@@ -20,29 +21,29 @@ rest, after_src = rest.split(END_MARKER)
# Load already added langs
languages = {}
-for lang in re.finditer(r'Pair\("(.*)", "(.*)"\)', rest):
- name, iso = lang.groups()
- languages[iso] = name
+for lang in re.finditer(r'Triple\("(.*)", "(.*)", "(.*)"\)', rest):
+ flag, name, iso = lang.groups()
+ languages[iso] = (flag, name)
# Add not yet added langs
for folder in glob.glob(f"{XML_NAME}*"):
- iso = folder[len(XML_NAME):].replace("+", "-")
+ iso = folder[len(XML_NAME):]
if iso not in languages.keys():
- entry = iso_map.get(iso.lower(), {'nativeName':iso}) # fallback to iso code if not found
- languages[iso] = entry['nativeName'].split(',')[0] # first name if there are multiple
+ entry = iso_map.get(iso.lower(),{'nativeName':iso})
+ languages[iso] = ("", entry['nativeName'].split(',')[0])
-# Create pairs
-pairs = []
-for iso in sorted(languages, key=lambda iso: languages[iso].lower()): # sort by language name
- name = languages[iso]
- pairs.append(f'{INDENT}Pair("{name}", "{iso}"),')
+# Create triples
+triples = []
+for iso in sorted(languages.keys()):
+ flag, name = languages[iso]
+ triples.append(f'{INDENT}Triple("{flag}", "{name}", "{iso}"),')
# Update settings file
open(SETTINGS_PATH, "w+",encoding='utf-8').write(
before_src +
START_MARKER +
"\n" +
- "\n".join(pairs) +
+ "\n".join(triples) +
"\n" +
END_MARKER +
after_src
@@ -61,5 +62,8 @@ for file in glob.glob(f"{XML_NAME}*/strings.xml"):
with open(file, 'wb') as fp:
fp.write(b'\n')
tree.write(fp, encoding="utf-8", method="xml", pretty_print=True, xml_declaration=False)
+ # Remove trailing new line to be consistent with weblate
+ fp.seek(-1, os.SEEK_END)
+ fp.truncate()
except ET.ParseError as ex:
print(f"[{file}] {ex}")
diff --git a/.github/workflows/build_to_archive.yml b/.github/workflows/build_to_archive.yml
index 056022d22..e84bb08b0 100644
--- a/.github/workflows/build_to_archive.yml
+++ b/.github/workflows/build_to_archive.yml
@@ -1,95 +1,78 @@
-name: Archive build
-
-on:
- push:
- branches: [ master ]
- paths-ignore:
- - '*.md'
- - '*.json'
- - '**/wcokey.txt'
- workflow_dispatch:
-
-permissions:
- contents: read
-
-concurrency:
- group: "Archive-build"
- cancel-in-progress: true
-
-jobs:
- build:
- runs-on: ubuntu-latest
- steps:
- - name: Generate access token
- id: generate_token
- uses: tibdex/github-app-token@v2
- with:
- app_id: ${{ secrets.GH_APP_ID }}
- private_key: ${{ secrets.GH_APP_KEY }}
- repository: "recloudstream/secrets"
-
- - name: Generate access token (archive)
- id: generate_archive_token
- uses: tibdex/github-app-token@v2
- with:
- app_id: ${{ secrets.GH_APP_ID }}
- private_key: ${{ secrets.GH_APP_KEY }}
- repository: "recloudstream/cloudstream-archive"
-
- - uses: actions/checkout@v6
-
- - name: Set up JDK 17
- uses: actions/setup-java@v5
- with:
- distribution: temurin
- java-version: 17
-
- - name: Grant execute permission for gradlew
- run: chmod +x gradlew
-
- - name: Fetch keystore
- id: fetch_keystore
- run: |
- TMP_KEYSTORE_FILE_PATH="${RUNNER_TEMP}"/keystore
- mkdir -p "${TMP_KEYSTORE_FILE_PATH}"
- curl -H "Authorization: token ${{ steps.generate_token.outputs.token }}" -o "${TMP_KEYSTORE_FILE_PATH}/prerelease_keystore.keystore" "https://raw.githubusercontent.com/recloudstream/secrets/master/keystore.jks"
- curl -H "Authorization: token ${{ steps.generate_token.outputs.token }}" -o "keystore_password.txt" "https://raw.githubusercontent.com/recloudstream/secrets/master/keystore_password.txt"
- KEY_PWD="$(cat keystore_password.txt)"
- echo "::add-mask::${KEY_PWD}"
- echo "key_pwd=$KEY_PWD" >> $GITHUB_OUTPUT
-
- - name: Setup Gradle
- uses: gradle/actions/setup-gradle@v5
- with:
- cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
-
- - name: Run Gradle
- run: ./gradlew assemblePrereleaseRelease
- env:
- SIGNING_KEY_ALIAS: "key0"
- SIGNING_KEY_PASSWORD: ${{ steps.fetch_keystore.outputs.key_pwd }}
- SIGNING_STORE_PASSWORD: ${{ steps.fetch_keystore.outputs.key_pwd }}
- SIMKL_CLIENT_ID: ${{ secrets.SIMKL_CLIENT_ID }}
- SIMKL_CLIENT_SECRET: ${{ secrets.SIMKL_CLIENT_SECRET }}
- TRAKT_CLIENT_ID: ${{ secrets.TRAKT_CLIENT_ID }}
- MDL_API_KEY: ${{ secrets.MDL_API_KEY }}
- MAL_KEY: ${{ secrets.MAL_KEY }}
- ANILIST_KEY: ${{ secrets.ANILIST_KEY }}
-
- - uses: actions/checkout@v6
- with:
- repository: "recloudstream/cloudstream-archive"
- token: ${{ steps.generate_archive_token.outputs.token }}
- path: "archive"
-
- - name: Move build
- run: cp app/build/outputs/apk/prerelease/release/*.apk "archive/$(git rev-parse --short HEAD).apk"
-
- - name: Push archive
- run: |
- cd $GITHUB_WORKSPACE/archive
- git config --local user.email "actions@github.com"
- git config --local user.name "GitHub Actions"
- git add .
- git commit --amend -m "Build $GITHUB_SHA" || exit 0 # do not error if nothing to commit
- git push --force
+name: Archive build
+
+on:
+ push:
+ branches: [ master ]
+ paths-ignore:
+ - '*.md'
+ - '*.json'
+ - '**/wcokey.txt'
+ workflow_dispatch:
+
+concurrency:
+ group: "Archive-build"
+ cancel-in-progress: true
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Generate access token
+ id: generate_token
+ uses: tibdex/github-app-token@v2
+ with:
+ app_id: ${{ secrets.GH_APP_ID }}
+ private_key: ${{ secrets.GH_APP_KEY }}
+ repository: "recloudstream/secrets"
+ - name: Generate access token (archive)
+ id: generate_archive_token
+ uses: tibdex/github-app-token@v2
+ with:
+ app_id: ${{ secrets.GH_APP_ID }}
+ private_key: ${{ secrets.GH_APP_KEY }}
+ repository: "recloudstream/cloudstream-archive"
+ - uses: actions/checkout@v4
+ - name: Set up JDK 17
+ uses: actions/setup-java@v4
+ with:
+ java-version: '17'
+ distribution: 'adopt'
+ - name: Grant execute permission for gradlew
+ run: chmod +x gradlew
+ - name: Fetch keystore
+ id: fetch_keystore
+ run: |
+ TMP_KEYSTORE_FILE_PATH="${RUNNER_TEMP}"/keystore
+ mkdir -p "${TMP_KEYSTORE_FILE_PATH}"
+ curl -H "Authorization: token ${{ steps.generate_token.outputs.token }}" -o "${TMP_KEYSTORE_FILE_PATH}/prerelease_keystore.keystore" "https://raw.githubusercontent.com/recloudstream/secrets/master/keystore.jks"
+ curl -H "Authorization: token ${{ steps.generate_token.outputs.token }}" -o "keystore_password.txt" "https://raw.githubusercontent.com/recloudstream/secrets/master/keystore_password.txt"
+ KEY_PWD="$(cat keystore_password.txt)"
+ echo "::add-mask::${KEY_PWD}"
+ echo "key_pwd=$KEY_PWD" >> $GITHUB_OUTPUT
+ - name: Run Gradle
+ run: |
+ ./gradlew assemblePrerelease
+ env:
+ SIGNING_KEY_ALIAS: "key0"
+ SIGNING_KEY_PASSWORD: ${{ steps.fetch_keystore.outputs.key_pwd }}
+ SIGNING_STORE_PASSWORD: ${{ steps.fetch_keystore.outputs.key_pwd }}
+ SIMKL_CLIENT_ID: ${{ secrets.SIMKL_CLIENT_ID }}
+ SIMKL_CLIENT_SECRET: ${{ secrets.SIMKL_CLIENT_SECRET }}
+ - uses: actions/checkout@v4
+ with:
+ repository: "recloudstream/cloudstream-archive"
+ token: ${{ steps.generate_archive_token.outputs.token }}
+ path: "archive"
+
+ - name: Move build
+ run: |
+ cp app/build/outputs/apk/prerelease/release/*.apk "archive/$(git rev-parse --short HEAD).apk"
+
+ - name: Push archive
+ run: |
+ cd $GITHUB_WORKSPACE/archive
+ git config --local user.email "actions@github.com"
+ git config --local user.name "GitHub Actions"
+ git add .
+ git commit --amend -m "Build $GITHUB_SHA" || exit 0 # do not error if nothing to commit
+ git push --force
\ No newline at end of file
diff --git a/.github/workflows/generate_dokka.yml b/.github/workflows/generate_dokka.yml
index d67b8a519..666e2ba10 100644
--- a/.github/workflows/generate_dokka.yml
+++ b/.github/workflows/generate_dokka.yml
@@ -1,18 +1,19 @@
name: Dokka
+# https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#concurrency
+concurrency:
+ group: "dokka"
+ cancel-in-progress: true
+
on:
push:
- branches: [ master ]
+ branches:
+ # choose your default branch
+ - master
+ - main
paths-ignore:
- '*.md'
-permissions:
- contents: read
-
-concurrency:
- group: "dokka"
- cancel-in-progress: true
-
jobs:
build:
runs-on: ubuntu-latest
@@ -24,35 +25,32 @@ jobs:
app_id: ${{ secrets.GH_APP_ID }}
private_key: ${{ secrets.GH_APP_KEY }}
repository: "recloudstream/dokka"
-
- name: Checkout
- uses: actions/checkout@v6
+ uses: actions/checkout@master
with:
path: "src"
- name: Checkout dokka
- uses: actions/checkout@v6
+ uses: actions/checkout@master
with:
repository: "recloudstream/dokka"
path: "dokka"
token: ${{ steps.generate_token.outputs.token }}
-
+
- name: Clean old builds
run: |
cd $GITHUB_WORKSPACE/dokka/
rm -rf "./app"
rm -rf "./library"
- - name: Set up JDK 17
- uses: actions/setup-java@v5
+ - name: Setup JDK 17
+ uses: actions/setup-java@v4
with:
- distribution: temurin
java-version: 17
+ distribution: 'adopt'
- - name: Setup Gradle
- uses: gradle/actions/setup-gradle@v5
- with:
- cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
+ - name: Setup Android SDK
+ uses: android-actions/setup-android@v3
- name: Generate Dokka
run: |
@@ -61,7 +59,8 @@ jobs:
./gradlew docs:dokkaGeneratePublicationHtml
- name: Copy Dokka
- run: cp -r $GITHUB_WORKSPACE/src/docs/build/dokka/html/* $GITHUB_WORKSPACE/dokka/
+ run: |
+ cp -r $GITHUB_WORKSPACE/src/docs/build/dokka/html/* $GITHUB_WORKSPACE/dokka/
- name: Push builds
run: |
diff --git a/.github/workflows/instrumented-tests.yml b/.github/workflows/instrumented-tests.yml
deleted file mode 100644
index 34c6eaf0b..000000000
--- a/.github/workflows/instrumented-tests.yml
+++ /dev/null
@@ -1,105 +0,0 @@
-name: Instrumented Tests
-
-on:
- issue_comment:
- types: [created]
-
-permissions:
- contents: read
- pull-requests: write
-
-jobs:
- instrumented-tests:
- runs-on: ubuntu-latest
- if: |
- github.event.issue.pull_request &&
- github.event.comment.body == '/run-tests'
- steps:
- - name: Check permission
- uses: actions/github-script@v9
- with:
- script: |
- const login = context.payload.comment.user.login;
- const association = context.payload.comment.author_association;
- const allowed = ['OWNER', 'MEMBER'];
-
- const isAllowed =
- login === 'Luna712' ||
- allowed.includes(association);
-
- if (!isAllowed) {
- core.setFailed(`User ${login} is not permitted to trigger this workflow.`);
- }
-
- - uses: actions/checkout@v6
- with:
- ref: refs/pull/${{ github.event.issue.number }}/head
-
- - name: Post started comment
- uses: actions/github-script@v9
- with:
- script: |
- github.rest.issues.createComment({
- issue_number: context.issue.number,
- owner: context.repo.owner,
- repo: context.repo.repo,
- body: 'Instrumented tests are running. [View live progress](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})'
- })
-
- - name: Set up JDK 17
- uses: actions/setup-java@v5
- with:
- distribution: temurin
- java-version: 17
-
- - name: Grant execute permission for gradlew
- run: chmod +x gradlew
-
- - name: Setup Gradle
- uses: gradle/actions/setup-gradle@v5
- with:
- cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
- cache-read-only: false
-
- - name: Get target SDK
- id: sdk
- run: |
- TARGET_SDK=$(grep 'targetSdk' gradle/libs.versions.toml | grep -o '[0-9]\+' | head -1)
- echo "version=$TARGET_SDK" >> $GITHUB_OUTPUT
-
- - name: Enable KVM
- run: |
- echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
- sudo udevadm control --reload-rules
- sudo udevadm trigger --name-match=kvm
-
- - name: Run Instrumented Tests
- id: tests
- uses: reactivecircus/android-emulator-runner@v2
- with:
- api-level: ${{ steps.sdk.outputs.version }}
- arch: x86_64
- profile: Nexus 6
- script: ./gradlew connectedPrereleaseDebugAndroidTest
-
- - name: Upload Test Results
- if: always()
- uses: actions/upload-artifact@v7
- with:
- name: instrumented-test-results
- path: '**/build/reports/androidTests/'
-
- - name: Post finished comment
- if: always()
- uses: actions/github-script@v9
- with:
- script: |
- const success = '${{ steps.tests.outcome }}' === 'success';
- github.rest.issues.createComment({
- issue_number: context.issue.number,
- owner: context.repo.owner,
- repo: context.repo.repo,
- body: success
- ? 'Instrumented tests passed. [View results](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})'
- : 'Instrumented tests failed. [View results](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})'
- })
diff --git a/.github/workflows/issue_action.yml b/.github/workflows/issue_action.yml
new file mode 100644
index 000000000..88ab3656c
--- /dev/null
+++ b/.github/workflows/issue_action.yml
@@ -0,0 +1,88 @@
+name: Issue automatic actions
+
+on:
+ issues:
+ types: [opened]
+
+jobs:
+ issue-moderator:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Generate access token
+ id: generate_token
+ uses: tibdex/github-app-token@v2
+ with:
+ app_id: ${{ secrets.GH_APP_ID }}
+ private_key: ${{ secrets.GH_APP_KEY }}
+ - name: Similarity analysis
+ id: similarity
+ uses: actions-cool/issues-similarity-analysis@v1
+ with:
+ token: ${{ steps.generate_token.outputs.token }}
+ filter-threshold: 0.60
+ title-excludes: ''
+ comment-title: |
+ ### Your issue looks similar to these issues:
+ Please close if duplicate.
+ comment-body: '${index}. ${similarity} #${number}'
+ - name: Label if possible duplicate
+ if: steps.similarity.outputs.similar-issues-found =='true'
+ uses: actions/github-script@v7
+ with:
+ github-token: ${{ steps.generate_token.outputs.token }}
+ script: |
+ github.rest.issues.addLabels({
+ issue_number: context.issue.number,
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ labels: ["possible duplicate"]
+ })
+ - uses: actions/checkout@v4
+ - name: Automatically close issues that dont follow the issue template
+ uses: lucasbento/auto-close-issues@v1.0.2
+ with:
+ github-token: ${{ steps.generate_token.outputs.token }}
+ issue-close-message: |
+ @${issue.user.login}: hello! :wave:
+ This issue is being automatically closed because it does not follow the issue template."
+ closed-issues-label: "invalid"
+ - name: Check if issue mentions a provider
+ id: provider_check
+ env:
+ GH_TEXT: "${{ github.event.issue.title }} ${{ github.event.issue.body }}"
+ run: |
+ wget --output-document check_issue.py "https://raw.githubusercontent.com/recloudstream/.github/master/.github/check_issue.py"
+ pip3 install httpx
+ RES="$(python3 ./check_issue.py)"
+ echo "name=${RES}" >> $GITHUB_OUTPUT
+ - name: Comment if issue mentions a provider
+ if: steps.provider_check.outputs.name != 'none'
+ uses: actions-cool/issues-helper@v3
+ with:
+ actions: 'create-comment'
+ token: ${{ steps.generate_token.outputs.token }}
+ body: |
+ Hello ${{ github.event.issue.user.login }}.
+ Please do not report any provider bugs here. This repository does not contain any providers. Please find the appropriate repository and report your issue there or join the [discord](https://discord.gg/5Hus6fM).
+
+ Found provider name: `${{ steps.provider_check.outputs.name }}`
+ - name: Label if mentions provider
+ if: steps.provider_check.outputs.name != 'none'
+ uses: actions/github-script@v7
+ with:
+ github-token: ${{ steps.generate_token.outputs.token }}
+ script: |
+ github.rest.issues.addLabels({
+ issue_number: context.issue.number,
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ labels: ["possible provider issue"]
+ })
+ - name: Add eyes reaction to all issues
+ uses: actions-cool/emoji-helper@v1.0.0
+ with:
+ type: 'issue'
+ token: ${{ steps.generate_token.outputs.token }}
+ emoji: 'eyes'
+
+
diff --git a/.github/workflows/prerelease.yml b/.github/workflows/prerelease.yml
index f089afa8f..f35cd58c5 100644
--- a/.github/workflows/prerelease.yml
+++ b/.github/workflows/prerelease.yml
@@ -8,13 +8,10 @@ on:
- '*.json'
- '**/wcokey.txt'
-concurrency:
+concurrency:
group: "pre-release"
cancel-in-progress: true
-permissions:
- contents: write
-
jobs:
build:
runs-on: ubuntu-latest
@@ -26,18 +23,14 @@ jobs:
app_id: ${{ secrets.GH_APP_ID }}
private_key: ${{ secrets.GH_APP_KEY }}
repository: "recloudstream/secrets"
-
- - uses: actions/checkout@v6
-
+ - uses: actions/checkout@v4
- name: Set up JDK 17
- uses: actions/setup-java@v5
+ uses: actions/setup-java@v4
with:
- distribution: temurin
- java-version: 17
-
+ java-version: '17'
+ distribution: 'adopt'
- name: Grant execute permission for gradlew
run: chmod +x gradlew
-
- name: Fetch keystore
id: fetch_keystore
run: |
@@ -48,27 +41,18 @@ jobs:
KEY_PWD="$(cat keystore_password.txt)"
echo "::add-mask::${KEY_PWD}"
echo "key_pwd=$KEY_PWD" >> $GITHUB_OUTPUT
-
- - name: Setup Gradle
- uses: gradle/actions/setup-gradle@v5
- with:
- cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
-
- name: Run Gradle
- run: ./gradlew assemblePrereleaseRelease androidSourcesJar makeJar
+ run: |
+ ./gradlew assemblePrerelease build androidSourcesJar
+ ./gradlew makeJar # for classes.jar, has to be done after assemblePrerelease
env:
SIGNING_KEY_ALIAS: "key0"
SIGNING_KEY_PASSWORD: ${{ steps.fetch_keystore.outputs.key_pwd }}
SIGNING_STORE_PASSWORD: ${{ steps.fetch_keystore.outputs.key_pwd }}
SIMKL_CLIENT_ID: ${{ secrets.SIMKL_CLIENT_ID }}
SIMKL_CLIENT_SECRET: ${{ secrets.SIMKL_CLIENT_SECRET }}
- TRAKT_CLIENT_ID: ${{ secrets.TRAKT_CLIENT_ID }}
- MDL_API_KEY: ${{ secrets.MDL_API_KEY }}
- MAL_KEY: ${{ secrets.MAL_KEY }}
- ANILIST_KEY: ${{ secrets.ANILIST_KEY }}
-
- name: Create pre-release
- uses: marvinpinto/action-automatic-releases@latest
+ uses: "marvinpinto/action-automatic-releases@latest"
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
automatic_release_tag: "pre-release"
diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml
index 433816e0f..7f6dd4123 100644
--- a/.github/workflows/pull_request.yml
+++ b/.github/workflows/pull_request.yml
@@ -2,40 +2,22 @@ name: Artifact Build
on: [pull_request]
-permissions:
- contents: read
-
jobs:
build:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v6
-
+ - uses: actions/checkout@v4
- name: Set up JDK 17
- uses: actions/setup-java@v5
+ uses: actions/setup-java@v4
with:
- distribution: temurin
- java-version: 17
-
+ java-version: '17'
+ distribution: 'adopt'
- name: Grant execute permission for gradlew
run: chmod +x gradlew
-
- - name: Setup Gradle
- uses: gradle/actions/setup-gradle@v5
- with:
- cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
- cache-read-only: false
-
- - name: Ensure binary compatibility
- # This is to ensure that your code is backwards compatible.
- # If this fails you need to add a @Prerelease annotation to new code.
- run: ./gradlew library:checkKotlinAbi
-
- name: Run Gradle
- run: ./gradlew assemblePrereleaseDebug lint check
-
+ run: ./gradlew assemblePrereleaseDebug
- name: Upload Artifact
- uses: actions/upload-artifact@v7
+ uses: actions/upload-artifact@v4
with:
name: pull-request-build
path: "app/build/outputs/apk/prerelease/debug/*.apk"
diff --git a/.github/workflows/update_locales.yml b/.github/workflows/update_locales.yml
index 0a538d5d4..ce140e559 100644
--- a/.github/workflows/update_locales.yml
+++ b/.github/workflows/update_locales.yml
@@ -1,19 +1,17 @@
name: Fix locale issues
on:
+ workflow_dispatch:
push:
- branches: [ master ]
paths:
- '**.xml'
- workflow_dispatch:
+ branches:
+ - master
-concurrency:
+concurrency:
group: "locale"
cancel-in-progress: true
-permissions:
- contents: read
-
jobs:
create:
runs-on: ubuntu-latest
@@ -25,17 +23,15 @@ jobs:
app_id: ${{ secrets.GH_APP_ID }}
private_key: ${{ secrets.GH_APP_KEY }}
repository: "recloudstream/cloudstream"
-
- - uses: actions/checkout@v6
+ - uses: actions/checkout@v4
with:
token: ${{ steps.generate_token.outputs.token }}
-
- name: Install dependencies
- run: pip3 install lxml requests
-
+ run: |
+ pip3 install lxml
- name: Edit files
- run: python3 .github/locales.py
-
+ run: |
+ python3 .github/locales.py
- name: Commit to the repo
run: |
git config --local user.email "111277985+recloudstream[bot]@users.noreply.github.com"
diff --git a/.gitignore b/.gitignore
index 5fc9f0870..2ac6c9695 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,5 @@
+*.iml
+.gradle
/local.properties
/.idea/caches
/.idea/misc.xml
@@ -9,220 +11,6 @@
.DS_Store
/build
/captures
-.cxx
-.kotlin/*
-
-# Created by https://www.toptal.com/developers/gitignore/api/kotlin,java,android,androidstudio,visualstudiocode
-# Edit at https://www.toptal.com/developers/gitignore?templates=kotlin,java,android,androidstudio,visualstudiocode
-
-### Android ###
-# Gradle files
-.gradle/
-build/
-
-# Local configuration file (sdk path, etc)
-local.properties
-
-# Log/OS Files
-*.log
-
-# Android Studio generated files and folders
-captures/
-.externalNativeBuild/
-.cxx/
-*.apk
-output.json
-
-# IntelliJ
-*.iml
-.idea/
-misc.xml
-deploymentTargetDropDown.xml
-render.experimental.xml
-
-# Keystore files
-*.jks
-*.keystore
-
-# Google Services (e.g. APIs or Firebase)
-google-services.json
-
-# Android Profiling
-*.hprof
-
-### Android Patch ###
-gen-external-apklibs
-
-# Replacement of .externalNativeBuild directories introduced
-# with Android Studio 3.5.
-
-### Java ###
-# Compiled class file
-*.class
-
-# Log file
-
-# BlueJ files
-*.ctxt
-
-# Mobile Tools for Java (J2ME)
-.mtj.tmp/
-
-# Package Files #
-*.jar
-*.war
-*.nar
-*.ear
-*.zip
-*.tar.gz
-*.rar
-
-# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
-hs_err_pid*
-replay_pid*
-
-### Kotlin ###
-# Compiled class file
-
-# Log file
-
-# BlueJ files
-
-# Mobile Tools for Java (J2ME)
-
-# Package Files #
-
-# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
-
-### VisualStudioCode ###
-.vscode/*
-
-# Local History for Visual Studio Code
-.history/
-
-# Built Visual Studio Code Extensions
-*.vsix
-
-### VisualStudioCode Patch ###
-# Ignore all local history of files
-.history
-.ionide
-
-### AndroidStudio ###
-# Covers files to be ignored for android development using Android Studio.
-
-# Built application files
-*.ap_
-*.aab
-
-# Files for the ART/Dalvik VM
-*.dex
-
-# Java class files
-
-# Generated files
-bin/
-gen/
-out/
-
-# Gradle files
-.gradle
-
-# Signing files
-.signing/
-
-# Local configuration file (sdk path, etc)
-
-# Proguard folder generated by Eclipse
-proguard/
-
-# Log Files
-
-# Android Studio
-/*/build/
-/*/local.properties
-/*/out
-/*/*/build
-/*/*/production
-.navigation/
-*.ipr
-*~
-*.swp
-
-# Keystore files
-
-# Google Services (e.g. APIs or Firebase)
-# google-services.json
-
-# Android Patch
-
-# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
-
-# NDK
-obj/
-
-# IntelliJ IDEA
-*.iws
-/out/
-
-# User-specific configurations
-.idea/caches/
-.idea/libraries/
-.idea/shelf/
-.idea/workspace.xml
-.idea/tasks.xml
-.idea/.name
-.idea/compiler.xml
-.idea/copyright/profiles_settings.xml
-.idea/encodings.xml
-.idea/misc.xml
-.idea/modules.xml
-.idea/scopes/scope_settings.xml
-.idea/dictionaries
-.idea/vcs.xml
-.idea/jsLibraryMappings.xml
-.idea/datasources.xml
-.idea/dataSources.ids
-.idea/sqlDataSources.xml
-.idea/dynamic.xml
-.idea/uiDesigner.xml
-.idea/assetWizardSettings.xml
-.idea/gradle.xml
-.idea/jarRepositories.xml
-.idea/navEditor.xml
-
-# Legacy Eclipse project files
-.classpath
-.project
-.cproject
-.settings/
-
-# Mobile Tools for Java (J2ME)
-
-# Package Files #
-
-# virtual machine crash logs (Reference: http://www.java.com/en/download/help/error_hotspot.xml)
-
-## Plugin-specific files:
-
-# mpeltonen/sbt-idea plugin
-.idea_modules/
-
-# JIRA plugin
-atlassian-ide-plugin.xml
-
-# Mongo Explorer plugin
-.idea/mongoSettings.xml
-
-# Crashlytics plugin (for Android Studio and IntelliJ)
-com_crashlytics_export_strings.xml
-crashlytics.properties
-crashlytics-build.properties
-fabric.properties
-
-### AndroidStudio Patch ###
-
-!/gradle/wrapper/gradle-wrapper.jar
-
-# End of https://www.toptal.com/developers/gitignore/api/kotlin,java,android,androidstudio,visualstudiocode
+.cxx
+local.properties
diff --git a/.idea/.name b/.idea/.name
new file mode 100644
index 000000000..1eb497a93
--- /dev/null
+++ b/.idea/.name
@@ -0,0 +1 @@
+CloudStream
\ No newline at end of file
diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml
new file mode 100644
index 000000000..7643783a8
--- /dev/null
+++ b/.idea/codeStyles/Project.xml
@@ -0,0 +1,123 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ xmlns:android
+
+ ^$
+
+
+
+
+
+
+
+
+ xmlns:.*
+
+ ^$
+
+
+ BY_NAME
+
+
+
+
+
+
+ .*:id
+
+ http://schemas.android.com/apk/res/android
+
+
+
+
+
+
+
+
+ .*:name
+
+ http://schemas.android.com/apk/res/android
+
+
+
+
+
+
+
+
+ name
+
+ ^$
+
+
+
+
+
+
+
+
+ style
+
+ ^$
+
+
+
+
+
+
+
+
+ .*
+
+ ^$
+
+
+ BY_NAME
+
+
+
+
+
+
+ .*
+
+ http://schemas.android.com/apk/res/android
+
+
+ ANDROID_ATTRIBUTE_ORDER
+
+
+
+
+
+
+ .*
+
+ .*
+
+
+ BY_NAME
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml
new file mode 100644
index 000000000..79ee123c2
--- /dev/null
+++ b/.idea/codeStyles/codeStyleConfig.xml
@@ -0,0 +1,5 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/compiler.xml b/.idea/compiler.xml
new file mode 100644
index 000000000..b86273d94
--- /dev/null
+++ b/.idea/compiler.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/discord.xml b/.idea/discord.xml
new file mode 100644
index 000000000..d8e956166
--- /dev/null
+++ b/.idea/discord.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/gradle.xml b/.idea/gradle.xml
new file mode 100644
index 000000000..db202a929
--- /dev/null
+++ b/.idea/gradle.xml
@@ -0,0 +1,21 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml
new file mode 100644
index 000000000..333d49373
--- /dev/null
+++ b/.idea/jarRepositories.xml
@@ -0,0 +1,40 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/studiobot.xml b/.idea/studiobot.xml
new file mode 100644
index 000000000..9298202cb
--- /dev/null
+++ b/.idea/studiobot.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
new file mode 100644
index 000000000..35eb1ddfb
--- /dev/null
+++ b/.idea/vcs.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100644
index 000000000..7282979ad
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,6 @@
+{
+ "githubPullRequests.ignoredPullRequestBranches": [
+ "master"
+ ],
+ "java.configuration.updateBuildConfiguration": "interactive"
+}
\ No newline at end of file
diff --git a/AI-POLICY.md b/AI-POLICY.md
deleted file mode 100644
index 5409393fb..000000000
--- a/AI-POLICY.md
+++ /dev/null
@@ -1,11 +0,0 @@
-# AI Policy
-
-AI is a great tool. However, we want you to follow these rules regarding usage of AI in order to ensure the quality of both code and discussions.
-
-1. Always state any AI usage in pull requests and issues.
-
-2. Always test code before making a pull request. We do not want to test your AI generated code.
-
-3. Listen to humans over computers. Contributors to CloudStream know this codebase better than an AI.
-
-4. You should be able to explain and fix any code you submit. We do in-depth reviews and will reject low effort contributions.
diff --git a/COMPOSE.md b/COMPOSE.md
deleted file mode 100644
index 8d83a50ae..000000000
--- a/COMPOSE.md
+++ /dev/null
@@ -1,21 +0,0 @@
-# Migration guide to Compose
-
-### 1. MVI instead of MVVM
-
-The current design of CloudStream loosely uses the MVVM architecture.
-
-This means that the UI invokes the viewmodel with function calls, and it responds with LiveData fields that are observed. While this has worked, it generates a lot of boilerplate and has created some friction.
-
-To make it easier to work with Compose, the new architecture will be based on MVI. In short this means that the viewmodel exposes a singular immutable class that is observed, and receives all UI events with a singular event that is a sealed class. All the UI should be able to be recreated based on this singular state class, and all interactions should be able to be replayed using only the event callback.
-
-For a more detailed overview, see: https://www.youtube.com/watch?v=b2z1jvD4VMQ
-
-This is part of the effort to make CloudStream cross platform, as it allows us to decouple UI and logic.
-
-### 2. KMP-compatible libraries
-
-We plan to leverage Kotlin's KMP project to compile our code to different architectures. However, this requires us to only use KMP-compatible libraries, no Java. Therefore any pull requests must ensure that they use KMP-compatible libraries only.
-
-### 3. UI Changes
-
-While migrating to the new compose UI, you also have the opportunity to change the UI. However, this should only be to freshen up the UI, not completely redesign it. It is also important to stress that this process should not lose any features of the old UI, and be very conservative with adding new features.
\ No newline at end of file
diff --git a/README.md b/README.md
index c2492c5d8..3980b1096 100644
--- a/README.md
+++ b/README.md
@@ -13,7 +13,7 @@
+ [Bugs Reports:](#bug_report)
+ [Enhancement:](#enhancment)
+ [Extension Development:](#extensions)
-+ [Language Support:](#languages)
++ [Languauge Support:](#languages)
+ [Further Sources](#contact_and_sources)
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 2ad8451a3..47e6a3606 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -1,96 +1,53 @@
import com.android.build.gradle.internal.cxx.configure.gradleLocalProperties
import org.jetbrains.dokka.gradle.engine.parameters.KotlinPlatform
import org.jetbrains.dokka.gradle.engine.parameters.VisibilityModifier
-import org.jetbrains.kotlin.gradle.dsl.JvmDefaultMode
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
import org.jetbrains.kotlin.gradle.tasks.KotlinJvmCompile
plugins {
- alias(libs.plugins.android.application)
- alias(libs.plugins.dokka)
- alias(libs.plugins.kotlin.serialization)
+ id("com.android.application")
+ id("kotlin-android")
+ id("org.jetbrains.dokka")
}
val javaTarget = JvmTarget.fromTarget(libs.versions.jvmTarget.get())
+val tmpFilePath = System.getProperty("user.home") + "/work/_temp/keystore/"
+val prereleaseStoreFile: File? = File(tmpFilePath).listFiles()?.first()
-abstract class GenerateGitHashTask : DefaultTask() {
+fun getGitCommitHash(): String {
+ return try {
+ val headFile = file("${project.rootDir}/.git/HEAD")
- @get:InputFile
- @get:PathSensitive(PathSensitivity.RELATIVE)
- abstract val headFile: RegularFileProperty
-
- @get:InputDirectory
- @get:PathSensitive(PathSensitivity.RELATIVE)
- abstract val headsDir: DirectoryProperty
-
- @get:OutputDirectory
- abstract val outputDir: DirectoryProperty
-
- @TaskAction
- fun generate() {
- val head = headFile.get().asFile
-
- val hash = try {
- if (head.exists()) {
- // Read the commit hash from .git/HEAD
- val headContent = head.readText().trim()
- if (headContent.startsWith("ref:")) {
- val refPath = headContent.substring(5) // e.g., refs/heads/main
- val commitFile = File(head.parentFile, refPath)
- if (commitFile.exists()) commitFile.readText().trim() else ""
- } else headContent // If it's a detached HEAD (commit hash directly)
- } else "" // If .git/HEAD doesn't exist
- } catch (_: Throwable) {
- "" // Just set to an empty string if any exception occurs
- }.take(7) // Get the short commit hash
-
- val outFile = outputDir.file("git-hash.txt").get().asFile
- outFile.parentFile.mkdirs()
- outFile.writeText(hash)
+ // Read the commit hash from .git/HEAD
+ if (headFile.exists()) {
+ val headContent = headFile.readText().trim()
+ if (headContent.startsWith("ref:")) {
+ val refPath = headContent.substring(5) // e.g., refs/heads/main
+ val commitFile = file("${project.rootDir}/.git/$refPath")
+ if (commitFile.exists()) commitFile.readText().trim() else ""
+ } else headContent // If it's a detached HEAD (commit hash directly)
+ } else {
+ "" // If .git/HEAD doesn't exist
+ }.take(7) // Return the short commit hash
+ } catch (_: Throwable) {
+ "" // Just return an empty string if any exception occurs
}
}
-val generateGitHash = tasks.register("generateGitHash") {
- val gitDir = layout.projectDirectory.dir("../.git")
-
- headFile.set(gitDir.file("HEAD"))
- headsDir.set(gitDir.dir("refs/heads"))
-
- outputDir.set(layout.buildDirectory.dir("generated/git"))
-}
-
android {
@Suppress("UnstableApiUsage")
testOptions {
unitTests.isReturnDefaultValues = true
}
- // Looks like google likes to add metadata only they can read https://gitlab.com/IzzyOnDroid/repo/-/work_items/491
- dependenciesInfo {
- // Disables dependency metadata when building APKs.
- includeInApk = false
- // Disables dependency metadata when building Android App Bundles.
- includeInBundle = false
- }
-
- androidComponents {
- onVariants { variant ->
- variant.sources.assets?.addGeneratedSourceDirectory(
- generateGitHash,
- GenerateGitHashTask::outputDir
- )
- }
+ viewBinding {
+ enable = true
}
signingConfigs {
- // We just use SIGNING_KEY_ALIAS here since it won't change
- // so won't kill the configuration cache.
- if (System.getenv("SIGNING_KEY_ALIAS") != null) {
+ if (prereleaseStoreFile != null) {
create("prerelease") {
- val tmpFilePath = System.getProperty("user.home") + "/work/_temp/keystore/"
- val prereleaseStoreFile: File? = File(tmpFilePath).listFiles()?.first()
-
- storeFile = prereleaseStoreFile?.let { file(it) }
+ storeFile = file(prereleaseStoreFile)
storePassword = System.getenv("SIGNING_STORE_PASSWORD")
keyAlias = System.getenv("SIGNING_KEY_ALIAS")
keyPassword = System.getenv("SIGNING_KEY_PASSWORD")
@@ -104,10 +61,12 @@ android {
applicationId = "com.lagradost.cloudstream3"
minSdk = libs.versions.minSdk.get().toInt()
targetSdk = libs.versions.targetSdk.get().toInt()
- versionCode = libs.versions.versionCode.get().toInt()
- versionName = libs.versions.versionName.get()
+ versionCode = 65
+ versionName = "4.5.1"
- manifestPlaceholders["target_sdk_version"] = libs.versions.targetSdk.get()
+ resValue("string", "app_version", "${defaultConfig.versionName}${versionNameSuffix ?: ""}")
+ resValue("string", "commit_hash", getGitCommitHash())
+ resValue("bool", "is_prerelease", "false")
// Reads local.properties
val localProperties = gradleLocalProperties(rootDir, project.providers)
@@ -127,16 +86,6 @@ android {
"SIMKL_CLIENT_SECRET",
"\"" + (System.getenv("SIMKL_CLIENT_SECRET") ?: localProperties["simkl.secret"]) + "\""
)
- buildConfigField(
- "String",
- "MAL_KEY",
- "\"" + (System.getenv("MAL_KEY") ?: localProperties["mal.key"]) + "\""
- )
- buildConfigField(
- "String",
- "ANILIST_KEY",
- "\"" + (System.getenv("ANILIST_KEY") ?: localProperties["anilist.key"]) + "\""
- )
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
@@ -164,9 +113,12 @@ android {
productFlavors {
create("stable") {
dimension = "state"
+ resValue("bool", "is_prerelease", "false")
}
create("prerelease") {
dimension = "state"
+ resValue("bool", "is_prerelease", "true")
+ buildConfigField("boolean", "BETA", "true")
applicationIdSuffix = ".prerelease"
if (signingConfigs.names.contains("prerelease")) {
signingConfig = signingConfigs.getByName("prerelease")
@@ -184,29 +136,13 @@ android {
targetCompatibility = JavaVersion.toVersion(javaTarget.target)
}
- java {
- // Use Java 17 toolchain even if a higher JDK runs the build.
- // We still use Java 8 for now which higher JDKs have deprecated.
- toolchain {
- languageVersion.set(JavaLanguageVersion.of(libs.versions.jdkToolchain.get()))
- }
- }
-
lint {
+ abortOnError = false
checkReleaseBuilds = false
}
buildFeatures {
buildConfig = true
- viewBinding = true
- }
-
- packaging {
- jniLibs {
- // Enables legacy JNI packaging to reduce APK size (similar to builds before minSdk 23).
- // Note: This may increase app startup time slightly.
- useLegacyPackaging = true
- }
}
namespace = "com.lagradost.cloudstream3"
@@ -217,46 +153,44 @@ dependencies {
testImplementation(libs.junit)
testImplementation(libs.json)
androidTestImplementation(libs.core)
- androidTestImplementation(libs.espresso.core)
+ implementation(libs.junit.ktx)
androidTestImplementation(libs.ext.junit)
- androidTestImplementation(libs.instancio.core)
- androidTestImplementation(libs.junit.ktx)
- androidTestImplementation(libs.kotlin.test)
+ androidTestImplementation(libs.espresso.core)
// Android Core & Lifecycle
implementation(libs.core.ktx)
- implementation(libs.activity.ktx)
- implementation(libs.annotation)
implementation(libs.appcompat)
- implementation(libs.fragment.ktx)
- implementation(libs.bundles.lifecycle)
- implementation(libs.bundles.navigation)
- implementation(libs.kotlinx.collections.immutable)
- implementation(libs.kotlinx.serialization.json) // JSON Parser
+ implementation(libs.navigation.ui.ktx)
+ implementation(libs.lifecycle.livedata.ktx)
+ implementation(libs.lifecycle.viewmodel.ktx)
+ implementation(libs.navigation.fragment.ktx)
// Design & UI
implementation(libs.preference.ktx)
implementation(libs.material)
implementation(libs.constraintlayout)
+ implementation(libs.swiperefreshlayout)
// Coil Image Loading
- implementation(libs.bundles.coil)
+ implementation(libs.coil)
+ implementation(libs.coil.network.okhttp)
// Media 3 (ExoPlayer)
implementation(libs.bundles.media3)
implementation(libs.video)
- // FFmpeg Decoding
- implementation(libs.bundles.nextlib)
-
- // Anime-db for filler
- implementation(libs.anime.db)
-
// PlayBack
implementation(libs.colorpicker) // Subtitle Color Picker
implementation(libs.newpipeextractor) // For Trailers
implementation(libs.juniversalchardet) // Subtitle Decoding
+ // FFmpeg Decoding
+ implementation(libs.bundles.nextlibMedia3)
+
+ // Crash Reports (AcraApplication.kt)
+ implementation(libs.acra.core)
+ implementation(libs.acra.toast)
+
// UI Stuff
implementation(libs.shimmer) // Shimmering Effect (Loading Skeleton)
implementation(libs.palette.ktx) // Palette for Images -> Colors
@@ -267,37 +201,50 @@ dependencies {
implementation(libs.qrcode.kotlin) // QR Code for PIN Auth on TV
// Extensions & Other Libs
- implementation(libs.jsoup) // HTML Parser
- implementation(libs.ksoup) // HTML Parser
implementation(libs.rhino) // Run JavaScript
+ implementation(libs.quickjs)
+ implementation(libs.fuzzywuzzy) // Library/Ext Searching with Levenshtein Distance
implementation(libs.safefile) // To Prevent the URI File Fu*kery
coreLibraryDesugaring(libs.desugar.jdk.libs.nio) // NIO Flavor Needed for NewPipeExtractor
- implementation(libs.conscrypt.android) // To Fix SSL Fu*kery on Android 9
- implementation(libs.jackson.module.kotlin) // JSON Parser
- implementation(libs.zipline)
-
- // Temp/deprecated; will be removed once extensions have time to migrate from using it
- implementation("com.google.code.gson:gson:2.11.0")
- // Deprecated; will be removed once extensions have time to migrate from using it
- implementation("me.xdrop:fuzzywuzzy:1.4.0")
+ implementation(libs.conscrypt.android) {
+ version {
+ strictly("2.5.2")
+ }
+ because("2.5.3 crashes everything for everyone.")
+ } // To Fix SSL Fu*kery on Android 9
+ implementation(libs.jackson.module.kotlin) {
+ version {
+ strictly("2.13.1")
+ }
+ because("Don't Bump Jackson above 2.13.1, Crashes on Android TV's and FireSticks that have Min API Level 25 or Less.")
+ } // JSON Parser
// Torrent Support
- implementation(libs.torrentserver)
+ // implementation(libs.torrentserver)
// Downloading & Networking
+ implementation(libs.work.runtime)
implementation(libs.work.runtime.ktx)
implementation(libs.nicehttp) // HTTP Lib
- implementation(project(":library"))
+ implementation(project(":library") {
+ // There does not seem to be a good way of getting the android flavor.
+ val isDebug = gradle.startParameter.taskRequests.any { task ->
+ task.args.any { arg ->
+ arg.contains("debug", true)
+ }
+ }
+
+ this.extra.set("isDebug", isDebug)
+ })
}
tasks.register("androidSourcesJar") {
archiveClassifier.set("sources")
- from(android.sourceSets.getByName("main").java.directories) // Full Sources
+ from(android.sourceSets.getByName("main").java.srcDirs) // Full Sources
}
tasks.register("copyJar") {
- dependsOn("build", ":library:jvmJar")
from(
"build/intermediates/compile_app_classes_jar/prereleaseDebug/bundlePrereleaseDebugClassesToCompileJar",
"../library/build/libs"
@@ -324,21 +271,15 @@ tasks.register("makeJar") {
tasks.withType {
compilerOptions {
jvmTarget.set(javaTarget)
- jvmDefault.set(JvmDefaultMode.ENABLE)
- optIn.addAll(
- "com.lagradost.cloudstream3.InternalAPI",
- "com.lagradost.cloudstream3.Prerelease",
- )
+ freeCompilerArgs.add("-Xjvm-default=all-compatibility")
}
}
dokka {
moduleName = "App"
dokkaSourceSets {
- configureEach {
- suppress = name != "prereleaseDebug"
+ main {
analysisPlatform = KotlinPlatform.JVM
- displayName = "JVM"
documentedVisibilities(
VisibilityModifier.Public,
VisibilityModifier.Protected
diff --git a/app/lint.xml b/app/lint.xml
deleted file mode 100644
index b2f5e8f2b..000000000
--- a/app/lint.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/app/src/androidTest/java/com/lagradost/cloudstream3/ExampleInstrumentedTest.kt b/app/src/androidTest/java/com/lagradost/cloudstream3/ExampleInstrumentedTest.kt
index e854356a0..c7f02baff 100644
--- a/app/src/androidTest/java/com/lagradost/cloudstream3/ExampleInstrumentedTest.kt
+++ b/app/src/androidTest/java/com/lagradost/cloudstream3/ExampleInstrumentedTest.kt
@@ -7,7 +7,6 @@ import android.view.LayoutInflater
import androidx.test.core.app.ActivityScenario
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.viewbinding.ViewBinding
-import com.lagradost.cloudstream3.databinding.BottomResultviewPreviewBinding
import com.lagradost.cloudstream3.databinding.FragmentHomeBinding
import com.lagradost.cloudstream3.databinding.FragmentHomeTvBinding
import com.lagradost.cloudstream3.databinding.FragmentLibraryBinding
@@ -55,6 +54,12 @@ class ExampleInstrumentedTest {
return APIHolder.allProviders.toTypedArray() //.filter { !it.usesWebView }
}
+ @Test
+ fun providersExist() {
+ Assert.assertTrue(getAllProviders().isNotEmpty())
+ println("Done providersExist")
+ }
+
@Throws
private inline fun testAllLayouts(
activity: Activity,
@@ -83,8 +88,6 @@ class ExampleInstrumentedTest {
// testAllLayouts(activity,R.layout.activity_main, R.layout.activity_main_tv)
//testAllLayouts(activity, R.layout.activity_main_tv)
- testAllLayouts(activity, R.layout.bottom_resultview_preview,R.layout.bottom_resultview_preview_tv)
-
testAllLayouts(activity, R.layout.fragment_player,R.layout.fragment_player_tv)
testAllLayouts(activity, R.layout.fragment_player,R.layout.fragment_player_tv)
@@ -130,14 +133,14 @@ class ExampleInstrumentedTest {
@Test
@Throws(AssertionError::class)
fun providerCorrectData() {
- val langTagsIETF = SubtitleHelper.languages.map { it.IETF_tag }
- Assert.assertFalse("IETFTagNames does not contain any languages", langTagsIETF.isNullOrEmpty())
+ val isoNames = SubtitleHelper.languages.map { it.ISO_639_1 }
+ Assert.assertFalse("ISO does not contain any languages", isoNames.isNullOrEmpty())
for (api in getAllProviders()) {
Assert.assertTrue("Api does not contain a mainUrl", api.mainUrl != "NONE")
Assert.assertTrue("Api does not contain a name", api.name != "NONE")
Assert.assertTrue(
"Api ${api.name} does not contain a valid language code",
- langTagsIETF.contains(api.lang)
+ isoNames.contains(api.lang)
)
Assert.assertTrue(
"Api ${api.name} does not contain any supported types",
diff --git a/app/src/androidTest/java/com/lagradost/cloudstream3/SerializationClassTester.kt b/app/src/androidTest/java/com/lagradost/cloudstream3/SerializationClassTester.kt
deleted file mode 100644
index 84ef1fee0..000000000
--- a/app/src/androidTest/java/com/lagradost/cloudstream3/SerializationClassTester.kt
+++ /dev/null
@@ -1,154 +0,0 @@
-package com.lagradost.cloudstream3
-
-import androidx.test.ext.junit.runners.AndroidJUnit4
-import androidx.test.platform.app.InstrumentationRegistry
-import com.lagradost.cloudstream3.SkipSerializationTest
-import com.lagradost.cloudstream3.utils.AppUtils.toJson
-import dalvik.system.DexFile
-import kotlinx.serialization.ExperimentalSerializationApi
-import kotlinx.serialization.InternalSerializationApi
-import kotlinx.serialization.KSerializer
-import kotlinx.serialization.Serializable
-import kotlinx.serialization.serializer
-import kotlinx.serialization.serializerOrNull
-import org.instancio.Instancio
-import org.junit.Test
-import org.junit.runner.RunWith
-import kotlin.reflect.KClass
-import kotlin.reflect.jvm.jvmName
-import kotlin.test.assertEquals
-import kotlin.test.assertNotNull
-
-@RunWith(AndroidJUnit4::class)
-class SerializationClassTester {
- // Same as app, or using app reference
- val jacksonMapper = mapper
- val kotlinxMapper = json
-
- @Test
- fun isIdenticalSerialization() {
- val serializableClasses = findSerializableClasses("com.lagradost")
- println("Number of serializable classes: ${serializableClasses.size}")
-
- val failures = mutableListOf()
-
- serializableClasses.forEach { kClass ->
- runCatching {
- val instance = Instancio.of(kClass.java).withMaxDepth(10).create()
-
- val jacksonJson = jacksonMapper.writeValueAsString(instance)
- val kotlinxJson = serializeWithKotlinx(kClass, instance)
-
- assertEquals(
- jacksonJson,
- kotlinxJson,
- """
- Serialization mismatch for:
- ${kClass.qualifiedName}
-
- Jackson:
- $jacksonJson
-
- Kotlinx:
- $kotlinxJson
-
- """.trimIndent()
- )
- println("Identical serialization for: ${kClass.jvmName}")
- }.onFailure { e ->
- failures.add("FAILED ${kClass.qualifiedName}: ${e.message}")
- }
- }
-
- if (failures.isNotEmpty()) {
- throw AssertionError("${failures.size} class(es) failed:\n${failures.joinToString("\n")}")
- }
- }
-
- @OptIn(InternalSerializationApi::class, ExperimentalSerializationApi::class)
- @Test
- fun isIdenticalDeserialization() {
- val serializableClasses = findSerializableClasses("com.lagradost")
- println("Number of serializable classes: ${serializableClasses.size}")
-
- val failures = mutableListOf()
-
- serializableClasses.forEach { kClass ->
- runCatching {
- val instance = Instancio.of(kClass.java).withMaxDepth(10).create()
- // Convert to JSON to get example JSON object
- // We prefer jackson here because the app may have many jackson JSON strings in local storage
- val originalJson = jacksonMapper.writeValueAsString(instance)
-
- // Create an object from the JSON using kotlinx
- val serializer =
- kClass.serializerOrNull() ?: kotlinxMapper.serializersModule.getContextual(kClass)
- assertNotNull(serializer, "The class: ${kClass.jvmName} must be serializable!")
- val kotlinxDecoded = kotlinxMapper.decodeFromString(serializer, originalJson)
-
- // Create an object from the JSON using jackson
- val mapperDecoded = jacksonMapper.readValue(originalJson, kClass.java)
-
- // Deep inspect both object using the mapper toJson function.
- // This deep equality check can be performed using other methods, but this just works.
- val jacksonJson = mapperDecoded.toJson()
- val kotlinxJson = kotlinxDecoded.toJson()
-
- assertEquals(
- jacksonJson,
- kotlinxJson,
- """
- Serialization mismatch for:
- ${kClass.qualifiedName}
-
- Jackson:
- $jacksonJson
-
- Kotlinx:
- $kotlinxJson
-
- """.trimIndent()
- )
- println("Identical deserialization for: ${kClass.jvmName}")
- }.onFailure { e ->
- failures.add("FAILED ${kClass.qualifiedName}: ${e.message}")
- }
- }
-
- if (failures.isNotEmpty()) {
- throw AssertionError("${failures.size} class(es) failed:\n${failures.joinToString("\n")}")
- }
- }
-
- // DEX files are the best solution to read all our classes dynamically.
- // classgraph could be used instead, but it only gives results on the JVM, not Android.
- @Suppress("DEPRECATION")
- private fun findSerializableClasses(packageName: String): List> {
- val context = InstrumentationRegistry
- .getInstrumentation()
- .targetContext
-
- val dexFile = DexFile(context.packageCodePath)
- return dexFile.entries()
- .toList()
- .filter { it.startsWith(packageName) }
- .mapNotNull {
- runCatching { Class.forName(it).kotlin }.getOrNull()
- }.filter { kClass ->
- // Not possible to use .hasAnnotation() on newer Android versions.
- kClass.java.annotations.any { it is Serializable }
- && kClass.java.annotations.none { it is SkipSerializationTest }
- && !kClass.isAbstract
- }
- }
-
- @OptIn(InternalSerializationApi::class)
- @Suppress("UNCHECKED_CAST")
- private fun serializeWithKotlinx(
- kClass: KClass<*>,
- value: Any
- ): String {
- val serializer = kClass.serializer() as KSerializer
- return kotlinxMapper.encodeToString(serializer, value)
- }
-}
diff --git a/app/src/androidTest/java/com/lagradost/cloudstream3/utils/serializers/UriSerializerTest.kt b/app/src/androidTest/java/com/lagradost/cloudstream3/utils/serializers/UriSerializerTest.kt
deleted file mode 100644
index 3ffd37124..000000000
--- a/app/src/androidTest/java/com/lagradost/cloudstream3/utils/serializers/UriSerializerTest.kt
+++ /dev/null
@@ -1,41 +0,0 @@
-package com.lagradost.cloudstream3.utils.serializers
-
-import android.net.Uri
-import com.lagradost.cloudstream3.utils.AppUtils.parseJson
-import com.lagradost.cloudstream3.utils.AppUtils.toJson
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
-import org.junit.Assert.assertEquals
-import org.junit.Assert.assertTrue
-import org.junit.Test
-
-@Serializable
-data class UriData(
- @Serializable(with = UriSerializer::class)
- @SerialName("uri") val uri: Uri = Uri.EMPTY,
-)
-
-class UriSerializerTest {
-
- @Test
- fun uriSerializerSerializesUriToString() {
- val data = UriData(uri = Uri.parse("https://example.com/path?query=1"))
- val result = data.toJson()
- assertTrue(result.contains("https://example.com/path?query=1"))
- }
-
- @Test
- fun uriSerializerDeserializesStringToUri() {
- val input = """{"uri":"https://example.com/path?query=1"}"""
- val result = parseJson(input)
- assertEquals(Uri.parse("https://example.com/path?query=1"), result.uri)
- }
-
- @Test
- fun uriSerializerRoundtripsCorrectly() {
- val data = UriData(uri = Uri.parse("https://example.com/path?query=1"))
- val encoded = data.toJson()
- val decoded = parseJson(encoded)
- assertEquals(data.uri, decoded.uri)
- }
-}
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index ee4c978f2..1a0b514a2 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -16,53 +16,12 @@
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+ tools:targetApi="35">
-
-
-
-
-
-
-
-
-
-
-
-
+ android:supportsPictureInPicture="true">
@@ -200,14 +142,7 @@
-
-
-
-
-
-
-
@@ -231,7 +166,7 @@
-
+
@@ -244,6 +179,25 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
+#include
+#include
+
+#define TAG "CloudStream Crash Handler"
+volatile sig_atomic_t gSignalStatus = 0;
+void handleNativeCrash(int signal) {
+ gSignalStatus = signal;
+}
+
+extern "C" JNIEXPORT void JNICALL
+Java_com_lagradost_cloudstream3_NativeCrashHandler_initNativeCrashHandler(JNIEnv *env, jobject) {
+ #define REGISTER_SIGNAL(X) signal(X, handleNativeCrash);
+ REGISTER_SIGNAL(SIGSEGV)
+ #undef REGISTER_SIGNAL
+}
+
+//extern "C" JNIEXPORT void JNICALL
+//Java_com_lagradost_cloudstream3_NativeCrashHandler_triggerNativeCrash(JNIEnv *env, jobject thiz) {
+// int *p = nullptr;
+// *p = 0;
+//}
+
+extern "C" JNIEXPORT int JNICALL
+Java_com_lagradost_cloudstream3_NativeCrashHandler_getSignalStatus(JNIEnv *env, jobject) {
+ //__android_log_print(ANDROID_LOG_INFO, TAG, "Got signal status %d", gSignalStatus);
+ return gSignalStatus;
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/AcraApplication.kt b/app/src/main/java/com/lagradost/cloudstream3/AcraApplication.kt
index b2ef28348..003d79a77 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/AcraApplication.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/AcraApplication.kt
@@ -1,78 +1,233 @@
package com.lagradost.cloudstream3
-/**
- * Deprecated alias for CloudStreamApp for backwards compatibility with plugins.
- * Use CloudStreamApp instead.
- */
-@Deprecated(
- message = "AcraApplication is deprecated, use CloudStreamApp instead",
- replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp"),
- level = DeprecationLevel.ERROR
-)
-class AcraApplication {
- companion object {
+import android.app.Activity
+import android.app.Application
+import android.content.Context
+import android.content.ContextWrapper
+import android.content.Intent
+import android.widget.Toast
+import androidx.fragment.app.Fragment
+import androidx.fragment.app.FragmentActivity
+import coil3.PlatformContext
+import coil3.SingletonImageLoader
+import com.lagradost.api.setContext
+import com.lagradost.cloudstream3.mvvm.normalSafeApiCall
+import com.lagradost.cloudstream3.mvvm.suspendSafeApiCall
+import com.lagradost.cloudstream3.plugins.PluginManager
+import com.lagradost.cloudstream3.ui.settings.Globals.EMULATOR
+import com.lagradost.cloudstream3.ui.settings.Globals.TV
+import com.lagradost.cloudstream3.ui.settings.Globals.isLayout
+import com.lagradost.cloudstream3.utils.AppContextUtils.openBrowser
+import com.lagradost.cloudstream3.utils.Coroutines.runOnMainThread
+import com.lagradost.cloudstream3.utils.DataStore.getKey
+import com.lagradost.cloudstream3.utils.DataStore.getKeys
+import com.lagradost.cloudstream3.utils.DataStore.removeKey
+import com.lagradost.cloudstream3.utils.DataStore.removeKeys
+import com.lagradost.cloudstream3.utils.DataStore.setKey
+import com.lagradost.cloudstream3.utils.ImageLoader
+import kotlinx.coroutines.runBlocking
+import org.acra.ACRA
+import org.acra.ReportField
+import org.acra.config.CoreConfiguration
+import org.acra.data.CrashReportData
+import org.acra.data.StringFormat
+import org.acra.ktx.initAcra
+import org.acra.sender.ReportSender
+import org.acra.sender.ReportSenderFactory
+import java.io.File
+import java.io.FileNotFoundException
+import java.io.PrintStream
+import java.lang.ref.WeakReference
+import java.util.Locale
+import kotlin.concurrent.thread
+import kotlin.system.exitProcess
- @Deprecated(
- message = "AcraApplication is deprecated, use CloudStreamApp instead",
- replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.context"),
- level = DeprecationLevel.ERROR
- )
- val context get() = CloudStreamApp.context
+class CustomReportSender : ReportSender {
+ // Sends all your crashes to google forms
+ override fun send(context: Context, errorContent: CrashReportData) {
+ /*println("Sending report")
+ val url =
+ "https://docs.google.com/forms/d/e/$id/formResponse"
+ val data = mapOf(
+ "entry.$entry" to errorContent.toJSON()
+ )
- @Deprecated(
- message = "AcraApplication is deprecated, use CloudStreamApp instead",
- replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.removeKeys(folder)"),
- level = DeprecationLevel.ERROR
- )
- fun removeKeys(folder: String): Int? =
- CloudStreamApp.removeKeys(folder)
+ thread { // to not run it on main thread
+ runBlocking {
+ suspendSafeApiCall {
+ app.post(url, data = data)
+ //println("Report response: $post")
+ }
+ }
+ }
- @Deprecated(
- message = "AcraApplication is deprecated, use CloudStreamApp instead",
- replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.setKey(path, value)"),
- level = DeprecationLevel.ERROR
- )
- fun setKey(path: String, value: T) =
- CloudStreamApp.setKey(path, value)
-
- @Deprecated(
- message = "AcraApplication is deprecated, use CloudStreamApp instead",
- replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.setKey(folder, path, value)"),
- level = DeprecationLevel.ERROR
- )
- fun setKey(folder: String, path: String, value: T) =
- CloudStreamApp.setKey(folder, path, value)
-
- @Deprecated(
- message = "AcraApplication is deprecated, use CloudStreamApp instead",
- replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.getKey(path, defVal)"),
- level = DeprecationLevel.ERROR
- )
- inline fun getKey(path: String, defVal: T?): T? =
- CloudStreamApp.getKey(path, defVal)
-
- @Deprecated(
- message = "AcraApplication is deprecated, use CloudStreamApp instead",
- replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.getKey(path)"),
- level = DeprecationLevel.ERROR
- )
- inline fun getKey(path: String): T? =
- CloudStreamApp.getKey(path)
-
- @Deprecated(
- message = "AcraApplication is deprecated, use CloudStreamApp instead",
- replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.getKey(folder, path)"),
- level = DeprecationLevel.ERROR
- )
- inline fun getKey(folder: String, path: String): T? =
- CloudStreamApp.getKey(folder, path)
-
- @Deprecated(
- message = "AcraApplication is deprecated, use CloudStreamApp instead",
- replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.getKey(folder, path, defVal)"),
- level = DeprecationLevel.ERROR
- )
- inline fun getKey(folder: String, path: String, defVal: T?): T? =
- CloudStreamApp.getKey(folder, path, defVal)
- }
+ runOnMainThread { // to run it on main looper
+ normalSafeApiCall {
+ Toast.makeText(context, R.string.acra_report_toast, Toast.LENGTH_SHORT).show()
+ }
+ }*/
+ }
}
+
+class CustomSenderFactory : ReportSenderFactory {
+ override fun create(context: Context, config: CoreConfiguration): ReportSender {
+ return CustomReportSender()
+ }
+
+ override fun enabled(config: CoreConfiguration): Boolean {
+ return true
+ }
+}
+
+class ExceptionHandler(val errorFile: File, val onError: (() -> Unit)) :
+ Thread.UncaughtExceptionHandler {
+ override fun uncaughtException(thread: Thread, error: Throwable) {
+ ACRA.errorReporter.handleException(error)
+ try {
+ PrintStream(errorFile).use { ps ->
+ ps.println("Currently loading extension: ${PluginManager.currentlyLoading ?: "none"}")
+ ps.println("Fatal exception on thread ${thread.name} (${thread.id})")
+ error.printStackTrace(ps)
+ }
+ } catch (ignored: FileNotFoundException) {
+ }
+ try {
+ onError.invoke()
+ } catch (ignored: Exception) {
+ }
+ exitProcess(1)
+ }
+
+}
+
+class AcraApplication : Application(), SingletonImageLoader.Factory {
+
+ override fun onCreate() {
+ super.onCreate()
+ // if we want to initialise coil at earliest
+ // (maybe when loading an image or gif using in splash screen activity)
+ //ImageLoader.buildImageLoader(applicationContext)
+
+ ExceptionHandler(filesDir.resolve("last_error")) {
+ val intent = context!!.packageManager.getLaunchIntentForPackage(context!!.packageName)
+ startActivity(Intent.makeRestartActivityTask(intent!!.component))
+ }.also {
+ exceptionHandler = it
+ Thread.setDefaultUncaughtExceptionHandler(it)
+ }
+ }
+
+ override fun attachBaseContext(base: Context?) {
+ super.attachBaseContext(base)
+ context = base
+
+ initAcra {
+ //core configuration:
+ buildConfigClass = BuildConfig::class.java
+ reportFormat = StringFormat.JSON
+
+ reportContent = listOf(
+ ReportField.BUILD_CONFIG, ReportField.USER_CRASH_DATE,
+ ReportField.ANDROID_VERSION, ReportField.PHONE_MODEL,
+ ReportField.STACK_TRACE,
+ )
+
+ // removed this due to bug when starting the app, moved it to when it actually crashes
+ //each plugin you chose above can be configured in a block like this:
+ /*toast {
+ text = getString(R.string.acra_report_toast)
+ //opening this block automatically enables the plugin.
+ }*/
+ }
+ }
+
+ override fun newImageLoader(context: PlatformContext): coil3.ImageLoader {
+ // Coil Module will be initialized & setSafe globally when first loadImage() is invoked
+ return ImageLoader.buildImageLoader(applicationContext)
+ }
+
+ companion object {
+ var exceptionHandler: ExceptionHandler? = null
+
+ /** Use to get activity from Context */
+ tailrec fun Context.getActivity(): Activity? {
+ return when (this) {
+ is Activity -> this
+ is ContextWrapper -> baseContext.getActivity()
+ else -> null
+ }
+ }
+
+ private var _context: WeakReference? = null
+ var context
+ get() = _context?.get()
+ private set(value) {
+ _context = WeakReference(value)
+ setContext(WeakReference(value))
+ }
+
+ fun getKeyClass(path: String, valueType: Class): T? {
+ return context?.getKey(path, valueType)
+ }
+
+ fun setKeyClass(path: String, value: T) {
+ context?.setKey(path, value)
+ }
+
+ fun removeKeys(folder: String): Int? {
+ return context?.removeKeys(folder)
+ }
+
+ fun setKey(path: String, value: T) {
+ context?.setKey(path, value)
+ }
+
+ fun setKey(folder: String, path: String, value: T) {
+ context?.setKey(folder, path, value)
+ }
+
+ inline fun getKey(path: String, defVal: T?): T? {
+ return context?.getKey(path, defVal)
+ }
+
+ inline fun getKey(path: String): T? {
+ return context?.getKey(path)
+ }
+
+ inline fun getKey(folder: String, path: String): T? {
+ return context?.getKey(folder, path)
+ }
+
+ inline fun getKey(folder: String, path: String, defVal: T?): T? {
+ return context?.getKey(folder, path, defVal)
+ }
+
+ fun getKeys(folder: String): List? {
+ return context?.getKeys(folder)
+ }
+
+ fun removeKey(folder: String, path: String) {
+ context?.removeKey(folder, path)
+ }
+
+ fun removeKey(path: String) {
+ context?.removeKey(path)
+ }
+
+ /**
+ * If fallbackWebview is true and a fragment is supplied then it will open a webview with the url if the browser fails.
+ * */
+ fun openBrowser(url: String, fallbackWebview: Boolean = false, fragment: Fragment? = null) {
+ context?.openBrowser(url, fallbackWebview, fragment)
+ }
+
+ /** Will fallback to webview if in TV layout */
+ fun openBrowser(url: String, activity: FragmentActivity?) {
+ openBrowser(
+ url,
+ isLayout(TV or EMULATOR),
+ activity?.supportFragmentManager?.fragments?.lastOrNull()
+ )
+ }
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/CloudStreamApp.kt b/app/src/main/java/com/lagradost/cloudstream3/CloudStreamApp.kt
deleted file mode 100644
index 466ef5a00..000000000
--- a/app/src/main/java/com/lagradost/cloudstream3/CloudStreamApp.kt
+++ /dev/null
@@ -1,181 +0,0 @@
-package com.lagradost.cloudstream3
-
-import android.app.Activity
-import android.app.Application
-import android.content.Context
-import android.content.ContextWrapper
-import android.content.Intent
-import android.os.Build
-import android.widget.Toast
-import androidx.fragment.app.Fragment
-import androidx.fragment.app.FragmentActivity
-import coil3.ImageLoader
-import coil3.PlatformContext
-import coil3.SingletonImageLoader
-import com.lagradost.api.setContext
-import com.lagradost.cloudstream3.BuildConfig
-import com.lagradost.cloudstream3.mvvm.safe
-import com.lagradost.cloudstream3.mvvm.safeAsync
-import com.lagradost.cloudstream3.plugins.PluginManager
-import com.lagradost.cloudstream3.ui.settings.Globals.EMULATOR
-import com.lagradost.cloudstream3.ui.settings.Globals.TV
-import com.lagradost.cloudstream3.ui.settings.Globals.isLayout
-import com.lagradost.cloudstream3.utils.AppContextUtils.openBrowser
-import com.lagradost.cloudstream3.utils.AppDebug
-import com.lagradost.cloudstream3.utils.Coroutines.runOnMainThread
-import com.lagradost.cloudstream3.utils.DataStore.getKey
-import com.lagradost.cloudstream3.utils.DataStore.getKeys
-import com.lagradost.cloudstream3.utils.DataStore.removeKey
-import com.lagradost.cloudstream3.utils.DataStore.removeKeys
-import com.lagradost.cloudstream3.utils.DataStore.setKey
-import com.lagradost.cloudstream3.utils.ImageLoader.buildImageLoader
-import kotlinx.coroutines.runBlocking
-import java.io.File
-import java.io.FileNotFoundException
-import java.io.PrintStream
-import java.lang.ref.WeakReference
-import java.util.Locale
-import kotlin.concurrent.thread
-import kotlin.system.exitProcess
-
-class ExceptionHandler(
- val errorFile: File,
- val onError: (() -> Unit)
-) : Thread.UncaughtExceptionHandler {
-
- override fun uncaughtException(thread: Thread, error: Throwable) {
- try {
- val threadId = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA) {
- thread.threadId()
- } else {
- @Suppress("DEPRECATION")
- thread.id
- }
-
- PrintStream(errorFile).use { ps ->
- ps.println("Currently loading extension: ${PluginManager.currentlyLoading ?: "none"}")
- ps.println("Fatal exception on thread ${thread.name} ($threadId)")
- error.printStackTrace(ps)
- }
- } catch (_: FileNotFoundException) {
- }
- try {
- onError()
- } catch (_: Exception) {
- }
- exitProcess(1)
- }
-}
-
-class CloudStreamApp : Application(), SingletonImageLoader.Factory {
-
- override fun onCreate() {
- super.onCreate()
- // If we want to initialize Coil as early as possible, maybe when
- // loading an image or GIF in a splash screen activity.
- // buildImageLoader(applicationContext)
-
- ExceptionHandler(filesDir.resolve("last_error")) {
- val intent = context!!.packageManager.getLaunchIntentForPackage(context!!.packageName)
- startActivity(Intent.makeRestartActivityTask(intent!!.component))
- }.also {
- exceptionHandler = it
- Thread.setDefaultUncaughtExceptionHandler(it)
- }
-
- AppDebug.isDebug = BuildConfig.DEBUG
- }
-
- override fun attachBaseContext(base: Context?) {
- super.attachBaseContext(base)
- context = base
- }
-
- override fun newImageLoader(context: PlatformContext): ImageLoader {
- // Coil module will be initialized globally when first loadImage() is invoked.
- return buildImageLoader(applicationContext)
- }
-
- companion object {
- var exceptionHandler: ExceptionHandler? = null
-
- /** Use to get Activity from Context. */
- tailrec fun Context.getActivity(): Activity? {
- return when (this) {
- is Activity -> this
- is ContextWrapper -> baseContext.getActivity()
- else -> null
- }
- }
-
- private var _context: WeakReference? = null
- var context
- get() = _context?.get()
- private set(value) {
- _context = WeakReference(value)
- setContext(value)
- }
-
- fun getKeyClass(path: String, valueType: Class): T? {
- return context?.getKey(path, valueType)
- }
-
- fun setKeyClass(path: String, value: T) {
- context?.setKey(path, value)
- }
-
- fun removeKeys(folder: String): Int? {
- return context?.removeKeys(folder)
- }
-
- fun setKey(path: String, value: T) {
- context?.setKey(path, value)
- }
-
- fun setKey(folder: String, path: String, value: T) {
- context?.setKey(folder, path, value)
- }
-
- inline fun getKey(path: String, defVal: T?): T? {
- return context?.getKey(path, defVal)
- }
-
- inline fun getKey(path: String): T? {
- return context?.getKey(path)
- }
-
- inline fun getKey(folder: String, path: String): T? {
- return context?.getKey(folder, path)
- }
-
- inline fun getKey(folder: String, path: String, defVal: T?): T? {
- return context?.getKey(folder, path, defVal)
- }
-
- fun getKeys(folder: String): List? {
- return context?.getKeys(folder)
- }
-
- fun removeKey(folder: String, path: String) {
- context?.removeKey(folder, path)
- }
-
- fun removeKey(path: String) {
- context?.removeKey(path)
- }
-
- /** If fallbackWebView is true and a fragment is supplied then it will open a WebView with the URL if the browser fails. */
- fun openBrowser(url: String, fallbackWebView: Boolean = false, fragment: Fragment? = null) {
- context?.openBrowser(url, fallbackWebView, fragment)
- }
-
- /** Will fall back to WebView if in TV or emulator layout. */
- fun openBrowser(url: String, activity: FragmentActivity?) {
- openBrowser(
- url,
- isLayout(TV or EMULATOR),
- activity?.supportFragmentManager?.fragments?.lastOrNull()
- )
- }
- }
-}
diff --git a/app/src/main/java/com/lagradost/cloudstream3/CommonActivity.kt b/app/src/main/java/com/lagradost/cloudstream3/CommonActivity.kt
index 4ce09bd44..02ace92d5 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/CommonActivity.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/CommonActivity.kt
@@ -1,16 +1,13 @@
package com.lagradost.cloudstream3
-import android.annotation.SuppressLint
+import android.Manifest
import android.app.Activity
import android.app.PictureInPictureParams
import android.content.Context
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.content.res.Resources
-import android.Manifest
import android.os.Build
-import android.os.Handler
-import android.os.Looper
import android.util.DisplayMetrics
import android.util.Log
import android.view.Gravity
@@ -27,41 +24,32 @@ import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.core.content.ContextCompat
import androidx.core.view.children
-import androidx.core.view.isNotEmpty
import androidx.preference.PreferenceManager
import com.google.android.gms.cast.framework.CastSession
import com.google.android.material.chip.ChipGroup
import com.google.android.material.navigationrail.NavigationRailView
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.removeKey
+import com.lagradost.cloudstream3.AcraApplication.Companion.getKey
+import com.lagradost.cloudstream3.AcraApplication.Companion.removeKey
import com.lagradost.cloudstream3.actions.OpenInAppAction
import com.lagradost.cloudstream3.actions.VideoClickActionHolder
import com.lagradost.cloudstream3.databinding.ToastBinding
import com.lagradost.cloudstream3.mvvm.logError
-import com.lagradost.cloudstream3.syncproviders.AccountManager
-import com.lagradost.cloudstream3.ui.home.HomeChildItemAdapter
-import com.lagradost.cloudstream3.ui.home.ParentItemAdapter
-import com.lagradost.cloudstream3.ui.player.PlayerPipHelper.isPIPPossible
+import com.lagradost.cloudstream3.ui.player.PlayerEventType
import com.lagradost.cloudstream3.ui.player.Torrent
-import com.lagradost.cloudstream3.ui.result.ActorAdaptor
-import com.lagradost.cloudstream3.ui.result.EpisodeAdapter
-import com.lagradost.cloudstream3.ui.result.ImageAdapter
-import com.lagradost.cloudstream3.ui.search.SearchAdapter
-import com.lagradost.cloudstream3.ui.settings.Globals.isLayout
-import com.lagradost.cloudstream3.ui.settings.Globals.TV
+import com.lagradost.cloudstream3.utils.UiText
import com.lagradost.cloudstream3.ui.settings.Globals.updateTv
-import com.lagradost.cloudstream3.ui.settings.extensions.PluginAdapter
import com.lagradost.cloudstream3.utils.AppContextUtils.isRtl
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
import com.lagradost.cloudstream3.utils.Event
-import com.lagradost.cloudstream3.utils.UIHelper.showInputMethod
+import com.lagradost.cloudstream3.utils.UIHelper
+import com.lagradost.cloudstream3.utils.UIHelper.hasPIPPermission
+import com.lagradost.cloudstream3.utils.UIHelper.shouldShowPIPMode
import com.lagradost.cloudstream3.utils.UIHelper.toPx
-import com.lagradost.cloudstream3.utils.UiText
+import org.schabi.newpipe.extractor.NewPipe
import java.lang.ref.WeakReference
import java.util.Locale
import kotlin.math.max
import kotlin.math.min
-import org.schabi.newpipe.extractor.NewPipe
enum class FocusDirection {
Start,
@@ -101,24 +89,17 @@ object CommonActivity {
get() {
return min(displayMetrics.widthPixels, displayMetrics.heightPixels)
}
- val screenWidthWithOrientation: Int
- get() {
- return displayMetrics.widthPixels
- }
- val screenHeightWithOrientation: Int
- get() {
- return displayMetrics.heightPixels
- }
- var isPipDesired: Boolean = false
+
+ var canEnterPipMode: Boolean = false
+ var canShowPipMode: Boolean = false
var isInPIPMode: Boolean = false
val onColorSelectedEvent = Event>()
val onDialogDismissedEvent = Event()
+ var playerEventListener: ((PlayerEventType) -> Unit)? = null
var keyEventListener: ((Pair) -> Boolean)? = null
- var appliedTheme: Int = 0
- var appliedColor: Int = 0
private var currentToast: Toast? = null
@@ -186,40 +167,27 @@ object CommonActivity {
toast.duration = duration ?: Toast.LENGTH_SHORT
toast.setGravity(Gravity.CENTER_HORIZONTAL or Gravity.BOTTOM, 0, 5.toPx)
@Suppress("DEPRECATION")
- toast.view =
- binding.root // FIXME Find an alternative using default Toasts since custom toasts are deprecated and won't appear with api30 set as minSDK version.
+ toast.view = binding.root // FIXME Find an alternative using default Toasts since custom toasts are deprecated and won't appear with api30 set as minSDK version.
currentToast = toast
toast.show()
- val handler = Handler(Looper.getMainLooper())
- val ref = WeakReference(toast)
-
- /* Clean up activity leak */
- handler.postDelayed({
- if (ref.get() == currentToast) {
- currentToast = null
- }
- }, 10_000)
-
} catch (e: Exception) {
logError(e)
}
}
/**
- * Set locale
- * @param languageTag shall a IETF BCP 47 conformant tag.
- * Check [com.lagradost.cloudstream3.utils.SubtitleHelper].
- *
- * See locales on:
- * https://github.com/unicode-org/cldr-json/blob/main/cldr-json/cldr-core/availableLocales.json
- * https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
- * https://android.googlesource.com/platform/frameworks/base/+/android-16.0.0_r2/core/res/res/values/locale_config.xml
- * https://iso639-3.sil.org/code_tables/639/data/all
- */
- fun setLocale(context: Context?, languageTag: String?) {
- if (context == null || languageTag == null) return
- val locale = Locale.forLanguageTag(languageTag)
+ * Not all languages can be fetched from locale with a code.
+ * This map allows sidestepping the default Locale(languageCode)
+ * when setting the app language.
+ **/
+ val appLanguageExceptions = hashMapOf(
+ "zh-rTW" to Locale.TRADITIONAL_CHINESE
+ )
+
+ fun setLocale(context: Context?, languageCode: String?) {
+ if (context == null || languageCode == null) return
+ val locale = appLanguageExceptions[languageCode] ?: Locale(languageCode)
val resources: Resources = context.resources
val config = resources.configuration
Locale.setDefault(locale)
@@ -227,12 +195,8 @@ object CommonActivity {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
context.createConfigurationContext(config)
-
@Suppress("DEPRECATION")
- resources.updateConfiguration(
- config,
- resources.displayMetrics
- ) // FIXME this should be replaced
+ resources.updateConfiguration(config, resources.displayMetrics) // FIXME this should be replaced
}
fun Context.updateLocale() {
@@ -244,26 +208,30 @@ object CommonActivity {
fun init(act: Activity) {
setActivityInstance(act)
ioSafe { Torrent.deleteAllFiles() }
+
val componentActivity = activity as? ComponentActivity ?: return
+ //https://stackoverflow.com/questions/52594181/how-to-know-if-user-has-disabled-picture-in-picture-feature-permission
+ //https://developer.android.com/guide/topics/ui/picture-in-picture
+ canShowPipMode =
+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && // OS SUPPORT
+ componentActivity.packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE) && // HAS FEATURE, MIGHT BE BLOCKED DUE TO POWER DRAIN
+ componentActivity.hasPIPPermission() // CHECK IF FEATURE IS ENABLED IN SETTINGS
+
componentActivity.updateLocale()
componentActivity.updateTv()
- AccountManager.initMainAPI()
NewPipe.init(DownloaderTestImpl.getInstance())
- MainActivity.activityResultLauncher =
- componentActivity.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
- if (result.resultCode == AppCompatActivity.RESULT_OK) {
- val actionUid =
- getKey("last_click_action") ?: return@registerForActivityResult
- Log.d(TAG, "Loading action $actionUid result handler")
- val action = VideoClickActionHolder.getByUniqueId(actionUid) as? OpenInAppAction
- ?: return@registerForActivityResult
- action.onResultSafe(act, result.data)
- removeKey("last_click_action")
- removeKey("last_opened")
- }
+ MainActivity.activityResultLauncher = componentActivity.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
+ if (result.resultCode == AppCompatActivity.RESULT_OK) {
+ val actionUid = getKey("last_click_action") ?: return@registerForActivityResult
+ Log.d(TAG, "Loading action $actionUid result handler")
+ val action = VideoClickActionHolder.getByUniqueId(actionUid) as? OpenInAppAction ?: return@registerForActivityResult
+ action.onResultSafe(act, result.data)
+ removeKey("last_click_action")
+ removeKey("last_opened_id")
}
+ }
// Ask for notification permissions on Android 13
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
@@ -283,15 +251,13 @@ object CommonActivity {
}
}
- /** Enters pip mode if it is both possible and desired to do so*/
private fun Activity.enterPIPMode() {
- if (!isPipDesired || !this.isPIPPossible()) return
-
+ if (!shouldShowPIPMode(canEnterPipMode) || !canShowPipMode) return
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
try {
enterPictureInPictureMode(PictureInPictureParams.Builder().build())
- } catch (_: Exception) {
+ } catch (e: Exception) {
// Use fallback just in case
@Suppress("DEPRECATION")
enterPictureInPictureMode()
@@ -307,18 +273,17 @@ object CommonActivity {
}
}
- fun onUserLeaveHint(act: Activity) {
- // On Android 12 and later we use setAutoEnterEnabled() instead.
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) return
- act.enterPIPMode()
+ fun onUserLeaveHint(act: Activity?) {
+ if (canEnterPipMode && canShowPipMode) {
+ act?.enterPIPMode()
+ }
}
fun updateTheme(act: Activity) {
val settingsManager = PreferenceManager.getDefaultSharedPreferences(act)
if (settingsManager
- .getString(act.getString(R.string.app_theme_key), "AmoledLight") == "System"
- && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
- ) {
+ .getString(act.getString(R.string.app_theme_key), "AmoledLight") == "System"
+ && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
loadThemes(act)
}
}
@@ -350,10 +315,6 @@ object CommonActivity {
"Monet" -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
R.style.MonetMode else R.style.AppTheme
- "Dracula" -> R.style.DraculaMode
- "Lavender" -> R.style.LavenderMode
- "SilentBlue" -> R.style.SilentBlueMode
-
else -> R.style.AppTheme
}
@@ -386,13 +347,9 @@ object CommonActivity {
else -> R.style.OverlayPrimaryColorNormal
}
-
act.theme.applyStyle(currentTheme, true)
act.theme.applyStyle(currentOverlayTheme, true)
- appliedTheme = currentTheme
- appliedColor = currentOverlayTheme
- act.updateTv()
- if (isLayout(TV)) act.theme.applyStyle(R.style.AppThemeTvOverlay, true)
+
act.theme.applyStyle(
R.style.LoadedStyle,
true
@@ -423,7 +380,8 @@ object CommonActivity {
private fun View.hasContent(): Boolean {
return isShown && when (this) {
- is ViewGroup -> this.isNotEmpty()
+ //is RecyclerView -> this.childCount > 0
+ is ViewGroup -> this.childCount > 0
else -> true
}
}
@@ -453,7 +411,7 @@ object CommonActivity {
// if cant focus but visible then break and let android decide
// the exception if is the view is a parent and has children that wants focus
val hasChildrenThatWantsFocus = (next as? ViewGroup)?.let { parent ->
- parent.descendantFocusability == ViewGroup.FOCUS_AFTER_DESCENDANTS && parent.isNotEmpty()
+ parent.descendantFocusability == ViewGroup.FOCUS_AFTER_DESCENDANTS && parent.childCount > 0
} ?: false
if (!next.isFocusable && shown && !hasChildrenThatWantsFocus) return null
@@ -531,8 +489,84 @@ object CommonActivity {
}
- fun onKeyDown(act: Activity?, keyCode: Int, event: KeyEvent?): Boolean? {
- return null
+ fun onKeyDown(act: Activity?, keyCode: Int, event: KeyEvent?) {
+
+ // 149 keycode_numpad 5
+ when (keyCode) {
+ KeyEvent.KEYCODE_FORWARD, KeyEvent.KEYCODE_D, KeyEvent.KEYCODE_MEDIA_SKIP_FORWARD, KeyEvent.KEYCODE_MEDIA_FAST_FORWARD -> {
+ PlayerEventType.SeekForward
+ }
+
+ KeyEvent.KEYCODE_A, KeyEvent.KEYCODE_MEDIA_SKIP_BACKWARD, KeyEvent.KEYCODE_MEDIA_REWIND -> {
+ PlayerEventType.SeekBack
+ }
+
+ KeyEvent.KEYCODE_MEDIA_NEXT, KeyEvent.KEYCODE_BUTTON_R1, KeyEvent.KEYCODE_N, KeyEvent.KEYCODE_NUMPAD_2, KeyEvent.KEYCODE_CHANNEL_UP -> {
+ PlayerEventType.NextEpisode
+ }
+
+ KeyEvent.KEYCODE_MEDIA_PREVIOUS, KeyEvent.KEYCODE_BUTTON_L1, KeyEvent.KEYCODE_B, KeyEvent.KEYCODE_NUMPAD_1, KeyEvent.KEYCODE_CHANNEL_DOWN -> {
+ PlayerEventType.PrevEpisode
+ }
+
+ KeyEvent.KEYCODE_MEDIA_PAUSE -> {
+ PlayerEventType.Pause
+ }
+
+ KeyEvent.KEYCODE_MEDIA_PLAY, KeyEvent.KEYCODE_BUTTON_START -> {
+ PlayerEventType.Play
+ }
+
+ KeyEvent.KEYCODE_L, KeyEvent.KEYCODE_NUMPAD_7, KeyEvent.KEYCODE_7 -> {
+ PlayerEventType.Lock
+ }
+
+ KeyEvent.KEYCODE_H, KeyEvent.KEYCODE_MENU -> {
+ PlayerEventType.ToggleHide
+ }
+
+ KeyEvent.KEYCODE_M, KeyEvent.KEYCODE_VOLUME_MUTE -> {
+ PlayerEventType.ToggleMute
+ }
+
+ KeyEvent.KEYCODE_S, KeyEvent.KEYCODE_NUMPAD_9, KeyEvent.KEYCODE_9 -> {
+ PlayerEventType.ShowMirrors
+ }
+ // OpenSubtitles shortcut
+ KeyEvent.KEYCODE_O, KeyEvent.KEYCODE_NUMPAD_8, KeyEvent.KEYCODE_8 -> {
+ PlayerEventType.SearchSubtitlesOnline
+ }
+
+ KeyEvent.KEYCODE_E, KeyEvent.KEYCODE_NUMPAD_3, KeyEvent.KEYCODE_3 -> {
+ PlayerEventType.ShowSpeed
+ }
+
+ KeyEvent.KEYCODE_R, KeyEvent.KEYCODE_NUMPAD_0, KeyEvent.KEYCODE_0 -> {
+ PlayerEventType.Resize
+ }
+
+ KeyEvent.KEYCODE_C, KeyEvent.KEYCODE_NUMPAD_4, KeyEvent.KEYCODE_4 -> {
+ PlayerEventType.SkipOp
+ }
+
+ KeyEvent.KEYCODE_V, KeyEvent.KEYCODE_NUMPAD_5, KeyEvent.KEYCODE_5 -> {
+ PlayerEventType.SkipCurrentChapter
+ }
+
+ KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, KeyEvent.KEYCODE_P, KeyEvent.KEYCODE_SPACE, KeyEvent.KEYCODE_NUMPAD_ENTER, KeyEvent.KEYCODE_ENTER -> { // space is not captured due to navigation
+ PlayerEventType.PlayPauseToggle
+ }
+
+ else -> null
+ }?.let { playerEvent ->
+ playerEventListener?.invoke(playerEvent)
+ }
+
+ //when (keyCode) {
+ // KeyEvent.KEYCODE_DPAD_CENTER -> {
+ // println("DPAD PRESSED")
+ // }
+ //}
}
/** overrides focus and custom key events */
@@ -569,7 +603,6 @@ object CommonActivity {
else -> null
}
-
// println("NEXT FOCUS : $nextView")
if (nextView != null) {
nextView.requestFocus()
@@ -577,15 +610,10 @@ object CommonActivity {
return true
}
- // TODO: Figure out why removing the check for SearchAutoComplete seems
- // to break focus on TV as it shouldn't need to be used.
- // Also handle KEYCODE_ENTER here because some remotes (e.g. LG Magic Remote)
- // send KEYCODE_ENTER instead of KEYCODE_DPAD_CENTER when clicking the OK button.
- @SuppressLint("RestrictedApi")
- if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) &&
+ if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER &&
(act.currentFocus is SearchView || act.currentFocus is SearchView.SearchAutoComplete)
) {
- showInputMethod(act.currentFocus?.findFocus())
+ UIHelper.showInputMethod(act.currentFocus?.findFocus())
}
//println("Keycode: $keyCode")
@@ -594,6 +622,7 @@ object CommonActivity {
// "Got Keycode $keyCode | ${KeyEvent.keyCodeToString(keyCode)} \n ${event?.action}",
// Toast.LENGTH_LONG
//)
+
}
// if someone else want to override the focus then don't handle the event as it is already
@@ -603,4 +632,4 @@ object CommonActivity {
}
return null
}
-}
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/HeaderDecorationBindingAdapter.kt b/app/src/main/java/com/lagradost/cloudstream3/HeaderDecorationBindingAdapter.kt
new file mode 100644
index 000000000..045a7963a
--- /dev/null
+++ b/app/src/main/java/com/lagradost/cloudstream3/HeaderDecorationBindingAdapter.kt
@@ -0,0 +1,11 @@
+package com.lagradost.cloudstream3
+
+import android.view.LayoutInflater
+import androidx.annotation.LayoutRes
+import androidx.recyclerview.widget.RecyclerView
+import com.lagradost.cloudstream3.ui.HeaderViewDecoration
+
+fun setHeaderDecoration(view: RecyclerView, @LayoutRes headerViewRes: Int) {
+ val headerView = LayoutInflater.from(view.context).inflate(headerViewRes, null)
+ view.addItemDecoration(HeaderViewDecoration(headerView))
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/MainActivity.kt b/app/src/main/java/com/lagradost/cloudstream3/MainActivity.kt
index 5d39f6554..0d0a56a92 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/MainActivity.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/MainActivity.kt
@@ -2,17 +2,16 @@ package com.lagradost.cloudstream3
import android.animation.ValueAnimator
import android.annotation.SuppressLint
-import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.res.ColorStateList
import android.content.res.Configuration
import android.graphics.Rect
+import android.net.Uri
import android.os.Bundle
import android.util.AttributeSet
import android.util.Log
-import android.view.Gravity
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
@@ -23,16 +22,15 @@ import android.widget.CheckBox
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.Toast
+import androidx.activity.OnBackPressedCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.annotation.IdRes
import androidx.annotation.MainThread
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
-import androidx.core.content.edit
-import androidx.core.net.toUri
+import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.children
-import androidx.core.view.get
import androidx.core.view.isGone
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
@@ -50,7 +48,6 @@ import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
-import androidx.viewpager2.widget.ViewPager2
import com.google.android.gms.cast.framework.CastContext
import com.google.android.gms.cast.framework.Session
import com.google.android.gms.cast.framework.SessionManager
@@ -64,9 +61,9 @@ import com.jaredrummler.android.colorpicker.ColorPickerDialogListener
import com.lagradost.cloudstream3.APIHolder.allProviders
import com.lagradost.cloudstream3.APIHolder.apis
import com.lagradost.cloudstream3.APIHolder.initAll
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.removeKey
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
+import com.lagradost.cloudstream3.AcraApplication.Companion.getKey
+import com.lagradost.cloudstream3.AcraApplication.Companion.removeKey
+import com.lagradost.cloudstream3.AcraApplication.Companion.setKey
import com.lagradost.cloudstream3.CommonActivity.loadThemes
import com.lagradost.cloudstream3.CommonActivity.onColorSelectedEvent
import com.lagradost.cloudstream3.CommonActivity.onDialogDismissedEvent
@@ -82,28 +79,30 @@ import com.lagradost.cloudstream3.databinding.ActivityMainTvBinding
import com.lagradost.cloudstream3.databinding.BottomResultviewPreviewBinding
import com.lagradost.cloudstream3.mvvm.Resource
import com.lagradost.cloudstream3.mvvm.logError
-import com.lagradost.cloudstream3.mvvm.safe
+import com.lagradost.cloudstream3.mvvm.normalSafeApiCall
import com.lagradost.cloudstream3.mvvm.observe
import com.lagradost.cloudstream3.mvvm.observeNullable
import com.lagradost.cloudstream3.network.initClient
import com.lagradost.cloudstream3.plugins.PluginManager
-import com.lagradost.cloudstream3.plugins.PluginManager.___DO_NOT_CALL_FROM_A_PLUGIN_loadAllOnlinePlugins
+import com.lagradost.cloudstream3.plugins.PluginManager.loadAllOnlinePlugins
import com.lagradost.cloudstream3.plugins.PluginManager.loadSinglePlugin
import com.lagradost.cloudstream3.receivers.VideoDownloadRestartReceiver
import com.lagradost.cloudstream3.services.SubscriptionWorkManager
-import com.lagradost.cloudstream3.syncproviders.AccountManager
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.APP_STRING
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.APP_STRING_PLAYER
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.APP_STRING_REPO
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.APP_STRING_RESUME_WATCHING
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.APP_STRING_SEARCH
-import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.APP_STRING_SHARE
+import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.OAuth2Apis
+import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.accountManagers
+import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.inAppAuths
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.localListApi
import com.lagradost.cloudstream3.syncproviders.SyncAPI
import com.lagradost.cloudstream3.ui.APIRepository
import com.lagradost.cloudstream3.ui.SyncWatchType
import com.lagradost.cloudstream3.ui.WatchType
import com.lagradost.cloudstream3.ui.account.AccountHelper.showAccountSelectLinear
+import com.lagradost.cloudstream3.ui.account.AccountViewModel
import com.lagradost.cloudstream3.ui.download.DOWNLOAD_NAVIGATE_TO
import com.lagradost.cloudstream3.ui.home.HomeViewModel
import com.lagradost.cloudstream3.ui.library.LibraryViewModel
@@ -119,7 +118,6 @@ import com.lagradost.cloudstream3.ui.search.SearchResultBuilder
import com.lagradost.cloudstream3.ui.settings.Globals.EMULATOR
import com.lagradost.cloudstream3.ui.settings.Globals.PHONE
import com.lagradost.cloudstream3.ui.settings.Globals.TV
-import com.lagradost.cloudstream3.ui.settings.Globals.isLandscape
import com.lagradost.cloudstream3.ui.settings.Globals.isLayout
import com.lagradost.cloudstream3.ui.settings.Globals.updateTv
import com.lagradost.cloudstream3.ui.settings.SettingsGeneral
@@ -157,31 +155,24 @@ import com.lagradost.cloudstream3.utils.DataStoreHelper.accounts
import com.lagradost.cloudstream3.utils.DataStoreHelper.migrateResumeWatching
import com.lagradost.cloudstream3.utils.Event
import com.lagradost.cloudstream3.utils.ImageLoader.loadImage
-import com.lagradost.cloudstream3.utils.InAppUpdater.runAutoUpdate
+import com.lagradost.cloudstream3.utils.InAppUpdater.Companion.runAutoUpdate
import com.lagradost.cloudstream3.utils.SingleSelectionHelper.showBottomDialog
import com.lagradost.cloudstream3.utils.SnackbarHelper.showSnackbar
-import com.lagradost.cloudstream3.utils.TvChannelUtils
import com.lagradost.cloudstream3.utils.UIHelper.changeStatusBarState
import com.lagradost.cloudstream3.utils.UIHelper.checkWrite
+import com.lagradost.cloudstream3.utils.UIHelper.colorFromAttribute
import com.lagradost.cloudstream3.utils.UIHelper.dismissSafe
-import com.lagradost.cloudstream3.utils.UIHelper.enableEdgeToEdgeCompat
-import com.lagradost.cloudstream3.utils.UIHelper.fixSystemBarsPadding
import com.lagradost.cloudstream3.utils.UIHelper.getResourceColor
import com.lagradost.cloudstream3.utils.UIHelper.hideKeyboard
import com.lagradost.cloudstream3.utils.UIHelper.navigate
import com.lagradost.cloudstream3.utils.UIHelper.requestRW
-import com.lagradost.cloudstream3.utils.UIHelper.setNavigationBarColorCompat
-import com.lagradost.cloudstream3.utils.UIHelper.showProgress
import com.lagradost.cloudstream3.utils.UIHelper.toPx
import com.lagradost.cloudstream3.utils.USER_PROVIDER_API
import com.lagradost.cloudstream3.utils.USER_SELECTED_HOMEPAGE_API
-import com.lagradost.cloudstream3.utils.downloader.DownloadQueueManager
import com.lagradost.cloudstream3.utils.setText
import com.lagradost.cloudstream3.utils.setTextHtml
import com.lagradost.cloudstream3.utils.txt
import com.lagradost.safefile.SafeFile
-import kotlinx.coroutines.Job
-import kotlinx.coroutines.cancel
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.io.File
@@ -191,7 +182,6 @@ import java.net.URLDecoder
import java.nio.charset.Charset
import kotlin.math.abs
import kotlin.math.absoluteValue
-import kotlin.reflect.full.createInstance
import kotlin.system.exitProcess
class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCallback {
@@ -202,21 +192,6 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
const val ANIMATED_OUTLINE: Boolean = false
var lastError: String? = null
- /** Update lastError variable based on error file, to check if app crashed.
- * Can be called multiple times without changing the lastError variable changing.
- **/
- fun setLastError(context: Context) {
- if (lastError != null) return
-
- val errorFile = context.filesDir.resolve("last_error")
- if (errorFile.exists() && errorFile.isFile) {
- lastError = errorFile.readText(Charset.defaultCharset())
- errorFile.delete()
- } else {
- lastError = null
- }
- }
-
private const val FILE_DELETE_KEY = "FILES_TO_DELETE_KEY"
const val API_NAME_EXTRA_KEY = "API_NAME_EXTRA_KEY"
@@ -288,7 +263,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
// TODO MUCH BETTER HANDLING
// Invalid URIs can crash
- fun safeURI(uri: String) = safe { URI(uri) }
+ fun safeURI(uri: String) = normalSafeApiCall { URI(uri) }
if (str != null && this != null) {
if (str.startsWith("https://cs.repo")) {
@@ -297,29 +272,28 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
loadRepository(realUrl)
return true
} else if (str.contains(APP_STRING)) {
- for (api in AccountManager.allApis) {
- if (api.isValidRedirectUrl(str)) {
+ for (api in OAuth2Apis) {
+ if (str.contains("/${api.redirectUrl}")) {
ioSafe {
Log.i(TAG, "handleAppIntent $str")
- try {
- val isSuccessful = api.login(str)
- if (isSuccessful) {
- Log.i(TAG, "authenticated ${api.name}")
- } else {
- Log.i(TAG, "failed to authenticate ${api.name}")
+ val isSuccessful = api.handleRedirect(str)
+
+ if (isSuccessful) {
+ Log.i(TAG, "authenticated ${api.name}")
+ } else {
+ Log.i(TAG, "failed to authenticate ${api.name}")
+ }
+
+ this@with.runOnUiThread {
+ try {
+ showToast(
+ getString(if (isSuccessful) R.string.authenticated_user else R.string.authenticated_user_fail).format(
+ api.name
+ )
+ )
+ } catch (e: Exception) {
+ logError(e) // format might fail
}
- showToast(
- if (isSuccessful) {
- txt(R.string.authenticated_user, api.name)
- } else {
- txt(R.string.authenticated_user_fail, api.name)
- }
- )
- } catch (t: Throwable) {
- logError(t)
- showToast(
- txt(R.string.authenticated_user_fail, api.name)
- )
}
}
return true
@@ -328,11 +302,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
// This specific intent is used for the gradle deployWithAdb
// https://github.com/recloudstream/gradle/blob/master/src/main/kotlin/com/lagradost/cloudstream3/gradle/tasks/DeployWithAdbTask.kt#L46
if (str == "$APP_STRING:") {
- ioSafe {
- PluginManager.___DO_NOT_CALL_FROM_A_PLUGIN_hotReloadAllLocalPlugins(
- activity
- )
- }
+ PluginManager.hotReloadAllLocalPlugins(activity)
}
} else if (safeURI(str)?.scheme == APP_STRING_REPO) {
val url = str.replaceFirst(APP_STRING_REPO, "https")
@@ -354,7 +324,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
activity?.findViewById(R.id.nav_rail_view)?.selectedItemId =
R.id.navigation_search
} else if (safeURI(str)?.scheme == APP_STRING_PLAYER) {
- val uri = str.toUri()
+ val uri = Uri.parse(str)
val name = uri.getQueryParameter("name")
val url = URLDecoder.decode(uri.authority, "UTF-8")
@@ -364,8 +334,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
LinkGenerator(
listOf(BasicLink(url, name)),
extract = true,
- id = url.hashCode()
- ), 0
+ )
)
)
} else if (safeURI(str)?.scheme == APP_STRING_RESUME_WATCHING) {
@@ -381,20 +350,6 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
START_ACTION_RESUME_LATEST
)
}
- } else if (str.startsWith(APP_STRING_SHARE)) {
- try {
- val data = str.substringAfter("$APP_STRING_SHARE:")
- val parts = data.split("?", limit = 2)
- loadResult(
- String(base64DecodeArray(parts[1]), Charsets.UTF_8),
- String(base64DecodeArray(parts[0]), Charsets.UTF_8),
- ""
- )
- return true
- } catch (e: Exception) {
- showToast("Invalid Uri", Toast.LENGTH_SHORT)
- return false
- }
} else if (!isWebview) {
if (str.startsWith(DOWNLOAD_NAVIGATE_TO)) {
this.navigate(R.id.navigation_downloads)
@@ -410,39 +365,22 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
return true
}
- val matchedApi = apis.filter { str.startsWith(it.mainUrl) }.firstOrNull()
- if (matchedApi != null) {
- loadResult(str, matchedApi.name, "")
- return true
+ synchronized(apis) {
+ for (api in apis) {
+ if (str.startsWith(api.mainUrl)) {
+ loadResult(str, api.name, "")
+ return true
+ }
+ }
}
}
}
}
return false
}
-
-
- fun centerView(view: View?) {
- if (view == null) return
- try {
- Log.v(TAG, "centerView: $view")
- val r = Rect(0, 0, 0, 0)
- view.getDrawingRect(r)
- val x = r.centerX()
- val y = r.centerY()
- val dx = r.width() / 2 //screenWidth / 2
- val dy = screenHeight / 2
- val r2 = Rect(x - dx, y - dy, x + dx, y + dy)
- view.requestRectangleOnScreen(r2, false)
- // TvFocus.current =TvFocus.current.copy(y=y.toFloat())
- } catch (_: Throwable) {
- }
- }
}
-
var lastPopup: SearchResponse? = null
- var lastPopupJob: Job? = null
fun loadPopup(result: SearchResponse, load: Boolean = true) {
lastPopup = result
val syncName = syncViewModel.syncName(result.apiName)
@@ -458,8 +396,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
syncViewModel.clear()
}
- lastPopupJob?.cancel()
- lastPopupJob = if (load) {
+ if (load) {
viewModel.load(
this, result.url, result.apiName, false, if (getApiDubstatusSettings()
.contains(DubStatus.Dubbed)
@@ -506,7 +443,6 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
R.id.navigation_downloads,
R.id.navigation_settings,
R.id.navigation_download_child,
- R.id.navigation_download_queue,
R.id.navigation_subtitles,
R.id.navigation_chrome_subtitles,
R.id.navigation_settings_player,
@@ -521,7 +457,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
).contains(destination.id)
- /*val dontPush = listOf(
+ val dontPush = listOf(
R.id.navigation_home,
R.id.navigation_search,
R.id.navigation_results_phone,
@@ -552,19 +488,25 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
}
layoutParams = params
- }*/
+ }
+
+ val landscape = when (resources.configuration.orientation) {
+ Configuration.ORIENTATION_LANDSCAPE -> {
+ true
+ }
+
+ Configuration.ORIENTATION_PORTRAIT -> {
+ isLayout(TV or EMULATOR)
+ }
+
+ else -> {
+ false
+ }
+ }
binding?.apply {
- navRailView.isVisible = isNavVisible && isLandscape()
- navView.isVisible = isNavVisible && !isLandscape()
- navHostFragment.apply {
- val marginPx = resources.getDimensionPixelSize(R.dimen.nav_rail_view_width)
- layoutParams =
- (navHostFragment.layoutParams as ViewGroup.MarginLayoutParams).apply {
- marginStart =
- if (isNavVisible && isLandscape() && isLayout(TV or EMULATOR)) marginPx else 0
- }
- }
+ navRailView.isVisible = isNavVisible && landscape
+ navView.isVisible = isNavVisible && !landscape
/**
* We need to make sure if we return to a sub-fragment,
@@ -572,15 +514,10 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
* highlight the wrong one in UI.
*/
when (destination.id) {
- in listOf(
- R.id.navigation_downloads,
- R.id.navigation_download_child,
- R.id.navigation_download_queue
- ) -> {
+ in listOf(R.id.navigation_downloads, R.id.navigation_download_child) -> {
navRailView.menu.findItem(R.id.navigation_downloads).isChecked = true
navView.menu.findItem(R.id.navigation_downloads).isChecked = true
}
-
in listOf(
R.id.navigation_settings,
R.id.navigation_subtitles,
@@ -667,11 +604,18 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
}
}
- override fun dispatchKeyEvent(event: KeyEvent): Boolean =
- CommonActivity.dispatchKeyEvent(this, event) ?: super.dispatchKeyEvent(event)
+ override fun dispatchKeyEvent(event: KeyEvent): Boolean {
+ val response = CommonActivity.dispatchKeyEvent(this, event)
+ if (response != null)
+ return response
+ return super.dispatchKeyEvent(event)
+ }
- override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean =
- CommonActivity.onKeyDown(this, keyCode, event) ?: super.onKeyDown(keyCode, event)
+ override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
+ CommonActivity.onKeyDown(this, keyCode, event)
+
+ return super.onKeyDown(keyCode, event)
+ }
override fun onUserLeaveHint() {
@@ -698,9 +642,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
.setNegativeButton(R.string.no) { _, _ -> /*NO-OP*/ }
.setPositiveButton(R.string.yes) { _, _ ->
if (dontShowAgainCheck.isChecked) {
- settingsManager.edit(commit = true) {
- putInt(getString(R.string.confirm_exit_key), 1)
- }
+ settingsManager.edit().putInt(getString(R.string.confirm_exit_key), 1).commit()
}
// finish() causes a bug on some TVs where player
// may keep playing after closing the app.
@@ -725,11 +667,10 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
broadcastIntent.setClass(this, VideoDownloadRestartReceiver::class.java)
this.sendBroadcast(broadcastIntent)
afterPluginsLoadedEvent -= ::onAllPluginsLoaded
- detachBackPressedCallback("MainActivityDefault")
super.onDestroy()
}
- override fun onNewIntent(intent: Intent) {
+ override fun onNewIntent(intent: Intent?) {
handleAppIntent(intent)
super.onNewIntent(intent)
}
@@ -738,54 +679,13 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
if (intent == null) return
val str = intent.dataString
loadCache()
-
handleAppIntentUrl(this, str, false, intent.extras)
}
private fun NavDestination.matchDestination(@IdRes destId: Int): Boolean =
hierarchy.any { it.id == destId }
- private var lastNavTime = 0L
private fun onNavDestinationSelected(item: MenuItem, navController: NavController): Boolean {
- val currentTime = System.currentTimeMillis()
- // safeDebounce: Check if a previous tap happened within the last 400ms
- if (currentTime - lastNavTime < 400) return false
- lastNavTime = currentTime
-
- val destinationId = item.itemId
-
- // Check if we are already at the selected destination
- if (navController.currentDestination?.id == destinationId) return false
-
- // Make all nav buttons focus on this specific view when nextFocusRightId
- val targetView = when (destinationId) {
- // Please note that if R.id.navigation_home is readded, then it will only take affect when
- // navigation to home for the second time as onNavDestinationSelected will not get called
- // when first loading up the app
-
- // R.id.navigation_home -> R.id.home_preview_change_api
- R.id.navigation_search -> R.id.main_search
- R.id.navigation_library -> R.id.main_search
- R.id.navigation_downloads -> R.id.download_appbar
- else -> null
- }
- if (targetView != null && isLayout(TV or EMULATOR)) {
- val fromView = binding?.navRailView
- if (fromView != null) {
- fromView.nextFocusRightId = targetView
-
- for (focusView in arrayOf(
- R.id.navigation_downloads,
- R.id.navigation_home,
- R.id.navigation_search,
- R.id.navigation_library,
- R.id.navigation_settings,
- )) {
- fromView.findViewById(focusView)?.nextFocusRightId = targetView
- }
- }
- }
-
val builder = NavOptions.Builder().setLaunchSingleTop(true).setRestoreState(true)
.setEnterAnim(R.anim.enter_anim)
.setExitAnim(R.anim.exit_anim)
@@ -798,11 +698,11 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
saveState = true
)
}
+ val options = builder.build()
return try {
- navController.navigate(destinationId, null, builder.build())
- navController.currentDestination?.matchDestination(destinationId) == true
+ navController.navigate(item.itemId, null, options)
+ navController.currentDestination?.matchDestination(item.itemId) == true
} catch (e: IllegalArgumentException) {
- Log.e("NavigationError", "Failed to navigate: ${e.message}")
false
}
}
@@ -811,29 +711,25 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
private fun onAllPluginsLoaded(success: Boolean = false) {
ioSafe {
pluginsLock.withLock {
- allProviders.withLock {
+ synchronized(allProviders) {
// Load cloned sites after plugins have been loaded since clones depend on plugins.
try {
getKey>(USER_PROVIDER_API)?.let { list ->
list.forEach { custom ->
- allProviders.firstOrNull {
- it::class.simpleName == custom.parentClassName
- }?.let {
- allProviders.add(
- it::class.createInstance().apply {
+ allProviders.firstOrNull { it.javaClass.simpleName == custom.parentJavaClass }
+ ?.let {
+ allProviders.add(it.javaClass.getDeclaredConstructor().newInstance().apply {
name = custom.name
lang = custom.lang
mainUrl = custom.url.trimEnd('/')
canBeOverridden = false
- }
- )
- }
+ })
+ }
}
}
// it.hashCode() is not enough to make sure they are distinct
- apis = allProviders.distinctBy {
- it.lang + it.name + it.mainUrl + it::class.qualifiedName
- }
+ apis =
+ allProviders.distinctBy { it.lang + it.name + it.mainUrl + it.javaClass.name }
APIHolder.apiMap = null
} catch (e: Exception) {
logError(e)
@@ -846,6 +742,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
lateinit var viewModel: ResultViewModel2
lateinit var syncViewModel: SyncViewModel
private var libraryViewModel: LibraryViewModel? = null
+ private var accountViewModel: AccountViewModel? = null
/** kinda dirty, however it signals that we should use the watch status as sync or not*/
var isLocalList: Boolean = false
@@ -859,37 +756,20 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
private fun hidePreviewPopupDialog() {
bottomPreviewPopup.dismissSafe(this)
- lastPopupJob?.cancel()
- lastPopupJob = null
bottomPreviewPopup = null
bottomPreviewBinding = null
}
- private var bottomPreviewPopup: Dialog? = null
+ private var bottomPreviewPopup: BottomSheetDialog? = null
private var bottomPreviewBinding: BottomResultviewPreviewBinding? = null
private fun showPreviewPopupDialog(): BottomResultviewPreviewBinding {
val ret = (bottomPreviewBinding ?: run {
-
- val builder: Dialog
- val layout: Int
-
- if (isLayout(PHONE)) {
- builder =
- BottomSheetDialog(this)
- layout = R.layout.bottom_resultview_preview
- } else {
- builder =
- Dialog(this, R.style.DialogHalfFullscreen)
- layout = R.layout.bottom_resultview_preview_tv
- // No way to do this in styles :(
- builder.window?.setGravity(Gravity.CENTER_VERTICAL or Gravity.END)
- }
-
- val root = layoutInflater.inflate(layout, null, false)
- val binding = BottomResultviewPreviewBinding.bind(root)
-
+ val builder =
+ BottomSheetDialog(this)
+ val binding: BottomResultviewPreviewBinding =
+ BottomResultviewPreviewBinding.inflate(builder.layoutInflater, null, false)
bottomPreviewBinding = binding
- builder.setContentView(root)
+ builder.setContentView(binding.root)
builder.setOnDismissListener {
bottomPreviewPopup = null
bottomPreviewBinding = null
@@ -1180,14 +1060,34 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
}
}
- override fun onCreate(savedInstanceState: Bundle?) {
- app.initClient(this, ignoreSSL = false)
- @OptIn(UnsafeSSL::class)
- insecureApp.initClient(this, ignoreSSL = true)
+ private fun centerView(view: View?) {
+ if (view == null) return
+ try {
+ Log.v(TAG, "centerView: $view")
+ val r = Rect(0, 0, 0, 0)
+ view.getDrawingRect(r)
+ val x = r.centerX()
+ val y = r.centerY()
+ val dx = r.width() / 2 //screenWidth / 2
+ val dy = screenHeight / 2
+ val r2 = Rect(x - dx, y - dy, x + dx, y + dy)
+ view.requestRectangleOnScreen(r2, false)
+ // TvFocus.current =TvFocus.current.copy(y=y.toFloat())
+ } catch (_: Throwable) {
+ }
+ }
+ override fun onCreate(savedInstanceState: Bundle?) {
+ app.initClient(this)
val settingsManager = PreferenceManager.getDefaultSharedPreferences(this)
- setLastError(this)
+ val errorFile = filesDir.resolve("last_error")
+ if (errorFile.exists() && errorFile.isFile) {
+ lastError = errorFile.readText(Charset.defaultCharset())
+ errorFile.delete()
+ } else {
+ lastError = null
+ }
val settingsForProvider = SettingsJson()
settingsForProvider.enableAdult =
@@ -1196,14 +1096,11 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
MainAPI.settingsForProvider = settingsForProvider
loadThemes(this)
- enableEdgeToEdgeCompat()
- setNavigationBarColorCompat(R.attr.primaryGrayBackground)
updateLocale()
super.onCreate(savedInstanceState)
try {
if (isCastApiAvailable()) {
- CastContext.getSharedInstance(this) { it.run() }
- .addOnSuccessListener { mSessionManager = it.sessionManager }
+ CastContext.getSharedInstance(this) {it.run()}.addOnSuccessListener { mSessionManager = it.sessionManager }
}
} catch (t: Throwable) {
logError(t)
@@ -1213,17 +1110,15 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
updateTv()
// backup when we update the app, I don't trust myself to not boot lock users, might want to make this a setting?
- safe {
+ normalSafeApiCall {
val appVer = BuildConfig.VERSION_NAME
- val lastAppAutoBackup: String = getKey("VERSION_NAME") ?: ""
+ val lastAppAutoBackup: String = getKey("VERSION_NAME") ?: ""
if (appVer != lastAppAutoBackup) {
setKey("VERSION_NAME", BuildConfig.VERSION_NAME)
- if (lastAppAutoBackup.isEmpty()) return@safe
-
- safe {
+ normalSafeApiCall {
backup(this)
}
- safe {
+ normalSafeApiCall {
// Recompile oat on new version
PluginManager.deleteAllOatFiles(this)
}
@@ -1251,7 +1146,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
if (isLayout(TV)) {
// Put here any button you don't want focusing it to center the view
val exceptionButtons = listOf(
- //R.id.home_preview_play_btt,
+ R.id.home_preview_play_btt,
R.id.home_preview_info_btt,
R.id.home_preview_hidden_next_focus,
R.id.home_preview_hidden_prev_focus,
@@ -1283,26 +1178,6 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
null
}
- binding?.apply {
- fixSystemBarsPadding(
- navView,
- heightResId = R.dimen.nav_view_height,
- padTop = false,
- overlayCutout = false
- )
-
- fixSystemBarsPadding(
- navRailView,
- widthResId = R.dimen.nav_rail_view_width,
- padRight = false,
- padTop = false
- )
- }
-
- // overscan
- val padding = settingsManager.getInt(getString(R.string.overscan_key), 0).toPx
- binding?.homeRoot?.setPadding(padding, padding, padding, padding)
-
changeStatusBarState(isLayout(EMULATOR))
/** Biometric stuff for users without accounts **/
@@ -1344,7 +1219,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
ioSafe { SafeFile.check(this@MainActivity) }
if (PluginManager.checkSafeModeFile()) {
- safe {
+ normalSafeApiCall {
showToast(R.string.safe_mode_file, Toast.LENGTH_LONG)
}
} else if (lastError == null) {
@@ -1361,11 +1236,9 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
true
)
) {
- PluginManager.___DO_NOT_CALL_FROM_A_PLUGIN_updateAllOnlinePluginsAndLoadThem(
- this@MainActivity
- )
+ PluginManager.updateAllOnlinePluginsAndLoadThem(this@MainActivity)
} else {
- ___DO_NOT_CALL_FROM_A_PLUGIN_loadAllOnlinePlugins(this@MainActivity)
+ loadAllOnlinePlugins(this@MainActivity)
}
//Automatically download not existing plugins, using mode specified.
@@ -1376,7 +1249,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
)
) ?: AutoDownloadMode.Disable
if (autoDownloadPlugin != AutoDownloadMode.Disable) {
- PluginManager.___DO_NOT_CALL_FROM_A_PLUGIN_downloadNotExistingPluginsAndLoad(
+ PluginManager.downloadNotExistingPluginsAndLoad(
this@MainActivity,
autoDownloadPlugin
)
@@ -1384,14 +1257,8 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
}
ioSafe {
- PluginManager.___DO_NOT_CALL_FROM_A_PLUGIN_loadAllLocalPlugins(
- this@MainActivity,
- false
- )
+ PluginManager.loadAllLocalPlugins(this@MainActivity, false)
}
-
-// Add your channel creation here
-
}
} else {
val builder: AlertDialog.Builder = AlertDialog.Builder(this)
@@ -1429,9 +1296,8 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
else -> {
resultviewPreviewBookmark.isEnabled = false
- resultviewPreviewBookmark.showProgress()
- //resultviewPreviewBookmark.setIconResource(R.drawable.ic_baseline_bookmark_border_24)
- //resultviewPreviewBookmark.setText(R.string.loading)
+ resultviewPreviewBookmark.setIconResource(R.drawable.ic_baseline_bookmark_border_24)
+ resultviewPreviewBookmark.setText(R.string.loading)
}
}
}
@@ -1517,17 +1383,9 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
resultviewPreviewMetaRating.setText(d.ratingText)
resultviewPreviewDescription.setTextHtml(d.plotText)
- if (isLayout(PHONE)) {
- resultviewPreviewPoster.loadImage(
- d.posterImage ?: d.posterBackgroundImage,
- headers = d.posterHeaders
- )
- } else {
- resultviewPreviewPoster.loadImage(
- d.posterBackgroundImage ?: d.posterImage,
- headers = d.posterHeaders
- )
- }
+ resultviewPreviewPoster.loadImage(
+ d.posterImage ?: d.posterBackgroundImage
+ )
setUserData(syncViewModel.userData.value)
setWatchStatus(viewModel.watchStatus.value)
@@ -1630,6 +1488,18 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
// init accounts
ioSafe {
+ for (api in accountManagers) {
+ api.init()
+ }
+
+ inAppAuths.amap { api ->
+ try {
+ api.initialize()
+ } catch (e: Exception) {
+ logError(e)
+ }
+ }
+
// we need to run this after we init all apis, otherwise currentSyncApi will fuck itself
this@MainActivity.runOnUiThread {
// Change library icon with logo of current api in sync
@@ -1657,7 +1527,9 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
ioSafe {
initAll()
// No duplicates (which can happen by registerMainAPI)
- apis = allProviders.distinctBy { it }
+ apis = synchronized(allProviders) {
+ allProviders.distinctBy { it }
+ }
}
// val navView: BottomNavigationView = findViewById(R.id.nav_view)
@@ -1680,6 +1552,10 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
if (navDestination.matchDestination(R.id.navigation_home)) {
attachBackPressedCallback("MainActivity") {
showConfirmExitDialog(settingsManager)
+ @Suppress("DEPRECATION")
+ window?.navigationBarColor =
+ colorFromAttribute(R.attr.primaryGrayBackground)
+ updateLocale()
}
} else detachBackPressedCallback("MainActivity")
}
@@ -1707,27 +1583,17 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
navController
)
}
-
}
binding?.navRailView?.apply {
- if (isLayout(PHONE)) {
- itemRippleColor = rippleColor
- itemActiveIndicatorColor = rippleColor
- } else {
- val rippleColor = ColorStateList.valueOf(getResourceColor(R.attr.textColor, 1.0f))
- val rippleColorTransparent =
- ColorStateList.valueOf(getResourceColor(R.attr.textColor, 0.2f))
- itemSpacing = 12.toPx // expandedItemSpacing does not have an attr
- itemRippleColor = rippleColorTransparent
- itemActiveIndicatorColor = rippleColor
- }
+ itemRippleColor = rippleColor
+ itemActiveIndicatorColor = rippleColor
setupWithNavController(navController)
- /*if (isLayout(TV or EMULATOR)) {
+ if (isLayout(TV or EMULATOR)) {
background?.alpha = 200
} else {
background?.alpha = 255
- }*/
+ }
setOnItemSelectedListener { item ->
onNavDestinationSelected(
@@ -1736,7 +1602,6 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
)
}
-
fun noFocus(view: View) {
view.tag = view.context.getString(R.string.tv_no_focus_tag)
(view as? ViewGroup)?.let {
@@ -1775,104 +1640,6 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
}
}
- val rail = binding?.navRailView
- if (rail != null) {
- binding?.navRailView?.labelVisibilityMode =
- NavigationRailView.LABEL_VISIBILITY_UNLABELED
- //val focus = mutableSetOf()
-
- var prevId: Int? = null
- var prevView: View? = null
-
- // The genius engineers at google did not actually
- // write a nextFocus for the navrail
- rail.findViewById(R.id.navigation_settings)?.nextFocusDownId =
- R.id.nav_footer_profile_card
- for (id in arrayOf(
- R.id.navigation_home,
- R.id.navigation_search,
- R.id.navigation_library,
- R.id.navigation_downloads,
- R.id.navigation_settings
- )) {
- val view = rail.findViewById(id) ?: continue
- prevId?.let { view.nextFocusUpId = it }
- prevView?.nextFocusDownId = id
-
- prevView = view
- prevId = id
- // Uncomment for focus expand
- /*if (!isLayout(TV)) {
- view.onFocusChangeListener = null
- } else {
- view.onFocusChangeListener =
- View.OnFocusChangeListener { v, hasFocus ->
- if (hasFocus) {
- focus += id
- binding?.navRailView?.labelVisibilityMode =
- NavigationRailView.LABEL_VISIBILITY_LABELED
- binding?.navRailView?.expand()
- } else {
- focus -= id
- v.post {
- if (focus.isEmpty()) {
- binding?.navRailView?.labelVisibilityMode =
- NavigationRailView.LABEL_VISIBILITY_UNLABELED
- binding?.navRailView?.collapse()
- }
- }
- }
- }
- }*/
- }
- }
-
- // Navigation button long click functionality to scroll to top
- for (view in listOf(binding?.navView, binding?.navRailView)) {
- view?.findViewById(R.id.navigation_home)?.setOnLongClickListener {
- val recycler = binding?.root?.findViewById(R.id.home_master_recycler)
- recycler?.smoothScrollToPosition(0)
- return@setOnLongClickListener recycler != null
- }
-
- view?.findViewById(R.id.navigation_library)?.setOnLongClickListener {
- val viewPager = binding?.root?.findViewById(R.id.viewpager)
- ?: return@setOnLongClickListener false
- try {
- val children = (viewPager[0] as? RecyclerView)?.children
- ?: return@setOnLongClickListener false
- for (child in children) {
- child.findViewById(R.id.page_recyclerview)
- ?.smoothScrollToPosition(0)
- }
- } catch (_: IndexOutOfBoundsException) {
- } catch (t: Throwable) {
- logError(t)
- }
- return@setOnLongClickListener true
- }
-
- view?.findViewById(R.id.navigation_search)?.setOnLongClickListener {
- for (recyclerId in arrayOf(
- R.id.search_master_recycler,
- R.id.search_autofit_results,
- R.id.search_history_recycler
- )) {
- val recycler = binding?.root?.findViewById(recyclerId)
- ?: return@setOnLongClickListener false
- recycler.smoothScrollToPosition(0)
- }
- return@setOnLongClickListener true
- }
-
- view?.findViewById(R.id.navigation_downloads)?.setOnLongClickListener {
- val recycler: RecyclerView? = binding?.root?.findViewById(R.id.download_list)
- ?: binding?.root?.findViewById(R.id.download_child_list)
- recycler?.smoothScrollToPosition(0)
- return@setOnLongClickListener recycler != null
- }
- }
-
loadCache()
updateHasTrailers()
/*nav_view.setOnNavigationItemSelectedListener { item ->
@@ -1939,7 +1706,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
fun buildMediaQueueItem(video: String): MediaQueueItem {
// val movieMetadata = MediaMetadata(MediaMetadata.MEDIA_TYPE_PHOTO)
//movieMetadata.putString(MediaMetadata.KEY_TITLE, "CloudStream")
- val mediaInfo = MediaInfo.Builder(video.toUri().toString())
+ val mediaInfo = MediaInfo.Builder(Uri.parse(video).toString())
.setStreamType(MediaInfo.STREAM_TYPE_NONE)
.setContentType(MimeTypes.IMAGE_JPEG)
// .setMetadata(movieMetadata).build()
@@ -1965,7 +1732,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
if (BuildConfig.DEBUG) {
var providersAndroidManifestString = "Current androidmanifest should be:\n"
- allProviders.withLock {
+ synchronized(allProviders) {
for (api in allProviders) {
providersAndroidManifestString += "(USER_SELECTED_HOMEPAGE_API)?.let { homepage ->
DataStoreHelper.currentHomePage = homepage
removeKey(USER_SELECTED_HOMEPAGE_API)
}
try {
- if (getKey(HAS_DONE_SETUP_KEY, false) != true) {
+ if (getKey(HAS_DONE_SETUP_KEY, false) != true) {
navController.navigate(R.id.navigation_setup_language)
// If no plugins bring up extensions screen
} else if (PluginManager.getPluginsOnline().isEmpty()
@@ -2043,14 +1799,23 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
// }
// }
- attachBackPressedCallback("MainActivityDefault") {
- setNavigationBarColorCompat(R.attr.primaryGrayBackground)
- updateLocale()
- runDefault()
- }
+ onBackPressedDispatcher.addCallback(
+ this,
+ object : OnBackPressedCallback(true) {
+ override fun handleOnBackPressed() {
+ @Suppress("DEPRECATION")
+ window?.navigationBarColor = colorFromAttribute(R.attr.primaryGrayBackground)
+ updateLocale()
- // Start the download queue
- DownloadQueueManager.init(this)
+ // If we don't disable we end up in a loop with default behavior calling
+ // this callback as well, so we disable it, run default behavior,
+ // then re-enable this callback so it can be used for next back press.
+ isEnabled = false
+ onBackPressedDispatcher.onBackPressed()
+ isEnabled = true
+ }
+ }
+ )
}
/** Biometric stuff **/
@@ -2073,4 +1838,4 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
false
}
}
-}
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/AlwaysAskAction.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/AlwaysAskAction.kt
deleted file mode 100644
index a3c4040b5..000000000
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/AlwaysAskAction.kt
+++ /dev/null
@@ -1,26 +0,0 @@
-package com.lagradost.cloudstream3.actions
-
-import android.content.Context
-import com.lagradost.cloudstream3.R
-import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
-import com.lagradost.cloudstream3.ui.result.ResultEpisode
-import com.lagradost.cloudstream3.utils.txt
-
-class AlwaysAskAction : VideoClickAction() {
- override val name = txt(R.string.player_settings_always_ask)
- override val isPlayer = true
-
- // Only show in settings, not on a video
- override fun shouldShow(context: Context?, video: ResultEpisode?): Boolean = video == null
-
- override suspend fun runAction(
- context: Context?,
- video: ResultEpisode,
- result: LinkLoadingResult,
- index: Int?
- ) {
- // This is handled specially in ResultViewModel2.kt by detecting the AlwaysAskAction
- // and showing the player selection dialog instead of executing the action directly
- throw NotImplementedError("AlwaysAskAction is handled specially by the calling code")
- }
-}
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/OpenInAppAction.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/OpenInAppAction.kt
index ac912cbeb..cc64a6d39 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/OpenInAppAction.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/actions/OpenInAppAction.kt
@@ -6,8 +6,8 @@ import android.content.Context
import android.content.Intent
import androidx.core.content.FileProvider
import androidx.core.net.toUri
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
+import com.lagradost.cloudstream3.AcraApplication.Companion.getKey
+import com.lagradost.cloudstream3.AcraApplication.Companion.setKey
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
@@ -21,8 +21,7 @@ import java.io.File
fun updateDurationAndPosition(position: Long, duration: Long) {
if (position <= 0 || duration <= 0) return
- val episode = getKey("last_opened") ?: return
- DataStoreHelper.setViewPosAndResume(episode.id, position, duration, episode, null)
+ DataStoreHelper.setViewPos(getKey("last_opened_id"), position, duration)
ResultFragment.updateUI()
}
@@ -99,7 +98,7 @@ abstract class OpenInAppAction(
intent.component = ComponentName(packageName, intentClass)
}
putExtra(context, intent, video, result, index)
- setKey("last_opened", video)
+ setKey("last_opened_id", video.id)
launchResult(intent)
}
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/VideoClickAction.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/VideoClickAction.kt
index f4e8768d8..7e8b1c97b 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/VideoClickAction.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/actions/VideoClickAction.kt
@@ -12,63 +12,44 @@ import com.lagradost.cloudstream3.CommonActivity
import com.lagradost.cloudstream3.ErrorLoadingException
import com.lagradost.cloudstream3.MainActivity
import com.lagradost.cloudstream3.R
-import com.lagradost.cloudstream3.actions.temp.BiglyBTPackage
import com.lagradost.cloudstream3.actions.temp.CopyClipboardAction
-import com.lagradost.cloudstream3.actions.temp.JustPlayerPackage
-import com.lagradost.cloudstream3.actions.temp.LibreTorrentPackage
-import com.lagradost.cloudstream3.actions.temp.MpvExPackage
import com.lagradost.cloudstream3.actions.temp.MpvKtPackage
import com.lagradost.cloudstream3.actions.temp.MpvKtPreviewPackage
import com.lagradost.cloudstream3.actions.temp.MpvPackage
-import com.lagradost.cloudstream3.actions.temp.MpvRxPackage
import com.lagradost.cloudstream3.actions.temp.MpvYTDLPackage
-import com.lagradost.cloudstream3.actions.temp.NextPlayerPackage
-import com.lagradost.cloudstream3.actions.temp.OnlyPlayer
import com.lagradost.cloudstream3.actions.temp.PlayInBrowserAction
-import com.lagradost.cloudstream3.actions.temp.PlayMirrorAction
import com.lagradost.cloudstream3.actions.temp.ViewM3U8Action
-import com.lagradost.cloudstream3.actions.temp.VlcNightlyPackage
import com.lagradost.cloudstream3.actions.temp.VlcPackage
import com.lagradost.cloudstream3.actions.temp.WebVideoCastPackage
import com.lagradost.cloudstream3.actions.temp.fcast.FcastAction
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
import com.lagradost.cloudstream3.ui.result.ResultEpisode
-import com.lagradost.cloudstream3.utils.Coroutines.atomicListOf
-import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
-import com.lagradost.cloudstream3.utils.ExtractorLinkType
import com.lagradost.cloudstream3.utils.UiText
+import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
+import com.lagradost.cloudstream3.utils.Coroutines.threadSafeListOf
+import com.lagradost.cloudstream3.utils.ExtractorLinkType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.concurrent.Callable
import java.util.concurrent.FutureTask
+import kotlin.reflect.jvm.jvmName
object VideoClickActionHolder {
- val allVideoClickActions = atomicListOf(
+ val allVideoClickActions = threadSafeListOf(
// Default
PlayInBrowserAction(),
CopyClipboardAction(),
ViewM3U8Action(),
- PlayMirrorAction(),
// main support external apps
VlcPackage(),
MpvPackage(),
- MpvExPackage(),
- NextPlayerPackage(),
- JustPlayerPackage(),
FcastAction(),
- LibreTorrentPackage(),
- BiglyBTPackage(),
// forks/backup apps
- VlcNightlyPackage(),
WebVideoCastPackage(),
MpvYTDLPackage(),
MpvKtPackage(),
MpvKtPreviewPackage(),
- OnlyPlayer(),
- MpvRxPackage(),
- // Always Ask option
- AlwaysAskAction(),
// added by plugins
// ...
)
@@ -160,7 +141,7 @@ abstract class VideoClickAction {
}
}
- fun uniqueId() = "$sourcePlugin:${this::class.qualifiedName}"
+ fun uniqueId() = "$sourcePlugin:${this::class.jvmName}"
@Throws
abstract fun shouldShow(context: Context?, video: ResultEpisode?): Boolean
@@ -201,4 +182,4 @@ abstract class VideoClickAction {
CommonActivity.showToast(t.toString(), Toast.LENGTH_LONG)
}
}
-}
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/Aria2Package.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/Aria2Package.kt
deleted file mode 100644
index a7401c2ff..000000000
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/Aria2Package.kt
+++ /dev/null
@@ -1,30 +0,0 @@
-package com.lagradost.cloudstream3.actions.temp
-
-import android.app.Activity
-import android.content.Context
-import android.content.Intent
-import com.lagradost.cloudstream3.actions.OpenInAppAction
-import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
-import com.lagradost.cloudstream3.ui.result.ResultEpisode
-import com.lagradost.cloudstream3.utils.txt
-
-/** https://github.com/devgianlu/Aria2Android */
-@Suppress("unused")
-class Aria2Package : OpenInAppAction(
- appName = txt("Aria2"),
- packageName = "com.gianlu.aria2android",
- intentClass = "com.gianlu.aria2android.MainActivity"
-) {
- override val oneSource: Boolean = true
- override suspend fun putExtra(
- context: Context,
- intent: Intent,
- video: ResultEpisode,
- result: LinkLoadingResult,
- index: Int?
- ) {
- throw NotImplementedError("Aria2Android is missing getIntent, and onNewIntent, meaning it cant handle intents")
- }
-
- override fun onResult(activity: Activity, intent: Intent?) = Unit
-}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/BiglyBTPackage.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/BiglyBTPackage.kt
deleted file mode 100644
index 3959bb9d3..000000000
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/BiglyBTPackage.kt
+++ /dev/null
@@ -1,36 +0,0 @@
-package com.lagradost.cloudstream3.actions.temp
-
-import android.app.Activity
-import android.content.Context
-import android.content.Intent
-import androidx.core.net.toUri
-import com.lagradost.cloudstream3.actions.OpenInAppAction
-import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
-import com.lagradost.cloudstream3.ui.result.ResultEpisode
-import com.lagradost.cloudstream3.utils.ExtractorLinkType
-import com.lagradost.cloudstream3.utils.txt
-
-/** https://github.com/BiglySoftware/BiglyBT-Android */
-class BiglyBTPackage : OpenInAppAction(
- appName = txt("BiglyBT"),
- packageName = "com.biglybt.android.client",
- intentClass = "com.biglybt.android.client.activity.IntentHandler"
-) {
- // Only torrents are supported by the app
- override val sourceTypes: Set =
- setOf(ExtractorLinkType.MAGNET, ExtractorLinkType.TORRENT)
-
- override val oneSource: Boolean = true
-
- override suspend fun putExtra(
- context: Context,
- intent: Intent,
- video: ResultEpisode,
- result: LinkLoadingResult,
- index: Int?
- ) {
- intent.data = result.links[index!!].url.toUri()
- }
-
- override fun onResult(activity: Activity, intent: Intent?) = Unit
-}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/CloudStreamPackage.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/CloudStreamPackage.kt
deleted file mode 100644
index a2bb53a16..000000000
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/CloudStreamPackage.kt
+++ /dev/null
@@ -1,160 +0,0 @@
-package com.lagradost.cloudstream3.actions.temp
-
-import android.app.Activity
-import android.content.Context
-import android.content.Intent
-import android.net.Uri
-import com.fasterxml.jackson.annotation.JsonProperty
-import com.lagradost.cloudstream3.actions.OpenInAppAction
-import com.lagradost.cloudstream3.BuildConfig
-import com.lagradost.cloudstream3.SkipSerializationTest
-import com.lagradost.cloudstream3.ui.player.ExtractorUri
-import com.lagradost.cloudstream3.ui.player.SubtitleData
-import com.lagradost.cloudstream3.ui.player.SubtitleOrigin
-import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
-import com.lagradost.cloudstream3.ui.result.ResultEpisode
-import com.lagradost.cloudstream3.utils.AppUtils.toJson
-import com.lagradost.cloudstream3.utils.DataStoreHelper.getViewPos
-import com.lagradost.cloudstream3.utils.DrmExtractorLink
-import com.lagradost.cloudstream3.utils.ExtractorLink
-import com.lagradost.cloudstream3.utils.ExtractorLinkPlayList
-import com.lagradost.cloudstream3.utils.ExtractorLinkType
-import com.lagradost.cloudstream3.utils.newExtractorLink
-import com.lagradost.cloudstream3.utils.Qualities
-import com.lagradost.cloudstream3.utils.SubtitleHelper.fromCodeToLangTagIETF
-import com.lagradost.cloudstream3.utils.SubtitleHelper.fromLanguageToTagIETF
-import com.lagradost.cloudstream3.utils.serializers.UriSerializer
-import com.lagradost.cloudstream3.utils.txt
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
-
-/**
- * If you want to support CloudStream 3 as an external player, then this shows how to play any video link
- * For basic interactions, just `intent.data = uri` works
- *
- * However for more advanced use, CloudStream 3 also supports playlists of MinimalVideoLink and MinimalSubtitleLink with a `String[]` of JSON
- * These are passed as LINKS_EXTRA and SUBTITLE_EXTRA respectively
- */
-@Suppress("Unused")
-class CloudStreamPackage : OpenInAppAction(
- appName = txt("CloudStream"),
- packageName = BuildConfig.APPLICATION_ID, //"com.lagradost.cloudstream3" or "com.lagradost.cloudstream3.prerelease"
- intentClass = "com.lagradost.cloudstream3.ui.player.DownloadedPlayerActivity"
-) {
- override val oneSource: Boolean = false
-
- companion object {
- const val SUBTITLE_EXTRA: String = "subs" // Json of an array of MinimalVideoLink
- const val LINKS_EXTRA: String = "links" // Json of an array of MinimalSubtitleLink
- const val TITLE_EXTRA: String = "title" // Unused (String)
- const val ID_EXTRA: String =
- "id" // Identification number for the video(s), used to store start time (Int)
- const val POSITION_EXTRA: String = "pos" // Start time in MS (Long)
- const val DURATION_EXTRA: String = "dur" // Duration time in MS (Long)
- }
-
- @Serializable
- @SkipSerializationTest //.Uri has issues with Jackson
- data class MinimalVideoLink(
- @JsonProperty("uri") @SerialName("uri")
- @Serializable(with = UriSerializer::class)
- val uri: Uri?,
- @JsonProperty("url") @SerialName("url") val url: String?,
- @JsonProperty("mimeType") @SerialName("mimeType") val mimeType: String = "video/mp4",
- @JsonProperty("name") @SerialName("name") val name: String?,
- @JsonProperty("headers") @SerialName("headers") var headers: Map = mapOf(),
- @JsonProperty("quality") @SerialName("quality") val quality: Int?,
- ) {
- companion object {
- fun fromExtractor(link: ExtractorLink): MinimalVideoLink = MinimalVideoLink(
- uri = null,
- url = link.url,
- name = link.name,
- mimeType = link.type.getMimeType(),
- headers = if (link.referer.isBlank()) emptyMap() else mapOf("referer" to link.referer) + link.headers,
- quality = link.quality
- )
- }
-
- suspend fun toExtractorLink(): Pair =
- url?.let { url ->
- newExtractorLink(
- source = "NONE",
- name = name ?: "Unknown",
- url = url,
- type = ExtractorLinkType.entries.firstOrNull { ty -> ty.getMimeType() == mimeType }
- ?: ExtractorLinkType.VIDEO) {
-
- this@newExtractorLink.headers =
- this@MinimalVideoLink.headers
-
- this@newExtractorLink.quality =
- this@MinimalVideoLink.quality ?: Qualities.Unknown.value
- }
- } to uri?.let { uri ->
- ExtractorUri(
- uri = uri,
- name = name ?: "Unknown",
- )
- }
- }
-
- @Serializable
- data class MinimalSubtitleLink(
- @JsonProperty("url") @SerialName("url") val url: String,
- @JsonProperty("mimeType") @SerialName("mimeType") val mimeType: String = "text/vtt",
- @JsonProperty("name") @SerialName("name") val name: String?,
- @JsonProperty("headers") @SerialName("headers") var headers: Map = mapOf(),
- ) {
- companion object {
- fun fromSubtitle(sub: SubtitleData): MinimalSubtitleLink = MinimalSubtitleLink(
- url = sub.url,
- mimeType = sub.mimeType,
- name = sub.originalName,
- headers = sub.headers,
- )
- }
-
- fun toSubtitleData(): SubtitleData = SubtitleData(
- url = url,
- nameSuffix = "",
- mimeType = mimeType,
- originalName = name ?: "Unknown",
- headers = headers,
- origin = SubtitleOrigin.URL,
- languageCode = fromCodeToLangTagIETF(name) ?:
- fromLanguageToTagIETF(name, true) ?:
- name,
- )
- }
-
- override suspend fun putExtra(
- context: Context,
- intent: Intent,
- video: ResultEpisode,
- result: LinkLoadingResult,
- index: Int?
- ) {
- intent.apply {
- val position = getViewPos(video.id)?.position
- if (position != null)
- putExtra(POSITION_EXTRA, position)
-
- putExtra(ID_EXTRA, video.id)
- putExtra(TITLE_EXTRA, video.name)
- putExtra(
- SUBTITLE_EXTRA,
- result.subs.map { MinimalSubtitleLink.fromSubtitle(it).toJson() }.toTypedArray()
- )
- putExtra(
- LINKS_EXTRA,
- result.links.filter { it !is ExtractorLinkPlayList && it !is DrmExtractorLink }
- .map { MinimalVideoLink.fromExtractor(it).toJson() }.toTypedArray()
- )
- }
- }
-
- override fun onResult(activity: Activity, intent: Intent?) {
- // No results yet
- }
-}
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/JustPlayerPackage.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/JustPlayerPackage.kt
deleted file mode 100644
index 20eb843c7..000000000
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/JustPlayerPackage.kt
+++ /dev/null
@@ -1,37 +0,0 @@
-package com.lagradost.cloudstream3.actions.temp
-
-import android.app.Activity
-import android.content.Context
-import android.content.Intent
-import androidx.core.net.toUri
-import com.lagradost.cloudstream3.actions.OpenInAppAction
-import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
-import com.lagradost.cloudstream3.ui.result.ResultEpisode
-import com.lagradost.cloudstream3.utils.ExtractorLinkType
-import com.lagradost.cloudstream3.utils.txt
-
-/** https://github.com/moneytoo/Player/ */
-class JustPlayerPackage : OpenInAppAction(
- appName = txt("JustPlayer"),
- packageName = "com.brouken.player",
- intentClass = "com.brouken.player.PlayerActivity"
-) {
- override val sourceTypes: Set =
- setOf(ExtractorLinkType.VIDEO, ExtractorLinkType.M3U8, ExtractorLinkType.DASH)
-
- override val oneSource: Boolean = true
-
- override suspend fun putExtra(
- context: Context,
- intent: Intent,
- video: ResultEpisode,
- result: LinkLoadingResult,
- index: Int?
- ) {
- // While JustPlayer has support for subs, it cant add both subs and links at the same time
- // See https://github.com/moneytoo/Player/blob/49d80eb8de7a7bfc662393fdf114788fed1ebb2e/app/src/main/java/com/brouken/player/PlayerActivity.java#L794
- intent.data = result.links[index!!].url.toUri()
- }
-
- override fun onResult(activity: Activity, intent: Intent?) = Unit
-}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/LibreTorrentPackage.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/LibreTorrentPackage.kt
deleted file mode 100644
index 11d1858c6..000000000
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/LibreTorrentPackage.kt
+++ /dev/null
@@ -1,36 +0,0 @@
-package com.lagradost.cloudstream3.actions.temp
-
-import android.app.Activity
-import android.content.Context
-import android.content.Intent
-import androidx.core.net.toUri
-import com.lagradost.cloudstream3.actions.OpenInAppAction
-import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
-import com.lagradost.cloudstream3.ui.result.ResultEpisode
-import com.lagradost.cloudstream3.utils.ExtractorLinkType
-import com.lagradost.cloudstream3.utils.txt
-
-/** https://github.com/proninyaroslav/libretorrent */
-class LibreTorrentPackage : OpenInAppAction(
- appName = txt("LibreTorrent"),
- packageName = "org.proninyaroslav.libretorrent",
- intentClass = "org.proninyaroslav.libretorrent.ui.addtorrent.AddTorrentActivity"
-) {
- // Only torrents are supported by the app
- override val sourceTypes: Set =
- setOf(ExtractorLinkType.MAGNET, ExtractorLinkType.TORRENT)
-
- override val oneSource: Boolean = true
-
- override suspend fun putExtra(
- context: Context,
- intent: Intent,
- video: ResultEpisode,
- result: LinkLoadingResult,
- index: Int?
- ) {
- intent.data = result.links[index!!].url.toUri()
- }
-
- override fun onResult(activity: Activity, intent: Intent?) = Unit
-}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/MpvKtPackage.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/MpvKtPackage.kt
index faae39212..102f0ac8b 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/MpvKtPackage.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/MpvKtPackage.kt
@@ -3,6 +3,7 @@ package com.lagradost.cloudstream3.actions.temp
import android.app.Activity
import android.content.Context
import android.content.Intent
+import android.net.Uri
import androidx.core.net.toUri
import com.lagradost.cloudstream3.actions.OpenInAppAction
import com.lagradost.cloudstream3.actions.updateDurationAndPosition
@@ -44,7 +45,7 @@ open class MpvKtPackage(
intent.apply {
putExtra("subs", result.subs.map { it.url.toUri() }.toTypedArray())
- setDataAndType(link.url.toUri(), "video/*")
+ setDataAndType(Uri.parse(link.url), "video/*")
// m3u8 plays, but changing sources feature is not available
// makeTempM3U8Intent(activity, this, result)
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/MpvPackage.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/MpvPackage.kt
index cd49eb994..68e619c92 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/MpvPackage.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/MpvPackage.kt
@@ -3,6 +3,7 @@ package com.lagradost.cloudstream3.actions.temp
import android.app.Activity
import android.content.Context
import android.content.Intent
+import android.net.Uri
import androidx.core.net.toUri
import com.lagradost.api.Log
import com.lagradost.cloudstream3.actions.OpenInAppAction
@@ -17,9 +18,6 @@ import com.lagradost.cloudstream3.utils.ExtractorLinkType
// https://github.com/mpv-android/mpv-android/blob/0eb3cdc6f1632636b9c30d52ec50e4b017661980/app/src/main/java/is/xyz/mpv/MPVActivity.kt#L904
// https://mpv-android.github.io/mpv-android/intent.html
-//https://github.com/marlboro-advance/mpvEx
-class MpvExPackage: MpvPackage("mpvEx","app.marlboroadvance.mpvex","app.marlboroadvance.mpvex.ui.player.PlayerActivity")
-
class MpvYTDLPackage : MpvPackage("MPV YTDL", "is.xyz.mpv.ytdl") {
override val sourceTypes = setOf(
ExtractorLinkType.VIDEO,
@@ -28,10 +26,10 @@ class MpvYTDLPackage : MpvPackage("MPV YTDL", "is.xyz.mpv.ytdl") {
)
}
-open class MpvPackage(appName: String = "MPV", packageName: String = "is.xyz.mpv",intentClass:String = "is.xyz.mpv.MPVActivity"): OpenInAppAction(
+open class MpvPackage(appName: String = "MPV", packageName: String = "is.xyz.mpv"): OpenInAppAction(
txt(appName),
packageName,
- intentClass
+ "is.xyz.mpv.MPVActivity"
) {
override val oneSource = true // mpv has poor playlist support on TV
override suspend fun putExtra(
@@ -46,7 +44,7 @@ open class MpvPackage(appName: String = "MPV", packageName: String = "is.xyz.mpv
putExtra("title", video.name)
if (index != null) {
- setDataAndType((result.links.getOrNull(index)?.url ?: return).toUri(), "video/*")
+ setDataAndType(Uri.parse(result.links.getOrNull(index)?.url ?: return), "video/*")
} else {
makeTempM3U8Intent(context, this, result)
}
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/MpvRxPackage.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/MpvRxPackage.kt
deleted file mode 100644
index e8bb93a99..000000000
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/MpvRxPackage.kt
+++ /dev/null
@@ -1,75 +0,0 @@
-package com.lagradost.cloudstream3.actions.temp
-
-import android.app.Activity
-import android.content.Context
-import android.content.Intent
-import androidx.core.net.toUri
-import com.lagradost.api.Log
-import com.lagradost.cloudstream3.actions.OpenInAppAction
-import com.lagradost.cloudstream3.actions.updateDurationAndPosition
-import com.lagradost.cloudstream3.isEpisodeBased
-import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
-import com.lagradost.cloudstream3.ui.result.ResultEpisode
-import com.lagradost.cloudstream3.utils.DataStoreHelper.getViewPos
-import com.lagradost.cloudstream3.utils.txt
-
-/** https://github.com/Riteshp2001/mpvRx
- *
- * https://github.com/Riteshp2001/mpvRx/blob/00e0c5e803ab53e5757426cbf2248448ba1f49bf/app/src/main/java/app/gyrolet/mpvrx/utils/media/MediaUtils.kt#L132
- * https://github.com/Riteshp2001/mpvRx/blob/00e0c5e803ab53e5757426cbf2248448ba1f49bf/app/src/main/java/app/gyrolet/mpvrx/utils/media/MediaUtils.kt#L56
- * */
-class MpvRxPackage : OpenInAppAction(
- appName = txt("mpvRx"),
- packageName = "app.gyrolet.mpvrx",
- intentClass = "app.gyrolet.mpvrx.ui.player.PlayerActivity"
-) {
- override val oneSource = true
- override suspend fun putExtra(
- context: Context,
- intent: Intent,
- video: ResultEpisode,
- result: LinkLoadingResult,
- index: Int?
- ) {
- intent.apply {
- putExtra("title", video.name)
- val link = result.links[index!!]
- val headers = link.headers
-
- setData(link.url.toUri())
- if (headers.isNotEmpty()) {
- // PlayerActivity expects a flat array: [key1, value1, key2, value2, ...]
- val flat = headers.entries.flatMap { listOf(it.key, it.value) }.toTypedArray()
- intent.putExtra("headers", flat)
- }
- /*val subs = result.subs // disabled due to https://github.com/Riteshp2001/mpvRx/issues/146
- intent.putExtra("subs", subs.map { it.url.toUri() }.toTypedArray())
- intent.putExtra(
- "subs.titles",
- subs.map { it.name }.toTypedArray(),
- )
- intent.putExtra(
- "subs.langs",
- subs.map { it.languageCode }.toTypedArray(),
- )
- val selected = subs.firstOrNull { it.matchesLanguageCode("en") }?.url?.toUri()
- intent.putExtra("subs.enable", selected?.let { arrayOf(it) } ?: arrayOf() )*/
-
- if (video.tvType.isEpisodeBased()) {
- video.season?.let { intent.putExtra("introdb_season", it) }
- video.episode.let { intent.putExtra("introdb_episode", it) }
- }
-
- val position = getViewPos(video.id)?.position
- if (position != null)
- putExtra("position", position.toInt())
- }
- }
-
- override fun onResult(activity: Activity, intent: Intent?) {
- val position = intent?.getIntExtra("position", -1) ?: -1
- val duration = intent?.getIntExtra("duration", -1) ?: -1
- Log.d("MPV", "Position: $position, Duration: $duration")
- updateDurationAndPosition(position.toLong(), duration.toLong())
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/NextPlayerPackage.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/NextPlayerPackage.kt
deleted file mode 100644
index 5d0923b81..000000000
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/NextPlayerPackage.kt
+++ /dev/null
@@ -1,35 +0,0 @@
-package com.lagradost.cloudstream3.actions.temp
-
-import android.app.Activity
-import android.content.Context
-import android.content.Intent
-import androidx.core.net.toUri
-import com.lagradost.cloudstream3.actions.OpenInAppAction
-import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
-import com.lagradost.cloudstream3.ui.result.ResultEpisode
-import com.lagradost.cloudstream3.utils.ExtractorLinkType
-import com.lagradost.cloudstream3.utils.txt
-
-/** https://github.com/anilbeesetti/nextplayer */
-class NextPlayerPackage : OpenInAppAction(
- appName = txt("NextPlayer"),
- packageName = "dev.anilbeesetti.nextplayer",
- intentClass = "dev.anilbeesetti.nextplayer.feature.player.PlayerActivity"
-) {
- override val sourceTypes: Set =
- setOf(ExtractorLinkType.VIDEO, ExtractorLinkType.M3U8, ExtractorLinkType.DASH)
-
- override val oneSource: Boolean = true
-
- override suspend fun putExtra(
- context: Context,
- intent: Intent,
- video: ResultEpisode,
- result: LinkLoadingResult,
- index: Int?
- ) {
- intent.data = result.links[index!!].url.toUri()
- }
-
- override fun onResult(activity: Activity, intent: Intent?) = Unit
-}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/OnlyPlayer.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/OnlyPlayer.kt
deleted file mode 100644
index 348be440a..000000000
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/OnlyPlayer.kt
+++ /dev/null
@@ -1,44 +0,0 @@
-package com.lagradost.cloudstream3.actions.temp
-
-import android.app.Activity
-import android.content.Context
-import android.content.Intent
-import android.os.Bundle
-import androidx.core.net.toUri
-import com.lagradost.cloudstream3.actions.OpenInAppAction
-import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
-import com.lagradost.cloudstream3.ui.result.ResultEpisode
-import com.lagradost.cloudstream3.utils.txt
-
-/** https://github.com/Kindness-Kismet/only_player/tree/main
- * https://github.com/Kindness-Kismet/only_player/blob/main/feature/player/src/main/java/one/only/player/feature/player/PlayerActivity.kt */
-class OnlyPlayer : OpenInAppAction(
- txt("Only Player"),
- "one.only.player",
- intentClass = "one.only.player.feature.player.PlayerActivity"
-) {
- override val oneSource = true
- override suspend fun putExtra(
- context: Context,
- intent: Intent,
- video: ResultEpisode,
- result: LinkLoadingResult,
- index: Int?
- ) {
- /** https://github.com/Kindness-Kismet/only_player/blob/d3f55049a2913fa762d31b311146073cc2da46cb/app/src/main/java/one/only/player/navigation/CloudNavGraph.kt#L39 */
- intent.apply {
- val link = result.links[index!!]
- setData(link.url.toUri())
-
- putExtra("headers", Bundle().apply {
- for ((key, value) in link.headers) {
- putExtra(key, value)
- }
- })
- }
- }
-
- override fun onResult(activity: Activity, intent: Intent?) {
- /* onResult does not get called */
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/PlayInBrowserAction.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/PlayInBrowserAction.kt
index bfd2926bf..7c1b68c05 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/PlayInBrowserAction.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/PlayInBrowserAction.kt
@@ -2,7 +2,7 @@ package com.lagradost.cloudstream3.actions.temp
import android.content.Context
import android.content.Intent
-import androidx.core.net.toUri
+import android.net.Uri
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.actions.VideoClickAction
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
@@ -33,7 +33,7 @@ class PlayInBrowserAction: VideoClickAction() {
) {
val link = result.links.getOrNull(index ?: 0) ?: return
val i = Intent(Intent.ACTION_VIEW)
- i.data = link.url.toUri()
+ i.data = Uri.parse(link.url)
launch(i)
}
}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/PlayMirrorAction.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/PlayMirrorAction.kt
deleted file mode 100644
index 56512377b..000000000
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/PlayMirrorAction.kt
+++ /dev/null
@@ -1,65 +0,0 @@
-package com.lagradost.cloudstream3.actions.temp
-
-import android.app.Activity
-import android.content.Context
-import com.lagradost.cloudstream3.R
-import com.lagradost.cloudstream3.actions.VideoClickAction
-import com.lagradost.cloudstream3.ui.player.ExtractorUri
-import com.lagradost.cloudstream3.ui.player.GeneratorPlayer
-import com.lagradost.cloudstream3.ui.player.LOADTYPE_INAPP
-import com.lagradost.cloudstream3.ui.player.SubtitleData
-import com.lagradost.cloudstream3.ui.player.VideoGenerator
-import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
-import com.lagradost.cloudstream3.ui.result.ResultEpisode
-import com.lagradost.cloudstream3.utils.ExtractorLink
-import com.lagradost.cloudstream3.utils.ExtractorLinkType
-import com.lagradost.cloudstream3.utils.UIHelper.navigate
-import com.lagradost.cloudstream3.utils.txt
-
-class PlayMirrorAction : VideoClickAction() {
- override val name = txt(R.string.episode_action_play_mirror)
-
- override val oneSource = true
-
- override val isPlayer = true
-
- override val sourceTypes: Set = LOADTYPE_INAPP
-
- override fun shouldShow(context: Context?, video: ResultEpisode?) = true
-
- override suspend fun runAction(
- context: Context?,
- video: ResultEpisode,
- result: LinkLoadingResult,
- index: Int?
- ) {
- //Implemented a generator to handle the single
- val activity = context as? Activity ?: return
- val link = index?.let { result.links[it] }
- val generatorMirror = object : VideoGenerator(listOf(video)) {
- override val hasCache: Boolean = false
- override val canSkipLoading: Boolean = false
- override fun getId(index: Int): Int = video.id
-
- override suspend fun generateLinks(
- clearCache: Boolean,
- sourceTypes: Set,
- callback: (Pair) -> Unit,
- subtitleCallback: (SubtitleData) -> Unit,
- offset: Int,
- isCasting: Boolean
- ): Boolean {
- index?.let { callback(link to null) }
- result.subs.forEach { subtitle -> subtitleCallback(subtitle) }
- return true
- }
- }
-
- activity.navigate(
- R.id.global_to_navigation_player,
- GeneratorPlayer.newInstance(
- generatorMirror, 0, result.syncData
- )
- )
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/VlcPackage.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/VlcPackage.kt
index b6478b1d9..df4fcca81 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/VlcPackage.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/VlcPackage.kt
@@ -6,7 +6,7 @@ import android.content.Intent
import android.os.Build
import androidx.core.net.toUri
import com.lagradost.api.Log
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
+import com.lagradost.cloudstream3.AcraApplication.Companion.getKey
import com.lagradost.cloudstream3.actions.OpenInAppAction
import com.lagradost.cloudstream3.actions.makeTempM3U8Intent
import com.lagradost.cloudstream3.actions.updateDurationAndPosition
@@ -19,12 +19,7 @@ import com.lagradost.cloudstream3.utils.DataStoreHelper.getViewPos
// https://github.com/videolan/vlc-android/blob/3706c4be2da6800b3d26344fc04fab03ffa4b860/application/vlc-android/src/org/videolan/vlc/gui/video/VideoPlayerActivity.kt#L1898
// https://wiki.videolan.org/Android_Player_Intents/
-class VlcNightlyPackage : VlcPackage() {
- override val packageName = "org.videolan.vlc.debug"
- override val appName = txt("VLC Nightly")
-}
-
-open class VlcPackage: OpenInAppAction(
+class VlcPackage: OpenInAppAction(
appName = txt("VLC"),
packageName = "org.videolan.vlc",
intentClass = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
@@ -60,7 +55,7 @@ open class VlcPackage: OpenInAppAction(
intent.putExtra("secure_uri", true)
intent.putExtra("title", video.name)
- val subsLang = getKey(SUBTITLE_AUTO_SELECT_KEY) ?: "en"
+ val subsLang = getKey(SUBTITLE_AUTO_SELECT_KEY) ?: "en"
result.subs.firstOrNull {
subsLang == it.languageCode
}?.let {
@@ -74,4 +69,4 @@ open class VlcPackage: OpenInAppAction(
Log.d("VLC", "Position: $position, Duration: $duration")
updateDurationAndPosition(position, duration)
}
-}
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/WebVideoCastPackage.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/WebVideoCastPackage.kt
index 963221bb3..9f7eee7b8 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/WebVideoCastPackage.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/WebVideoCastPackage.kt
@@ -3,6 +3,7 @@ package com.lagradost.cloudstream3.actions.temp
import android.app.Activity
import android.content.Context
import android.content.Intent
+import android.net.Uri
import android.os.Bundle
import androidx.core.net.toUri
import com.lagradost.cloudstream3.USER_AGENT
@@ -37,7 +38,7 @@ class WebVideoCastPackage: OpenInAppAction(
val link = result.links[index ?: 0]
intent.apply {
- setDataAndType(link.url.toUri(), "video/*")
+ setDataAndType(Uri.parse(link.url), "video/*")
val title = video.name ?: video.headerName
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/fcast/FcastAction.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/fcast/FcastAction.kt
index 1036a7055..e3916df01 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/fcast/FcastAction.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/fcast/FcastAction.kt
@@ -1,7 +1,7 @@
package com.lagradost.cloudstream3.actions.temp.fcast
import android.content.Context
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.getActivity
+import com.lagradost.cloudstream3.AcraApplication.Companion.getActivity
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.USER_AGENT
import com.lagradost.cloudstream3.actions.VideoClickAction
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/fcast/FcastManager.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/fcast/FcastManager.kt
index e2cf4f002..282ef834e 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/fcast/FcastManager.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/fcast/FcastManager.kt
@@ -7,7 +7,6 @@ import android.net.nsd.NsdServiceInfo
import android.os.Build
import android.os.ext.SdkExtensions
import android.util.Log
-import com.lagradost.cloudstream3.mvvm.safe
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
class FcastManager {
@@ -73,66 +72,52 @@ class FcastManager {
}
override fun onServiceFound(serviceInfo: NsdServiceInfo?) {
- // Safe here as, java.lang.NoClassDefFoundError: Failed resolution of: Landroid/net/nsd/NsdManager$ServiceInfoCallback
- safe {
- if (serviceInfo == null) return@safe
+ if (serviceInfo == null) return
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && SdkExtensions.getExtensionVersion(
- Build.VERSION_CODES.TIRAMISU
- ) >= 7
- ) {
- nsdManager?.registerServiceInfoCallback(
- serviceInfo,
- Runnable::run,
- object : NsdManager.ServiceInfoCallback {
- override fun onServiceInfoCallbackRegistrationFailed(errorCode: Int) {
- Log.e(tag, "Service registration failed: $errorCode")
- }
-
- override fun onServiceUpdated(serviceInfo: NsdServiceInfo) {
- Log.d(
- tag,
- "Service updated: ${serviceInfo.serviceName}," +
- "Net: ${serviceInfo.hostAddresses.firstOrNull()?.hostAddress}"
- )
- synchronized(_currentDevices) {
- _currentDevices.removeIf { it.rawName == serviceInfo.serviceName }
- _currentDevices.add(PublicDeviceInfo(serviceInfo))
- }
- }
-
- override fun onServiceLost() {
- Log.d(tag, "Service lost: ${serviceInfo.serviceName},")
- synchronized(_currentDevices) {
- _currentDevices.removeIf { it.rawName == serviceInfo.serviceName }
- }
- }
-
- override fun onServiceInfoCallbackUnregistered() {}
- })
- } else {
- @Suppress("DEPRECATION")
- nsdManager?.resolveService(serviceInfo, object : ResolveListener {
- override fun onResolveFailed(
- serviceInfo: NsdServiceInfo?,
- errorCode: Int
- ) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && SdkExtensions.getExtensionVersion(
+ Build.VERSION_CODES.TIRAMISU) >= 7) {
+ nsdManager?.registerServiceInfoCallback(serviceInfo,
+ Runnable::run,
+ object : NsdManager.ServiceInfoCallback {
+ override fun onServiceInfoCallbackRegistrationFailed(errorCode: Int) {
+ Log.e(tag, "Service registration failed: $errorCode")
}
-
- override fun onServiceResolved(serviceInfo: NsdServiceInfo?) {
- if (serviceInfo == null) return
-
+ override fun onServiceUpdated(serviceInfo: NsdServiceInfo) {
+ Log.d(tag,
+ "Service updated: ${serviceInfo.serviceName}," +
+ "Net: ${serviceInfo.hostAddresses.firstOrNull()?.hostAddress}"
+ )
synchronized(_currentDevices) {
+ _currentDevices.removeIf { it.rawName == serviceInfo.serviceName }
_currentDevices.add(PublicDeviceInfo(serviceInfo))
}
-
- Log.d(
- tag,
- "Service found: ${serviceInfo.serviceName}, Net: ${serviceInfo.host.hostAddress}"
- )
}
+ override fun onServiceLost() {
+ Log.d(tag, "Service lost: ${serviceInfo.serviceName},")
+ synchronized(_currentDevices) {
+ _currentDevices.removeIf { it.rawName == serviceInfo.serviceName }
+ }
+ }
+ override fun onServiceInfoCallbackUnregistered() {}
})
- }
+ } else {
+ @Suppress("DEPRECATION")
+ nsdManager?.resolveService(serviceInfo, object : ResolveListener {
+ override fun onResolveFailed(serviceInfo: NsdServiceInfo?, errorCode: Int) {}
+
+ override fun onServiceResolved(serviceInfo: NsdServiceInfo?) {
+ if (serviceInfo == null) return
+
+ synchronized(_currentDevices) {
+ _currentDevices.add(PublicDeviceInfo(serviceInfo))
+ }
+
+ Log.d(
+ tag,
+ "Service found: ${serviceInfo.serviceName}, Net: ${serviceInfo.host.hostAddress}"
+ )
+ }
+ })
}
}
@@ -183,9 +168,8 @@ class PublicDeviceInfo(serviceInfo: NsdServiceInfo) {
val host: String? = if (
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R &&
SdkExtensions.getExtensionVersion(
- Build.VERSION_CODES.TIRAMISU
- ) >= 7
- ) {
+ Build.VERSION_CODES.TIRAMISU) >= 7
+ ) {
serviceInfo.hostAddresses.firstOrNull()?.hostAddress
} else {
@Suppress("DEPRECATION")
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/fcast/Packets.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/fcast/Packets.kt
index d54791e89..26f5cec53 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/fcast/Packets.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/fcast/Packets.kt
@@ -1,9 +1,5 @@
package com.lagradost.cloudstream3.actions.temp.fcast
-import com.fasterxml.jackson.annotation.JsonProperty
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
-
// See https://gitlab.com/futo-org/fcast/-/wikis/Protocol-version-1
enum class Opcode(val value: Byte) {
None(0),
@@ -22,18 +18,18 @@ enum class Opcode(val value: Byte) {
Pong(13);
}
-@Serializable
+
data class PlayMessage(
- @JsonProperty("container") @SerialName("container") val container: String,
- @JsonProperty("url") @SerialName("url") val url: String? = null,
- @JsonProperty("content") @SerialName("content") val content: String? = null,
- @JsonProperty("time") @SerialName("time") val time: Double? = null,
- @JsonProperty("speed") @SerialName("speed") val speed: Double? = null,
- @JsonProperty("headers") @SerialName("headers") val headers: Map? = null,
+ val container: String,
+ val url: String? = null,
+ val content: String? = null,
+ val time: Double? = null,
+ val speed: Double? = null,
+ val headers: Map? = null
)
data class SeekMessage(
- val time: Double,
+ val time: Double
)
data class PlaybackUpdateMessage(
@@ -41,26 +37,26 @@ data class PlaybackUpdateMessage(
val time: Double,
val duration: Double,
val state: Int,
- val speed: Double,
+ val speed: Double
)
data class VolumeUpdateMessage(
val generationTime: Long,
- val volume: Double,
+ val volume: Double
)
data class PlaybackErrorMessage(
- val message: String,
+ val message: String
)
data class SetSpeedMessage(
- val speed: Double,
+ val speed: Double
)
data class SetVolumeMessage(
- val volume: Double,
+ val volume: Double
)
data class VersionMessage(
- val version: Long,
+ val version: Long
)
diff --git a/app/src/main/java/com/lagradost/cloudstream3/mvvm/Lifecycle.kt b/app/src/main/java/com/lagradost/cloudstream3/mvvm/Lifecycle.kt
index 482ec05fc..3df5197cd 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/mvvm/Lifecycle.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/mvvm/Lifecycle.kt
@@ -1,68 +1,16 @@
package com.lagradost.cloudstream3.mvvm
-import android.view.View
-import androidx.activity.ComponentActivity
-import androidx.core.view.doOnAttach
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
-import androidx.lifecycle.findViewTreeLifecycleOwner
-import androidx.viewbinding.ViewBinding
-import com.lagradost.cloudstream3.ui.BaseFragment
/** NOTE: Only one observer at a time per value */
-fun ComponentActivity.observe(liveData: LiveData, action: (T) -> Unit) {
- observeNullable(liveData) { t -> t?.run(action) }
-}
-
-/** NOTE: Only one observer at a time per value */
-fun ComponentActivity.observeNullable(liveData: LiveData, action: (T?) -> Unit) {
+fun LifecycleOwner.observe(liveData: LiveData, action: (t: T) -> Unit) {
liveData.removeObservers(this)
- liveData.observe(this, action)
+ liveData.observe(this) { it?.let { t -> action(t) } }
}
/** NOTE: Only one observer at a time per value */
-fun BaseFragment.observe(liveData: LiveData, action: (T) -> Unit) {
- observeNullable(liveData) { t -> t?.run(action) }
+fun LifecycleOwner.observeNullable(liveData: LiveData, action: (t: T) -> Unit) {
+ liveData.removeObservers(this)
+ liveData.observe(this) { action(it) }
}
-
-/**
- * Attaches an observable to the root binding, instead of the fragment. This is more efficient as
- * it will not call observe if the view is in the background.
- *
- * NOTE: Only one observer at a time per value
- * */
-fun BaseFragment.observeNullable(
- liveData: LiveData, action: (T?) -> Unit
-) {
- val root = this.binding?.root
- if (root == null) {
- liveData.removeObservers(this)
- liveData.observe(this, action)
- } else {
- root.doOnAttach { view ->
- // On attach should make findViewTreeLifecycleOwner non-null, but use "this" just in case
- val owner: LifecycleOwner = view.findViewTreeLifecycleOwner() ?: this@observeNullable
- liveData.removeObservers(owner)
- liveData.observe(owner, action)
- }
- }
-}
-
-/** NOTE: Only one observer at a time per value */
-fun View.observe(liveData: LiveData, action: (T) -> Unit) {
- observeNullable(liveData) { t -> t?.run(action) }
-}
-
-/** NOTE: Only one observer at a time per value */
-fun View.observeNullable(liveData: LiveData, action: (T?) -> Unit) {
- doOnAttach { view ->
- // On attach should make findViewTreeLifecycleOwner non-null
- val owner: LifecycleOwner? = view.findViewTreeLifecycleOwner()
- if(owner == null) {
- debugException { "Expected non-null findViewTreeLifecycleOwner" }
- return@doOnAttach
- }
- liveData.removeObservers(owner)
- liveData.observe(owner, action)
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/network/CloudflareKiller.kt b/app/src/main/java/com/lagradost/cloudstream3/network/CloudflareKiller.kt
index 9efa88a37..85a9db5db 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/network/CloudflareKiller.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/network/CloudflareKiller.kt
@@ -5,7 +5,7 @@ import android.webkit.CookieManager
import androidx.annotation.AnyThread
import com.lagradost.cloudstream3.app
import com.lagradost.cloudstream3.mvvm.debugWarning
-import com.lagradost.cloudstream3.mvvm.safe
+import com.lagradost.cloudstream3.mvvm.normalSafeApiCall
import com.lagradost.nicehttp.Requests.Companion.await
import com.lagradost.nicehttp.cookies
import kotlinx.coroutines.runBlocking
@@ -32,7 +32,7 @@ class CloudflareKiller : Interceptor {
init {
// Needs to clear cookies between sessions to generate new cookies.
- safe {
+ normalSafeApiCall {
// This can throw an exception on unsupported devices :(
CookieManager.getInstance().removeAllCookies(null)
}
@@ -77,7 +77,7 @@ class CloudflareKiller : Interceptor {
}
private fun getWebViewCookie(url: String): String? {
- return safe {
+ return normalSafeApiCall {
CookieManager.getInstance()?.getCookie(url)
}
}
diff --git a/app/src/main/java/com/lagradost/cloudstream3/network/RequestsHelper.kt b/app/src/main/java/com/lagradost/cloudstream3/network/RequestsHelper.kt
index 203a503e9..1565d92cf 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/network/RequestsHelper.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/network/RequestsHelper.kt
@@ -2,10 +2,9 @@ package com.lagradost.cloudstream3.network
import android.content.Context
import androidx.preference.PreferenceManager
-import com.lagradost.cloudstream3.Prerelease
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.USER_AGENT
-import com.lagradost.cloudstream3.mvvm.safe
+import com.lagradost.cloudstream3.mvvm.normalSafeApiCall
import com.lagradost.nicehttp.Requests
import com.lagradost.nicehttp.ignoreAllSSLErrors
import okhttp3.Cache
@@ -16,36 +15,19 @@ import org.conscrypt.Conscrypt
import java.io.File
import java.security.Security
-// Backwards compatible constructor, mark as deprecated later
fun Requests.initClient(context: Context) {
this.baseClient = buildDefaultClient(context)
}
-/** Only use ignoreSSL if you know what you are doing*/
-fun Requests.initClient(context: Context, ignoreSSL: Boolean = false) {
- this.baseClient = buildDefaultClient(context, ignoreSSL)
-}
-
-
-// Backwards compatible constructor, mark as deprecated later
fun buildDefaultClient(context: Context): OkHttpClient {
- return buildDefaultClient(context, false)
-}
-
-/** Only use ignoreSSL if you know what you are doing*/
-fun buildDefaultClient(context: Context, ignoreSSL: Boolean = false): OkHttpClient {
- safe { Security.insertProviderAt(Conscrypt.newProvider(), 1) }
+ normalSafeApiCall { Security.insertProviderAt(Conscrypt.newProvider(), 1) }
val settingsManager = PreferenceManager.getDefaultSharedPreferences(context)
val dns = settingsManager.getInt(context.getString(R.string.dns_pref), 0)
val baseClient = OkHttpClient.Builder()
.followRedirects(true)
.followSslRedirects(true)
- .apply {
- if (ignoreSSL) {
- ignoreAllSSLErrors()
- }
- }
+ .ignoreAllSSLErrors()
.cache(
// Note that you need to add a ResponseInterceptor to make this 100% active.
// The server response dictates if and when stuff should be cached.
@@ -70,6 +52,11 @@ fun buildDefaultClient(context: Context, ignoreSSL: Boolean = false): OkHttpClie
return baseClient
}
+//val Request.cookies: Map
+// get() {
+// return this.headers.getCookies("Cookie")
+// }
+
private val DEFAULT_HEADERS = mapOf("user-agent" to USER_AGENT)
/**
diff --git a/app/src/main/java/com/lagradost/cloudstream3/plugins/Plugin.kt b/app/src/main/java/com/lagradost/cloudstream3/plugins/Plugin.kt
index e1496db06..efa028d14 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/plugins/Plugin.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/plugins/Plugin.kt
@@ -7,6 +7,7 @@ import com.lagradost.cloudstream3.actions.VideoClickAction
import com.lagradost.cloudstream3.actions.VideoClickActionHolder
import kotlin.Throws
+
abstract class Plugin : BasePlugin() {
/**
* Called when your Plugin is loaded
@@ -25,7 +26,9 @@ abstract class Plugin : BasePlugin() {
fun registerVideoClickAction(element: VideoClickAction) {
Log.i(PLUGIN_TAG, "Adding ${element.name} VideoClickAction")
element.sourcePlugin = this.filename
- VideoClickActionHolder.allVideoClickActions.add(element)
+ synchronized(VideoClickActionHolder.allVideoClickActions) {
+ VideoClickActionHolder.allVideoClickActions.add(element)
+ }
}
/**
@@ -37,4 +40,4 @@ abstract class Plugin : BasePlugin() {
* This will add a button in the settings allowing you to add custom settings
*/
var openSettings: ((context: Context) -> Unit)? = null
-}
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/plugins/PluginManager.kt b/app/src/main/java/com/lagradost/cloudstream3/plugins/PluginManager.kt
index 6054bbfaf..2a4e57656 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/plugins/PluginManager.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/plugins/PluginManager.kt
@@ -13,7 +13,6 @@ import android.os.Build
import android.os.Environment
import android.util.Log
import android.widget.Toast
-import androidx.annotation.WorkerThread
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
@@ -21,32 +20,30 @@ import androidx.fragment.app.FragmentActivity
import com.fasterxml.jackson.annotation.JsonProperty
import com.lagradost.cloudstream3.APIHolder
import com.lagradost.cloudstream3.APIHolder.removePluginMapping
+import com.lagradost.cloudstream3.AcraApplication.Companion.getActivity
+import com.lagradost.cloudstream3.AcraApplication.Companion.getKey
+import com.lagradost.cloudstream3.AcraApplication.Companion.removeKey
+import com.lagradost.cloudstream3.AcraApplication.Companion.setKey
import com.lagradost.cloudstream3.AllLanguagesName
import com.lagradost.cloudstream3.AutoDownloadMode
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.removeKey
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
import com.lagradost.cloudstream3.CommonActivity.showToast
-import com.lagradost.cloudstream3.InternalAPI
import com.lagradost.cloudstream3.MainAPI
import com.lagradost.cloudstream3.MainAPI.Companion.settingsForProvider
import com.lagradost.cloudstream3.MainActivity.Companion.afterPluginsLoadedEvent
-import com.lagradost.cloudstream3.MainActivity.Companion.lastError
import com.lagradost.cloudstream3.PROVIDER_STATUS_DOWN
import com.lagradost.cloudstream3.PROVIDER_STATUS_OK
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.TvType
import com.lagradost.cloudstream3.actions.VideoClickAction
import com.lagradost.cloudstream3.actions.VideoClickActionHolder
-import com.lagradost.cloudstream3.amap
+import com.lagradost.cloudstream3.apmap
import com.lagradost.cloudstream3.mvvm.debugPrint
import com.lagradost.cloudstream3.mvvm.logError
-import com.lagradost.cloudstream3.mvvm.safe
+import com.lagradost.cloudstream3.mvvm.normalSafeApiCall
import com.lagradost.cloudstream3.plugins.RepositoryManager.ONLINE_PLUGINS_FOLDER
import com.lagradost.cloudstream3.plugins.RepositoryManager.PREBUILT_REPOSITORIES
import com.lagradost.cloudstream3.plugins.RepositoryManager.downloadPluginToFile
import com.lagradost.cloudstream3.plugins.RepositoryManager.getRepoPlugins
-import com.lagradost.cloudstream3.plugins.RepositoryManager.sha256
import com.lagradost.cloudstream3.ui.settings.extensions.REPOSITORIES_KEY
import com.lagradost.cloudstream3.ui.settings.extensions.RepositoryData
import com.lagradost.cloudstream3.utils.AppContextUtils.getApiProviderLangSettings
@@ -55,14 +52,12 @@ import com.lagradost.cloudstream3.utils.Coroutines.main
import com.lagradost.cloudstream3.utils.ExtractorApi
import com.lagradost.cloudstream3.utils.UIHelper.colorFromAttribute
import com.lagradost.cloudstream3.utils.UiText
-import com.lagradost.cloudstream3.utils.downloader.DownloadFileManagement.sanitizeFilename
+import com.lagradost.cloudstream3.utils.VideoDownloadManager.sanitizeFilename
import com.lagradost.cloudstream3.utils.extractorApis
import com.lagradost.cloudstream3.utils.txt
import dalvik.system.PathClassLoader
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
import java.io.File
import java.io.InputStreamReader
@@ -75,15 +70,13 @@ const val EXTENSIONS_CHANNEL_NAME = "Extensions"
const val EXTENSIONS_CHANNEL_DESCRIPT = "Extension notification channel"
// Data class for internal storage
-@Serializable
data class PluginData(
- @JsonProperty("internalName") @SerialName("internalName") val internalName: String,
- @JsonProperty("url") @SerialName("url") val url: String?,
- @JsonProperty("isOnline") @SerialName("isOnline") val isOnline: Boolean,
- @JsonProperty("filePath") @SerialName("filePath") val filePath: String,
- @JsonProperty("version") @SerialName("version") val version: Int,
+ @JsonProperty("internalName") val internalName: String,
+ @JsonProperty("url") val url: String?,
+ @JsonProperty("isOnline") val isOnline: Boolean,
+ @JsonProperty("filePath") val filePath: String,
+ @JsonProperty("version") val version: Int,
) {
- @WorkerThread
fun toSitePlugin(): SitePlugin {
return SitePlugin(
this.filePath,
@@ -98,9 +91,7 @@ data class PluginData(
null,
null,
null,
- File(this.filePath).length(),
- // No file hash for local plugins. Local plugins have no use for the hash, and it's expensive to compute.
- null
+ File(this.filePath).length()
)
}
}
@@ -154,7 +145,7 @@ object PluginManager {
!it.filePath.contains(repositoryPath)
}
val file = File(repositoryPath)
- safe {
+ normalSafeApiCall {
if (file.exists()) file.deleteRecursively()
}
setKey(PLUGINS_KEY, plugins)
@@ -176,11 +167,11 @@ object PluginManager {
fun getPluginsOnline(): Array {
- return getKey>(PLUGINS_KEY) ?: emptyArray()
+ return getKey(PLUGINS_KEY) ?: emptyArray()
}
fun getPluginsLocal(): Array {
- return getKey>(PLUGINS_KEY_LOCAL) ?: emptyArray()
+ return getKey(PLUGINS_KEY_LOCAL) ?: emptyArray()
}
private val CLOUD_STREAM_FOLDER =
@@ -224,17 +215,17 @@ object PluginManager {
// Helper class for updateAllOnlinePluginsAndLoadThem
data class OnlinePluginData(
val savedData: PluginData,
- val onlineData: PluginWrapper,
+ val onlineData: Pair,
) {
val isOutdated =
- onlineData.plugin.version > savedData.version || onlineData.plugin.version == PLUGIN_VERSION_ALWAYS_UPDATE
- val isDisabled = onlineData.plugin.status == PROVIDER_STATUS_DOWN
+ onlineData.second.version > savedData.version || onlineData.second.version == PLUGIN_VERSION_ALWAYS_UPDATE
+ val isDisabled = onlineData.second.status == PROVIDER_STATUS_DOWN
fun validOnlineData(context: Context): Boolean {
return getPluginPath(
context,
savedData.internalName,
- onlineData.repositoryData.url
+ onlineData.first
).absolutePath == savedData.filePath
}
}
@@ -264,37 +255,29 @@ object PluginManager {
* 2. If disabled do nothing
* 3. If outdated download and load the plugin
* 4. Else load the plugin normally
- *
- * DO NOT USE THIS IN A PLUGIN! It may case an infinite recursive loop lagging or crashing everyone's devices.
- * If you use it from a plugin, do not expect a stable jvmName, SO DO NOT USE IT!
- */
- @Suppress("FunctionName")
- @InternalAPI
- @Throws
- suspend fun ___DO_NOT_CALL_FROM_A_PLUGIN_updateAllOnlinePluginsAndLoadThem(activity: Activity) {
- assertNonRecursiveCallstack()
-
+ **/
+ fun updateAllOnlinePluginsAndLoadThem(activity: Activity) {
// Load all plugins as fast as possible!
- ___DO_NOT_CALL_FROM_A_PLUGIN_loadAllOnlinePlugins(activity)
+ loadAllOnlinePlugins(activity)
afterPluginsLoadedEvent.invoke(false)
val urls = (getKey>(REPOSITORIES_KEY)
?: emptyArray()) + PREBUILT_REPOSITORIES
- val onlinePlugins = urls.toList().amap {
- getRepoPlugins(it) ?: emptyList()
- }.flatten().distinctBy { it.plugin.url }
+ val onlinePlugins = urls.toList().apmap {
+ getRepoPlugins(it.url)?.toList() ?: emptyList()
+ }.flatten().distinctBy { it.second.url }
// Iterates over all offline plugins, compares to remote repo and returns the plugins which are outdated
val outdatedPlugins = getPluginsOnline().map { savedData ->
onlinePlugins
- .filter { onlineData -> savedData.internalName == onlineData.plugin.internalName }
+ .filter { onlineData -> savedData.internalName == onlineData.second.internalName }
.map { onlineData ->
OnlinePluginData(savedData, onlineData)
}.filter {
it.validOnlineData(activity)
}
- }.flatten().distinctBy { it.onlineData.plugin.url }
+ }.flatten().distinctBy { it.onlineData.second.url }
debugPrint {
"Outdated plugins: ${outdatedPlugins.filter { it.isOutdated }}"
@@ -302,21 +285,20 @@ object PluginManager {
val updatedPlugins = mutableListOf()
- outdatedPlugins.amap { pluginData ->
+ outdatedPlugins.apmap { pluginData ->
if (pluginData.isDisabled) {
//updatedPlugins.add(activity.getString(R.string.single_plugin_disabled, pluginData.onlineData.second.name))
unloadPlugin(pluginData.savedData.filePath)
} else if (pluginData.isOutdated) {
downloadPlugin(
activity,
- pluginData.onlineData.plugin.url,
- pluginData.onlineData.plugin.fileHash,
+ pluginData.onlineData.second.url,
pluginData.savedData.internalName,
File(pluginData.savedData.filePath),
true
).let { success ->
if (success)
- updatedPlugins.add(pluginData.onlineData.plugin.name)
+ updatedPlugins.add(pluginData.onlineData.second.name)
}
}
}
@@ -342,32 +324,21 @@ object PluginManager {
* 1. Gets all online data from online plugins repo
* 2. Fetch all not downloaded plugins
* 3. Download them and reload plugins
- *
- * DO NOT USE THIS IN A PLUGIN! It may case an infinite recursive loop lagging or crashing everyone's devices.
- * If you use it from a plugin, do not expect a stable jvmName, SO DO NOT USE IT!
- */
- @Suppress("FunctionName")
- @InternalAPI
- @Throws
- suspend fun ___DO_NOT_CALL_FROM_A_PLUGIN_downloadNotExistingPluginsAndLoad(
- activity: Activity,
- mode: AutoDownloadMode
- ) {
- assertNonRecursiveCallstack()
-
+ **/
+ fun downloadNotExistingPluginsAndLoad(activity: Activity, mode: AutoDownloadMode) {
val newDownloadPlugins = mutableListOf()
val urls = (getKey>(REPOSITORIES_KEY)
?: emptyArray()) + PREBUILT_REPOSITORIES
- val onlinePlugins = urls.toList().amap {
- getRepoPlugins(it)?.toList() ?: emptyList()
- }.flatten().distinctBy { it.plugin.url }
+ val onlinePlugins = urls.toList().apmap {
+ getRepoPlugins(it.url)?.toList() ?: emptyList()
+ }.flatten().distinctBy { it.second.url }
val providerLang = activity.getApiProviderLangSettings()
//Log.i(TAG, "providerLang => ${providerLang.toJson()}")
// Iterate online repos and returns not downloaded plugins
val notDownloadedPlugins = onlinePlugins.mapNotNull { onlineData ->
- val sitePlugin = onlineData.plugin
+ val sitePlugin = onlineData.second
val tvtypes = sitePlugin.tvTypes ?: listOf()
//Don't include empty urls
@@ -379,7 +350,7 @@ object PluginManager {
}
//Omit already existing plugins
- if (getPluginPath(activity, sitePlugin.internalName, onlineData.repositoryData.url).exists()) {
+ if (getPluginPath(activity, sitePlugin.internalName, onlineData.first).exists()) {
Log.i(TAG, "Skip > ${sitePlugin.internalName}")
return@mapNotNull null
}
@@ -418,17 +389,16 @@ object PluginManager {
}
//Log.i(TAG, "notDownloadedPlugins => ${notDownloadedPlugins.toJson()}")
- notDownloadedPlugins.amap { pluginData ->
+ notDownloadedPlugins.apmap { pluginData ->
downloadPlugin(
activity,
- pluginData.onlineData.plugin.url,
- pluginData.onlineData.plugin.fileHash,
+ pluginData.onlineData.second.url,
pluginData.savedData.internalName,
- pluginData.onlineData.repositoryData.url,
+ pluginData.onlineData.first,
!pluginData.isDisabled
).let { success ->
if (success)
- newDownloadPlugins.add(pluginData.onlineData.plugin.name)
+ newDownloadPlugins.add(pluginData.onlineData.second.name)
}
}
@@ -444,27 +414,12 @@ object PluginManager {
Log.i(TAG, "Plugin download done!")
}
- @Throws
- private fun assertNonRecursiveCallstack() {
- if (Thread.currentThread().stackTrace.any { it.methodName == "loadPlugin" }) {
- throw Error("You tried to call a function that will recursively call loadPlugin, this will cause crashes or memory leaks. Do not do this, there is better ways to implement the feature than reloading plugins. Are you sure you read the compile error or docs?")
- }
- }
-
/**
* Use updateAllOnlinePluginsAndLoadThem
- *
- * DO NOT USE THIS IN A PLUGIN! It may case an infinite recursive loop lagging or crashing everyone's devices.
- * If you use it from a plugin, do not expect a stable jvmName, SO DO NOT USE IT!
- */
- @Suppress("FunctionName")
- @InternalAPI
- @Throws
- suspend fun ___DO_NOT_CALL_FROM_A_PLUGIN_loadAllOnlinePlugins(context: Context) {
- assertNonRecursiveCallstack()
-
+ * */
+ fun loadAllOnlinePlugins(context: Context) {
// Load all plugins as fast as possible!
- (getPluginsOnline()).toList().amap { pluginData ->
+ (getPluginsOnline()).toList().apmap { pluginData ->
loadPlugin(
context,
File(pluginData.filePath),
@@ -475,46 +430,27 @@ object PluginManager {
/**
* Reloads all local plugins and forces a page update, used for hot reloading with deployWithAdb
- *
- * DO NOT USE THIS IN A PLUGIN! It may case an infinite recursive loop lagging or crashing everyone's devices.
- * If you use it from a plugin, do not expect a stable jvmName, SO DO NOT USE IT!
- */
- @Suppress("FunctionName")
- @InternalAPI
- @Throws
- suspend fun ___DO_NOT_CALL_FROM_A_PLUGIN_hotReloadAllLocalPlugins(activity: FragmentActivity?) {
- assertNonRecursiveCallstack()
-
+ **/
+ fun hotReloadAllLocalPlugins(activity: FragmentActivity?) {
Log.d(TAG, "Reloading all local plugins!")
if (activity == null) return
getPluginsLocal().forEach {
unloadPlugin(it.filePath)
}
- ___DO_NOT_CALL_FROM_A_PLUGIN_loadAllLocalPlugins(activity, true)
+ loadAllLocalPlugins(activity, true)
}
/**
* @param forceReload see afterPluginsLoadedEvent, basically a way to load all local plugins
* and reload all pages even if they are previously valid
- *
- * DO NOT USE THIS IN A PLUGIN! It may case an infinite recursive loop lagging or crashing everyone's devices.
- * If you use it from a plugin, do not expect a stable jvmName, SO DO NOT USE IT!
- */
- @Suppress("FunctionName")
- @InternalAPI
- @Throws
- suspend fun ___DO_NOT_CALL_FROM_A_PLUGIN_loadAllLocalPlugins(context: Context, forceReload: Boolean) {
- assertNonRecursiveCallstack()
-
+ **/
+ fun loadAllLocalPlugins(context: Context, forceReload: Boolean) {
val dir = File(LOCAL_PLUGINS_PATH)
if (!dir.exists()) {
val res = dir.mkdirs()
if (!res) {
Log.w(TAG, "Failed to create local directories")
- // We have tried to load local plugins, but exit early.
- // This needs to be true to prevent the downloader waiting for plugins.
- loadedLocalPlugins = true
return
}
}
@@ -535,7 +471,7 @@ object PluginManager {
// Make sure all local plugins are fully refreshed.
removeKey(PLUGINS_KEY_LOCAL)
- sortedPlugins?.sortedBy { it.name }?.amap { file ->
+ sortedPlugins?.sortedBy { it.name }?.apmap { file ->
try {
val destinationFile = File(pluginDirectory, file.name)
@@ -543,8 +479,7 @@ object PluginManager {
// has been modified (check file length and modification time).
if (!destinationFile.exists() ||
destinationFile.length() != file.length() ||
- destinationFile.lastModified() != file.lastModified()
- ) {
+ destinationFile.lastModified() != file.lastModified()) {
// Copy the file to the app-specific plugin directory
file.copyTo(destinationFile, overwrite = true)
@@ -567,19 +502,14 @@ object PluginManager {
afterPluginsLoadedEvent.invoke(forceReload)
}
- /** @return true if safe mode is enabled in any possible way. */
- fun isSafeMode(): Boolean {
- return checkSafeModeFile() || lastError != null
- }
-
/**
* This can be used to override any extension loading to fix crashes!
* @return true if safe mode file is present
**/
fun checkSafeModeFile(): Boolean {
- return safe {
+ return normalSafeApiCall {
val folder = File(CLOUD_STREAM_FOLDER)
- if (!folder.exists()) return@safe false
+ if (!folder.exists()) return@normalSafeApiCall false
val files = folder.listFiles { _, name ->
name.equals("safe", ignoreCase = true)
}
@@ -616,7 +546,7 @@ object PluginManager {
return false
}
InputStreamReader(stream).use { reader ->
- manifest = parseJson(reader.readText())
+ manifest = parseJson(reader, BasePlugin.Manifest::class.java)
}
}
@@ -657,15 +587,9 @@ object PluginManager {
context.resources.configuration
)
}
- synchronized(plugins) {
- plugins[filePath] = pluginInstance
- }
- synchronized(classLoaders) {
- classLoaders[loader] = pluginInstance
- }
- synchronized(urlPlugins) {
- urlPlugins[data.url ?: filePath] = pluginInstance
- }
+ plugins[filePath] = pluginInstance
+ classLoaders[loader] = pluginInstance
+ urlPlugins[data.url ?: filePath] = pluginInstance
if (pluginInstance is Plugin) {
pluginInstance.load(context)
} else {
@@ -677,7 +601,7 @@ object PluginManager {
} catch (e: Throwable) {
Log.e(TAG, "Failed to load $file: ${Log.getStackTraceString(e)}")
showToast(
- // context.getActivity(), // we are not always on the main thread
+ context.getActivity(),
context.getString(R.string.plugin_load_fail).format(fileName),
Toast.LENGTH_LONG
)
@@ -701,33 +625,25 @@ object PluginManager {
}
// remove all registered apis
- APIHolder.apis.filter { api -> api.sourcePlugin == plugin.filename }.forEach {
- removePluginMapping(it)
+ synchronized(APIHolder.apis) {
+ APIHolder.apis.filter { api -> api.sourcePlugin == plugin.filename }.forEach {
+ removePluginMapping(it)
+ }
+ }
+ synchronized(APIHolder.allProviders) {
+ APIHolder.allProviders.removeIf { provider: MainAPI -> provider.sourcePlugin == plugin.filename }
}
- APIHolder.allProviders.withLock {
- APIHolder.allProviders.removeAll { provider -> provider.sourcePlugin == plugin.filename }
+ extractorApis.removeIf { provider: ExtractorApi -> provider.sourcePlugin == plugin.filename }
+
+ synchronized(VideoClickActionHolder.allVideoClickActions) {
+ VideoClickActionHolder.allVideoClickActions.removeIf { action: VideoClickAction -> action.sourcePlugin == plugin.filename }
}
- extractorApis.withLock {
- extractorApis.removeAll { provider -> provider.sourcePlugin == plugin.filename }
- }
+ classLoaders.values.removeIf { v -> v == plugin }
- VideoClickActionHolder.allVideoClickActions.withLock {
- VideoClickActionHolder.allVideoClickActions.removeAll { action -> action.sourcePlugin == plugin.filename }
- }
-
- synchronized(classLoaders) {
- classLoaders.values.removeIf { v -> v == plugin }
- }
-
- synchronized(plugins) {
- plugins.remove(absolutePath)
- }
-
- synchronized(urlPlugins) {
- urlPlugins.values.removeIf { v -> v == plugin }
- }
+ plugins.remove(absolutePath)
+ urlPlugins.values.removeIf { v -> v == plugin }
}
/**
@@ -757,27 +673,25 @@ object PluginManager {
suspend fun downloadPlugin(
activity: Activity,
pluginUrl: String,
- pluginHash: String?,
internalName: String,
repositoryUrl: String,
loadPlugin: Boolean
): Boolean {
val file = getPluginPath(activity, internalName, repositoryUrl)
- return downloadPlugin(activity, pluginUrl, pluginHash, internalName, file, loadPlugin)
+ return downloadPlugin(activity, pluginUrl, internalName, file, loadPlugin)
}
suspend fun downloadPlugin(
activity: Activity,
pluginUrl: String,
- pluginHash: String?,
internalName: String,
file: File,
- loadPlugin: Boolean,
+ loadPlugin: Boolean
): Boolean {
try {
Log.d(TAG, "Downloading plugin: $pluginUrl to ${file.absolutePath}")
// The plugin file needs to be salted with the repository url hash as to allow multiple repositories with the same internal plugin names
- val newFile = downloadPluginToFile(activity, pluginUrl, file, pluginHash) ?: return false
+ val newFile = downloadPluginToFile(pluginUrl, file) ?: return false
val data = PluginData(
internalName,
@@ -820,84 +734,6 @@ object PluginManager {
}
}
- /**
- * DO NOT USE THIS IN A PLUGIN! It may case an infinite recursive loop lagging or crashing everyone's devices.
- * If you use it from a plugin, do not expect a stable jvmName, SO DO NOT USE IT!
- */
- @Suppress("FunctionName")
- @InternalAPI
- @Throws
- suspend fun ___DO_NOT_CALL_FROM_A_PLUGIN_manuallyReloadAndUpdatePlugins(activity: Activity) {
- assertNonRecursiveCallstack()
-
- showToast(activity.getString(R.string.starting_plugin_update_manually), Toast.LENGTH_LONG)
-
- ___DO_NOT_CALL_FROM_A_PLUGIN_loadAllOnlinePlugins(activity)
- afterPluginsLoadedEvent.invoke(false)
-
- val urls = (getKey>(REPOSITORIES_KEY)
- ?: emptyArray()) + PREBUILT_REPOSITORIES
- val onlinePlugins = urls.toList().amap {
- getRepoPlugins(it) ?: emptyList()
- }.flatten().distinctBy { it.plugin.url }
-
- val allPlugins = getPluginsOnline().flatMap { savedData ->
- onlinePlugins
- .filter { it.plugin.internalName == savedData.internalName }
- .mapNotNull { onlineData ->
- OnlinePluginData(savedData, onlineData).takeIf { it.validOnlineData(activity) }
- }
- }.distinctBy { it.onlineData.plugin.url }
-
- val updatedPlugins = mutableListOf()
-
- allPlugins.amap { pluginData ->
- if (pluginData.isDisabled) {
- Log.e(
- "PluginManager",
- "Unloading disabled plugin: ${pluginData.onlineData.plugin.name}"
- )
- unloadPlugin(pluginData.savedData.filePath)
- } else {
- val existingFile = File(pluginData.savedData.filePath)
- if (existingFile.exists()) existingFile.delete()
-
- if (downloadPlugin(
- activity,
- pluginData.onlineData.plugin.url,
- pluginData.onlineData.plugin.fileHash,
- pluginData.savedData.internalName,
- existingFile,
- true
- )
- ) {
- updatedPlugins.add(pluginData.onlineData.plugin.name)
- }
- }
- }.also {
- main {
- val message = if (updatedPlugins.isNotEmpty()) {
- activity.getString(R.string.plugins_updated_manually, updatedPlugins.size)
- } else {
- activity.getString(R.string.no_plugins_updated_manually)
- }
- showToast(message, Toast.LENGTH_LONG)
-
- val notificationText = UiText.StringResource(
- R.string.plugins_updated_manually,
- listOf(updatedPlugins.size)
- )
- createNotification(activity, notificationText, updatedPlugins)
-
- }
- }
-
- loadedOnlinePlugins = true
- afterPluginsLoadedEvent.invoke(false)
-
- Log.i("PluginManager", "Plugin update done!")
- }
-
private fun Context.createNotificationChannel() {
hasCreatedNotChanel = true
// Create the NotificationChannel, but only on API 26+ because
@@ -964,4 +800,4 @@ object PluginManager {
return null
}
}
-}
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/plugins/RepositoryManager.kt b/app/src/main/java/com/lagradost/cloudstream3/plugins/RepositoryManager.kt
index 3879ddca4..c6ec9df7f 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/plugins/RepositoryManager.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/plugins/RepositoryManager.kt
@@ -1,42 +1,37 @@
package com.lagradost.cloudstream3.plugins
import android.content.Context
-import androidx.annotation.WorkerThread
import com.fasterxml.jackson.annotation.JsonProperty
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.context
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
+import com.lagradost.cloudstream3.AcraApplication.Companion.context
+import com.lagradost.cloudstream3.AcraApplication.Companion.getKey
+import com.lagradost.cloudstream3.AcraApplication.Companion.setKey
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.amap
import com.lagradost.cloudstream3.app
import com.lagradost.cloudstream3.mvvm.logError
-import com.lagradost.cloudstream3.mvvm.safe
-import com.lagradost.cloudstream3.mvvm.safeAsync
+import com.lagradost.cloudstream3.mvvm.normalSafeApiCall
+import com.lagradost.cloudstream3.mvvm.suspendSafeApiCall
import com.lagradost.cloudstream3.plugins.PluginManager.getPluginSanitizedFileName
import com.lagradost.cloudstream3.plugins.PluginManager.unloadPlugin
import com.lagradost.cloudstream3.ui.settings.extensions.REPOSITORIES_KEY
import com.lagradost.cloudstream3.ui.settings.extensions.RepositoryData
+import com.lagradost.cloudstream3.utils.AppUtils.tryParseJson
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
+import java.io.BufferedInputStream
import java.io.File
-import java.nio.file.AtomicMoveNotSupportedException
-import java.nio.file.Files
-import java.nio.file.StandardCopyOption
-import java.security.MessageDigest
-import java.util.concurrent.TimeUnit
+import java.io.InputStream
+import java.io.OutputStream
/**
* Comes with the app, always available in the app, non removable.
- */
-@Serializable
+ * */
+
data class Repository(
- @JsonProperty("iconUrl") @SerialName("iconUrl") val iconUrl: String?,
- @JsonProperty("name") @SerialName("name") val name: String,
- @JsonProperty("description") @SerialName("description") val description: String?,
- @JsonProperty("manifestVersion") @SerialName("manifestVersion") val manifestVersion: Int,
- @JsonProperty("pluginLists") @SerialName("pluginLists") val pluginLists: List,
+ @JsonProperty("name") val name: String,
+ @JsonProperty("description") val description: String?,
+ @JsonProperty("manifestVersion") val manifestVersion: Int,
+ @JsonProperty("pluginLists") val pluginLists: List
)
/**
@@ -45,81 +40,40 @@ data class Repository(
* 1: Ok
* 2: Slow
* 3: Beta only
- */
-@Serializable
+ * */
data class SitePlugin(
// Url to the .cs3 file
- @JsonProperty("url") @SerialName("url") val url: String,
+ @JsonProperty("url") val url: String,
// Status to remotely disable the provider
- @JsonProperty("status") @SerialName("status") val status: Int,
+ @JsonProperty("status") val status: Int,
// Integer over 0, any change of this will trigger an auto update
- @JsonProperty("version") @SerialName("version") val version: Int,
+ @JsonProperty("version") val version: Int,
// Unused currently, used to make the api backwards compatible?
// Set to 1
- @JsonProperty("apiVersion") @SerialName("apiVersion") val apiVersion: Int,
+ @JsonProperty("apiVersion") val apiVersion: Int,
// Name to be shown in app
- @JsonProperty("name") @SerialName("name") val name: String,
+ @JsonProperty("name") val name: String,
// Name to be referenced internally. Separate to make name and url changes possible
- @JsonProperty("internalName") @SerialName("internalName") val internalName: String,
- @JsonProperty("authors") @SerialName("authors") val authors: List,
- @JsonProperty("description") @SerialName("description") val description: String?,
+ @JsonProperty("internalName") val internalName: String,
+ @JsonProperty("authors") val authors: List,
+ @JsonProperty("description") val description: String?,
// Might be used to go directly to the plugin repo in the future
- @JsonProperty("repositoryUrl") @SerialName("repositoryUrl") val repositoryUrl: String?,
+ @JsonProperty("repositoryUrl") val repositoryUrl: String?,
// These types are yet to be mapped and used, ignore for now
- @JsonProperty("tvTypes") @SerialName("tvTypes") val tvTypes: List?,
- // Most often a language tag like "en" or "zh-TW"
- @JsonProperty("language") @SerialName("language") val language: String?,
- @JsonProperty("iconUrl") @SerialName("iconUrl") val iconUrl: String?,
+ @JsonProperty("tvTypes") val tvTypes: List?,
+ @JsonProperty("language") val language: String?,
+ @JsonProperty("iconUrl") val iconUrl: String?,
// Automatically generated by the gradle plugin
- @JsonProperty("fileSize") @SerialName("fileSize") val fileSize: Long?,
- @JsonProperty("fileHash") @SerialName("fileHash") val fileHash: String?,
+ @JsonProperty("fileSize") val fileSize: Long?,
)
-@Serializable
-data class PluginWrapper(
- @JsonProperty("repository") @SerialName("repository") val repository: Repository,
- @JsonProperty("repositoryData") @SerialName("repositoryData") val repositoryData: RepositoryData,
- @JsonProperty("plugin") @SerialName("plugin") val plugin: SitePlugin
-) {
- companion object {
- private val localRepository = Repository("", "", "", 1, emptyList())
- private val localRepositoryData = RepositoryData("", "", "")
- fun getLocalPluginWrapper(plugin: SitePlugin): PluginWrapper {
- return PluginWrapper(
- localRepository,
- localRepositoryData,
- plugin
- )
- }
- }
-}
-
object RepositoryManager {
const val ONLINE_PLUGINS_FOLDER = "Extensions"
val PREBUILT_REPOSITORIES: Array by lazy {
- getKey>("PREBUILT_REPOSITORIES") ?: emptyArray()
- }
- private val GH_REGEX =
- Regex("^https://raw.githubusercontent.com/([A-Za-z0-9-]+)/([A-Za-z0-9_.-]+)/(.*)$")
-
-
- /** Returns a SHA-256 string of the file content.
- * Example: "sha256-b70462c264cb7f90fc2860a8e58d7544ce747ff347d1d11fa093623901853573" **/
- @WorkerThread
- fun sha256(file: File): String {
- val digest = MessageDigest.getInstance("SHA-256")
-
- file.inputStream().use { fis ->
- val buffer = ByteArray(8192)
- var read = fis.read(buffer)
- while (read != -1) {
- digest.update(buffer, 0, read)
- read = fis.read(buffer)
- }
- }
- return "sha256-" + digest.digest().joinToString("") { "%02x".format(it) }
+ getKey("PREBUILT_REPOSITORIES") ?: emptyArray()
}
+ private val GH_REGEX = Regex("^https://raw.githubusercontent.com/([A-Za-z0-9-]+)/([A-Za-z0-9_.-]+)/(.*)$")
/* Convert raw.githubusercontent.com urls to cdn.jsdelivr.net if enabled in settings */
fun convertRawGitUrl(url: String): String {
@@ -140,37 +94,32 @@ object RepositoryManager {
else fixedUrl
}
} else if (fixedUrl.matches("^[a-zA-Z0-9!_-]+$".toRegex())) {
- safeAsync {
- if (fixedUrl.startsWith("!")) {
- val response = app.get("https://py.md/${fixedUrl.removePrefix("!")}", allowRedirects = false)
- val url = response.headers["Location"] ?: return@safeAsync null
- if (url.startsWith("https://py.md/404")) return@safeAsync null
- if (url.removeSuffix("/") == "https://py.md") return@safeAsync null
- return@safeAsync url
- } else {
- val response = app.get("https://cutt.ly/${fixedUrl}", allowRedirects = false)
- val url = response.headers["Location"] ?: return@safeAsync null
- if (url.startsWith("https://cutt.ly/404")) return@safeAsync null
- if (url.removeSuffix("/") == "https://cutt.ly") return@safeAsync null
- return@safeAsync url
+ suspendSafeApiCall {
+ app.get("https://cutt.ly/${fixedUrl}", allowRedirects = false).let { it2 ->
+ it2.headers["Location"]?.let { url ->
+ if (url.startsWith("https://cutt.ly/404")) return@suspendSafeApiCall null
+ if (url.removeSuffix("/") == "https://cutt.ly") return@suspendSafeApiCall null
+ return@suspendSafeApiCall url
+ }
}
}
} else null
}
suspend fun parseRepository(url: String): Repository? {
- return safeAsync {
+ return suspendSafeApiCall {
// Take manifestVersion and such into account later
- app.get(convertRawGitUrl(url), cacheTime = 5, cacheUnit = TimeUnit.MINUTES)
- .parsedSafe()
+ app.get(convertRawGitUrl(url)).parsedSafe()
}
}
private suspend fun parsePlugins(pluginUrls: String): List {
// Take manifestVersion and such into account later
return try {
- app.get(convertRawGitUrl(pluginUrls), cacheTime = 5, cacheUnit = TimeUnit.MINUTES)
- .parsed>().toList()
+ val response = app.get(convertRawGitUrl(pluginUrls))
+ // Normal parsed function not working?
+ // return response.parsedSafe()
+ tryParseJson>(response.text)?.toList() ?: emptyList()
} catch (t: Throwable) {
logError(t)
emptyList()
@@ -179,68 +128,37 @@ object RepositoryManager {
/**
* Gets all plugins from repositories and pairs them with the repository url
- */
- suspend fun getRepoPlugins(repositoryData: RepositoryData): List? {
- val repo = parseRepository(repositoryData.url) ?: return null
- val list = repo.pluginLists.amap { url ->
+ * */
+ suspend fun getRepoPlugins(repositoryUrl: String): List>? {
+ val repo = parseRepository(repositoryUrl) ?: return null
+ return repo.pluginLists.amap { url ->
parsePlugins(url).map {
- PluginWrapper(repo, repositoryData, it)
+ repositoryUrl to it
}
}.flatten()
- return list
}
suspend fun downloadPluginToFile(
- context: Context,
pluginUrl: String,
- file: File,
- expectedFileHash: String?
+ file: File
): File? {
- return safeAsync {
- val parentDir = file.parentFile ?: return@safeAsync null
- parentDir.mkdirs()
+ return suspendSafeApiCall {
+ file.mkdirs()
- // Prevent corrupting the plugin file if the operation fails
- val tempFile = File.createTempFile(file.name, ".tmp", context.cacheDir)
+ // Overwrite if exists
+ if (file.exists()) {
+ file.delete()
+ }
+ file.createNewFile()
val body = app.get(convertRawGitUrl(pluginUrl)).okhttpResponse.body
-
- body.byteStream().use { body ->
- tempFile.outputStream().use { fileSteam ->
- body.copyTo(fileSteam)
- }
- }
-
- if (expectedFileHash != null) {
- val downloadHash = sha256(tempFile)
- if (expectedFileHash != downloadHash) {
- tempFile.delete()
- throw IllegalStateException("Extension hash mismatch when validating '${file.name}'! Expected: '$expectedFileHash', got: '$downloadHash'.")
- }
- }
-
- // We prefer the operation to be atomic
- try {
- Files.move(
- tempFile.toPath(),
- file.toPath(),
- StandardCopyOption.REPLACE_EXISTING,
- StandardCopyOption.ATOMIC_MOVE
- )
- } catch (_: AtomicMoveNotSupportedException) {
- Files.move(
- tempFile.toPath(),
- file.toPath(),
- StandardCopyOption.REPLACE_EXISTING
- )
- }
-
+ write(body.byteStream(), file.outputStream())
file
}
}
fun getRepositories(): Array {
- return getKey>(REPOSITORIES_KEY) ?: emptyArray()
+ return getKey(REPOSITORIES_KEY) ?: emptyArray()
}
// Don't want to read before we write in another thread
@@ -255,7 +173,7 @@ object RepositoryManager {
/**
* Also deletes downloaded repository plugins
- */
+ * */
suspend fun removeRepository(context: Context, repository: RepositoryData) {
val extensionsDir = File(context.filesDir, ONLINE_PLUGINS_FOLDER)
@@ -273,7 +191,7 @@ object RepositoryManager {
// Unload all plugins, not using deletePlugin since we
// delete all data and files in deleteRepositoryData
- safe {
+ normalSafeApiCall {
file.listFiles { plugin: File ->
unloadPlugin(plugin.absolutePath)
false
@@ -282,4 +200,13 @@ object RepositoryManager {
PluginManager.deleteRepositoryData(file.absolutePath)
}
+
+ private fun write(stream: InputStream, output: OutputStream) {
+ val input = BufferedInputStream(stream)
+ val dataBuffer = ByteArray(512)
+ var readBytes: Int
+ while (input.read(dataBuffer).also { readBytes = it } != -1) {
+ output.write(dataBuffer, 0, readBytes)
+ }
+ }
}
diff --git a/app/src/main/java/com/lagradost/cloudstream3/plugins/VotingApi.kt b/app/src/main/java/com/lagradost/cloudstream3/plugins/VotingApi.kt
index 57f6f4750..d1b702f4c 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/plugins/VotingApi.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/plugins/VotingApi.kt
@@ -2,88 +2,97 @@ package com.lagradost.cloudstream3.plugins
import android.util.Log
import android.widget.Toast
-import com.fasterxml.jackson.annotation.JsonProperty
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.context
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
+import com.lagradost.cloudstream3.AcraApplication.Companion.context
+import com.lagradost.cloudstream3.AcraApplication.Companion.getKey
+import com.lagradost.cloudstream3.AcraApplication.Companion.setKey
import com.lagradost.cloudstream3.R
import java.security.MessageDigest
import com.lagradost.cloudstream3.app
import com.lagradost.cloudstream3.utils.Coroutines.main
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
-object VotingApi {
+object VotingApi { // please do not cheat the votes lol
private const val LOGKEY = "VotingApi"
- private const val API_DOMAIN = "https://api.countify.xyz"
- private fun transformUrl(url: String): String =
+ private const val API_DOMAIN = "https://counterapi.com/api"
+
+ private fun transformUrl(url: String): String = // dont touch or all votes get reset
MessageDigest
.getInstance("SHA-256")
.digest("${url}#funny-salt".toByteArray())
.fold("") { str, it -> str + "%02x".format(it) }
- suspend fun SitePlugin.getVotes(): Int = getVotes(url)
- fun SitePlugin.hasVoted(): Boolean = hasVoted(url)
- suspend fun SitePlugin.vote(): Int = vote(url)
- fun SitePlugin.canVote(): Boolean = canVote(this.url)
+ suspend fun SitePlugin.getVotes(): Int {
+ return getVotes(url)
+ }
+ fun SitePlugin.hasVoted(): Boolean {
+ return hasVoted(url)
+ }
+
+ suspend fun SitePlugin.vote(): Int {
+ return vote(url)
+ }
+
+ fun SitePlugin.canVote(): Boolean {
+ return canVote(this.url)
+ }
+
+ // Plugin url to Int
private val votesCache = mutableMapOf()
+ private fun getRepository(pluginUrl: String) = pluginUrl
+ .split("/")
+ .drop(2)
+ .take(3)
+ .joinToString("-")
+
private suspend fun readVote(pluginUrl: String): Int {
- val id = transformUrl(pluginUrl)
- val url = "$API_DOMAIN/get-total/$id"
- Log.d(LOGKEY, "Requesting GET: $url")
- return app.get(url).parsedSafe()?.count ?: 0
+ val url = "${API_DOMAIN}/cs-${getRepository(pluginUrl)}/vote/${transformUrl(pluginUrl)}?readOnly=true"
+ Log.d(LOGKEY, "Requesting: $url")
+ return app.get(url).parsedSafe()?.value ?: 0
}
private suspend fun writeVote(pluginUrl: String): Boolean {
- val id = transformUrl(pluginUrl)
- val url = "$API_DOMAIN/increment/$id"
- Log.d(LOGKEY, "Requesting POST: $url")
- return app.post(url, emptyMap())
- .parsedSafe()?.count != null
+ val url = "${API_DOMAIN}/cs-${getRepository(pluginUrl)}/vote/${transformUrl(pluginUrl)}"
+ Log.d(LOGKEY, "Requesting: $url")
+ return app.get(url).parsedSafe()?.value != null
}
suspend fun getVotes(pluginUrl: String): Int =
- votesCache[pluginUrl] ?: readVote(pluginUrl).also {
- votesCache[pluginUrl] = it
- }
+ votesCache[pluginUrl] ?: readVote(pluginUrl).also {
+ votesCache[pluginUrl] = it
+ }
- fun hasVoted(pluginUrl: String): Boolean =
- getKey("cs3-votes/${transformUrl(pluginUrl)}") ?: false
+ fun hasVoted(pluginUrl: String) =
+ getKey("cs3-votes/${transformUrl(pluginUrl)}") ?: false
- fun canVote(pluginUrl: String): Boolean =
- PluginManager.urlPlugins.contains(pluginUrl)
+ fun canVote(pluginUrl: String): Boolean {
+ return PluginManager.urlPlugins.contains(pluginUrl)
+ }
private val voteLock = Mutex()
-
suspend fun vote(pluginUrl: String): Int {
+ // Prevent multiple requests at the same time.
voteLock.withLock {
if (!canVote(pluginUrl)) {
main {
- Toast.makeText(
- context,
- R.string.extension_install_first,
- Toast.LENGTH_SHORT
- ).show()
+ Toast.makeText(context, R.string.extension_install_first, Toast.LENGTH_SHORT)
+ .show()
}
return getVotes(pluginUrl)
}
if (hasVoted(pluginUrl)) {
main {
- Toast.makeText(
- context,
- R.string.already_voted,
- Toast.LENGTH_SHORT
- ).show()
+ Toast.makeText(context, R.string.already_voted, Toast.LENGTH_SHORT)
+ .show()
}
return getVotes(pluginUrl)
}
+
if (writeVote(pluginUrl)) {
setKey("cs3-votes/${transformUrl(pluginUrl)}", true)
votesCache[pluginUrl] = votesCache[pluginUrl]?.plus(1) ?: 1
@@ -93,9 +102,7 @@ object VotingApi {
}
}
- @Serializable
- private data class CountifyResult(
- @JsonProperty("id") @SerialName("id") val id: String? = null,
- @JsonProperty("count") @SerialName("count") val count: Int? = null,
+ private data class Result(
+ val value: Int?
)
-}
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/services/DownloadQueueService.kt b/app/src/main/java/com/lagradost/cloudstream3/services/DownloadQueueService.kt
deleted file mode 100644
index e07747a86..000000000
--- a/app/src/main/java/com/lagradost/cloudstream3/services/DownloadQueueService.kt
+++ /dev/null
@@ -1,279 +0,0 @@
-package com.lagradost.cloudstream3.services
-
-import android.Manifest
-import android.app.Service
-import android.content.Context
-import android.content.Intent
-import android.content.pm.PackageManager
-import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
-import android.os.Build.VERSION.SDK_INT
-import android.os.IBinder
-import android.util.Log
-import androidx.core.app.NotificationCompat
-import androidx.core.app.NotificationManagerCompat
-import androidx.core.app.PendingIntentCompat
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.removeKey
-import com.lagradost.cloudstream3.MainActivity
-import com.lagradost.cloudstream3.MainActivity.Companion.lastError
-import com.lagradost.cloudstream3.MainActivity.Companion.setLastError
-import com.lagradost.cloudstream3.R
-import com.lagradost.cloudstream3.mvvm.debugAssert
-import com.lagradost.cloudstream3.mvvm.debugWarning
-import com.lagradost.cloudstream3.mvvm.logError
-import com.lagradost.cloudstream3.mvvm.safe
-import com.lagradost.cloudstream3.plugins.PluginManager
-import com.lagradost.cloudstream3.utils.AppContextUtils.createNotificationChannel
-import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
-import com.lagradost.cloudstream3.utils.UIHelper.colorFromAttribute
-import com.lagradost.cloudstream3.utils.downloader.DownloadQueueManager
-import com.lagradost.cloudstream3.utils.downloader.VideoDownloadManager
-import com.lagradost.cloudstream3.utils.downloader.VideoDownloadManager.KEY_RESUME_IN_QUEUE
-import com.lagradost.cloudstream3.utils.downloader.VideoDownloadManager.KEY_RESUME_PACKAGES
-import com.lagradost.cloudstream3.utils.downloader.VideoDownloadManager.downloadEvent
-import kotlinx.coroutines.ExperimentalCoroutinesApi
-import kotlinx.coroutines.FlowPreview
-import kotlinx.coroutines.delay
-import kotlinx.coroutines.flow.MutableStateFlow
-import kotlinx.coroutines.flow.StateFlow
-import kotlinx.coroutines.flow.combine
-import kotlinx.coroutines.flow.debounce
-import kotlinx.coroutines.flow.takeWhile
-import kotlinx.coroutines.flow.update
-import kotlinx.coroutines.flow.updateAndGet
-import kotlinx.coroutines.withTimeoutOrNull
-import kotlin.system.measureTimeMillis
-import kotlin.time.Duration.Companion.milliseconds
-import kotlin.time.Duration.Companion.seconds
-
-class DownloadQueueService : Service() {
- companion object {
- const val TAG = "DownloadQueueService"
- const val DOWNLOAD_QUEUE_CHANNEL_ID = "cloudstream3.download.queue"
- const val DOWNLOAD_QUEUE_CHANNEL_NAME = "Download queue service"
- const val DOWNLOAD_QUEUE_CHANNEL_DESCRIPTION = "App download queue notification."
- const val DOWNLOAD_QUEUE_NOTIFICATION_ID = 917194232 // Random unique
- @Volatile
- var isRunning = false
-
- fun getIntent(
- context: Context,
- ): Intent {
- return Intent(context, DownloadQueueService::class.java)
- }
-
- private val _downloadInstances: MutableStateFlow> =
- MutableStateFlow(emptyList())
-
- /** Flow of all active downloads, not queued. May temporarily contain completed or failed EpisodeDownloadInstances.
- * Completed or failed instances are automatically removed by the download queue service.
- *
- */
- val downloadInstances: StateFlow> =
- _downloadInstances
-
- private val totalDownloadFlow =
- downloadInstances.combine(DownloadQueueManager.queue) { instances, queue ->
- instances to queue
- }
- .combine(VideoDownloadManager.currentDownloads) { (instances, queue), currentDownloads ->
- Triple(instances, queue, currentDownloads)
- }
- }
-
-
- private val baseNotification by lazy {
- val intent = Intent(this, MainActivity::class.java)
- val pendingIntent =
- PendingIntentCompat.getActivity(this, 0, intent, 0, false)
-
- val activeDownloads = resources.getQuantityString(R.plurals.downloads_active, 0).format(0)
- val activeQueue = resources.getQuantityString(R.plurals.downloads_queued, 0).format(0)
-
- NotificationCompat.Builder(this, DOWNLOAD_QUEUE_CHANNEL_ID)
- .setOngoing(true) // Make it persistent
- .setAutoCancel(false)
- .setColorized(false)
- .setOnlyAlertOnce(true)
- .setSilent(true)
- .setShowWhen(false)
- // If low priority then the notification might not show :(
- .setPriority(NotificationCompat.PRIORITY_DEFAULT)
- .setColor(this.colorFromAttribute(R.attr.colorPrimary))
- .setContentText(activeDownloads)
- .setSubText(activeQueue)
- .setContentIntent(pendingIntent)
- .setSmallIcon(R.drawable.download_icon_load)
- }
-
-
- private fun updateNotification(context: Context, downloads: Int, queued: Int) {
- if (context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS)
- != PackageManager.PERMISSION_GRANTED
- ) return
-
- val activeDownloads =
- resources.getQuantityString(R.plurals.downloads_active, downloads).format(downloads)
- val activeQueue =
- resources.getQuantityString(R.plurals.downloads_queued, queued).format(queued)
-
- val newNotification = baseNotification
- .setContentText(activeDownloads)
- .setSubText(activeQueue)
- .build()
-
- safe {
- NotificationManagerCompat.from(context)
- .notify(DOWNLOAD_QUEUE_NOTIFICATION_ID, newNotification)
- }
- }
-
- // We always need to listen to events, even before the download is launched.
- // Stopping link loading is an event which can trigger before downloading.
- val downloadEventListener = { event: Pair ->
- when (event.second) {
- VideoDownloadManager.DownloadActionType.Stop -> {
- removeKey(KEY_RESUME_PACKAGES, event.first.toString())
- removeKey(KEY_RESUME_IN_QUEUE, event.first.toString())
- DownloadQueueManager.cancelDownload(event.first)
- }
-
- else -> {}
- }
- }
-
- @OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
- override fun onCreate() {
- isRunning = true
- val context: Context = this // To make code more readable
-
- Log.d(TAG, "Download queue service started.")
- this.createNotificationChannel(
- DOWNLOAD_QUEUE_CHANNEL_ID,
- DOWNLOAD_QUEUE_CHANNEL_NAME,
- DOWNLOAD_QUEUE_CHANNEL_DESCRIPTION
- )
- if (SDK_INT >= 29) {
- startForeground(
- DOWNLOAD_QUEUE_NOTIFICATION_ID,
- baseNotification.build(),
- FOREGROUND_SERVICE_TYPE_DATA_SYNC
- )
- } else {
- startForeground(DOWNLOAD_QUEUE_NOTIFICATION_ID, baseNotification.build())
- }
-
- downloadEvent += downloadEventListener
-
- val queueJob = ioSafe {
- // Ensure this is up to date to prevent race conditions with MainActivity launches
- setLastError(context)
- // Early return, to prevent waiting for plugins in safe mode
- if (lastError != null) return@ioSafe
-
- // Try to ensure all plugins are loaded before starting the downloader.
- // To prevent infinite stalls we use a timeout of 15 seconds, it is judged as long enough
- val timeout = 15.seconds
- val timeTaken = withTimeoutOrNull(timeout) {
- measureTimeMillis {
- while (!(PluginManager.loadedOnlinePlugins && PluginManager.loadedLocalPlugins)) {
- delay(100.milliseconds)
- }
- }
- }
-
- debugWarning({ timeTaken == null || timeTaken > 3_000 }, {
- "Abnormally long downloader startup time of: ${timeTaken ?: timeout.inWholeMilliseconds}ms"
- })
- debugAssert({ timeTaken == null }, { "Downloader startup should not time out" })
-
- totalDownloadFlow
- .debounce { (instances, queue) ->
- // Filter away incorrect transient queue states.
- // For example when we pop the queue and add a download instance there exists a transient state where
- // there is no queue and no download instances (leading to an early exit)
- if (instances.isEmpty() && queue.isEmpty()) {
- 500.milliseconds
- } else {
- 0.milliseconds
- }
- }
- .takeWhile { (instances, queue) ->
- // Stop if destroyed
- isRunning
- // Run as long as there is a queue to process
- && (instances.isNotEmpty() || queue.isNotEmpty())
- // Run as long as there are no app crashes
- && lastError == null
- }
- .collect { (_, queue, currentDownloads) ->
- // Remove completed or failed
- val newInstances = _downloadInstances.updateAndGet { currentInstances ->
- currentInstances.filterNot { it.isCompleted || it.isFailed || it.isCancelled }
- }
-
- val maxDownloads = VideoDownloadManager.maxConcurrentDownloads(context)
- val currentInstanceCount = newInstances.size
-
- val newDownloads = minOf(
- // Cannot exceed the max downloads
- maxOf(0, maxDownloads - currentInstanceCount),
- // Cannot start more downloads than the queue size
- queue.size
- )
-
- // Cant start multiple downloads at once. If this is rerun it may start too many downloads.
- if (newDownloads > 0) {
- _downloadInstances.update { instances ->
- val downloadInstance = DownloadQueueManager.popQueue(context)
- if (downloadInstance != null) {
- downloadInstance.startDownload()
- instances + downloadInstance
- } else {
- instances
- }
- }
- }
-
- // The downloads actually displayed to the user with a notification
- val currentVisualDownloads =
- currentDownloads.size + newInstances.count {
- currentDownloads.contains(it.downloadQueueWrapper.id)
- .not()
- }
- // Just the queue
- val currentVisualQueue = queue.size
-
- updateNotification(context, currentVisualDownloads, currentVisualQueue)
- }
- }
-
- // Stop self regardless of job outcome
- queueJob.invokeOnCompletion { throwable ->
- if (throwable != null) {
- logError(throwable)
- }
- safe {
- stopSelf()
- }
- }
- }
-
- override fun onDestroy() {
- Log.d(TAG, "Download queue service stopped.")
- downloadEvent -= downloadEventListener
- isRunning = false
- super.onDestroy()
- }
-
- override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
- return START_STICKY // We want the service restarted if its killed
- }
-
- override fun onBind(intent: Intent?): IBinder? = null
-
- override fun onTimeout(reason: Int) {
- stopSelf()
- Log.e(TAG, "Service stopped due to timeout: $reason")
- }
-
-}
diff --git a/app/src/main/java/com/lagradost/cloudstream3/services/SubscriptionWorkManager.kt b/app/src/main/java/com/lagradost/cloudstream3/services/SubscriptionWorkManager.kt
index 7134650ed..56ab43dbf 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/services/SubscriptionWorkManager.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/services/SubscriptionWorkManager.kt
@@ -22,7 +22,7 @@ import com.lagradost.cloudstream3.utils.DataStoreHelper
import com.lagradost.cloudstream3.utils.DataStoreHelper.getAllSubscriptions
import com.lagradost.cloudstream3.utils.DataStoreHelper.getDub
import com.lagradost.cloudstream3.utils.UIHelper.colorFromAttribute
-import com.lagradost.cloudstream3.utils.downloader.DownloadUtils.getImageBitmapFromUrl
+import com.lagradost.cloudstream3.utils.VideoDownloadManager.getImageBitmapFromUrl
import kotlinx.coroutines.withTimeoutOrNull
import java.util.concurrent.TimeUnit
@@ -128,18 +128,18 @@ class SubscriptionWorkManager(val context: Context, workerParams: WorkerParamete
updateProgress(max, progress, true)
// We need all plugins loaded.
- PluginManager.___DO_NOT_CALL_FROM_A_PLUGIN_loadAllOnlinePlugins(context)
- PluginManager.___DO_NOT_CALL_FROM_A_PLUGIN_loadAllLocalPlugins(context, false)
+ PluginManager.loadAllOnlinePlugins(context)
+ PluginManager.loadAllLocalPlugins(context, false)
- subscriptions.amap { savedData ->
+ subscriptions.apmap { savedData ->
try {
- val id = savedData.id ?: return@amap null
- val api = getApiFromNameNull(savedData.apiName) ?: return@amap null
+ val id = savedData.id ?: return@apmap null
+ val api = getApiFromNameNull(savedData.apiName) ?: return@apmap null
// Reasonable timeout to prevent having this worker run forever.
val response = withTimeoutOrNull(60_000) {
api.load(savedData.url) as? EpisodeResponse
- } ?: return@amap null
+ } ?: return@apmap null
val dubPreference =
getDub(id) ?: if (
diff --git a/app/src/main/java/com/lagradost/cloudstream3/services/VideoDownloadService.kt b/app/src/main/java/com/lagradost/cloudstream3/services/VideoDownloadService.kt
index d63b18cdc..6151a0edd 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/services/VideoDownloadService.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/services/VideoDownloadService.kt
@@ -2,13 +2,12 @@ package com.lagradost.cloudstream3.services
import android.app.Service
import android.content.Intent
import android.os.IBinder
-import com.lagradost.cloudstream3.utils.downloader.VideoDownloadManager
+import com.lagradost.cloudstream3.utils.VideoDownloadManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
-/** Handle notification actions such as pause/resume downloads */
class VideoDownloadService : Service() {
private val downloadScope = CoroutineScope(Dispatchers.Default)
@@ -43,3 +42,19 @@ class VideoDownloadService : Service() {
super.onDestroy()
}
}
+// override fun onHandleIntent(intent: Intent?) {
+// if (intent != null) {
+// val id = intent.getIntExtra("id", -1)
+// val type = intent.getStringExtra("type")
+// if (id != -1 && type != null) {
+// val state = when (type) {
+// "resume" -> VideoDownloadManager.DownloadActionType.Resume
+// "pause" -> VideoDownloadManager.DownloadActionType.Pause
+// "stop" -> VideoDownloadManager.DownloadActionType.Stop
+// else -> return
+// }
+// VideoDownloadManager.downloadEvent.invoke(Pair(id, state))
+// }
+// }
+// }
+//}
diff --git a/app/src/main/java/com/lagradost/cloudstream3/subtitles/AbstractSubProvider.kt b/app/src/main/java/com/lagradost/cloudstream3/subtitles/AbstractSubProvider.kt
index 9e6f241fb..bfc6dacb6 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/subtitles/AbstractSubProvider.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/subtitles/AbstractSubProvider.kt
@@ -1,9 +1,18 @@
package com.lagradost.cloudstream3.subtitles
+import androidx.annotation.WorkerThread
import androidx.core.net.toUri
+import com.lagradost.cloudstream3.APIHolder.unixTime
+import com.lagradost.cloudstream3.ErrorLoadingException
import com.lagradost.cloudstream3.MainActivity.Companion.deleteFileOnExit
import com.lagradost.cloudstream3.app
+import com.lagradost.cloudstream3.mvvm.Resource
+import com.lagradost.cloudstream3.mvvm.safeApiCall
+import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities.SubtitleEntity
+import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities.SubtitleSearch
+import com.lagradost.cloudstream3.syncproviders.AuthAPI
import com.lagradost.cloudstream3.ui.player.SubtitleOrigin
+import com.lagradost.cloudstream3.utils.Coroutines.threadSafeListOf
import okio.BufferedSource
import okio.buffer
import okio.sink
@@ -11,6 +20,116 @@ import okio.source
import java.io.File
import java.util.zip.ZipInputStream
+interface AbstractSubProvider {
+ val idPrefix: String
+
+ @WorkerThread
+ @Throws
+ suspend fun search(query: SubtitleSearch): List? {
+ throw NotImplementedError()
+ }
+
+ @WorkerThread
+ @Throws
+ suspend fun load(data: SubtitleEntity): String? {
+ throw NotImplementedError()
+ }
+
+ @WorkerThread
+ @Throws
+ suspend fun SubtitleResource.getResources(data: SubtitleEntity) {
+ this.addUrl(load(data))
+ }
+
+ @WorkerThread
+ @Throws
+ suspend fun getResource(data: SubtitleEntity): SubtitleResource {
+ return SubtitleResource().apply {
+ this.getResources(data)
+ }
+ }
+}
+
+class SubRepository(val api: AbstractSubProvider) {
+ companion object {
+ data class SavedSearchResponse(
+ val unixTime: Long,
+ val response: List,
+ val query: SubtitleSearch
+ )
+
+ data class SavedResourceResponse(
+ val unixTime: Long,
+ val response: SubtitleResource,
+ val query: SubtitleEntity
+ )
+
+ // maybe make this a generic struct? right now there is a lot of boilerplate
+ private val searchCache = threadSafeListOf()
+ private var searchCacheIndex: Int = 0
+ private val resourceCache = threadSafeListOf()
+ private var resourceCacheIndex: Int = 0
+ const val CACHE_SIZE = 20
+ }
+
+ val idPrefix: String get() = api.idPrefix
+
+ @WorkerThread
+ suspend fun getResource(data: SubtitleEntity): Resource = safeApiCall {
+ synchronized(resourceCache) {
+ for (item in resourceCache) {
+ // 20 min save
+ if (item.query == data && (unixTime - item.unixTime) < 60 * 20) {
+ return@safeApiCall item.response
+ }
+ }
+ }
+
+ val returnValue = api.getResource(data)
+ synchronized(resourceCache) {
+ val add = SavedResourceResponse(unixTime, returnValue, data)
+ if (resourceCache.size > CACHE_SIZE) {
+ resourceCache[resourceCacheIndex] = add // rolling cache
+ resourceCacheIndex = (resourceCacheIndex + 1) % CACHE_SIZE
+ } else {
+ resourceCache.add(add)
+ }
+ }
+ returnValue
+ }
+
+ @WorkerThread
+ suspend fun search(query: SubtitleSearch): Resource> {
+ return safeApiCall {
+ synchronized(searchCache) {
+ for (item in searchCache) {
+ // 120 min save
+ if (item.query == query && (unixTime - item.unixTime) < 60 * 120) {
+ return@safeApiCall item.response
+ }
+ }
+ }
+
+ val returnValue = api.search(query) ?: throw ErrorLoadingException("Null subtitles")
+
+ // only cache valid return values
+ if (returnValue.isNotEmpty()) {
+ val add = SavedSearchResponse(unixTime, returnValue, query)
+ synchronized(searchCache) {
+ if (searchCache.size > CACHE_SIZE) {
+ searchCache[searchCacheIndex] = add // rolling cache
+ searchCacheIndex = (searchCacheIndex + 1) % CACHE_SIZE
+ } else {
+ searchCache.add(add)
+ }
+ }
+ }
+ returnValue
+ }
+ }
+
+}
+
/**
* A builder for subtitle files.
* @see addUrl
@@ -91,3 +210,4 @@ class SubtitleResource {
}
}
+interface AbstractSubApi : AbstractSubProvider, AuthAPI
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/AccountManager.kt b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/AccountManager.kt
index 68fba9777..2e14c3c46 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/AccountManager.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/AccountManager.kt
@@ -1,167 +1,149 @@
-package com.lagradost.cloudstream3.syncproviders
-
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
-import com.lagradost.cloudstream3.LoadResponse
-import com.lagradost.cloudstream3.syncproviders.providers.Addic7ed
-import com.lagradost.cloudstream3.syncproviders.providers.AniListApi
-import com.lagradost.cloudstream3.syncproviders.providers.KitsuApi
-import com.lagradost.cloudstream3.syncproviders.providers.LocalList
-import com.lagradost.cloudstream3.syncproviders.providers.MALApi
-import com.lagradost.cloudstream3.syncproviders.providers.OpenSubtitlesApi
-import com.lagradost.cloudstream3.syncproviders.providers.SimklApi
-import com.lagradost.cloudstream3.syncproviders.providers.SubDlApi
-import com.lagradost.cloudstream3.syncproviders.providers.SubSourceApi
-import com.lagradost.cloudstream3.utils.DataStoreHelper
-import com.lagradost.cloudstream3.utils.videoskip.AnimeSkipAuth
-import java.util.concurrent.TimeUnit
-
-abstract class AccountManager {
- companion object {
- const val NONE_ID: Int = -1
- val malApi = MALApi()
- val kitsuApi = KitsuApi()
- val aniListApi = AniListApi()
- val simklApi = SimklApi()
- val localListApi = LocalList()
-
- val openSubtitlesApi = OpenSubtitlesApi()
- val addic7ed = Addic7ed()
- val subDlApi = SubDlApi()
- val subSourceApi = SubSourceApi()
- val animeSkipApi = AnimeSkipAuth()
-
- var cachedAccounts: MutableMap>
- var cachedAccountIds: MutableMap
-
- const val ACCOUNT_TOKEN = "auth_tokens"
- const val ACCOUNT_IDS = "auth_ids"
-
- fun accounts(prefix: String): Array {
- require(prefix != "NONE")
- return getKey>(
- ACCOUNT_TOKEN,
- "${prefix}/${DataStoreHelper.currentAccount}"
- ) ?: arrayOf()
- }
-
- fun updateAccounts(prefix: String, array: Array) {
- require(prefix != "NONE")
- setKey(ACCOUNT_TOKEN, "${prefix}/${DataStoreHelper.currentAccount}", array)
- synchronized(cachedAccounts) {
- cachedAccounts[prefix] = array
- }
- }
-
- fun updateAccountsId(prefix: String, id: Int) {
- require(prefix != "NONE")
- setKey(ACCOUNT_IDS, "${prefix}/${DataStoreHelper.currentAccount}", id)
- synchronized(cachedAccountIds) {
- cachedAccountIds[prefix] = id
- }
- }
-
- val allApis = arrayOf(
- SyncRepo(malApi),
- SyncRepo(kitsuApi),
- SyncRepo(aniListApi),
- SyncRepo(simklApi),
- SyncRepo(localListApi),
- SubtitleRepo(openSubtitlesApi),
- SubtitleRepo(addic7ed),
- SubtitleRepo(subDlApi),
- PlainAuthRepo(animeSkipApi),
- SubtitleRepo(subSourceApi)
- )
-
- fun updateAccountIds() {
- val ids = mutableMapOf()
- for (api in allApis) {
- ids.put(
- api.idPrefix,
- getKey(
- ACCOUNT_IDS,
- "${api.idPrefix}/${DataStoreHelper.currentAccount}",
- NONE_ID
- ) ?: NONE_ID
- )
- }
- synchronized(cachedAccountIds) {
- cachedAccountIds = ids
- }
- }
-
- init {
- val data = mutableMapOf>()
- val ids = mutableMapOf()
- for (api in allApis) {
- data.put(api.idPrefix, accounts(api.idPrefix))
- ids.put(
- api.idPrefix,
- getKey(
- ACCOUNT_IDS,
- "${api.idPrefix}/${DataStoreHelper.currentAccount}",
- NONE_ID
- ) ?: NONE_ID
- )
- }
- cachedAccounts = data
- cachedAccountIds = ids
- }
-
- // I do not want to place this in the init block as JVM initialization order is weird, and it may cause exceptions
- // accessing other classes
- fun initMainAPI() {
- LoadResponse.malIdPrefix = malApi.idPrefix
- LoadResponse.kitsuIdPrefix = kitsuApi.idPrefix
- LoadResponse.aniListIdPrefix = aniListApi.idPrefix
- LoadResponse.simklIdPrefix = simklApi.idPrefix
- }
-
- val subtitleProviders = arrayOf(
- SubtitleRepo(openSubtitlesApi),
- SubtitleRepo(addic7ed),
- SubtitleRepo(subDlApi),
- SubtitleRepo(subSourceApi)
- )
- val syncApis = arrayOf(
- SyncRepo(malApi),
- SyncRepo(kitsuApi),
- SyncRepo(aniListApi),
- SyncRepo(simklApi),
- SyncRepo(localListApi)
- )
-
- const val APP_STRING = "cloudstreamapp"
- const val APP_STRING_REPO = "cloudstreamrepo"
- const val APP_STRING_PLAYER = "cloudstreamplayer"
-
- // Instantly start the search given a query
- const val APP_STRING_SEARCH = "cloudstreamsearch"
-
- // Instantly resume watching a show
- const val APP_STRING_RESUME_WATCHING = "cloudstreamcontinuewatching"
-
- const val APP_STRING_SHARE = "csshare"
-
- fun secondsToReadable(seconds: Int, completedValue: String): String {
- var secondsLong = seconds.toLong()
- val days = TimeUnit.SECONDS
- .toDays(secondsLong)
- secondsLong -= TimeUnit.DAYS.toSeconds(days)
-
- val hours = TimeUnit.SECONDS
- .toHours(secondsLong)
- secondsLong -= TimeUnit.HOURS.toSeconds(hours)
-
- val minutes = TimeUnit.SECONDS
- .toMinutes(secondsLong)
- secondsLong -= TimeUnit.MINUTES.toSeconds(minutes)
- if (minutes < 0) {
- return completedValue
- }
- //println("$days $hours $minutes")
- return "${if (days != 0L) "$days" + "d " else ""}${if (hours != 0L) "$hours" + "h " else ""}${minutes}m"
- }
- }
-}
\ No newline at end of file
+package com.lagradost.cloudstream3.syncproviders
+
+import com.lagradost.cloudstream3.AcraApplication.Companion.getKey
+import com.lagradost.cloudstream3.AcraApplication.Companion.removeKeys
+import com.lagradost.cloudstream3.AcraApplication.Companion.setKey
+import com.lagradost.cloudstream3.LoadResponse
+import com.lagradost.cloudstream3.syncproviders.providers.*
+import java.util.concurrent.TimeUnit
+
+abstract class AccountManager(private val defIndex: Int) : AuthAPI {
+ companion object {
+ val malApi = MALApi(0).also { api ->
+ LoadResponse.Companion.malIdPrefix = api.idPrefix
+ }
+ val aniListApi = AniListApi(0).also { api ->
+ LoadResponse.Companion.aniListIdPrefix = api.idPrefix
+ }
+ val simklApi = SimklApi(0).also { api ->
+ LoadResponse.Companion.simklIdPrefix = api.idPrefix
+ }
+ val openSubtitlesApi = OpenSubtitlesApi(0)
+ val addic7ed = Addic7ed()
+ val subDlApi = SubDlApi(0)
+ val localListApi = LocalList()
+ val subSourceApi = SubSourceApi()
+
+ // used to login via app intent
+ val OAuth2Apis
+ get() = listOf(
+ malApi, aniListApi, simklApi
+ )
+
+ // this needs init with context and can be accessed in settings
+ val accountManagers
+ get() = listOf(
+ malApi, aniListApi, openSubtitlesApi, subDlApi, simklApi //nginxApi
+ )
+
+ // used for active syncing
+ val SyncApis
+ get() = listOf(
+ SyncRepo(malApi), SyncRepo(aniListApi), SyncRepo(localListApi), SyncRepo(simklApi)
+ )
+
+ val inAppAuths
+ get() = listOf(
+ openSubtitlesApi,
+ subDlApi
+ )//, nginxApi)
+
+ val subtitleProviders
+ get() = listOf(
+ openSubtitlesApi,
+ addic7ed,
+ subDlApi,
+ subSourceApi
+ )
+
+ const val APP_STRING = "cloudstreamapp"
+ const val APP_STRING_REPO = "cloudstreamrepo"
+ const val APP_STRING_PLAYER = "cloudstreamplayer"
+
+ // Instantly start the search given a query
+ const val APP_STRING_SEARCH = "cloudstreamsearch"
+
+ // Instantly resume watching a show
+ const val APP_STRING_RESUME_WATCHING = "cloudstreamcontinuewatching"
+
+ val unixTime: Long
+ get() = System.currentTimeMillis() / 1000L
+ val unixTimeMs: Long
+ get() = System.currentTimeMillis()
+
+ const val MAX_STALE = 60 * 10
+
+ fun secondsToReadable(seconds: Int, completedValue: String): String {
+ var secondsLong = seconds.toLong()
+ val days = TimeUnit.SECONDS
+ .toDays(secondsLong)
+ secondsLong -= TimeUnit.DAYS.toSeconds(days)
+
+ val hours = TimeUnit.SECONDS
+ .toHours(secondsLong)
+ secondsLong -= TimeUnit.HOURS.toSeconds(hours)
+
+ val minutes = TimeUnit.SECONDS
+ .toMinutes(secondsLong)
+ secondsLong -= TimeUnit.MINUTES.toSeconds(minutes)
+ if (minutes < 0) {
+ return completedValue
+ }
+ //println("$days $hours $minutes")
+ return "${if (days != 0L) "$days" + "d " else ""}${if (hours != 0L) "$hours" + "h " else ""}${minutes}m"
+ }
+ }
+
+ var accountIndex = defIndex
+ private var lastAccountIndex = defIndex
+ protected val accountId get() = "${idPrefix}_account_$accountIndex"
+ private val accountActiveKey get() = "${idPrefix}_active"
+
+ // int array of all accounts indexes
+ private val accountsKey get() = "${idPrefix}_accounts"
+
+ protected fun removeAccountKeys() {
+ removeKeys(accountId)
+ val accounts = getAccounts()?.toMutableList() ?: mutableListOf()
+ accounts.remove(accountIndex)
+ setKey(accountsKey, accounts.toIntArray())
+
+ init()
+ }
+
+ fun getAccounts(): IntArray? {
+ return getKey(accountsKey, intArrayOf())
+ }
+
+ fun init() {
+ accountIndex = getKey(accountActiveKey, defIndex)!!
+ val accounts = getAccounts()
+ if (accounts?.isNotEmpty() == true && this.loginInfo() == null) {
+ accountIndex = accounts.first()
+ }
+ }
+
+ protected fun switchToNewAccount() {
+ val accounts = getAccounts()
+ lastAccountIndex = accountIndex
+ accountIndex = (accounts?.maxOrNull() ?: 0) + 1
+ }
+ protected fun switchToOldAccount() {
+ accountIndex = lastAccountIndex
+ }
+
+ protected fun registerAccount() {
+ setKey(accountActiveKey, accountIndex)
+ val accounts = getAccounts()?.toMutableList() ?: mutableListOf()
+ if (!accounts.contains(accountIndex)) {
+ accounts.add(accountIndex)
+ }
+
+ setKey(accountsKey, accounts.toIntArray())
+ }
+
+ fun changeAccount(index: Int) {
+ accountIndex = index
+ setKey(accountActiveKey, index)
+ }
+}
diff --git a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/AuthAPI.kt b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/AuthAPI.kt
index c0f0e4a03..8b085bc0b 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/AuthAPI.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/AuthAPI.kt
@@ -1,265 +1,23 @@
package com.lagradost.cloudstream3.syncproviders
-import com.fasterxml.jackson.annotation.JsonAlias
-import com.fasterxml.jackson.annotation.JsonProperty
-import com.lagradost.cloudstream3.APIHolder
-import com.lagradost.cloudstream3.APIHolder.unixTime
-import com.lagradost.cloudstream3.APIHolder.unixTimeMS
-import com.lagradost.cloudstream3.base64Encode
-import com.lagradost.cloudstream3.splitUrlParameters
-import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.APP_STRING
-import kotlinx.serialization.ExperimentalSerializationApi
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
-import kotlinx.serialization.json.JsonNames
-import java.security.SecureRandom
+interface AuthAPI {
+ val name: String
+ val icon: Int?
-data class AuthLoginPage(
- /** The website to open to authenticate */
- val url: String,
- /**
- * State/control code to verify against the redirectUrl to make sure the request is valid.
- * This parameter will be saved, and then used in AuthAPI::login.
- */
- val payload: String? = null,
-)
+ val requiresLogin: Boolean
-@Serializable
-data class AuthToken(
- /**
- * This is the general access tokens/api token representing a logged in user.
- * Access tokens are the thing that applications use to make API requests on behalf of a user.
- */
- @JsonProperty("accessToken") @SerialName("accessToken")
- val accessToken: String? = null,
- /** For OAuth a special refresh token is issues to refresh the access token. */
- @JsonProperty("refreshToken") @SerialName("refreshToken")
- val refreshToken: String? = null,
- /** In UnixTime (sec) when it expires */
- @JsonProperty("accessTokenLifetime") @SerialName("accessTokenLifetime")
- val accessTokenLifetime: Long? = null,
- /** In UnixTime (sec) when it expires */
- @JsonProperty("refreshTokenLifetime") @SerialName("refreshTokenLifetime")
- val refreshTokenLifetime: Long? = null,
- /**
- * Sometimes AuthToken needs to be customized to store e.g. username/password,
- * this acts as a catch all to store text or JSON data.
- */
- @JsonProperty("payload") @SerialName("payload")
- val payload: String? = null,
-) {
- fun isAccessTokenExpired(marginSec: Long = 10L) =
- accessTokenLifetime != null && unixTime + marginSec >= accessTokenLifetime
+ val createAccountUrl : String?
- fun isRefreshTokenExpired(marginSec: Long = 10L) =
- refreshTokenLifetime != null && unixTime + marginSec >= refreshTokenLifetime
-}
+ // don't change this as all keys depend on it
+ val idPrefix: String
-@OptIn(ExperimentalSerializationApi::class) // JsonNames is an experimental annotation for now
-@Serializable
-data class AuthUser(
- /** Account display-name, can also be email if name does not exist */
- @JsonProperty("name") @SerialName("name")
- val name: String?,
- /**
- * Unique account identifier. If a subsequent login is done then it
- * will be refused if another account with the same id exists.
- */
- @JsonProperty("id") @SerialName("id")
- val id: Int,
- /** Profile picture URL */
- @JsonProperty("profilePicture") @SerialName("profilePicture")
- val profilePicture: String? = null,
- /** Profile picture Headers of the URL */
- @JsonProperty("profilePictureHeaders") @JsonAlias("profilePictureHeader")
- @SerialName("profilePictureHeaders") @JsonNames("profilePictureHeader")
- val profilePictureHeaders: Map? = null,
-)
+ // if this returns null then you are not logged in
+ fun loginInfo(): LoginInfo?
+ fun logOut()
-/**
- * Stores all information that should be used to authorize access.
- * Be aware that token and user may change independently when a refresh is needed,
- * and as such there should be no strong pairing between the two.
- *
- * Any local set/get key should use user.id.toString(),
- * as token.accessToken (even hashed) is unsecure, and will rotate.
- */
-@Serializable
-data class AuthData(
- @JsonProperty("user") @SerialName("user") val user: AuthUser,
- @JsonProperty("token") @SerialName("token") val token: AuthToken,
-)
-
-data class AuthPinData(
- val deviceCode: String,
- val userCode: String,
- /** QR Code url */
- val verificationUrl: String,
- /** In seconds */
- val expiresIn: Int,
- /** Check if the code has been verified interval */
- val interval: Int,
-)
-
-/** The login field requirements to display to the user */
-data class AuthLoginRequirement(
- val password: Boolean = false,
- val username: Boolean = false,
- val email: Boolean = false,
- val server: Boolean = false,
-)
-
-/** What the user responds to the AuthLoginRequirement */
-@Serializable
-data class AuthLoginResponse(
- @JsonProperty("password") @SerialName("password") val password: String?,
- @JsonProperty("username") @SerialName("username") val username: String?,
- @JsonProperty("email") @SerialName("email") val email: String?,
- @JsonProperty("server") @SerialName("server") val server: String?,
-)
-
-/** Stateless Authentication class used for all personalized content */
-abstract class AuthAPI {
- open val name: String = "NONE"
- open val idPrefix: String = "NONE"
-
- /** Drawable icon of the service */
- open val icon: Int? = null
-
- /** If this service requires an account to use */
- open val requiresLogin: Boolean = true
-
- /** Link to a website for creating a new account */
- open val createAccountUrl: String? = null
-
- /** The sensitive redirect URL from OAuth should contain "/redirectUrlIdentifier" to trigger the login */
- open val redirectUrlIdentifier: String? = null
-
- /** Has OAuth2 login support, including login, loginRequest and refreshToken */
- open val hasOAuth2: Boolean = false
-
- /** Has on device pin support, aka login with a QR code */
- open val hasPin: Boolean = false
-
- /** Has in app login support, aka login with a dialog */
- open val hasInApp: Boolean = false
-
- /** The requirements to login in app */
- open val inAppLoginRequirement: AuthLoginRequirement? = null
-
- companion object {
- @Deprecated(
- message = "Use APIHolder.unixTime instead",
- replaceWith = ReplaceWith(
- expression = "APIHolder.unixTime",
- imports = ["com.lagradost.cloudstream3.APIHolder"]
- ),
- level = DeprecationLevel.WARNING,
- )
- val unixTime: Long
- get() = APIHolder.unixTime
-
- @Deprecated(
- message = "Use APIHolder.unixTimeMS instead",
- replaceWith = ReplaceWith(
- expression = "unixTimeMS",
- imports = ["com.lagradost.cloudstream3.APIHolder.unixTimeMS"]
- ),
- level = DeprecationLevel.WARNING,
- )
- val unixTimeMs: Long
- get() = unixTimeMS
-
- fun splitRedirectUrl(redirectUrl: String): Map {
- return splitUrlParameters(
- redirectUrl.replace(APP_STRING, "https").replace("/#", "?")
- )
- }
-
- fun generateCodeVerifier(): String {
- // It is recommended to use a URL-safe string as code_verifier.
- // See section 4 of RFC 7636 for more details.
- val secureRandom = SecureRandom()
- val codeVerifierBytes = ByteArray(96) // base64 has 6bit per char; (8/6)*96 = 128
- secureRandom.nextBytes(codeVerifierBytes)
- return base64Encode(codeVerifierBytes).trimEnd('=')
- .replace("+", "-").replace("/", "_").replace("\n", "")
- }
- }
-
- /** Is this url a valid redirect url for this service? */
- @Throws
- open fun isValidRedirectUrl(url: String): Boolean =
- redirectUrlIdentifier != null && url.contains("/$redirectUrlIdentifier")
-
- /** OAuth2 login from a valid redirectUrl, and payload given in loginRequest */
- @Throws
- open suspend fun login(redirectUrl: String, payload: String?): AuthToken? =
- throw NotImplementedError()
-
- /** OAuth2 login request, asking the service to provide a url to open in the browser */
- @Throws
- open fun loginRequest(): AuthLoginPage? = throw NotImplementedError()
-
- /** Pin login request, asking the service to provide an verificationUrl to display with a QR code */
- @Throws
- open suspend fun pinRequest(): AuthPinData? = throw NotImplementedError()
-
- /** OAuth2 token refresh, this ensures that all token passed to other functions will be valid */
- @Throws
- open suspend fun refreshToken(token: AuthToken): AuthToken? = throw NotImplementedError()
-
- /** Pin login, this will be called periodically while logging in to check if the pin has been verified by the user */
- @Throws
- open suspend fun login(payload: AuthPinData): AuthToken? = throw NotImplementedError()
-
- /** In app login */
- @Throws
- open suspend fun login(form: AuthLoginResponse): AuthToken? = throw NotImplementedError()
-
- /** Get the visible user account */
- @Throws
- open suspend fun user(token: AuthToken?): AuthUser? = throw NotImplementedError()
-
- /**
- * An optional security measure to make sure that even if an attacker gets ahold of the token, it will be invalid.
- *
- * Note that this will currently only be called *once* on logout,
- * and as such any network issues it will fail silently, and the token will not be revoked.
- */
- @Throws
- open suspend fun invalidateToken(token: AuthToken): Nothing = throw NotImplementedError()
-
- @Throws
- @Deprecated("Please use the new API for AuthAPI", level = DeprecationLevel.ERROR)
- fun toRepo(): AuthRepo = when (this) {
- is SubtitleAPI -> SubtitleRepo(this)
- is SyncAPI -> SyncRepo(this)
- else -> throw NotImplementedError("Unknown inheritance from AuthAPI")
- }
-
- @Suppress("DEPRECATION_ERROR")
- @Deprecated("Please use the new API for AuthAPI", level = DeprecationLevel.ERROR)
- fun loginInfo(): LoginInfo? {
- return this.toRepo().authUser()?.let { user ->
- LoginInfo(
- profilePicture = user.profilePicture,
- name = user.name,
- accountIndex = -1,
- )
- }
- }
-
- @Deprecated("Please use the new API for AuthAPI", level = DeprecationLevel.ERROR)
- suspend fun getPersonalLibrary(): SyncAPI.LibraryMetadata? {
- @Suppress("DEPRECATION_ERROR")
- return (this.toRepo() as? SyncRepo)?.library()?.getOrThrow()
- }
-
- @Deprecated("Please use the new API for AuthAPI", level = DeprecationLevel.ERROR)
class LoginInfo(
val profilePicture: String? = null,
val name: String?,
val accountIndex: Int,
)
-}
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/AuthRepo.kt b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/AuthRepo.kt
deleted file mode 100644
index 645a19e3a..000000000
--- a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/AuthRepo.kt
+++ /dev/null
@@ -1,168 +0,0 @@
-package com.lagradost.cloudstream3.syncproviders
-
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.openBrowser
-import com.lagradost.cloudstream3.CommonActivity.showToast
-import com.lagradost.cloudstream3.ErrorLoadingException
-import com.lagradost.cloudstream3.R
-import com.lagradost.cloudstream3.mvvm.logError
-import com.lagradost.cloudstream3.mvvm.safe
-import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.NONE_ID
-import com.lagradost.cloudstream3.utils.txt
-
-/** General-purpose repo */
-class PlainAuthRepo(api: AuthAPI) : AuthRepo(api)
-
-/** Safe abstraction for AuthAPI that provides both a catching interface, and automatic token management. */
-abstract class AuthRepo(open val api: AuthAPI) {
- fun isValidRedirectUrl(url: String) = safe { api.isValidRedirectUrl(url) } ?: false
- val idPrefix get() = api.idPrefix
- val name get() = api.name
- val icon get() = api.icon
- val requiresLogin get() = api.requiresLogin
- val createAccountUrl get() = api.createAccountUrl
- val hasOAuth2 get() = api.hasOAuth2
- val hasPin get() = api.hasPin
- val hasInApp get() = api.hasInApp
- val inAppLoginRequirement get() = api.inAppLoginRequirement
- val isAvailable get() = !api.requiresLogin || authUser() != null
-
- companion object {
- private val oauthPayload: MutableMap = mutableMapOf()
- }
-
- @Throws
- protected suspend fun freshAuth(): AuthData? {
- val data = authData() ?: return null
- if (data.token.isAccessTokenExpired()) {
- val newToken = api.refreshToken(data.token) ?: return null
- val newAuth = AuthData(user = data.user, token = newToken)
- refreshUser(newAuth)
- return newAuth
- }
- return data
- }
-
- @Throws
- fun openOAuth2Page(): Boolean {
- val page = api.loginRequest() ?: return false
- synchronized(oauthPayload) {
- oauthPayload.put(idPrefix, page.payload)
- }
- openBrowser(page.url)
- return true
- }
-
- fun openOAuth2PageWithToast() {
- try {
- if (!openOAuth2Page()) {
- showToast(txt(R.string.authenticated_user_fail, api.name))
- }
- } catch (t: Throwable) {
- logError(t)
- if (t is ErrorLoadingException && t.message != null) {
- showToast(t.message)
- return
- }
- showToast(txt(R.string.authenticated_user_fail, api.name))
- }
- }
-
- suspend fun logout(from: AuthUser) {
- val currentAccounts = AccountManager.accounts(idPrefix)
- val (newAccounts, oldAccounts) = currentAccounts.partition { it.user.id != from.id }
- if (newAccounts.size < currentAccounts.size) {
- AccountManager.updateAccounts(idPrefix, newAccounts.toTypedArray())
- AccountManager.updateAccountsId(idPrefix, 0)
- }
-
- for (oldAccount in oldAccounts) {
- try {
- api.invalidateToken(oldAccount.token)
- } catch (_: NotImplementedError) {
- // no-op
- } catch (t: Throwable) {
- logError(t)
- }
- }
- }
-
- fun refreshUser(newAuth: AuthData) {
- val currentAccounts = AccountManager.accounts(idPrefix)
- val newAccounts = currentAccounts.map {
- if (it.user.id == newAuth.user.id) {
- newAuth
- } else {
- it
- }
- }.toTypedArray()
- AccountManager.updateAccounts(idPrefix, newAccounts)
- }
-
- fun authData(): AuthData? = synchronized(AccountManager.cachedAccountIds) {
- AccountManager.cachedAccountIds[idPrefix]?.let { id ->
- AccountManager.cachedAccounts[idPrefix]?.firstOrNull { data -> data.user.id == id }
- }
- }
-
- fun authToken(): AuthToken? = authData()?.token
-
- fun authUser(): AuthUser? = authData()?.user
-
- val accounts
- get() = synchronized(AccountManager.cachedAccounts) {
- AccountManager.cachedAccounts[idPrefix] ?: emptyArray()
- }
- var accountId
- get() = synchronized(AccountManager.cachedAccountIds) {
- AccountManager.cachedAccountIds[idPrefix] ?: NONE_ID
- }
- set(value) {
- AccountManager.updateAccountsId(idPrefix, value)
- }
-
- @Throws
- suspend fun pinRequest() =
- api.pinRequest()
-
- @Throws
- private suspend fun setupLogin(token: AuthToken): Boolean {
- val user = api.user(token) ?: return false
-
- val newAccount = AuthData(
- token = token,
- user = user,
- )
-
- val currentAccounts = AccountManager.accounts(idPrefix)
- if (currentAccounts.any { it.user.id == newAccount.user.id }) {
- throw ErrorLoadingException("Already logged into this account")
- }
-
- val newAccounts = currentAccounts + newAccount
- AccountManager.updateAccounts(idPrefix, newAccounts)
- AccountManager.updateAccountsId(idPrefix, user.id)
- if (this is SyncRepo) {
- requireLibraryRefresh = true
- }
- return true
- }
-
- @Throws
- suspend fun login(form: AuthLoginResponse): Boolean {
- return setupLogin(api.login(form) ?: return false)
- }
-
- @Throws
- suspend fun login(payload: AuthPinData): Boolean {
- return setupLogin(api.login(payload) ?: return false)
- }
-
- @Throws
- suspend fun login(redirectUrl: String): Boolean {
- return setupLogin(
- api.login(
- redirectUrl,
- synchronized(oauthPayload) { oauthPayload[api.idPrefix] }) ?: return false
- )
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/BackupAPI.kt b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/BackupAPI.kt
deleted file mode 100644
index 5efb88e5b..000000000
--- a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/BackupAPI.kt
+++ /dev/null
@@ -1,14 +0,0 @@
-package com.lagradost.cloudstream3.syncproviders
-
-/** Work in progress */
-abstract class BackupAPI : AuthAPI() {
- open val filename : String = "cloudstream-backup.json"
-
- /** Get the backup file as a JSON string from the remote storage. Return null if not found/empty */
- @Throws
- open suspend fun downloadFile(auth: AuthData?) : String? = throw NotImplementedError()
-
- /** Get the backup file as a JSON string from the remote storage. */
- @Throws
- open suspend fun uploadFile(auth: AuthData?, data : String) : String? = throw NotImplementedError()
-}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/InAppAuthAPI.kt b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/InAppAuthAPI.kt
new file mode 100644
index 000000000..8b6fdf463
--- /dev/null
+++ b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/InAppAuthAPI.kt
@@ -0,0 +1,66 @@
+package com.lagradost.cloudstream3.syncproviders
+
+import androidx.annotation.WorkerThread
+
+interface InAppAuthAPI : AuthAPI {
+ data class LoginData(
+ val username: String? = null,
+ val password: String? = null,
+ val server: String? = null,
+ val email: String? = null,
+ )
+
+ // this is for displaying the UI
+ val requiresPassword: Boolean
+ val requiresUsername: Boolean
+ val requiresServer: Boolean
+ val requiresEmail: Boolean
+
+ // if this is false we can assume that getLatestLoginData returns null and wont be called
+ // this is used in case for some reason it is not preferred to store any login data besides the "token" or encrypted data
+ val storesPasswordInPlainText: Boolean
+
+ // return true if logged in successfully
+ suspend fun login(data: LoginData): Boolean
+
+ // used to fill the UI if you want to edit any data about your login info
+ fun getLatestLoginData(): LoginData?
+}
+
+abstract class InAppAuthAPIManager(defIndex: Int) : AccountManager(defIndex), InAppAuthAPI {
+ override val requiresPassword = false
+ override val requiresUsername = false
+ override val requiresEmail = false
+ override val requiresServer = false
+ override val storesPasswordInPlainText = true
+ override val requiresLogin = true
+
+ // runs on startup
+ @WorkerThread
+ open suspend fun initialize() {
+ }
+
+ override fun logOut() {
+ throw NotImplementedError()
+ }
+
+ override val idPrefix: String
+ get() = throw NotImplementedError()
+
+ override val name: String
+ get() = throw NotImplementedError()
+
+ override val icon: Int? = null
+
+ override suspend fun login(data: InAppAuthAPI.LoginData): Boolean {
+ throw NotImplementedError()
+ }
+
+ override fun getLatestLoginData(): InAppAuthAPI.LoginData? {
+ throw NotImplementedError()
+ }
+
+ override fun loginInfo(): AuthAPI.LoginInfo? {
+ throw NotImplementedError()
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/OAuth2API.kt b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/OAuth2API.kt
new file mode 100644
index 000000000..3d0bb9402
--- /dev/null
+++ b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/OAuth2API.kt
@@ -0,0 +1,27 @@
+package com.lagradost.cloudstream3.syncproviders
+
+import androidx.fragment.app.FragmentActivity
+
+interface OAuth2API : AuthAPI {
+ val key: String
+ val redirectUrl: String
+ val supportDeviceAuth: Boolean
+
+ suspend fun handleRedirect(url: String) : Boolean
+ fun authenticate(activity: FragmentActivity?)
+ suspend fun getDevicePin() : PinAuthData? {
+ return null
+ }
+
+ suspend fun handleDeviceAuth(pinAuthData: PinAuthData) : Boolean {
+ return false
+ }
+
+ data class PinAuthData(
+ val deviceCode: String,
+ val userCode: String,
+ val verificationUrl: String,
+ val expiresIn: Int,
+ val interval: Int,
+ )
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SubtitleAPI.kt b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SubtitleAPI.kt
deleted file mode 100644
index a1149b5f8..000000000
--- a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SubtitleAPI.kt
+++ /dev/null
@@ -1,37 +0,0 @@
-package com.lagradost.cloudstream3.syncproviders
-
-import androidx.annotation.WorkerThread
-import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities.SubtitleEntity
-import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities.SubtitleSearch
-import com.lagradost.cloudstream3.subtitles.SubtitleResource
-
-/**
- * Stateless subtitle class for external subtitles.
- *
- * All non-null `AuthToken` will be non-expired when each function is called.
- */
-abstract class SubtitleAPI : AuthAPI() {
- @WorkerThread
- @Throws
- open suspend fun search(auth: AuthData?, query: SubtitleSearch): List? =
- throw NotImplementedError()
-
- @WorkerThread
- @Throws
- open suspend fun load(auth: AuthData?, subtitle: SubtitleEntity): String? =
- throw NotImplementedError()
-
- @WorkerThread
- @Throws
- open suspend fun SubtitleResource.getResources(auth: AuthData?, subtitle: SubtitleEntity) {
- this.addUrl(load(auth, subtitle))
- }
-
- @WorkerThread
- @Throws
- suspend fun resource(auth: AuthData?, subtitle: SubtitleEntity): SubtitleResource {
- return SubtitleResource().apply {
- this.getResources(auth, subtitle)
- }
- }
-}
diff --git a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SubtitleRepo.kt b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SubtitleRepo.kt
deleted file mode 100644
index 161001611..000000000
--- a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SubtitleRepo.kt
+++ /dev/null
@@ -1,95 +0,0 @@
-package com.lagradost.cloudstream3.syncproviders
-
-import androidx.annotation.WorkerThread
-import com.lagradost.cloudstream3.APIHolder.unixTime
-import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities.SubtitleEntity
-import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities.SubtitleSearch
-import com.lagradost.cloudstream3.subtitles.SubtitleResource
-import com.lagradost.cloudstream3.utils.Coroutines.atomicListOf
-
-/** Stateless safe abstraction of SubtitleAPI */
-class SubtitleRepo(override val api: SubtitleAPI) : AuthRepo(api) {
- companion object {
- data class SavedSearchResponse(
- val unixTime: Long,
- val response: List,
- val query: SubtitleSearch,
- val idPrefix: String,
- )
-
- data class SavedResourceResponse(
- val unixTime: Long,
- val response: SubtitleResource,
- val query: SubtitleEntity
- )
-
- // maybe make this a generic struct? right now there is a lot of boilerplate
- private val searchCache = atomicListOf()
- private var searchCacheIndex: Int = 0
- private val resourceCache = atomicListOf()
- private var resourceCacheIndex: Int = 0
- const val CACHE_SIZE = 20
- }
-
- @WorkerThread
- suspend fun resource(data: SubtitleEntity): Result = runCatching {
- val cached = resourceCache.withLock {
- var found: SubtitleResource? = null
- for (item in resourceCache) {
- // 20 min save
- if (item.query == data && (unixTime - item.unixTime) < 60 * 20) {
- found = item.response
- break
- }
- }
- found
- }
- if (cached != null) return@runCatching cached
-
- val returnValue = api.resource(freshAuth(), data)
- resourceCache.withLock {
- val add = SavedResourceResponse(unixTime, returnValue, data)
- if (resourceCache.size > CACHE_SIZE) {
- resourceCache[resourceCacheIndex] = add // rolling cache
- resourceCacheIndex = (resourceCacheIndex + 1) % CACHE_SIZE
- } else {
- resourceCache.add(add)
- }
- }
- returnValue
- }
-
- @WorkerThread
- suspend fun search(query: SubtitleSearch): Result> {
- return runCatching {
- val cached = searchCache.withLock {
- var found: List? = null
- for (item in searchCache) {
- // 120 min save
- if (item.idPrefix == idPrefix && item.query == query && (unixTime - item.unixTime) < 60 * 120) {
- found = item.response
- break
- }
- }
- found
- }
-
- if (cached != null) return@runCatching cached
- val returnValue = api.search(freshAuth(), query) ?: emptyList()
-
- // only cache valid return values
- if (returnValue.isNotEmpty()) {
- val add = SavedSearchResponse(unixTime, returnValue, query, idPrefix)
- searchCache.withLock {
- if (searchCache.size > CACHE_SIZE) {
- searchCache[searchCacheIndex] = add // rolling cache
- searchCacheIndex = (searchCacheIndex + 1) % CACHE_SIZE
- } else {
- searchCache.add(add)
- }
- }
- }
- returnValue
- }
- }
-}
diff --git a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SyncAPI.kt b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SyncApi.kt
similarity index 62%
rename from app/src/main/java/com/lagradost/cloudstream3/syncproviders/SyncAPI.kt
rename to app/src/main/java/com/lagradost/cloudstream3/syncproviders/SyncApi.kt
index f30a64748..9d43685c8 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SyncAPI.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SyncApi.kt
@@ -1,194 +1,170 @@
-package com.lagradost.cloudstream3.syncproviders
-
-import androidx.annotation.WorkerThread
-import com.lagradost.cloudstream3.ActorData
-import com.lagradost.cloudstream3.NextAiring
-import com.lagradost.cloudstream3.Score
-import com.lagradost.cloudstream3.SearchQuality
-import com.lagradost.cloudstream3.SearchResponse
-import com.lagradost.cloudstream3.ShowStatus
-import com.lagradost.cloudstream3.TvType
-import com.lagradost.cloudstream3.ui.SyncWatchType
-import com.lagradost.cloudstream3.ui.library.ListSorting
-import com.lagradost.cloudstream3.utils.Levenshtein
-import com.lagradost.cloudstream3.utils.UiText
-import java.util.Date
-
-/**
- * Stateless synchronization class, used for syncing status about a specific movie/show.
- *
- * All non-null `AuthToken` will be non-expired when each function is called.
- */
-abstract class SyncAPI : AuthAPI() {
- /**
- * Set this to true if the user updates something on the list like watch status or score
- **/
- open var requireLibraryRefresh: Boolean = true
- open val mainUrl: String = "NONE"
-
- /** Currently unused, but will be used to correctly render the UI.
- * This should specify what sync watch types can be used with this service. */
- open val supportedWatchTypes: Set = SyncWatchType.entries.toSet()
- /**
- * Allows certain providers to open pages from
- * library links.
- **/
- open val syncIdName: SyncIdName? = null
-
- /** Modify the current status of an item */
- @Throws
- @WorkerThread
- open suspend fun updateStatus(
- auth: AuthData?,
- id: String,
- newStatus: AbstractSyncStatus
- ): Boolean = throw NotImplementedError()
-
- /** Get the current status of an item */
- @Throws
- @WorkerThread
- open suspend fun status(auth: AuthData?, id: String): AbstractSyncStatus? =
- throw NotImplementedError()
-
- /** Get metadata about an item */
- @Throws
- @WorkerThread
- open suspend fun load(auth: AuthData?, id: String): SyncResult? = throw NotImplementedError()
-
- /** Search this service for any results for a given query */
- @Throws
- @WorkerThread
- open suspend fun search(auth: AuthData?, query: String): List? =
- throw NotImplementedError()
-
- /** Get the current library/bookmarks of this service */
- @Throws
- @WorkerThread
- open suspend fun library(auth: AuthData?): LibraryMetadata? = throw NotImplementedError()
-
- /** Helper function, may be used in the future */
- @Throws
- open fun urlToId(url: String): String? = null
-
- data class SyncSearchResult(
- override val name: String,
- override val apiName: String,
- var syncId: String,
- override val url: String,
- override var posterUrl: String?,
- override var type: TvType? = null,
- override var quality: SearchQuality? = null,
- override var posterHeaders: Map? = null,
- override var id: Int? = null,
- override var score: Score? = null,
- ) : SearchResponse
-
- abstract class AbstractSyncStatus {
- abstract var status: SyncWatchType
- abstract var score: Score?
- abstract var watchedEpisodes: Int?
- abstract var isFavorite: Boolean?
- abstract var maxEpisodes: Int?
- }
-
- data class SyncStatus(
- override var status: SyncWatchType,
- override var score: Score?,
- override var watchedEpisodes: Int?,
- override var isFavorite: Boolean? = null,
- override var maxEpisodes: Int? = null,
- ) : AbstractSyncStatus()
-
- data class SyncResult(
- /**Used to verify*/
- var id: String,
-
- var totalEpisodes: Int? = null,
-
- var title: String? = null,
- var publicScore: Score? = null,
- /**In minutes*/
- var duration: Int? = null,
- var synopsis: String? = null,
- var airStatus: ShowStatus? = null,
- var nextAiring: NextAiring? = null,
- var studio: List? = null,
- var genres: List? = null,
- var synonyms: List? = null,
- var trailers: List? = null,
- var isAdult: Boolean? = null,
- var posterUrl: String? = null,
- var backgroundPosterUrl: String? = null,
-
- /** In unixtime */
- var startDate: Long? = null,
- /** In unixtime */
- var endDate: Long? = null,
- var recommendations: List? = null,
- var nextSeason: SyncSearchResult? = null,
- var prevSeason: SyncSearchResult? = null,
- var actors: List? = null,
- )
-
- data class Page(
- val title: UiText, var items: List
- ) {
- fun sort(method: ListSorting?, query: String? = null) {
- items = when (method) {
- ListSorting.Query ->
- if (query != null) {
- items.sortedBy {
- -Levenshtein.partialRatio(
- query.lowercase(), it.name.lowercase()
- )
- }
- } else items
-
- ListSorting.RatingHigh -> items.sortedBy { -(it.personalRating?.toInt(100) ?: 0) }
- ListSorting.RatingLow -> items.sortedBy { (it.personalRating?.toInt(100) ?: 0) }
- ListSorting.AlphabeticalA -> items.sortedBy { it.name }
- ListSorting.AlphabeticalZ -> items.sortedBy { it.name }.reversed()
- ListSorting.UpdatedNew -> items.sortedBy { it.lastUpdatedUnixTime?.times(-1) }
- ListSorting.UpdatedOld -> items.sortedBy { it.lastUpdatedUnixTime }
- ListSorting.ReleaseDateNew -> items.sortedByDescending { it.releaseDate }
- ListSorting.ReleaseDateOld -> items.sortedBy { it.releaseDate }
- else -> items
- }
- }
- }
-
- data class LibraryMetadata(
- val allLibraryLists: List,
- val supportedListSorting: Set
- )
-
- data class LibraryList(
- val name: UiText,
- val items: List
- )
-
- data class LibraryItem(
- override val name: String,
- override val url: String,
- /**
- * Unique unchanging string used for data storage.
- * This should be the actual id when you change scores and status
- * since score changes from library might get added in the future.
- **/
- val syncId: String,
- val episodesCompleted: Int?,
- val episodesTotal: Int?,
- val personalRating: Score?,
- val lastUpdatedUnixTime: Long?,
- override val apiName: String,
- override var type: TvType?,
- override var posterUrl: String?,
- override var posterHeaders: Map?,
- override var quality: SearchQuality?,
- val releaseDate: Date?,
- override var id: Int? = null,
- val plot: String? = null,
- override var score: Score? = null,
- val tags: List? = null
- ) : SearchResponse
-}
+package com.lagradost.cloudstream3.syncproviders
+
+import com.lagradost.cloudstream3.*
+import com.lagradost.cloudstream3.ui.SyncWatchType
+import com.lagradost.cloudstream3.ui.library.ListSorting
+import com.lagradost.cloudstream3.utils.UiText
+import me.xdrop.fuzzywuzzy.FuzzySearch
+import java.util.Date
+
+interface SyncAPI : OAuth2API {
+ /**
+ * Set this to true if the user updates something on the list like watch status or score
+ **/
+ var requireLibraryRefresh: Boolean
+ val mainUrl: String
+
+ /**
+ * Allows certain providers to open pages from
+ * library links.
+ **/
+ val syncIdName: SyncIdName
+
+ /**
+ -1 -> None
+ 0 -> Watching
+ 1 -> Completed
+ 2 -> OnHold
+ 3 -> Dropped
+ 4 -> PlanToWatch
+ 5 -> ReWatching
+ */
+ suspend fun score(id: String, status: AbstractSyncStatus): Boolean
+
+ suspend fun getStatus(id: String): AbstractSyncStatus?
+
+ suspend fun getResult(id: String): SyncResult?
+
+ suspend fun search(name: String): List?
+
+ suspend fun getPersonalLibrary(): LibraryMetadata?
+
+ fun getIdFromUrl(url: String): String
+
+ data class SyncSearchResult(
+ override val name: String,
+ override val apiName: String,
+ var syncId: String,
+ override val url: String,
+ override var posterUrl: String?,
+ override var type: TvType? = null,
+ override var quality: SearchQuality? = null,
+ override var posterHeaders: Map? = null,
+ override var id: Int? = null,
+ ) : SearchResponse
+
+ abstract class AbstractSyncStatus {
+ abstract var status: SyncWatchType
+
+ /** 1-10 */
+ abstract var score: Int?
+ abstract var watchedEpisodes: Int?
+ abstract var isFavorite: Boolean?
+ abstract var maxEpisodes: Int?
+ }
+
+
+ data class SyncStatus(
+ override var status: SyncWatchType,
+ /** 1-10 */
+ override var score: Int?,
+ override var watchedEpisodes: Int?,
+ override var isFavorite: Boolean? = null,
+ override var maxEpisodes: Int? = null,
+ ) : AbstractSyncStatus()
+
+ data class SyncResult(
+ /**Used to verify*/
+ var id: String,
+
+ var totalEpisodes: Int? = null,
+
+ var title: String? = null,
+ /**1-1000*/
+ var publicScore: Int? = null,
+ /**In minutes*/
+ var duration: Int? = null,
+ var synopsis: String? = null,
+ var airStatus: ShowStatus? = null,
+ var nextAiring: NextAiring? = null,
+ var studio: List? = null,
+ var genres: List? = null,
+ var synonyms: List? = null,
+ var trailers: List? = null,
+ var isAdult: Boolean? = null,
+ var posterUrl: String? = null,
+ var backgroundPosterUrl: String? = null,
+
+ /** In unixtime */
+ var startDate: Long? = null,
+ /** In unixtime */
+ var endDate: Long? = null,
+ var recommendations: List? = null,
+ var nextSeason: SyncSearchResult? = null,
+ var prevSeason: SyncSearchResult? = null,
+ var actors: List? = null,
+ )
+
+
+ data class Page(
+ val title: UiText, var items: List
+ ) {
+ fun sort(method: ListSorting?, query: String? = null) {
+ items = when (method) {
+ ListSorting.Query ->
+ if (query != null) {
+ items.sortedBy {
+ -FuzzySearch.partialRatio(
+ query.lowercase(), it.name.lowercase()
+ )
+ }
+ } else items
+ ListSorting.RatingHigh -> items.sortedBy { -(it.personalRating ?: 0) }
+ ListSorting.RatingLow -> items.sortedBy { (it.personalRating ?: 0) }
+ ListSorting.AlphabeticalA -> items.sortedBy { it.name }
+ ListSorting.AlphabeticalZ -> items.sortedBy { it.name }.reversed()
+ ListSorting.UpdatedNew -> items.sortedBy { it.lastUpdatedUnixTime?.times(-1) }
+ ListSorting.UpdatedOld -> items.sortedBy { it.lastUpdatedUnixTime }
+ ListSorting.ReleaseDateNew -> items.sortedByDescending { it.releaseDate }
+ ListSorting.ReleaseDateOld -> items.sortedBy { it.releaseDate }
+ else -> items
+ }
+ }
+ }
+
+ data class LibraryMetadata(
+ val allLibraryLists: List,
+ val supportedListSorting: Set
+ )
+
+ data class LibraryList(
+ val name: UiText,
+ val items: List
+ )
+
+ data class LibraryItem(
+ override val name: String,
+ override val url: String,
+ /**
+ * Unique unchanging string used for data storage.
+ * This should be the actual id when you change scores and status
+ * since score changes from library might get added in the future.
+ **/
+ val syncId: String,
+ val episodesCompleted: Int?,
+ val episodesTotal: Int?,
+ /** Out of 100 */
+ val personalRating: Int?,
+ val lastUpdatedUnixTime: Long?,
+ override val apiName: String,
+ override var type: TvType?,
+ override var posterUrl: String?,
+ override var posterHeaders: Map?,
+ override var quality: SearchQuality?,
+ val releaseDate: Date?,
+ override var id: Int? = null,
+ val plot : String? = null,
+ val rating: Int? = null,
+ val tags: List? = null
+ ) : SearchResponse
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SyncRepo.kt b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SyncRepo.kt
index de82624fc..9363cb6fb 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SyncRepo.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SyncRepo.kt
@@ -1,30 +1,48 @@
-package com.lagradost.cloudstream3.syncproviders
-
-/** Stateless safe abstraction of SyncAPI */
-class SyncRepo(override val api: SyncAPI) : AuthRepo(api) {
- val syncIdName = api.syncIdName
- var requireLibraryRefresh: Boolean
- get() = api.requireLibraryRefresh
- set(value) {
- api.requireLibraryRefresh = value
- }
-
- suspend fun updateStatus(id: String, newStatus: SyncAPI.AbstractSyncStatus): Result =
- runCatching {
- val status = api.updateStatus(freshAuth() ?: return@runCatching false, id, newStatus)
- requireLibraryRefresh = true
- status
- }
-
- suspend fun status(id: String): Result = runCatching {
- api.status(freshAuth(), id)
- }
-
- suspend fun load(id: String): Result = runCatching {
- api.load(freshAuth(), id)
- }
-
- suspend fun library(): Result = runCatching {
- api.library(freshAuth())
- }
-}
+package com.lagradost.cloudstream3.syncproviders
+
+import com.lagradost.cloudstream3.ErrorLoadingException
+import com.lagradost.cloudstream3.mvvm.Resource
+import com.lagradost.cloudstream3.mvvm.normalSafeApiCall
+import com.lagradost.cloudstream3.mvvm.safeApiCall
+
+class SyncRepo(private val repo: SyncAPI) {
+ val idPrefix = repo.idPrefix
+ val name = repo.name
+ val icon = repo.icon
+ val mainUrl = repo.mainUrl
+ val requiresLogin = repo.requiresLogin
+ val syncIdName = repo.syncIdName
+ var requireLibraryRefresh: Boolean
+ get() = repo.requireLibraryRefresh
+ set(value) {
+ repo.requireLibraryRefresh = value
+ }
+
+ suspend fun score(id: String, status: SyncAPI.AbstractSyncStatus): Resource {
+ return safeApiCall { repo.score(id, status) }
+ }
+
+ suspend fun getStatus(id: String): Resource {
+ return safeApiCall { repo.getStatus(id) ?: throw ErrorLoadingException("No data") }
+ }
+
+ suspend fun getResult(id: String): Resource {
+ return safeApiCall { repo.getResult(id) ?: throw ErrorLoadingException("No data") }
+ }
+
+ suspend fun search(query: String): Resource> {
+ return safeApiCall { repo.search(query) ?: throw ErrorLoadingException() }
+ }
+
+ suspend fun getPersonalLibrary(): Resource {
+ return safeApiCall { repo.getPersonalLibrary() ?: throw ErrorLoadingException() }
+ }
+
+ fun hasAccount(): Boolean {
+ return normalSafeApiCall { repo.loginInfo() != null } ?: false
+ }
+
+ fun getIdFromUrl(url: String): String? = normalSafeApiCall {
+ repo.getIdFromUrl(url)
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/Addic7ed.kt b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/Addic7ed.kt
index 144efff99..db4676393 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/Addic7ed.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/Addic7ed.kt
@@ -1,205 +1,108 @@
package com.lagradost.cloudstream3.syncproviders.providers
-import com.lagradost.cloudstream3.AllLanguagesName
-import com.lagradost.cloudstream3.app
-import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities.SubtitleEntity
-import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities.SubtitleSearch
-import com.lagradost.cloudstream3.syncproviders.AuthData
-import com.lagradost.cloudstream3.syncproviders.SubtitleAPI
import com.lagradost.cloudstream3.TvType
-import com.lagradost.cloudstream3.utils.SubtitleHelper.fromTagToEnglishLanguageName
+import com.lagradost.cloudstream3.app
+import com.lagradost.cloudstream3.subtitles.AbstractSubApi
+import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities
+import com.lagradost.cloudstream3.utils.SubtitleHelper
-class Addic7ed : SubtitleAPI() {
+class Addic7ed : AbstractSubApi {
override val name = "Addic7ed"
override val idPrefix = "addic7ed"
override val requiresLogin = false
+ override val icon: Nothing? = null
+ override val createAccountUrl: Nothing? = null
+
+ override fun loginInfo(): Nothing? = null
+
+ override fun logOut() {}
companion object {
const val HOST = "https://www.addic7ed.com"
const val TAG = "ADDIC7ED"
}
- private fun String.fixUrl(): String {
- val url = this
+ private fun fixUrl(url: String): String {
return if (url.startsWith("/")) HOST + url
else if (!url.startsWith("http")) "$HOST/$url"
else url
+
}
- override suspend fun search(
- auth: AuthData?,
- query: SubtitleSearch
- ): List? {
- val langTagIETF = query.lang ?: AllLanguagesName
- val langNumAddic7ed =
- langTagIETF2Addic7ed[langTagIETF]?.first ?: 0 // all languages = 0
- val langName =
- langTagIETF2Addic7ed[langTagIETF]?.second ?:
- fromTagToEnglishLanguageName(langTagIETF) ?:
- "Completed" // this bypasses language filtering
- val title = query.query.trim()
+ override suspend fun search(query: AbstractSubtitleEntities.SubtitleSearch): List {
+ val lang = query.lang
+ val queryLang = SubtitleHelper.fromTwoLettersToLanguage(lang.toString())
+ val queryText = query.query.trim()
val epNum = query.epNumber ?: 0
val seasonNum = query.seasonNumber ?: 0
val yearNum = query.year ?: 0
- val searchQuery = if (seasonNum > 0) "$title $seasonNum $epNum" else title
- var downloadPage = ""
- fun newSubtitleEntity (
- displayName: String?,
- link: String?,
+ fun cleanResources(
+ results: MutableList,
+ name: String,
+ link: String,
+ headers: Map,
isHearingImpaired: Boolean
- ): SubtitleEntity? {
- if (displayName.isNullOrBlank() || link.isNullOrBlank()) return null
- return SubtitleEntity(
- idPrefix = this.idPrefix,
- name = displayName,
- lang = langTagIETF,
- data = link,
- source = this.name,
- type = if (seasonNum > 0) TvType.TvSeries else TvType.Movie,
- epNumber = epNum,
- seasonNumber = seasonNum,
- year = yearNum,
- headers = mapOf("referer" to "$HOST/"),
- isHearingImpaired = isHearingImpaired
+ ) {
+ results.add(
+ AbstractSubtitleEntities.SubtitleEntity(
+ idPrefix = idPrefix,
+ name = name,
+ lang = queryLang.toString(),
+ data = link,
+ source = this.name,
+ type = if (seasonNum > 0) TvType.TvSeries else TvType.Movie,
+ epNumber = epNum,
+ seasonNumber = seasonNum,
+ year = yearNum,
+ headers = headers,
+ isHearingImpaired = isHearingImpaired
+ )
)
}
- val response = app.get(url = "$HOST/search.php?search=$searchQuery&Submit=Search")
- val hostDocument = response.document
-
- // 1st case: found one movie or episode. Redirected to $HOST/movie/1234 or $HOST/serie/show-name/$seasonNum/$epNum/ep-name
- if (response.url.contains("/movie/") || response.url.contains("/serie/"))
- downloadPage = response.url
-
- // 2nd case: found tv series ep list. Redirected to $HOST/show/1234
- else if (response.url.contains("/show/")) {
- val showId = response.url.substringAfterLast("/")
+ val title = queryText.substringBefore("(").trim()
+ val url = "$HOST/search.php?search=${title}&Submit=Search"
+ val hostDocument = app.get(url).document
+ var searchResult = ""
+ if (!hostDocument.select("span:contains($title)").isNullOrEmpty()) searchResult = url
+ else if (!hostDocument.select("table.tabel")
+ .isNullOrEmpty()
+ ) searchResult = hostDocument.select("a:contains($title)").attr("href").toString()
+ else {
+ val show =
+ hostDocument.selectFirst("#sl button")?.attr("onmouseup")?.substringAfter("(")
+ ?.substringBefore(",")
val doc = app.get(
- "$HOST/ajax_loadShow.php?show=$showId&season=$seasonNum&langs=|$langNumAddic7ed|&hd=0&hi=0",
+ "$HOST/ajax_loadShow.php?show=$show&season=$seasonNum&langs=&hd=undefined&hi=undefined",
referer = "$HOST/"
).document
-
- // get direct subtitles links from list
- return doc.select("#season tbody tr").mapNotNull { node ->
- if (node.select("td:eq(1)").text().toIntOrNull() == epNum)
- newSubtitleEntity(
- displayName = node.select("td:eq(2)").text() + "\n" + node.select("td:eq(4)").text(),
- link = node.selectFirst("a[href~=updated\\/|original\\/]")?.attr("href")?.fixUrl(),
- isHearingImpaired = node.select("td:eq(6)").text().isNotEmpty()
- )
- else null
+ doc.select("#season tr:contains($queryLang)").mapNotNull { node ->
+ if (node.selectFirst("td")?.text()
+ ?.toIntOrNull() == seasonNum && node.select("td:eq(1)")
+ .text()
+ .toIntOrNull() == epNum
+ ) searchResult = fixUrl(node.select("a").attr("href"))
}
- // 3rd case: found several or no results. Still in $HOST/search.php?search=title
- } else {// (response.url.contains("/search.php"))
- downloadPage = hostDocument.select("table.tabel a").selectFirst({
- // tv series
- if (seasonNum > 0) "a[href~=serie\\/.+\\/$seasonNum\\/$epNum\\/\\w]"
- // movie + year
- else if( yearNum > 0) "a[href~=movie\\/]:contains($yearNum)"
- // movie
- else "a[href~=movie\\/]"
- }())?.attr("href")?.fixUrl() ?: return null
}
+ val results = mutableListOf()
+ val document = app.get(
+ url = fixUrl(searchResult),
+ ).document
- // filter download page by language. Do not work for movies :/
- if (downloadPage.contains("/serie/"))
- downloadPage = downloadPage.substringBeforeLast("/") + "/$langNumAddic7ed"
- val doc = app.get(url = downloadPage).document
-
- // get subtitles links from download page
- return doc.select(".tabel95 .tabel95 tr:has(.language):contains($langName)").mapNotNull { node ->
- val displayName =
- doc.selectFirst("span.titulo")?.text()?.substringBefore(" Subtitle") + "\n" +
- node.parent()!!.select(".NewsTitle").text().substringAfter("Version ").substringBefore(", Duration")
- val link =
- node.selectFirst("a[href~=updated\\/|original\\/]")?.attr("href")?.fixUrl()
+ document.select(".tabel95 .tabel95 tr:contains($queryLang)").mapNotNull { node ->
+ val name = if (seasonNum > 0) "${document.select(".titulo").text().replace("Subtitle","").trim()}${
+ node.parent()!!.select(".NewsTitle").text().substringAfter("Version").substringBefore(", Duration")
+ }" else "${document.select(".titulo").text().replace("Subtitle","").trim()}${node.parent()!!.select(".NewsTitle").text().substringAfter("Version").substringBefore(", Duration")}"
+ val link = fixUrl(node.select("a.buttonDownload").attr("href"))
val isHearingImpaired =
- node.parent()!!.select("tr:last-child [title=\"Hearing Impaired\"]").isNotEmpty()
-
- newSubtitleEntity(displayName, link, isHearingImpaired)
+ !node.parent()!!.select("tr:last-child [title=\"Hearing Impaired\"]").isNullOrEmpty()
+ cleanResources(results, name, link, mapOf("referer" to "$HOST/"), isHearingImpaired)
}
+ return results
}
- override suspend fun load(
- auth: AuthData?,
- subtitle: SubtitleEntity
- ): String? {
- return subtitle.data
+ override suspend fun load(data: AbstractSubtitleEntities.SubtitleEntity): String {
+ return data.data
}
-
- // Missing (?_?)
- // Pair("2", ""),
- // Pair("3", ""),
- // Pair("33", ""),
- // Pair("34", ""),
- // Do not modify unless Addic7ed changes them!
- // as they are the exact values from their website
- private val langTagIETF2Addic7ed = mapOf(
- "ar" to Pair("38", "Arabic"),
- "az" to Pair("48", "Azerbaijani"),
- "bg" to Pair("35", "Bulgarian"),
- "bn" to Pair("47", "Bengali"),
- "bs" to Pair("44", "Bosnian"),
- "ca" to Pair("12", "Català"),
- "cs" to Pair("14", "Czech"),
- "cy" to Pair("65", "Welsh"),
- "da" to Pair("30", "Danish"),
- "de" to Pair("11", "German"),
- "el" to Pair("27", "Greek"),
- "en" to Pair("1", "English"),
- "es-419" to Pair("6", "Spanish (Latin America)"),
- "es-ar" to Pair("69", "Spanish (Argentina)"),
- "es-es" to Pair("5", "Spanish (Spain)"),
- "es" to Pair("4", "Spanish"),
- "et" to Pair("54", "Estonian"),
- "eu" to Pair("13", "Euskera"),
- "fa" to Pair("43", "Persian"),
- "fi" to Pair("28", "Finnish"),
- "fr-ca" to Pair("53", "French (Canadian)"),
- "fr" to Pair("8", "French"),
- "gl" to Pair("15", "Galego"),
- "he" to Pair("23", "Hebrew"),
- "hi" to Pair("55", "Hindi"),
- "hr" to Pair("31", "Croatian"),
- "hu" to Pair("20", "Hungarian"),
- "hy" to Pair("50", "Armenian"),
- "id" to Pair("37", "Indonesian"),
- "is" to Pair("56", "Icelandic"),
- "it" to Pair("7", "Italian"),
- "ja" to Pair("32", "Japanese"),
- "kn" to Pair("66", "Kannada"),
- "ko" to Pair("42", "Korean"),
- "lt" to Pair("58", "Lithuanian"),
- "lv" to Pair("57", "Latvian"),
- "mk" to Pair("49", "Macedonian"),
- "ml" to Pair("67", "Malayalam"),
- "mr" to Pair("62", "Marathi"),
- "ms" to Pair("40", "Malay"),
- "nl" to Pair("17", "Dutch"),
- "no" to Pair("29", "Norwegian"),
- "pl" to Pair("21", "Polish"),
- "pt-br" to Pair("10", "Portuguese (Brazilian)"),
- "pt" to Pair("9", "Portuguese"),
- "ro" to Pair("26", "Romanian"),
- "ru" to Pair("19", "Russian"),
- "si" to Pair("60", "Sinhala"),
- "sk" to Pair("25", "Slovak"),
- "sl" to Pair("22", "Slovenian"),
- "sq" to Pair("52", "Albanian"),
- "sr-latn" to Pair("36", "Serbian (Latin)"),
- "sr" to Pair("39", "Serbian (Cyrillic)"),
- "sv" to Pair("18", "Swedish"),
- "ta" to Pair("59", "Tamil"),
- "te" to Pair("63", "Telugu"),
- "th" to Pair("46", "Thai"),
- "tl" to Pair("68", "Tagalog"),
- "tlh" to Pair("61", "Klingon"),
- "tr" to Pair("16", "Turkish"),
- "uk" to Pair("51", "Ukrainian"),
- "vi" to Pair("45", "Vietnamese"),
- "yue" to Pair("64", "Cantonese"),
- "zh-hans" to Pair("41", "Chinese (Simplified)"),
- "zh-hant" to Pair("24", "Chinese (Traditional)"),
- )
}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/AniListApi.kt b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/AniListApi.kt
index d3e7f22c7..68a4a9a54 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/AniListApi.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/AniListApi.kt
@@ -1,93 +1,93 @@
package com.lagradost.cloudstream3.syncproviders.providers
import androidx.annotation.StringRes
+import androidx.fragment.app.FragmentActivity
import com.fasterxml.jackson.annotation.JsonProperty
-import com.lagradost.cloudstream3.Actor
-import com.lagradost.cloudstream3.ActorData
-import com.lagradost.cloudstream3.ActorRole
-import com.lagradost.cloudstream3.APIHolder
-import com.lagradost.cloudstream3.BuildConfig
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
-import com.lagradost.cloudstream3.ErrorLoadingException
-import com.lagradost.cloudstream3.NextAiring
-import com.lagradost.cloudstream3.R
-import com.lagradost.cloudstream3.Score
-import com.lagradost.cloudstream3.TvType
-import com.lagradost.cloudstream3.app
+import com.lagradost.cloudstream3.*
+import com.lagradost.cloudstream3.AcraApplication.Companion.getKey
+import com.lagradost.cloudstream3.AcraApplication.Companion.openBrowser
+import com.lagradost.cloudstream3.AcraApplication.Companion.setKey
import com.lagradost.cloudstream3.mvvm.logError
-import com.lagradost.cloudstream3.syncproviders.AuthData
-import com.lagradost.cloudstream3.syncproviders.AuthLoginPage
-import com.lagradost.cloudstream3.syncproviders.AuthToken
-import com.lagradost.cloudstream3.syncproviders.AuthUser
+import com.lagradost.cloudstream3.mvvm.suspendSafeApiCall
+import com.lagradost.cloudstream3.syncproviders.AccountManager
+import com.lagradost.cloudstream3.syncproviders.AuthAPI
import com.lagradost.cloudstream3.syncproviders.SyncAPI
import com.lagradost.cloudstream3.syncproviders.SyncIdName
import com.lagradost.cloudstream3.ui.SyncWatchType
import com.lagradost.cloudstream3.ui.library.ListSorting
+import com.lagradost.cloudstream3.utils.txt
+import com.lagradost.cloudstream3.utils.AppContextUtils.splitQuery
import com.lagradost.cloudstream3.utils.AppUtils.parseJson
import com.lagradost.cloudstream3.utils.AppUtils.toJson
import com.lagradost.cloudstream3.utils.AppUtils.tryParseJson
+import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
+import com.lagradost.cloudstream3.utils.DataStore.toKotlinObject
import com.lagradost.cloudstream3.utils.DataStoreHelper.toYear
-import com.lagradost.cloudstream3.utils.txt
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
+import java.net.URL
import java.net.URLEncoder
import java.util.Locale
-class AniListApi : SyncAPI() {
+class AniListApi(index: Int) : AccountManager(index), SyncAPI {
override var name = "AniList"
+ override val key = "6871"
+ override val redirectUrl = "anilistlogin"
override val idPrefix = "anilist"
-
- private val key = BuildConfig.ANILIST_KEY
- override val redirectUrlIdentifier = "anilistlogin"
override var requireLibraryRefresh = true
- override val hasOAuth2 = true
+ override val supportDeviceAuth = false
override var mainUrl = "https://anilist.co"
override val icon = R.drawable.ic_anilist_icon
+ override val requiresLogin = false
override val createAccountUrl = "$mainUrl/signup"
override val syncIdName = SyncIdName.Anilist
- override fun loginRequest(): AuthLoginPage? =
- AuthLoginPage("https://anilist.co/api/v2/oauth/authorize?client_id=$key&response_type=token")
-
- override suspend fun login(redirectUrl: String, payload: String?): AuthToken? {
- val sanitizer = splitRedirectUrl(redirectUrl)
- val token = AuthToken(
- accessToken = sanitizer["access_token"]
- ?: throw ErrorLoadingException("No access token"),
- // refreshToken = sanitizer["refresh_token"],
- accessTokenLifetime = APIHolder.unixTime + sanitizer["expires_in"]!!.toLong(),
- )
- return token
+ override fun loginInfo(): AuthAPI.LoginInfo? {
+ // context.getUser(true)?.
+ getKey(accountId, ANILIST_USER_KEY)?.let { user ->
+ return AuthAPI.LoginInfo(
+ profilePicture = user.picture,
+ name = user.name,
+ accountIndex = accountIndex
+ )
+ }
+ return null
}
- // https://docs.anilist.co/guide/auth/
- override suspend fun refreshToken(token: AuthToken): AuthToken? {
- // AniList access tokens are long-lived. They will remain valid for 1 year from the time they are issued.
- // Refresh tokens are not currently supported. Once a token expires, you will need to re-authenticate your users.
- return super.refreshToken(token)
+ override fun logOut() {
+ requireLibraryRefresh = true
+ removeAccountKeys()
}
- override suspend fun user(token: AuthToken?): AuthUser? {
- val user = getUser(token ?: return null)
- ?: throw ErrorLoadingException("Unable to fetch user data")
-
- return AuthUser(
- id = user.id,
- name = user.name,
- profilePicture = user.picture,
- )
+ override fun authenticate(activity: FragmentActivity?) {
+ val request = "https://anilist.co/api/v2/oauth/authorize?client_id=$key&response_type=token"
+ openBrowser(request, activity)
}
- override fun urlToId(url: String): String? =
- url.removePrefix("$mainUrl/anime/").removeSuffix("/")
+ override suspend fun handleRedirect(url: String): Boolean {
+ val sanitizer =
+ splitQuery(URL(url.replace(APP_STRING, "https").replace("/#", "?"))) // FIX ERROR
+ val token = sanitizer["access_token"]!!
+ val expiresIn = sanitizer["expires_in"]!!
+
+ val endTime = unixTime + expiresIn.toLong()
+
+ switchToNewAccount()
+ setKey(accountId, ANILIST_UNIXTIME_KEY, endTime)
+ setKey(accountId, ANILIST_TOKEN_KEY, token)
+ val user = getUser()
+ requireLibraryRefresh = true
+ return user != null
+ }
+
+ override fun getIdFromUrl(url: String): String {
+ return url.removePrefix("$mainUrl/anime/").removeSuffix("/")
+ }
private fun getUrlFromId(id: Int): String {
return "$mainUrl/anime/$id"
}
- override suspend fun search(auth: AuthData?, query: String): List? {
- val data = searchShows(query) ?: return null
+ override suspend fun search(name: String): List? {
+ val data = searchShows(name) ?: return null
return data.data?.page?.media?.map {
SyncAPI.SyncSearchResult(
it.title.romaji ?: return null,
@@ -99,16 +99,17 @@ class AniListApi : SyncAPI() {
}
}
- override suspend fun load(auth: AuthData?, id: String): SyncAPI.SyncResult? {
+ override suspend fun getResult(id: String): SyncAPI.SyncResult {
val internalId = (Regex("anilist\\.co/anime/(\\d*)").find(id)?.groupValues?.getOrNull(1)
?: id).toIntOrNull() ?: throw ErrorLoadingException("Invalid internalId")
val season = getSeason(internalId).data.media
+
return SyncAPI.SyncResult(
season.id.toString(),
nextAiring = season.nextAiringEpisode?.let {
NextAiring(
it.episode ?: return@let null,
- (it.timeUntilAiring ?: return@let null) + APIHolder.unixTime
+ (it.timeUntilAiring ?: return@let null) + unixTime
)
},
title = season.title?.userPreferred,
@@ -140,11 +141,11 @@ class AniListApi : SyncAPI() {
}
)
},
- publicScore = Score.from100(season.averageScore),
+ publicScore = season.averageScore?.times(100),
recommendations = season.recommendations?.edges?.mapNotNull { rec ->
val recMedia = rec.node.mediaRecommendation
SyncAPI.SyncSearchResult(
- name = recMedia?.title?.userPreferred ?: return@mapNotNull null,
+ name = recMedia.title?.userPreferred ?: return@mapNotNull null,
this.name,
recMedia.id?.toString() ?: return@mapNotNull null,
getUrlFromId(recMedia.id),
@@ -156,15 +157,16 @@ class AniListApi : SyncAPI() {
"youtube" -> listOf("https://www.youtube.com/watch?v=${season.trailer.id}")
else -> null
}
- // TODO REST
+ //TODO REST
)
}
- override suspend fun status(auth: AuthData?, id: String): SyncAPI.AbstractSyncStatus? {
+ override suspend fun getStatus(id: String): SyncAPI.AbstractSyncStatus? {
val internalId = id.toIntOrNull() ?: return null
- val data = getDataAboutId(auth ?: return null, internalId) ?: return null
+ val data = getDataAboutId(internalId) ?: return null
+
return SyncAPI.SyncStatus(
- score = Score.from100(data.score),
+ score = data.score,
watchedEpisodes = data.progress,
status = SyncWatchType.fromInternalId(data.type?.value ?: return null),
isFavorite = data.isFavourite,
@@ -172,25 +174,24 @@ class AniListApi : SyncAPI() {
)
}
- override suspend fun updateStatus(
- auth: AuthData?,
- id: String,
- newStatus: AbstractSyncStatus
- ): Boolean {
+ override suspend fun score(id: String, status: SyncAPI.AbstractSyncStatus): Boolean {
return postDataAboutId(
- auth ?: return false,
id.toIntOrNull() ?: return false,
- fromIntToAnimeStatus(newStatus.status.internalId),
- newStatus.score,
- newStatus.watchedEpisodes
- )
+ fromIntToAnimeStatus(status.status.internalId),
+ status.score,
+ status.watchedEpisodes
+ ).also {
+ requireLibraryRefresh = requireLibraryRefresh || it
+ }
}
companion object {
- const val MAX_STALE = 60 * 10
private val aniListStatusString =
arrayOf("CURRENT", "COMPLETED", "PAUSED", "DROPPED", "PLANNING", "REPEATING")
+ const val ANILIST_UNIXTIME_KEY: String = "anilist_unixtime" // When token expires
+ const val ANILIST_TOKEN_KEY: String = "anilist_token" // anilist token for api
+ const val ANILIST_USER_KEY: String = "anilist_user" // user data like profile
const val ANILIST_CACHED_LIST: String = "anilist_cached_list"
private fun fixName(name: String): String {
@@ -258,24 +259,24 @@ class AniListApi : SyncAPI() {
val data =
mapOf(
"query" to query,
- "variables" to Variables(
- search = name,
- page = 1,
- type = "ANIME",
- ).toJson()
+ "variables" to
+ mapOf(
+ "search" to name,
+ "page" to 1,
+ "type" to "ANIME"
+ ).toJson()
)
val res = app.post(
"https://graphql.anilist.co/",
- // headers = mapOf(),
- data = data, // (if (vars == null) mapOf("query" to q) else mapOf("query" to q, "variables" to vars))
+ //headers = mapOf(),
+ data = data,//(if (vars == null) mapOf("query" to q) else mapOf("query" to q, "variables" to vars))
timeout = 5000 // REASONABLE TIMEOUT
).text.replace("\\", "")
- return parseJson(res)
+ return res.toKotlinObject()
} catch (e: Exception) {
logError(e)
}
-
return null
}
@@ -298,7 +299,7 @@ class AniListApi : SyncAPI() {
.replace(")", "\\)")
})"""
)
- // println("NAME $name NEW NAME ${name.replace(blackListRegex, "")}")
+ //println("NAME $name NEW NAME ${name.replace(blackListRegex, "")}")
val shows = searchShows(name.replace(blackListRegex, ""))
shows?.data?.page?.media?.find {
@@ -456,11 +457,25 @@ class AniListApi : SyncAPI() {
cacheTime = 0,
).text
- return tryParseJson(data) ?: throw ErrorLoadingException("Error parsing $data")
+ return tryParseJson(data) ?: throw ErrorLoadingException("Error parsing $data")
}
}
- private suspend fun getDataAboutId(auth: AuthData, id: Int): AniListTitleHolder? {
+ fun initGetUser() {
+ if (getAuth() == null) return
+ ioSafe {
+ getUser()
+ }
+ }
+
+ private fun checkToken(): Boolean {
+ return unixTime > getKey(
+ accountId,
+ ANILIST_UNIXTIME_KEY, 0L
+ )!!
+ }
+
+ private suspend fun getDataAboutId(id: Int): AniListTitleHolder? {
val q =
"""query (${'$'}id: Int = $id) { # Define which variables will be used in the query (id)
Media (id: ${'$'}id, type: ANIME) { # Insert our variables into the query arguments (id) (type: ANIME is hard-coded in the query)
@@ -470,7 +485,7 @@ class AniListApi : SyncAPI() {
mediaListEntry {
progress
status
- score (format: POINT_100)
+ score (format: POINT_10)
}
title {
english
@@ -479,7 +494,7 @@ class AniListApi : SyncAPI() {
}
}"""
- val data = postApi(auth.token, q, true)
+ val data = postApi(q, true)
val d = parseJson(data ?: return null)
val main = d.data?.media
@@ -504,99 +519,100 @@ class AniListApi : SyncAPI() {
type = AniListStatusType.None,
)
}
+
}
- private suspend fun postApi(token: AuthToken, q: String, cache: Boolean = false): String? {
- return app.post(
- "https://graphql.anilist.co/",
- headers = mapOf(
- "Authorization" to "Bearer ${token.accessToken ?: return null}",
- if (cache) "Cache-Control" to "max-stale=$MAX_STALE" else "Cache-Control" to "no-cache"
- ),
- cacheTime = 0,
- data = mapOf(
- "query" to URLEncoder.encode(
- q,
- "UTF-8"
- )
- ), // (if (vars == null) mapOf("query" to q) else mapOf("query" to q, "variables" to vars))
- timeout = 5 // REASONABLE TIMEOUT
- ).text.replace("\\/", "/")
+ private fun getAuth(): String? {
+ return getKey(
+ accountId,
+ ANILIST_TOKEN_KEY
+ )
}
- @Serializable
- data class Variables(
- @JsonProperty("search") @SerialName("search") val search: String,
- @JsonProperty("page") @SerialName("page") val page: Int,
- @JsonProperty("type") @SerialName("type") val type: String,
- )
+ private suspend fun postApi(q: String, cache: Boolean = false): String? {
+ return suspendSafeApiCall {
+ if (!checkToken()) {
+ app.post(
+ "https://graphql.anilist.co/",
+ headers = mapOf(
+ "Authorization" to "Bearer " + (getAuth()
+ ?: return@suspendSafeApiCall null),
+ if (cache) "Cache-Control" to "max-stale=$MAX_STALE" else "Cache-Control" to "no-cache"
+ ),
+ cacheTime = 0,
+ data = mapOf(
+ "query" to URLEncoder.encode(
+ q,
+ "UTF-8"
+ )
+ ), //(if (vars == null) mapOf("query" to q) else mapOf("query" to q, "variables" to vars))
+ timeout = 5 // REASONABLE TIMEOUT
+ ).text.replace("\\/", "/")
+ } else {
+ null
+ }
+ }
+ }
- @Serializable
data class MediaRecommendation(
- @JsonProperty("id") @SerialName("id") val id: Int,
- @JsonProperty("title") @SerialName("title") val title: Title?,
- @JsonProperty("idMal") @SerialName("idMal") val idMal: Int?,
- @JsonProperty("coverImage") @SerialName("coverImage") val coverImage: CoverImage?,
- @JsonProperty("averageScore") @SerialName("averageScore") val averageScore: Int?,
+ @JsonProperty("id") val id: Int,
+ @JsonProperty("title") val title: Title?,
+ @JsonProperty("idMal") val idMal: Int?,
+ @JsonProperty("coverImage") val coverImage: CoverImage?,
+ @JsonProperty("averageScore") val averageScore: Int?
)
- @Serializable
data class FullAnilistList(
- @JsonProperty("data") @SerialName("data") val data: Data?,
+ @JsonProperty("data") val data: Data?
)
- @Serializable
data class CompletedAt(
- @JsonProperty("year") @SerialName("year") val year: Int,
- @JsonProperty("month") @SerialName("month") val month: Int,
- @JsonProperty("day") @SerialName("day") val day: Int,
+ @JsonProperty("year") val year: Int,
+ @JsonProperty("month") val month: Int,
+ @JsonProperty("day") val day: Int
)
- @Serializable
data class StartedAt(
- @JsonProperty("year") @SerialName("year") val year: String?,
- @JsonProperty("month") @SerialName("month") val month: String?,
- @JsonProperty("day") @SerialName("day") val day: String?,
+ @JsonProperty("year") val year: String?,
+ @JsonProperty("month") val month: String?,
+ @JsonProperty("day") val day: String?
)
- @Serializable
data class Title(
- @JsonProperty("english") @SerialName("english") val english: String?,
- @JsonProperty("romaji") @SerialName("romaji") val romaji: String?,
+ @JsonProperty("english") val english: String?,
+ @JsonProperty("romaji") val romaji: String?
)
- @Serializable
data class CoverImage(
- @JsonProperty("medium") @SerialName("medium") val medium: String?,
- @JsonProperty("large") @SerialName("large") val large: String?,
- @JsonProperty("extraLarge") @SerialName("extraLarge") val extraLarge: String?,
+ @JsonProperty("medium") val medium: String?,
+ @JsonProperty("large") val large: String?,
+ @JsonProperty("extraLarge") val extraLarge: String?
)
- @Serializable
data class Media(
- @JsonProperty("id") @SerialName("id") val id: Int,
- @JsonProperty("idMal") @SerialName("idMal") val idMal: Int?,
- @JsonProperty("season") @SerialName("season") val season: String?,
- @JsonProperty("seasonYear") @SerialName("seasonYear") val seasonYear: Int,
- @JsonProperty("format") @SerialName("format") val format: String?,
- @JsonProperty("episodes") @SerialName("episodes") val episodes: Int,
- @JsonProperty("title") @SerialName("title") val title: Title,
- @JsonProperty("description") @SerialName("description") val description: String?,
- @JsonProperty("coverImage") @SerialName("coverImage") val coverImage: CoverImage,
- @JsonProperty("synonyms") @SerialName("synonyms") val synonyms: List,
- @JsonProperty("nextAiringEpisode") @SerialName("nextAiringEpisode") val nextAiringEpisode: SeasonNextAiringEpisode?,
+ @JsonProperty("id") val id: Int,
+ @JsonProperty("idMal") val idMal: Int?,
+ @JsonProperty("season") val season: String?,
+ @JsonProperty("seasonYear") val seasonYear: Int,
+ @JsonProperty("format") val format: String?,
+ //@JsonProperty("source") val source: String,
+ @JsonProperty("episodes") val episodes: Int,
+ @JsonProperty("title") val title: Title,
+ @JsonProperty("description") val description: String?,
+ @JsonProperty("coverImage") val coverImage: CoverImage,
+ @JsonProperty("synonyms") val synonyms: List,
+ @JsonProperty("nextAiringEpisode") val nextAiringEpisode: SeasonNextAiringEpisode?,
)
- @Serializable
data class Entries(
- @JsonProperty("status") @SerialName("status") val status: String?,
- @JsonProperty("completedAt") @SerialName("completedAt") val completedAt: CompletedAt,
- @JsonProperty("startedAt") @SerialName("startedAt") val startedAt: StartedAt,
- @JsonProperty("updatedAt") @SerialName("updatedAt") val updatedAt: Int,
- @JsonProperty("progress") @SerialName("progress") val progress: Int,
- @JsonProperty("score") @SerialName("score") val score: Int,
- @JsonProperty("private") @SerialName("private") val private: Boolean,
- @JsonProperty("media") @SerialName("media") val media: Media,
+ @JsonProperty("status") val status: String?,
+ @JsonProperty("completedAt") val completedAt: CompletedAt,
+ @JsonProperty("startedAt") val startedAt: StartedAt,
+ @JsonProperty("updatedAt") val updatedAt: Int,
+ @JsonProperty("progress") val progress: Int,
+ @JsonProperty("score") val score: Int,
+ @JsonProperty("private") val private: Boolean,
+ @JsonProperty("media") val media: Media
) {
fun toLibraryItem(): SyncAPI.LibraryItem {
return SyncAPI.LibraryItem(
@@ -608,7 +624,7 @@ class AniListApi : SyncAPI() {
this.media.id.toString(),
this.progress,
this.media.episodes,
- Score.from100(this.score),
+ this.score,
this.updatedAt.toLong(),
"AniList",
TvType.Anime,
@@ -623,39 +639,40 @@ class AniListApi : SyncAPI() {
}
}
- @Serializable
data class Lists(
- @JsonProperty("status") @SerialName("status") val status: String?,
- @JsonProperty("entries") @SerialName("entries") val entries: List,
+ @JsonProperty("status") val status: String?,
+ @JsonProperty("entries") val entries: List
)
- @Serializable
data class MediaListCollection(
- @JsonProperty("lists") @SerialName("lists") val lists: List,
+ @JsonProperty("lists") val lists: List
)
- @Serializable
data class Data(
- @JsonProperty("MediaListCollection") @SerialName("MediaListCollection") val mediaListCollection: MediaListCollection,
+ @JsonProperty("MediaListCollection") val mediaListCollection: MediaListCollection
)
- private suspend fun getAniListAnimeListSmart(auth: AuthData): Array? {
+ private fun getAniListListCached(): Array? {
+ return getKey(ANILIST_CACHED_LIST) as? Array
+ }
+
+ private suspend fun getAniListAnimeListSmart(): Array? {
+ if (getAuth() == null) return null
+
+ if (checkToken()) return null
return if (requireLibraryRefresh) {
- val list = getFullAniListList(auth)?.data?.mediaListCollection?.lists?.toTypedArray()
+ val list = getFullAniListList()?.data?.mediaListCollection?.lists?.toTypedArray()
if (list != null) {
- setKey(ANILIST_CACHED_LIST, auth.user.id.toString(), list)
+ setKey(ANILIST_CACHED_LIST, list)
}
list
} else {
- getKey>(
- ANILIST_CACHED_LIST,
- auth.user.id.toString()
- ) as? Array
+ getAniListListCached()
}
}
- override suspend fun library(auth: AuthData?): SyncAPI.LibraryMetadata? {
- val list = getAniListAnimeListSmart(auth ?: return null)?.groupBy {
+ override suspend fun getPersonalLibrary(): SyncAPI.LibraryMetadata {
+ val list = getAniListAnimeListSmart()?.groupBy {
convertAniListStringToStatus(it.status ?: "").stringRes
}?.mapValues { group ->
group.value.map { it.entries.map { entry -> entry.toLibraryItem() } }.flatten()
@@ -682,9 +699,12 @@ class AniListApi : SyncAPI() {
)
}
- private suspend fun getFullAniListList(auth: AuthData): FullAnilistList? {
- val userID = auth.user.id
+ private suspend fun getFullAniListList(): FullAnilistList? {
+ /** WARNING ASSUMES ONE USER! **/
+
+ val userID = getKey(accountId, ANILIST_USER_KEY)?.id ?: return null
val mediaType = "ANIME"
+
val query = """
query (${'$'}userID: Int = $userID, ${'$'}MEDIA: MediaType = $mediaType) {
MediaListCollection (userId: ${'$'}userID, type: ${'$'}MEDIA) {
@@ -723,56 +743,44 @@ class AniListApi : SyncAPI() {
}
}
}
- }
+ }
"""
- val text = postApi(auth.token, query)
- return tryParseJson(text)
+ val text = postApi(query)
+ return text?.toKotlinObject()
}
- suspend fun toggleLike(auth: AuthData, id: Int): Boolean {
+ suspend fun toggleLike(id: Int): Boolean {
val q = """mutation (${'$'}animeId: Int = $id) {
- ToggleFavourite (animeId: ${'$'}animeId) {
- anime {
- nodes {
- id
- title {
- romaji
- }
- }
- }
- }
- }"""
- val data = postApi(auth.token, q)
+ ToggleFavourite (animeId: ${'$'}animeId) {
+ anime {
+ nodes {
+ id
+ title {
+ romaji
+ }
+ }
+ }
+ }
+ }"""
+ val data = postApi(q)
return data != ""
}
/** Used to query a saved MediaItem on the list to get the id for removal */
- @Serializable
- data class MediaListItemRoot(
- @JsonProperty("data") @SerialName("data") val data: MediaListItem? = null,
- )
-
- @Serializable
- data class MediaListItem(
- @JsonProperty("MediaList") @SerialName("MediaList") val mediaList: MediaListId? = null,
- )
-
- @Serializable
- data class MediaListId(
- @JsonProperty("id") @SerialName("id") val id: Long? = null,
- )
+ data class MediaListItemRoot(@JsonProperty("data") val data: MediaListItem? = null)
+ data class MediaListItem(@JsonProperty("MediaList") val mediaList: MediaListId? = null)
+ data class MediaListId(@JsonProperty("id") val id: Long? = null)
private suspend fun postDataAboutId(
- auth: AuthData,
id: Int,
type: AniListStatusType,
- score: Score?,
+ score: Int?,
progress: Int?
): Boolean {
- val userID = auth.user.id
val q =
// Delete item if status type is None
if (type == AniListStatusType.None) {
+ val userID = getKey(accountId, ANILIST_USER_KEY)?.id ?: return false
// Get list ID for deletion
val idQuery = """
query MediaList(${'$'}userId: Int = $userID, ${'$'}mediaId: Int = $id) {
@@ -781,7 +789,7 @@ class AniListApi : SyncAPI() {
}
}
"""
- val response = postApi(auth.token, idQuery)
+ val response = postApi(idQuery)
val listId =
tryParseJson(response)?.data?.mediaList?.id ?: return false
"""
@@ -797,7 +805,7 @@ class AniListApi : SyncAPI() {
0,
type.value
)]
- }, ${if (score != null) "${'$'}scoreRaw: Int = ${score.toInt(100)}" else ""} , ${if (progress != null) "${'$'}progress: Int = $progress" else ""}) {
+ }, ${if (score != null) "${'$'}scoreRaw: Int = ${score * 10}" else ""} , ${if (progress != null) "${'$'}progress: Int = $progress" else ""}) {
SaveMediaListEntry (mediaId: ${'$'}id, status: ${'$'}status, scoreRaw: ${'$'}scoreRaw, progress: ${'$'}progress) {
id
status
@@ -807,37 +815,45 @@ class AniListApi : SyncAPI() {
}"""
}
- val data = postApi(auth.token, q)
+ val data = postApi(q)
return data != ""
}
- private suspend fun getUser(token: AuthToken): AniListUser? {
+ private suspend fun getUser(setSettings: Boolean = true): AniListUser? {
val q = """
- {
- Viewer {
- id
- name
- avatar {
- large
- }
- favourites {
- anime {
- nodes {
- id
+ {
+ Viewer {
+ id
+ name
+ avatar {
+ large
+ }
+ favourites {
+ anime {
+ nodes {
+ id
+ }
}
}
- }
- }
- }"""
- val data = postApi(token, q)
+ }
+ }"""
+ val data = postApi(q)
if (data.isNullOrBlank()) return null
val userData = parseJson(data)
- val u = userData.data?.viewer ?: return null
+ val u = userData.data?.viewer
val user = AniListUser(
- u.id,
- u.name,
- u.avatar?.large,
+ u?.id,
+ u?.name,
+ u?.avatar?.large,
)
+ if (setSettings) {
+ setKey(accountId, ANILIST_USER_KEY, user)
+ registerAccount()
+ }
+ /* // TODO FIX FAVS
+ for(i in u.favourites.anime.nodes) {
+ println("FFAV:" + i.id)
+ }*/
return user
}
@@ -861,356 +877,304 @@ class AniListApi : SyncAPI() {
return seasons.toList()
}
- @Serializable
data class SeasonResponse(
- @JsonProperty("data") @SerialName("data") val data: SeasonData,
+ @JsonProperty("data") val data: SeasonData,
)
- @Serializable
data class SeasonData(
- @JsonProperty("Media") @SerialName("Media") val media: SeasonMedia,
+ @JsonProperty("Media") val media: SeasonMedia,
)
- @Serializable
- data class RecommendedMedia(
- @JsonProperty("id") @SerialName("id") val id: Int?,
- @JsonProperty("title") @SerialName("title") val title: MediaTitle?,
- @JsonProperty("coverImage") @SerialName("coverImage") val coverImage: MediaCoverImage?,
- )
-
- @Serializable
- data class CharacterMedia(
- @JsonProperty("id") @SerialName("id") val id: Int?,
- @JsonProperty("title") @SerialName("title") val title: MediaTitle?,
- @JsonProperty("coverImage") @SerialName("coverImage") val coverImage: MediaCoverImage?,
- )
-
- @Serializable
data class SeasonMedia(
- @JsonProperty("id") @SerialName("id") val id: Int?,
- @JsonProperty("title") @SerialName("title") val title: MediaTitle?,
- @JsonProperty("idMal") @SerialName("idMal") val idMal: Int?,
- @JsonProperty("format") @SerialName("format") val format: String?,
- @JsonProperty("nextAiringEpisode") @SerialName("nextAiringEpisode") val nextAiringEpisode: SeasonNextAiringEpisode?,
- @JsonProperty("relations") @SerialName("relations") val relations: SeasonEdges?,
- @JsonProperty("coverImage") @SerialName("coverImage") val coverImage: MediaCoverImage?,
- @JsonProperty("duration") @SerialName("duration") val duration: Int?,
- @JsonProperty("episodes") @SerialName("episodes") val episodes: Int?,
- @JsonProperty("genres") @SerialName("genres") val genres: List?,
- @JsonProperty("synonyms") @SerialName("synonyms") val synonyms: List?,
- @JsonProperty("averageScore") @SerialName("averageScore") val averageScore: Int?,
- @JsonProperty("isAdult") @SerialName("isAdult") val isAdult: Boolean?,
- @JsonProperty("trailer") @SerialName("trailer") val trailer: MediaTrailer?,
- @JsonProperty("description") @SerialName("description") val description: String?,
- @JsonProperty("characters") @SerialName("characters") val characters: CharacterConnection?,
- @JsonProperty("recommendations") @SerialName("recommendations") val recommendations: RecommendationConnection?,
+ @JsonProperty("id") val id: Int?,
+ @JsonProperty("title") val title: MediaTitle?,
+ @JsonProperty("idMal") val idMal: Int?,
+ @JsonProperty("format") val format: String?,
+ @JsonProperty("nextAiringEpisode") val nextAiringEpisode: SeasonNextAiringEpisode?,
+ @JsonProperty("relations") val relations: SeasonEdges?,
+ @JsonProperty("coverImage") val coverImage: MediaCoverImage?,
+ @JsonProperty("duration") val duration: Int?,
+ @JsonProperty("episodes") val episodes: Int?,
+ @JsonProperty("genres") val genres: List?,
+ @JsonProperty("synonyms") val synonyms: List?,
+ @JsonProperty("averageScore") val averageScore: Int?,
+ @JsonProperty("isAdult") val isAdult: Boolean?,
+ @JsonProperty("trailer") val trailer: MediaTrailer?,
+ @JsonProperty("description") val description: String?,
+ @JsonProperty("characters") val characters: CharacterConnection?,
+ @JsonProperty("recommendations") val recommendations: RecommendationConnection?,
)
- @Serializable
data class RecommendationConnection(
- @JsonProperty("edges") @SerialName("edges") val edges: List = emptyList(),
- @JsonProperty("nodes") @SerialName("nodes") val nodes: List = emptyList(),
+ @JsonProperty("edges") val edges: List = emptyList(),
+ @JsonProperty("nodes") val nodes: List = emptyList(),
+ //@JsonProperty("pageInfo") val pageInfo: PageInfo,
)
- @Serializable
data class RecommendationEdge(
- @JsonProperty("node") @SerialName("node") val node: Recommendation,
+ //@JsonProperty("rating") val rating: Int,
+ @JsonProperty("node") val node: Recommendation,
)
- @Serializable
data class Recommendation(
- @JsonProperty("mediaRecommendation") @SerialName("mediaRecommendation") val mediaRecommendation: RecommendedMedia?,
+ @JsonProperty("mediaRecommendation") val mediaRecommendation: SeasonMedia,
)
- @Serializable
data class CharacterName(
- @JsonProperty("name") @SerialName("name") val first: String?,
- @JsonProperty("middle") @SerialName("middle") val middle: String?,
- @JsonProperty("last") @SerialName("last") val last: String?,
- @JsonProperty("full") @SerialName("full") val full: String?,
- @JsonProperty("native") @SerialName("native") val native: String?,
- @JsonProperty("alternative") @SerialName("alternative") val alternative: List?,
- @JsonProperty("alternativeSpoiler") @SerialName("alternativeSpoiler") val alternativeSpoiler: List?,
- @JsonProperty("userPreferred") @SerialName("userPreferred") val userPreferred: String?,
+ @JsonProperty("name") val first: String?,
+ @JsonProperty("middle") val middle: String?,
+ @JsonProperty("last") val last: String?,
+ @JsonProperty("full") val full: String?,
+ @JsonProperty("native") val native: String?,
+ @JsonProperty("alternative") val alternative: List?,
+ @JsonProperty("alternativeSpoiler") val alternativeSpoiler: List?,
+ @JsonProperty("userPreferred") val userPreferred: String?,
)
- @Serializable
data class CharacterImage(
- @JsonProperty("large") @SerialName("large") val large: String?,
- @JsonProperty("medium") @SerialName("medium") val medium: String?,
+ @JsonProperty("large") val large: String?,
+ @JsonProperty("medium") val medium: String?,
)
- @Serializable
data class Character(
- @JsonProperty("name") @SerialName("name") val name: CharacterName?,
- @JsonProperty("age") @SerialName("age") val age: String?,
- @JsonProperty("image") @SerialName("image") val image: CharacterImage?,
+ @JsonProperty("name") val name: CharacterName?,
+ @JsonProperty("age") val age: String?,
+ @JsonProperty("image") val image: CharacterImage?,
)
- @Serializable
data class CharacterEdge(
- @JsonProperty("id") @SerialName("id") val id: Int?,
+ @JsonProperty("id") val id: Int?,
/**
- * MAIN - A primary character role in the media
- * SUPPORTING - A supporting character role in the media
- * BACKGROUND - A background character in the media
+ MAIN
+ A primary character role in the media
+
+ SUPPORTING
+ A supporting character role in the media
+
+ BACKGROUND
+ A background character in the media
*/
- @JsonProperty("role") @SerialName("role") val role: String?,
- @JsonProperty("name") @SerialName("name") val name: String?,
- @JsonProperty("voiceActors") @SerialName("voiceActors") val voiceActors: List?,
- @JsonProperty("favouriteOrder") @SerialName("favouriteOrder") val favouriteOrder: Int?,
- @JsonProperty("media") @SerialName("media") val media: List?,
- @JsonProperty("node") @SerialName("node") val node: Character?,
+ @JsonProperty("role") val role: String?,
+ @JsonProperty("name") val name: String?,
+ @JsonProperty("voiceActors") val voiceActors: List