Compare commits

...

52 commits

Author SHA1 Message Date
nomadics9
e009b86153 build: 16 version-0.10.6-0.14.2
Some checks failed
Build / Assemble (push) Has been cancelled
2024-07-26 05:13:37 +03:00
nomadics9
d669dcb618 hotfix 2024-07-26 05:13:08 +03:00
nomadics9
ff5bce074e build: 16 version-0.10.6-0.14.2 2024-07-26 05:02:31 +03:00
nomadics9
d85684317b feat: very simple update checker 2024-07-26 04:58:50 +03:00
nomadics9
3cc52938f2 bugfix: Download season dialog strings 2024-07-26 02:42:48 +03:00
nomadics9
3ff71ae489 build: 15 version-0.10.5-0.14.2 2024-07-21 06:23:54 +03:00
nomadics9
b511b26aa1 feat: Markdown support for disclamer 2024-07-21 06:18:21 +03:00
nomadics9
059b17af9a personal 2024-07-21 05:16:04 +03:00
nomadics9
c293c906d4 build: 15 version-0.10.5-0.14.2 2024-07-21 04:38:32 +03:00
nomadics9
b5d31a6c72 feat: select transcoding codec in network settings / code: clean up, refactors & rework alot of transcoding stuff / bugfixes: mainly deviceId 2024-07-21 04:18:08 +03:00
nomadics9
5609f7368d code: cleanup
Some checks failed
Build / Lint (push) Has been cancelled
Build / Assemble (push) Has been cancelled
2024-07-21 01:49:30 +03:00
nomadics9
d70253140d refactor: string 2024-07-21 00:43:12 +03:00
nomadics9
8482df9733 feat: choice of codec in network settings / bugfix: nullsafe fix 2024-07-21 00:42:35 +03:00
nomadics9
21ae815223 rework: getting original resolution for quality selection dialog 2024-07-20 23:55:34 +03:00
nomadics9
c79342523b refactor: strings & naming standard for icon 2024-07-20 23:12:12 +03:00
nomadics9
7adcc50d75 rework: Enum 2024-07-20 22:28:38 +03:00
nomadics9
0ace01f5f8 klint 2024-07-20 08:40:23 +03:00
nomadics9
6dded2e726 bugfixes: deviceId / code: New Enum VideoQuality 2024-07-20 08:36:23 +03:00
nomadics9
89d5a332d1 build: 14 bugfixes 2024-07-20 06:42:02 +03:00
nomadics9
4e8ee15d0a bugfixes: getDeviceId() / code: New Enum VideoQuality 2024-07-20 06:31:53 +03:00
nomadics9
ba580f8769 lint: fix 2024-07-19 05:27:17 +03:00
nomadics9
4baa7bc046 lint: klint standard 2024-07-19 05:10:32 +03:00
nomadics9
633ee6b8c4 lint: klint standard 2024-07-19 05:01:09 +03:00
nomadics9
062781a43d feat: Download transcoded media 2024-07-19 03:44:43 +03:00
nomadics9
ccc6788a02 feat: Transcoding stream in player selection /code: prep repo for next commit transcoding downloads 2024-07-19 02:20:55 +03:00
nomadics9
36dd8480e1 flow: Version 2024-07-18 23:33:28 +03:00
nomadics9
a6c1ef15b7 hotfix 2024-07-18 07:23:34 +03:00
nomadics9
75ea1dc43a hotfix 2024-07-18 07:11:32 +03:00
nomadics9
2b2e6ce58b build: 12 Embedded subs in downloaded transcode 2024-07-18 06:52:52 +03:00
nomadics9
09427e1de0 feat: Embedded subs in downloaded transcode 2024-07-18 05:20:34 +03:00
nomadics9
fbf4c185f0 build: 11 embedded subs 2024-07-18 04:08:17 +03:00
nomadics9
c84ec082be feat: Embedded subtitle in transcoding stream / bugfixes: Download quality dialog loop / code: clean up 2024-07-18 03:59:38 +03:00
nomadics9
5a8403f6a9 Build: 10 Transcoding Download Merge 2024-07-17 06:30:54 +03:00
renovate[bot]
db79b50629
chore(deps): update dependency com.google.devtools.ksp to v2.0.0-1.0.23 (#788)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-07-16 22:20:48 +02:00
renovate[bot]
45d4b88738
chore(deps): update dependency gradle to v8.9 (#789)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-07-16 22:08:26 +02:00
xxzp3
eabe738136 chore(translate): (Danish)
Currently translated at 65.2% (126 of 193 strings)

Translation: Findroid/core
Translate-URL: https://weblate.jdtech.dev/projects/findroid/core/da/
2024-07-16 12:30:01 +02:00
Jarne Demeulemeester
48d8b18bae
lint: run ktlintFormat 2024-07-15 23:20:42 +02:00
Jarne Demeulemeester
15c1ac9593
refactor(tv): replace deprecated tv lazy layouts with normal lazy layouts
Use beta version of compose for now (1.7.x)
TV compose foundation library removed
No longer using bom to specify dependencies (doesn't work with the beta versions)
2024-07-15 22:18:09 +02:00
Jarne Demeulemeester
307ce957c2
chore: target SDK 35 2024-07-13 17:12:56 +02:00
Jarne Demeulemeester
1267f9809d
chore(deps): upgrade agp, tv, tv-material3 and jellyfin
agp 8.5.0 -> 8.5.1
tv 1.0.0-alpha10 -> 1.0.0-alpha11
tv-material3 1.0.0-beta01 -> 1.0.0-rc01
jellyfin 1.5.0-beta.4 -> 1.5.0
2024-07-13 16:52:03 +02:00
Suyash Mahar
e00156cd1c chore(translate): (Hindi)
Currently translated at 59.5% (115 of 193 strings)

Translation: Findroid/core
Translate-URL: https://weblate.jdtech.dev/projects/findroid/core/hi/
2024-07-13 04:30:01 +02:00
Suyash Mahar
ea1163d25d chore(translate): (French)
Currently translated at 99.4% (192 of 193 strings)

Translation: Findroid/core
Translate-URL: https://weblate.jdtech.dev/projects/findroid/core/fr/
2024-07-13 04:30:01 +02:00
Suyash Mahar
0c94c3c7dc chore(translate): add (Hindi) 2024-07-12 04:20:24 +02:00
Jasper
03023d8c9f chore(translate): (Dutch)
Currently translated at 98.9% (191 of 193 strings)

Translation: Findroid/core
Translate-URL: https://weblate.jdtech.dev/projects/findroid/core/nl/
2024-07-10 12:41:17 +02:00
Jarne Demeulemeester
785db44744
chore(deps): update androidx lifecyle to 2.8.3
lifecycle 2.8.2 -> 2.8.3
2024-07-07 14:01:18 +02:00
renovate[bot]
2dd65705af
fix(deps): update dependency org.jetbrains.kotlinx:kotlinx-serialization-json to v1.7.1 (#786)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-07-02 12:39:35 +02:00
renovate[bot]
2bfe4388ea
chore(deps): update aboutlibraries to v11.2.2 (#785)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-07-02 12:38:31 +02:00
adiskill
44fe7dac35 chore(translate): (Slovak)
Currently translated at 100.0% (193 of 193 strings)

Translation: Findroid/core
Translate-URL: https://weblate.jdtech.dev/projects/findroid/core/sk/
2024-06-30 20:30:01 +02:00
Jarne Demeulemeester
544e6432f5
chore(deps): update libmpv
libmpv 0.2.0 -> 0.3.0
2024-06-30 18:47:03 +02:00
Jarne Demeulemeester
36891e7682
test: fix main flow test and update dependencies 2024-06-29 23:00:11 +02:00
nomadics9
32c6d22035 chore(translate): (Arabic)
Currently translated at 8.8% (17 of 193 strings)

Translation: Findroid/core
Translate-URL: https://weblate.jdtech.dev/projects/findroid/core/ar/
2024-06-29 14:30:01 +02:00
Tio
ba03ef4e9f chore(translate): (Portuguese (Brazil))
Currently translated at 98.9% (191 of 193 strings)

Translation: Findroid/core
Translate-URL: https://weblate.jdtech.dev/projects/findroid/core/pt_BR/
2024-06-29 14:30:01 +02:00
46 changed files with 2011 additions and 1374 deletions

View file

@ -25,6 +25,7 @@ jobs:
assemble: assemble:
name: Assemble name: Assemble
runs-on: ubuntu-22.04 runs-on: ubuntu-22.04
if: startsWith(github.event.head_commit.message, 'build:')
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v4 uses: actions/checkout@v4
@ -40,11 +41,11 @@ jobs:
- name: Build with Gradle - name: Build with Gradle
run: ./gradlew assemble run: ./gradlew assemble
# Upload all build artifacts in separate steps. This can be shortened once https://github.com/actions/upload-artifact/pull/354 is merged. # Upload all build artifacts in separate steps. This can be shortened once https://github.com/actions/upload-artifact/pull/354 is merged.
- name: Upload artifact ananas-v0.14.2-libre-arm64-v8a.apk - name: Upload artifact ananas-v0.10.3-0.14.2-libre-arm64-v8a.apk
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
with: with:
name: phone-libre-arm64-v8a.apk name: phone-libre-arm64-v8a.apk
path: ./app/phone/build/outputs/apk/libre/release/ananas-v0.14.2-libre-arm64-v8a.apk path: ./app/phone/build/outputs/apk/libre/release/ananas-v0.10.3-0.14.2-libre-arm64-v8a.apk
# - name: Upload artifact phone-libre-armeabi-v7a-debug.apk # - name: Upload artifact phone-libre-armeabi-v7a-debug.apk
# uses: actions/upload-artifact@v4 # uses: actions/upload-artifact@v4
# with: # with:

1
.gitignore vendored
View file

@ -41,3 +41,4 @@ fastlane/report.xml
fastlane/Preview.html fastlane/Preview.html
fastlane/screenshots fastlane/screenshots
fastlane/test_output fastlane/test_output
push.sh

View file

@ -10,7 +10,8 @@ Personal fork
- Completely native interface - Completely native interface
- Supported media items: movies, series, seasons, episodes - Supported media items: movies, series, seasons, episodes
- Direct play and Transcoding - Direct play and Transcoding
- Offline playback / downloads - Offline playback / downloads
- Transcoding Downloads (Original - 720p - 480p - 360p)
- ExoPlayer - ExoPlayer
- Video codecs: H.263, H.264, H.265, VP8, VP9, AV1 - Video codecs: H.263, H.264, H.265, VP8, VP9, AV1
- Support depends on Android device - Support depends on Android device

View file

@ -0,0 +1,87 @@
{
"version": 3,
"artifactType": {
"type": "APK",
"kind": "Directory"
},
"applicationId": "com.nomadics9.ananas",
"variantName": "AnanasRelease",
"elements": [
{
"type": "ONE_OF_MANY",
"filters": [
{
"filterType": "ABI",
"value": "armeabi-v7a"
}
],
"attributes": [],
"versionCode": 16,
"versionName": "0.10.6-0.14.2",
"outputFile": "ananas-v0.10.6-0.14.2-Ananas-armeabi-v7a.apk"
},
{
"type": "ONE_OF_MANY",
"filters": [
{
"filterType": "ABI",
"value": "arm64-v8a"
}
],
"attributes": [],
"versionCode": 16,
"versionName": "0.10.6-0.14.2",
"outputFile": "ananas-v0.10.6-0.14.2-Ananas-arm64-v8a.apk"
},
{
"type": "ONE_OF_MANY",
"filters": [
{
"filterType": "ABI",
"value": "x86_64"
}
],
"attributes": [],
"versionCode": 16,
"versionName": "0.10.6-0.14.2",
"outputFile": "ananas-v0.10.6-0.14.2-Ananas-x86_64.apk"
},
{
"type": "ONE_OF_MANY",
"filters": [
{
"filterType": "ABI",
"value": "x86"
}
],
"attributes": [],
"versionCode": 16,
"versionName": "0.10.6-0.14.2",
"outputFile": "ananas-v0.10.6-0.14.2-Ananas-x86.apk"
}
],
"elementType": "File",
"baselineProfiles": [
{
"minApi": 28,
"maxApi": 30,
"baselineProfiles": [
"baselineProfiles/1/ananas-v0.10.6-0.14.2-Ananas-armeabi-v7a.dm",
"baselineProfiles/1/ananas-v0.10.6-0.14.2-Ananas-arm64-v8a.dm",
"baselineProfiles/1/ananas-v0.10.6-0.14.2-Ananas-x86_64.dm",
"baselineProfiles/1/ananas-v0.10.6-0.14.2-Ananas-x86.dm"
]
},
{
"minApi": 31,
"maxApi": 2147483647,
"baselineProfiles": [
"baselineProfiles/0/ananas-v0.10.6-0.14.2-Ananas-armeabi-v7a.dm",
"baselineProfiles/0/ananas-v0.10.6-0.14.2-Ananas-arm64-v8a.dm",
"baselineProfiles/0/ananas-v0.10.6-0.14.2-Ananas-x86_64.dm",
"baselineProfiles/0/ananas-v0.10.6-0.14.2-Ananas-x86.dm"
]
}
],
"minSdkVersionForDexing": 28
}

View file

@ -23,6 +23,10 @@ android {
versionName = Versions.appName versionName = Versions.appName
testInstrumentationRunner = "com.nomadics9.ananas.HiltTestRunner" testInstrumentationRunner = "com.nomadics9.ananas.HiltTestRunner"
buildConfigField( "String", "DEFAULT_SERVER_ADDRESS", "\" \"")
buildConfigField( "String", "REQUEST_SERVER_ADDRESS", "\" \"")
buildConfigField("String", "FORGET_PASSWORD_ADDRESS", "\" \"")
buildConfigField("String", "UPDATE_ADDRESS", "\" \"")
} }
applicationVariants.all { applicationVariants.all {
@ -57,10 +61,18 @@ android {
flavorDimensions += "variant" flavorDimensions += "variant"
productFlavors { productFlavors {
register("libre") { create("libre") {
dimension = "variant" dimension = "variant"
isDefault = true isDefault = true
} }
create("Ananas") {
dimension = "variant"
isDefault = false
buildConfigField( "String", "DEFAULT_SERVER_ADDRESS", "\"https://askar.tv\"")
buildConfigField( "String", "REQUEST_SERVER_ADDRESS", "\"https://r.askar.tv\"")
buildConfigField("String", "FORGET_PASSWORD_ADDRESS", "\"https://user.askar.tv/my/account\"")
buildConfigField("String", "UPDATE_ADDRESS", "\"https://fs.nmd.mov/p/ananas.apk\"")
}
} }
splits { splits {
@ -122,6 +134,7 @@ dependencies {
implementation(libs.material) implementation(libs.material)
implementation(libs.media3.ffmpeg.decoder) implementation(libs.media3.ffmpeg.decoder)
implementation(libs.timber) implementation(libs.timber)
implementation(libs.markwon)
coreLibraryDesugaring(libs.android.desugar.jdk) coreLibraryDesugaring(libs.android.desugar.jdk)

View file

@ -16,9 +16,9 @@
} }
], ],
"attributes": [], "attributes": [],
"versionCode": 9, "versionCode": 11,
"versionName": "0.14.2", "versionName": "0.10.1-0.14.2",
"outputFile": "ananas-v0.14.2-libre-armeabi-v7a.apk" "outputFile": "ananas-v0.10.1-0.14.2-libre-armeabi-v7a.apk"
}, },
{ {
"type": "ONE_OF_MANY", "type": "ONE_OF_MANY",
@ -29,22 +29,9 @@
} }
], ],
"attributes": [], "attributes": [],
"versionCode": 9, "versionCode": 11,
"versionName": "0.14.2", "versionName": "0.10.1-0.14.2",
"outputFile": "ananas-v0.14.2-libre-x86_64.apk" "outputFile": "ananas-v0.10.1-0.14.2-libre-x86_64.apk"
},
{
"type": "ONE_OF_MANY",
"filters": [
{
"filterType": "ABI",
"value": "x86"
}
],
"attributes": [],
"versionCode": 9,
"versionName": "0.14.2",
"outputFile": "ananas-v0.14.2-libre-x86.apk"
}, },
{ {
"type": "ONE_OF_MANY", "type": "ONE_OF_MANY",
@ -55,9 +42,22 @@
} }
], ],
"attributes": [], "attributes": [],
"versionCode": 9, "versionCode": 11,
"versionName": "0.14.2", "versionName": "0.10.1-0.14.2",
"outputFile": "ananas-v0.14.2-libre-arm64-v8a.apk" "outputFile": "ananas-v0.10.1-0.14.2-libre-arm64-v8a.apk"
},
{
"type": "ONE_OF_MANY",
"filters": [
{
"filterType": "ABI",
"value": "x86"
}
],
"attributes": [],
"versionCode": 11,
"versionName": "0.10.1-0.14.2",
"outputFile": "ananas-v0.10.1-0.14.2-libre-x86.apk"
} }
], ],
"elementType": "File", "elementType": "File",
@ -66,20 +66,20 @@
"minApi": 28, "minApi": 28,
"maxApi": 30, "maxApi": 30,
"baselineProfiles": [ "baselineProfiles": [
"baselineProfiles/1/ananas-v0.14.2-libre-armeabi-v7a.dm", "baselineProfiles/1/ananas-v0.10.1-0.14.2-libre-armeabi-v7a.dm",
"baselineProfiles/1/ananas-v0.14.2-libre-x86_64.dm", "baselineProfiles/1/ananas-v0.10.1-0.14.2-libre-x86_64.dm",
"baselineProfiles/1/ananas-v0.14.2-libre-x86.dm", "baselineProfiles/1/ananas-v0.10.1-0.14.2-libre-arm64-v8a.dm",
"baselineProfiles/1/ananas-v0.14.2-libre-arm64-v8a.dm" "baselineProfiles/1/ananas-v0.10.1-0.14.2-libre-x86.dm"
] ]
}, },
{ {
"minApi": 31, "minApi": 31,
"maxApi": 2147483647, "maxApi": 2147483647,
"baselineProfiles": [ "baselineProfiles": [
"baselineProfiles/0/ananas-v0.14.2-libre-armeabi-v7a.dm", "baselineProfiles/0/ananas-v0.10.1-0.14.2-libre-armeabi-v7a.dm",
"baselineProfiles/0/ananas-v0.14.2-libre-x86_64.dm", "baselineProfiles/0/ananas-v0.10.1-0.14.2-libre-x86_64.dm",
"baselineProfiles/0/ananas-v0.14.2-libre-x86.dm", "baselineProfiles/0/ananas-v0.10.1-0.14.2-libre-arm64-v8a.dm",
"baselineProfiles/0/ananas-v0.14.2-libre-arm64-v8a.dm" "baselineProfiles/0/ananas-v0.10.1-0.14.2-libre-x86.dm"
] ]
} }
], ],

View file

@ -24,19 +24,16 @@ import android.widget.ImageView
import android.widget.Space import android.widget.Space
import android.widget.TextView import android.widget.TextView
import androidx.activity.viewModels import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isVisible import androidx.core.view.isVisible
import androidx.lifecycle.Lifecycle import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle import androidx.lifecycle.repeatOnLifecycle
import androidx.media3.common.C import androidx.media3.common.C
import androidx.media3.common.Player
import androidx.media3.ui.DefaultTimeBar import androidx.media3.ui.DefaultTimeBar
import androidx.media3.ui.PlayerControlView import androidx.media3.ui.PlayerControlView
import androidx.media3.ui.PlayerView import androidx.media3.ui.PlayerView
import androidx.navigation.navArgs import androidx.navigation.navArgs
import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.dialog.MaterialAlertDialogBuilder
import dagger.hilt.android.AndroidEntryPoint
import com.nomadics9.ananas.databinding.ActivityPlayerBinding import com.nomadics9.ananas.databinding.ActivityPlayerBinding
import com.nomadics9.ananas.dialogs.SpeedSelectionDialogFragment import com.nomadics9.ananas.dialogs.SpeedSelectionDialogFragment
import com.nomadics9.ananas.dialogs.TrackSelectionDialogFragment import com.nomadics9.ananas.dialogs.TrackSelectionDialogFragment
@ -45,16 +42,17 @@ import com.nomadics9.ananas.utils.PlayerGestureHelper
import com.nomadics9.ananas.utils.PreviewScrubListener import com.nomadics9.ananas.utils.PreviewScrubListener
import com.nomadics9.ananas.viewmodels.PlayerActivityViewModel import com.nomadics9.ananas.viewmodels.PlayerActivityViewModel
import com.nomadics9.ananas.viewmodels.PlayerEvents import com.nomadics9.ananas.viewmodels.PlayerEvents
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import timber.log.Timber import timber.log.Timber
import javax.inject.Inject import javax.inject.Inject
import com.nomadics9.ananas.core.R as CoreR import com.nomadics9.ananas.core.R as CoreR
import com.nomadics9.ananas.models.VideoQuality
var isControlsLocked: Boolean = false var isControlsLocked: Boolean = false
@AndroidEntryPoint @AndroidEntryPoint
class PlayerActivity : BasePlayerActivity() { class PlayerActivity : BasePlayerActivity() {
@Inject @Inject
lateinit var appPreferences: AppPreferences lateinit var appPreferences: AppPreferences
@ -89,12 +87,10 @@ class PlayerActivity : BasePlayerActivity() {
binding = ActivityPlayerBinding.inflate(layoutInflater) binding = ActivityPlayerBinding.inflate(layoutInflater)
setContentView(binding.root) setContentView(binding.root)
val changeQualityButton: ImageButton = findViewById(R.id.btnChangeQuality) val changeQualityButton: ImageButton = findViewById(R.id.btnChangeQuality)
changeQualityButton.setOnClickListener { changeQualityButton.setOnClickListener {
showQualitySelectionDialog() showQualitySelectionDialog()
} }
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
binding.playerView.player = viewModel.player binding.playerView.player = viewModel.player
@ -115,12 +111,13 @@ class PlayerActivity : BasePlayerActivity() {
configureInsets(lockedControls) configureInsets(lockedControls)
if (appPreferences.playerGestures) { if (appPreferences.playerGestures) {
playerGestureHelper = PlayerGestureHelper( playerGestureHelper =
appPreferences, PlayerGestureHelper(
this, appPreferences,
binding.playerView, this,
getSystemService(AUDIO_SERVICE) as AudioManager, binding.playerView,
) getSystemService(AUDIO_SERVICE) as AudioManager,
)
} }
binding.playerView.findViewById<View>(R.id.back_button).setOnClickListener { binding.playerView.findViewById<View>(R.id.back_button).setOnClickListener {
@ -155,7 +152,12 @@ class PlayerActivity : BasePlayerActivity() {
skipButton.text = skipButton.text =
getString(CoreR.string.skip_intro_button) getString(CoreR.string.skip_intro_button)
skipButton.isVisible = skipButton.isVisible =
!isInPictureInPictureMode && !buttonPressed && (showSkip == true || (binding.playerView.isControllerFullyVisible && currentSegment?.skip == true)) !isInPictureInPictureMode &&
!buttonPressed &&
(
showSkip == true ||
(binding.playerView.isControllerFullyVisible && currentSegment?.skip == true)
)
watchCreditsButton.isVisible = false watchCreditsButton.isVisible = false
} }
@ -167,7 +169,10 @@ class PlayerActivity : BasePlayerActivity() {
getString(CoreR.string.skip_credit_button_last) getString(CoreR.string.skip_credit_button_last)
} }
skipButton.isVisible = skipButton.isVisible =
!isInPictureInPictureMode && !buttonPressed && currentSegment?.skip == true && !binding.playerView.isControllerFullyVisible !isInPictureInPictureMode &&
!buttonPressed &&
currentSegment?.skip == true &&
!binding.playerView.isControllerFullyVisible
watchCreditsButton.isVisible = skipButton.isVisible watchCreditsButton.isVisible = skipButton.isVisible
} }
@ -181,12 +186,15 @@ class PlayerActivity : BasePlayerActivity() {
when (currentSegment?.type) { when (currentSegment?.type) {
"intro" -> { "intro" -> {
skipButton.isVisible = skipButton.isVisible =
!buttonPressed && (showSkip == true || (visibility == View.VISIBLE && currentSegment?.skip == true)) !buttonPressed &&
(showSkip == true || (visibility == View.VISIBLE && currentSegment?.skip == true))
} }
"credit" -> { "credit" -> {
skipButton.isVisible = skipButton.isVisible =
!buttonPressed && currentSegment?.skip == true && visibility == View.GONE !buttonPressed &&
currentSegment?.skip == true &&
visibility == View.GONE
watchCreditsButton.isVisible = skipButton.isVisible watchCreditsButton.isVisible = skipButton.isVisible
} }
} }
@ -268,7 +276,8 @@ class PlayerActivity : BasePlayerActivity() {
if (appPreferences.playerPipGesture) { if (appPreferences.playerPipGesture) {
try { try {
setPictureInPictureParams(pipParams(event.isPlaying)) setPictureInPictureParams(pipParams(event.isPlaying))
} catch (_: IllegalArgumentException) { } } catch (_: IllegalArgumentException) {
}
} }
} }
} }
@ -381,34 +390,38 @@ class PlayerActivity : BasePlayerActivity() {
private fun pipParams(enableAutoEnter: Boolean = viewModel.player.isPlaying): PictureInPictureParams { private fun pipParams(enableAutoEnter: Boolean = viewModel.player.isPlaying): PictureInPictureParams {
val displayAspectRatio = Rational(binding.playerView.width, binding.playerView.height) val displayAspectRatio = Rational(binding.playerView.width, binding.playerView.height)
val aspectRatio = binding.playerView.player?.videoSize?.let { val aspectRatio =
Rational( binding.playerView.player?.videoSize?.let {
it.width.coerceAtMost((it.height * 2.39f).toInt()), Rational(
it.height.coerceAtMost((it.width * 2.39f).toInt()), it.width.coerceAtMost((it.height * 2.39f).toInt()),
) it.height.coerceAtMost((it.width * 2.39f).toInt()),
} )
}
val sourceRectHint = if (displayAspectRatio < aspectRatio!!) { val sourceRectHint =
val space = ((binding.playerView.height - (binding.playerView.width.toFloat() / aspectRatio.toFloat())) / 2).toInt() if (displayAspectRatio < aspectRatio!!) {
Rect( val space = ((binding.playerView.height - (binding.playerView.width.toFloat() / aspectRatio.toFloat())) / 2).toInt()
0, Rect(
space, 0,
binding.playerView.width, space,
(binding.playerView.width.toFloat() / aspectRatio.toFloat()).toInt() + space, binding.playerView.width,
) (binding.playerView.width.toFloat() / aspectRatio.toFloat()).toInt() + space,
} else { )
val space = ((binding.playerView.width - (binding.playerView.height.toFloat() * aspectRatio.toFloat())) / 2).toInt() } else {
Rect( val space = ((binding.playerView.width - (binding.playerView.height.toFloat() * aspectRatio.toFloat())) / 2).toInt()
space, Rect(
0, space,
(binding.playerView.height.toFloat() * aspectRatio.toFloat()).toInt() + space, 0,
binding.playerView.height, (binding.playerView.height.toFloat() * aspectRatio.toFloat()).toInt() + space,
) binding.playerView.height,
} )
}
val builder = PictureInPictureParams.Builder() val builder =
.setAspectRatio(aspectRatio) PictureInPictureParams
.setSourceRectHint(sourceRectHint) .Builder()
.setAspectRatio(aspectRatio)
.setSourceRectHint(sourceRectHint)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
builder.setAutoEnterEnabled(enableAutoEnter) builder.setAutoEnterEnabled(enableAutoEnter)
@ -427,28 +440,31 @@ class PlayerActivity : BasePlayerActivity() {
} catch (_: IllegalArgumentException) { } } catch (_: IllegalArgumentException) { }
} }
private var selectedIndex = 1 // Default to "Original" (index 1)
private fun showQualitySelectionDialog() { private fun showQualitySelectionDialog() {
val height = viewModel.getOriginalHeight() val originalResolution = viewModel.getOriginalResolution() ?: 0
val qualityEntries = resources.getStringArray(CoreR.array.quality_entries).toList()
val qualityValues = resources.getStringArray(CoreR.array.quality_values).toList()
val qualities = when (height) { val qualities = qualityEntries.toMutableList()
0 -> arrayOf("Auto", "Original - Max", "720p - 2Mbps", "480p - 1Mbps", "360p - 800kbps") val closestQuality = VideoQuality.entries
in 1001..1999 -> arrayOf("Auto", "Original (1080p) - Max", "720p - 2Mbps", "480p - 1Mbps", "360p - 800kbps") .filter { it != VideoQuality.Auto && it != VideoQuality.Original }
in 2000..3000 -> arrayOf("Auto", "Original (4K) - Max", "720p - 2Mbps", "480p - 1Mbps", "360p - 800kbps") .minByOrNull { kotlin.math.abs(it.height*it.width - originalResolution) }
else -> arrayOf("Auto", "Original - Max", "720p - 2Mbps", "480p - 1Mbps", "360p - 800kbps")
if (closestQuality != null) {
qualities[1] = "${qualities[1]} (${closestQuality})"
} }
MaterialAlertDialogBuilder(this) MaterialAlertDialogBuilder(this)
.setTitle("Select Video Quality") .setTitle(CoreR.string.select_quality)
.setItems(qualities) { _, which -> .setSingleChoiceItems(qualities.toTypedArray(), selectedIndex) { dialog, which ->
val selectedQuality = qualities[which] selectedIndex = which
viewModel.changeVideoQuality(selectedQuality) val selectedQualityValue = qualityValues[which]
viewModel.changeVideoQuality(selectedQualityValue)
dialog.dismiss()
} }
.show() .show()
} }
override fun onPictureInPictureModeChanged( override fun onPictureInPictureModeChanged(
isInPictureInPictureMode: Boolean, isInPictureInPictureMode: Boolean,
newConfig: Configuration, newConfig: Configuration,
@ -463,25 +479,29 @@ class PlayerActivity : BasePlayerActivity() {
playerGestureHelper?.updateZoomMode(false) playerGestureHelper?.updateZoomMode(false)
// Brightness mode Auto // Brightness mode Auto
window.attributes = window.attributes.apply { window.attributes =
screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE window.attributes.apply {
} screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE
}
} }
false -> { false -> {
binding.playerView.useController = true binding.playerView.useController = true
playerGestureHelper?.updateZoomMode(wasZoom) playerGestureHelper?.updateZoomMode(wasZoom)
// Override auto brightness // Override auto brightness
window.attributes = window.attributes.apply { window.attributes =
screenBrightness = if (appPreferences.playerBrightnessRemember) { window.attributes.apply {
appPreferences.playerBrightness screenBrightness =
} else { if (appPreferences.playerBrightnessRemember) {
Settings.System.getInt( appPreferences.playerBrightness
contentResolver, } else {
Settings.System.SCREEN_BRIGHTNESS, Settings.System
).toFloat() / 255 .getInt(
contentResolver,
Settings.System.SCREEN_BRIGHTNESS,
).toFloat() / 255
}
} }
}
} }
} }
} }

View file

@ -14,6 +14,7 @@ import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.findNavController
import com.nomadics9.ananas.BuildConfig
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import com.nomadics9.ananas.adapters.DiscoveredServerListAdapter import com.nomadics9.ananas.adapters.DiscoveredServerListAdapter
import com.nomadics9.ananas.databinding.FragmentAddServerBinding import com.nomadics9.ananas.databinding.FragmentAddServerBinding
@ -89,7 +90,12 @@ class AddServerFragment : Fragment() {
} }
} }
} }
connectToServer(DEFAULT_SERVER_ADDRESS) if (BuildConfig.FLAVOR == "Ananas") {
fun connectToServerDirectly(serverAddress: String = BuildConfig.DEFAULT_SERVER_ADDRESS) {
viewModel.checkServer(serverAddress.removeSuffix("/"))
}
connectToServerDirectly()
}
return binding.root return binding.root
} }
@ -129,18 +135,21 @@ class AddServerFragment : Fragment() {
} }
} }
private fun connectToServer() {
val serverAddress = (binding.editTextServerAddress as AppCompatEditText).text.toString()
viewModel.checkServer(serverAddress.removeSuffix("/"))
}
// private fun connectToServer() { // private fun connectToServer() {
// val serverAddress = (binding.editTextServerAddress as AppCompatEditText).text.toString() // val serverAddress = (binding.editTextServerAddress as AppCompatEditText).text.toString()
// viewModel.checkServer(serverAddress.removeSuffix("/")) // if (serverAddress.isNotBlank()) {
// viewModel.checkServer(serverAddress.removeSuffix("/"))
// } else {
// viewModel.checkServer(BuildConfig.DEFAULT_SERVER_ADDRESS.removeSuffix("/"))
// }
// } // }
companion object {
private const val DEFAULT_SERVER_ADDRESS = "https://askar.tv"
}
private fun connectToServer(serverAddress: String = DEFAULT_SERVER_ADDRESS) {
viewModel.checkServer(serverAddress.removeSuffix("/"))
}
private fun navigateToLoginFragment() { private fun navigateToLoginFragment() {
findNavController().navigate(AddServerFragmentDirections.actionAddServerFragmentToLoginFragment()) findNavController().navigate(AddServerFragmentDirections.actionAddServerFragmentToLoginFragment())
} }

View file

@ -172,59 +172,63 @@ class EpisodeBottomSheetFragment : BottomSheetDialogFragment() {
}else if (!appPreferences.downloadQualityDefault) { }else if (!appPreferences.downloadQualityDefault) {
createPickQualityDialog() createPickQualityDialog()
} else { } else {
binding.itemActions.downloadButton.setIconResource(AndroidR.color.transparent) startDownload()
binding.itemActions.progressDownload.isIndeterminate = true }
binding.itemActions.progressDownload.isVisible = true }
if (requireContext().getExternalFilesDirs(null).filterNotNull().size > 1) {
val storageDialog = getStorageSelectionDialog( private fun startDownload(){
requireContext(), binding.itemActions.downloadButton.setIconResource(AndroidR.color.transparent)
onItemSelected = { storageIndex -> binding.itemActions.progressDownload.isIndeterminate = true
if (viewModel.item.sources.size > 1) { binding.itemActions.progressDownload.isVisible = true
val dialog = getVideoVersionDialog( if (requireContext().getExternalFilesDirs(null).filterNotNull().size > 1) {
requireContext(), val storageDialog = getStorageSelectionDialog(
viewModel.item, requireContext(),
onItemSelected = { sourceIndex -> onItemSelected = { storageIndex ->
createDownloadPreparingDialog() if (viewModel.item.sources.size > 1) {
viewModel.download(sourceIndex, storageIndex) val dialog = getVideoVersionDialog(
}, requireContext(),
onCancel = { viewModel.item,
binding.itemActions.progressDownload.isVisible = false onItemSelected = { sourceIndex ->
binding.itemActions.downloadButton.setIconResource(CoreR.drawable.ic_download) createDownloadPreparingDialog()
}, viewModel.download(sourceIndex, storageIndex)
) },
dialog.show() onCancel = {
return@getStorageSelectionDialog binding.itemActions.progressDownload.isVisible = false
} binding.itemActions.downloadButton.setIconResource(CoreR.drawable.ic_download)
createDownloadPreparingDialog() },
viewModel.download(storageIndex = storageIndex) )
}, dialog.show()
onCancel = { return@getStorageSelectionDialog
binding.itemActions.progressDownload.isVisible = false }
binding.itemActions.downloadButton.setIconResource(CoreR.drawable.ic_download) createDownloadPreparingDialog()
}, viewModel.download(storageIndex = storageIndex)
) },
storageDialog.show() onCancel = {
return binding.itemActions.progressDownload.isVisible = false
} binding.itemActions.downloadButton.setIconResource(CoreR.drawable.ic_download)
if (viewModel.item.sources.size > 1) { },
val dialog = getVideoVersionDialog( )
requireContext(), storageDialog.show()
viewModel.item, return
onItemSelected = { sourceIndex ->
createDownloadPreparingDialog()
viewModel.download(sourceIndex)
},
onCancel = {
binding.itemActions.progressDownload.isVisible = false
binding.itemActions.downloadButton.setIconResource(CoreR.drawable.ic_download)
},
)
dialog.show()
return
}
createDownloadPreparingDialog()
viewModel.download()
} }
if (viewModel.item.sources.size > 1) {
val dialog = getVideoVersionDialog(
requireContext(),
viewModel.item,
onItemSelected = { sourceIndex ->
createDownloadPreparingDialog()
viewModel.download(sourceIndex)
},
onCancel = {
binding.itemActions.progressDownload.isVisible = false
binding.itemActions.downloadButton.setIconResource(CoreR.drawable.ic_download)
},
)
dialog.show()
return
}
createDownloadPreparingDialog()
viewModel.download()
} }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
@ -409,8 +413,8 @@ class EpisodeBottomSheetFragment : BottomSheetDialogFragment() {
} }
private fun createPickQualityDialog() { private fun createPickQualityDialog() {
val qualityEntries = resources.getStringArray(com.nomadics9.ananas.core.R.array.quality_entries) val qualityEntries = resources.getStringArray(CoreR.array.download_quality_entries)
val qualityValues = resources.getStringArray(com.nomadics9.ananas.core.R.array.quality_values) val qualityValues = resources.getStringArray(CoreR.array.download_quality_values)
val quality = appPreferences.downloadQuality val quality = appPreferences.downloadQuality
val currentQualityIndex = qualityValues.indexOf(quality) val currentQualityIndex = qualityValues.indexOf(quality)
var selectedQuality = quality var selectedQuality = quality
@ -424,7 +428,7 @@ class EpisodeBottomSheetFragment : BottomSheetDialogFragment() {
builder.setPositiveButton("Download") { dialog, _ -> builder.setPositiveButton("Download") { dialog, _ ->
appPreferences.downloadQuality = selectedQuality appPreferences.downloadQuality = selectedQuality
dialog.dismiss() dialog.dismiss()
handleDownload() startDownload()
} }
builder.setNegativeButton("Cancel") { dialog, _ -> builder.setNegativeButton("Cancel") { dialog, _ ->
dialog.dismiss() dialog.dismiss()

View file

@ -1,5 +1,7 @@
package com.nomadics9.ananas.fragments package com.nomadics9.ananas.fragments
import android.content.Intent
import android.net.Uri
import android.os.Bundle import android.os.Bundle
import android.text.Html.fromHtml import android.text.Html.fromHtml
import android.view.LayoutInflater import android.view.LayoutInflater
@ -17,11 +19,13 @@ import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs import androidx.navigation.fragment.navArgs
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import com.nomadics9.ananas.AppPreferences import com.nomadics9.ananas.AppPreferences
import com.nomadics9.ananas.BuildConfig
import com.nomadics9.ananas.adapters.UserLoginListAdapter import com.nomadics9.ananas.adapters.UserLoginListAdapter
import com.nomadics9.ananas.database.ServerDatabaseDao import com.nomadics9.ananas.database.ServerDatabaseDao
import com.nomadics9.ananas.databinding.FragmentLoginBinding import com.nomadics9.ananas.databinding.FragmentLoginBinding
import com.nomadics9.ananas.viewmodels.LoginEvent import com.nomadics9.ananas.viewmodels.LoginEvent
import com.nomadics9.ananas.viewmodels.LoginViewModel import com.nomadics9.ananas.viewmodels.LoginViewModel
import io.noties.markwon.Markwon
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import timber.log.Timber import timber.log.Timber
import javax.inject.Inject import javax.inject.Inject
@ -78,6 +82,17 @@ class LoginFragment : Fragment() {
(binding.editTextPassword as AppCompatEditText).requestFocus() (binding.editTextPassword as AppCompatEditText).requestFocus()
} }
if (BuildConfig.FLAVOR == "Ananas") {
binding.buttonForgetPassword.setOnClickListener {
val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(BuildConfig.FORGET_PASSWORD_ADDRESS))
startActivity(browserIntent)
}
binding.buttonForgetPassword.isVisible = true
} else {
binding.buttonForgetPassword.isVisible = false
}
viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.uiState.collect { uiState -> viewModel.uiState.collect { uiState ->
@ -143,7 +158,21 @@ class LoginFragment : Fragment() {
binding.editTextPasswordLayout.isEnabled = true binding.editTextPasswordLayout.isEnabled = true
uiState.disclaimer?.let { disclaimer -> uiState.disclaimer?.let { disclaimer ->
binding.loginDisclaimer.text = fromHtml(disclaimer, 0) if (BuildConfig.FLAVOR == "Ananas") {
val lines = disclaimer.lines()
val lineToRemoveIndex = 3
val filteredLines = lines.toMutableList().apply {
if (size > lineToRemoveIndex) {
removeAt(lineToRemoveIndex)
}
}
val filteredDisclaimer = filteredLines.joinToString("\n")
val markwon = Markwon.create(requireContext())
markwon.setMarkdown(binding.loginDisclaimer, filteredDisclaimer)
} else {
val markwon = Markwon.create(requireContext())
markwon.setMarkdown(binding.loginDisclaimer, disclaimer)
}
} }
} }

View file

@ -209,61 +209,65 @@ class MovieFragment : Fragment() {
} else if (!appPreferences.downloadQualityDefault) { } else if (!appPreferences.downloadQualityDefault) {
createPickQualityDialog() createPickQualityDialog()
} else { } else {
binding.itemActions.downloadButton.setIconResource(android.R.color.transparent) startDownload()
binding.itemActions.progressDownload.isIndeterminate = true
binding.itemActions.progressDownload.isVisible = true
if (requireContext().getExternalFilesDirs(null).filterNotNull().size > 1) {
val storageDialog = getStorageSelectionDialog(
requireContext(),
onItemSelected = { storageIndex ->
if (viewModel.item.sources.size > 1) {
val dialog = getVideoVersionDialog(
requireContext(),
viewModel.item,
onItemSelected = { sourceIndex ->
createDownloadPreparingDialog()
viewModel.download(sourceIndex, storageIndex)
},
onCancel = {
binding.itemActions.progressDownload.isVisible = false
binding.itemActions.downloadButton.setIconResource(CoreR.drawable.ic_download)
},
)
dialog.show()
return@getStorageSelectionDialog
}
createDownloadPreparingDialog()
viewModel.download(storageIndex = storageIndex)
},
onCancel = {
binding.itemActions.progressDownload.isVisible = false
binding.itemActions.downloadButton.setIconResource(CoreR.drawable.ic_download)
},
)
storageDialog.show()
return
}
if (viewModel.item.sources.size > 1) {
val dialog = getVideoVersionDialog(
requireContext(),
viewModel.item,
onItemSelected = { sourceIndex ->
createDownloadPreparingDialog()
viewModel.download(sourceIndex)
},
onCancel = {
binding.itemActions.progressDownload.isVisible = false
binding.itemActions.downloadButton.setIconResource(CoreR.drawable.ic_download)
},
)
dialog.show()
return
}
createDownloadPreparingDialog()
viewModel.download()
} }
} }
private fun startDownload() {
binding.itemActions.downloadButton.setIconResource(android.R.color.transparent)
binding.itemActions.progressDownload.isIndeterminate = true
binding.itemActions.progressDownload.isVisible = true
if (requireContext().getExternalFilesDirs(null).filterNotNull().size > 1) {
val storageDialog = getStorageSelectionDialog(
requireContext(),
onItemSelected = { storageIndex ->
if (viewModel.item.sources.size > 1) {
val dialog = getVideoVersionDialog(
requireContext(),
viewModel.item,
onItemSelected = { sourceIndex ->
createDownloadPreparingDialog()
viewModel.download(sourceIndex, storageIndex)
},
onCancel = {
binding.itemActions.progressDownload.isVisible = false
binding.itemActions.downloadButton.setIconResource(CoreR.drawable.ic_download)
},
)
dialog.show()
return@getStorageSelectionDialog
}
createDownloadPreparingDialog()
viewModel.download(storageIndex = storageIndex)
},
onCancel = {
binding.itemActions.progressDownload.isVisible = false
binding.itemActions.downloadButton.setIconResource(CoreR.drawable.ic_download)
},
)
storageDialog.show()
return
}
if (viewModel.item.sources.size > 1) {
val dialog = getVideoVersionDialog(
requireContext(),
viewModel.item,
onItemSelected = { sourceIndex ->
createDownloadPreparingDialog()
viewModel.download(sourceIndex)
},
onCancel = {
binding.itemActions.progressDownload.isVisible = false
binding.itemActions.downloadButton.setIconResource(CoreR.drawable.ic_download)
},
)
dialog.show()
return
}
createDownloadPreparingDialog()
viewModel.download()
}
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()
@ -502,8 +506,8 @@ class MovieFragment : Fragment() {
} }
private fun createPickQualityDialog() { private fun createPickQualityDialog() {
val qualityEntries = resources.getStringArray(com.nomadics9.ananas.core.R.array.quality_entries) val qualityEntries = resources.getStringArray(CoreR.array.download_quality_entries)
val qualityValues = resources.getStringArray(com.nomadics9.ananas.core.R.array.quality_values) val qualityValues = resources.getStringArray(CoreR.array.download_quality_values)
val quality = appPreferences.downloadQuality val quality = appPreferences.downloadQuality
val currentQualityIndex = qualityValues.indexOf(quality) val currentQualityIndex = qualityValues.indexOf(quality)
var selectedQuality = quality var selectedQuality = quality
@ -516,8 +520,8 @@ class MovieFragment : Fragment() {
} }
builder.setPositiveButton("Download") { dialog, _ -> builder.setPositiveButton("Download") { dialog, _ ->
appPreferences.downloadQuality = selectedQuality appPreferences.downloadQuality = selectedQuality
startDownload()
dialog.dismiss() dialog.dismiss()
handleDownload()
} }
builder.setNegativeButton("Cancel") { dialog, _ -> builder.setNegativeButton("Cancel") { dialog, _ ->
dialog.dismiss() dialog.dismiss()

View file

@ -11,6 +11,7 @@ import android.webkit.WebViewClient
import android.widget.ProgressBar import android.widget.ProgressBar
import androidx.activity.OnBackPressedCallback import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import com.nomadics9.ananas.BuildConfig
import com.nomadics9.ananas.R import com.nomadics9.ananas.R
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
@ -53,7 +54,7 @@ class RequestsWebViewFragment : Fragment() {
} }
// Load your URL here // Load your URL here
webView.loadUrl("https://r.askar.tv") webView.loadUrl(BuildConfig.REQUEST_SERVER_ADDRESS)
requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) { requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() { override fun handleOnBackPressed() {

View file

@ -226,8 +226,8 @@ class SeasonFragment : Fragment() {
} }
private fun createPickQualityDialog(onQualitySelected: () -> Unit) { private fun createPickQualityDialog(onQualitySelected: () -> Unit) {
val qualityEntries = resources.getStringArray(com.nomadics9.ananas.core.R.array.quality_entries) val qualityEntries = resources.getStringArray(com.nomadics9.ananas.core.R.array.download_quality_entries)
val qualityValues = resources.getStringArray(com.nomadics9.ananas.core.R.array.quality_values) val qualityValues = resources.getStringArray(com.nomadics9.ananas.core.R.array.download_quality_values)
val quality = appPreferences.downloadQuality val quality = appPreferences.downloadQuality
val currentQualityIndex = qualityValues.indexOf(quality) val currentQualityIndex = qualityValues.indexOf(quality)
@ -240,8 +240,8 @@ class SeasonFragment : Fragment() {
} }
builder.setPositiveButton("Download") { dialog, _ -> builder.setPositiveButton("Download") { dialog, _ ->
appPreferences.downloadQuality = selectedQuality appPreferences.downloadQuality = selectedQuality
dialog.dismiss()
onQualitySelected() onQualitySelected()
dialog.dismiss()
} }
builder.setNegativeButton("Cancel") { dialog, _ -> builder.setNegativeButton("Cancel") { dialog, _ ->
dialog.dismiss() dialog.dismiss()

View file

@ -3,12 +3,23 @@ package com.nomadics9.ananas.fragments
import android.content.Intent import android.content.Intent
import android.net.Uri import android.net.Uri
import android.os.Bundle import android.os.Bundle
import androidx.core.content.res.ResourcesCompat
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.findNavController
import androidx.preference.Preference import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceFragmentCompat
import dagger.hilt.android.AndroidEntryPoint
import com.nomadics9.ananas.AppPreferences import com.nomadics9.ananas.AppPreferences
import com.nomadics9.ananas.BuildConfig
import com.nomadics9.ananas.utils.restart import com.nomadics9.ananas.utils.restart
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.net.HttpURLConnection
import java.net.URL
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject import javax.inject.Inject
import com.nomadics9.ananas.core.R as CoreR import com.nomadics9.ananas.core.R as CoreR
@ -17,6 +28,10 @@ class SettingsFragment : PreferenceFragmentCompat() {
@Inject @Inject
lateinit var appPreferences: AppPreferences lateinit var appPreferences: AppPreferences
private val updateUrl = BuildConfig.UPDATE_ADDRESS
private var isUpdateAvailable: Boolean = false
private var newLastModifiedDate: Date? = null
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(CoreR.xml.fragment_settings, rootKey) setPreferencesFromResource(CoreR.xml.fragment_settings, rootKey)
@ -27,13 +42,21 @@ class SettingsFragment : PreferenceFragmentCompat() {
findPreference<Preference>("switchUser")?.setOnPreferenceClickListener { findPreference<Preference>("switchUser")?.setOnPreferenceClickListener {
val serverId = appPreferences.currentServer!! val serverId = appPreferences.currentServer!!
findNavController().navigate(TwoPaneSettingsFragmentDirections.actionNavigationSettingsToUsersFragment(serverId)) findNavController().navigate(
TwoPaneSettingsFragmentDirections.actionNavigationSettingsToUsersFragment(
serverId
)
)
true true
} }
findPreference<Preference>("switchAddress")?.setOnPreferenceClickListener { findPreference<Preference>("switchAddress")?.setOnPreferenceClickListener {
val serverId = appPreferences.currentServer!! val serverId = appPreferences.currentServer!!
findNavController().navigate(TwoPaneSettingsFragmentDirections.actionNavigationSettingsToServerAddressesFragment(serverId)) findNavController().navigate(
TwoPaneSettingsFragmentDirections.actionNavigationSettingsToServerAddressesFragment(
serverId
)
)
true true
} }
@ -51,14 +74,102 @@ class SettingsFragment : PreferenceFragmentCompat() {
true true
} }
findPreference<Preference>("appInfo")?.setOnPreferenceClickListener { findPreference<Preference>("appInfo")?.setOnPreferenceClickListener {
findNavController().navigate(TwoPaneSettingsFragmentDirections.actionSettingsFragmentToAboutLibraries()) if (isUpdateAvailable && newLastModifiedDate != null) {
true val intent = Intent(Intent.ACTION_VIEW, Uri.parse(updateUrl))
startActivity(intent)
storeDate(newLastModifiedDate!!)
true
} else {
findNavController().navigate(TwoPaneSettingsFragmentDirections.actionSettingsFragmentToAboutLibraries())
false
}
} }
findPreference<Preference>("requests")?.setOnPreferenceClickListener { findPreference<Preference>("requests")?.setOnPreferenceClickListener {
findNavController().navigate(TwoPaneSettingsFragmentDirections.actionNavigationSettingsToRequestsWebFragment()) findNavController().navigate(TwoPaneSettingsFragmentDirections.actionNavigationSettingsToRequestsWebFragment())
true true
} }
// Check for updates when the settings screen is opened
checkForUpdates()
}
private fun checkForUpdates() {
lifecycleScope.launch {
val lastModifiedDate = fetchLastModifiedDate(updateUrl)
if (lastModifiedDate != null) {
Timber.d("Fetched Last-Modified date: $lastModifiedDate")
val storedDate = getStoredDate()
Timber.d("Stored date: $storedDate")
if (storedDate == Date(0L) || lastModifiedDate.after(storedDate)) {
Timber.d("Update available")
isUpdateAvailable = true
newLastModifiedDate = lastModifiedDate
showUpdateAvailable()
} else {
Timber.d("No update available")
isUpdateAvailable = false
}
} else {
Timber.d("Failed to fetch Last-Modified date")
isUpdateAvailable = false
}
}
}
private suspend fun fetchLastModifiedDate(urlString: String): Date? {
return withContext(Dispatchers.IO) {
var urlConnection: HttpURLConnection? = null
try {
val url = URL(urlString)
urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = "HEAD"
val lastModified = urlConnection.getHeaderField("Last-Modified")
if (lastModified != null) {
val dateFormat = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US)
dateFormat.parse(lastModified)
} else {
null
}
} catch (e: Exception) {
Timber.e(e, "Error fetching Last-Modified date")
null
} finally {
urlConnection?.disconnect()
}
}
}
private fun getStoredDate(): Date {
val sharedPreferences = preferenceManager.sharedPreferences
val storedDateString = sharedPreferences?.getString("stored_date", null)
Timber.d("Retrieved stored date string: $storedDateString")
return if (storedDateString != null) {
try {
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).parse(storedDateString) ?: Date(0)
} catch (e: Exception) {
Timber.e(e, "Error parsing stored date string")
Date(0)
}
} else {
Date(0)
}
}
private fun storeDate(date: Date) {
val dateString = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).format(date)
preferenceManager.sharedPreferences?.edit()?.putString("stored_date", dateString)?.apply()
Timber.d("Stored new date: $dateString")
}
private fun showUpdateAvailable() {
val appInfoPreference = findPreference<Preference>("appInfo")
appInfoPreference?.let {
it.summary = "Update available!"
it.icon = ResourcesCompat.getDrawable(resources, CoreR.drawable.ic_download, null) // Ensure this drawable exists
Timber.d("Update available UI shown")
}
} }
} }

View file

@ -73,6 +73,7 @@
android:layout_height="0dp" android:layout_height="0dp"
android:layout_weight="1" /> android:layout_weight="1" />
<!--TODO: Content Desc to Strings-->
<ImageButton <ImageButton
android:id="@+id/btnChangeQuality" android:id="@+id/btnChangeQuality"
android:layout_width="wrap_content" android:layout_width="wrap_content"
@ -80,7 +81,7 @@
android:background="@drawable/transparent_circle_background" android:background="@drawable/transparent_circle_background"
android:contentDescription="Quality" android:contentDescription="Quality"
android:padding="16dp" android:padding="16dp"
android:src="@drawable/ic_quality" android:src="@drawable/ic_monitor_play"
android:layout_gravity="end" android:layout_gravity="end"
app:tint="@android:color/white" app:tint="@android:color/white"
/> />

View file

@ -141,10 +141,24 @@
android:visibility="invisible" /> android:visibility="invisible" />
</RelativeLayout> </RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="24dp">
<Button
android:id="@+id/button_forget_password"
style="@style/Widget.Material3.Button.OutlinedButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/forget_password" />
</RelativeLayout>
<TextView <TextView
android:id="@+id/login_disclaimer" android:id="@+id/login_disclaimer"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginHorizontal="24dp" android:layout_marginHorizontal="24dp"
android:layout_margin="24dp" android:layout_margin="24dp"
android:textSize="16sp" android:textSize="16sp"

View file

@ -1,8 +1,8 @@
import org.gradle.api.JavaVersion import org.gradle.api.JavaVersion
object Versions { object Versions {
const val appCode = 9 const val appCode = 16
const val appName = "0.14.2" const val appName = "0.10.6-0.14.2"
const val compileSdk = 34 const val compileSdk = 34
const val buildTools = "34.0.0" const val buildTools = "34.0.0"
@ -12,4 +12,4 @@ object Versions {
val java = JavaVersion.VERSION_17 val java = JavaVersion.VERSION_17
const val ktlint = "0.50.0" const val ktlint = "0.50.0"
} }

View file

@ -30,6 +30,7 @@ android {
flavorDimensions += "variant" flavorDimensions += "variant"
productFlavors { productFlavors {
register("libre") register("libre")
create("Ananas")
} }
compileOptions { compileOptions {

View file

@ -6,10 +6,8 @@ import android.net.Uri
import android.os.Environment import android.os.Environment
import android.os.StatFs import android.os.StatFs
import android.text.format.Formatter import android.text.format.Formatter
import androidx.core.net.toFile
import androidx.core.net.toUri import androidx.core.net.toUri
import com.nomadics9.ananas.AppPreferences import com.nomadics9.ananas.AppPreferences
import com.nomadics9.ananas.api.JellyfinApi
import com.nomadics9.ananas.database.ServerDatabaseDao import com.nomadics9.ananas.database.ServerDatabaseDao
import com.nomadics9.ananas.models.FindroidEpisode import com.nomadics9.ananas.models.FindroidEpisode
import com.nomadics9.ananas.models.FindroidItem import com.nomadics9.ananas.models.FindroidItem
@ -19,6 +17,7 @@ import com.nomadics9.ananas.models.FindroidSource
import com.nomadics9.ananas.models.FindroidSources import com.nomadics9.ananas.models.FindroidSources
import com.nomadics9.ananas.models.FindroidTrickplayInfo import com.nomadics9.ananas.models.FindroidTrickplayInfo
import com.nomadics9.ananas.models.UiText import com.nomadics9.ananas.models.UiText
import com.nomadics9.ananas.models.VideoQuality
import com.nomadics9.ananas.models.toFindroidEpisodeDto import com.nomadics9.ananas.models.toFindroidEpisodeDto
import com.nomadics9.ananas.models.toFindroidMediaStreamDto import com.nomadics9.ananas.models.toFindroidMediaStreamDto
import com.nomadics9.ananas.models.toFindroidMovieDto import com.nomadics9.ananas.models.toFindroidMovieDto
@ -29,34 +28,10 @@ import com.nomadics9.ananas.models.toFindroidSourceDto
import com.nomadics9.ananas.models.toFindroidTrickplayInfoDto import com.nomadics9.ananas.models.toFindroidTrickplayInfoDto
import com.nomadics9.ananas.models.toFindroidUserDataDto import com.nomadics9.ananas.models.toFindroidUserDataDto
import com.nomadics9.ananas.repository.JellyfinRepository import com.nomadics9.ananas.repository.JellyfinRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jellyfin.sdk.api.client.extensions.dynamicHlsApi
import org.jellyfin.sdk.api.client.extensions.videosApi
import org.jellyfin.sdk.model.api.ClientCapabilitiesDto
import org.jellyfin.sdk.model.api.DeviceProfile
import org.jellyfin.sdk.model.api.DirectPlayProfile
import org.jellyfin.sdk.model.api.DlnaProfileType
import org.jellyfin.sdk.model.api.EncodingContext import org.jellyfin.sdk.model.api.EncodingContext
import org.jellyfin.sdk.model.api.MediaStreamProtocol import org.jellyfin.sdk.model.api.MediaStreamType
import org.jellyfin.sdk.model.api.PlaybackInfoDto
import org.jellyfin.sdk.model.api.ProfileCondition
import org.jellyfin.sdk.model.api.ProfileConditionType
import org.jellyfin.sdk.model.api.ProfileConditionValue
import org.jellyfin.sdk.model.api.SubtitleDeliveryMethod
import org.jellyfin.sdk.model.api.SubtitleProfile
import org.jellyfin.sdk.model.api.TranscodeSeekInfo
import org.jellyfin.sdk.model.api.TranscodingProfile
import timber.log.Timber import timber.log.Timber
import java.io.File import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.net.URL
import java.util.UUID import java.util.UUID
import kotlin.Exception import kotlin.Exception
import kotlin.math.ceil import kotlin.math.ceil
@ -76,17 +51,17 @@ class DownloaderImpl(
storageIndex: Int, storageIndex: Int,
): Pair<Long, UiText?> { ): Pair<Long, UiText?> {
try { try {
Timber.d("Downloading item: ${item.id} with sourceId: $sourceId") Timber.d("Downloading item: ${item.id} with sourceId: $sourceId")
val source = val source =
jellyfinRepository.getMediaSources(item.id, true).first { it.id == sourceId } jellyfinRepository.getMediaSources(item.id, true).first { it.id == sourceId }
val segments = jellyfinRepository.getSegmentsTimestamps(item.id) val segments = jellyfinRepository.getSegmentsTimestamps(item.id)
val trickplayInfo = if (item is FindroidSources) { val trickplayInfo =
item.trickplayInfo?.get(sourceId) if (item is FindroidSources) {
} else { item.trickplayInfo?.get(sourceId)
null } else {
} null
}
val storageLocation = context.getExternalFilesDirs(null)[storageIndex] val storageLocation = context.getExternalFilesDirs(null)[storageIndex]
if (storageLocation == null || Environment.getExternalStorageState(storageLocation) != Environment.MEDIA_MOUNTED) { if (storageLocation == null || Environment.getExternalStorageState(storageLocation) != Environment.MEDIA_MOUNTED) {
return Pair(-1, UiText.StringResource(CoreR.string.storage_unavailable)) return Pair(-1, UiText.StringResource(CoreR.string.storage_unavailable))
@ -104,15 +79,8 @@ class DownloaderImpl(
), ),
) )
} }
val qualityPreference = appPreferences.downloadQuality!! handleDownload(item, source, storageIndex, trickplayInfo, segments, path)
Timber.d("Quality preference: $qualityPreference") return Pair(-1, null)
return if (qualityPreference != "Original") {
Timber.d("Handling Transcoding download for item: ${item.id}")
handleTranscodeDownload(item, source, storageIndex, trickplayInfo, segments, path, qualityPreference)
} else {
Timber.d("Handling original download for item: ${item.id}")
downloadOriginalItem(item, source, storageIndex, trickplayInfo, segments, path)
}
} catch (e: Exception) { } catch (e: Exception) {
try { try {
val source = jellyfinRepository.getMediaSources(item.id).first { it.id == sourceId } val source = jellyfinRepository.getMediaSources(item.id).first { it.id == sourceId }
@ -122,79 +90,18 @@ class DownloaderImpl(
return Pair( return Pair(
-1, -1,
if (e.message != null) UiText.DynamicString(e.message!!) else UiText.StringResource( if (e.message != null) {
CoreR.string.unknown_error UiText.DynamicString(e.message!!)
) } else {
UiText.StringResource(
CoreR.string.unknown_error,
)
},
) )
} }
} }
private suspend fun handleTranscodeDownload( private suspend fun handleDownload(
item: FindroidItem,
source: FindroidSource,
storageIndex: Int,
trickplayInfo: FindroidTrickplayInfo?,
segments: List<FindroidSegment>?,
path: Uri,
quality: String
): Pair<Long, UiText?> {
val transcodingUrl = getTranscodedUrl(item.id, quality)
when (item) {
is FindroidMovie -> {
database.insertMovie(item.toFindroidMovieDto(appPreferences.currentServer!!))
database.insertSource(source.toFindroidSourceDto(item.id, path.path.orEmpty()))
database.insertUserData(item.toFindroidUserDataDto(jellyfinRepository.getUserId()))
downloadExternalMediaStreams(item, source, storageIndex)
if (trickplayInfo != null) {
downloadTrickplayData(item.id, source.id, trickplayInfo)
}
if (segments != null) {
database.insertSegments(segments.toFindroidSegmentsDto(item.id))
}
val request = DownloadManager.Request(transcodingUrl)
.setTitle(item.name)
.setAllowedOverMetered(appPreferences.downloadOverMobileData)
.setAllowedOverRoaming(appPreferences.downloadWhenRoaming)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationUri(path)
val downloadId = downloadManager.enqueue(request)
database.setSourceDownloadId(source.id, downloadId)
return Pair(downloadId, null)
}
is FindroidEpisode -> {
database.insertShow(
jellyfinRepository.getShow(item.seriesId)
.toFindroidShowDto(appPreferences.currentServer!!),
)
database.insertSeason(
jellyfinRepository.getSeason(item.seasonId).toFindroidSeasonDto(),
)
database.insertEpisode(item.toFindroidEpisodeDto(appPreferences.currentServer!!))
database.insertSource(source.toFindroidSourceDto(item.id, path.path.orEmpty()))
database.insertUserData(item.toFindroidUserDataDto(jellyfinRepository.getUserId()))
downloadExternalMediaStreams(item, source, storageIndex)
if (trickplayInfo != null) {
downloadTrickplayData(item.id, source.id, trickplayInfo)
}
if (segments != null) {
database.insertSegments(segments.toFindroidSegmentsDto(item.id))
}
val request = DownloadManager.Request(transcodingUrl)
.setTitle(item.name)
.setAllowedOverMetered(appPreferences.downloadOverMobileData)
.setAllowedOverRoaming(appPreferences.downloadWhenRoaming)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationUri(path)
val downloadId = downloadManager.enqueue(request)
database.setSourceDownloadId(source.id, downloadId)
return Pair(downloadId, null)
}
}
return Pair(-1, null)
}
private suspend fun downloadOriginalItem(
item: FindroidItem, item: FindroidItem,
source: FindroidSource, source: FindroidSource,
storageIndex: Int, storageIndex: Int,
@ -214,20 +121,40 @@ class DownloaderImpl(
if (segments != null) { if (segments != null) {
database.insertSegments(segments.toFindroidSegmentsDto(item.id)) database.insertSegments(segments.toFindroidSegmentsDto(item.id))
} }
val request = DownloadManager.Request(source.path.toUri()) if (appPreferences.downloadQuality != VideoQuality.Original.toString()) {
.setTitle(item.name) downloadEmbeddedMediaStreams(item, source, storageIndex)
.setAllowedOverMetered(appPreferences.downloadOverMobileData) val transcodingUrl =
.setAllowedOverRoaming(appPreferences.downloadWhenRoaming) getTranscodedUrl(item.id, appPreferences.downloadQuality!!)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) val request =
.setDestinationUri(path) DownloadManager
val downloadId = downloadManager.enqueue(request) .Request(transcodingUrl)
database.setSourceDownloadId(source.id, downloadId) .setTitle(item.name)
return Pair(downloadId, null) .setAllowedOverMetered(appPreferences.downloadOverMobileData)
.setAllowedOverRoaming(appPreferences.downloadWhenRoaming)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationUri(path)
val downloadId = downloadManager.enqueue(request)
database.setSourceDownloadId(source.id, downloadId)
return Pair(downloadId, null)
} else {
val request =
DownloadManager
.Request(source.path.toUri())
.setTitle(item.name)
.setAllowedOverMetered(appPreferences.downloadOverMobileData)
.setAllowedOverRoaming(appPreferences.downloadWhenRoaming)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationUri(path)
val downloadId = downloadManager.enqueue(request)
database.setSourceDownloadId(source.id, downloadId)
return Pair(downloadId, null)
}
} }
is FindroidEpisode -> { is FindroidEpisode -> {
database.insertShow( database.insertShow(
jellyfinRepository.getShow(item.seriesId) jellyfinRepository
.getShow(item.seriesId)
.toFindroidShowDto(appPreferences.currentServer!!), .toFindroidShowDto(appPreferences.currentServer!!),
) )
database.insertSeason( database.insertSeason(
@ -243,29 +170,53 @@ class DownloaderImpl(
if (segments != null) { if (segments != null) {
database.insertSegments(segments.toFindroidSegmentsDto(item.id)) database.insertSegments(segments.toFindroidSegmentsDto(item.id))
} }
val request = DownloadManager.Request(source.path.toUri()) if (appPreferences.downloadQuality != VideoQuality.Original.toString()) {
.setTitle(item.name) downloadEmbeddedMediaStreams(item, source, storageIndex)
.setAllowedOverMetered(appPreferences.downloadOverMobileData) val transcodingUrl =
.setAllowedOverRoaming(appPreferences.downloadWhenRoaming) getTranscodedUrl(item.id, appPreferences.downloadQuality!!)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) val request =
.setDestinationUri(path) DownloadManager
val downloadId = downloadManager.enqueue(request) .Request(transcodingUrl)
database.setSourceDownloadId(source.id, downloadId) .setTitle(item.name)
return Pair(downloadId, null) .setAllowedOverMetered(appPreferences.downloadOverMobileData)
.setAllowedOverRoaming(appPreferences.downloadWhenRoaming)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationUri(path)
val downloadId = downloadManager.enqueue(request)
database.setSourceDownloadId(source.id, downloadId)
return Pair(downloadId, null)
} else {
val request =
DownloadManager
.Request(source.path.toUri())
.setTitle(item.name)
.setAllowedOverMetered(appPreferences.downloadOverMobileData)
.setAllowedOverRoaming(appPreferences.downloadWhenRoaming)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationUri(path)
val downloadId = downloadManager.enqueue(request)
database.setSourceDownloadId(source.id, downloadId)
return Pair(downloadId, null)
}
} }
} }
return Pair(-1, null) return Pair(-1, null)
} }
override suspend fun cancelDownload(
override suspend fun cancelDownload(item: FindroidItem, source: FindroidSource) { item: FindroidItem,
source: FindroidSource,
) {
if (source.downloadId != null) { if (source.downloadId != null) {
downloadManager.remove(source.downloadId!!) downloadManager.remove(source.downloadId!!)
} }
deleteItem(item, source) deleteItem(item, source)
} }
override suspend fun deleteItem(item: FindroidItem, source: FindroidSource) { override suspend fun deleteItem(
item: FindroidItem,
source: FindroidSource,
) {
when (item) { when (item) {
is FindroidMovie -> { is FindroidMovie -> {
database.deleteMovie(item.id) database.deleteMovie(item.id)
@ -307,15 +258,18 @@ class DownloaderImpl(
if (downloadId == null) { if (downloadId == null) {
return Pair(downloadStatus, progress) return Pair(downloadStatus, progress)
} }
val query = DownloadManager.Query() val query =
.setFilterById(downloadId) DownloadManager
.Query()
.setFilterById(downloadId)
val cursor = downloadManager.query(query) val cursor = downloadManager.query(query)
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
downloadStatus = cursor.getInt( downloadStatus =
cursor.getColumnIndexOrThrow( cursor.getInt(
DownloadManager.COLUMN_STATUS, cursor.getColumnIndexOrThrow(
), DownloadManager.COLUMN_STATUS,
) ),
)
when (downloadStatus) { when (downloadStatus) {
DownloadManager.STATUS_RUNNING -> { DownloadManager.STATUS_RUNNING -> {
val totalBytes = val totalBytes =
@ -344,25 +298,69 @@ class DownloaderImpl(
val storageLocation = context.getExternalFilesDirs(null)[storageIndex] val storageLocation = context.getExternalFilesDirs(null)[storageIndex]
for (mediaStream in source.mediaStreams.filter { it.isExternal }) { for (mediaStream in source.mediaStreams.filter { it.isExternal }) {
val id = UUID.randomUUID() val id = UUID.randomUUID()
val streamPath = Uri.fromFile( val streamPath =
File( Uri.fromFile(
storageLocation, File(
"downloads/${item.id}.${source.id}.$id.download" storageLocation,
"downloads/${item.id}.${source.id}.$id.download",
),
) )
)
database.insertMediaStream( database.insertMediaStream(
mediaStream.toFindroidMediaStreamDto( mediaStream.toFindroidMediaStreamDto(
id, id,
source.id, source.id,
streamPath.path.orEmpty() streamPath.path.orEmpty(),
) ),
) )
val request = DownloadManager.Request(Uri.parse(mediaStream.path)) val request =
.setTitle(mediaStream.title) DownloadManager
.setAllowedOverMetered(appPreferences.downloadOverMobileData) .Request(Uri.parse(mediaStream.path))
.setAllowedOverRoaming(appPreferences.downloadWhenRoaming) .setTitle(mediaStream.title)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN) .setAllowedOverMetered(appPreferences.downloadOverMobileData)
.setDestinationUri(streamPath) .setAllowedOverRoaming(appPreferences.downloadWhenRoaming)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN)
.setDestinationUri(streamPath)
val downloadId = downloadManager.enqueue(request)
database.setMediaStreamDownloadId(id, downloadId)
}
}
private fun downloadEmbeddedMediaStreams(
item: FindroidItem,
source: FindroidSource,
storageIndex: Int = 0,
) {
val storageLocation = context.getExternalFilesDirs(null)[storageIndex]
val subtitleStreams = source.mediaStreams.filter { !it.isExternal && it.type == MediaStreamType.SUBTITLE && it.path != null }
for (mediaStream in subtitleStreams) {
var deliveryUrl = mediaStream.path!!
if (mediaStream.codec == "webvtt") {
deliveryUrl = deliveryUrl.replace("Stream.srt", "Stream.vtt")
}
val id = UUID.randomUUID()
val streamPath =
Uri.fromFile(
File(
storageLocation,
"downloads/${item.id}.${source.id}.$id.download",
),
)
database.insertMediaStream(
mediaStream.toFindroidMediaStreamDto(
id,
source.id,
streamPath.path.orEmpty(),
),
)
val request =
DownloadManager
.Request(Uri.parse(deliveryUrl))
.setTitle(mediaStream.title)
.setAllowedOverMetered(appPreferences.downloadOverMobileData)
.setAllowedOverRoaming(appPreferences.downloadWhenRoaming)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN)
.setDestinationUri(streamPath)
val downloadId = downloadManager.enqueue(request) val downloadId = downloadManager.enqueue(request)
database.setMediaStreamDownloadId(id, downloadId) database.setMediaStreamDownloadId(id, downloadId)
} }
@ -373,19 +371,22 @@ class DownloaderImpl(
sourceId: String, sourceId: String,
trickplayInfo: FindroidTrickplayInfo, trickplayInfo: FindroidTrickplayInfo,
) { ) {
val maxIndex = ceil( val maxIndex =
trickplayInfo.thumbnailCount.toDouble() ceil(
.div(trickplayInfo.tileWidth * trickplayInfo.tileHeight) trickplayInfo.thumbnailCount
).toInt() .toDouble()
.div(trickplayInfo.tileWidth * trickplayInfo.tileHeight),
).toInt()
val byteArrays = mutableListOf<ByteArray>() val byteArrays = mutableListOf<ByteArray>()
for (i in 0..maxIndex) { for (i in 0..maxIndex) {
jellyfinRepository.getTrickplayData( jellyfinRepository
itemId, .getTrickplayData(
trickplayInfo.width, itemId,
i, trickplayInfo.width,
)?.let { byteArray -> i,
byteArrays.add(byteArray) )?.let { byteArray ->
} byteArrays.add(byteArray)
}
} }
saveTrickplayData(itemId, sourceId, trickplayInfo, byteArrays) saveTrickplayData(itemId, sourceId, trickplayInfo, byteArrays)
} }
@ -405,51 +406,46 @@ class DownloaderImpl(
} }
} }
private suspend fun getTranscodedUrl(itemId: UUID, quality: String): Uri? { private suspend fun getTranscodedUrl(
val maxBitrate = when (quality) { itemId: UUID,
"720p" -> 2000000 // 2 Mbps quality: String,
"480p" -> 1000000 // 1 Mbps ): Uri? {
"360p" -> 800000 // 800Kbps val videoQuality = VideoQuality.fromString(quality)!!
else -> 2000000 // Default to 2 Mbps if not specified
}
return try { return try {
val deviceProfile =
val deviceProfile = jellyfinRepository.buildDeviceProfile(maxBitrate,"mkv", EncodingContext.STATIC) jellyfinRepository.buildDeviceProfile(
val playbackInfo = jellyfinRepository.getPostedPlaybackInfo(itemId,false,deviceProfile,maxBitrate) VideoQuality.getBitrate(videoQuality),
val mediaSourceId = playbackInfo.content.mediaSources.firstOrNull()?.id!! "mkv",
EncodingContext.STATIC,
)
val playbackInfo =
jellyfinRepository.getPostedPlaybackInfo(
itemId,
false,
deviceProfile,
VideoQuality.getBitrate(videoQuality),
)
val mediaSourceId =
playbackInfo.content.mediaSources
.firstOrNull()
?.id!!
val playSessionId = playbackInfo.content.playSessionId!! val playSessionId = playbackInfo.content.playSessionId!!
val downloadUrl = jellyfinRepository.getVideoStreambyContainerUrl(itemId, mediaSourceId, playSessionId, maxBitrate, "ts") val deviceId = jellyfinRepository.getDeviceId()
val downloadUrl =
jellyfinRepository.getVideoStreambyContainerUrl(
itemId,
deviceId,
mediaSourceId,
playSessionId,
VideoQuality.getBitrate(videoQuality),
"mkv",
VideoQuality.getHeight(videoQuality),
)
val transcodeUri = buildTranscodeUri(downloadUrl, maxBitrate, quality) return downloadUrl.toUri()
Timber.d("Constructed Transcode URL: $transcodeUri")
transcodeUri
} catch (e: Exception) { } catch (e: Exception) {
Timber.e(e) Timber.e(e)
null null
} }
} }
private fun buildTranscodeUri(
transcodingUrl: String,
maxBitrate: Int,
quality: String
): Uri {
val resolution = when (quality) {
"720p" -> "720"
"480p" -> "480"
"360p" -> "360"
else -> "720"
}
return Uri.parse(transcodingUrl).buildUpon()
.appendQueryParameter("MaxVideoHeight", resolution)
.appendQueryParameter("MaxVideoBitRate", maxBitrate.toString())
.appendQueryParameter("subtitleMethod", "External")
//.appendQueryParameter("api_key", apiKey)
.build()
}
} }

View file

@ -0,0 +1,35 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24"
android:tint="?attr/colorControlNormal">
<path
android:pathData="M10,7.75a0.75,0.75 0,0 1,1.142 -0.638l3.664,2.249a0.75,0.75 0,0 1,0 1.278l-3.664,2.25a0.75,0.75 0,0 1,-1.142 -0.64z"
android:strokeLineJoin="round"
android:strokeWidth="2"
android:fillColor="#00000000"
android:strokeColor="@android:color/white"
android:strokeLineCap="round"/>
<path
android:pathData="M12,17v4"
android:strokeLineJoin="round"
android:strokeWidth="2"
android:fillColor="#00000000"
android:strokeColor="@android:color/white"
android:strokeLineCap="round"/>
<path
android:pathData="M8,21h8"
android:strokeLineJoin="round"
android:strokeWidth="2"
android:fillColor="#00000000"
android:strokeColor="@android:color/white"
android:strokeLineCap="round"/>
<path
android:pathData="M4,3L20,3A2,2 0,0 1,22 5L22,15A2,2 0,0 1,20 17L4,17A2,2 0,0 1,2 15L2,5A2,2 0,0 1,4 3z"
android:strokeLineJoin="round"
android:strokeWidth="2"
android:fillColor="#00000000"
android:strokeColor="@android:color/white"
android:strokeLineCap="round"/>
</vector>

View file

@ -1,2 +1,20 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources></resources> <resources>
<string name="add_server_error_outdated">اصدار الخادم قديم: %1$s. الرجاء تحديث الخادم</string>
<string name="add_server_error_not_jellyfin">ليس خادم جيلي فن:%1$s</string>
<string name="add_server_error_version">اصدار الخادم غير مدعوم: %1$s. الرجاء تحديث الخادم</string>
<string name="add_server_error_slow">رد الخادم بطيء: %1$s</string>
<string name="login">تسجيل دخول</string>
<string name="login_error_wrong_username_password">اسم المستخدم او الكلمه السريه غير صحيحه</string>
<string name="select_server">اختر الخادم</string>
<string name="edit_text_server_address_hint">عنوان الخادم</string>
<string name="edit_text_username_hint">اسم المستخدم</string>
<string name="edit_text_password_hint">الكلمه السريه</string>
<string name="button_connect">اتصل</string>
<string name="button_login">تسجيل دخول</string>
<string name="remove_server">حذف الخادم</string>
<string name="add_server">اضافه خادم</string>
<string name="add_server_error_not_found">الخادم غير موجود</string>
<string name="add_server_error_empty_address">عنوان الخادم فاضي</string>
<string name="add_server_error_no_id">الخادم غير معرف بالid , يبدو انه هناك خلل في الخادم</string>
</resources>

View file

@ -26,15 +26,37 @@
<item>opensles</item> <item>opensles</item>
</string-array> </string-array>
<string-array name="quality_entries"> <string-array name="quality_entries">
<item>Original</item> <item>@string/quality_auto</item>
<item>720p - 2Mbps</item> <item>@string/quality_original</item>
<item>480p - 1Mbps</item> <item>@string/quality_1080p</item>
<item>360p - 800Kbps</item> <item>@string/quality_720p</item>
<item>@string/quality_480p</item>
<item>@string/quality_360p</item>
</string-array> </string-array>
<string-array name="quality_values"> <string-array name="quality_values">
<item>Auto</item>
<item>Original</item> <item>Original</item>
<item>1080p</item>
<item>720p</item> <item>720p</item>
<item>480p</item> <item>480p</item>
<item>360p</item> <item>360p</item>
</string-array> </string-array>
<string-array name="download_quality_entries">
<item>@string/quality_original</item>
<item>@string/quality_1080p</item>
<item>@string/quality_720p</item>
<item>@string/quality_480p</item>
<item>@string/quality_360p</item>
</string-array>
<string-array name="download_quality_values">
<item>Original</item>
<item>1080p</item>
<item>720p</item>
<item>480p</item>
<item>360p</item>
</string-array>
<string-array name="codecs">
<item>h264</item>
<item>hevc</item>
</string-array>
</resources> </resources>

View file

@ -11,6 +11,7 @@
<string name="add_server_error_not_found">Server not found</string> <string name="add_server_error_not_found">Server not found</string>
<string name="add_server_error_no_id">Server has no id, something seems to be wrong with the server</string> <string name="add_server_error_no_id">Server has no id, something seems to be wrong with the server</string>
<string name="login">Login</string> <string name="login">Login</string>
<string name="forget_password">Forget Password?</string>
<string name="login_error_wrong_username_password">Wrong username or password</string> <string name="login_error_wrong_username_password">Wrong username or password</string>
<string name="select_server">Select server</string> <string name="select_server">Select server</string>
<string name="edit_text_server_address_hint">Server address</string> <string name="edit_text_server_address_hint">Server address</string>
@ -139,6 +140,7 @@
<string name="settings_request_timeout">Request timeout (ms)</string> <string name="settings_request_timeout">Request timeout (ms)</string>
<string name="settings_connect_timeout">Connect timeout (ms)</string> <string name="settings_connect_timeout">Connect timeout (ms)</string>
<string name="settings_socket_timeout">Socket timeout (ms)</string> <string name="settings_socket_timeout">Socket timeout (ms)</string>
<string name="settings_quality_codec">Transcoding codec</string>
<string name="users">Users</string> <string name="users">Users</string>
<string name="add_user">Add user</string> <string name="add_user">Add user</string>
<string name="pref_player_mpv_hwdec">Hardware decoding</string> <string name="pref_player_mpv_hwdec">Hardware decoding</string>
@ -193,6 +195,15 @@
<string name="unmark_as_played">Unmark as played</string> <string name="unmark_as_played">Unmark as played</string>
<string name="add_to_favorites">Add to favorites</string> <string name="add_to_favorites">Add to favorites</string>
<string name="remove_from_favorites">Remove from favorites</string> <string name="remove_from_favorites">Remove from favorites</string>
<string name="quality_default">Default to selected download quality</string>
<string name="download_quality">Download Quality</string>
<string name="select_quality">Select Video Quality</string>
<string name="quality_auto">Auto</string>
<string name="quality_original">Original</string>
<string name="quality_1080p">1080p - 8Mbps</string>
<string name="quality_720p">720p - 3Mbps</string>
<string name="quality_480p">480p - 1.5Mbps</string>
<string name="quality_360p">360p - 0.8Mbps</string>
<string name="alaskarTV_requests">AlaskarTV Requests</string> <string name="alaskarTV_requests">AlaskarTV Requests</string>
<string name="pref_player_trickplay_gesture">Trick Play in seek gesture</string> <string name="pref_player_trickplay_gesture">Trick Play in seek gesture</string>
<string name="pref_player_trickplay_gesture_summary">Requires \'Seek gesture\' and \'Trick Play\'</string> <string name="pref_player_trickplay_gesture_summary">Requires \'Seek gesture\' and \'Trick Play\'</string>

View file

@ -75,7 +75,8 @@
<Preference <Preference
app:key="appInfo" app:key="appInfo"
app:icon="@drawable/ic_logo" app:icon="@drawable/ic_logo"
app:title="@string/app_info" /> app:title="@string/app_info"
app:summary="" />
</PreferenceCategory> </PreferenceCategory>

View file

@ -11,15 +11,13 @@
app:title="@string/download_roaming" /> app:title="@string/download_roaming" />
<ListPreference <ListPreference
android:key="pref_downloads_quality" android:key="pref_downloads_quality"
android:title="Download Quality" android:title="@string/download_quality"
android:defaultValue="Original" android:defaultValue="@string/quality_original"
android:entries="@array/quality_entries" android:entries="@array/download_quality_entries"
android:entryValues="@array/quality_values" android:entryValues="@array/download_quality_values"
android:summary="%s" /> android:summary="%s" />
<SwitchPreferenceCompat <SwitchPreferenceCompat
android:defaultValue="false" android:defaultValue="false"
app:key="pref_downloads_quality_default" app:key="pref_downloads_quality_default"
app:summary="Default to picked Download Quality" /> app:summary="@string/quality_default" />
</PreferenceScreen> </PreferenceScreen>

View file

@ -20,4 +20,11 @@
android:defaultValue="true" android:defaultValue="true"
app:key="pref_auto_offline" app:key="pref_auto_offline"
app:title="@string/turn_on_offline_mode_automatically" /> app:title="@string/turn_on_offline_mode_automatically" />
<ListPreference
app:defaultValue="hevc"
app:key="pref_network_codec"
app:title="@string/settings_quality_codec"
app:useSimpleSummaryProvider="true"
app:entries="@array/codecs"
app:entryValues="@array/codecs" />
</PreferenceScreen> </PreferenceScreen>

View file

@ -0,0 +1,31 @@
package com.nomadics9.ananas.models
enum class VideoQuality(
val bitrate: Int,
val height: Int,
val width: Int,
val isOriginalQuality: Boolean,
) {
Auto(10000000, 1080, 1920, false),
Original(1000000000, 1080, 1920, true),
P3840(12000000,3840, 2160, false), // Here for future proofing and to calculate original resolution only
P1080(8000000, 1080, 1920, false),
P720(3000000, 720, 1280, false),
P480(1500000, 480, 854, false),
P360(800000, 360, 640, false);
override fun toString(): String = when (this) {
Auto -> "Auto"
Original -> "Original"
P3840 -> "4K"
else -> "${height}p"
}
companion object {
fun fromString(quality: String): VideoQuality? = entries.find { it.toString() == quality }
fun getBitrate(quality: VideoQuality): Int = quality.bitrate
fun getHeight(quality: VideoQuality): Int = quality.height
fun getWidth(quality: VideoQuality): Int = quality.width
fun getIsOriginalQuality(quality: VideoQuality): Boolean = quality.isOriginalQuality
}
}

View file

@ -14,7 +14,6 @@ import kotlinx.coroutines.flow.Flow
import org.jellyfin.sdk.api.client.Response import org.jellyfin.sdk.api.client.Response
import org.jellyfin.sdk.model.api.BaseItemDto import org.jellyfin.sdk.model.api.BaseItemDto
import org.jellyfin.sdk.model.api.BaseItemKind import org.jellyfin.sdk.model.api.BaseItemKind
import org.jellyfin.sdk.model.api.DeviceInfoQueryResult
import org.jellyfin.sdk.model.api.DeviceProfile import org.jellyfin.sdk.model.api.DeviceProfile
import org.jellyfin.sdk.model.api.EncodingContext import org.jellyfin.sdk.model.api.EncodingContext
import org.jellyfin.sdk.model.api.ItemFields import org.jellyfin.sdk.model.api.ItemFields
@ -30,7 +29,9 @@ interface JellyfinRepository {
suspend fun getUserViews(): List<BaseItemDto> suspend fun getUserViews(): List<BaseItemDto>
suspend fun getItem(itemId: UUID): BaseItemDto suspend fun getItem(itemId: UUID): BaseItemDto
suspend fun getEpisode(itemId: UUID): FindroidEpisode suspend fun getEpisode(itemId: UUID): FindroidEpisode
suspend fun getMovie(itemId: UUID): FindroidMovie suspend fun getMovie(itemId: UUID): FindroidMovie
suspend fun getShow(itemId: UUID): FindroidShow suspend fun getShow(itemId: UUID): FindroidShow
@ -71,7 +72,10 @@ interface JellyfinRepository {
suspend fun getLatestMedia(parentId: UUID): List<FindroidItem> suspend fun getLatestMedia(parentId: UUID): List<FindroidItem>
suspend fun getSeasons(seriesId: UUID, offline: Boolean = false): List<FindroidSeason> suspend fun getSeasons(
seriesId: UUID,
offline: Boolean = false,
): List<FindroidSeason>
suspend fun getNextUp(seriesId: UUID? = null): List<FindroidEpisode> suspend fun getNextUp(seriesId: UUID? = null): List<FindroidEpisode>
@ -86,7 +90,7 @@ interface JellyfinRepository {
suspend fun getMediaSources(itemId: UUID, includePath: Boolean = false): List<FindroidSource> suspend fun getMediaSources(itemId: UUID, includePath: Boolean = false): List<FindroidSource>
suspend fun getStreamUrl(itemId: UUID, mediaSourceId: String): String suspend fun getStreamUrl(itemId: UUID, mediaSourceId: String, playSessionId: String? = null): String
suspend fun getSegmentsTimestamps(itemId: UUID): List<FindroidSegment>? suspend fun getSegmentsTimestamps(itemId: UUID): List<FindroidSegment>?
@ -120,13 +124,38 @@ interface JellyfinRepository {
suspend fun getDeviceId(): String suspend fun getDeviceId(): String
suspend fun getVideoTranscodeBitRate(transcodeResolution: Int): Pair<Int, Int> suspend fun buildDeviceProfile(
maxBitrate: Int,
container: String,
context: EncodingContext,
): DeviceProfile
suspend fun buildDeviceProfile(maxBitrate: Int, container: String, context: EncodingContext): DeviceProfile suspend fun getVideoStreambyContainerUrl(
itemId: UUID,
deviceId: String,
mediaSourceId: String,
playSessionId: String,
videoBitrate: Int,
container: String,
maxHeight: Int,
): String
suspend fun getVideoStreambyContainerUrl(itemId: UUID, mediaSourceId: String, playSessionId: String, videoBitrate: Int, container: String): String suspend fun getTranscodedVideoStream(
itemId: UUID,
deviceId: String,
mediaSourceId: String,
playSessionId: String,
videoBitrate: Int,
): String
suspend fun getPostedPlaybackInfo(itemId: UUID, enableDirectStream: Boolean, deviceProfile: DeviceProfile ,maxBitrate: Int): Response<PlaybackInfoResponse> suspend fun getPostedPlaybackInfo(
itemId: UUID,
enableDirectStream: Boolean,
deviceProfile: DeviceProfile,
maxBitrate: Int,
): Response<PlaybackInfoResponse>
suspend fun stopEncodingProcess(playSessionId: String) suspend fun stopEncodingProcess(playSessionId: String)
suspend fun getAccessToken(): String?
} }

View file

@ -17,6 +17,7 @@ import com.nomadics9.ananas.models.FindroidSegments
import com.nomadics9.ananas.models.FindroidShow import com.nomadics9.ananas.models.FindroidShow
import com.nomadics9.ananas.models.FindroidSource import com.nomadics9.ananas.models.FindroidSource
import com.nomadics9.ananas.models.SortBy import com.nomadics9.ananas.models.SortBy
import com.nomadics9.ananas.models.VideoQuality
import com.nomadics9.ananas.models.toFindroidCollection import com.nomadics9.ananas.models.toFindroidCollection
import com.nomadics9.ananas.models.toFindroidEpisode import com.nomadics9.ananas.models.toFindroidEpisode
import com.nomadics9.ananas.models.toFindroidItem import com.nomadics9.ananas.models.toFindroidItem
@ -30,12 +31,12 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import org.jellyfin.sdk.api.client.Response import org.jellyfin.sdk.api.client.Response
import org.jellyfin.sdk.api.client.extensions.dynamicHlsApi
import org.jellyfin.sdk.api.client.extensions.get import org.jellyfin.sdk.api.client.extensions.get
import org.jellyfin.sdk.api.client.extensions.hlsSegmentApi import org.jellyfin.sdk.api.client.extensions.hlsSegmentApi
import org.jellyfin.sdk.model.api.BaseItemDto import org.jellyfin.sdk.model.api.BaseItemDto
import org.jellyfin.sdk.model.api.BaseItemKind import org.jellyfin.sdk.model.api.BaseItemKind
import org.jellyfin.sdk.model.api.ClientCapabilitiesDto import org.jellyfin.sdk.model.api.ClientCapabilitiesDto
import org.jellyfin.sdk.model.api.DeviceInfoQueryResult
import org.jellyfin.sdk.model.api.DeviceOptionsDto import org.jellyfin.sdk.model.api.DeviceOptionsDto
import org.jellyfin.sdk.model.api.DeviceProfile import org.jellyfin.sdk.model.api.DeviceProfile
import org.jellyfin.sdk.model.api.DirectPlayProfile import org.jellyfin.sdk.model.api.DirectPlayProfile
@ -69,55 +70,70 @@ class JellyfinRepositoryImpl(
private val database: ServerDatabaseDao, private val database: ServerDatabaseDao,
private val appPreferences: AppPreferences, private val appPreferences: AppPreferences,
) : JellyfinRepository { ) : JellyfinRepository {
override suspend fun getPublicSystemInfo(): PublicSystemInfo = withContext(Dispatchers.IO) { override suspend fun getPublicSystemInfo(): PublicSystemInfo =
jellyfinApi.systemApi.getPublicSystemInfo().content withContext(Dispatchers.IO) {
} jellyfinApi.systemApi.getPublicSystemInfo().content
}
override suspend fun getUserViews(): List<BaseItemDto> = withContext(Dispatchers.IO) { override suspend fun getUserViews(): List<BaseItemDto> =
jellyfinApi.viewsApi.getUserViews(jellyfinApi.userId!!).content.items.orEmpty() withContext(Dispatchers.IO) {
} jellyfinApi.viewsApi
.getUserViews(jellyfinApi.userId!!)
.content.items
.orEmpty()
}
override suspend fun getItem(itemId: UUID): BaseItemDto = withContext(Dispatchers.IO) { override suspend fun getItem(itemId: UUID): BaseItemDto =
jellyfinApi.userLibraryApi.getItem(itemId, jellyfinApi.userId!!).content withContext(Dispatchers.IO) {
} jellyfinApi.userLibraryApi.getItem(itemId, jellyfinApi.userId!!).content
}
override suspend fun getEpisode(itemId: UUID): FindroidEpisode = override suspend fun getEpisode(itemId: UUID): FindroidEpisode =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
jellyfinApi.userLibraryApi.getItem( jellyfinApi.userLibraryApi
itemId, .getItem(
jellyfinApi.userId!!, itemId,
).content.toFindroidEpisode(this@JellyfinRepositoryImpl, database)!! jellyfinApi.userId!!,
).content
.toFindroidEpisode(this@JellyfinRepositoryImpl, database)!!
} }
override suspend fun getMovie(itemId: UUID): FindroidMovie = override suspend fun getMovie(itemId: UUID): FindroidMovie =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
jellyfinApi.userLibraryApi.getItem( jellyfinApi.userLibraryApi
itemId, .getItem(
jellyfinApi.userId!!, itemId,
).content.toFindroidMovie(this@JellyfinRepositoryImpl, database) jellyfinApi.userId!!,
).content
.toFindroidMovie(this@JellyfinRepositoryImpl, database)
} }
override suspend fun getShow(itemId: UUID): FindroidShow = override suspend fun getShow(itemId: UUID): FindroidShow =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
jellyfinApi.userLibraryApi.getItem( jellyfinApi.userLibraryApi
itemId, .getItem(
jellyfinApi.userId!!, itemId,
).content.toFindroidShow(this@JellyfinRepositoryImpl) jellyfinApi.userId!!,
).content
.toFindroidShow(this@JellyfinRepositoryImpl)
} }
override suspend fun getSeason(itemId: UUID): FindroidSeason = override suspend fun getSeason(itemId: UUID): FindroidSeason =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
jellyfinApi.userLibraryApi.getItem( jellyfinApi.userLibraryApi
itemId, .getItem(
jellyfinApi.userId!!, itemId,
).content.toFindroidSeason(this@JellyfinRepositoryImpl) jellyfinApi.userId!!,
).content
.toFindroidSeason(this@JellyfinRepositoryImpl)
} }
override suspend fun getLibraries(): List<FindroidCollection> = override suspend fun getLibraries(): List<FindroidCollection> =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
jellyfinApi.itemsApi.getItems( jellyfinApi.itemsApi
jellyfinApi.userId!!, .getItems(
).content.items jellyfinApi.userId!!,
).content.items
.orEmpty() .orEmpty()
.mapNotNull { it.toFindroidCollection(this@JellyfinRepositoryImpl) } .mapNotNull { it.toFindroidCollection(this@JellyfinRepositoryImpl) }
} }
@ -132,16 +148,17 @@ class JellyfinRepositoryImpl(
limit: Int?, limit: Int?,
): List<FindroidItem> = ): List<FindroidItem> =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
jellyfinApi.itemsApi.getItems( jellyfinApi.itemsApi
jellyfinApi.userId!!, .getItems(
parentId = parentId, jellyfinApi.userId!!,
includeItemTypes = includeTypes, parentId = parentId,
recursive = recursive, includeItemTypes = includeTypes,
sortBy = listOf(ItemSortBy.fromName(sortBy.sortString)), recursive = recursive,
sortOrder = listOf(sortOrder), sortBy = listOf(ItemSortBy.fromName(sortBy.sortString)),
startIndex = startIndex, sortOrder = listOf(sortOrder),
limit = limit, startIndex = startIndex,
).content.items limit = limit,
).content.items
.orEmpty() .orEmpty()
.mapNotNull { it.toFindroidItem(this@JellyfinRepositoryImpl, database) } .mapNotNull { it.toFindroidItem(this@JellyfinRepositoryImpl, database) }
} }
@ -152,13 +169,14 @@ class JellyfinRepositoryImpl(
recursive: Boolean, recursive: Boolean,
sortBy: SortBy, sortBy: SortBy,
sortOrder: SortOrder, sortOrder: SortOrder,
): Flow<PagingData<FindroidItem>> { ): Flow<PagingData<FindroidItem>> =
return Pager( Pager(
config = PagingConfig( config =
pageSize = 10, PagingConfig(
maxSize = 100, pageSize = 10,
enablePlaceholders = false, maxSize = 100,
), enablePlaceholders = false,
),
pagingSourceFactory = { pagingSourceFactory = {
ItemsPagingSource( ItemsPagingSource(
this, this,
@ -170,87 +188,102 @@ class JellyfinRepositoryImpl(
) )
}, },
).flow ).flow
}
override suspend fun getPersonItems( override suspend fun getPersonItems(
personIds: List<UUID>, personIds: List<UUID>,
includeTypes: List<BaseItemKind>?, includeTypes: List<BaseItemKind>?,
recursive: Boolean, recursive: Boolean,
): List<FindroidItem> = withContext(Dispatchers.IO) { ): List<FindroidItem> =
jellyfinApi.itemsApi.getItems( withContext(Dispatchers.IO) {
jellyfinApi.userId!!, jellyfinApi.itemsApi
personIds = personIds, .getItems(
includeItemTypes = includeTypes, jellyfinApi.userId!!,
recursive = recursive, personIds = personIds,
).content.items includeItemTypes = includeTypes,
.orEmpty() recursive = recursive,
.mapNotNull { ).content.items
it.toFindroidItem(this@JellyfinRepositoryImpl, database) .orEmpty()
} .mapNotNull {
} it.toFindroidItem(this@JellyfinRepositoryImpl, database)
}
}
override suspend fun getFavoriteItems(): List<FindroidItem> = override suspend fun getFavoriteItems(): List<FindroidItem> =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
jellyfinApi.itemsApi.getItems( jellyfinApi.itemsApi
jellyfinApi.userId!!, .getItems(
filters = listOf(ItemFilter.IS_FAVORITE), jellyfinApi.userId!!,
includeItemTypes = listOf( filters = listOf(ItemFilter.IS_FAVORITE),
BaseItemKind.MOVIE, includeItemTypes =
BaseItemKind.SERIES, listOf(
BaseItemKind.EPISODE, BaseItemKind.MOVIE,
), BaseItemKind.SERIES,
recursive = true, BaseItemKind.EPISODE,
).content.items ),
recursive = true,
).content.items
.orEmpty() .orEmpty()
.mapNotNull { it.toFindroidItem(this@JellyfinRepositoryImpl, database) } .mapNotNull { it.toFindroidItem(this@JellyfinRepositoryImpl, database) }
} }
override suspend fun getSearchItems(searchQuery: String): List<FindroidItem> = override suspend fun getSearchItems(searchQuery: String): List<FindroidItem> =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
jellyfinApi.itemsApi.getItems( jellyfinApi.itemsApi
jellyfinApi.userId!!, .getItems(
searchTerm = searchQuery, jellyfinApi.userId!!,
includeItemTypes = listOf( searchTerm = searchQuery,
BaseItemKind.MOVIE, includeItemTypes =
BaseItemKind.SERIES, listOf(
BaseItemKind.EPISODE, BaseItemKind.MOVIE,
), BaseItemKind.SERIES,
recursive = true, BaseItemKind.EPISODE,
).content.items ),
recursive = true,
).content.items
.orEmpty() .orEmpty()
.mapNotNull { it.toFindroidItem(this@JellyfinRepositoryImpl, database) } .mapNotNull { it.toFindroidItem(this@JellyfinRepositoryImpl, database) }
} }
override suspend fun getResumeItems(): List<FindroidItem> { override suspend fun getResumeItems(): List<FindroidItem> {
val items = withContext(Dispatchers.IO) { val items =
jellyfinApi.itemsApi.getResumeItems( withContext(Dispatchers.IO) {
jellyfinApi.userId!!, jellyfinApi.itemsApi
limit = 12, .getResumeItems(
includeItemTypes = listOf(BaseItemKind.MOVIE, BaseItemKind.EPISODE), jellyfinApi.userId!!,
).content.items.orEmpty() limit = 12,
} includeItemTypes = listOf(BaseItemKind.MOVIE, BaseItemKind.EPISODE),
).content.items
.orEmpty()
}
return items.mapNotNull { return items.mapNotNull {
it.toFindroidItem(this, database) it.toFindroidItem(this, database)
} }
} }
override suspend fun getLatestMedia(parentId: UUID): List<FindroidItem> { override suspend fun getLatestMedia(parentId: UUID): List<FindroidItem> {
val items = withContext(Dispatchers.IO) { val items =
jellyfinApi.userLibraryApi.getLatestMedia( withContext(Dispatchers.IO) {
jellyfinApi.userId!!, jellyfinApi.userLibraryApi
parentId = parentId, .getLatestMedia(
limit = 16, jellyfinApi.userId!!,
).content parentId = parentId,
} limit = 16,
).content
}
return items.mapNotNull { return items.mapNotNull {
it.toFindroidItem(this, database) it.toFindroidItem(this, database)
} }
} }
override suspend fun getSeasons(seriesId: UUID, offline: Boolean): List<FindroidSeason> = override suspend fun getSeasons(
seriesId: UUID,
offline: Boolean,
): List<FindroidSeason> =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
if (!offline) { if (!offline) {
jellyfinApi.showsApi.getSeasons(seriesId, jellyfinApi.userId!!).content.items jellyfinApi.showsApi
.getSeasons(seriesId, jellyfinApi.userId!!)
.content.items
.orEmpty() .orEmpty()
.map { it.toFindroidSeason(this@JellyfinRepositoryImpl) } .map { it.toFindroidSeason(this@JellyfinRepositoryImpl) }
} else { } else {
@ -260,12 +293,13 @@ class JellyfinRepositoryImpl(
override suspend fun getNextUp(seriesId: UUID?): List<FindroidEpisode> = override suspend fun getNextUp(seriesId: UUID?): List<FindroidEpisode> =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
jellyfinApi.showsApi.getNextUp( jellyfinApi.showsApi
jellyfinApi.userId!!, .getNextUp(
limit = 24, jellyfinApi.userId!!,
seriesId = seriesId, limit = 24,
enableResumable = false, seriesId = seriesId,
).content.items enableResumable = false,
).content.items
.orEmpty() .orEmpty()
.mapNotNull { it.toFindroidEpisode(this@JellyfinRepositoryImpl) } .mapNotNull { it.toFindroidEpisode(this@JellyfinRepositoryImpl) }
} }
@ -280,14 +314,15 @@ class JellyfinRepositoryImpl(
): List<FindroidEpisode> = ): List<FindroidEpisode> =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
if (!offline) { if (!offline) {
jellyfinApi.showsApi.getEpisodes( jellyfinApi.showsApi
seriesId, .getEpisodes(
jellyfinApi.userId!!, seriesId,
seasonId = seasonId, jellyfinApi.userId!!,
fields = fields, seasonId = seasonId,
startItemId = startItemId, fields = fields,
limit = limit, startItemId = startItemId,
).content.items limit = limit,
).content.items
.orEmpty() .orEmpty()
.mapNotNull { it.toFindroidEpisode(this@JellyfinRepositoryImpl, database) } .mapNotNull { it.toFindroidEpisode(this@JellyfinRepositoryImpl, database) }
} else { } else {
@ -295,39 +330,47 @@ class JellyfinRepositoryImpl(
} }
} }
override suspend fun getMediaSources(itemId: UUID, includePath: Boolean): List<FindroidSource> = override suspend fun getMediaSources(
itemId: UUID,
includePath: Boolean,
): List<FindroidSource> =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
val sources = mutableListOf<FindroidSource>() val sources = mutableListOf<FindroidSource>()
sources.addAll( sources.addAll(
jellyfinApi.mediaInfoApi.getPostedPlaybackInfo( jellyfinApi.mediaInfoApi
itemId, .getPostedPlaybackInfo(
PlaybackInfoDto(
userId = jellyfinApi.userId!!,
deviceProfile = DeviceProfile(
name = "Direct play all",
maxStaticBitrate = 1_000_000_000,
maxStreamingBitrate = 1_000_000_000,
codecProfiles = emptyList(),
containerProfiles = emptyList(),
directPlayProfiles = listOf(
DirectPlayProfile(type = DlnaProfileType.VIDEO),
DirectPlayProfile(type = DlnaProfileType.AUDIO),
),
transcodingProfiles = emptyList(),
subtitleProfiles = listOf(
SubtitleProfile("srt", SubtitleDeliveryMethod.EXTERNAL),
SubtitleProfile("ass", SubtitleDeliveryMethod.EXTERNAL),
),
),
maxStreamingBitrate = 1_000_000_000,
),
).content.mediaSources.map {
it.toFindroidSource(
this@JellyfinRepositoryImpl,
itemId, itemId,
includePath, PlaybackInfoDto(
) userId = jellyfinApi.userId!!,
}, deviceProfile =
DeviceProfile(
name = "Direct play all",
maxStaticBitrate = 1_000_000_000,
maxStreamingBitrate = 1_000_000_000,
codecProfiles = emptyList(),
containerProfiles = emptyList(),
directPlayProfiles =
listOf(
DirectPlayProfile(type = DlnaProfileType.VIDEO),
DirectPlayProfile(type = DlnaProfileType.AUDIO),
),
transcodingProfiles = emptyList(),
subtitleProfiles =
listOf(
SubtitleProfile("srt", SubtitleDeliveryMethod.EXTERNAL),
SubtitleProfile("ass", SubtitleDeliveryMethod.EXTERNAL),
),
),
maxStreamingBitrate = 1_000_000_000,
),
).content.mediaSources
.map {
it.toFindroidSource(
this@JellyfinRepositoryImpl,
itemId,
includePath,
)
},
) )
sources.addAll( sources.addAll(
database.getSources(itemId).map { it.toFindroidSource(database) }, database.getSources(itemId).map { it.toFindroidSource(database) },
@ -335,14 +378,33 @@ class JellyfinRepositoryImpl(
sources sources
} }
override suspend fun getStreamUrl(itemId: UUID, mediaSourceId: String): String = override suspend fun getStreamUrl(
itemId: UUID,
mediaSourceId: String,
playSessionId: String?,
): String =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
val deviceId = getDeviceId()
try { try {
jellyfinApi.videosApi.getVideoStreamUrl( val url =
itemId, if (playSessionId != null) {
static = true, jellyfinApi.videosApi.getVideoStreamUrl(
mediaSourceId = mediaSourceId, itemId,
) static = true,
mediaSourceId = mediaSourceId,
playSessionId = playSessionId,
deviceId = deviceId,
context = EncodingContext.STREAMING,
)
} else {
jellyfinApi.videosApi.getVideoStreamUrl(
itemId,
static = true,
mediaSourceId = mediaSourceId,
deviceId = deviceId,
)
}
url
} catch (e: Exception) { } catch (e: Exception) {
Timber.e(e) Timber.e(e)
"" ""
@ -362,33 +424,36 @@ class JellyfinRepositoryImpl(
pathParameters["itemId"] = itemId pathParameters["itemId"] = itemId
try { try {
val segmentToConvert = jellyfinApi.api.get<FindroidSegments>( val segmentToConvert =
"/Episode/{itemId}/IntroSkipperSegments", jellyfinApi.api
pathParameters, .get<FindroidSegments>(
).content "/Episode/{itemId}/IntroSkipperSegments",
pathParameters,
).content
val segmentConverted = mutableListOf( val segmentConverted =
segmentToConvert.intro!!.let { mutableListOf(
FindroidSegment( segmentToConvert.intro!!.let {
type = "intro", FindroidSegment(
skip = true, type = "intro",
startTime = it.startTime, skip = true,
endTime = it.endTime, startTime = it.startTime,
showAt = it.showAt, endTime = it.endTime,
hideAt = it.hideAt, showAt = it.showAt,
) hideAt = it.hideAt,
}, )
segmentToConvert.credit!!.let { },
FindroidSegment( segmentToConvert.credit!!.let {
type = "credit", FindroidSegment(
skip = true, type = "credit",
startTime = it.startTime, skip = true,
endTime = it.endTime, startTime = it.startTime,
showAt = it.showAt, endTime = it.endTime,
hideAt = it.hideAt, showAt = it.showAt,
) hideAt = it.hideAt,
}, )
) },
)
Timber.tag("SegmentInfo").d("segmentToConvert: %s", segmentToConvert) Timber.tag("SegmentInfo").d("segmentToConvert: %s", segmentToConvert)
Timber.tag("SegmentInfo").d("segmentConverted: %s", segmentConverted) Timber.tag("SegmentInfo").d("segmentConverted: %s", segmentConverted)
@ -398,7 +463,11 @@ class JellyfinRepositoryImpl(
} }
} }
override suspend fun getTrickplayData(itemId: UUID, width: Int, index: Int): ByteArray? = override suspend fun getTrickplayData(
itemId: UUID,
width: Int,
index: Int,
): ByteArray? =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
try { try {
try { try {
@ -406,9 +475,13 @@ class JellyfinRepositoryImpl(
if (sources != null) { if (sources != null) {
return@withContext File(sources.first(), index.toString()).readBytes() return@withContext File(sources.first(), index.toString()).readBytes()
} }
} catch (_: Exception) { } } catch (_: Exception) {
}
return@withContext jellyfinApi.trickplayApi.getTrickplayTileImage(itemId, width, index).content.toByteArray() return@withContext jellyfinApi.trickplayApi
.getTrickplayTileImage(itemId, width, index)
.content
.toByteArray()
} catch (e: Exception) { } catch (e: Exception) {
return@withContext null return@withContext null
} }
@ -419,21 +492,22 @@ class JellyfinRepositoryImpl(
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
jellyfinApi.sessionApi.postCapabilities( jellyfinApi.sessionApi.postCapabilities(
playableMediaTypes = listOf(MediaType.VIDEO), playableMediaTypes = listOf(MediaType.VIDEO),
supportedCommands = listOf( supportedCommands =
GeneralCommandType.VOLUME_UP, listOf(
GeneralCommandType.VOLUME_DOWN, GeneralCommandType.VOLUME_UP,
GeneralCommandType.TOGGLE_MUTE, GeneralCommandType.VOLUME_DOWN,
GeneralCommandType.SET_AUDIO_STREAM_INDEX, GeneralCommandType.TOGGLE_MUTE,
GeneralCommandType.SET_SUBTITLE_STREAM_INDEX, GeneralCommandType.SET_AUDIO_STREAM_INDEX,
GeneralCommandType.MUTE, GeneralCommandType.SET_SUBTITLE_STREAM_INDEX,
GeneralCommandType.UNMUTE, GeneralCommandType.MUTE,
GeneralCommandType.SET_VOLUME, GeneralCommandType.UNMUTE,
GeneralCommandType.DISPLAY_MESSAGE, GeneralCommandType.SET_VOLUME,
GeneralCommandType.PLAY, GeneralCommandType.DISPLAY_MESSAGE,
GeneralCommandType.PLAY_STATE, GeneralCommandType.PLAY,
GeneralCommandType.PLAY_NEXT, GeneralCommandType.PLAY_STATE,
GeneralCommandType.PLAY_MEDIA_SOURCE, GeneralCommandType.PLAY_NEXT,
), GeneralCommandType.PLAY_MEDIA_SOURCE,
),
supportsMediaControl = true, supportsMediaControl = true,
) )
} }
@ -555,140 +629,218 @@ class JellyfinRepositoryImpl(
} }
} }
override suspend fun getUserConfiguration(): UserConfiguration = withContext(Dispatchers.IO) { override suspend fun getUserConfiguration(): UserConfiguration =
jellyfinApi.userApi.getCurrentUser().content.configuration!! withContext(Dispatchers.IO) {
} jellyfinApi.userApi
.getCurrentUser()
.content.configuration!!
}
override suspend fun getDownloads(): List<FindroidItem> = override suspend fun getDownloads(): List<FindroidItem> =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
val items = mutableListOf<FindroidItem>() val items = mutableListOf<FindroidItem>()
items.addAll( items.addAll(
database.getMoviesByServerId(appPreferences.currentServer!!) database
.getMoviesByServerId(appPreferences.currentServer!!)
.map { it.toFindroidMovie(database, jellyfinApi.userId!!) }, .map { it.toFindroidMovie(database, jellyfinApi.userId!!) },
) )
items.addAll( items.addAll(
database.getShowsByServerId(appPreferences.currentServer!!) database
.getShowsByServerId(appPreferences.currentServer!!)
.map { it.toFindroidShow(database, jellyfinApi.userId!!) }, .map { it.toFindroidShow(database, jellyfinApi.userId!!) },
) )
items items
} }
override fun getUserId(): UUID { override fun getUserId(): UUID = jellyfinApi.userId!!
return jellyfinApi.userId!!
}
override suspend fun buildDeviceProfile(
override suspend fun getVideoTranscodeBitRate(transcodeResolution: Int): Pair<Int, Int> { maxBitrate: Int,
return when (transcodeResolution) { container: String,
1080 -> 8000000 to 384000 // Adjusted for 1080p context: EncodingContext,
720 -> 2000000 to 384000 // Adjusted for 720p ): DeviceProfile {
480 -> 1000000 to 384000 // Adjusted for 480p val deviceProfile =
360 -> 800000 to 128000 // Adjusted for 360p ClientCapabilitiesDto(
else -> 8000000 to 384000 supportedCommands = emptyList(),
} playableMediaTypes =
} listOf(
MediaType.VIDEO,
override suspend fun buildDeviceProfile(maxBitrate: Int, container: String, context: EncodingContext): DeviceProfile { MediaType.AUDIO,
val deviceProfile = ClientCapabilitiesDto( MediaType.UNKNOWN,
supportedCommands = emptyList(), ),
playableMediaTypes = emptyList(), supportsMediaControl = true,
supportsMediaControl = true, supportsPersistentIdentifier = true,
supportsPersistentIdentifier = true, deviceProfile =
deviceProfile = DeviceProfile( DeviceProfile(
name = "AnanasUser", name = "AnanasUser",
id = getUserId().toString(), id = getUserId().toString(),
maxStaticBitrate = maxBitrate, maxStaticBitrate = maxBitrate,
maxStreamingBitrate = maxBitrate, maxStreamingBitrate = maxBitrate,
codecProfiles = emptyList(), codecProfiles = emptyList(),
containerProfiles = listOf(), containerProfiles = listOf(),
directPlayProfiles = listOf( directPlayProfiles =
DirectPlayProfile(type = DlnaProfileType.VIDEO), listOf(
DirectPlayProfile(type = DlnaProfileType.AUDIO), DirectPlayProfile(type = DlnaProfileType.VIDEO),
), DirectPlayProfile(type = DlnaProfileType.AUDIO),
transcodingProfiles = listOf( ),
TranscodingProfile( transcodingProfiles =
container = container, listOf(
context = context, TranscodingProfile(
protocol = MediaStreamProtocol.HLS, container = container,
audioCodec = "aac,ac3,eac3", context = context,
videoCodec = "hevc,h264", protocol = MediaStreamProtocol.HLS,
type = DlnaProfileType.VIDEO, audioCodec = "aac,ac3,eac3",
conditions = listOf( videoCodec = "hevc,h264",
ProfileCondition( type = DlnaProfileType.VIDEO,
condition = ProfileConditionType.LESS_THAN_EQUAL, conditions =
property = ProfileConditionValue.VIDEO_BITRATE, listOf(
value = "8000000", ProfileCondition(
isRequired = true, condition = ProfileConditionType.LESS_THAN_EQUAL,
) property = ProfileConditionValue.VIDEO_BITRATE,
), value = "8000000",
copyTimestamps = true, isRequired = true,
enableSubtitlesInManifest = true, ),
transcodeSeekInfo = TranscodeSeekInfo.AUTO, ),
copyTimestamps = true,
enableSubtitlesInManifest = true,
transcodeSeekInfo = TranscodeSeekInfo.AUTO,
),
),
subtitleProfiles =
listOf(
SubtitleProfile("srt", SubtitleDeliveryMethod.EXTERNAL),
SubtitleProfile("ass", SubtitleDeliveryMethod.EXTERNAL),
SubtitleProfile("sub", SubtitleDeliveryMethod.EXTERNAL),
SubtitleProfile("vtt", SubtitleDeliveryMethod.EXTERNAL),
SubtitleProfile("ssa", SubtitleDeliveryMethod.EXTERNAL),
SubtitleProfile("pgs", SubtitleDeliveryMethod.EXTERNAL),
SubtitleProfile("dvb_teletext", SubtitleDeliveryMethod.EXTERNAL),
SubtitleProfile("dvd_subtitle", SubtitleDeliveryMethod.EXTERNAL),
),
), ),
),
subtitleProfiles = listOf(
SubtitleProfile("srt", SubtitleDeliveryMethod.EXTERNAL),
SubtitleProfile("ass", SubtitleDeliveryMethod.EXTERNAL),
SubtitleProfile("sub", SubtitleDeliveryMethod.EXTERNAL),
SubtitleProfile("vtt", SubtitleDeliveryMethod.EXTERNAL),
SubtitleProfile("ssa", SubtitleDeliveryMethod.EXTERNAL),
SubtitleProfile("pgs", SubtitleDeliveryMethod.EXTERNAL),
SubtitleProfile("dvb_teletext", SubtitleDeliveryMethod.EXTERNAL),
SubtitleProfile("dvd_subtitle", SubtitleDeliveryMethod.EXTERNAL)
),
) )
)
return deviceProfile.deviceProfile!! return deviceProfile.deviceProfile!!
} }
override suspend fun getPostedPlaybackInfo(
override suspend fun getPostedPlaybackInfo(itemId: UUID ,enableDirectStream: Boolean ,deviceProfile: DeviceProfile ,maxBitrate: Int): Response<PlaybackInfoResponse> { itemId: UUID,
val playbackInfo = jellyfinApi.mediaInfoApi.getPostedPlaybackInfo( enableDirectStream: Boolean,
itemId = itemId, deviceProfile: DeviceProfile,
PlaybackInfoDto( maxBitrate: Int,
userId = jellyfinApi.userId!!, ): Response<PlaybackInfoResponse> {
enableTranscoding = true, val playbackInfo =
enableDirectPlay = false, jellyfinApi.mediaInfoApi.getPostedPlaybackInfo(
enableDirectStream = enableDirectStream, itemId = itemId,
autoOpenLiveStream = true, PlaybackInfoDto(
deviceProfile = deviceProfile, userId = jellyfinApi.userId!!,
allowAudioStreamCopy = true, enableTranscoding = true,
allowVideoStreamCopy = true, enableDirectPlay = false,
maxStreamingBitrate = maxBitrate, enableDirectStream = enableDirectStream,
autoOpenLiveStream = true,
deviceProfile = buildDeviceProfile(maxBitrate, "ts", EncodingContext.STREAMING),
allowAudioStreamCopy = true,
allowVideoStreamCopy = true,
maxStreamingBitrate = maxBitrate,
),
) )
)
return playbackInfo return playbackInfo
} }
override suspend fun getVideoStreambyContainerUrl(itemId: UUID, mediaSourceId: String, playSessionId: String, videoBitrate: Int, container: String): String { override suspend fun getVideoStreambyContainerUrl(
val url = jellyfinApi.videosApi.getVideoStreamByContainerUrl( itemId: UUID,
itemId, deviceId: String,
static = false, mediaSourceId: String,
mediaSourceId = mediaSourceId, playSessionId: String,
playSessionId = playSessionId, videoBitrate: Int,
videoBitRate = videoBitrate, container: String,
audioBitRate = 384000, maxHeight: Int,
videoCodec = "hevc", ): String {
audioCodec = "aac,ac3,eac3", val url =
container = container, jellyfinApi.videosApi.getVideoStreamByContainerUrl(
startTimeTicks = 0, itemId,
copyTimestamps = true, static = false,
) deviceId = deviceId,
mediaSourceId = mediaSourceId,
playSessionId = playSessionId,
videoBitRate = videoBitrate,
maxHeight = maxHeight,
audioBitRate = 328000,
videoCodec = appPreferences.transcodeCodec,
audioCodec = "aac,ac3,eac3",
container = container,
startTimeTicks = 0,
copyTimestamps = true,
subtitleMethod = SubtitleDeliveryMethod.EXTERNAL,
)
return url return url
} }
override suspend fun getDeviceId(): String { override suspend fun getTranscodedVideoStream(
val deviceId = jellyfinApi.devicesApi.getDevices(getUserId()) itemId: UUID,
return deviceId.toString() deviceId: String,
mediaSourceId: String,
playSessionId: String,
videoBitrate: Int,
): String {
val isAuto = videoBitrate == VideoQuality.getBitrate(VideoQuality.Auto)
val url: String
try {
url =
if (!isAuto) {
jellyfinApi.api.dynamicHlsApi.getMasterHlsVideoPlaylistUrl(
itemId,
static = false,
deviceId = deviceId,
mediaSourceId = mediaSourceId,
playSessionId = playSessionId,
videoBitRate = videoBitrate,
enableAdaptiveBitrateStreaming = false,
audioBitRate = 328000,
videoCodec = appPreferences.transcodeCodec,
audioCodec = "aac,ac3,eac3",
startTimeTicks = 0,
copyTimestamps = true,
subtitleMethod = SubtitleDeliveryMethod.EXTERNAL,
context = EncodingContext.STREAMING,
segmentContainer = "ts",
transcodeReasons = "ContainerBitrateExceedsLimit",
)
} else {
jellyfinApi.api.dynamicHlsApi.getMasterHlsVideoPlaylistUrl(
itemId,
static = false,
deviceId = deviceId,
mediaSourceId = mediaSourceId,
playSessionId = playSessionId,
enableAdaptiveBitrateStreaming = true,
videoCodec = appPreferences.transcodeCodec,
audioCodec = "aac,ac3,eac3",
startTimeTicks = 0,
copyTimestamps = true,
subtitleMethod = SubtitleDeliveryMethod.EXTERNAL,
context = EncodingContext.STREAMING,
segmentContainer = "ts",
transcodeReasons = "ContainerBitrateExceedsLimit",
)
}
} catch (e: Exception) {
Timber.e(e)
throw e
}
return url
} }
override suspend fun getDeviceId(): String = jellyfinApi.api.deviceInfo.id
override suspend fun stopEncodingProcess(playSessionId: String) { override suspend fun stopEncodingProcess(playSessionId: String) {
val deviceId = getDeviceId()
jellyfinApi.api.hlsSegmentApi.stopEncodingProcess( jellyfinApi.api.hlsSegmentApi.stopEncodingProcess(
deviceId = getDeviceId(), deviceId = deviceId,
playSessionId = playSessionId playSessionId = playSessionId,
) )
} }
override suspend fun getAccessToken(): String? {
return jellyfinApi.api.accessToken
}
} }

View file

@ -42,14 +42,9 @@ class JellyfinRepositoryOfflineImpl(
private val database: ServerDatabaseDao, private val database: ServerDatabaseDao,
private val appPreferences: AppPreferences, private val appPreferences: AppPreferences,
) : JellyfinRepository { ) : JellyfinRepository {
override suspend fun getPublicSystemInfo(): PublicSystemInfo = throw Exception("System info not available in offline mode")
override suspend fun getPublicSystemInfo(): PublicSystemInfo { override suspend fun getUserViews(): List<BaseItemDto> = emptyList()
throw Exception("System info not available in offline mode")
}
override suspend fun getUserViews(): List<BaseItemDto> {
return emptyList()
}
override suspend fun getItem(itemId: UUID): BaseItemDto { override suspend fun getItem(itemId: UUID): BaseItemDto {
TODO("Not yet implemented") TODO("Not yet implemented")
@ -113,38 +108,61 @@ class JellyfinRepositoryOfflineImpl(
TODO("Not yet implemented") TODO("Not yet implemented")
} }
override suspend fun getSearchItems(searchQuery: String): List<FindroidItem> { override suspend fun getSearchItems(searchQuery: String): List<FindroidItem> =
return withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
val movies = database.searchMovies(appPreferences.currentServer!!, searchQuery).map { it.toFindroidMovie(database, jellyfinApi.userId!!) } val movies =
val shows = database.searchShows(appPreferences.currentServer!!, searchQuery).map { it.toFindroidShow(database, jellyfinApi.userId!!) } database
val episodes = database.searchEpisodes(appPreferences.currentServer!!, searchQuery).map { it.toFindroidEpisode(database, jellyfinApi.userId!!) } .searchMovies(
appPreferences.currentServer!!,
searchQuery,
).map { it.toFindroidMovie(database, jellyfinApi.userId!!) }
val shows =
database
.searchShows(
appPreferences.currentServer!!,
searchQuery,
).map { it.toFindroidShow(database, jellyfinApi.userId!!) }
val episodes =
database.searchEpisodes(appPreferences.currentServer!!, searchQuery).map {
it.toFindroidEpisode(database, jellyfinApi.userId!!)
}
movies + shows + episodes movies + shows + episodes
} }
}
override suspend fun getResumeItems(): List<FindroidItem> { override suspend fun getResumeItems(): List<FindroidItem> =
return withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
val movies = database.getMoviesByServerId(appPreferences.currentServer!!).map { it.toFindroidMovie(database, jellyfinApi.userId!!) }.filter { it.playbackPositionTicks > 0 } val movies =
val episodes = database.getEpisodesByServerId(appPreferences.currentServer!!).map { it.toFindroidEpisode(database, jellyfinApi.userId!!) }.filter { it.playbackPositionTicks > 0 } database
.getMoviesByServerId(appPreferences.currentServer!!)
.map {
it.toFindroidMovie(database, jellyfinApi.userId!!)
}.filter { it.playbackPositionTicks > 0 }
val episodes =
database
.getEpisodesByServerId(appPreferences.currentServer!!)
.map {
it.toFindroidEpisode(database, jellyfinApi.userId!!)
}.filter { it.playbackPositionTicks > 0 }
movies + episodes movies + episodes
} }
}
override suspend fun getLatestMedia(parentId: UUID): List<FindroidItem> { override suspend fun getLatestMedia(parentId: UUID): List<FindroidItem> = emptyList()
return emptyList()
}
override suspend fun getSeasons(seriesId: UUID, offline: Boolean): List<FindroidSeason> = override suspend fun getSeasons(
seriesId: UUID,
offline: Boolean,
): List<FindroidSeason> =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
database.getSeasonsByShowId(seriesId).map { it.toFindroidSeason(database, jellyfinApi.userId!!) } database.getSeasonsByShowId(seriesId).map { it.toFindroidSeason(database, jellyfinApi.userId!!) }
} }
override suspend fun getNextUp(seriesId: UUID?): List<FindroidEpisode> { override suspend fun getNextUp(seriesId: UUID?): List<FindroidEpisode> =
return withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
val result = mutableListOf<FindroidEpisode>() val result = mutableListOf<FindroidEpisode>()
val shows = database.getShowsByServerId(appPreferences.currentServer!!).filter { val shows =
if (seriesId != null) it.id == seriesId else true database.getShowsByServerId(appPreferences.currentServer!!).filter {
} if (seriesId != null) it.id == seriesId else true
}
for (show in shows) { for (show in shows) {
val episodes = database.getEpisodesByShowId(show.id).map { it.toFindroidEpisode(database, jellyfinApi.userId!!) } val episodes = database.getEpisodesByShowId(show.id).map { it.toFindroidEpisode(database, jellyfinApi.userId!!) }
val indexOfLastPlayed = episodes.indexOfLast { it.played } val indexOfLastPlayed = episodes.indexOfLast { it.played }
@ -156,7 +174,6 @@ class JellyfinRepositoryOfflineImpl(
} }
result.filter { it.playbackPositionTicks == 0L } result.filter { it.playbackPositionTicks == 0L }
} }
}
override suspend fun getEpisodes( override suspend fun getEpisodes(
seriesId: UUID, seriesId: UUID,
@ -172,12 +189,19 @@ class JellyfinRepositoryOfflineImpl(
items items
} }
override suspend fun getMediaSources(itemId: UUID, includePath: Boolean): List<FindroidSource> = override suspend fun getMediaSources(
itemId: UUID,
includePath: Boolean,
): List<FindroidSource> =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
database.getSources(itemId).map { it.toFindroidSource(database) } database.getSources(itemId).map { it.toFindroidSource(database) }
} }
override suspend fun getStreamUrl(itemId: UUID, mediaSourceId: String): String { override suspend fun getStreamUrl(
itemId: UUID,
mediaSourceId: String,
playSessionId: String?,
): String {
TODO("Not yet implemented") TODO("Not yet implemented")
} }
@ -186,7 +210,11 @@ class JellyfinRepositoryOfflineImpl(
database.getSegments(itemId)?.toFindroidSegments() database.getSegments(itemId)?.toFindroidSegments()
} }
override suspend fun getTrickplayData(itemId: UUID, width: Int, index: Int): ByteArray? = override suspend fun getTrickplayData(
itemId: UUID,
width: Int,
index: Int,
): ByteArray? =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
try { try {
val sources = File(context.filesDir, "trickplay/$itemId").listFiles() ?: return@withContext null val sources = File(context.filesDir, "trickplay/$itemId").listFiles() ?: return@withContext null
@ -200,7 +228,11 @@ class JellyfinRepositoryOfflineImpl(
override suspend fun postPlaybackStart(itemId: UUID) {} override suspend fun postPlaybackStart(itemId: UUID) {}
override suspend fun postPlaybackStop(itemId: UUID, positionTicks: Long, playedPercentage: Int) { override suspend fun postPlaybackStop(
itemId: UUID,
positionTicks: Long,
playedPercentage: Int,
) {
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
when { when {
playedPercentage < 10 -> { playedPercentage < 10 -> {
@ -260,35 +292,31 @@ class JellyfinRepositoryOfflineImpl(
} }
} }
override fun getBaseUrl(): String { override fun getBaseUrl(): String = ""
return ""
}
override suspend fun updateDeviceName(name: String) { override suspend fun updateDeviceName(name: String) {
TODO("Not yet implemented") TODO("Not yet implemented")
} }
override suspend fun getUserConfiguration(): UserConfiguration? { override suspend fun getUserConfiguration(): UserConfiguration? = null
return null
}
override suspend fun getDownloads(): List<FindroidItem> = override suspend fun getDownloads(): List<FindroidItem> =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
val items = mutableListOf<FindroidItem>() val items = mutableListOf<FindroidItem>()
items.addAll( items.addAll(
database.getMoviesByServerId(appPreferences.currentServer!!) database
.getMoviesByServerId(appPreferences.currentServer!!)
.map { it.toFindroidMovie(database, jellyfinApi.userId!!) }, .map { it.toFindroidMovie(database, jellyfinApi.userId!!) },
) )
items.addAll( items.addAll(
database.getShowsByServerId(appPreferences.currentServer!!) database
.getShowsByServerId(appPreferences.currentServer!!)
.map { it.toFindroidShow(database, jellyfinApi.userId!!) }, .map { it.toFindroidShow(database, jellyfinApi.userId!!) },
) )
items items
} }
override fun getUserId(): UUID { override fun getUserId(): UUID = jellyfinApi.userId!!
return jellyfinApi.userId!!
}
override suspend fun getDeviceId(): String { override suspend fun getDeviceId(): String {
TODO("Not yet implemented") TODO("Not yet implemented")
@ -297,17 +325,29 @@ class JellyfinRepositoryOfflineImpl(
override suspend fun buildDeviceProfile( override suspend fun buildDeviceProfile(
maxBitrate: Int, maxBitrate: Int,
container: String, container: String,
context: EncodingContext context: EncodingContext,
): DeviceProfile { ): DeviceProfile {
TODO("Not yet implemented") TODO("Not yet implemented")
} }
override suspend fun getVideoStreambyContainerUrl( override suspend fun getVideoStreambyContainerUrl(
itemId: UUID, itemId: UUID,
deviceId: String,
mediaSourceId: String,
playSessionId: String,
videoBitrate: Int,
container: String,
maxHeight: Int,
): String {
TODO("Not yet implemented")
}
override suspend fun getTranscodedVideoStream(
itemId: UUID,
deviceId: String,
mediaSourceId: String, mediaSourceId: String,
playSessionId: String, playSessionId: String,
videoBitrate: Int, videoBitrate: Int,
container: String
): String { ): String {
TODO("Not yet implemented") TODO("Not yet implemented")
} }
@ -316,7 +356,7 @@ class JellyfinRepositoryOfflineImpl(
itemId: UUID, itemId: UUID,
enableDirectStream: Boolean, enableDirectStream: Boolean,
deviceProfile: DeviceProfile, deviceProfile: DeviceProfile,
maxBitrate: Int maxBitrate: Int,
): Response<PlaybackInfoResponse> { ): Response<PlaybackInfoResponse> {
TODO("Not yet implemented") TODO("Not yet implemented")
} }
@ -325,7 +365,7 @@ class JellyfinRepositoryOfflineImpl(
TODO("Not yet implemented") TODO("Not yet implemented")
} }
override suspend fun getVideoTranscodeBitRate(transcodeResolution: Int): Pair<Int, Int> { override suspend fun getAccessToken(): String? {
TODO("Not yet implemented") TODO("Not yet implemented")
} }
} }

View file

@ -38,6 +38,7 @@ libmpv = "0.3.0"
material = "1.12.0" material = "1.12.0"
media3-ffmpeg-decoder = "1.3.1+2" media3-ffmpeg-decoder = "1.3.1+2"
timber = "5.0.1" timber = "5.0.1"
markwon = "4.6.2"
[libraries] [libraries]
aboutlibraries-core = { group = "com.mikepenz", name = "aboutlibraries-core", version.ref = "aboutlibraries" } aboutlibraries-core = { group = "com.mikepenz", name = "aboutlibraries-core", version.ref = "aboutlibraries" }
@ -99,6 +100,7 @@ material = { group = "com.google.android.material", name = "material", version.r
media3-ffmpeg-decoder = { group = "org.jellyfin.media3", name = "media3-ffmpeg-decoder", version.ref = "media3-ffmpeg-decoder" } media3-ffmpeg-decoder = { group = "org.jellyfin.media3", name = "media3-ffmpeg-decoder", version.ref = "media3-ffmpeg-decoder" }
timber = { group = "com.jakewharton.timber", name = "timber", version.ref = "timber" } timber = { group = "com.jakewharton.timber", name = "timber", version.ref = "timber" }
kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinx-serialization" } kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinx-serialization" }
markwon = { group = "io.noties.markwon", name = "core", version.ref = "markwon" }
[plugins] [plugins]
aboutlibraries = { id = "com.mikepenz.aboutlibraries.plugin", version.ref = "aboutlibraries" } aboutlibraries = { id = "com.mikepenz.aboutlibraries.plugin", version.ref = "aboutlibraries" }

View file

@ -1,4 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<lint> <lint>
<issue id="MissingTranslation" severity="ignore" /> <issue id="MissingTranslation" severity="ignore" />
</lint> </lint>

View file

@ -0,0 +1,20 @@
package com.nomadics9.ananas
import androidx.media3.common.MimeTypes
public fun setSubtitlesMimeTypes(codec: String): String {
return when (codec) {
"subrip" -> MimeTypes.APPLICATION_SUBRIP
"webvtt" -> MimeTypes.TEXT_VTT
"ssa" -> MimeTypes.TEXT_SSA
"pgs" -> MimeTypes.APPLICATION_PGS
"ass" -> MimeTypes.TEXT_SSA
"srt" -> MimeTypes.APPLICATION_SUBRIP
"vtt" -> MimeTypes.TEXT_VTT
"ttml" -> MimeTypes.APPLICATION_TTML
"dfxp" -> MimeTypes.APPLICATION_TTML
"stl" -> MimeTypes.APPLICATION_TTML
"sbv" -> MimeTypes.APPLICATION_SUBRIP
else -> MimeTypes.TEXT_UNKNOWN
}
}

View file

@ -18,6 +18,7 @@ import com.nomadics9.ananas.models.PlayerChapter
import com.nomadics9.ananas.models.PlayerItem import com.nomadics9.ananas.models.PlayerItem
import com.nomadics9.ananas.models.TrickplayInfo import com.nomadics9.ananas.models.TrickplayInfo
import com.nomadics9.ananas.repository.JellyfinRepository import com.nomadics9.ananas.repository.JellyfinRepository
import com.nomadics9.ananas.setSubtitlesMimeTypes
import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
@ -136,7 +137,22 @@ class PlayerViewModel @Inject internal constructor(
} else { } else {
mediaSources[mediaSourceIndex] mediaSources[mediaSourceIndex]
} }
val externalSubtitles = mediaSource.mediaStreams // Embedded Sub externally for offline playback
val externalSubtitles = if (mediaSource.type.toString() == "LOCAL" ) {
mediaSource.mediaStreams
.filter { mediaStream ->
mediaStream.type == MediaStreamType.SUBTITLE && !mediaStream.path.isNullOrBlank()
}
.map { mediaStream ->
ExternalSubtitle(
mediaStream.title,
mediaStream.language,
Uri.parse(mediaStream.path!!),
setSubtitlesMimeTypes(mediaStream.codec),
)
}
}else {
mediaSource.mediaStreams
.filter { mediaStream -> .filter { mediaStream ->
mediaStream.isExternal && mediaStream.type == MediaStreamType.SUBTITLE && !mediaStream.path.isNullOrBlank() mediaStream.isExternal && mediaStream.type == MediaStreamType.SUBTITLE && !mediaStream.path.isNullOrBlank()
} }
@ -145,14 +161,10 @@ class PlayerViewModel @Inject internal constructor(
mediaStream.title, mediaStream.title,
mediaStream.language, mediaStream.language,
Uri.parse(mediaStream.path!!), Uri.parse(mediaStream.path!!),
when (mediaStream.codec) { setSubtitlesMimeTypes(mediaStream.codec)
"subrip" -> MimeTypes.APPLICATION_SUBRIP
"webvtt" -> MimeTypes.APPLICATION_SUBRIP
"ass" -> MimeTypes.TEXT_SSA
else -> MimeTypes.TEXT_UNKNOWN
},
) )
} }
}
val trickplayInfo = when (this) { val trickplayInfo = when (this) {
is FindroidSources -> { is FindroidSources -> {
this.trickplayInfo?.get(mediaSource.id)?.let { this.trickplayInfo?.get(mediaSource.id)?.let {

View file

@ -121,6 +121,11 @@ constructor(
Constants.NETWORK_DEFAULT_SOCKET_TIMEOUT.toString(), Constants.NETWORK_DEFAULT_SOCKET_TIMEOUT.toString(),
)!!.toLongOrNull() ?: Constants.NETWORK_DEFAULT_SOCKET_TIMEOUT )!!.toLongOrNull() ?: Constants.NETWORK_DEFAULT_SOCKET_TIMEOUT
val transcodeCodec get() = sharedPreferences.getString(
Constants.PREF_NETWORK_CODEC,
Constants.NETWORK_DEFAULT_CODEC,
)
// Cache // Cache
val imageCache get() = sharedPreferences.getBoolean( val imageCache get() = sharedPreferences.getBoolean(
Constants.PREF_IMAGE_CACHE, Constants.PREF_IMAGE_CACHE,
@ -150,8 +155,9 @@ constructor(
val downloadQualityDefault get() = sharedPreferences.getBoolean( val downloadQualityDefault get() = sharedPreferences.getBoolean(
Constants.PREF_DOWNLOADS_QUALITY_DEFAULT, Constants.PREF_DOWNLOADS_QUALITY_DEFAULT,
false false,
) )
// Sorting // Sorting
var sortBy: String var sortBy: String

View file

@ -43,6 +43,7 @@ object Constants {
const val PREF_NETWORK_REQUEST_TIMEOUT = "pref_network_request_timeout" const val PREF_NETWORK_REQUEST_TIMEOUT = "pref_network_request_timeout"
const val PREF_NETWORK_CONNECT_TIMEOUT = "pref_network_connect_timeout" const val PREF_NETWORK_CONNECT_TIMEOUT = "pref_network_connect_timeout"
const val PREF_NETWORK_SOCKET_TIMEOUT = "pref_network_socket_timeout" const val PREF_NETWORK_SOCKET_TIMEOUT = "pref_network_socket_timeout"
const val PREF_NETWORK_CODEC = "pref_network_codec"
const val PREF_DOWNLOADS_MOBILE_DATA = "pref_downloads_mobile_data" const val PREF_DOWNLOADS_MOBILE_DATA = "pref_downloads_mobile_data"
const val PREF_DOWNLOADS_ROAMING = "pref_downloads_roaming" const val PREF_DOWNLOADS_ROAMING = "pref_downloads_roaming"
const val PREF_DOWNLOADS_QUALITY = "pref_downloads_quality" const val PREF_DOWNLOADS_QUALITY = "pref_downloads_quality"
@ -63,6 +64,7 @@ object Constants {
const val NETWORK_DEFAULT_REQUEST_TIMEOUT = 30_000L const val NETWORK_DEFAULT_REQUEST_TIMEOUT = 30_000L
const val NETWORK_DEFAULT_CONNECT_TIMEOUT = 6_000L const val NETWORK_DEFAULT_CONNECT_TIMEOUT = 6_000L
const val NETWORK_DEFAULT_SOCKET_TIMEOUT = 10_000L const val NETWORK_DEFAULT_SOCKET_TIMEOUT = 10_000L
const val NETWORK_DEFAULT_CODEC = "h264"
// sorting // sorting
// This values must correspond to a SortString from [SortBy] // This values must correspond to a SortString from [SortBy]

1
version Normal file
View file

@ -0,0 +1 @@
0.10.6