Skip to content

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

feat: complete OpenSubtitles subtitle integration

David Nashash8f6af201ce38
diff --git a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt b/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt
index 9c771431..44e0e312 100644
--- a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt
+++ b/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt
@@ -22,6 +22,7 @@ import com.streamvault.data.remote.xtream.PlaybackObservationCoordinator
import com.streamvault.data.remote.xtream.PlaybackObservationSink
import com.streamvault.data.validation.ProviderSetupInputValidatorImpl
import com.streamvault.domain.manager.ParentalPinVerifier
+import com.streamvault.domain.manager.OpenSubtitlesAccountManager
import com.streamvault.domain.manager.ProviderSetupInputValidator
import com.streamvault.domain.manager.ProviderSyncStateReader
import com.streamvault.data.repository.*
@@ -100,6 +101,9 @@ abstract class RepositoryModule {
@Binds @Singleton
abstract fun bindExternalSubtitleRepository(impl: OpenSubtitlesRepositoryImpl): ExternalSubtitleRepository
+ @Binds @Singleton
+ abstract fun bindOpenSubtitlesAccountManager(impl: OpenSubtitlesRepositoryImpl): OpenSubtitlesAccountManager
+
@Binds @Singleton
abstract fun bindSyncMetadataRepository(impl: SyncMetadataRepositoryImpl): SyncMetadataRepository
diff --git a/data/src/main/java/com/streamvault/data/remote/subtitle/OpenSubtitlesApi.kt b/data/src/main/java/com/streamvault/data/remote/subtitle/OpenSubtitlesApi.kt
index 1ffcd91a..747fff8f 100644
--- a/data/src/main/java/com/streamvault/data/remote/subtitle/OpenSubtitlesApi.kt
+++ b/data/src/main/java/com/streamvault/data/remote/subtitle/OpenSubtitlesApi.kt
@@ -15,6 +15,7 @@ import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
+import okhttp3.logging.HttpLoggingInterceptor
internal const val OPENSUBTITLES_DEFAULT_BASE_URL = "https://api.opensubtitles.com/api/v1"
internal const val OPENSUBTITLES_DEFAULT_BASE_HOST = "api.opensubtitles.com"
@@ -27,7 +28,8 @@ class OpenSubtitlesApi @Inject constructor(
data class DownloadLink(
val url: String,
val fileName: String,
- val remaining: Int,
+ val remaining: Int?,
+ val resetTimeUtc: String?,
)
data class SearchQuery(
@@ -62,10 +64,10 @@ class OpenSubtitlesApi @Inject constructor(
Result.error("OpenSubtitles login failed: ${e.message}", e)
}
- suspend fun logout(token: String): Result<Unit> = try {
+ suspend fun logout(token: String, baseUrlHost: String): Result<Unit> = try {
withContext(Dispatchers.IO) {
val request = Request.Builder()
- .url("$OPENSUBTITLES_DEFAULT_BASE_URL/logout")
+ .url(buildUrl(baseUrlHost, "/logout", emptyMap()))
.header("Accept", "application/json")
.header("Api-Key", API_KEY)
.header("Authorization", "Bearer $token")
@@ -127,7 +129,8 @@ class OpenSubtitlesApi @Inject constructor(
DownloadLink(
url = url,
fileName = response.fileName.orEmpty(),
- remaining = response.remaining ?: 0,
+ remaining = response.remaining,
+ resetTimeUtc = response.resetTimeUtc,
)
}
Result.success(link)
@@ -138,30 +141,51 @@ class OpenSubtitlesApi @Inject constructor(
suspend fun downloadSubtitleFile(link: DownloadLink, destination: File): Result<File> = try {
val file = withContext(Dispatchers.IO) {
- val request = Request.Builder()
- .url(link.url)
- .header("User-Agent", USER_AGENT)
- .get()
- .build()
- okHttpClient.newBuilder()
- .callTimeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
- .build()
- .newCall(request)
- .execute()
- .use { response ->
- if (!response.isSuccessful) {
- throw OpenSubtitlesApiException(
- message = "OpenSubtitles subtitle file download failed with HTTP ${response.code}",
- statusCode = response.code,
- )
+ destination.parentFile?.mkdirs()
+ val temporaryFile = File(destination.parentFile, "${destination.name}.part")
+ temporaryFile.delete()
+ try {
+ val request = Request.Builder()
+ .url(link.url)
+ .header("User-Agent", USER_AGENT)
+ .get()
+ .build()
+ // OpenSubtitles links contain short-lived download tokens in their URL. Keep the
+ // shared connection pool and interceptors, but never log this request line.
+ okHttpClient.newBuilder()
+ .apply {
+ interceptors().removeAll { it is HttpLoggingInterceptor }
+ networkInterceptors().removeAll { it is HttpLoggingInterceptor }
}
- val body = response.body
- ?: throw OpenSubtitlesApiException("OpenSubtitles subtitle file download returned an empty body")
- destination.outputStream().use { out ->
- body.byteStream().use { input -> input.copyTo(out) }
+ .callTimeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
+ .build()
+ .newCall(request)
+ .useCancellableResponse { response ->
+ if (!response.isSuccessful) {
+ throw OpenSubtitlesApiException(
+ message = "OpenSubtitles subtitle file download failed with HTTP ${response.code}",
+ statusCode = response.code,
+ )
+ }
+ val body = response.body
+ ?: throw OpenSubtitlesApiException("OpenSubtitles subtitle file download returned an empty body")
+ temporaryFile.outputStream().use { out ->
+ body.byteStream().use { input -> input.copyTo(out) }
+ }
}
+ if (temporaryFile.length() <= 0L) {
+ throw OpenSubtitlesApiException("OpenSubtitles subtitle file download returned an empty file")
+ }
+ if (destination.exists() && !destination.delete()) {
+ throw OpenSubtitlesApiException("Could not replace the cached subtitle file")
}
- destination
+ if (!temporaryFile.renameTo(destination)) {
+ throw OpenSubtitlesApiException("Could not save the downloaded subtitle file")
+ }
+ destination
+ } finally {
+ temporaryFile.delete()
+ }
}
Result.success(file)
} catch (e: Exception) {
diff --git a/data/src/main/java/com/streamvault/data/remote/subtitle/OpenSubtitlesSessionStore.kt b/data/src/main/java/com/streamvault/data/remote/subtitle/OpenSubtitlesSessionStore.kt
index 589c2709..6bf840b0 100644
--- a/data/src/main/java/com/streamvault/data/remote/subtitle/OpenSubtitlesSessionStore.kt
+++ b/data/src/main/java/com/streamvault/data/remote/subtitle/OpenSubtitlesSessionStore.kt
@@ -18,6 +18,7 @@ import javax.inject.Singleton
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
+import java.time.Instant
data class OpenSubtitlesSession(
val token: String,
@@ -26,6 +27,7 @@ data class OpenSubtitlesSession(
val allowedDownloads: Int,
val level: String?,
val vip: Boolean,
+ val remainingDownloads: Int? = null,
)
data class OpenSubtitlesCredentials(
@@ -48,19 +50,24 @@ class OpenSubtitlesSessionStore @Inject constructor(
val session: Flow<OpenSubtitlesSession?> = dataStore.data.map { prefs ->
val token = prefs[KEY_TOKEN]?.let { runCatching { credentialCrypto.decryptIfNeeded(it) }.getOrNull() }
val baseUrl = prefs[KEY_BASE_URL].orEmpty().ifBlank { OPENSUBTITLES_DEFAULT_BASE_HOST }
- val username = prefs[KEY_USERNAME].orEmpty()
+ val username = prefs[KEY_USERNAME]
+ ?.let { runCatching { credentialCrypto.decryptIfNeeded(it) }.getOrNull() }
+ .orEmpty()
val allowedDownloads = prefs[KEY_ALLOWED_DOWNLOADS] ?: 0
+ val remainingDownloads = prefs.activeRemainingDownloads()
val level = prefs[KEY_LEVEL]
val vip = prefs[KEY_VIP] ?: false
if (token.isNullOrBlank() || username.isBlank()) null
- else OpenSubtitlesSession(token, baseUrl, username, allowedDownloads, level, vip)
+ else OpenSubtitlesSession(token, baseUrl, username, allowedDownloads, level, vip, remainingDownloads)
}
suspend fun loadSession(): OpenSubtitlesSession? {
val prefs = dataStore.data.first()
val token = prefs[KEY_TOKEN]?.let { runCatching { credentialCrypto.decryptIfNeeded(it) }.getOrNull() }
val baseUrl = prefs[KEY_BASE_URL].orEmpty().ifBlank { OPENSUBTITLES_DEFAULT_BASE_HOST }
- val username = prefs[KEY_USERNAME].orEmpty()
+ val username = prefs[KEY_USERNAME]
+ ?.let { runCatching { credentialCrypto.decryptIfNeeded(it) }.getOrNull() }
+ .orEmpty()
if (token.isNullOrBlank() || username.isBlank()) return null
return OpenSubtitlesSession(
token = token,
@@ -69,12 +76,15 @@ class OpenSubtitlesSessionStore @Inject constructor(
allowedDownloads = prefs[KEY_ALLOWED_DOWNLOADS] ?: 0,
level = prefs[KEY_LEVEL],
vip = prefs[KEY_VIP] ?: false,
+ remainingDownloads = prefs.activeRemainingDownloads(),
)
}
suspend fun loadCredentials(): OpenSubtitlesCredentials? {
val prefs = dataStore.data.first()
- val username = prefs[KEY_USERNAME].orEmpty()
+ val username = prefs[KEY_USERNAME]
+ ?.let { runCatching { credentialCrypto.decryptIfNeeded(it) }.getOrNull() }
+ .orEmpty()
val password = prefs[KEY_PASSWORD]
?.let { runCatching { credentialCrypto.decryptIfNeeded(it) }.getOrNull() }
.orEmpty()
@@ -86,17 +96,29 @@ class OpenSubtitlesSessionStore @Inject constructor(
dataStore.edit { prefs ->
prefs[KEY_TOKEN] = credentialCrypto.encryptIfNeeded(session.token)
prefs[KEY_BASE_URL] = session.baseUrl
- prefs[KEY_USERNAME] = session.username
+ prefs[KEY_USERNAME] = credentialCrypto.encryptIfNeeded(session.username)
prefs[KEY_ALLOWED_DOWNLOADS] = session.allowedDownloads
+ session.remainingDownloads?.let { prefs[KEY_REMAINING_DOWNLOADS] = it }
+ ?: run {
+ prefs.remove(KEY_REMAINING_DOWNLOADS)
+ prefs.remove(KEY_REMAINING_RESET_AT)
+ }
session.level?.takeIf { it.isNotBlank() }?.let { prefs[KEY_LEVEL] = it }
prefs[KEY_VIP] = session.vip
}
}
- suspend fun saveCredentials(credentials: OpenSubtitlesCredentials) {
+ suspend fun saveSignedInAccount(session: OpenSubtitlesSession, password: String) {
dataStore.edit { prefs ->
- prefs[KEY_USERNAME] = credentials.username
- prefs[KEY_PASSWORD] = credentialCrypto.encryptIfNeeded(credentials.password)
+ prefs[KEY_TOKEN] = credentialCrypto.encryptIfNeeded(session.token)
+ prefs[KEY_BASE_URL] = session.baseUrl
+ prefs[KEY_USERNAME] = credentialCrypto.encryptIfNeeded(session.username)
+ prefs[KEY_PASSWORD] = credentialCrypto.encryptIfNeeded(password)
+ prefs[KEY_ALLOWED_DOWNLOADS] = session.allowedDownloads
+ prefs.remove(KEY_REMAINING_DOWNLOADS)
+ prefs.remove(KEY_REMAINING_RESET_AT)
+ session.level?.takeIf { it.isNotBlank() }?.let { prefs[KEY_LEVEL] = it }
+ prefs[KEY_VIP] = session.vip
}
}
@@ -105,6 +127,8 @@ class OpenSubtitlesSessionStore @Inject constructor(
prefs.remove(KEY_TOKEN)
prefs.remove(KEY_BASE_URL)
prefs.remove(KEY_ALLOWED_DOWNLOADS)
+ prefs.remove(KEY_REMAINING_DOWNLOADS)
+ prefs.remove(KEY_REMAINING_RESET_AT)
prefs.remove(KEY_LEVEL)
prefs.remove(KEY_VIP)
}
@@ -117,11 +141,34 @@ class OpenSubtitlesSessionStore @Inject constructor(
prefs.remove(KEY_USERNAME)
prefs.remove(KEY_PASSWORD)
prefs.remove(KEY_ALLOWED_DOWNLOADS)
+ prefs.remove(KEY_REMAINING_DOWNLOADS)
+ prefs.remove(KEY_REMAINING_RESET_AT)
prefs.remove(KEY_LEVEL)
prefs.remove(KEY_VIP)
}
}
+ suspend fun updateRemainingDownloads(remaining: Int, resetTimeUtc: String?) {
+ val resetAt = resetTimeUtc?.let { value ->
+ runCatching { Instant.parse(value).epochSecond }.getOrNull()
+ }?.takeIf { it > Instant.now().epochSecond }
+ dataStore.edit { prefs ->
+ if (resetAt == null) {
+ prefs.remove(KEY_REMAINING_DOWNLOADS)
+ prefs.remove(KEY_REMAINING_RESET_AT)
+ } else {
+ prefs[KEY_REMAINING_DOWNLOADS] = remaining.coerceAtLeast(0)
+ prefs[KEY_REMAINING_RESET_AT] = resetAt
+ }
+ }
+ }
+
+ private fun Preferences.activeRemainingDownloads(): Int? {
+ val resetAt = this[KEY_REMAINING_RESET_AT] ?: return null
+ if (resetAt <= Instant.now().epochSecond) return null
+ return this[KEY_REMAINING_DOWNLOADS]
+ }
+
private companion object {
const val DATASTORE_NAME = "opensubtitles_session"
val KEY_TOKEN = stringPreferencesKey("token")
@@ -129,6 +176,8 @@ class OpenSubtitlesSessionStore @Inject constructor(
val KEY_USERNAME = stringPreferencesKey("username")
val KEY_PASSWORD = stringPreferencesKey("password")
val KEY_ALLOWED_DOWNLOADS = intPreferencesKey("allowed_downloads")
+ val KEY_REMAINING_DOWNLOADS = intPreferencesKey("remaining_downloads")
+ val KEY_REMAINING_RESET_AT = androidx.datastore.preferences.core.longPreferencesKey("remaining_reset_at")
val KEY_LEVEL = stringPreferencesKey("level")
val KEY_VIP = booleanPreferencesKey("vip")
}
diff --git a/data/src/main/java/com/streamvault/data/repository/OpenSubtitlesRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/OpenSubtitlesRepositoryImpl.kt
index 04b35950..4c5fab6f 100644
--- a/data/src/main/java/com/streamvault/data/repository/OpenSubtitlesRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/OpenSubtitlesRepositoryImpl.kt
@@ -7,6 +7,8 @@ import com.streamvault.data.remote.subtitle.OpenSubtitlesCredentials
import com.streamvault.data.remote.subtitle.OpenSubtitlesSession
import com.streamvault.data.remote.subtitle.OpenSubtitlesSessionStore
import com.streamvault.data.remote.subtitle.OpenSubtitlesSubtitleDto
+import com.streamvault.domain.manager.OpenSubtitlesAccount
+import com.streamvault.domain.manager.OpenSubtitlesAccountManager
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.ExternalSubtitle
import com.streamvault.domain.model.ExternalSubtitleSource
@@ -17,13 +19,59 @@ import java.io.File
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
@Singleton
class OpenSubtitlesRepositoryImpl @Inject constructor(
@ApplicationContext private val context: Context,
private val api: OpenSubtitlesApi,
private val sessionStore: OpenSubtitlesSessionStore,
-) : ExternalSubtitleRepository {
+) : ExternalSubtitleRepository, OpenSubtitlesAccountManager {
+
+ private val sessionMutex = Mutex()
+
+ override val account: Flow<OpenSubtitlesAccount?> = sessionStore.session
+ .map { it?.toAccount() }
+ .distinctUntilChanged()
+
+ override suspend fun signIn(username: String, password: String): Result<OpenSubtitlesAccount> {
+ val cleanUsername = username.trim()
+ if (cleanUsername.isBlank() || password.isBlank()) {
+ return Result.error("Enter your OpenSubtitles username and password.")
+ }
+ return try {
+ sessionMutex.withLock {
+ when (val login = api.login(cleanUsername, password)) {
+ is Result.Success -> {
+ sessionStore.saveSignedInAccount(login.data, password)
+ Result.success(login.data.toAccount())
+ }
+ is Result.Error -> Result.error(login.message, login.exception)
+ is Result.Loading -> Result.Loading
+ }
+ }
+ } catch (e: Exception) {
+ if (e is CancellationException) throw e
+ Result.error("OpenSubtitles sign-in failed: ${e.message}", e)
+ }
+ }
+
+ override suspend fun signOut(): Result<Unit> = try {
+ sessionMutex.withLock {
+ val session = sessionStore.loadSession()
+ if (session != null) api.logout(session.token, session.baseUrl)
+ sessionStore.clearAll()
+ }
+ // Local sign-out always succeeds, even if OpenSubtitles is temporarily unreachable.
+ Result.success(Unit)
+ } catch (e: Exception) {
+ if (e is CancellationException) throw e
+ Result.error("Could not sign out of OpenSubtitles: ${e.message}", e)
+ }
override suspend fun search(
contentType: ContentType,
@@ -35,91 +83,116 @@ class OpenSubtitlesRepositoryImpl @Inject constructor(
episodeNumber: Int?,
language: String,
): Result<List<ExternalSubtitle>> = try {
- val session = obtainSession()
- ?: return Result.error(NOT_SIGNED_IN_MESSAGE)
val query = buildSearchQuery(contentType, title, year, tmdbId, parentTmdbId, seasonNumber, episodeNumber, language)
- var result = api.search(query, session.token, session.baseUrl)
- if (result.isUnauthorized()) {
- val refreshed = refreshSession()
- if (refreshed != null) {
- result = api.search(query, refreshed.token, refreshed.baseUrl)
- }
- }
- when (result) {
- is Result.Success -> Result.success(result.data.map(::mapSubtitle))
- is Result.Error -> Result.error(result.message, result.exception)
- is Result.Loading -> Result.Loading
- }
+ authenticatedRequest { session -> api.search(query, session.token, session.baseUrl) }
+ .map { subtitles -> subtitles.mapNotNull(::mapSubtitle) }
} catch (e: Exception) {
if (e is CancellationException) throw e
Result.error("OpenSubtitles search failed: ${e.message}", e)
}
- override suspend fun downloadToCache(subtitle: ExternalSubtitle): Result<File> = try {
- val session = obtainSession()
- ?: return Result.error(NOT_SIGNED_IN_MESSAGE)
- val fileId = subtitle.downloadId.toLongOrNull()
- ?: return Result.error("OpenSubtitles subtitle has no file id")
- var link = api.downloadLink(fileId, session.token, session.baseUrl)
- if (link.isUnauthorized()) {
- val refreshed = refreshSession()
- if (refreshed != null) {
- link = api.downloadLink(fileId, refreshed.token, refreshed.baseUrl)
+ override suspend fun downloadToCache(subtitle: ExternalSubtitle): Result<File> {
+ return try {
+ val fileId = subtitle.downloadId.toLongOrNull()?.takeIf { it > 0L }
+ ?: return Result.error("This subtitle has no downloadable file.")
+ val destination = subtitleCacheFile(fileId)
+ if (destination.isFile && destination.length() > 0L) return Result.success(destination)
+
+ authenticatedRequest { session ->
+ if (session.remainingDownloads == 0) {
+ return@authenticatedRequest Result.error("Your OpenSubtitles download allowance is used for today.")
+ }
+ when (val link = api.downloadLink(fileId, session.token, session.baseUrl)) {
+ is Result.Success -> {
+ link.data.remaining?.let { remaining ->
+ sessionStore.updateRemainingDownloads(remaining, link.data.resetTimeUtc)
+ }
+ api.downloadSubtitleFile(link.data, destination)
+ }
+ is Result.Error -> Result.error(link.message, link.exception)
+ is Result.Loading -> Result.Loading
+ }
}
+ } catch (e: Exception) {
+ if (e is CancellationException) throw e
+ Result.error("OpenSubtitles download failed: ${e.message}", e)
}
- when (link) {
- is Result.Success -> {
- val destination = subtitleCacheFile(subtitle, link.data.fileName)
- api.downloadSubtitleFile(link.data, destination)
- }
- is Result.Error -> Result.error(link.message, link.exception)
- is Result.Loading -> Result.Loading
+ }
+
+ private suspend fun <T> authenticatedRequest(
+ request: suspend (OpenSubtitlesSession) -> Result<T>,
+ ): Result<T> {
+ val initial = obtainSession()
+ val session = initial.getOrNull() ?: return initial.asError("Sign in to OpenSubtitles in Settings to search for subtitles.")
+ val response = request(session)
+ if (!response.isUnauthorized()) return response
+
+ val refreshed = refreshSession(rejectedToken = session.token)
+ val refreshedSession = refreshed.getOrNull() ?: return refreshed.asError(
+ "Your OpenSubtitles session expired. Sign in again in Settings."
+ )
+ val retry = request(refreshedSession)
+ if (retry.isUnauthorized()) invalidateRejectedSession(refreshedSession.token)
+ return retry
+ }
+
+ private suspend fun invalidateRejectedSession(rejectedToken: String) {
+ sessionMutex.withLock {
+ if (sessionStore.loadSession()?.token == rejectedToken) sessionStore.clearAll()
}
- } catch (e: Exception) {
- if (e is CancellationException) throw e
- Result.error("OpenSubtitles download failed: ${e.message}", e)
}
- private suspend fun obtainSession(): OpenSubtitlesSession? {
- sessionStore.loadSession()?.let { return it }
- val credentials = sessionStore.loadCredentials() ?: return null
- val result = api.login(credentials.username, credentials.password)
- val session = result.getOrNull() ?: return null
- sessionStore.saveSession(session)
- return session
+ private suspend fun obtainSession(): Result<OpenSubtitlesSession> = sessionMutex.withLock {
+ sessionStore.loadSession()?.let { return@withLock Result.success(it) }
+ val credentials = sessionStore.loadCredentials()
+ ?: return@withLock Result.error(NOT_SIGNED_IN_MESSAGE)
+ loginAndStore(credentials)
}
- private suspend fun refreshSession(): OpenSubtitlesSession? {
- val credentials = sessionStore.loadCredentials() ?: return null
- val result = api.login(credentials.username, credentials.password)
- val session = result.getOrNull() ?: return null
- sessionStore.saveSession(session)
- return session
+ /** Reuses a token another concurrent request has already refreshed. */
+ private suspend fun refreshSession(rejectedToken: String): Result<OpenSubtitlesSession> = sessionMutex.withLock {
+ sessionStore.loadSession()
+ ?.takeIf { it.token != rejectedToken }
+ ?.let { return@withLock Result.success(it) }
+ val credentials = sessionStore.loadCredentials()
+ ?: return@withLock Result.error("OpenSubtitles session expired and no saved credentials are available.")
+ loginAndStore(credentials)
}
- private fun mapSubtitle(dto: OpenSubtitlesSubtitleDto): ExternalSubtitle {
- val attributes = dto.attributes
- val file = attributes?.files?.firstOrNull()
- val fileId = file?.fileId?.toString()
- ?: attributes?.subtitleId
- ?: dto.id
- ?: ""
- val language = attributes?.language.orEmpty()
+ private suspend fun loginAndStore(credentials: OpenSubtitlesCredentials): Result<OpenSubtitlesSession> =
+ when (val login = api.login(credentials.username, credentials.password)) {
+ is Result.Success -> {
+ sessionStore.saveSession(login.data)
+ Result.success(login.data)
+ }
+ is Result.Error -> {
+ if (login.exception.isUnauthorized()) sessionStore.clearAll()
+ Result.error(login.message, login.exception)
+ }
+ is Result.Loading -> Result.Loading
+ }
+
+ private fun mapSubtitle(dto: OpenSubtitlesSubtitleDto): ExternalSubtitle? {
+ val attributes = dto.attributes ?: return null
+ val fileId = attributes.files.orEmpty()
+ .firstNotNullOfOrNull { file -> file.fileId?.takeIf { it > 0L } }
+ ?: return null
+ val language = attributes.language.orEmpty()
+ if (language.isBlank()) return null
return ExternalSubtitle(
- id = dto.id.orEmpty(),
+ id = dto.id?.takeIf { it.isNotBlank() } ?: fileId.toString(),
language = language,
- displayLanguage = attributes?.languageName?.takeIf { it.isNotBlank() } ?: language,
- releaseName = attributes?.release.orEmpty(),
+ displayLanguage = attributes.languageName?.takeIf { it.isNotBlank() } ?: language,
+ releaseName = attributes.release.orEmpty(),
source = ExternalSubtitleSource.OPENSUBTITLES,
- downloadId = fileId,
+ downloadId = fileId.toString(),
+ downloadCount = attributes.downloadCount ?: 0L,
)
}
- private fun subtitleCacheFile(subtitle: ExternalSubtitle, fileName: String): File {
- val directory = File(context.cacheDir, "subtitles").apply { mkdirs() }
- val extension = fileName.substringAfterLast('.', "srt").takeIf { it.isNotBlank() } ?: "srt"
- val baseName = subtitle.downloadId.ifBlank { subtitle.id }.ifBlank { "subtitle" }
- return File(directory, "$baseName.$extension")
+ private fun subtitleCacheFile(fileId: Long): File {
+ val directory = File(context.cacheDir, "subtitles/opensubtitles").apply { mkdirs() }
+ return File(directory, "$fileId.srt")
}
private fun buildSearchQuery(
@@ -132,7 +205,7 @@ class OpenSubtitlesRepositoryImpl @Inject constructor(
episodeNumber: Int?,
language: String,
): OpenSubtitlesApi.SearchQuery {
- val languageCode = language.trim().lowercase().takeIf { it.isNotBlank() }
+ val languageCode = language.trim().lowercase().takeIf { it.isNotBlank() && it != "auto" }
return when (contentType) {
ContentType.MOVIE -> OpenSubtitlesApi.SearchQuery(
query = buildTitleQuery(title, year),
@@ -182,7 +255,24 @@ class OpenSubtitlesRepositoryImpl @Inject constructor(
}
private fun Result<*>.isUnauthorized(): Boolean =
- (this as? Result.Error)?.exception?.let { it is OpenSubtitlesApiException && it.isUnauthorized } == true
+ (this as? Result.Error)?.exception.isUnauthorized()
+
+ private fun Throwable?.isUnauthorized(): Boolean =
+ this is OpenSubtitlesApiException && isUnauthorized
+
+ private fun <T> Result<*>.asError(fallbackMessage: String): Result<T> = when (this) {
+ is Result.Error -> Result.error(message, exception)
+ is Result.Loading -> Result.error(fallbackMessage)
+ is Result.Success -> Result.error(fallbackMessage)
+ }
+
+ private fun OpenSubtitlesSession.toAccount() = OpenSubtitlesAccount(
+ username = username,
+ allowedDownloads = allowedDownloads,
+ remainingDownloads = remainingDownloads,
+ level = level,
+ vip = vip,
+ )
private companion object {
const val NOT_SIGNED_IN_MESSAGE =
diff --git a/data/src/test/java/com/streamvault/data/remote/subtitle/OpenSubtitlesApiDownloadTest.kt b/data/src/test/java/com/streamvault/data/remote/subtitle/OpenSubtitlesApiDownloadTest.kt
new file mode 100644
index 00000000..49742967
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/remote/subtitle/OpenSubtitlesApiDownloadTest.kt
@@ -0,0 +1,114 @@
+package com.streamvault.data.remote.subtitle
+
+import com.google.common.truth.Truth.assertThat
+import com.google.gson.Gson
+import java.io.File
+import kotlinx.coroutines.async
+import kotlinx.coroutines.cancelAndJoin
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.runBlocking
+import okhttp3.OkHttpClient
+import okhttp3.logging.HttpLoggingInterceptor
+import okhttp3.mockwebserver.MockResponse
+import okhttp3.mockwebserver.MockWebServer
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TemporaryFolder
+
+class OpenSubtitlesApiDownloadTest {
+
+ @get:Rule
+ val temporaryFolder = TemporaryFolder()
+
+ @Test
+ fun `temporary link token is not written to network logs and file is committed`() = runBlocking {
+ val server = MockWebServer()
+ server.start()
+ try {
+ server.enqueue(MockResponse().setBody("1\n00:00:01,000 --> 00:00:02,000\nHello\n"))
+ val logLines = mutableListOf<String>()
+ val logger = HttpLoggingInterceptor { line -> logLines += line }.apply {
+ level = HttpLoggingInterceptor.Level.BASIC
+ }
+ val api = OpenSubtitlesApi(OkHttpClient.Builder().addInterceptor(logger).build(), Gson())
+ val destination = File(temporaryFolder.newFolder(), "123.srt")
+ val token = "private-download-token"
+ val link = OpenSubtitlesApi.DownloadLink(
+ url = server.url("/download/$token/subfile/movie.srt").toString(),
+ fileName = "movie.srt",
+ remaining = 19,
+ resetTimeUtc = "2030-01-01T00:00:00Z",
+ )
+
+ val result = api.downloadSubtitleFile(link, destination)
+
+ assertThat(result.getOrNull()).isEqualTo(destination)
+ assertThat(destination.readText()).contains("Hello")
+ assertThat(File(destination.parentFile, "${destination.name}.part").exists()).isFalse()
+ assertThat(logLines.joinToString("\n")).doesNotContain(token)
+ assertThat(server.takeRequest().path).contains(token)
+ } finally {
+ server.shutdown()
+ }
+ }
+
+ @Test
+ fun `failed response leaves no final or partial subtitle file`() = runBlocking {
+ val server = MockWebServer()
+ server.start()
+ try {
+ server.enqueue(MockResponse().setResponseCode(503).setBody("unavailable"))
+ val api = OpenSubtitlesApi(OkHttpClient(), Gson())
+ val destination = File(temporaryFolder.newFolder(), "456.srt")
+
+ val result = api.downloadSubtitleFile(
+ OpenSubtitlesApi.DownloadLink(
+ url = server.url("/private-link").toString(),
+ fileName = "captions.srt",
+ remaining = null,
+ resetTimeUtc = null,
+ ),
+ destination,
+ )
+
+ assertThat(result.isError).isTrue()
+ assertThat(destination.exists()).isFalse()
+ assertThat(File(destination.parentFile, "${destination.name}.part").exists()).isFalse()
+ } finally {
+ server.shutdown()
+ }
+ }
+
+ @Test
+ fun `cancelling a response body read removes the temporary file`() = runBlocking {
+ val server = MockWebServer()
+ server.start()
+ try {
+ server.enqueue(
+ MockResponse()
+ .setBody("x".repeat(100_000))
+ .throttleBody(512, 1, java.util.concurrent.TimeUnit.SECONDS)
+ )
+ val api = OpenSubtitlesApi(OkHttpClient(), Gson())
+ val destination = File(temporaryFolder.newFolder(), "789.srt")
+ val download = async {
+ api.downloadSubtitleFile(
+ OpenSubtitlesApi.DownloadLink(
+ url = server.url("/slow-link").toString(),
+ fileName = "slow.srt",
+ remaining = null,
+ resetTimeUtc = null,
+ ),
+ destination,
+ )
+ }
+ delay(200)
+ download.cancelAndJoin()
+
+ assertThat(destination.exists()).isFalse()
+ assertThat(File(destination.parentFile, "${destination.name}.part").exists()).isFalse()
+ } finally {
+ server.shutdown()
+ }
+ }
+}
diff --git a/docs/OPENSUBTITLES_INTEGRATION.md b/docs/OPENSUBTITLES_INTEGRATION.md
index f4db0829..d52fc714 100644
--- a/docs/OPENSUBTITLES_INTEGRATION.md
+++ b/docs/OPENSUBTITLES_INTEGRATION.md
@@ -1,348 +1,30 @@
-# OpenSubtitles.com Integration Plan
+# OpenSubtitles.com integration
Branch: `feature/opensubtitles-integration`
-Status: Plan (no code written yet)
-## 1. Goal
+The account, settings, search, download, and player-injection flows are implemented. The application API key remains the existing placeholder in `OpenSubtitlesApi`; key provisioning/configuration is intentionally deferred.
-Add an official, open-source-friendly subtitles provider backed by the
-OpenSubtitles.com REST API v1:
+## User flow
-- The developer registers one application API key for StreamVault and ships it
- in the app (it is expected to be visible in public source).
-- Users sign in with their own free OpenSubtitles.com account from a new
- Settings section.
-- The app uses that user's session token for search and download, so the daily
- download quota is per-user (typically 20/day for a free account) instead of a
- shared global pool.
-- Downloaded `.srt`/`.vtt` files are injected into the existing Media3 player.
+1. Open **Settings → Playback → Subtitles** and connect an OpenSubtitles.com account.
+2. During movie or series-episode playback, open **Subtitles → Search online subtitles**.
+3. Choose a result to download and add it to the current player session.
-## 2. What already exists (foundation)
+Online search is hidden for live TV and catch-up. Search uses the movie or series TMDb ID when available, title/year fallbacks for movies, season/episode metadata for episodes, and the preferred audio language (English when the preference is automatic).
-The repository already contains a partial, dormant external-subtitle path. Do
-not rebuild it — wire it up.
+## Session, quota, and downloads
-| Layer | Existing symbol | Location |
-|-------|-----------------|----------|
-| Model | `ExternalSubtitle`, `ExternalSubtitleSource.OPENSUBTITLES` | `domain/.../model/ExternalSubtitle.kt` |
-| Contract | `ExternalSubtitleRepository` (`search`, `downloadToCache`) | `domain/.../repository/ExternalSubtitleRepository.kt` |
-| Use case | `SearchExternalSubtitles` | `domain/.../usecase/SearchExternalSubtitles.kt` |
-| Player | `PlayerEngine.addExternalSubtitle(uri, language)` | `player/.../PlayerEngine.kt:104` |
-| Player impl | `Media3PlayerEngine.addExternalSubtitle(...)` | `player/.../Media3PlayerEngine.kt:803` |
-| Player helpers | `buildExternalSubtitleConfiguration`, `buildExternalSubtitleMediaSource`, `withExternalSubtitleEnabled` | `player/.../ExternalSubtitlePlayback.kt` |
-| Settings page | `SettingsPage.SUBTITLES` (under `PLAYBACK`) | `feature/settings/.../SettingsDestination.kt:37` |
-| Subtitle picker | `PlayerTrackSelectionDialog` | `feature/playback/.../overlay/PlayerSystemOverlays.kt:254` |
+- Username, password, and JWT are encrypted with the app's `CredentialCrypto`. Existing plaintext usernames are still readable for migration; new writes are encrypted.
+- Session reads, sign-in/out, and one-time refresh after HTTP 401 share a mutex. Concurrent requests reuse a token refreshed by another request. If the refreshed token also receives 401, the saved session and credentials are cleared.
+- The account page shows the daily allowance from login until a current remaining count is known. Successful `/download` responses update the remaining count, which expires at `reset_time_utc`.
+- Subtitle files are cached by OpenSubtitles file ID. A valid cached file avoids another quota-consuming `/download` request.
+- File responses are cancellable, written to a temporary file, and moved into the cache only after completion. The temporary download URL is excluded from OkHttp request logging.
+- OpenSubtitles can enforce both account download allowances and request limits. The app displays the account's remaining download count when the API provides it; IP-based request limits remain controlled by OpenSubtitles.
-There is **no** data-layer implementation of `ExternalSubtitleRepository` and
-**no** DI binding for it. That is the core of this work.
+## API key
-## 3. API reference (verified against OpenSubtitles docs)
+`OpenSubtitlesApi` still contains `STREAMVAULT_OPENSUBTITLES_API_KEY`. This branch does not change the key or add ignore-file changes. The API key is an application identifier; account credentials and bearer tokens remain private and encrypted locally.
-Base URL: `https://api.opensubtitles.com/api/v1` (default)
-VIP mirror: `https://vip-api.opensubtitles.com/api/v1`
+## Validation
-Required headers on every request:
-
-- `Api-Key: <app API key>` (application key)
-- `Authorization: Bearer <user token>` (user session; required for download,
- recommended everywhere)
-- `User-Agent: StreamVault v<version>` (OpenSubtitles asks consumers not to use
- a generic default)
-- `Content-Type: application/json` (for POST bodies)
-
-### 3.1 Login
-
-`POST /api/v1/login`
-
-```json
-{ "username": "<user>", "password": "<pass>" }
-```
-
-Response `200`:
-
-```json
-{
- "token": "<JWT>",
- "base_url": "api.opensubtitles.com",
- "user": { "allowed_downloads": 20, "level": "Sub leecher", "user_id": 66, "vip": false }
-}
-```
-
-Rules:
-
-- Rate limit is intentionally tight (1/s, 10/min, 30/hour). Treat login as
- expensive: on `401`, stop retrying the same credentials until the user edits
- them.
-- Honor the returned `base_url` host for subsequent requests (VIP users get a
- different host).
-
-### 3.2 Logout
-
-`DELETE /api/v1/logout` (Bearer token required). Response `200`.
-
-### 3.3 Search
-
-`GET /api/v1/subtitles`
-
-Query parameters (all optional, at least one identity is required):
-
-- `query` — free-text title (least precise; prefer IDs)
-- `imdb_id` — IMDb id **without** the `tt` prefix (e.g. `1375666`)
-- `tmdb_id` — TMDB movie/series id
-- `parent_imdb_id` / `parent_tmdb_id` — series id for episode lookups
-- `season_number`, `episode_number` — episode targeting
-- `languages` — ISO 639-1 code(s), e.g. `en` (see `/api/v1/infos/languages`)
-- `order_by` — e.g. `download_count`, `language`, `upload_date`
-- Defaults: `ai_translated=include`, `machine_translated=exclude`
-
-Response `200`:
-
-```json
-{
- "total_pages": 1,
- "total_count": 13,
- "page": 1,
- "data": [
- {
- "id": "1000001",
- "type": "subtitle",
- "attributes": {
- "subtitle_id": "1000001",
- "language": "en",
- "language_name": "English",
- "release": "Movie.Name.2020.1080p.WEB-DL",
- "download_count": 1234,
- "feature_details": {
- "title": "Movie Name",
- "year": 2020,
- "imdb_id": 1375666,
- "tmdb_id": 27205,
- "parent_imdb_id": null,
- "parent_tmdb_id": null,
- "season_number": 0,
- "episode_number": 0
- },
- "files": [
- { "file_id": 123456, "file_name": "movie.srt", "cd_number": 1 }
- ]
- }
- }
- ]
-}
-```
-
-### 3.4 Download link
-
-`POST /api/v1/download` (requires **both** `Api-Key` and `Authorization`)
-
-```json
-{ "file_id": 123456 }
-```
-
-Optional: `sub_format` (`srt`, `webvtt`, ...), `file_name`, `timeshift`.
-
-Response `200`:
-
-```json
-{
- "link": "https://www.opensubtitles.com/download/<token>/subfile/movie.srt",
- "file_name": "movie.srt",
- "requests": 3,
- "remaining": 17,
- "message": "Your quota will be renewed in 07 hours and 30 minutes ...",
- "reset_time": "07 hours and 30 minutes",
- "reset_time_utc": "2022-04-08T13:03:16.000Z"
-}
-```
-
-The `link` is a temporary URL to fetch the subtitle file itself (always UTF-8).
-Track `remaining` and stop attempting downloads once it hits zero; there is no
-dedicated "quota exceeded" error code.
-
-## 4. Design
-
-Follow existing codebase conventions (OkHttp + Gson, no Retrofit; Hilt; Room +
-DataStore; Compose). Mirror `JellyfinProvider` for the HTTP client and
-`MinistraApiV3Provider`/`StalkerPortalStateStore` for encrypted credential and
-token storage.
-
-### 4.1 API key
-
-Add a single top-level constant in the data layer, e.g.
-`OpenSubtitlesApi.API_KEY`. It is intentionally non-secret and shipped in source
-(per the official open-source policy). The actual key value is obtained from
-https://www.opensubtitles.com/consumers after registering StreamVault; keep it
-as a named constant so it is trivial to rotate.
-
-### 4.2 Session model
-
-Introduce a session holder (data layer) that caches, in memory and in
-encrypted DataStore:
-
-- `token` (JWT, encrypted with `CredentialCrypto`)
-- `baseUrl` (host, plaintext)
-- `allowedDownloads` / `level` / `vip` (for the settings status line)
-- `username` (encrypted) and a boolean `hasCredentials`
-
-The repository obtains a valid token lazily: if a cached token exists use it; if
-a request returns `401`, drop the token and re-login once using stored
-credentials; if that also fails, surface a "sign in required" result.
-
-## 5. Work breakdown
-
-### Phase A — Data layer (core)
-
-New files under `data/src/main/java/com/streamvault/data/remote/subtitle/`:
-
-1. `OpenSubtitlesApi.kt` — OkHttp-based client (`@Singleton`, injects
- `OkHttpClient` + `Gson`). Methods:
- - `suspend fun login(username, password): Result<OpenSubtitlesSession>`
- - `suspend fun logout(token): Result<Unit>`
- - `suspend fun search(query): Result<List<OpenSubtitlesSubtitleDto>>`
- - `suspend fun downloadLink(fileId, token): Result<OpenSubtitlesDownloadDto>`
- - Builds `Api-Key` / `Authorization` / `User-Agent` headers; uses
- `useCancellableResponse` and `withContext(Dispatchers.IO)` like
- `JellyfinProvider`.
-2. `OpenSubtitlesDtos.kt` — Gson DTOs for the payloads above (login, search
- envelope, `data[].attributes`, `files[]`, download, languages optional).
- Nullable scalar fields with defaults, matching the lenient style in
- `data/remote/dto/LenientJsonSerializers.kt`.
-3. `OpenSubtitlesSessionStore.kt` — encrypted persistence of token/baseUrl/quota
- using `CredentialCrypto` + DataStore (see `StalkerPortalStateStore.kt`).
-4. `OpenSubtitlesApiException.kt` — small error type mapping HTTP codes
- (`401 Unauthorized`, `429 Rate limited`, non-2xx, decode errors).
-
-New file under `data/src/main/java/com/streamvault/data/repository/`:
-
-5. `OpenSubtitlesRepositoryImpl.kt` — `@Singleton`, implements
- `ExternalSubtitleRepository`. Responsibilities:
- - Map `ContentType` + ids into a search request (see 5.1).
- - `search(...)` returns `Result<List<ExternalSubtitle>>`, populating
- `id`/`downloadId` from `files[0].file_id`, `language`, `releaseName`,
- `source = OPENSUBTITLES`.
- - `downloadToCache(subtitle)` calls `downloadLink`, fetches the file into a
- cache dir (e.g. `context.cacheDir/subtitles/<id>.srt`), returns the local
- `File`.
- - When there is no stored token and no stored credentials, return
- `Result.error("OpenSubtitles not signed in")` (or a dedicated result the
- UI can map to a sign-in prompt).
-
-DI wiring:
-
-6. `app/src/main/java/com/streamvault/app/di/RepositoryModule.kt` — add
- `@Binds abstract fun bindExternalSubtitleRepository(impl: OpenSubtitlesRepositoryImpl): ExternalSubtitleRepository`.
-7. Confirm an `OkHttpClient`/`Gson` provider exists (used by `JellyfinProvider`);
- if not, add providers in the appropriate data DI module.
-
-### 5.1 Search mapping
-
-For `search(contentType, title, year, tmdbId, parentTmdbId, seasonNumber, episodeNumber, language)`:
-
-- `MOVIE`: `tmdb_id=tmdbId` when present, plus `query="$title $year"`, `languages`.
-- `SERIES`: `tmdb_id=tmdbId` (or `query=title`), `languages`.
-- `SERIES_EPISODE`: `parent_tmdb_id=parentTmdbId`, `season_number`,
- `episode_number`; fall back to `query="$title S${season}E${episode}"`.
-- Strip `tt` and leading zeros from any IMDb id (none is passed today, but keep
- a helper for future use). Prefer IDs over `query`; only send `query` as a
- fallback.
-- Normalize `language` to an ISO 639-1 code (OpenSubtitles uses codes like
- `en`, `fr`, `zh-cn`). Wire the app's preferred subtitle/audio language or the
- currently selected subtitle language as the default.
-
-### Phase B — Settings UI ("Subtitles Provider (OpenSubtitles)")
-
-Extend the existing `SUBTITLES` page (`SettingsPlaybackSection.kt`, the
-`if (page == null || page == SettingsPage.SUBTITLES)` block around line 371):
-
-1. Add a "Subtitles provider" section header + status rows:
- - Signed-out: `ClickableSettingsRow` "Sign in to OpenSubtitles" opening a
- login dialog (username + password text fields).
- - Signed-in: status text ("Signed in as <username> · N downloads remaining")
- plus a "Sign out" action.
-2. Add login/logout actions to the settings ViewModel. Persist credentials
- (password encrypted via `CredentialCrypto`) and the session via
- `OpenSubtitlesSessionStore`.
-3. New dialog composable (follow `SettingsPreferenceDialogs.kt` /
- `SettingsProviderManagementDialogs.kt` patterns for TV text entry).
-4. Add strings to `feature/settings/.../values/strings.xml` and a catalog/search
- entry in `SettingsSearchSurface.kt` (e.g. `playback.subtitles_provider`).
-5. Expose sign-in state (Flow) from the session store to the settings UI.
-
-The developer-facing detail (the app key is public, per-user quota, why a login
-is needed) belongs in the section subtitle text.
-
-### Phase C — Player subtitle search + injection
-
-1. In `PlayerTrackSelectionDialog` (`PlayerSystemOverlays.kt`), add a
- "Search subtitles online" item at the bottom of the `TrackType.TEXT` list
- (mirror the existing `liveTranslationAvailable` hook at lines 362-369).
-2. Add a new modal/route in `PlayerModalHosts.kt` + `PlayerModal` that hosts a
- subtitle search sheet:
- - Query OpenSubtitles via `SearchExternalSubtitles` using the currently
- playing item's metadata (title, year, tmdb id, season/episode) sourced from
- the playback context already held by `PlayerViewModel`/`PlaybackContextCoordinator`.
- - Show results (language + release name + download count).
- - On selection, call `downloadToCache`, then
- `playerEngine.addExternalSubtitle(Uri.fromFile(file), language)`.
- - Handle "not signed in": show a message directing the user to Settings.
-3. New `SubtitleSearchViewModel` (or extend `PlayerViewModel`) in
- `feature/playback`, using `SearchExternalSubtitles` and the download use case.
- The selected file should be downloaded to cache then handed to the engine as
- a `file://` Uri — the engine's `addExternalSubtitle` already builds a
- `SubtitleConfiguration` and a merged media source.
-
-### 5.2 Mime type handling
-
-`ExternalSubtitlePlayback.kt` currently hard-codes `MimeTypes.APPLICATION_SUBRIP`
-(and the player test asserts `.srt`). Prefer requesting `sub_format=srt` on
-download so existing code works unchanged. If `.vtt` support is wanted later,
-extend `buildExternalSubtitleConfiguration` to select
-`APPLICATION_SUBRIP` vs `TEXT_VTT` by file extension and update
-`ExternalSubtitlePlaybackTest`.
-
-## 6. Domain additions (small)
-
-Optionally extend the domain contract so the UI can drive sign-in and report
-state cleanly:
-
-- `ExternalSubtitleRepository` gains `suspend fun signIn(username, password)`,
- `suspend fun signOut()`, and `val sessionState: Flow<...>` — OR keep the
- session store purely in the data layer and expose a separate
- `OpenSubtitlesSessionManager` domain contract. Prefer the separate-manager
- approach so `ExternalSubtitleRepository` stays focused on search/download.
-
-## 7. Security notes
-
-- Password and JWT token: encrypted at rest via `CredentialCrypto`
- (AES-GCM, Android Keystore) — reuse existing helper, do not store plaintext.
-- API key: plaintext constant by design (not a secret).
-- Never log credentials or tokens; sanitize error messages before they reach
- the UI/logs.
-
-## 8. Testing
-
-- Unit tests for DTO parsing and search-query mapping (no network), following
- `player/src/test/.../ExternalSubtitlePlaybackTest.kt` style.
-- Unit tests for `OpenSubtitlesRepositoryImpl` with a fake client (mock the
- OkHttp layer or a fake `OpenSubtitlesApi`) covering: signed-out error, token
- reuse, `401` re-login, download-to-cache path, quota-zero handling.
-- Verify existing `ExternalSubtitlePlaybackTest` still passes (no changes to the
- player helpers expected in this phase).
-
-## 9. Risks / open questions
-
-- The actual API key must be requested from the OpenSubtitles.com "API
- consumers" page; a placeholder constant ships until then.
-- `addExternalSubtitle` re-prepares the media source; confirm it is safe to call
- mid-playback for VOD vs live (live typically has no metadata to match, so
- subtitle search should be surfaced only for VOD/movie/series contexts).
-- OpenSubtitles search precision depends on having TMDB/IMDb ids; providers vary
- in metadata quality. Fall back to `query` (title + year) when ids are absent.
-
-## 10. Suggested commit sequence
-
-1. Data layer: DTOs + API client + session store + repository impl + DI.
-2. Domain: session-manager contract (if added).
-3. Settings UI: provider section + login dialog + status.
-4. Player: search sheet + injection wiring.
-5. Tests + strings + search-surface catalog entries.
+The implementation was checked with the data, settings, playback, and app Hilt compilation tasks. Focused unit tests cover temporary-link log redaction, complete/failed/cancelled file downloads, VOD subtitle-action availability, and player Back behavior.
diff --git a/domain/src/main/java/com/streamvault/domain/manager/OpenSubtitlesAccountManager.kt b/domain/src/main/java/com/streamvault/domain/manager/OpenSubtitlesAccountManager.kt
new file mode 100644
index 00000000..ac5833e5
--- /dev/null
+++ b/domain/src/main/java/com/streamvault/domain/manager/OpenSubtitlesAccountManager.kt
@@ -0,0 +1,21 @@
+package com.streamvault.domain.manager
+
+import com.streamvault.domain.model.Result
+import kotlinx.coroutines.flow.Flow
+
+data class OpenSubtitlesAccount(
+ val username: String,
+ val allowedDownloads: Int,
+ val remainingDownloads: Int?,
+ val level: String?,
+ val vip: Boolean,
+)
+
+/** Account operations and current sign-in state for the OpenSubtitles provider. */
+interface OpenSubtitlesAccountManager {
+ val account: Flow<OpenSubtitlesAccount?>
+
+ suspend fun signIn(username: String, password: String): Result<OpenSubtitlesAccount>
+
+ suspend fun signOut(): Result<Unit>
+}
diff --git a/domain/src/main/java/com/streamvault/domain/model/ExternalSubtitle.kt b/domain/src/main/java/com/streamvault/domain/model/ExternalSubtitle.kt
index 3a4bc5f3..1cdd3b6d 100644
--- a/domain/src/main/java/com/streamvault/domain/model/ExternalSubtitle.kt
+++ b/domain/src/main/java/com/streamvault/domain/model/ExternalSubtitle.kt
@@ -6,7 +6,8 @@ data class ExternalSubtitle(
val displayLanguage: String,
val releaseName: String,
val source: ExternalSubtitleSource,
- val downloadId: String = id
+ val downloadId: String = id,
+ val downloadCount: Long = 0L,
)
enum class ExternalSubtitleSource {
diff --git a/domain/src/main/java/com/streamvault/domain/usecase/DownloadExternalSubtitle.kt b/domain/src/main/java/com/streamvault/domain/usecase/DownloadExternalSubtitle.kt
new file mode 100644
index 00000000..f0f726ae
--- /dev/null
+++ b/domain/src/main/java/com/streamvault/domain/usecase/DownloadExternalSubtitle.kt
@@ -0,0 +1,14 @@
+package com.streamvault.domain.usecase
+
+import com.streamvault.domain.model.ExternalSubtitle
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.repository.ExternalSubtitleRepository
+import java.io.File
+import javax.inject.Inject
+
+class DownloadExternalSubtitle @Inject constructor(
+ private val repository: ExternalSubtitleRepository,
+) {
+ suspend operator fun invoke(subtitle: ExternalSubtitle): Result<File> =
+ repository.downloadToCache(subtitle)
+}
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerBackNavigationPolicy.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerBackNavigationPolicy.kt
index 5203d642..f39d4e26 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerBackNavigationPolicy.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerBackNavigationPolicy.kt
@@ -21,6 +21,7 @@ internal enum class PlayerBackAction {
CLOSE_IDLE_STANDBY_TIMER,
CLOSE_VARIANT_SELECTION,
CLOSE_TRACK_SELECTION,
+ CLOSE_SUBTITLE_SEARCH,
TOGGLE_DIAGNOSTICS,
CLOSE_CHANNEL_INFO,
CLOSE_LIVE_OVERLAYS,
@@ -42,6 +43,7 @@ internal data class PlayerBackNavigationState(
val showStopPlaybackTimerDialog: Boolean = false,
val showIdleStandbyTimerDialog: Boolean = false,
val hasTrackSelection: Boolean = false,
+ val showSubtitleSearch: Boolean = false,
val showVariantSelection: Boolean = false,
val showDiagnostics: Boolean = false,
val showChannelInfoOverlay: Boolean = false,
@@ -65,6 +67,7 @@ internal fun playerBackAction(state: PlayerBackNavigationState): PlayerBackActio
state.showStopPlaybackTimerDialog -> PlayerBackAction.CLOSE_STOP_PLAYBACK_TIMER
state.showIdleStandbyTimerDialog -> PlayerBackAction.CLOSE_IDLE_STANDBY_TIMER
state.showVariantSelection -> PlayerBackAction.CLOSE_VARIANT_SELECTION
+ state.showSubtitleSearch -> PlayerBackAction.CLOSE_SUBTITLE_SEARCH
state.hasTrackSelection -> PlayerBackAction.CLOSE_TRACK_SELECTION
state.showDiagnostics -> PlayerBackAction.TOGGLE_DIAGNOSTICS
state.showChannelInfoOverlay -> PlayerBackAction.CLOSE_CHANNEL_INFO
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerControlsOverlayHost.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerControlsOverlayHost.kt
index 98b721df..f431ac05 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerControlsOverlayHost.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerControlsOverlayHost.kt
@@ -55,6 +55,7 @@ internal fun PlayerControlsOverlayHost(
contentType: String,
modifier: Modifier = Modifier,
isCatchUpPlayback: Boolean = false,
+ onlineSubtitleSearchAvailable: Boolean = false,
isPlaying: Boolean,
currentChannel: Channel?,
currentChannelName: String?,
@@ -119,6 +120,7 @@ internal fun PlayerControlsOverlayHost(
audioTrackCount = availableAudioTracks.size,
videoQualityCount = availableVideoQualities.size,
audioVideoSyncEnabled = audioVideoSyncEnabled,
+ onlineSubtitleSearchAvailable = onlineSubtitleSearchAvailable,
showExternalPlayerAction = false,
isCastConnected = isCastConnected
)
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerExternalSubtitleActions.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerExternalSubtitleActions.kt
new file mode 100644
index 00000000..082753ca
--- /dev/null
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerExternalSubtitleActions.kt
@@ -0,0 +1,151 @@
+package com.streamvault.feature.playback.player
+
+import android.net.Uri
+import androidx.lifecycle.viewModelScope
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.Result
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.launch
+
+internal fun PlayerViewModel.searchExternalSubtitles() {
+ externalSubtitleSearchJob?.cancel()
+ if (currentContentType !in setOf(ContentType.MOVIE, ContentType.VOD, ContentType.SERIES_EPISODE)) {
+ externalSubtitleSearchStateFlow.value = externalSubtitleSearchStateFlow.value.copy(
+ isSearching = false,
+ subtitles = emptyList(),
+ errorMessage = "Online subtitles are available for movies and series episodes.",
+ )
+ return
+ }
+ if (externalSubtitleSearchStateFlow.value.account == null) {
+ externalSubtitleSearchStateFlow.value = externalSubtitleSearchStateFlow.value.copy(
+ isSearching = false,
+ subtitles = emptyList(),
+ errorMessage = null,
+ )
+ return
+ }
+
+ externalSubtitleSearchJob = viewModelScope.launch {
+ externalSubtitleSearchStateFlow.update {
+ it.copy(
+ isSearching = true,
+ subtitles = emptyList(),
+ errorMessage = null,
+ appliedSubtitleName = null,
+ )
+ }
+ try {
+ val query = when (currentContentType) {
+ ContentType.SERIES_EPISODE -> {
+ val series = currentSeries.value ?: currentSeriesId?.takeIf { it > 0L }?.let { id ->
+ playerContentResolver.getSeriesDetails(currentProviderId, id).getOrNull()
+ }
+ ExternalSubtitleQuery(
+ contentType = ContentType.SERIES_EPISODE,
+ title = series?.name?.takeIf { it.isNotBlank() }
+ ?: currentTitle.ifBlank { playbackTitleFlow.value },
+ tmdbId = null,
+ parentTmdbId = series?.tmdbId,
+ seasonNumber = currentSeasonNumber,
+ episodeNumber = currentEpisodeNumber,
+ )
+ }
+ ContentType.MOVIE, ContentType.VOD -> {
+ val movie = currentContentId.takeIf { it > 0L }?.let { id ->
+ playerContentResolver.getMovie(id)
+ }
+ ExternalSubtitleQuery(
+ contentType = ContentType.MOVIE,
+ title = movie?.name?.takeIf { it.isNotBlank() }
+ ?: currentTitle.ifBlank { playbackTitleFlow.value },
+ year = movie?.year?.takeIf { it.isNotBlank() }?.take(4)?.toIntOrNull(),
+ tmdbId = movie?.tmdbId,
+ )
+ }
+ else -> error("Online subtitles are not available for this content.")
+ }
+ if (query.title.isBlank()) {
+ externalSubtitleSearchStateFlow.update {
+ it.copy(isSearching = false, errorMessage = "Could not identify this title for subtitle search.")
+ }
+ return@launch
+ }
+ val preferredLanguage = playerPreferencesCoordinator.preferredAudioLanguage.first()
+ ?.trim()
+ ?.takeIf { it.isNotBlank() && !it.equals("auto", ignoreCase = true) }
+ ?: "en"
+ when (val result = searchExternalSubtitlesUseCase(
+ contentType = query.contentType,
+ title = query.title,
+ year = query.year,
+ tmdbId = query.tmdbId,
+ parentTmdbId = query.parentTmdbId,
+ seasonNumber = query.seasonNumber,
+ episodeNumber = query.episodeNumber,
+ language = preferredLanguage,
+ )) {
+ is Result.Success -> externalSubtitleSearchStateFlow.update {
+ it.copy(isSearching = false, subtitles = result.data)
+ }
+ is Result.Error -> externalSubtitleSearchStateFlow.update {
+ it.copy(isSearching = false, errorMessage = result.message)
+ }
+ is Result.Loading -> externalSubtitleSearchStateFlow.update { it.copy(isSearching = false) }
+ }
+ } catch (e: Exception) {
+ if (e is CancellationException) throw e
+ externalSubtitleSearchStateFlow.update {
+ it.copy(isSearching = false, errorMessage = e.message ?: "Subtitle search failed.")
+ }
+ }
+ }
+}
+
+internal fun PlayerViewModel.downloadExternalSubtitle(subtitleId: String) {
+ val subtitle = externalSubtitleSearchStateFlow.value.subtitles.firstOrNull { it.id == subtitleId }
+ ?: return
+ externalSubtitleDownloadJob?.cancel()
+ externalSubtitleDownloadJob = viewModelScope.launch {
+ externalSubtitleSearchStateFlow.update {
+ it.copy(downloadingSubtitleId = subtitle.id, errorMessage = null)
+ }
+ try {
+ when (val result = downloadExternalSubtitleUseCase(subtitle)) {
+ is Result.Success -> {
+ playerEngine.addExternalSubtitle(Uri.fromFile(result.data), subtitle.language)
+ externalSubtitleSearchStateFlow.update {
+ it.copy(downloadingSubtitleId = null, appliedSubtitleName = subtitle.displayLanguage)
+ }
+ }
+ is Result.Error -> externalSubtitleSearchStateFlow.update {
+ it.copy(downloadingSubtitleId = null, errorMessage = result.message)
+ }
+ is Result.Loading -> externalSubtitleSearchStateFlow.update { it.copy(downloadingSubtitleId = null) }
+ }
+ } catch (e: Exception) {
+ if (e is CancellationException) throw e
+ externalSubtitleSearchStateFlow.update {
+ it.copy(downloadingSubtitleId = null, errorMessage = e.message ?: "Subtitle download failed.")
+ }
+ }
+ }
+}
+
+internal fun PlayerViewModel.cancelExternalSubtitleSearch() {
+ externalSubtitleSearchJob?.cancel()
+ externalSubtitleDownloadJob?.cancel()
+ externalSubtitleSearchStateFlow.update { it.copy(isSearching = false, downloadingSubtitleId = null) }
+}
+
+private data class ExternalSubtitleQuery(
+ val contentType: ContentType,
+ val title: String,
+ val year: Int? = null,
+ val tmdbId: Long? = null,
+ val parentTmdbId: Long? = null,
+ val seasonNumber: Int? = null,
+ val episodeNumber: Int? = null,
+)
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerExternalSubtitleSearchDialog.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerExternalSubtitleSearchDialog.kt
new file mode 100644
index 00000000..574b686a
--- /dev/null
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerExternalSubtitleSearchDialog.kt
@@ -0,0 +1,265 @@
+package com.streamvault.feature.playback.player
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxHeight
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.widthIn
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.focus.FocusRequester
+import androidx.compose.ui.focus.focusRequester
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.window.Dialog
+import androidx.compose.ui.window.DialogProperties
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import androidx.tv.material3.Button
+import androidx.tv.material3.ButtonDefaults
+import androidx.tv.material3.ClickableSurfaceDefaults
+import androidx.tv.material3.MaterialTheme
+import androidx.tv.material3.Surface
+import androidx.tv.material3.SurfaceDefaults
+import androidx.tv.material3.Text
+import com.streamvault.core.ui.design.AppColors
+import com.streamvault.core.ui.design.requestFocusSafely
+import com.streamvault.core.ui.interaction.TvClickableSurface
+import com.streamvault.feature.playback.R
+import java.text.NumberFormat
+
+@Composable
+internal fun PlayerExternalSubtitleSearchDialog(
+ viewModel: PlayerViewModel,
+ onDismiss: () -> Unit,
+ onOpenSettings: () -> Unit,
+) {
+ val state by viewModel.externalSubtitleSearchState.collectAsStateWithLifecycle()
+ val playbackTitle by viewModel.playbackTitle.collectAsStateWithLifecycle()
+ val description = when {
+ state.account == null -> stringResource(R.string.player_subtitle_search_signed_out)
+ playbackTitle.isBlank() -> stringResource(R.string.player_subtitle_search_signed_in)
+ else -> stringResource(R.string.player_subtitle_search_results_for, playbackTitle)
+ }
+ val firstResultFocusRequester = androidx.compose.runtime.remember { FocusRequester() }
+ val dismissSearch = {
+ viewModel.cancelExternalSubtitleSearch()
+ onDismiss()
+ }
+
+ LaunchedEffect(state.account?.username) {
+ if (state.account != null) viewModel.searchExternalSubtitles()
+ }
+ LaunchedEffect(state.isSearching, state.subtitles.firstOrNull()?.id, state.account?.username) {
+ if (state.account != null && !state.isSearching && state.subtitles.isNotEmpty()) {
+ firstResultFocusRequester.requestFocusSafely(
+ tag = "PlayerExternalSubtitleSearchDialog",
+ target = "First subtitle result",
+ )
+ }
+ }
+
+ Dialog(
+ onDismissRequest = dismissSearch,
+ properties = DialogProperties(usePlatformDefaultWidth = false),
+ ) {
+ Box(
+ modifier = Modifier.fillMaxSize().background(androidx.compose.ui.graphics.Color.Black.copy(alpha = 0.82f))
+ .clickable(onClick = dismissSearch),
+ contentAlignment = Alignment.Center,
+ ) {
+ Surface(
+ modifier = Modifier.widthIn(min = 360.dp, max = 720.dp).fillMaxHeight(0.82f),
+ shape = RoundedCornerShape(24.dp),
+ colors = SurfaceDefaults.colors(containerColor = AppColors.SurfaceElevated),
+ ) {
+ Column(
+ modifier = Modifier.padding(28.dp),
+ verticalArrangement = Arrangement.spacedBy(16.dp),
+ ) {
+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ Text(
+ text = stringResource(R.string.player_subtitle_search_title),
+ style = MaterialTheme.typography.headlineSmall,
+ color = AppColors.TextPrimary,
+ )
+ Text(
+ text = description,
+ style = MaterialTheme.typography.bodyMedium,
+ color = AppColors.TextSecondary,
+ )
+ }
+
+ if (state.account == null) {
+ Column(
+ modifier = Modifier.weight(1f).fillMaxWidth(),
+ verticalArrangement = Arrangement.Center,
+ horizontalAlignment = Alignment.CenterHorizontally,
+ ) {
+ Button(onClick = onOpenSettings) {
+ Text(stringResource(R.string.player_subtitle_search_open_settings))
+ }
+ }
+ } else {
+ LazyColumn(
+ modifier = Modifier.weight(1f).fillMaxWidth(),
+ verticalArrangement = Arrangement.spacedBy(8.dp),
+ ) {
+ if (state.isSearching) {
+ item {
+ Row(
+ modifier = Modifier.fillMaxWidth().padding(16.dp),
+ horizontalArrangement = Arrangement.spacedBy(12.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ androidx.compose.material3.CircularProgressIndicator(
+ modifier = Modifier.size(24.dp),
+ color = AppColors.Brand,
+ strokeWidth = 2.dp,
+ )
+ Text(
+ text = stringResource(R.string.player_subtitle_search_loading),
+ style = MaterialTheme.typography.bodyMedium,
+ color = AppColors.TextSecondary,
+ )
+ }
+ }
+ }
+
+ state.errorMessage?.let { error ->
+ item {
+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ Text(
+ text = error,
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.error,
+ modifier = Modifier.padding(12.dp),
+ )
+ if (!state.isSearching && state.subtitles.isEmpty()) {
+ Button(onClick = viewModel::searchExternalSubtitles) {
+ Text(stringResource(R.string.player_subtitle_search_retry))
+ }
+ }
+ }
+ }
+ }
+
+ if (!state.isSearching && state.errorMessage == null && state.subtitles.isEmpty()) {
+ item {
+ Text(
+ text = stringResource(R.string.player_subtitle_search_no_results),
+ style = MaterialTheme.typography.bodyMedium,
+ color = AppColors.TextSecondary,
+ modifier = Modifier.padding(16.dp),
+ )
+ }
+ }
+
+ state.appliedSubtitleName?.let { name ->
+ item {
+ Text(
+ text = stringResource(R.string.player_subtitle_search_applied, name),
+ style = MaterialTheme.typography.bodyMedium,
+ color = AppColors.Brand,
+ modifier = Modifier.padding(12.dp),
+ )
+ }
+ }
+
+ items(state.subtitles, key = { it.id }) { subtitle ->
+ val downloading = state.downloadingSubtitleId != null
+ TvClickableSurface(
+ onClick = { viewModel.downloadExternalSubtitle(subtitle.id) },
+ enabled = !downloading,
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = AppColors.Surface,
+ focusedContainerColor = AppColors.SurfaceEmphasis,
+ ),
+ modifier = if (subtitle == state.subtitles.firstOrNull()) {
+ Modifier.focusRequester(firstResultFocusRequester)
+ } else {
+ Modifier
+ },
+ ) {
+ Row(
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 14.dp),
+ horizontalArrangement = Arrangement.spacedBy(16.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Column(
+ modifier = Modifier.weight(1f),
+ verticalArrangement = Arrangement.spacedBy(4.dp),
+ ) {
+ Text(
+ text = subtitle.displayLanguage,
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.SemiBold,
+ color = AppColors.TextPrimary,
+ )
+ Text(
+ text = subtitle.releaseName.ifBlank {
+ stringResource(R.string.player_subtitle_search_release_unknown)
+ },
+ style = MaterialTheme.typography.bodySmall,
+ color = AppColors.TextSecondary,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis,
+ )
+ Text(
+ text = stringResource(
+ R.string.player_subtitle_search_download_count,
+ NumberFormat.getIntegerInstance().format(subtitle.downloadCount),
+ ),
+ style = MaterialTheme.typography.labelSmall,
+ color = AppColors.TextSecondary,
+ )
+ }
+ if (state.downloadingSubtitleId == subtitle.id) {
+ androidx.compose.material3.CircularProgressIndicator(
+ modifier = Modifier.size(26.dp),
+ color = AppColors.Brand,
+ strokeWidth = 2.dp,
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.End,
+ ) {
+ Button(
+ onClick = {
+ dismissSearch()
+ },
+ colors = ButtonDefaults.colors(
+ containerColor = AppColors.Surface,
+ focusedContainerColor = AppColors.SurfaceEmphasis,
+ ),
+ ) {
+ Text(stringResource(R.string.player_subtitle_search_close))
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerModalHosts.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerModalHosts.kt
index d0a34f62..b5c25793 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerModalHosts.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerModalHosts.kt
@@ -51,6 +51,8 @@ internal fun PlayerControlsModalHost(
viewModel: PlayerViewModel,
isInPictureInPictureMode: Boolean,
showTrackSelection: TrackType?,
+ showSubtitleSearch: Boolean,
+ onlineSubtitleSearchAvailable: Boolean,
showVariantSelection: Boolean,
currentChannel: Channel?,
showSpeedSelection: Boolean,
@@ -62,6 +64,8 @@ internal fun PlayerControlsModalHost(
fallbackTitle: String,
fallbackEpisodeId: Long,
fallbackSeasonNumber: Int?,
+ onOpenSubtitleSearch: () -> Unit,
+ onOpenSettings: () -> Unit,
onDismissModal: () -> Unit,
) {
if (showAudioVideoOffsetDialog) {
@@ -105,6 +109,7 @@ internal fun PlayerControlsModalHost(
videoTracks = availableVideoQualities,
liveTranslationAvailable = liveTranslationAvailable,
liveTranslationActive = liveTranslationActive,
+ onlineSubtitleSearchAvailable = onlineSubtitleSearchAvailable,
onDismiss = onDismissModal,
onSelectAudio = viewModel::selectAudioTrack,
onSelectVideo = viewModel::selectVideoQuality,
@@ -115,7 +120,22 @@ internal fun PlayerControlsModalHost(
onSelectLiveTranslation = {
viewModel.selectSubtitleTrack(null)
viewModel.activateLiveTranslation()
- }
+ },
+ onSearchOnlineSubtitles = onOpenSubtitleSearch,
+ )
+ }
+ if (!isInPictureInPictureMode && showSubtitleSearch) {
+ PlayerExternalSubtitleSearchDialog(
+ viewModel = viewModel,
+ onDismiss = {
+ viewModel.cancelExternalSubtitleSearch()
+ onDismissModal()
+ },
+ onOpenSettings = {
+ viewModel.cancelExternalSubtitleSearch()
+ onDismissModal()
+ onOpenSettings()
+ },
)
}
if (!isInPictureInPictureMode && showVariantSelection) {
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerModalState.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerModalState.kt
index 436a1f75..1ce5caa3 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerModalState.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerModalState.kt
@@ -14,6 +14,7 @@ internal sealed interface PlayerModal {
data object EpisodePicker : PlayerModal
data object ChapterSelection : PlayerModal
data object PlaybackSettings : PlayerModal
+ data object SubtitleSearch : PlayerModal
}
/**
* UI-owned modal state for the player screen.
@@ -57,6 +58,9 @@ internal data class PlayerModalState(
val showPlaybackSettings: Boolean
get() = active is PlayerModal.PlaybackSettings
+ val showSubtitleSearch: Boolean
+ get() = active is PlayerModal.SubtitleSearch
+
val hasVisibleModal: Boolean
get() = active != null
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerScreen.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerScreen.kt
index 195f7b24..630568c8 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerScreen.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerScreen.kt
@@ -164,6 +164,7 @@ fun PlayerScreen(
val playerPreferencesUiState by viewModel.playerPreferencesUiState.collectAsStateWithLifecycle()
val isCatchUpPlayback by viewModel.isCatchUpPlayback.collectAsStateWithLifecycle()
+ val onlineSubtitleSearchAvailable = !isCatchUpPlayback && contentType in setOf("VOD", "MOVIE", "SERIES_EPISODE")
val showChannelListOverlay by viewModel.showChannelListOverlay.collectAsStateWithLifecycle()
val showCategoryListOverlay by viewModel.showCategoryListOverlay.collectAsStateWithLifecycle()
val showEpgOverlay by viewModel.showEpgOverlay.collectAsStateWithLifecycle()
@@ -421,6 +422,7 @@ fun PlayerScreen(
showStopPlaybackTimerDialog = modalState.showStopPlaybackTimerDialog,
showIdleStandbyTimerDialog = modalState.showIdleStandbyTimerDialog,
hasTrackSelection = modalState.trackSelection != null,
+ showSubtitleSearch = modalState.showSubtitleSearch,
showVariantSelection = modalState.showVariantSelection,
showDiagnostics = showDiagnostics,
showChannelInfoOverlay = showChannelInfoOverlay,
@@ -447,6 +449,10 @@ fun PlayerScreen(
PlayerBackAction.CLOSE_IDLE_STANDBY_TIMER -> modalState = modalState.dismiss()
PlayerBackAction.CLOSE_VARIANT_SELECTION -> modalState = modalState.dismiss()
PlayerBackAction.CLOSE_TRACK_SELECTION -> modalState = modalState.dismiss()
+ PlayerBackAction.CLOSE_SUBTITLE_SEARCH -> {
+ viewModel.cancelExternalSubtitleSearch()
+ modalState = modalState.dismiss()
+ }
PlayerBackAction.TOGGLE_DIAGNOSTICS -> viewModel.toggleDiagnostics()
PlayerBackAction.CLOSE_CHANNEL_INFO -> viewModel.closeChannelInfoOverlay()
PlayerBackAction.CLOSE_LIVE_OVERLAYS -> viewModel.closeOverlays()
@@ -779,6 +785,7 @@ fun PlayerScreen(
title = title,
contentType = contentType,
isCatchUpPlayback = isCatchUpPlayback,
+ onlineSubtitleSearchAvailable = onlineSubtitleSearchAvailable,
isPlaying = isPlaying,
currentChannel = currentChannel,
currentChannelName = currentChannel?.name,
@@ -887,6 +894,8 @@ fun PlayerScreen(
viewModel = viewModel,
isInPictureInPictureMode = isInPictureInPictureMode,
showTrackSelection = modalState.trackSelection,
+ showSubtitleSearch = modalState.showSubtitleSearch,
+ onlineSubtitleSearchAvailable = onlineSubtitleSearchAvailable,
showVariantSelection = modalState.showVariantSelection,
currentChannel = currentChannel,
showSpeedSelection = modalState.showSpeedSelection,
@@ -898,6 +907,8 @@ fun PlayerScreen(
fallbackTitle = title,
fallbackEpisodeId = internalChannelId,
fallbackSeasonNumber = seasonNumber,
+ onOpenSubtitleSearch = { modalState = modalState.open(PlayerModal.SubtitleSearch) },
+ onOpenSettings = { onNavigate?.invoke(AppDestination.Settings()) },
onDismissModal = { modalState = modalState.dismiss() }
)
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModel.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModel.kt
index bf7f939f..aeee6c07 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModel.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModel.kt
@@ -14,6 +14,7 @@ import com.streamvault.domain.model.Program
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.DecoderMode
import com.streamvault.domain.model.Episode
+import com.streamvault.domain.model.ExternalSubtitle
import com.streamvault.domain.model.LiveChannelObservedQuality
import com.streamvault.domain.model.PlaybackHistory
import com.streamvault.domain.model.RecordingItem
@@ -26,6 +27,9 @@ import com.streamvault.domain.model.StreamInfo
import com.streamvault.domain.model.VirtualCategoryIds
import com.streamvault.domain.model.VideoFormat
import com.streamvault.domain.settings.VodTrackPreferences
+import com.streamvault.domain.manager.OpenSubtitlesAccountManager
+import com.streamvault.domain.usecase.DownloadExternalSubtitle
+import com.streamvault.domain.usecase.SearchExternalSubtitles
import com.streamvault.player.AUDIO_VIDEO_OFFSET_MAX_MS
import com.streamvault.player.AUDIO_VIDEO_OFFSET_MIN_MS
import com.streamvault.player.PlaybackState
@@ -76,6 +80,9 @@ class PlayerViewModel @Inject constructor(
internal val playerPlaybackContextCoordinator: PlayerPlaybackContextCoordinator,
internal val playerRecoveryCoordinator: PlayerRecoveryCoordinator,
internal val playerRecoveryExecutionCoordinator: PlayerRecoveryExecutionCoordinator,
+ internal val searchExternalSubtitlesUseCase: SearchExternalSubtitles,
+ internal val downloadExternalSubtitleUseCase: DownloadExternalSubtitle,
+ internal val openSubtitlesAccountManager: OpenSubtitlesAccountManager,
) : ViewModel() {
companion object {
private const val MIN_WATCHED_FOR_AUTO_PLAY_MS = 5_000L
@@ -127,6 +134,12 @@ class PlayerViewModel @Inject constructor(
internal val playbackTitleFlow = MutableStateFlow("")
val playbackTitle: StateFlow<String> = playbackTitleFlow.asStateFlow()
+
+ internal val externalSubtitleSearchStateFlow = MutableStateFlow(ExternalSubtitleSearchUiState())
+ val externalSubtitleSearchState: StateFlow<ExternalSubtitleSearchUiState> =
+ externalSubtitleSearchStateFlow.asStateFlow()
+ internal var externalSubtitleSearchJob: Job? = null
+ internal var externalSubtitleDownloadJob: Job? = null
internal val _resumePrompt = MutableStateFlow(ResumePromptState())
val resumePrompt: StateFlow<ResumePromptState> = _resumePrompt.asStateFlow()
@@ -502,6 +515,11 @@ class PlayerViewModel @Inject constructor(
init {
observeCastPlaybackEvents()
+ viewModelScope.launch {
+ openSubtitlesAccountManager.account.collect { account ->
+ externalSubtitleSearchStateFlow.update { it.copy(account = account) }
+ }
+ }
viewModelScope.launch {
activePlayerEngineFlow.flatMapLatest { it.error }.collect { error ->
if (error != null) {
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModelModels.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModelModels.kt
index e4602098..3adcb626 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModelModels.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModelModels.kt
@@ -6,6 +6,8 @@ import com.streamvault.domain.model.ChannelQualityOption
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.AppTimeFormat
import com.streamvault.domain.model.Episode
+import com.streamvault.domain.model.ExternalSubtitle
+import com.streamvault.domain.manager.OpenSubtitlesAccount
import com.streamvault.domain.model.ExternalPlaybackMode
import com.streamvault.domain.model.LiveClockFont
import com.streamvault.domain.model.LiveClockPosition
@@ -29,6 +31,15 @@ data class NumericChannelInputState(
val invalid: Boolean = false
)
+data class ExternalSubtitleSearchUiState(
+ val account: OpenSubtitlesAccount? = null,
+ val isSearching: Boolean = false,
+ val subtitles: List<ExternalSubtitle> = emptyList(),
+ val errorMessage: String? = null,
+ val downloadingSubtitleId: String? = null,
+ val appliedSubtitleName: String? = null,
+)
+
data class PlayerNoticeState(
val message: String = "",
val recoveryType: PlayerRecoveryType = PlayerRecoveryType.UNKNOWN,
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/VodOverlayState.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/VodOverlayState.kt
index 409ad0c8..62587365 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/VodOverlayState.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/VodOverlayState.kt
@@ -29,6 +29,7 @@ internal fun buildVodOverlayState(
audioTrackCount: Int,
videoQualityCount: Int,
audioVideoSyncEnabled: Boolean = false,
+ onlineSubtitleSearchAvailable: Boolean = false,
showExternalPlayerAction: Boolean,
isCastConnected: Boolean
): VodOverlayState {
@@ -48,7 +49,7 @@ internal fun buildVodOverlayState(
nextChapterTargetMs = nextChapterTarget(visibleChapters, currentPositionMs),
showChapterAction = isVod && visibleChapters.isNotEmpty() && !isCastConnected,
showEpisodesAction = isVod && normalizedContentType == "SERIES_EPISODE" && showEpisodesAction,
- showSubtitleAction = isVod && subtitleTrackCount > 0,
+ showSubtitleAction = isVod && (subtitleTrackCount > 0 || onlineSubtitleSearchAvailable),
showAudioAction = isVod && audioTrackCount > 0,
showVideoQualityAction = isVod && videoQualityCount > 0,
showAudioVideoSyncAction = isVod && audioVideoSyncEnabled && !isCastConnected,
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/overlay/PlayerSystemOverlays.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/overlay/PlayerSystemOverlays.kt
index b33f31d9..c23e405d 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/overlay/PlayerSystemOverlays.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/overlay/PlayerSystemOverlays.kt
@@ -258,11 +258,13 @@ fun PlayerTrackSelectionDialog(
videoTracks: List<PlayerTrack>,
liveTranslationAvailable: Boolean = false,
liveTranslationActive: Boolean = false,
+ onlineSubtitleSearchAvailable: Boolean = false,
onDismiss: () -> Unit,
onSelectAudio: (String) -> Unit,
onSelectVideo: (String) -> Unit,
onSelectSubtitle: (String?) -> Unit,
- onSelectLiveTranslation: () -> Unit = {}
+ onSelectLiveTranslation: () -> Unit = {},
+ onSearchOnlineSubtitles: () -> Unit = {},
) {
if (trackType == null) return
@@ -371,6 +373,16 @@ fun PlayerTrackSelectionDialog(
)
}
}
+
+ if (trackType == TrackType.TEXT && onlineSubtitleSearchAvailable) {
+ item {
+ TrackSelectionItem(
+ name = stringResource(R.string.player_search_online_subtitles),
+ isSelected = false,
+ onClick = onSearchOnlineSubtitles,
+ )
+ }
+ }
}
}
}
diff --git a/feature/playback/src/main/res/values/playback_player_strings.xml b/feature/playback/src/main/res/values/playback_player_strings.xml
index 3c0a2dea..8a168f7c 100644
--- a/feature/playback/src/main/res/values/playback_player_strings.xml
+++ b/feature/playback/src/main/res/values/playback_player_strings.xml
@@ -1,4 +1,18 @@
<resources xmlns:tools="http://schemas.android.com/tools">
+ <string name="player_search_online_subtitles" tools:ignore="MissingTranslation">Search online subtitles</string>
+ <string name="player_subtitle_search_title" tools:ignore="MissingTranslation">Find subtitles</string>
+ <string name="player_subtitle_search_signed_in" tools:ignore="MissingTranslation">Choose a subtitle to add to this video.</string>
+ <string name="player_subtitle_search_results_for" tools:ignore="MissingTranslation">Results for %1$s</string>
+ <string name="player_subtitle_search_signed_out" tools:ignore="MissingTranslation">Connect your OpenSubtitles account in Settings to search and download subtitles.</string>
+ <string name="player_subtitle_search_open_settings" tools:ignore="MissingTranslation">Open Settings</string>
+ <string name="player_subtitle_search_loading" tools:ignore="MissingTranslation">Searching OpenSubtitles…</string>
+ <string name="player_subtitle_search_no_results" tools:ignore="MissingTranslation">No subtitles found for this title and language.</string>
+ <string name="player_subtitle_search_retry" tools:ignore="MissingTranslation">Search again</string>
+ <string name="player_subtitle_search_download_count" tools:ignore="MissingTranslation">%1$s downloads</string>
+ <string name="player_subtitle_search_release_unknown" tools:ignore="MissingTranslation">General release</string>
+ <string name="player_subtitle_search_downloading" tools:ignore="MissingTranslation">Downloading subtitle…</string>
+ <string name="player_subtitle_search_applied" tools:ignore="MissingTranslation">%1$s added. The player is loading the subtitle.</string>
+ <string name="player_subtitle_search_close" tools:ignore="MissingTranslation">Close</string>
<plurals name="settings_timer_minutes">
<item quantity="one">%1$d minute</item>
<item quantity="other">%1$d minutes</item>
diff --git a/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerBackNavigationPolicyTest.kt b/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerBackNavigationPolicyTest.kt
index 224ad2af..9842feee 100644
--- a/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerBackNavigationPolicyTest.kt
+++ b/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerBackNavigationPolicyTest.kt
@@ -72,6 +72,16 @@ class PlayerBackNavigationPolicyTest {
assertThat(playerBackAction(state)).isEqualTo(PlayerBackAction.CLOSE_PLAYBACK_SETTINGS)
}
+ @Test
+ fun `subtitle search closes before returning to playback controls`() {
+ val state = PlayerBackNavigationState(
+ showSubtitleSearch = true,
+ showControls = true,
+ )
+
+ assertThat(playerBackAction(state)).isEqualTo(PlayerBackAction.CLOSE_SUBTITLE_SEARCH)
+ }
+
@Test
fun `empty player state navigates back`() {
assertThat(playerBackAction(PlayerBackNavigationState()))
diff --git a/feature/playback/src/test/java/com/streamvault/feature/playback/player/VodOverlayStateTest.kt b/feature/playback/src/test/java/com/streamvault/feature/playback/player/VodOverlayStateTest.kt
index d30fc392..818b6327 100644
--- a/feature/playback/src/test/java/com/streamvault/feature/playback/player/VodOverlayStateTest.kt
+++ b/feature/playback/src/test/java/com/streamvault/feature/playback/player/VodOverlayStateTest.kt
@@ -58,6 +58,25 @@ class VodOverlayStateTest {
assertThat(state.showChapterAction).isFalse()
}
+ @Test
+ fun `movie exposes subtitle action for online search without embedded tracks`() {
+ val state = buildVodOverlayState(
+ contentType = "MOVIE",
+ isCatchUpPlayback = false,
+ chapters = emptyList(),
+ currentPositionMs = 0L,
+ showEpisodesAction = false,
+ subtitleTrackCount = 0,
+ audioTrackCount = 0,
+ videoQualityCount = 0,
+ onlineSubtitleSearchAvailable = true,
+ showExternalPlayerAction = false,
+ isCastConnected = false,
+ )
+
+ assertThat(state.showSubtitleAction).isTrue()
+ }
+
@Test
fun `cast hides chapter action while preserving navigation state`() {
val state = buildVodOverlayState(
@@ -89,6 +108,7 @@ class VodOverlayStateTest {
subtitleTrackCount = 1,
audioTrackCount = 1,
videoQualityCount = 1,
+ onlineSubtitleSearchAvailable = true,
showExternalPlayerAction = true,
isCastConnected = false
)
diff --git a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/OpenSubtitlesAccountSettings.kt b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/OpenSubtitlesAccountSettings.kt
new file mode 100644
index 00000000..a607747f
--- /dev/null
+++ b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/OpenSubtitlesAccountSettings.kt
@@ -0,0 +1,189 @@
+package com.streamvault.feature.settings.presentation
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.input.KeyboardType
+import androidx.compose.ui.text.input.PasswordVisualTransformation
+import androidx.compose.ui.unit.dp
+import androidx.tv.material3.MaterialTheme
+import androidx.tv.material3.Text
+import com.streamvault.core.ui.components.dialogs.PremiumDialog
+import com.streamvault.core.ui.components.dialogs.PremiumDialogFooterButton
+import com.streamvault.core.ui.theme.OnSurfaceDim
+import com.streamvault.feature.settings.R
+
+@Composable
+internal fun OpenSubtitlesAccountSettings(
+ uiState: SettingsUiState,
+ viewModel: SettingsViewModel,
+ targetFocusModifier: Modifier = Modifier,
+) {
+ var showSignIn by rememberSaveable { mutableStateOf(false) }
+ var showSignOut by rememberSaveable { mutableStateOf(false) }
+ val account = uiState.openSubtitlesAccount
+ val remainingDownloads = account?.remainingDownloads
+
+ Column(
+ modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
+ verticalArrangement = Arrangement.spacedBy(4.dp),
+ ) {
+ SettingsRow(
+ label = stringResource(R.string.settings_opensubtitles_title),
+ value = stringResource(R.string.settings_opensubtitles_description),
+ )
+ if (account == null) {
+ ClickableSettingsRow(
+ label = stringResource(R.string.settings_opensubtitles_connect),
+ value = if (uiState.isOpenSubtitlesBusy) {
+ stringResource(R.string.settings_opensubtitles_signing_in)
+ } else {
+ stringResource(R.string.settings_opensubtitles_signed_out)
+ },
+ enabled = !uiState.isOpenSubtitlesBusy,
+ onClick = { showSignIn = true },
+ modifier = targetFocusModifier,
+ )
+ } else {
+ SettingsRow(
+ label = account.username,
+ value = when {
+ remainingDownloads != null && remainingDownloads == 1 ->
+ stringResource(R.string.settings_opensubtitles_remaining_one)
+ remainingDownloads != null -> stringResource(
+ R.string.settings_opensubtitles_remaining,
+ remainingDownloads,
+ )
+ account.allowedDownloads > 0 -> stringResource(
+ R.string.settings_opensubtitles_daily_allowance,
+ account.allowedDownloads,
+ )
+ else -> stringResource(R.string.settings_opensubtitles_quota_unknown)
+ },
+ )
+ ClickableSettingsRow(
+ label = stringResource(R.string.settings_opensubtitles_sign_out),
+ value = if (uiState.isOpenSubtitlesBusy) {
+ stringResource(R.string.settings_opensubtitles_signing_out)
+ } else {
+ ""
+ },
+ enabled = !uiState.isOpenSubtitlesBusy,
+ onClick = { showSignOut = true },
+ modifier = targetFocusModifier,
+ )
+ }
+ uiState.openSubtitlesError?.let { error ->
+ Text(
+ text = error,
+ color = MaterialTheme.colorScheme.error,
+ style = MaterialTheme.typography.bodySmall,
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp),
+ )
+ }
+ }
+
+ if (showSignIn) {
+ var username by rememberSaveable { mutableStateOf("") }
+ var password by rememberSaveable { mutableStateOf("") }
+ LaunchedEffect(account) {
+ if (account != null) showSignIn = false
+ }
+ PremiumDialog(
+ title = stringResource(R.string.settings_opensubtitles_sign_in_title),
+ subtitle = stringResource(R.string.settings_opensubtitles_sign_in_subtitle),
+ onDismissRequest = { if (!uiState.isOpenSubtitlesBusy) showSignIn = false },
+ widthFraction = 0.58f,
+ heightFraction = 0.76f,
+ bodyHeightFraction = 0.62f,
+ content = {
+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ EpgSourceTextField(
+ value = username,
+ onValueChange = { username = it },
+ placeholder = stringResource(R.string.settings_opensubtitles_username),
+ )
+ EpgSourceTextField(
+ value = password,
+ onValueChange = { password = it },
+ placeholder = stringResource(R.string.settings_opensubtitles_password),
+ visualTransformation = PasswordVisualTransformation(),
+ keyboardType = KeyboardType.Password,
+ )
+ uiState.openSubtitlesError?.let { error ->
+ Text(
+ text = error,
+ color = MaterialTheme.colorScheme.error,
+ style = MaterialTheme.typography.bodySmall,
+ )
+ }
+ }
+ },
+ footer = {
+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ PremiumDialogFooterButton(
+ label = stringResource(R.string.settings_cancel),
+ onClick = { showSignIn = false },
+ enabled = !uiState.isOpenSubtitlesBusy,
+ )
+ PremiumDialogFooterButton(
+ label = if (uiState.isOpenSubtitlesBusy) {
+ stringResource(R.string.settings_opensubtitles_signing_in)
+ } else {
+ stringResource(R.string.settings_opensubtitles_sign_in)
+ },
+ onClick = {
+ viewModel.signInToOpenSubtitles(username, password)
+ },
+ enabled = username.isNotBlank() && password.isNotBlank() && !uiState.isOpenSubtitlesBusy,
+ emphasized = true,
+ )
+ }
+ },
+ )
+ }
+
+ if (showSignOut && account != null) {
+ PremiumDialog(
+ title = stringResource(R.string.settings_opensubtitles_sign_out_title),
+ subtitle = stringResource(R.string.settings_opensubtitles_sign_out_subtitle),
+ onDismissRequest = { if (!uiState.isOpenSubtitlesBusy) showSignOut = false },
+ content = {
+ Text(
+ text = account.username,
+ style = MaterialTheme.typography.bodyLarge,
+ color = OnSurfaceDim,
+ )
+ },
+ footer = {
+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ PremiumDialogFooterButton(
+ label = stringResource(R.string.settings_cancel),
+ onClick = { showSignOut = false },
+ enabled = !uiState.isOpenSubtitlesBusy,
+ )
+ PremiumDialogFooterButton(
+ label = stringResource(R.string.settings_opensubtitles_sign_out),
+ onClick = {
+ showSignOut = false
+ viewModel.signOutOfOpenSubtitles()
+ },
+ enabled = !uiState.isOpenSubtitlesBusy,
+ destructive = true,
+ )
+ }
+ },
+ )
+ }
+}
diff --git a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsPlaybackSection.kt b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsPlaybackSection.kt
index 32031262..417a6539 100644
--- a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsPlaybackSection.kt
+++ b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsPlaybackSection.kt
@@ -369,6 +369,11 @@ public fun LazyListScope.settingsPlaybackSection(
modifier = if (targetItemId == "playback.ethernet_cap") targetFocusModifier else Modifier,)
}
if (page == null || page == SettingsPage.SUBTITLES) {
+ OpenSubtitlesAccountSettings(
+ uiState = uiState,
+ viewModel = viewModel,
+ targetFocusModifier = if (targetItemId == "playback.subtitles_provider") targetFocusModifier else Modifier,
+ )
SwitchSettingsRow(
label = stringResource(R.string.settings_live_translation_enabled),
value = stringResource(R.string.settings_live_translation_enabled_subtitle),
diff --git a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsSearchSurface.kt b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsSearchSurface.kt
index c7cfa47a..03979ac0 100644
--- a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsSearchSurface.kt
+++ b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsSearchSurface.kt
@@ -223,6 +223,7 @@ private fun resolvedSettingsCatalog(
setting("playback.audio_language", SettingsCategory.PLAYBACK, SettingsPage.AUDIO, R.string.settings_preferred_audio_language, "language"),
setting("playback.live_translation", SettingsCategory.PLAYBACK, SettingsPage.SUBTITLES, R.string.settings_live_translation_enabled, "translate subtitles"),
setting("playback.translation_endpoint", SettingsCategory.PLAYBACK, SettingsPage.SUBTITLES, R.string.settings_live_translation_endpoint, "translation server"),
+ setting("playback.subtitles_provider", SettingsCategory.PLAYBACK, SettingsPage.SUBTITLES, R.string.settings_opensubtitles_title, "opensubtitles", "online subtitles", "subtitle account"),
setting("playback.subtitle_size", SettingsCategory.PLAYBACK, SettingsPage.SUBTITLES, R.string.settings_subtitle_size, "captions"),
setting("playback.subtitle_text_color", SettingsCategory.PLAYBACK, SettingsPage.SUBTITLES, R.string.settings_subtitle_text_color, "captions color"),
setting("playback.subtitle_background", SettingsCategory.PLAYBACK, SettingsPage.SUBTITLES, R.string.settings_subtitle_background, "captions background"),
diff --git a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsSharedUiComponents.kt b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsSharedUiComponents.kt
index 487e216d..3a03c1bf 100644
--- a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsSharedUiComponents.kt
+++ b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsSharedUiComponents.kt
@@ -41,6 +41,7 @@ import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.input.ImeAction
+import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.tv.material3.Border
import androidx.tv.material3.ClickableSurfaceDefaults
@@ -131,6 +132,8 @@ fun EpgSourceTextField(
onValueChange: (String) -> Unit,
placeholder: String,
modifier: Modifier = Modifier,
+ visualTransformation: VisualTransformation = VisualTransformation.None,
+ keyboardType: androidx.compose.ui.text.input.KeyboardType = androidx.compose.ui.text.input.KeyboardType.Text,
) {
val settingsColors = SettingsDesignTokens.colors(com.streamvault.core.ui.design.AppColors.current)
val isTelevisionDevice = com.streamvault.core.ui.device.rememberIsTelevisionDevice()
@@ -267,6 +270,7 @@ fun EpgSourceTextField(
textStyle = MaterialTheme.typography.bodyMedium.copy(color = settingsColors.searchText),
singleLine = true,
cursorBrush = SolidColor(settingsColors.cursor),
+ visualTransformation = visualTransformation,
modifier = Modifier
.fillMaxWidth()
.focusRequester(inputFocusRequester)
@@ -316,7 +320,7 @@ fun EpgSourceTextField(
keyboardController?.hide()
}
},
- keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
+ keyboardOptions = KeyboardOptions(keyboardType = keyboardType, imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = { dismissInput() }),
readOnly = isTelevisionDevice && !acceptsInput
)
diff --git a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsUiStateModel.kt b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsUiStateModel.kt
index bfaee1a9..95bb3ad0 100644
--- a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsUiStateModel.kt
+++ b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsUiStateModel.kt
@@ -11,6 +11,7 @@ import com.streamvault.domain.manager.DriveAuthState
import com.streamvault.domain.manager.DriveBackupSnapshot
import com.streamvault.domain.manager.DriveSignInRequest
import com.streamvault.domain.manager.DriveSyncStatus
+import com.streamvault.domain.manager.OpenSubtitlesAccount
import com.streamvault.domain.manager.ProviderCredentials
import com.streamvault.domain.model.ActiveLiveSource
import com.streamvault.domain.model.VodCategoryLoadMode
@@ -113,6 +114,9 @@ data class SettingsUiState(
val subtitleBackgroundColor: Int = 0x80000000.toInt(),
val playerLiveTranslationEnabled: Boolean = false,
val playerLiveTranslationEndpoint: String = "http://10.0.2.2:8765",
+ val openSubtitlesAccount: OpenSubtitlesAccount? = null,
+ val isOpenSubtitlesBusy: Boolean = false,
+ val openSubtitlesError: String? = null,
val wifiMaxVideoHeight: Int? = null,
val ethernetMaxVideoHeight: Int? = null,
val playerTimeshiftEnabled: Boolean = false,
diff --git a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsViewModel.kt b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsViewModel.kt
index bdbf73f3..828bddbb 100644
--- a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsViewModel.kt
+++ b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsViewModel.kt
@@ -24,6 +24,7 @@ import com.streamvault.domain.manager.BackupPreview
import com.streamvault.domain.manager.BackupRestoreStatusStore
import com.streamvault.domain.manager.DriveBackupSyncManager
import com.streamvault.domain.manager.ParentalControlManager
+import com.streamvault.domain.manager.OpenSubtitlesAccountManager
import com.streamvault.domain.manager.RecordingManager
import com.streamvault.domain.model.Category
import com.streamvault.domain.model.AppHomeDashboardShelf
@@ -116,7 +117,8 @@ class SettingsViewModel @Inject constructor(
private val epgSourceRepository: com.streamvault.domain.repository.EpgSourceRepository,
private val appUpdatePort: SettingsAppUpdatePort,
private val getCustomCategories: GetCustomCategories,
- private val audioCompatibilityMemoryStore: AudioCompatibilityMemoryStore
+ private val audioCompatibilityMemoryStore: AudioCompatibilityMemoryStore,
+ private val openSubtitlesAccountManager: OpenSubtitlesAccountManager,
) : ViewModel() {
private val appContext = application
private val exportBackup = ExportBackup(backupManager)
@@ -187,6 +189,11 @@ class SettingsViewModel @Inject constructor(
init {
refreshCrashReport()
+ viewModelScope.launch {
+ openSubtitlesAccountManager.account.collect { account ->
+ _uiState.update { it.copy(openSubtitlesAccount = account) }
+ }
+ }
registerPreferenceObservers()
registerXtreamIndexJobObserver()
registerXtreamLiveOnboardingObserver()
@@ -819,6 +826,34 @@ class SettingsViewModel @Inject constructor(
}
}
+ fun signInToOpenSubtitles(username: String, password: String) {
+ viewModelScope.launch {
+ _uiState.update { it.copy(isOpenSubtitlesBusy = true, openSubtitlesError = null) }
+ val result = openSubtitlesAccountManager.signIn(username, password)
+ _uiState.update { state ->
+ state.copy(
+ isOpenSubtitlesBusy = false,
+ openSubtitlesAccount = result.getOrNull() ?: state.openSubtitlesAccount,
+ openSubtitlesError = result.errorMessageOrNull(),
+ )
+ }
+ }
+ }
+
+ fun signOutOfOpenSubtitles() {
+ viewModelScope.launch {
+ _uiState.update { it.copy(isOpenSubtitlesBusy = true, openSubtitlesError = null) }
+ val result = openSubtitlesAccountManager.signOut()
+ _uiState.update { state ->
+ state.copy(
+ isOpenSubtitlesBusy = false,
+ openSubtitlesAccount = if (result.isSuccess) null else state.openSubtitlesAccount,
+ openSubtitlesError = result.errorMessageOrNull(),
+ )
+ }
+ }
+ }
+
fun setPlayerTimeshiftDepthMinutes(minutes: Int) {
viewModelScope.launch {
preferencesRepository.setPlayerTimeshiftDepthMinutes(minutes)
diff --git a/feature/settings/src/main/res/values/strings.xml b/feature/settings/src/main/res/values/strings.xml
index 81ed71b1..cc8217d4 100644
--- a/feature/settings/src/main/res/values/strings.xml
+++ b/feature/settings/src/main/res/values/strings.xml
@@ -721,5 +721,23 @@
<string name="settings_drive_manage_subtitle">Delete only snapshots you no longer need.</string>
<string name="settings_drive_manage_title">Saved Drive backups</string>
<string name="settings_providers_subtitle">Switch, sync, edit, and troubleshoot your IPTV sources.</string>
+ <string name="settings_opensubtitles_title">OpenSubtitles</string>
+ <string name="settings_opensubtitles_description">Use your OpenSubtitles account to find subtitles while watching movies and series. Downloads count toward your account’s daily allowance.</string>
+ <string name="settings_opensubtitles_connect">Connect OpenSubtitles account</string>
+ <string name="settings_opensubtitles_signed_out">Not connected</string>
+ <string name="settings_opensubtitles_sign_in_title">Connect OpenSubtitles</string>
+ <string name="settings_opensubtitles_sign_in_subtitle">Sign in with your OpenSubtitles.com account. Your password is stored encrypted on this device.</string>
+ <string name="settings_opensubtitles_username">Username</string>
+ <string name="settings_opensubtitles_password">Password</string>
+ <string name="settings_opensubtitles_sign_in">Sign in</string>
+ <string name="settings_opensubtitles_signing_in">Signing in…</string>
+ <string name="settings_opensubtitles_sign_out">Sign out</string>
+ <string name="settings_opensubtitles_sign_out_title">Sign out of OpenSubtitles?</string>
+ <string name="settings_opensubtitles_sign_out_subtitle">Saved OpenSubtitles credentials will be removed from this device.</string>
+ <string name="settings_opensubtitles_remaining">%1$d downloads remaining today</string>
+ <string name="settings_opensubtitles_remaining_one">1 download remaining today</string>
+ <string name="settings_opensubtitles_daily_allowance">%1$d downloads per day</string>
+ <string name="settings_opensubtitles_quota_unknown">Daily allowance is managed by OpenSubtitles.</string>
+ <string name="settings_opensubtitles_signing_out">Signing out…</string>
<string name="settings_title">Settings</string>
</resources>