Skip to content

StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.

Jellyfin provider support

root297a25be783b
diff --git a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
index 3a71ea77..8321c587 100644
--- a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
+++ b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
@@ -7,6 +7,9 @@ import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory
import com.streamvault.app.BuildConfig
import com.streamvault.data.local.StreamVaultDatabase
import com.streamvault.data.local.dao.*
+import com.streamvault.data.remote.jellyfin.JellyfinProvider
+import com.google.gson.Gson
+import okhttp3.OkHttpClient
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
@@ -103,6 +106,9 @@ object DatabaseModule {
// All future schema changes MUST add a corresponding Migration in StreamVaultDatabase.
.build()
+ @Provides @Singleton
+ fun provideJellyfinProvider(okHttpClient: OkHttpClient, gson: Gson): JellyfinProvider = JellyfinProvider(okHttpClient, gson)
+
@Provides fun provideProviderDao(db: StreamVaultDatabase): ProviderDao = db.providerDao()
@Provides fun provideChannelDao(db: StreamVaultDatabase): ChannelDao = db.channelDao()
@Provides fun provideChannelPreferenceDao(db: StreamVaultDatabase): ChannelPreferenceDao = db.channelPreferenceDao()
diff --git a/app/src/main/java/com/streamvault/app/pairing/ProviderQrPairingManager.kt b/app/src/main/java/com/streamvault/app/pairing/ProviderQrPairingManager.kt
index 28c08129..8b059301 100644
--- a/app/src/main/java/com/streamvault/app/pairing/ProviderQrPairingManager.kt
+++ b/app/src/main/java/com/streamvault/app/pairing/ProviderQrPairingManager.kt
@@ -14,6 +14,10 @@ import com.google.zxing.qrcode.QRCodeWriter
import com.streamvault.domain.model.ProviderEpgSyncMode
import com.streamvault.domain.model.ProviderXtreamLiveSyncMode
import com.streamvault.domain.model.StalkerAuthMode
+import com.streamvault.data.remote.jellyfin.JellyfinProvider
+import com.streamvault.domain.model.Provider
+import com.streamvault.domain.repository.ProviderRepository
+import com.streamvault.domain.usecase.JellyfinProviderSetupCommand
import com.streamvault.domain.usecase.M3uProviderSetupCommand
import com.streamvault.domain.usecase.StalkerProviderSetupCommand
import com.streamvault.domain.usecase.ValidateAndAddProvider
@@ -53,7 +57,9 @@ private const val TAG = "ProviderQrPairing"
@Singleton
class ProviderQrPairingManager @Inject constructor(
@ApplicationContext private val context: Context,
- private val validateAndAddProvider: ValidateAndAddProvider
+ private val validateAndAddProvider: ValidateAndAddProvider,
+ private val providerRepository: ProviderRepository,
+ private val jellyfinProvider: JellyfinProvider
) {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val secureRandom = SecureRandom()
@@ -196,18 +202,26 @@ class ProviderQrPairingManager @Inject constructor(
status = ProviderQrPairingStatus.RECEIVING,
message = "Phone submitted provider details. Validating..."
)
- val result = addProviderFromForm(form)
- when (result) {
+ val providerName = form["name"].orEmpty().ifBlank {
+ when (form["type"].orEmpty().lowercase(Locale.US)) {
+ "m3u" -> "Phone M3U Playlist"
+ "stalker" -> "Phone Stalker Portal"
+ "jellyfin" -> "Phone Jellyfin"
+ else -> "Phone Xtream Provider"
+ }
+ }
+ val saveResult = saveProviderOnly(form, providerName)
+ when (saveResult) {
is ProviderPairingSubmitResult.Success -> {
- writeHtml(client.getOutputStream(), 200, successPage(result.providerName))
- invalidateAfterSuccess(result.providerName)
+ writeHtml(client.getOutputStream(), 200, successPage(providerName))
+ invalidateAfterSuccess(providerName)
}
is ProviderPairingSubmitResult.Error -> {
_state.value = _state.value.copy(
status = ProviderQrPairingStatus.READY,
- message = result.message
+ message = saveResult.message
)
- writeHtml(client.getOutputStream(), 400, errorPage(result.message))
+ writeHtml(client.getOutputStream(), 400, errorPage(saveResult.message))
}
}
}
@@ -216,12 +230,56 @@ class ProviderQrPairingManager @Inject constructor(
}
}
+ private suspend fun saveProviderOnly(form: Map<String, String>, providerName: String): ProviderPairingSubmitResult {
+ val type = form["type"].orEmpty().lowercase(Locale.US)
+ return try {
+ val provider = when (type) {
+ "m3u" -> {
+ val url = form["m3uUrl"].orEmpty()
+ if (url.isBlank()) return ProviderPairingSubmitResult.Error("Please enter M3U URL")
+ Provider(name = providerName, type = com.streamvault.domain.model.ProviderType.M3U, serverUrl = "", m3uUrl = url, isActive = false, status = com.streamvault.domain.model.ProviderStatus.PARTIAL)
+ }
+ "stalker" -> {
+ val portalUrl = form["serverUrl"].orEmpty()
+ val macAddress = form["macAddress"].orEmpty()
+ if (portalUrl.isBlank()) return ProviderPairingSubmitResult.Error("Please enter portal URL")
+ Provider(name = providerName, type = com.streamvault.domain.model.ProviderType.STALKER_PORTAL, serverUrl = portalUrl, stalkerMacAddress = macAddress, username = form["username"].orEmpty(), password = form["password"].orEmpty(), isActive = false, status = com.streamvault.domain.model.ProviderStatus.PARTIAL)
+ }
+ "jellyfin" -> {
+ val serverUrl = form["serverUrl"].orEmpty()
+ val username = form["username"].orEmpty()
+ val password = form["password"].orEmpty()
+ if (serverUrl.isBlank()) return ProviderPairingSubmitResult.Error("Please enter server URL")
+ if (password.isBlank()) return ProviderPairingSubmitResult.Error("Please enter password")
+ val authResult = jellyfinProvider.authenticate(serverUrl, username, password)
+ val accessToken = when (authResult) {
+ is com.streamvault.domain.model.Result.Success -> authResult.data
+ is com.streamvault.domain.model.Result.Error -> return ProviderPairingSubmitResult.Error("Jellyfin authentication failed: ${authResult.message}")
+ is com.streamvault.domain.model.Result.Loading -> return ProviderPairingSubmitResult.Error("Authentication failed")
+ }
+ Provider(name = providerName, type = com.streamvault.domain.model.ProviderType.JELLYFIN, serverUrl = serverUrl, username = username, password = accessToken, isActive = false, status = com.streamvault.domain.model.ProviderStatus.PARTIAL)
+ }
+ else -> {
+ val serverUrl = form["serverUrl"].orEmpty()
+ if (serverUrl.isBlank()) return ProviderPairingSubmitResult.Error("Please enter server URL")
+ Provider(name = providerName, type = com.streamvault.domain.model.ProviderType.XTREAM_CODES, serverUrl = serverUrl, username = form["username"].orEmpty(), password = form["password"].orEmpty(), isActive = false, status = com.streamvault.domain.model.ProviderStatus.PARTIAL)
+ }
+ }
+ val providerId = providerRepository.addProvider(provider).getOrNull()
+ ?: return ProviderPairingSubmitResult.Error("Failed to save provider")
+ ProviderPairingSubmitResult.Success(providerName)
+ } catch (e: Exception) {
+ ProviderPairingSubmitResult.Error("Failed to save provider: ${e.message ?: "unknown error"}")
+ }
+ }
+
private suspend fun addProviderFromForm(form: Map<String, String>): ProviderPairingSubmitResult {
val type = form["type"].orEmpty().lowercase(Locale.US)
val name = form["name"].orEmpty().ifBlank {
when (type) {
"m3u" -> "Phone M3U Playlist"
"stalker" -> "Phone Stalker Portal"
+ "jellyfin" -> "Phone Jellyfin"
else -> "Phone Xtream Provider"
}
}
@@ -246,6 +304,15 @@ class ProviderQrPairingManager @Inject constructor(
),
onProgress = ::updateProgress
)
+ "jellyfin" -> validateAndAddProvider.loginJellyfin(
+ JellyfinProviderSetupCommand(
+ serverUrl = form["serverUrl"].orEmpty(),
+ username = form["username"].orEmpty(),
+ password = form["password"].orEmpty(),
+ name = name
+ ),
+ onProgress = ::updateProgress
+ )
else -> validateAndAddProvider.loginXtream(
XtreamProviderSetupCommand(
serverUrl = form["serverUrl"].orEmpty(),
@@ -348,8 +415,11 @@ class ProviderQrPairingManager @Inject constructor(
}
.toMap()
- private fun decode(value: String): String =
+ private fun decode(value: String): String = try {
URLDecoder.decode(value, StandardCharsets.UTF_8.name())
+ } catch (e: IllegalArgumentException) {
+ value
+ }
private fun writeHtml(output: OutputStream, status: Int, html: String) {
writeResponse(output, status, "text/html; charset=utf-8", html)
@@ -408,6 +478,7 @@ class ProviderQrPairingManager @Inject constructor(
<option value="xtream">Xtream Codes</option>
<option value="m3u">M3U Playlist URL</option>
<option value="stalker">Stalker / MAG Portal</option>
+ <option value="jellyfin">Jellyfin</option>
</select>
<label>Provider name</label>
<input name="name" placeholder="Provider Name">
@@ -428,13 +499,17 @@ class ProviderQrPairingManager @Inject constructor(
<input name="macAddress" placeholder="00:1A:79:AA:BB:CC">
<p class="hint">For credential-only portals, leave MAC blank and fill username/password above.</p>
</div>
+ <div id="jellyfinFields" class="field-group">
+ <p class="hint">Enter your Jellyfin server details below, then press Quick Connect in the app.</p>
+ </div>
<button type="submit">Send to TV</button>
</form>
</main>
<script>
function updateType(){
const t=document.getElementById('type').value;
- document.getElementById('serverFields').classList.toggle('active', t !== 'm3u');
+ const showServer = t !== 'm3u';
+ document.getElementById('serverFields').classList.toggle('active', showServer);
document.getElementById('m3uFields').classList.toggle('active', t === 'm3u');
document.getElementById('stalkerFields').classList.toggle('active', t === 'stalker');
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt
index 86f01787..3eaf85e9 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt
@@ -525,6 +525,7 @@ private fun DashboardProviderHealthCard(
com.streamvault.domain.model.ProviderType.XTREAM_CODES -> stringResource(R.string.dashboard_provider_xtream)
com.streamvault.domain.model.ProviderType.M3U -> stringResource(R.string.dashboard_provider_m3u)
com.streamvault.domain.model.ProviderType.STALKER_PORTAL -> "Stalker/MAG Portal"
+ com.streamvault.domain.model.ProviderType.JELLYFIN -> "Jellyfin"
}
Surface(
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt
index 487dc8ba..699af503 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt
@@ -1487,6 +1487,7 @@ class EpgViewModel @Inject constructor(
com.streamvault.domain.model.ProviderType.XTREAM_CODES -> "Xtream Codes"
com.streamvault.domain.model.ProviderType.M3U -> "M3U Playlist"
com.streamvault.domain.model.ProviderType.STALKER_PORTAL -> "Stalker/MAG Portal"
+ com.streamvault.domain.model.ProviderType.JELLYFIN -> "Jellyfin"
}
}
@@ -1506,6 +1507,12 @@ class EpgViewModel @Inject constructor(
} else {
"Guide combines optional XMLTV with on-demand Stalker portal data."
}
+ com.streamvault.domain.model.ProviderType.JELLYFIN ->
+ if (provider.epgUrl.isBlank()) {
+ "Jellyfin replay depends on the server guide data being populated."
+ } else {
+ "Jellyfin replay combines server guide data with optional XMLTV import."
+ }
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
index eabfe913..545b9ef3 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
@@ -1567,6 +1567,7 @@ class PlayerViewModel @Inject constructor(
com.streamvault.domain.model.ProviderType.XTREAM_CODES -> "Xtream Codes"
com.streamvault.domain.model.ProviderType.M3U -> "M3U Playlist"
com.streamvault.domain.model.ProviderType.STALKER_PORTAL -> "Stalker/MAG Portal"
+ com.streamvault.domain.model.ProviderType.JELLYFIN -> "Jellyfin"
}
)
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerZapActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerZapActions.kt
index 9509e7cb..db7ce028 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerZapActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerZapActions.kt
@@ -99,6 +99,7 @@ internal fun shouldPreloadAdjacentChannel(
if (streamUrl.isBlank() || preloadCoolingDown) return false
return when (providerType) {
ProviderType.M3U -> true
+ ProviderType.JELLYFIN -> true
ProviderType.XTREAM_CODES,
ProviderType.STALKER_PORTAL -> maxConnections >= 2
null -> false
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt
index c0900f87..e9c7dcb5 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt
@@ -26,6 +26,7 @@ import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.LinearProgressIndicator
+
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Switch
import androidx.compose.material3.TextButton
@@ -57,6 +58,7 @@ import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.OffsetMapping
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.input.TransformedText
+import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
@@ -73,14 +75,20 @@ import com.streamvault.app.pairing.ProviderQrPairingStatus
import com.streamvault.app.ui.components.dialogs.PremiumDialog
import com.streamvault.app.ui.components.dialogs.PremiumDialogFooterButton
import com.streamvault.app.ui.components.extractProgressFraction
+import com.streamvault.app.ui.interaction.TvButton
import com.streamvault.app.ui.interaction.TvClickableSurface
import com.streamvault.app.ui.components.shell.StatusPill
import com.streamvault.app.ui.screens.settings.BackupImportPreviewDialog
import com.streamvault.app.ui.theme.*
+import com.google.zxing.qrcode.QRCodeWriter
+import com.google.zxing.BarcodeFormat
+import android.graphics.Bitmap
import com.streamvault.data.util.ProviderInputSanitizer
import com.streamvault.domain.model.ProviderEpgSyncMode
import com.streamvault.domain.model.ProviderXtreamLiveSyncMode
import com.streamvault.domain.model.StalkerAuthMode
+import com.streamvault.domain.usecase.JellyfinProviderSetupCommand
+import com.streamvault.domain.usecase.JellyfinQuickConnectProviderSetupCommand
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@@ -89,7 +97,7 @@ import android.widget.Toast
// ??? Source type ?????????????????????????????????????????????????????????????
-private enum class SourceType { XTREAM, STALKER, M3U_URL, M3U_FILE }
+private enum class SourceType { XTREAM, STALKER, M3U_URL, M3U_FILE, JELLYFIN }
// ??? Screen ??????????????????????????????????????????????????????????????????
@@ -126,6 +134,7 @@ fun ProviderSetupScreen(
var stalkerDeviceId by rememberSaveable { mutableStateOf("") }
var stalkerDeviceId2 by rememberSaveable { mutableStateOf("") }
var stalkerSignature by rememberSaveable { mutableStateOf("") }
+ var jellyfinQuickConnectCode by rememberSaveable { mutableStateOf("") }
var fileImportError by rememberSaveable { mutableStateOf<String?>(null) }
var handledInitialImportUri by rememberSaveable { mutableStateOf<String?>(null) }
var showDiscardDraftDialog by rememberSaveable { mutableStateOf(false) }
@@ -252,6 +261,7 @@ fun ProviderSetupScreen(
val sourceType = when {
selectedTab == 0 -> SourceType.XTREAM
selectedTab == 1 -> SourceType.STALKER
+ selectedTab == 3 -> SourceType.JELLYFIN
uiState.m3uTab == 1 -> SourceType.M3U_FILE
else -> SourceType.M3U_URL
}
@@ -277,6 +287,10 @@ fun ProviderSetupScreen(
viewModel.updateM3uTab(1)
viewModel.applySourceDefaults(ProviderSetupViewModel.SetupSourceType.M3U)
}
+ SourceType.JELLYFIN -> {
+ selectedTab = 3
+ viewModel.applySourceDefaults(ProviderSetupViewModel.SetupSourceType.JELLYFIN)
+ }
}
}
@@ -360,6 +374,9 @@ fun ProviderSetupScreen(
onLoginXtream = { viewModel.loginXtream(serverUrl, username, password, name, httpUserAgent, httpHeaders) },
onLoginStalker = { viewModel.loginStalker(serverUrl, stalkerMacAddress, stalkerAuthMode, username, password, name, stalkerDeviceProfile, stalkerDeviceTimezone, stalkerDeviceLocale, stalkerSerialNumber, stalkerDeviceId, stalkerDeviceId2, stalkerSignature) },
onAddM3u = { viewModel.addM3u(m3uUrl, name, httpUserAgent, httpHeaders) },
+ onLoginJellyfin = { viewModel.loginJellyfin(serverUrl, username, password, name) },
+ quickConnectCode = uiState.jellyfinQuickConnectCode,
+ onQuickConnectRequest = { viewModel.loginJellyfinQuickConnect(serverUrl.trim(), name.trim()) },
onStartPhonePairing = viewModel::startPhonePairing,
onStopPhonePairing = viewModel::stopPhonePairing,
onToggleM3uVodClassification = { viewModel.updateM3uVodClassificationEnabled(!uiState.m3uVodClassificationEnabled) },
@@ -404,6 +421,9 @@ fun ProviderSetupScreen(
onLoginXtream = { viewModel.loginXtream(serverUrl, username, password, name, httpUserAgent, httpHeaders) },
onLoginStalker = { viewModel.loginStalker(serverUrl, stalkerMacAddress, stalkerAuthMode, username, password, name, stalkerDeviceProfile, stalkerDeviceTimezone, stalkerDeviceLocale, stalkerSerialNumber, stalkerDeviceId, stalkerDeviceId2, stalkerSignature) },
onAddM3u = { viewModel.addM3u(m3uUrl, name, httpUserAgent, httpHeaders) },
+ onLoginJellyfin = { viewModel.loginJellyfin(serverUrl, username, password, name) },
+ quickConnectCode = uiState.jellyfinQuickConnectCode,
+ onQuickConnectRequest = { viewModel.loginJellyfinQuickConnect(serverUrl.trim(), name.trim()) },
onStartPhonePairing = viewModel::startPhonePairing,
onStopPhonePairing = viewModel::stopPhonePairing,
onToggleM3uVodClassification = { viewModel.updateM3uVodClassificationEnabled(!uiState.m3uVodClassificationEnabled) },
@@ -428,7 +448,12 @@ fun ProviderSetupScreen(
}
if (uiState.syncProgress != null) {
- SyncProgressDialog(message = uiState.syncProgress!!)
+ SyncProgressDialog(
+ message = uiState.syncProgress!!,
+ quickConnectCode = if (uiState.jellyfinQuickConnectCode.isNotBlank()) uiState.jellyfinQuickConnectCode else null,
+ serverUrl = serverUrl,
+ onCancel = if (uiState.jellyfinQuickConnectCode.isNotBlank()) ({ viewModel.cancelJellyfinQuickConnect() }) else null
+ )
}
val backupPreview = uiState.backupPreview
@@ -708,6 +733,9 @@ private fun ProviderFormContent(
onLoginXtream: () -> Unit,
onLoginStalker: () -> Unit,
onAddM3u: () -> Unit,
+ onLoginJellyfin: () -> Unit,
+ quickConnectCode: String,
+ onQuickConnectRequest: () -> Unit,
onStartPhonePairing: () -> Unit,
onStopPhonePairing: () -> Unit,
onToggleM3uVodClassification: () -> Unit,
@@ -999,6 +1027,32 @@ private fun ProviderFormContent(
onClick = onAddM3u
)
}
+
+ SourceType.JELLYFIN -> {
+ JellyfinProviderForm(
+ serverUrl = serverUrl,
+ onServerUrlChange = onServerUrlChange,
+ username = username,
+ onUsernameChange = onUsernameChange,
+ password = password,
+ onPasswordChange = onPasswordChange,
+ name = name,
+ onNameChange = onNameChange,
+ quickConnectCode = quickConnectCode,
+ onQuickConnectRequest = onQuickConnectRequest,
+ isEditing = uiState.isEditing
+ )
+ FormErrors(uiState.validationError, uiState.error)
+ ActionButton(
+ text = when {
+ uiState.isLoading -> stringResource(R.string.setup_validating)
+ uiState.isEditing -> stringResource(R.string.setup_save)
+ else -> stringResource(R.string.setup_add)
+ },
+ isLoading = uiState.isLoading,
+ onClick = onLoginJellyfin
+ )
+ }
}
}
}
@@ -1043,7 +1097,8 @@ private fun AdvancedProviderOptionsSection(
SourceType.STALKER -> ProviderEpgSyncMode.BACKGROUND
SourceType.XTREAM,
SourceType.M3U_URL,
- SourceType.M3U_FILE -> ProviderEpgSyncMode.UPFRONT
+ SourceType.M3U_FILE,
+ SourceType.JELLYFIN -> ProviderEpgSyncMode.UPFRONT
}
LaunchedEffect(uiState.isEditing, uiState.epgSyncMode, uiState.xtreamLiveSyncMode, sourceType) {
@@ -1647,6 +1702,15 @@ private fun SourceTypeSelectorPanel(
onClick = { onSelect(SourceType.M3U_FILE) }
)
}
+ if (!isEditing || sourceType == SourceType.JELLYFIN) {
+ SourceTypeCard(
+ title = androidx.compose.ui.res.stringResource(R.string.setup_tab_jellyfin),
+ subtitle = "Jellyfin media server",
+ selected = sourceType == SourceType.JELLYFIN,
+ enabled = !isEditing,
+ onClick = { onSelect(SourceType.JELLYFIN) }
+ )
+ }
if (!isEditing) {
ImportOptionsButton(
text = stringResource(R.string.settings_restore_data),
@@ -1760,6 +1824,13 @@ private fun SourceTypeTabRow(
onClick = { if (!isEditing) onSelect(SourceType.M3U_FILE) }
)
}
+ if (!isEditing || sourceType == SourceType.JELLYFIN) {
+ TabButton(
+ text = androidx.compose.ui.res.stringResource(R.string.setup_tab_jellyfin),
+ isSelected = sourceType == SourceType.JELLYFIN,
+ onClick = { if (!isEditing) onSelect(SourceType.JELLYFIN) }
+ )
+ }
}
}
@@ -2076,51 +2147,108 @@ private fun PasswordVisibilityGlyph(
// ??? Sync progress dialog ?????????????????????????????????????????????????????
@Composable
-fun SyncProgressDialog(message: String) {
- val fraction = extractProgressFraction(message)
- val animatedFraction by animateFloatAsState(
- targetValue = fraction ?: 0f,
- animationSpec = tween(durationMillis = 400),
- label = "syncFraction"
- )
- PremiumDialog(
- title = androidx.compose.ui.res.stringResource(R.string.settings_syncing_title),
- subtitle = androidx.compose.ui.res.stringResource(R.string.settings_syncing_subtitle),
- onDismissRequest = {},
- widthFraction = 0.32f,
- heightFraction = null,
- content = {
- Column(
- modifier = Modifier.fillMaxWidth(),
- horizontalAlignment = Alignment.CenterHorizontally,
- verticalArrangement = Arrangement.spacedBy(16.dp)
- ) {
- CircularProgressIndicator(color = Primary)
- StatusPill(
- label = androidx.compose.ui.res.stringResource(R.string.settings_syncing_btn),
- containerColor = PrimaryGlow
- )
- if (fraction != null) {
- LinearProgressIndicator(
- progress = { animatedFraction },
- color = Primary,
- modifier = Modifier.fillMaxWidth()
+fun SyncProgressDialog(
+ message: String,
+ quickConnectCode: String? = null,
+ serverUrl: String? = null,
+ onCancel: (() -> Unit)? = null
+) {
+ if (quickConnectCode != null && serverUrl != null) {
+ val qrCodeBitmap = remember(quickConnectCode, serverUrl) {
+ generateJellyfinQuickConnectQrCode(serverUrl, quickConnectCode)
+ }
+ PremiumDialog(
+ title = "Quick Connect",
+ subtitle = "Enter this code on your Jellyfin server",
+ onDismissRequest = {},
+ widthFraction = 0.38f,
+ heightFraction = null,
+ content = {
+ Column(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ if (qrCodeBitmap != null) {
+ Box(
+ modifier = Modifier
+ .size(200.dp)
+ .background(Color.White, RoundedCornerShape(12.dp))
+ .padding(8.dp),
+ contentAlignment = Alignment.Center
+ ) {
+ Image(
+ bitmap = qrCodeBitmap.asImageBitmap(),
+ contentDescription = "Quick Connect QR Code",
+ modifier = Modifier.fillMaxSize()
+ )
+ }
+ }
+ Text(
+ text = stringResource(R.string.setup_jellyfin_quick_connect_code, quickConnectCode),
+ style = MaterialTheme.typography.headlineMedium,
+ color = Color.White
)
- } else {
- LinearProgressIndicator(
- color = Primary,
- modifier = Modifier.fillMaxWidth()
+ Text(
+ text = message,
+ style = MaterialTheme.typography.bodyMedium,
+ color = TextSecondary,
+ textAlign = TextAlign.Center
)
+ if (onCancel != null) {
+ TextButton(onClick = onCancel) {
+ Text("Cancel", color = Color.White)
+ }
+ }
}
- Text(
- text = message,
- style = MaterialTheme.typography.bodyMedium,
- color = OnBackground,
- textAlign = TextAlign.Center
- )
}
- }
- )
+ )
+ } else {
+ val fraction = extractProgressFraction(message)
+ val animatedFraction by animateFloatAsState(
+ targetValue = fraction ?: 0f,
+ animationSpec = tween(durationMillis = 400),
+ label = "syncFraction"
+ )
+ PremiumDialog(
+ title = androidx.compose.ui.res.stringResource(R.string.settings_syncing_title),
+ subtitle = androidx.compose.ui.res.stringResource(R.string.settings_syncing_subtitle),
+ onDismissRequest = {},
+ widthFraction = 0.32f,
+ heightFraction = null,
+ content = {
+ Column(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(16.dp)
+ ) {
+ CircularProgressIndicator(color = Primary)
+ StatusPill(
+ label = androidx.compose.ui.res.stringResource(R.string.settings_syncing_btn),
+ containerColor = PrimaryGlow
+ )
+ if (fraction != null) {
+ LinearProgressIndicator(
+ progress = { animatedFraction },
+ color = Primary,
+ modifier = Modifier.fillMaxWidth()
+ )
+ } else {
+ LinearProgressIndicator(
+ color = Primary,
+ modifier = Modifier.fillMaxWidth()
+ )
+ }
+ Text(
+ text = message,
+ style = MaterialTheme.typography.bodyMedium,
+ color = OnBackground,
+ textAlign = TextAlign.Center
+ )
+ }
+ }
+ )
+ }
}
// ??? ActionButton ?????????????????????????????????????????????????????????????
@@ -2443,3 +2571,115 @@ private fun resolveFileImportError(context: android.content.Context, error: Thro
return if (isStorageFull) context.getString(R.string.setup_file_import_storage_full)
else context.getString(R.string.setup_file_import_failed)
}
+
+// ??? Jellyfin form ?????????????????????????????????????????????????????????????
+
+@Composable
+private fun JellyfinProviderForm(
+ serverUrl: String,
+ onServerUrlChange: (String) -> Unit,
+ username: String,
+ onUsernameChange: (String) -> Unit,
+ password: String,
+ onPasswordChange: (String) -> Unit,
+ name: String,
+ onNameChange: (String) -> Unit,
+ quickConnectCode: String,
+ onQuickConnectRequest: () -> Unit,
+ isEditing: Boolean
+) {
+ Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
+ Text(
+ text = stringResource(R.string.setup_tab_jellyfin),
+ style = MaterialTheme.typography.titleLarge,
+ color = TextPrimary
+ )
+
+ // Step 1: Server URL
+ ProviderTextField(
+ value = serverUrl,
+ onValueChange = onServerUrlChange,
+ placeholder = stringResource(R.string.setup_server_url)
+ )
+
+ // Quick Connect button + QR code display
+ if (!isEditing) {
+ TvButton(
+ onClick = onQuickConnectRequest,
+ colors = ButtonDefaults.colors(containerColor = AccentCyan, contentColor = Color.Black)
+ ) {
+ Text(stringResource(R.string.setup_jellyfin_quick_connect))
+ }
+ }
+
+ // QR code and code text (shown after quick connect is initiated)
+ if (quickConnectCode.isNotBlank()) {
+ Spacer(modifier = Modifier.height(8.dp))
+ val qrCodeBitmap = remember(quickConnectCode, serverUrl) {
+ generateJellyfinQuickConnectQrCode(serverUrl, quickConnectCode)
+ }
+ if (qrCodeBitmap != null) {
+ Box(
+ modifier = Modifier
+ .size(240.dp)
+ .background(Color.White, RoundedCornerShape(12.dp))
+ .padding(8.dp),
+ contentAlignment = Alignment.Center
+ ) {
+ Image(
+ bitmap = qrCodeBitmap.asImageBitmap(),
+ contentDescription = "Quick Connect QR Code",
+ modifier = Modifier.fillMaxSize()
+ )
+ }
+ Spacer(modifier = Modifier.height(8.dp))
+ }
+ Text(
+ text = stringResource(R.string.setup_jellyfin_quick_connect_code, quickConnectCode),
+ style = MaterialTheme.typography.bodyMedium,
+ color = TextSecondary
+ )
+ Text(
+ text = stringResource(R.string.setup_jellyfin_quick_connect_code_instructions),
+ style = MaterialTheme.typography.bodySmall,
+ color = TextTertiary
+ )
+ Spacer(modifier = Modifier.height(14.dp))
+ }
+
+ // Step 2: Manual credentials (for password auth or existing provider edit)
+ ProviderTextField(
+ value = username,
+ onValueChange = onUsernameChange,
+ placeholder = stringResource(R.string.setup_username)
+ )
+ ProviderTextField(
+ value = password,
+ onValueChange = onPasswordChange,
+ placeholder = stringResource(R.string.setup_password),
+ isPassword = true
+ )
+ ProviderTextField(
+ value = name,
+ onValueChange = onNameChange,
+ placeholder = stringResource(R.string.setup_name_placeholder)
+ )
+ }
+}
+
+private fun generateJellyfinQuickConnectQrCode(serverUrl: String, code: String): Bitmap? {
+ return try {
+ val qrUrl = "${serverUrl.trimEnd('/')}/web/index.html#!/quickconnect.html?code=$code"
+ val writer = QRCodeWriter()
+ val bitMatrix = writer.encode(qrUrl, BarcodeFormat.QR_CODE, 512, 512)
+ val bitmap = Bitmap.createBitmap(512, 512, Bitmap.Config.RGB_565)
+ for (x in 0 until 512) {
+ for (y in 0 until 512) {
+ bitmap.setPixel(x, y, if (bitMatrix[x, y]) android.graphics.Color.BLACK else android.graphics.Color.WHITE)
+ }
+ }
+ bitmap
+ } catch (e: Exception) {
+ null
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.kt
index c3221417..1682c762 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.kt
@@ -29,6 +29,8 @@ import com.streamvault.domain.usecase.ImportBackupCommand
import com.streamvault.domain.usecase.ImportBackupResult
import com.streamvault.domain.usecase.InspectBackupCommand
import com.streamvault.domain.usecase.InspectBackupResult
+import com.streamvault.domain.usecase.JellyfinProviderSetupCommand
+import com.streamvault.domain.usecase.JellyfinQuickConnectProviderSetupCommand
import com.streamvault.domain.usecase.M3uProviderSetupCommand
import com.streamvault.domain.usecase.StalkerProviderSetupCommand
import com.streamvault.domain.usecase.ValidateAndAddProvider
@@ -70,7 +72,8 @@ class ProviderSetupViewModel @Inject constructor(
enum class SetupSourceType {
XTREAM,
STALKER,
- M3U
+ M3U,
+ JELLYFIN
}
private val _uiState = MutableStateFlow(ProviderSetupState())
@@ -78,6 +81,7 @@ class ProviderSetupViewModel @Inject constructor(
private val _knownLocalM3uUrls = MutableStateFlow<Set<String>>(emptySet())
val knownLocalM3uUrls: StateFlow<Set<String>> = _knownLocalM3uUrls.asStateFlow()
val pairingState: StateFlow<ProviderQrPairingState> = providerQrPairingManager.state
+ private var jellyfinQuickConnectJob: kotlinx.coroutines.Job? = null
init {
viewModelScope.launch {
@@ -229,6 +233,7 @@ class ProviderSetupViewModel @Inject constructor(
ProviderType.XTREAM_CODES -> 0
ProviderType.STALKER_PORTAL -> 1
ProviderType.M3U -> 2
+ ProviderType.JELLYFIN -> 3
},
m3uTab = if (provider.m3uUrl.startsWith("file://")) 1 else 0
)
@@ -551,6 +556,174 @@ class ProviderSetupViewModel @Inject constructor(
}
}
+ fun loginJellyfin(
+ serverUrl: String,
+ username: String,
+ password: String,
+ name: String
+ ) {
+ _uiState.update {
+ it.copy(
+ validationError = null,
+ error = null,
+ completionWarning = null,
+ onboardingCompletion = OnboardingCompletion.NONE,
+ loginSuccess = false
+ )
+ }
+
+ viewModelScope.launch {
+ _uiState.update { it.copy(isLoading = true, validationError = null, syncProgress = "Connecting...") }
+ val existingId = if (_uiState.value.isEditing) _uiState.value.existingProviderId else null
+
+ when (val result = validateAndAddProvider.loginJellyfin(
+ JellyfinProviderSetupCommand(
+ serverUrl = serverUrl,
+ username = username,
+ password = password,
+ name = name,
+ existingProviderId = existingId
+ ),
+ onProgress = { msg -> _uiState.update { it.copy(syncProgress = msg) } }
+ )) {
+ is ValidateAndAddProviderResult.Success -> {
+ _uiState.update {
+ it.copy(
+ isLoading = false,
+ loginSuccess = true,
+ onboardingCompletion = OnboardingCompletion.READY,
+ createdProviderId = result.provider.id,
+ error = null,
+ validationError = null,
+ syncProgress = null
+ )
+ }
+ }
+ is ValidateAndAddProviderResult.SavedWithWarning -> {
+ _uiState.update {
+ it.copy(
+ isLoading = false,
+ loginSuccess = false,
+ onboardingCompletion = OnboardingCompletion.SAVED_RESUMING,
+ createdProviderId = result.provider.id,
+ error = null,
+ validationError = null,
+ completionWarning = result.warning,
+ syncProgress = null
+ )
+ }
+ }
+ is ValidateAndAddProviderResult.ValidationError -> {
+ _uiState.update {
+ it.copy(isLoading = false, validationError = result.message, error = null, syncProgress = null)
+ }
+ }
+ is ValidateAndAddProviderResult.Error -> {
+ _uiState.update {
+ it.copy(
+ isLoading = false,
+ error = mapJellyfinLoginError(result),
+ validationError = null,
+ syncProgress = null
+ )
+ }
+ }
+ }
+ }
+ }
+
+ fun loginJellyfinQuickConnect(
+ serverUrl: String,
+ name: String
+ ) {
+ _uiState.update {
+ it.copy(
+ validationError = null,
+ error = null,
+ completionWarning = null,
+ onboardingCompletion = OnboardingCompletion.NONE,
+ loginSuccess = false
+ )
+ }
+
+ jellyfinQuickConnectJob?.cancel()
+ jellyfinQuickConnectJob = viewModelScope.launch {
+ _uiState.update { it.copy(isLoading = true, validationError = null, syncProgress = "Connecting...") }
+ val existingId = if (_uiState.value.isEditing) _uiState.value.existingProviderId else null
+
+ when (val result = validateAndAddProvider.loginJellyfinQuickConnect(
+ JellyfinQuickConnectProviderSetupCommand(
+ serverUrl = serverUrl,
+ name = name,
+ existingProviderId = existingId
+ ),
+ onCode = { code ->
+ _uiState.update {
+ it.copy(jellyfinQuickConnectCode = code, syncProgress = "Waiting for approval on your Jellyfin server...", isLoading = false)
+ }
+ },
+ onProgress = { msg -> _uiState.update { it.copy(syncProgress = msg) } }
+ )) {
+ is ValidateAndAddProviderResult.Success -> {
+ _uiState.update {
+ it.copy(
+ isLoading = false,
+ loginSuccess = true,
+ onboardingCompletion = OnboardingCompletion.READY,
+ createdProviderId = result.provider.id,
+ error = null,
+ validationError = null,
+ syncProgress = null
+ )
+ }
+ }
+ is ValidateAndAddProviderResult.SavedWithWarning -> {
+ _uiState.update {
+ it.copy(
+ isLoading = false,
+ loginSuccess = false,
+ onboardingCompletion = OnboardingCompletion.SAVED_RESUMING,
+ createdProviderId = result.provider.id,
+ error = null,
+ validationError = null,
+ completionWarning = result.warning,
+ syncProgress = null
+ )
+ }
+ }
+ is ValidateAndAddProviderResult.ValidationError -> {
+ _uiState.update {
+ it.copy(isLoading = false, validationError = result.message, error = null, syncProgress = null)
+ }
+ }
+ is ValidateAndAddProviderResult.Error -> {
+ _uiState.update {
+ it.copy(
+ isLoading = false,
+ error = mapJellyfinLoginError(result),
+ validationError = null,
+ syncProgress = null
+ )
+ }
+ }
+ }
+ }
+ }
+
+ fun cancelJellyfinQuickConnect() {
+ jellyfinQuickConnectJob?.cancel()
+ jellyfinQuickConnectJob = null
+ _uiState.update {
+ it.copy(
+ syncProgress = null,
+ jellyfinQuickConnectCode = "",
+ isLoading = false,
+ error = null,
+ validationError = null
+ )
+ }
+ }
+
fun inspectBackup(uriString: String) {
viewModelScope.launch {
_uiState.update {
@@ -821,6 +994,32 @@ class ProviderSetupViewModel @Inject constructor(
private inline fun <reified T : Throwable> Throwable?.hasCause(): Boolean =
findCause<T>() != null
+ private fun mapJellyfinLoginError(result: ValidateAndAddProviderResult.Error): String {
+ val failure = result.exception
+ return when {
+ result.message.startsWith(PROVIDER_LOGIN_SYNC_FAILED_PREFIX, ignoreCase = true) ->
+ "Login succeeded, but the initial sync failed while loading the Jellyfin library"
+
+ failure.hasCause<CredentialDecryptionException>() ->
+ failure.findCause<CredentialDecryptionException>()?.message
+ ?: CredentialDecryptionException.MESSAGE
+
+ failure.hasCause<SSLPeerUnverifiedException>() ||
+ failure.hasCause<CertificateException>() ||
+ failure.hasCause<SSLException>() ->
+ "Secure connection failed - the server's TLS certificate is not trusted on this device"
+
+ failure.hasCause<SocketTimeoutException>() ||
+ failure.hasCause<InterruptedIOException>() ||
+ failure.hasCause<UnknownHostException>() ||
+ failure.hasCause<ConnectException>() ||
+ failure.hasCause<NoRouteToHostException>() ->
+ "Cannot reach server - check your internet connection and server URL"
+
+ else -> result.message
+ }
+ }
+
private companion object {
private const val PROVIDER_LOGIN_SYNC_FAILED_PREFIX =
"Provider login succeeded, but initial sync failed"
@@ -859,6 +1058,7 @@ data class ProviderSetupState(
val stalkerDeviceId: String = "",
val stalkerDeviceId2: String = "",
val stalkerSignature: String = "",
+ val jellyfinQuickConnectCode: String = "",
val createdProviderId: Long? = null,
val createdProviderName: String? = null,
val pendingCombinedAttachProfileId: Long? = null,
@@ -878,5 +1078,6 @@ data class ProviderSetupState(
private fun defaultEpgSyncModeFor(sourceType: ProviderSetupViewModel.SetupSourceType): ProviderEpgSyncMode = when (sourceType) {
ProviderSetupViewModel.SetupSourceType.STALKER,
ProviderSetupViewModel.SetupSourceType.XTREAM,
- ProviderSetupViewModel.SetupSourceType.M3U -> ProviderEpgSyncMode.BACKGROUND
+ ProviderSetupViewModel.SetupSourceType.M3U,
+ ProviderSetupViewModel.SetupSourceType.JELLYFIN -> ProviderEpgSyncMode.BACKGROUND
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsDerivedStateObservers.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsDerivedStateObservers.kt
index 66e5b2b9..caae8141 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsDerivedStateObservers.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsDerivedStateObservers.kt
@@ -169,6 +169,13 @@ private fun buildCapabilitySummary(application: Application, provider: Provider)
"Portal catalog with MAC auth and on-demand guide/playback resolution."
}
}
+ ProviderType.JELLYFIN -> {
+ if (provider.epgUrl.isNotBlank()) {
+ "Jellyfin catalog with direct streaming, optional XMLTV import."
+ } else {
+ "Jellyfin catalog with direct streaming and guide data from the server."
+ }
+ }
}
}
@@ -176,6 +183,7 @@ private fun Provider.sourceLabel(): String = when (type) {
ProviderType.XTREAM_CODES -> "Xtream Codes"
ProviderType.M3U -> "M3U Playlist"
ProviderType.STALKER_PORTAL -> "Stalker/MAG Portal"
+ ProviderType.JELLYFIN -> "Jellyfin"
}
private fun Provider.expirySummary(): String {
@@ -207,4 +215,11 @@ private fun Provider.archiveSummary(): String = when (type) {
"Stalker replay depends on portal support with optional XMLTV coverage."
}
}
+ ProviderType.JELLYFIN -> {
+ if (epgUrl.isBlank()) {
+ "Jellyfin replay depends on server guide data."
+ } else {
+ "Jellyfin replay combines server guide data with optional XMLTV coverage."
+ }
+ }
}
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 4a99619b..7f4a2a5c 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -1004,6 +1004,15 @@
<string name="setup_discard_draft_cancel">Keep editing</string>
<string name="setup_validating">Validating...</string>
<string name="setup_add">Add Playlist</string>
+ <string name="setup_tab_jellyfin">Jellyfin</string>
+ <string name="setup_jellyfin_quick_connect">Quick Connect</string>
+ <string name="setup_jellyfin_quick_connect_code">Code: %s</string>
+ <string name="setup_jellyfin_quick_connect_code_instructions">Open your Jellyfin server in a browser and enter this code, or scan the QR code with your phone.</string>
+ <string name="setup_server_url">Server URL</string>
+ <string name="setup_username">Username</string>
+ <string name="setup_password">Password</string>
+ <string name="setup_name">Name</string>
+ <string name="setup_name_placeholder">My Jellyfin Server</string>
<string name="player_buffering">Buffering...</string>
diff --git a/data/src/main/java/com/streamvault/data/remote/jellyfin/JellyfinAuth.kt b/data/src/main/java/com/streamvault/data/remote/jellyfin/JellyfinAuth.kt
new file mode 100644
index 00000000..6fed25fa
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/remote/jellyfin/JellyfinAuth.kt
@@ -0,0 +1,25 @@
+package com.streamvault.data.remote.jellyfin
+
+import java.security.MessageDigest
+
+private const val JELLYFIN_CLIENT_NAME = "StreamVault"
+private const val JELLYFIN_CLIENT_VERSION = "1.0.0"
+
+internal fun buildJellyfinAuthorizationHeader(
+ serverUrl: String,
+ username: String,
+ accessToken: String? = null
+): String {
+ val deviceId = buildJellyfinDeviceId(serverUrl, username)
+ return buildString {
+ append("MediaBrowser Client=\"$JELLYFIN_CLIENT_NAME\", Device=\"$JELLYFIN_CLIENT_NAME\", DeviceId=\"$deviceId\", Version=\"$JELLYFIN_CLIENT_VERSION\"")
+ accessToken?.takeIf { it.isNotBlank() }?.let { token ->
+ append(", Token=\"$token\"")
+ }
+ }
+}
+
+internal fun buildJellyfinDeviceId(serverUrl: String, username: String): String {
+ val digest = MessageDigest.getInstance("SHA-256").digest("$serverUrl|$username".toByteArray(Charsets.UTF_8))
+ return digest.take(16).joinToString("") { byte -> "%02x".format(byte) }
+}
diff --git a/data/src/main/java/com/streamvault/data/remote/jellyfin/JellyfinProvider.kt b/data/src/main/java/com/streamvault/data/remote/jellyfin/JellyfinProvider.kt
new file mode 100644
index 00000000..c99e2f32
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/remote/jellyfin/JellyfinProvider.kt
@@ -0,0 +1,411 @@
+package com.streamvault.data.remote.jellyfin
+
+import com.google.gson.Gson
+import com.google.gson.annotations.SerializedName
+import com.google.gson.reflect.TypeToken
+import com.streamvault.data.local.entity.EpisodeEntity
+import com.streamvault.data.local.entity.MovieEntity
+import com.streamvault.data.local.entity.SeriesEntity
+import com.streamvault.domain.model.Provider
+import com.streamvault.domain.model.Result
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.RequestBody.Companion.toRequestBody
+import java.util.concurrent.TimeUnit
+import javax.inject.Inject
+import javax.inject.Singleton
+import kotlinx.coroutines.delay
+import java.net.URLEncoder
+
+@Singleton
+class JellyfinProvider @Inject constructor(
+ private val okHttpClient: OkHttpClient,
+ private val gson: Gson
+) {
+ private companion object {
+ private const val MOVIE_CATEGORY_ID = 1L
+ private const val SERIES_CATEGORY_ID = 2L
+ private const val REQUEST_TIMEOUT_SECONDS = 60L
+ private const val QUICK_CONNECT_TIMEOUT_MILLIS = 120_000L
+ private const val QUICK_CONNECT_POLL_INTERVAL_MILLIS = 2_000L
+ }
+
+ private val itemsResponseType = object : TypeToken<JellyfinItemsResponseDto>() {}.type
+ private val seriesResponseType = object : TypeToken<JellyfinSeriesEpisodesResponseDto>() {}.type
+ private val authResultType = object : TypeToken<JellyfinAuthenticationResultDto>() {}.type
+
+ suspend fun authenticate(serverUrl: String, username: String, password: String): Result<String> {
+ return try {
+ val session = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
+ authenticateSession(serverUrl, username, password)
+ }
+ Result.success(session.accessToken)
+ } catch (e: Exception) {
+ Result.error("Jellyfin authentication failed: ${e.message}", e)
+ }
+ }
+
+ suspend fun authenticateQuickConnect(
+ serverUrl: String,
+ onCode: ((String) -> Unit)? = null,
+ onProgress: ((String) -> Unit)? = null
+ ): Result<JellyfinQuickConnectAuthenticationResult> {
+ return try {
+ onProgress?.invoke("Requesting Quick Connect code...")
+ val initiation = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
+ initiateQuickConnect(serverUrl)
+ }
+ val secret = initiation.secret?.takeIf { it.isNotBlank() }
+ ?: throw IllegalStateException("Jellyfin Quick Connect did not return a secret")
+ val code = initiation.code?.takeIf { it.isNotBlank() } ?: secret
+ onCode?.invoke(code)
+ onProgress?.invoke("Waiting for approval on your Jellyfin server...")
+ val deadline = System.currentTimeMillis() + QUICK_CONNECT_TIMEOUT_MILLIS
+ while (System.currentTimeMillis() < deadline) {
+ val state = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
+ pollQuickConnectState(serverUrl, secret)
+ }
+ if (state.authenticated) {
+ return kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
+ authenticateWithQuickConnect(serverUrl, secret)
+ }
+ }
+ delay(QUICK_CONNECT_POLL_INTERVAL_MILLIS)
+ }
+ Result.error("Quick Connect timed out waiting for approval")
+ } catch (e: Exception) {
+ Result.error("Jellyfin Quick Connect failed: ${e.message}", e)
+ }
+ }
+
+ suspend fun fetchMovies(provider: Provider): Result<List<MovieEntity>> = try {
+ val items = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
+ fetchItems(provider, "/Items", mapOf(
+ "IncludeItemTypes" to "Movie",
+ "Recursive" to "true",
+ "EnableImages" to "false",
+ "EnableUserData" to "false",
+ "Fields" to "Overview,ProviderIds,ProductionYear,PremiereDate,RunTimeTicks,Genres,CommunityRating,ImageTags,BackdropImageTags,MediaSources,DateCreated,Path"
+ ))
+ }
+ Result.success(items.map { item -> buildMovieEntity(item, provider) })
+ } catch (e: Exception) {
+ Result.error("Failed to load Jellyfin movies: ${e.message}", e)
+ }
+
+ suspend fun fetchSeries(provider: Provider): Result<List<SeriesEntity>> = try {
+ val items = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
+ fetchItems(provider, "/Items", mapOf(
+ "IncludeItemTypes" to "Series",
+ "Recursive" to "true",
+ "EnableImages" to "false",
+ "EnableUserData" to "false",
+ "Fields" to "Overview,ProviderIds,ProductionYear,PremiereDate,RunTimeTicks,Genres,CommunityRating,ImageTags,BackdropImageTags,DateCreated,DateLastMediaAdded,Path"
+ ))
+ }
+ Result.success(items.map { item -> buildSeriesEntity(item, provider) })
+ } catch (e: Exception) {
+ Result.error("Failed to load Jellyfin series: ${e.message}", e)
+ }
+
+ suspend fun fetchEpisodes(provider: Provider, seriesRemoteId: String, seriesLocalId: Long): Result<List<EpisodeEntity>> = try {
+ val response = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
+ fetchSeriesEpisodes(provider, seriesRemoteId)
+ }
+ Result.success(response.map { item -> buildEpisodeEntity(item, provider, seriesLocalId) })
+ } catch (e: Exception) {
+ Result.error("Failed to load Jellyfin episodes: ${e.message}", e)
+ }
+
+ private fun authenticateSession(serverUrl: String, username: String, password: String): JellyfinAuthenticatedSession {
+ val url = "${serverUrl.trimEnd('/')}/Users/AuthenticateByName"
+ val payload = gson.toJson(JellyfinAuthenticateRequestDto(username = username, password = password))
+ val request = Request.Builder()
+ .url(url)
+ .header("Accept", "application/json")
+ .header("Content-Type", "application/json")
+ .header("Authorization", buildJellyfinAuthorizationHeader(serverUrl, username))
+ .post(payload.toRequestBody("application/json".toMediaType()))
+ .build()
+ val body = executeRequest(request, "Jellyfin login failed")
+ val parsed = gson.fromJson<JellyfinAuthenticationResultDto>(body, authResultType)
+ val token = parsed.accessToken?.takeIf { it.isNotBlank() }
+ ?: throw IllegalStateException("Jellyfin login did not return an access token")
+ val userId = parsed.user?.id?.takeIf { it.isNotBlank() }
+ ?: parsed.sessionInfo?.userId?.takeIf { it.isNotBlank() }
+ ?: throw IllegalStateException("Jellyfin login did not return a user id")
+ return JellyfinAuthenticatedSession(accessToken = token, userId = userId, userName = parsed.user?.name ?: username)
+ }
+
+ private fun initiateQuickConnect(serverUrl: String): JellyfinQuickConnectInitiateResponseDto {
+ val url = buildUrl(serverUrl, "/QuickConnect/Initiate", emptyMap())
+ val request = Request.Builder()
+ .url(url)
+ .header("Authorization", buildJellyfinAuthorizationHeader(serverUrl, "StreamVault"))
+ .header("Accept", "application/json")
+ .post("{}".toRequestBody("application/json".toMediaType()))
+ .build()
+ return executeJsonRequest(request, object : TypeToken<JellyfinQuickConnectInitiateResponseDto>() {}.type, "Quick Connect initiation failed")
+ }
+
+ private fun pollQuickConnectState(serverUrl: String, secret: String): JellyfinQuickConnectStatusResponseDto {
+ val url = buildUrl(serverUrl, "/QuickConnect/Connect", mapOf("Secret" to secret))
+ val request = Request.Builder()
+ .url(url)
+ .header("Authorization", buildJellyfinAuthorizationHeader(serverUrl, "StreamVault"))
+ .header("Accept", "application/json")
+ .get()
+ .build()
+ return executeJsonRequest(request, object : TypeToken<JellyfinQuickConnectStatusResponseDto>() {}.type, "Quick Connect status failed")
+ }
+
+ private fun authenticateWithQuickConnect(serverUrl: String, secret: String): Result<JellyfinQuickConnectAuthenticationResult> {
+ return try {
+ val url = buildUrl(serverUrl, "/Users/AuthenticateWithQuickConnect", emptyMap())
+ val request = Request.Builder()
+ .url(url)
+ .header("Authorization", buildJellyfinAuthorizationHeader(serverUrl, "StreamVault"))
+ .header("Accept", "application/json")
+ .header("Content-Type", "application/json")
+ .post(gson.toJson(JellyfinQuickConnectAuthenticateRequestDto(secret)).toRequestBody("application/json".toMediaType()))
+ .build()
+ val body = executeRequest(request, "Quick Connect authentication failed")
+ val auth = gson.fromJson<JellyfinAuthenticationResultDto>(body, authResultType)
+ val accessToken = auth.accessToken?.takeIf { it.isNotBlank() }
+ ?: throw IllegalStateException("Quick Connect did not return an access token")
+ val userId = auth.user?.id?.takeIf { it.isNotBlank() }
+ ?: auth.sessionInfo?.userId?.takeIf { it.isNotBlank() }
+ ?: throw IllegalStateException("Quick Connect did not return a user id")
+ Result.success(JellyfinQuickConnectAuthenticationResult(accessToken, userId, auth.user?.name ?: ""))
+ } catch (e: Exception) {
+ Result.error("Quick Connect authentication failed: ${e.message}", e)
+ }
+ }
+
+ private fun fetchItems(provider: Provider, path: String, query: Map<String, String>): List<JellyfinItemDto> {
+ val url = buildUrl(provider.serverUrl, path, query)
+ val request = Request.Builder()
+ .url(url)
+ .header("Authorization", buildJellyfinAuthorizationHeader(provider.serverUrl, provider.username, provider.password))
+ .header("Accept", "application/json")
+ .get()
+ .build()
+ val body = executeRequest(request, "Jellyfin request failed")
+ if (body.isBlank()) return emptyList()
+ val parsed = gson.fromJson<JellyfinItemsResponseDto>(body, itemsResponseType)
+ return parsed.items.orEmpty().filter { !it.id.isNullOrBlank() }
+ }
+
+ private fun fetchSeriesEpisodes(provider: Provider, seriesRemoteId: String): List<JellyfinItemDto> {
+ try {
+ val url = buildUrl(provider.serverUrl, "/Shows/$seriesRemoteId/Episodes", mapOf(
+ "Fields" to "Overview,ProviderIds,PremiereDate,RunTimeTicks,Genres,CommunityRating,ImageTags,MediaSources,ParentIndexNumber,IndexNumber",
+ "EnableImages" to "false",
+ "EnableUserData" to "false"
+ ))
+ val request = Request.Builder()
+ .url(url)
+ .header("Authorization", buildJellyfinAuthorizationHeader(provider.serverUrl, provider.username, provider.password))
+ .header("Accept", "application/json")
+ .get()
+ .build()
+ val body = executeRequest(request, "Jellyfin episodes request failed")
+ if (body.isBlank()) return emptyList()
+ val parsed = gson.fromJson<JellyfinSeriesEpisodesResponseDto>(body, seriesResponseType)
+ return parsed.items.orEmpty().filter { !it.id.isNullOrBlank() }
+ } catch (e: Exception) {
+ android.util.Log.e("JellyfinEps", "fetchSeriesEpisodes error for seriesRemoteId=$seriesRemoteId url=${provider.serverUrl}: ${e::class.java.simpleName} msg='${e.message}'", e)
+ throw e
+ }
+ }
+
+ private fun buildMovieEntity(item: JellyfinItemDto, provider: Provider): MovieEntity {
+ val remoteId = item.id.orEmpty()
+ return MovieEntity(
+ streamId = stableRemoteId(remoteId),
+ name = item.name.orEmpty(),
+ posterUrl = buildImageUrl(provider.serverUrl, remoteId, "Primary", item.imageTags?.get("Primary"), provider.password),
+ backdropUrl = item.backdropImageTags?.firstOrNull()?.let { tag ->
+ buildImageUrl(provider.serverUrl, remoteId, "Backdrop", tag, provider.password, imageIndex = 0)
+ },
+ categoryId = MOVIE_CATEGORY_ID,
+ categoryName = "Movies",
+ streamUrl = buildStreamUrl(provider.serverUrl, remoteId),
+ containerExtension = item.primaryMediaSource?.container?.takeIf { it.isNotBlank() },
+ plot = item.overview,
+ genre = item.genres?.joinToString(", "),
+ releaseDate = item.premiereDate?.take(10),
+ duration = item.runTimeTicks?.let(::ticksToDurationString),
+ durationSeconds = item.runTimeTicks?.let(::ticksToSeconds)?.toInt() ?: 0,
+ rating = item.communityRating?.toFloat() ?: 0f,
+ year = item.productionYear?.toString(),
+ tmdbId = item.providerIds?.get("Tmdb")?.toLongOrNull(),
+ providerId = provider.id,
+ isAdult = false,
+ addedAt = item.dateCreated?.let(::parseJellyfinDateMillis) ?: System.currentTimeMillis()
+ )
+ }
+
+ private fun buildSeriesEntity(item: JellyfinItemDto, provider: Provider): SeriesEntity {
+ val remoteId = item.id.orEmpty()
+ return SeriesEntity(
+ seriesId = stableRemoteId(remoteId),
+ providerSeriesId = remoteId,
+ name = item.name.orEmpty(),
+ posterUrl = buildImageUrl(provider.serverUrl, remoteId, "Primary", item.imageTags?.get("Primary"), provider.password),
+ backdropUrl = item.backdropImageTags?.firstOrNull()?.let { tag ->
+ buildImageUrl(provider.serverUrl, remoteId, "Backdrop", tag, provider.password, imageIndex = 0)
+ },
+ categoryId = SERIES_CATEGORY_ID,
+ categoryName = "Series",
+ plot = item.overview,
+ genre = item.genres?.joinToString(", "),
+ releaseDate = item.premiereDate?.take(10),
+ rating = item.communityRating?.toFloat() ?: 0f,
+ tmdbId = item.providerIds?.get("Tmdb")?.toLongOrNull(),
+ episodeRunTime = item.runTimeTicks?.let(::ticksToDurationString),
+ lastModified = (item.dateLastMediaAdded?.let(::parseJellyfinDateMillis)
+ ?: item.dateCreated?.let(::parseJellyfinDateMillis)
+ ?: System.currentTimeMillis()).coerceAtLeast(0L),
+ providerId = provider.id,
+ isAdult = false
+ )
+ }
+
+ private fun buildEpisodeEntity(item: JellyfinItemDto, provider: Provider, seriesLocalId: Long): EpisodeEntity {
+ val remoteId = item.id.orEmpty()
+ return EpisodeEntity(
+ episodeId = stableRemoteId(remoteId),
+ title = item.name.orEmpty(),
+ episodeNumber = item.indexNumber ?: 0,
+ seasonNumber = item.parentIndexNumber ?: 0,
+ streamUrl = buildStreamUrl(provider.serverUrl, remoteId),
+ containerExtension = item.primaryMediaSource?.container?.takeIf { it.isNotBlank() },
+ coverUrl = buildImageUrl(provider.serverUrl, remoteId, "Primary", item.imageTags?.get("Primary"), provider.password),
+ plot = item.overview,
+ duration = item.runTimeTicks?.let(::ticksToDurationString),
+ durationSeconds = item.runTimeTicks?.let(::ticksToSeconds)?.toInt() ?: 0,
+ rating = item.communityRating?.toFloat() ?: 0f,
+ releaseDate = item.premiereDate?.take(10),
+ seriesId = seriesLocalId,
+ providerId = provider.id,
+ isAdult = false
+ )
+ }
+
+ private fun <T> executeJsonRequest(request: Request, responseType: java.lang.reflect.Type, errorPrefix: String): T {
+ val body = executeRequest(request, errorPrefix)
+ @Suppress("UNCHECKED_CAST")
+ return gson.fromJson<T>(body, responseType)
+ }
+
+ private fun executeRequest(request: Request, errorPrefix: String): String {
+ okHttpClient.newBuilder()
+ .callTimeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
+ .build()
+ .newCall(request)
+ .execute()
+ .use { response ->
+ if (!response.isSuccessful) {
+ throw IllegalStateException("$errorPrefix with HTTP ${response.code}")
+ }
+ return response.body?.string().orEmpty()
+ }
+ }
+
+ private fun buildUrl(baseUrl: String, path: String, query: Map<String, String>): String {
+ val normalized = baseUrl.trimEnd('/')
+ val qs = query.entries.joinToString("&") { (k, v) -> "${enc(k)}=${enc(v)}" }
+ return "$normalized$path${if (qs.isNotBlank()) "?$qs" else ""}"
+ }
+
+ private fun buildStreamUrl(baseUrl: String, itemId: String): String =
+ "${baseUrl.trimEnd('/')}/Videos/$itemId/stream"
+
+ private fun buildImageUrl(baseUrl: String, itemId: String, imageType: String, tag: String?, apiKey: String?, imageIndex: Int? = null): String {
+ val qs = buildList {
+ apiKey?.takeIf { it.isNotBlank() }?.let { add("api_key=${enc(it)}") }
+ tag?.takeIf { it.isNotBlank() }?.let { add("tag=${enc(it)}") }
+ }.joinToString("&")
+ val path = if (imageIndex != null) "/Items/$itemId/Images/$imageType/$imageIndex" else "/Items/$itemId/Images/$imageType"
+ return "${baseUrl.trimEnd('/')}$path${if (qs.isNotBlank()) "?$qs" else ""}"
+ }
+
+ private fun stableRemoteId(value: String): Long {
+ val digest = java.security.MessageDigest.getInstance("SHA-256").digest(value.toByteArray(Charsets.UTF_8))
+ var result = 0L
+ for (i in 0 until 8) result = (result shl 8) or (digest[i].toLong() and 0xff)
+ return result and Long.MAX_VALUE
+ }
+
+ private fun enc(value: String): String = URLEncoder.encode(value, Charsets.UTF_8.name())
+ private fun ticksToSeconds(ticks: Long): Long = ticks / 10_000_000L
+ private fun ticksToDurationString(ticks: Long): String {
+ val total = ticksToSeconds(ticks)
+ val h = total / 3600; val m = (total % 3600) / 60; val s = total % 60
+ return if (h > 0) "%d:%02d:%02d".format(h, m, s) else "%02d:%02d".format(m, s)
+ }
+ private fun parseJellyfinDateMillis(value: String): Long =
+ runCatching { java.time.Instant.parse(value).toEpochMilli() }.getOrDefault(0L)
+}
+
+private data class JellyfinAuthenticateRequestDto(
+ @SerializedName("Username") val username: String,
+ @SerializedName("Pw") val password: String
+)
+
+private data class JellyfinAuthenticationResultDto(
+ @SerializedName("AccessToken") val accessToken: String? = null,
+ @SerializedName("User") val user: JellyfinAuthenticatedUserDto? = null,
+ @SerializedName("SessionInfo") val sessionInfo: JellyfinSessionInfoDto? = null
+)
+
+private data class JellyfinItemsResponseDto(
+ @SerializedName("Items") val items: List<JellyfinItemDto>? = emptyList()
+)
+
+private data class JellyfinSeriesEpisodesResponseDto(
+ @SerializedName("Items") val items: List<JellyfinItemDto>? = emptyList()
+)
+
+private data class JellyfinItemDto(
+ @SerializedName("Id") val id: String? = null,
+ @SerializedName("Name") val name: String? = null,
+ @SerializedName("Overview") val overview: String? = null,
+ @SerializedName("PremiereDate") val premiereDate: String? = null,
+ @SerializedName("ProductionYear") val productionYear: Int? = null,
+ @SerializedName("RunTimeTicks") val runTimeTicks: Long? = null,
+ @SerializedName("CommunityRating") val communityRating: Double? = null,
+ @SerializedName("ProviderIds") val providerIds: Map<String, String>? = null,
+ @SerializedName("Genres") val genres: List<String>? = null,
+ @SerializedName("DateCreated") val dateCreated: String? = null,
+ @SerializedName("DateLastMediaAdded") val dateLastMediaAdded: String? = null,
+ @SerializedName("ImageTags") val imageTags: Map<String, String>? = null,
+ @SerializedName("BackdropImageTags") val backdropImageTags: List<String>? = null,
+ @SerializedName("ParentIndexNumber") val parentIndexNumber: Int? = null,
+ @SerializedName("IndexNumber") val indexNumber: Int? = null,
+ @SerializedName("MediaSources") val mediaSources: List<JellyfinMediaSourceDto>? = null
+) {
+ val primaryMediaSource: JellyfinMediaSourceDto? get() = mediaSources?.firstOrNull()
+}
+
+private data class JellyfinMediaSourceDto(
+ @SerializedName("Id") val id: String? = null,
+ @SerializedName("Container") val container: String? = null
+)
+
+private data class JellyfinAuthenticatedSession(val accessToken: String, val userId: String, val userName: String)
+private data class JellyfinAuthenticatedUserDto(@SerializedName("Id") val id: String? = null, @SerializedName("Name") val name: String? = null)
+private data class JellyfinSessionInfoDto(@SerializedName("UserId") val userId: String? = null)
+
+private data class JellyfinQuickConnectInitiateResponseDto(
+ @SerializedName("Code") val code: String? = null,
+ @SerializedName("Secret") val secret: String? = null
+)
+
+private data class JellyfinQuickConnectStatusResponseDto(@SerializedName("Authenticated") val authenticated: Boolean = false)
+
+private data class JellyfinQuickConnectAuthenticateRequestDto(@SerializedName("Secret") val secret: String)
+
+data class JellyfinQuickConnectAuthenticationResult(val accessToken: String, val userId: String, val userName: String)
diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt
index d04109ea..735c3053 100644
--- a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt
+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt
@@ -200,6 +200,8 @@ class XtreamStreamUrlResolver @Inject constructor(
)
)
}
+ ProviderType.M3U,
+ ProviderType.JELLYFIN -> null
}
}
diff --git a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
index d1fa16ee..68d0f798 100644
--- a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
@@ -397,6 +397,7 @@ class MovieRepositoryImpl @Inject constructor(
ProviderType.XTREAM_CODES -> getOrCreateXtreamProvider(providerId, provider).getVodInfo(movieEntity.streamId)
ProviderType.STALKER_PORTAL -> return Result.success(movieEntity.toDomain())
ProviderType.M3U -> return Result.success(movieEntity.toDomain())
+ ProviderType.JELLYFIN -> return Result.success(movieEntity.toDomain())
}
} catch (e: Exception) {
if (provider.type == ProviderType.XTREAM_CODES) {
diff --git a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt
index e9575717..7a2bb50c 100644
--- a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt
@@ -8,6 +8,7 @@ import com.streamvault.data.manager.reminder.ProgramReminderAlarmScheduler
import com.streamvault.data.mapper.*
import com.streamvault.data.preferences.PreferencesRepository
import com.streamvault.data.remote.http.buildGenericProviderRequestProfile
+import com.streamvault.data.remote.jellyfin.JellyfinProvider
import com.streamvault.data.remote.stalker.StalkerApiService
import com.streamvault.data.remote.stalker.StalkerPlaybackMode
import com.streamvault.data.remote.stalker.StalkerProvider
@@ -56,7 +57,8 @@ class ProviderRepositoryImpl @Inject constructor(
private val syncMetadataRepository: SyncMetadataRepository,
private val transactionRunner: DatabaseTransactionRunner,
private val recordingAlarmScheduler: RecordingAlarmScheduler,
- private val programReminderAlarmScheduler: ProgramReminderAlarmScheduler
+ private val programReminderAlarmScheduler: ProgramReminderAlarmScheduler,
+ private val jellyfinProvider: JellyfinProvider
) : ProviderRepository {
private companion object {
const val XTREAM_GUIDE_BATCH_CONCURRENCY = 4
@@ -345,6 +347,121 @@ class ProviderRepositoryImpl @Inject constructor(
Result.error("Failed to add M3U provider: ${e.message}", e)
}
+ override suspend fun loginJellyfin(
+ serverUrl: String,
+ username: String,
+ password: String,
+ name: String,
+ onProgress: ((String) -> Unit)?,
+ id: Long?
+ ): Result<Provider> {
+ return try {
+ val normalizedServerUrl = ProviderInputSanitizer.normalizeUrl(serverUrl)
+ val normalizedUsername = ProviderInputSanitizer.normalizeUsername(username)
+ val normalizedPassword = ProviderInputSanitizer.normalizePassword(password)
+ val normalizedName = ProviderInputSanitizer.normalizeProviderName(name)
+ ProviderInputSanitizer.validateUrl(normalizedServerUrl)?.let { return Result.error(it) }
+ if (normalizedUsername.isBlank()) return Result.error("Please enter Jellyfin username")
+ val providerName = normalizedName.ifBlank {
+ normalizedServerUrl.substringAfter("//").substringBefore("/").ifBlank { "Jellyfin" }
+ }
+ val existingProviderEntity = if (id != null) {
+ val collision = providerDao.getByUrlAndUser(normalizedServerUrl, normalizedUsername)
+ if (collision != null && collision.id != id) return Result.error("A Jellyfin provider with this server URL and username already exists.")
+ providerDao.getById(id)
+ } else {
+ providerDao.getByUrlAndUser(normalizedServerUrl, normalizedUsername)
+ }
+ val existingProvider = existingProviderEntity?.toDomain()
+ val authResult = when {
+ normalizedPassword.isNotBlank() -> {
+ onProgress?.invoke("Signing in to Jellyfin...")
+ when (val loginResult = jellyfinProvider.authenticate(normalizedServerUrl, normalizedUsername, normalizedPassword)) {
+ is Result.Success -> loginResult.data
+ is Result.Error -> return Result.error(loginResult.message, loginResult.exception)
+ is Result.Loading -> return Result.error("Unexpected loading state")
+ }
+ }
+ existingProvider != null -> try { credentialCrypto.decryptIfNeeded(existingProvider.password) }
+ catch (e: CredentialDecryptionException) { return Result.error(e.message ?: CredentialDecryptionException.MESSAGE, e) }
+ else -> return Result.error("Please enter Jellyfin password")
+ }
+ val providerData = if (existingProvider != null) {
+ val updated = existingProvider.copy(
+ name = providerName.ifBlank { existingProvider.name }, type = ProviderType.JELLYFIN,
+ serverUrl = normalizedServerUrl, username = normalizedUsername, password = authResult,
+ m3uUrl = "", epgUrl = "", httpUserAgent = "", httpHeaders = "",
+ isActive = false, status = ProviderStatus.PARTIAL, lastSyncedAt = 0
+ )
+ providerDao.update(updated.toSecureEntity())
+ updated.copy(password = "")
+ } else {
+ val provider = Provider(name = providerName, type = ProviderType.JELLYFIN,
+ serverUrl = normalizedServerUrl, username = normalizedUsername, password = authResult,
+ isActive = false, status = ProviderStatus.PARTIAL)
+ val newId = providerDao.insert(provider.toSecureEntity())
+ provider.copy(id = newId).copy(password = "")
+ }
+ handleInitialOnboardingSync(providerData = providerData,
+ syncResult = syncManager.sync(providerData.id, force = false, onProgress = onProgress),
+ syncFailurePrefix = "Jellyfin provider saved, but initial sync failed. The provider was saved and can be retried from Settings")
+ } catch (e: Exception) {
+ Result.error("Failed to add Jellyfin provider: ${e.message}", e)
+ }
+ }
+
+ override suspend fun loginJellyfinQuickConnect(
+ serverUrl: String, name: String, onCode: ((String) -> Unit)?, onProgress: ((String) -> Unit)?, id: Long?
+ ): Result<Provider> {
+ return try {
+ val normalizedServerUrl = ProviderInputSanitizer.normalizeUrl(serverUrl)
+ val normalizedName = ProviderInputSanitizer.normalizeProviderName(name)
+ ProviderInputSanitizer.validateUrl(normalizedServerUrl)?.let { return Result.error(it) }
+ val providerName = normalizedName.ifBlank {
+ normalizedServerUrl.substringAfter("//").substringBefore("/").ifBlank { "Jellyfin" }
+ }
+ val existingProvider = if (id != null) providerDao.getById(id)?.toDomain() else null
+ onProgress?.invoke("Requesting Quick Connect code...")
+ val quickConnect = when (val quickConnectResult = jellyfinProvider.authenticateQuickConnect(
+ serverUrl = normalizedServerUrl, onCode = onCode, onProgress = onProgress
+ )) {
+ is Result.Success -> quickConnectResult.data
+ is Result.Error -> return Result.error(quickConnectResult.message, quickConnectResult.exception)
+ is Result.Loading -> return Result.error("Unexpected loading state")
+ }
+ val providerData = saveJellyfinProvider(providerName = providerName,
+ serverUrl = normalizedServerUrl, username = quickConnect.userName.ifBlank { providerName },
+ password = quickConnect.accessToken, existingProvider = existingProvider)
+ handleInitialOnboardingSync(providerData = providerData,
+ syncResult = syncManager.sync(providerData.id, force = false, onProgress = onProgress),
+ syncFailurePrefix = "Jellyfin provider saved, but initial sync failed. The provider was saved and can be retried from Settings")
+ } catch (e: Exception) {
+ Result.error("Failed to add Jellyfin provider: ${e.message}", e)
+ }
+ }
+
+ private suspend fun saveJellyfinProvider(
+ providerName: String, serverUrl: String, username: String, password: String, existingProvider: Provider?
+ ): Provider {
+ return if (existingProvider != null) {
+ val updated = existingProvider.copy(
+ name = providerName.ifBlank { existingProvider.name }, type = ProviderType.JELLYFIN,
+ serverUrl = serverUrl, username = username, password = password,
+ m3uUrl = "", epgUrl = "", httpUserAgent = "", httpHeaders = "",
+ isActive = false, status = ProviderStatus.PARTIAL, lastSyncedAt = 0
+ )
+ providerDao.update(updated.toSecureEntity())
+ updated.copy(password = "")
+ } else {
+ val provider = Provider(name = providerName, type = ProviderType.JELLYFIN,
+ serverUrl = serverUrl, username = username, password = password,
+ isActive = false, status = ProviderStatus.PARTIAL)
+ val newId = providerDao.insert(provider.toSecureEntity())
+ provider.copy(id = newId).copy(password = "")
+ }
+ }
+
+
override suspend fun loginStalker(
portalUrl: String,
macAddress: String,
@@ -643,7 +760,8 @@ class ProviderRepositoryImpl @Inject constructor(
is Result.Loading -> Result.error("Unexpected loading state")
}
}
- ProviderType.M3U -> Result.error("On-demand guide lookup is unavailable for this provider.")
+ ProviderType.M3U,
+ ProviderType.JELLYFIN -> Result.error("On-demand guide lookup is unavailable for this provider.")
}
}
@@ -714,7 +832,8 @@ class ProviderRepositoryImpl @Inject constructor(
}
results
}
- ProviderType.M3U -> normalizedRequests.associateWith {
+ ProviderType.M3U,
+ ProviderType.JELLYFIN -> normalizedRequests.associateWith {
Result.error("On-demand guide lookup is unavailable for this provider.")
}
}
@@ -751,6 +870,7 @@ class ProviderRepositoryImpl @Inject constructor(
sourceStreamUrl = channel?.streamUrl,
sourceCatchUpSource = channel?.catchUpSource
)
+ ProviderType.JELLYFIN -> emptyList()
}
}
diff --git a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
index 613dc6af..30311fd5 100644
--- a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
@@ -5,6 +5,7 @@ import android.util.Log
import com.streamvault.data.local.dao.*
import com.streamvault.data.local.entity.*
import com.streamvault.data.mapper.*
+import com.streamvault.data.remote.jellyfin.JellyfinProvider
import com.streamvault.data.remote.http.toGenericRequestProfile
import com.streamvault.data.remote.stalker.StalkerApiService
import com.streamvault.data.remote.stalker.StalkerPlaybackMode
@@ -64,7 +65,8 @@ class SeriesRepositoryImpl @Inject constructor(
private val xtreamContentIndexDao: XtreamContentIndexDao,
private val xtreamIndexJobDao: XtreamIndexJobDao,
private val syncManager: SyncManager,
- private val seriesCategoryHydrationDao: SeriesCategoryHydrationDao
+ private val seriesCategoryHydrationDao: SeriesCategoryHydrationDao,
+ private val jellyfinProvider: JellyfinProvider
) : SeriesRepository {
private companion object {
const val TAG = "SeriesRepository"
@@ -360,6 +362,33 @@ class SeriesRepositoryImpl @Inject constructor(
seriesEntity.providerSeriesId?.takeIf { it.isNotBlank() } ?: seriesEntity.seriesId.toString()
)
ProviderType.M3U -> return Result.success(buildSeriesWithPersistedEpisodes(seriesEntity))
+ ProviderType.JELLYFIN -> {
+ val remoteId = seriesEntity.providerSeriesId?.takeIf { it.isNotBlank() }
+ ?: return Result.success(buildSeriesWithPersistedEpisodes(seriesEntity))
+ val decryptedPassword = credentialCrypto.decryptIfNeeded(provider.password)
+ when (val episodesResult = jellyfinProvider.fetchEpisodes(
+ provider = com.streamvault.domain.model.Provider(
+ id = providerId, name = "Jellyfin", type = ProviderType.JELLYFIN,
+ serverUrl = provider.serverUrl, username = provider.username,
+ password = decryptedPassword
+ ),
+ seriesRemoteId = remoteId,
+ seriesLocalId = seriesEntity.id
+ )) {
+ is com.streamvault.domain.model.Result.Success -> {
+ if (episodesResult.data.isNotEmpty()) {
+ episodeDao.replaceAll(seriesEntity.id, providerId, episodesResult.data)
+ }
+ return Result.success(buildSeriesWithPersistedEpisodes(seriesEntity))
+ }
+ is com.streamvault.domain.model.Result.Error -> {
+ Log.w(TAG, "Failed to fetch Jellyfin episodes: ${episodesResult.message}")
+ return Result.success(buildSeriesWithPersistedEpisodes(seriesEntity))
+ }
+ is com.streamvault.domain.model.Result.Loading -> {}
+ }
+ return Result.success(buildSeriesWithPersistedEpisodes(seriesEntity))
+ }
}
} catch (e: Exception) {
if (provider.type == ProviderType.XTREAM_CODES) {
diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
index 167b863c..548d557f 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
@@ -6,6 +6,7 @@ import com.streamvault.data.local.DatabaseTransactionRunner
import com.streamvault.data.local.dao.CatalogSyncDao
import com.streamvault.data.local.dao.CategoryDao
import com.streamvault.data.local.dao.ChannelDao
+import com.streamvault.data.local.dao.EpisodeDao
import com.streamvault.data.local.dao.MovieCategoryHydrationDao
import com.streamvault.data.local.dao.MovieDao
import com.streamvault.data.local.dao.ProgramDao
@@ -33,6 +34,7 @@ import com.streamvault.data.remote.stalker.StalkerApiService
import com.streamvault.data.remote.stalker.StalkerPlaybackMode
import com.streamvault.data.remote.stalker.StalkerProvider
import com.streamvault.data.remote.stalker.StalkerProviderProfile
+import com.streamvault.data.remote.jellyfin.JellyfinProvider
import com.streamvault.data.remote.stalker.StalkerTrafficCoordinator
import com.streamvault.data.remote.dto.XtreamCategory
import com.streamvault.data.remote.dto.XtreamSeriesItem
@@ -180,6 +182,8 @@ class SyncManager @Inject constructor(
private val xtreamIndexJobDao: XtreamIndexJobDao,
private val xtreamLiveOnboardingDao: XtreamLiveOnboardingDao,
private val stalkerApiService: StalkerApiService,
+ private val episodeDao: EpisodeDao,
+ private val jellyfinProvider: JellyfinProvider,
private val xtreamJson: Json,
private val m3uParser: M3uParser,
private val epgRepository: EpgRepository,
@@ -690,6 +694,7 @@ class SyncManager @Inject constructor(
)
ProviderType.M3U -> syncM3u(provider, force, onProgress)
ProviderType.STALKER_PORTAL -> syncStalker(provider, force, onProgress)
+ ProviderType.JELLYFIN -> syncJellyfin(provider, force, onProgress)
}
}
providerDao.updateSyncTime(providerId, System.currentTimeMillis())
@@ -4080,6 +4085,83 @@ class SyncManager @Inject constructor(
return if (warnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = warnings)
}
+ private suspend fun syncJellyfin(
+ provider: Provider,
+ force: Boolean,
+ onProgress: ((String) -> Unit)?
+ ): SyncOutcome {
+ val warnings = mutableListOf<String>()
+ try {
+ val decryptedPassword = credentialCrypto.decryptIfNeeded(provider.password)
+ val tokenPreview = decryptedPassword.take(8)
+ android.util.Log.e("JellyfinSync", "syncJellyfin: provider=${provider.id} url=${provider.serverUrl} user=${provider.username} pwd.len=${provider.password.length} pwd.prefix=${provider.password.take(10)} decrypted.len=${decryptedPassword.length} token=$tokenPreview")
+ val decryptedProvider = provider.copy(password = decryptedPassword)
+ progress(provider.id, onProgress, "Loading Jellyfin library...")
+ val (resolvedMovies, resolvedSeries) = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
+ val movieResult = jellyfinProvider.fetchMovies(decryptedProvider)
+ val seriesResult = jellyfinProvider.fetchSeries(decryptedProvider)
+ movieResult to seriesResult
+ }
+ if (resolvedMovies is com.streamvault.domain.model.Result.Error) android.util.Log.e("JellyfinSync", "Movies error: ${resolvedMovies.message}")
+ if (resolvedSeries is com.streamvault.domain.model.Result.Error) android.util.Log.e("JellyfinSync", "Series error: ${resolvedSeries.message}")
+
+ if (resolvedMovies is com.streamvault.domain.model.Result.Error && resolvedSeries is com.streamvault.domain.model.Result.Error) {
+ warnings.add("Failed to load Jellyfin catalog: ${resolvedMovies.message}; ${resolvedSeries.message}")
+ return SyncOutcome(partial = true, warnings = warnings)
+ }
+
+ val movieEntities = (resolvedMovies as? com.streamvault.domain.model.Result.Success)?.data.orEmpty()
+ val seriesEntities = (resolvedSeries as? com.streamvault.domain.model.Result.Success)?.data.orEmpty()
+
+ if (movieEntities.isNotEmpty()) {
+ progress(provider.id, onProgress, "Importing Jellyfin movies...")
+ movieEntities.chunked(50).forEach { chunk ->
+ transactionRunner.inTransaction {
+ movieDao.upsertCategoryPage(provider.id, chunk)
+ }
+ }
+ transactionRunner.inTransaction {
+ categoryDao.replaceAll(provider.id, com.streamvault.domain.model.ContentType.MOVIE.name, listOf(
+ com.streamvault.data.local.entity.CategoryEntity(
+ providerId = provider.id, categoryId = 1L, name = "Movies",
+ type = com.streamvault.domain.model.ContentType.MOVIE
+ )
+ ))
+ }
+ }
+
+ if (seriesEntities.isNotEmpty()) {
+ progress(provider.id, onProgress, "Importing Jellyfin series...")
+ seriesEntities.forEach { seriesEntity ->
+ val remoteId = seriesEntity.providerSeriesId
+ if (!remoteId.isNullOrBlank()) {
+ transactionRunner.inTransaction {
+ seriesDao.insertAll(listOf(seriesEntity))
+ }
+ }
+ }
+ transactionRunner.inTransaction {
+ categoryDao.replaceAll(provider.id, com.streamvault.domain.model.ContentType.SERIES.name, listOf(
+ com.streamvault.data.local.entity.CategoryEntity(
+ providerId = provider.id, categoryId = 2L, name = "Series",
+ type = com.streamvault.domain.model.ContentType.SERIES
+ )
+ ))
+ }
+ }
+
+ if (movieEntities.isEmpty() && seriesEntities.isEmpty()) {
+ warnings.add("Jellyfin library is empty or contains no supported movies or series.")
+ return SyncOutcome(partial = true, warnings = warnings)
+ }
+
+ return SyncOutcome(warnings = warnings)
+ } catch (e: Exception) {
+ warnings.add("Jellyfin sync failed: ${e.message.orEmpty()}")
+ return SyncOutcome(partial = true, warnings = warnings)
+ }
+ }
+
/**
* Returned by [syncProviderEpg] so callers can distinguish between warning-only
* degradations and transient network/IO failures that WorkManager should retry.
@@ -4199,6 +4281,8 @@ class SyncManager @Inject constructor(
updatedMetadata = syncMetadataRepository.getMetadata(provider.id) ?: updatedMetadata
}
}
+
+ ProviderType.JELLYFIN -> Unit
}
try {
@@ -4254,6 +4338,7 @@ class SyncManager @Inject constructor(
}
ProviderType.M3U -> providerDao.getById(provider.id)?.epgUrl ?: provider.epgUrl
ProviderType.STALKER_PORTAL -> providerDao.getById(provider.id)?.epgUrl ?: provider.epgUrl
+ ProviderType.JELLYFIN -> ""
}
if (epgUrl.isBlank()) {
if (provider.type == ProviderType.STALKER_PORTAL) {
@@ -4274,6 +4359,7 @@ class SyncManager @Inject constructor(
ProviderType.XTREAM_CODES -> UrlSecurityPolicy.validateXtreamEpgUrl(epgUrl)
ProviderType.M3U -> UrlSecurityPolicy.validateOptionalEpgUrl(epgUrl)
ProviderType.STALKER_PORTAL -> UrlSecurityPolicy.validateOptionalEpgUrl(epgUrl)
+ ProviderType.JELLYFIN -> null
}
validationError?.let { message ->
throw IllegalStateException(message)
@@ -4740,6 +4826,8 @@ class SyncManager @Inject constructor(
)
sectionWarnings += liveCatalogResult.warnings
}
+
+ ProviderType.JELLYFIN -> throw IllegalStateException("Live TV retry is unavailable for Jellyfin providers")
}
return if (sectionWarnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = sectionWarnings)
}
@@ -4849,6 +4937,8 @@ class SyncManager @Inject constructor(
syncMetadataRepository.updateMetadata(metadata)
scheduleStalkerIndexContinuation(provider, ContentType.MOVIE, force = true)
}
+
+ ProviderType.JELLYFIN -> throw IllegalStateException("Movies retry is unavailable for Jellyfin providers")
}
return if (sectionWarnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = sectionWarnings)
}
@@ -4936,6 +5026,8 @@ class SyncManager @Inject constructor(
ProviderType.M3U -> {
throw IllegalStateException("Series retry is unavailable for this provider")
}
+
+ ProviderType.JELLYFIN -> throw IllegalStateException("Series retry is unavailable for Jellyfin providers")
}
return if (sectionWarnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = sectionWarnings)
}
diff --git a/data/src/main/java/com/streamvault/data/validation/ProviderSetupInputValidatorImpl.kt b/data/src/main/java/com/streamvault/data/validation/ProviderSetupInputValidatorImpl.kt
index 5b80ccda..04813cec 100644
--- a/data/src/main/java/com/streamvault/data/validation/ProviderSetupInputValidatorImpl.kt
+++ b/data/src/main/java/com/streamvault/data/validation/ProviderSetupInputValidatorImpl.kt
@@ -3,6 +3,8 @@ package com.streamvault.data.validation
import com.streamvault.data.util.ProviderInputSanitizer
import com.streamvault.data.util.UrlSecurityPolicy
import com.streamvault.domain.manager.ProviderSetupInputValidator
+import com.streamvault.domain.manager.ValidatedJellyfinProviderInput
+import com.streamvault.domain.manager.ValidatedJellyfinQuickConnectProviderInput
import com.streamvault.domain.manager.ValidatedM3uProviderInput
import com.streamvault.domain.manager.ValidatedStalkerProviderInput
import com.streamvault.domain.manager.ValidatedXtreamProviderInput
@@ -250,6 +252,34 @@ class ProviderSetupInputValidatorImpl @Inject constructor() : ProviderSetupInput
)
}
+ override fun validateJellyfin(
+ serverUrl: String,
+ username: String,
+ password: String,
+ name: String,
+ allowBlankPassword: Boolean
+ ): Result<ValidatedJellyfinProviderInput> {
+ val trimmedUrl = serverUrl.trim()
+ if (trimmedUrl.isBlank()) return Result.error("Server URL is required")
+ if (!trimmedUrl.startsWith("http://") && !trimmedUrl.startsWith("https://")) {
+ return Result.error("Server URL must start with http:// or https://")
+ }
+ val trimmedName = name.trim().ifBlank { trimmedUrl.substringAfter("//").substringBefore("/").ifBlank { "Jellyfin" } }
+ val trimmedUser = username.trim()
+ if (!allowBlankPassword && password.isBlank()) return Result.error("Password is required")
+ return Result.success(ValidatedJellyfinProviderInput(serverUrl = trimmedUrl, username = trimmedUser, password = password.trim(), name = trimmedName))
+ }
+
+ override fun validateJellyfinQuickConnect(serverUrl: String, name: String): Result<ValidatedJellyfinQuickConnectProviderInput> {
+ val trimmedUrl = serverUrl.trim()
+ if (trimmedUrl.isBlank()) return Result.error("Server URL is required")
+ if (!trimmedUrl.startsWith("http://") && !trimmedUrl.startsWith("https://")) {
+ return Result.error("Server URL must start with http:// or https://")
+ }
+ val trimmedName = name.trim().ifBlank { trimmedUrl.substringAfter("//").substringBefore("/").ifBlank { "Jellyfin" } }
+ return Result.success(ValidatedJellyfinQuickConnectProviderInput(serverUrl = trimmedUrl, name = trimmedName))
+ }
+
private companion object {
private val HEADER_SEPARATOR_REGEX = Regex("\\s*\\|\\s*|[\\r\\n]+")
private val DISALLOWED_GENERIC_HEADER_NAMES = setOf(
diff --git a/domain/src/main/java/com/streamvault/domain/manager/ProviderSetupInputValidator.kt b/domain/src/main/java/com/streamvault/domain/manager/ProviderSetupInputValidator.kt
index 82a4aaa0..5e395065 100644
--- a/domain/src/main/java/com/streamvault/domain/manager/ProviderSetupInputValidator.kt
+++ b/domain/src/main/java/com/streamvault/domain/manager/ProviderSetupInputValidator.kt
@@ -35,6 +35,18 @@ data class ValidatedStalkerProviderInput(
val signature: String = ""
)
+data class ValidatedJellyfinProviderInput(
+ val serverUrl: String,
+ val username: String,
+ val password: String,
+ val name: String
+)
+
+data class ValidatedJellyfinQuickConnectProviderInput(
+ val serverUrl: String,
+ val name: String
+)
+
interface ProviderSetupInputValidator {
fun validateXtream(
serverUrl: String,
@@ -69,4 +81,17 @@ interface ProviderSetupInputValidator {
deviceId2: String = "",
signature: String = ""
): Result<ValidatedStalkerProviderInput>
+
+ fun validateJellyfin(
+ serverUrl: String,
+ username: String,
+ password: String,
+ name: String,
+ allowBlankPassword: Boolean = false
+ ): Result<ValidatedJellyfinProviderInput>
+
+ fun validateJellyfinQuickConnect(
+ serverUrl: String,
+ name: String
+ ): Result<ValidatedJellyfinQuickConnectProviderInput>
}
diff --git a/domain/src/main/java/com/streamvault/domain/model/Provider.kt b/domain/src/main/java/com/streamvault/domain/model/Provider.kt
index 3f838bde..f6286a80 100644
--- a/domain/src/main/java/com/streamvault/domain/model/Provider.kt
+++ b/domain/src/main/java/com/streamvault/domain/model/Provider.kt
@@ -61,7 +61,8 @@ data class Provider(
enum class ProviderType {
XTREAM_CODES,
M3U,
- STALKER_PORTAL
+ STALKER_PORTAL,
+ JELLYFIN
}
enum class ProviderEpgSyncMode {
diff --git a/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt
index bf322db3..7df50828 100644
--- a/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt
+++ b/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt
@@ -62,6 +62,21 @@ interface ProviderRepository {
onProgress: ((String) -> Unit)? = null,
id: Long? = null
): Result<Provider>
+ suspend fun loginJellyfin(
+ serverUrl: String,
+ username: String,
+ password: String,
+ name: String,
+ onProgress: ((String) -> Unit)? = null,
+ id: Long? = null
+ ): Result<Provider>
+ suspend fun loginJellyfinQuickConnect(
+ serverUrl: String,
+ name: String,
+ onCode: ((String) -> Unit)? = null,
+ onProgress: ((String) -> Unit)? = null,
+ id: Long? = null
+ ): Result<Provider>
suspend fun refreshProviderData(
providerId: Long,
force: Boolean = false,
diff --git a/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt b/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt
index e5d45555..baa3c06d 100644
--- a/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt
+++ b/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt
@@ -54,6 +54,20 @@ data class StalkerProviderSetupCommand(
val existingProviderId: Long? = null
)
+data class JellyfinProviderSetupCommand(
+ val serverUrl: String,
+ val username: String,
+ val password: String,
+ val name: String,
+ val existingProviderId: Long? = null
+)
+
+data class JellyfinQuickConnectProviderSetupCommand(
+ val serverUrl: String,
+ val name: String,
+ val existingProviderId: Long? = null
+)
+
sealed class ValidateAndAddProviderResult {
data class Success(val provider: Provider) : ValidateAndAddProviderResult()
data class SavedWithWarning(val provider: Provider, val warning: String) : ValidateAndAddProviderResult()
@@ -274,6 +288,57 @@ class ValidateAndAddProvider @Inject constructor(
}
}
+ suspend fun loginJellyfin(
+ command: JellyfinProviderSetupCommand,
+ onProgress: ((String) -> Unit)? = null
+ ): ValidateAndAddProviderResult {
+ return when (
+ val validated = providerSetupInputValidator.validateJellyfin(
+ serverUrl = command.serverUrl,
+ username = command.username,
+ password = command.password,
+ allowBlankPassword = command.existingProviderId != null,
+ name = command.name
+ )
+ ) {
+ is Result.Success -> providerRepository.loginJellyfin(
+ serverUrl = validated.data.serverUrl,
+ username = validated.data.username,
+ password = validated.data.password,
+ name = validated.data.name,
+ onProgress = onProgress,
+ id = command.existingProviderId
+ ).toUseCaseResult()
+
+ is Result.Error -> ValidateAndAddProviderResult.ValidationError(validated.message)
+ is Result.Loading -> ValidateAndAddProviderResult.Error("Unexpected loading state")
+ }
+ }
+
+ suspend fun loginJellyfinQuickConnect(
+ command: JellyfinQuickConnectProviderSetupCommand,
+ onCode: ((String) -> Unit)? = null,
+ onProgress: ((String) -> Unit)? = null
+ ): ValidateAndAddProviderResult {
+ return when (
+ val validated = providerSetupInputValidator.validateJellyfinQuickConnect(
+ serverUrl = command.serverUrl,
+ name = command.name
+ )
+ ) {
+ is Result.Success -> providerRepository.loginJellyfinQuickConnect(
+ serverUrl = validated.data.serverUrl,
+ name = validated.data.name,
+ onCode = onCode,
+ onProgress = onProgress,
+ id = command.existingProviderId
+ ).toUseCaseResult()
+
+ is Result.Error -> ValidateAndAddProviderResult.ValidationError(validated.message)
+ is Result.Loading -> ValidateAndAddProviderResult.Error("Unexpected loading state")
+ }
+ }
+
private fun Result<Provider>.toUseCaseResult(): ValidateAndAddProviderResult = when (this) {
is Result.Success -> ValidateAndAddProviderResult.Success(data)
is Result.Error -> {