Skip to content

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

feat: integrate OpenSubtitles API for subtitle search and download functionality

David Nashash8f9c58cd52fb
diff --git a/.gitignore b/.gitignore
index c2b98ee0..e3a3c170 100644
--- a/.gitignore
+++ b/.gitignore
@@ -69,6 +69,7 @@ releases/*.apk
# AI tooling
.claude/
.opencode/
+docs/superpowers/
# Dev handoff notes
docs/*-handoff.md
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 b1588fd1..9c771431 100644
--- a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt
+++ b/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt
@@ -97,6 +97,9 @@ abstract class RepositoryModule {
@Binds @Singleton
abstract fun bindExternalRatingsRepository(impl: ExternalRatingsRepositoryImpl): ExternalRatingsRepository
+ @Binds @Singleton
+ abstract fun bindExternalSubtitleRepository(impl: OpenSubtitlesRepositoryImpl): ExternalSubtitleRepository
+
@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
new file mode 100644
index 00000000..1ffcd91a
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/remote/subtitle/OpenSubtitlesApi.kt
@@ -0,0 +1,232 @@
+package com.streamvault.data.remote.subtitle
+
+import com.google.gson.Gson
+import com.streamvault.data.remote.http.useCancellableResponse
+import com.streamvault.domain.model.Result
+import java.io.File
+import java.net.URLEncoder
+import java.util.concurrent.TimeUnit
+import javax.inject.Inject
+import javax.inject.Singleton
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.RequestBody.Companion.toRequestBody
+
+internal const val OPENSUBTITLES_DEFAULT_BASE_URL = "https://api.opensubtitles.com/api/v1"
+internal const val OPENSUBTITLES_DEFAULT_BASE_HOST = "api.opensubtitles.com"
+
+@Singleton
+class OpenSubtitlesApi @Inject constructor(
+ private val okHttpClient: OkHttpClient,
+ private val gson: Gson,
+) {
+ data class DownloadLink(
+ val url: String,
+ val fileName: String,
+ val remaining: Int,
+ )
+
+ data class SearchQuery(
+ val query: String? = null,
+ val tmdbId: Long? = null,
+ val imdbId: Long? = null,
+ val parentTmdbId: Long? = null,
+ val parentImdbId: Long? = null,
+ val seasonNumber: Int? = null,
+ val episodeNumber: Int? = null,
+ val languages: String? = null,
+ val orderBy: String? = null,
+ ) {
+ fun toQueryParams(): Map<String, String> = buildMap {
+ query?.takeIf { it.isNotBlank() }?.let { put("query", it) }
+ tmdbId?.takeIf { it > 0 }?.let { put("tmdb_id", it.toString()) }
+ imdbId?.takeIf { it > 0 }?.let { put("imdb_id", it.toString()) }
+ parentTmdbId?.takeIf { it > 0 }?.let { put("parent_tmdb_id", it.toString()) }
+ parentImdbId?.takeIf { it > 0 }?.let { put("parent_imdb_id", it.toString()) }
+ seasonNumber?.takeIf { it > 0 }?.let { put("season_number", it.toString()) }
+ episodeNumber?.takeIf { it > 0 }?.let { put("episode_number", it.toString()) }
+ languages?.takeIf { it.isNotBlank() }?.let { put("languages", it) }
+ orderBy?.takeIf { it.isNotBlank() }?.let { put("order_by", it) }
+ }
+ }
+
+ suspend fun login(username: String, password: String): Result<OpenSubtitlesSession> = try {
+ val session = withContext(Dispatchers.IO) { loginSession(username, password) }
+ Result.success(session)
+ } catch (e: Exception) {
+ if (e is CancellationException) throw e
+ Result.error("OpenSubtitles login failed: ${e.message}", e)
+ }
+
+ suspend fun logout(token: String): Result<Unit> = try {
+ withContext(Dispatchers.IO) {
+ val request = Request.Builder()
+ .url("$OPENSUBTITLES_DEFAULT_BASE_URL/logout")
+ .header("Accept", "application/json")
+ .header("Api-Key", API_KEY)
+ .header("Authorization", "Bearer $token")
+ .header("User-Agent", USER_AGENT)
+ .delete()
+ .build()
+ execute(request, "OpenSubtitles logout")
+ }
+ Result.success(Unit)
+ } catch (e: Exception) {
+ if (e is CancellationException) throw e
+ Result.error("OpenSubtitles logout failed: ${e.message}", e)
+ }
+
+ suspend fun search(
+ query: SearchQuery,
+ token: String,
+ baseUrlHost: String,
+ ): Result<List<OpenSubtitlesSubtitleDto>> = try {
+ val subtitles = withContext(Dispatchers.IO) {
+ val request = Request.Builder()
+ .url(buildUrl(baseUrlHost, "/subtitles", query.toQueryParams()))
+ .header("Accept", "application/json")
+ .header("Api-Key", API_KEY)
+ .header("Authorization", "Bearer $token")
+ .header("User-Agent", USER_AGENT)
+ .get()
+ .build()
+ val body = execute(request, "OpenSubtitles search")
+ gson.fromJson(body, OpenSubtitlesSearchResponseDto::class.java).data.orEmpty()
+ }
+ Result.success(subtitles)
+ } catch (e: Exception) {
+ if (e is CancellationException) throw e
+ Result.error("OpenSubtitles search failed: ${e.message}", e)
+ }
+
+ suspend fun downloadLink(
+ fileId: Long,
+ token: String,
+ baseUrlHost: String,
+ subFormat: String = "srt",
+ ): Result<DownloadLink> = try {
+ val link = withContext(Dispatchers.IO) {
+ val payload = gson.toJson(OpenSubtitlesDownloadRequestDto(fileId = fileId, subFormat = subFormat))
+ val request = Request.Builder()
+ .url(buildUrl(baseUrlHost, "/download", emptyMap()))
+ .header("Accept", "application/json")
+ .header("Content-Type", "application/json")
+ .header("Api-Key", API_KEY)
+ .header("Authorization", "Bearer $token")
+ .header("User-Agent", USER_AGENT)
+ .post(payload.toRequestBody("application/json".toMediaType()))
+ .build()
+ val body = execute(request, "OpenSubtitles download")
+ val response = gson.fromJson(body, OpenSubtitlesDownloadResponseDto::class.java)
+ val url = response.link?.takeIf { it.isNotBlank() }
+ ?: throw OpenSubtitlesApiException("OpenSubtitles download returned no link")
+ DownloadLink(
+ url = url,
+ fileName = response.fileName.orEmpty(),
+ remaining = response.remaining ?: 0,
+ )
+ }
+ Result.success(link)
+ } catch (e: Exception) {
+ if (e is CancellationException) throw e
+ Result.error("OpenSubtitles download failed: ${e.message}", e)
+ }
+
+ 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,
+ )
+ }
+ 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) }
+ }
+ }
+ destination
+ }
+ Result.success(file)
+ } catch (e: Exception) {
+ if (e is CancellationException) throw e
+ Result.error("OpenSubtitles subtitle file download failed: ${e.message}", e)
+ }
+
+ private suspend fun loginSession(username: String, password: String): OpenSubtitlesSession {
+ val payload = gson.toJson(OpenSubtitlesLoginRequestDto(username = username, password = password))
+ val request = Request.Builder()
+ .url("$OPENSUBTITLES_DEFAULT_BASE_URL/login")
+ .header("Accept", "application/json")
+ .header("Content-Type", "application/json")
+ .header("Api-Key", API_KEY)
+ .header("User-Agent", USER_AGENT)
+ .post(payload.toRequestBody("application/json".toMediaType()))
+ .build()
+ val body = execute(request, "OpenSubtitles login")
+ val response = gson.fromJson(body, OpenSubtitlesLoginResponseDto::class.java)
+ val token = response.token?.takeIf { it.isNotBlank() }
+ ?: throw OpenSubtitlesApiException("OpenSubtitles login did not return a token")
+ return OpenSubtitlesSession(
+ token = token,
+ baseUrl = response.baseUrl?.takeIf { it.isNotBlank() } ?: OPENSUBTITLES_DEFAULT_BASE_HOST,
+ username = username,
+ allowedDownloads = response.user?.allowedDownloads ?: 0,
+ level = response.user?.level,
+ vip = response.user?.vip == true,
+ )
+ }
+
+ private suspend fun execute(request: Request, errorPrefix: String): String {
+ return okHttpClient.newBuilder()
+ .callTimeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
+ .build()
+ .newCall(request)
+ .useCancellableResponse { response ->
+ if (!response.isSuccessful) {
+ throw OpenSubtitlesApiException(
+ message = "$errorPrefix failed with HTTP ${response.code}",
+ statusCode = response.code,
+ isUnauthorized = response.code == 401,
+ isRateLimited = response.code == 429,
+ )
+ }
+ response.body?.string().orEmpty()
+ }
+ }
+
+ private fun buildUrl(baseUrlHost: String, path: String, query: Map<String, String>): String {
+ val normalized = baseUrlHost.trimEnd('/')
+ val host = if (normalized.startsWith("http://") || normalized.startsWith("https://")) {
+ normalized
+ } else {
+ "https://$normalized"
+ }
+ val qs = query.entries.joinToString("&") { (k, v) -> "${enc(k)}=${enc(v)}" }
+ return "$host/api/v1$path${if (qs.isNotBlank()) "?$qs" else ""}"
+ }
+
+ private fun enc(value: String): String = URLEncoder.encode(value, Charsets.UTF_8.name())
+
+ private companion object {
+ const val API_KEY = "STREAMVAULT_OPENSUBTITLES_API_KEY"
+ const val USER_AGENT = "StreamVault v1"
+ const val REQUEST_TIMEOUT_SECONDS = 30L
+ }
+}
diff --git a/data/src/main/java/com/streamvault/data/remote/subtitle/OpenSubtitlesApiException.kt b/data/src/main/java/com/streamvault/data/remote/subtitle/OpenSubtitlesApiException.kt
new file mode 100644
index 00000000..3220a32c
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/remote/subtitle/OpenSubtitlesApiException.kt
@@ -0,0 +1,11 @@
+package com.streamvault.data.remote.subtitle
+
+import java.io.IOException
+
+class OpenSubtitlesApiException(
+ message: String,
+ val statusCode: Int? = null,
+ val isUnauthorized: Boolean = false,
+ val isRateLimited: Boolean = false,
+ cause: Throwable? = null
+) : IOException(message, cause)
diff --git a/data/src/main/java/com/streamvault/data/remote/subtitle/OpenSubtitlesDtos.kt b/data/src/main/java/com/streamvault/data/remote/subtitle/OpenSubtitlesDtos.kt
new file mode 100644
index 00000000..e7e6cf91
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/remote/subtitle/OpenSubtitlesDtos.kt
@@ -0,0 +1,78 @@
+package com.streamvault.data.remote.subtitle
+
+import com.google.gson.annotations.SerializedName
+
+data class OpenSubtitlesLoginRequestDto(
+ @SerializedName("username") val username: String,
+ @SerializedName("password") val password: String,
+)
+
+data class OpenSubtitlesLoginResponseDto(
+ @SerializedName("token") val token: String? = null,
+ @SerializedName("base_url") val baseUrl: String? = null,
+ @SerializedName("status") val status: Int? = null,
+ @SerializedName("user") val user: OpenSubtitlesUserDto? = null,
+)
+
+data class OpenSubtitlesUserDto(
+ @SerializedName("allowed_downloads") val allowedDownloads: Int? = null,
+ @SerializedName("level") val level: String? = null,
+ @SerializedName("user_id") val userId: Long? = null,
+ @SerializedName("vip") val vip: Boolean? = null,
+)
+
+data class OpenSubtitlesDownloadRequestDto(
+ @SerializedName("file_id") val fileId: Long,
+ @SerializedName("sub_format") val subFormat: String? = null,
+ @SerializedName("file_name") val fileName: String? = null,
+)
+
+data class OpenSubtitlesDownloadResponseDto(
+ @SerializedName("link") val link: String? = null,
+ @SerializedName("file_name") val fileName: String? = null,
+ @SerializedName("requests") val requests: Int? = null,
+ @SerializedName("remaining") val remaining: Int? = null,
+ @SerializedName("message") val message: String? = null,
+ @SerializedName("reset_time") val resetTime: String? = null,
+ @SerializedName("reset_time_utc") val resetTimeUtc: String? = null,
+)
+
+data class OpenSubtitlesSearchResponseDto(
+ @SerializedName("total_pages") val totalPages: Int? = null,
+ @SerializedName("total_count") val totalCount: Int? = null,
+ @SerializedName("page") val page: Int? = null,
+ @SerializedName("data") val data: List<OpenSubtitlesSubtitleDto>? = emptyList(),
+)
+
+data class OpenSubtitlesSubtitleDto(
+ @SerializedName("id") val id: String? = null,
+ @SerializedName("type") val type: String? = null,
+ @SerializedName("attributes") val attributes: OpenSubtitlesSubtitleAttributesDto? = null,
+)
+
+data class OpenSubtitlesSubtitleAttributesDto(
+ @SerializedName("subtitle_id") val subtitleId: String? = null,
+ @SerializedName("language") val language: String? = null,
+ @SerializedName("language_name") val languageName: String? = null,
+ @SerializedName("release") val release: String? = null,
+ @SerializedName("download_count") val downloadCount: Long? = null,
+ @SerializedName("feature_details") val featureDetails: OpenSubtitlesFeatureDetailsDto? = null,
+ @SerializedName("files") val files: List<OpenSubtitlesFileDto>? = emptyList(),
+)
+
+data class OpenSubtitlesFeatureDetailsDto(
+ @SerializedName("title") val title: String? = null,
+ @SerializedName("year") val year: Int? = null,
+ @SerializedName("imdb_id") val imdbId: Long? = null,
+ @SerializedName("tmdb_id") val tmdbId: Long? = null,
+ @SerializedName("parent_imdb_id") val parentImdbId: Long? = null,
+ @SerializedName("parent_tmdb_id") val parentTmdbId: Long? = null,
+ @SerializedName("season_number") val seasonNumber: Int? = null,
+ @SerializedName("episode_number") val episodeNumber: Int? = null,
+)
+
+data class OpenSubtitlesFileDto(
+ @SerializedName("file_id") val fileId: Long? = null,
+ @SerializedName("file_name") val fileName: String? = null,
+ @SerializedName("cd_number") val cdNumber: Int? = null,
+)
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
new file mode 100644
index 00000000..589c2709
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/remote/subtitle/OpenSubtitlesSessionStore.kt
@@ -0,0 +1,135 @@
+package com.streamvault.data.remote.subtitle
+
+import android.content.Context
+import androidx.datastore.core.DataStore
+import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler
+import androidx.datastore.preferences.core.Preferences
+import androidx.datastore.preferences.core.PreferenceDataStoreFactory
+import androidx.datastore.preferences.core.booleanPreferencesKey
+import androidx.datastore.preferences.core.edit
+import androidx.datastore.preferences.core.emptyPreferences
+import androidx.datastore.preferences.core.intPreferencesKey
+import androidx.datastore.preferences.core.stringPreferencesKey
+import androidx.datastore.preferences.preferencesDataStoreFile
+import com.streamvault.data.security.CredentialCrypto
+import dagger.hilt.android.qualifiers.ApplicationContext
+import javax.inject.Inject
+import javax.inject.Singleton
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.map
+
+data class OpenSubtitlesSession(
+ val token: String,
+ val baseUrl: String,
+ val username: String,
+ val allowedDownloads: Int,
+ val level: String?,
+ val vip: Boolean,
+)
+
+data class OpenSubtitlesCredentials(
+ val username: String,
+ val password: String,
+)
+
+@Singleton
+class OpenSubtitlesSessionStore @Inject constructor(
+ @ApplicationContext private val context: Context,
+ private val credentialCrypto: CredentialCrypto,
+) {
+ private val dataStore: DataStore<Preferences> by lazy {
+ PreferenceDataStoreFactory.create(
+ corruptionHandler = ReplaceFileCorruptionHandler { emptyPreferences() },
+ produceFile = { context.preferencesDataStoreFile(DATASTORE_NAME) }
+ )
+ }
+
+ 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 allowedDownloads = prefs[KEY_ALLOWED_DOWNLOADS] ?: 0
+ 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)
+ }
+
+ 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()
+ if (token.isNullOrBlank() || username.isBlank()) return null
+ return OpenSubtitlesSession(
+ token = token,
+ baseUrl = baseUrl,
+ username = username,
+ allowedDownloads = prefs[KEY_ALLOWED_DOWNLOADS] ?: 0,
+ level = prefs[KEY_LEVEL],
+ vip = prefs[KEY_VIP] ?: false,
+ )
+ }
+
+ suspend fun loadCredentials(): OpenSubtitlesCredentials? {
+ val prefs = dataStore.data.first()
+ val username = prefs[KEY_USERNAME].orEmpty()
+ val password = prefs[KEY_PASSWORD]
+ ?.let { runCatching { credentialCrypto.decryptIfNeeded(it) }.getOrNull() }
+ .orEmpty()
+ if (username.isBlank() || password.isBlank()) return null
+ return OpenSubtitlesCredentials(username, password)
+ }
+
+ suspend fun saveSession(session: OpenSubtitlesSession) {
+ dataStore.edit { prefs ->
+ prefs[KEY_TOKEN] = credentialCrypto.encryptIfNeeded(session.token)
+ prefs[KEY_BASE_URL] = session.baseUrl
+ prefs[KEY_USERNAME] = session.username
+ prefs[KEY_ALLOWED_DOWNLOADS] = session.allowedDownloads
+ session.level?.takeIf { it.isNotBlank() }?.let { prefs[KEY_LEVEL] = it }
+ prefs[KEY_VIP] = session.vip
+ }
+ }
+
+ suspend fun saveCredentials(credentials: OpenSubtitlesCredentials) {
+ dataStore.edit { prefs ->
+ prefs[KEY_USERNAME] = credentials.username
+ prefs[KEY_PASSWORD] = credentialCrypto.encryptIfNeeded(credentials.password)
+ }
+ }
+
+ suspend fun clearSession() {
+ dataStore.edit { prefs ->
+ prefs.remove(KEY_TOKEN)
+ prefs.remove(KEY_BASE_URL)
+ prefs.remove(KEY_ALLOWED_DOWNLOADS)
+ prefs.remove(KEY_LEVEL)
+ prefs.remove(KEY_VIP)
+ }
+ }
+
+ suspend fun clearAll() {
+ dataStore.edit { prefs ->
+ prefs.remove(KEY_TOKEN)
+ prefs.remove(KEY_BASE_URL)
+ prefs.remove(KEY_USERNAME)
+ prefs.remove(KEY_PASSWORD)
+ prefs.remove(KEY_ALLOWED_DOWNLOADS)
+ prefs.remove(KEY_LEVEL)
+ prefs.remove(KEY_VIP)
+ }
+ }
+
+ private companion object {
+ const val DATASTORE_NAME = "opensubtitles_session"
+ val KEY_TOKEN = stringPreferencesKey("token")
+ val KEY_BASE_URL = stringPreferencesKey("base_url")
+ val KEY_USERNAME = stringPreferencesKey("username")
+ val KEY_PASSWORD = stringPreferencesKey("password")
+ val KEY_ALLOWED_DOWNLOADS = intPreferencesKey("allowed_downloads")
+ 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
new file mode 100644
index 00000000..04b35950
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/repository/OpenSubtitlesRepositoryImpl.kt
@@ -0,0 +1,191 @@
+package com.streamvault.data.repository
+
+import android.content.Context
+import com.streamvault.data.remote.subtitle.OpenSubtitlesApi
+import com.streamvault.data.remote.subtitle.OpenSubtitlesApiException
+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.model.ContentType
+import com.streamvault.domain.model.ExternalSubtitle
+import com.streamvault.domain.model.ExternalSubtitleSource
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.repository.ExternalSubtitleRepository
+import dagger.hilt.android.qualifiers.ApplicationContext
+import java.io.File
+import javax.inject.Inject
+import javax.inject.Singleton
+import kotlinx.coroutines.CancellationException
+
+@Singleton
+class OpenSubtitlesRepositoryImpl @Inject constructor(
+ @ApplicationContext private val context: Context,
+ private val api: OpenSubtitlesApi,
+ private val sessionStore: OpenSubtitlesSessionStore,
+) : ExternalSubtitleRepository {
+
+ override suspend fun search(
+ contentType: ContentType,
+ title: String,
+ year: Int?,
+ tmdbId: Long?,
+ parentTmdbId: Long?,
+ seasonNumber: Int?,
+ 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
+ }
+ } 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)
+ }
+ }
+ 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
+ }
+ } 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 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
+ }
+
+ 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()
+ return ExternalSubtitle(
+ id = dto.id.orEmpty(),
+ language = language,
+ displayLanguage = attributes?.languageName?.takeIf { it.isNotBlank() } ?: language,
+ releaseName = attributes?.release.orEmpty(),
+ source = ExternalSubtitleSource.OPENSUBTITLES,
+ downloadId = fileId,
+ )
+ }
+
+ 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 buildSearchQuery(
+ contentType: ContentType,
+ title: String,
+ year: Int?,
+ tmdbId: Long?,
+ parentTmdbId: Long?,
+ seasonNumber: Int?,
+ episodeNumber: Int?,
+ language: String,
+ ): OpenSubtitlesApi.SearchQuery {
+ val languageCode = language.trim().lowercase().takeIf { it.isNotBlank() }
+ return when (contentType) {
+ ContentType.MOVIE -> OpenSubtitlesApi.SearchQuery(
+ query = buildTitleQuery(title, year),
+ tmdbId = tmdbId?.takeIf { it > 0 },
+ languages = languageCode,
+ orderBy = "download_count",
+ )
+ ContentType.SERIES -> OpenSubtitlesApi.SearchQuery(
+ query = title.trim().takeIf { it.isNotBlank() },
+ tmdbId = tmdbId?.takeIf { it > 0 },
+ languages = languageCode,
+ orderBy = "download_count",
+ )
+ ContentType.SERIES_EPISODE -> OpenSubtitlesApi.SearchQuery(
+ query = buildEpisodeQuery(title, seasonNumber, episodeNumber),
+ parentTmdbId = parentTmdbId?.takeIf { it > 0 },
+ seasonNumber = seasonNumber,
+ episodeNumber = episodeNumber,
+ languages = languageCode,
+ orderBy = "download_count",
+ )
+ else -> OpenSubtitlesApi.SearchQuery(
+ query = title.trim().takeIf { it.isNotBlank() },
+ languages = languageCode,
+ orderBy = "download_count",
+ )
+ }
+ }
+
+ private fun buildTitleQuery(title: String, year: Int?): String? {
+ val normalized = title.trim()
+ if (normalized.isBlank()) return null
+ return if (year != null && year > 0) "$normalized $year" else normalized
+ }
+
+ private fun buildEpisodeQuery(title: String, seasonNumber: Int?, episodeNumber: Int?): String? {
+ val normalized = title.trim()
+ if (normalized.isBlank()) return null
+ val season = seasonNumber?.takeIf { it > 0 }
+ val episode = episodeNumber?.takeIf { it > 0 }
+ return when {
+ season != null && episode != null ->
+ "$normalized S${season.toString().padStart(2, '0')}E${episode.toString().padStart(2, '0')}"
+ season != null -> "$normalized S${season.toString().padStart(2, '0')}"
+ else -> normalized
+ }
+ }
+
+ private fun Result<*>.isUnauthorized(): Boolean =
+ (this as? Result.Error)?.exception?.let { it is OpenSubtitlesApiException && it.isUnauthorized } == true
+
+ private companion object {
+ const val NOT_SIGNED_IN_MESSAGE =
+ "OpenSubtitles is not signed in. Add your OpenSubtitles.com account in Settings."
+ }
+}
diff --git a/domain/src/main/java/com/streamvault/domain/repository/ExternalSubtitleRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/ExternalSubtitleRepository.kt
index 6a9b1887..79a3d1e2 100644
--- a/domain/src/main/java/com/streamvault/domain/repository/ExternalSubtitleRepository.kt
+++ b/domain/src/main/java/com/streamvault/domain/repository/ExternalSubtitleRepository.kt
@@ -2,6 +2,7 @@ package com.streamvault.domain.repository
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.ExternalSubtitle
+import com.streamvault.domain.model.Result
import java.io.File
interface ExternalSubtitleRepository {
diff --git a/domain/src/main/java/com/streamvault/domain/usecase/SearchExternalSubtitles.kt b/domain/src/main/java/com/streamvault/domain/usecase/SearchExternalSubtitles.kt
index 5e122a15..7c1e1207 100644
--- a/domain/src/main/java/com/streamvault/domain/usecase/SearchExternalSubtitles.kt
+++ b/domain/src/main/java/com/streamvault/domain/usecase/SearchExternalSubtitles.kt
@@ -2,6 +2,7 @@ package com.streamvault.domain.usecase
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.ExternalSubtitle
+import com.streamvault.domain.model.Result
import com.streamvault.domain.repository.ExternalSubtitleRepository
import javax.inject.Inject