package eu.friedcutlet.yokan.services.tracking import eu.friedcutlet.yokan.database.DbTrackPreference import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpResponse import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.util.nowMillis import io.ktor.http.decodeURLQueryComponent import io.ktor.http.encodeURLParameter import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.longOrNull /** A credential the connect dialog asks for; adapters list theirs in [TrackerService.loginFields]. */ enum class TrackerLoginField(val label: String, val secret: Boolean = false) { ServerUrl("Server URL"), Username("Username"), Password("Password", secret = true), ApiKey("API key / access token", secret = true), ClientId("OAuth client ID"), ClientSecret("OAuth client secret", secret = true), /** The code the provider shows, or the whole callback URL copied from the browser. */ AuthorizationCode("Authorization code or callback URL", secret = true), } /** * User-owned tracker configuration stored as JSON in [DbTrackPreference.prefs]; the access token or * session itself lives in [DbTrackPreference.oauth]. Exported only with sensitive backups. */ @Serializable data class TrackerCredentials( val serverUrl: String? = null, val clientId: String? = null, val clientSecret: String? = null, val refreshToken: String? = null, /** Epoch milliseconds; null when the provider gives no expiry. */ val expiresAt: Long? = null, val userId: String? = null, val apiKey: String? = null, ) internal val trackerJson = Json { ignoreUnknownKeys = true; isLenient = true; explicitNulls = false } fun DbTrackPreference.credentials(): TrackerCredentials = prefs?.takeIf { it.isNotBlank() }?.let { runCatching { trackerJson.decodeFromString(TrackerCredentials.serializer(), it) }.getOrNull() } ?: TrackerCredentials() fun TrackerCredentials.encode(): String = trackerJson.encodeToString(TrackerCredentials.serializer(), this) /** The stored sign-in of tracker [syncId], or null when it was never connected. */ fun YokanDatabase.trackPreference(syncId: Int): DbTrackPreference? = trackPreferences().firstOrNull { it.syncId?.toInt() == syncId } /** `id:12345` (case-insensitive prefix) → `12345`; null for a free-text query. */ fun trackerSearchId(query: String): String? = query.trim().takeIf { it.startsWith("id:", ignoreCase = true) }?.substring(3)?.trim()?.takeIf { it.isNotEmpty() } /** [raw] is either a bare value or a pasted callback URL carrying `name=value`. */ fun callbackParameter(raw: String, name: String): String { val value = raw.trim() if (!value.contains("$name=")) return value return value.substringAfter('?', value).replace('#', '&').split('&') .firstOrNull { it.startsWith("$name=") }?.substringAfter('=') ?.let { runCatching { it.decodeURLQueryComponent(plusIsSpace = true) }.getOrDefault(it) } ?: value } /** Required non-blank login value, or a user-readable failure. */ fun Map.required(field: TrackerLoginField): String = this[field]?.trim()?.takeIf { it.isNotEmpty() } ?: throw IllegalArgumentException("${field.label} is required") fun Map.optional(field: TrackerLoginField): String? = this[field]?.trim()?.takeIf { it.isNotEmpty() } /** A non-2xx tracker response; [status] 401/403 means the stored credentials were rejected. */ class TrackerHttpException(val tracker: String, val status: Int, body: String) : Exception("$tracker returned HTTP $status${body.trim().take(200).takeIf { it.isNotEmpty() }?.let { ": $it" }.orEmpty()}") { val unauthorized: Boolean get() = status == 401 || status == 403 } fun HttpResponse.requireSuccess(tracker: String): HttpResponse = if (statusCode in 200..299) this else throw TrackerHttpException(tracker, statusCode, body) fun HttpResponse.json(tracker: String): JsonElement = trackerJson.parseToJsonElement(requireSuccess(tracker).body) /** `application/x-www-form-urlencoded` body. */ fun formBody(vararg fields: Pair): String = fields.joinToString("&") { (k, v) -> "${k.encodeURLParameter()}=${v.encodeURLParameter()}" } /** OAuth token response expiry in epoch millis (one minute early), or null without `expires_in`. */ internal fun JsonObject.oauthExpiresAt(): Long? = (this["expires_in"] as? JsonPrimitive)?.longOrNull?.let { nowMillis() + (it - 60) * 1000 } /** * Bearer-token calls for a tracker signed in with the user's own OAuth application, whose client id/secret and * refresh token live in [TrackerCredentials]. [refreshFields] are extra form fields the provider's refresh grant * needs (Bangumi's `redirect_uri`). */ internal class TrackerOAuthClient( private val tracker: String, private val syncId: Int, private val tokenUrl: String, private val database: YokanDatabase, private val http: HttpService, private val refreshFields: List> = emptyList(), ) { /** Form POST to the token endpoint; returns the token response. */ suspend fun tokenRequest(vararg fields: Pair): JsonObject = http.request( HttpRequest( url = tokenUrl, method = "POST", headers = mapOf("User-Agent" to UserAgent, "Content-Type" to "application/x-www-form-urlencoded"), body = formBody(*fields), ), ).json(tracker) as JsonObject /** Authorized call; a login with a refresh token refreshes an expired token up front, or once after a 401. */ suspend fun api(method: String, url: String, body: String? = null): HttpResponse { val pref = database.trackPreference(syncId) val token = pref?.oauth?.takeIf { it.isNotBlank() } ?: throw IllegalStateException("Not logged in to $tracker") val credentials = pref.credentials() val canRefresh = credentials.refreshToken != null val expiresAt = credentials.expiresAt if (canRefresh && expiresAt != null && nowMillis() >= expiresAt) return send(method, url, refresh(pref), body) val response = send(method, url, token, body) if (response.statusCode != 401 || !canRefresh) return response return send(method, url, refresh(pref), body) } suspend fun send(method: String, url: String, token: String, body: String? = null): HttpResponse = http.request( HttpRequest( url = url, method = method, headers = mapOf("User-Agent" to UserAgent, "Authorization" to "Bearer $token"), body = body, ), ) /** Exchanges the stored refresh token, stores the new token and returns it. */ private suspend fun refresh(pref: DbTrackPreference): String { val credentials = pref.credentials() val response = tokenRequest( "grant_type" to "refresh_token", "client_id" to credentials.clientId.orEmpty(), "client_secret" to credentials.clientSecret.orEmpty(), "refresh_token" to credentials.refreshToken.orEmpty(), *refreshFields.toTypedArray(), ) val token = response.string("access_token") ?: throw TrackerHttpException(tracker, 401, "No access token") database.upsertTrackPreference( pref.copy( oauth = token, prefs = credentials.copy( refreshToken = response.string("refresh_token") ?: credentials.refreshToken, expiresAt = response.oauthExpiresAt(), ).encode(), ), ) return token } private fun JsonObject.string(key: String): String? = (this[key] as? JsonPrimitive)?.contentOrNull private companion object { const val UserAgent = "Yokan" } } /** Trailing-slash-free server origin a user typed, with `https://` assumed when no scheme is given. */ fun normalizeServerUrl(raw: String): String { val trimmed = raw.trim().trimEnd('/') require(trimmed.isNotEmpty()) { "Server URL is required" } return if ("://" in trimmed) trimmed else "https://$trimmed" }