Yokan / rebuild
Course 1 8624561

TrackerLogin.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/TrackerLogin.kt

implementation179 lines
1package eu.friedcutlet.yokan.services.tracking23import eu.friedcutlet.yokan.database.DbTrackPreference4import eu.friedcutlet.yokan.database.YokanDatabase5import eu.friedcutlet.yokan.services.http.HttpRequest6import eu.friedcutlet.yokan.services.http.HttpResponse7import eu.friedcutlet.yokan.services.http.HttpService8import eu.friedcutlet.yokan.util.nowMillis9import io.ktor.http.decodeURLQueryComponent10import io.ktor.http.encodeURLParameter11import kotlinx.serialization.Serializable12import kotlinx.serialization.json.Json13import kotlinx.serialization.json.JsonElement14import kotlinx.serialization.json.JsonObject15import kotlinx.serialization.json.JsonPrimitive16import kotlinx.serialization.json.contentOrNull17import kotlinx.serialization.json.longOrNull1819/** A credential the connect dialog asks for; adapters list theirs in [TrackerService.loginFields]. */20enum class TrackerLoginField(val label: String, val secret: Boolean = false) {21    ServerUrl("Server URL"),22    Username("Username"),23    Password("Password", secret = true),24    ApiKey("API key / access token", secret = true),25    ClientId("OAuth client ID"),26    ClientSecret("OAuth client secret", secret = true),27    /** The code the provider shows, or the whole callback URL copied from the browser. */28    AuthorizationCode("Authorization code or callback URL", secret = true),29}3031/**32 * User-owned tracker configuration stored as JSON in [DbTrackPreference.prefs]; the access token or33 * session itself lives in [DbTrackPreference.oauth]. Exported only with sensitive backups.34 */35@Serializable36data class TrackerCredentials(37    val serverUrl: String? = null,38    val clientId: String? = null,39    val clientSecret: String? = null,40    val refreshToken: String? = null,41    /** Epoch milliseconds; null when the provider gives no expiry. */42    val expiresAt: Long? = null,43    val userId: String? = null,44    val apiKey: String? = null,45)4647internal val trackerJson = Json { ignoreUnknownKeys = true; isLenient = true; explicitNulls = false }4849fun DbTrackPreference.credentials(): TrackerCredentials =50    prefs?.takeIf { it.isNotBlank() }?.let { runCatching { trackerJson.decodeFromString(TrackerCredentials.serializer(), it) }.getOrNull() }51        ?: TrackerCredentials()5253fun TrackerCredentials.encode(): String = trackerJson.encodeToString(TrackerCredentials.serializer(), this)5455/** The stored sign-in of tracker [syncId], or null when it was never connected. */56fun YokanDatabase.trackPreference(syncId: Int): DbTrackPreference? =57    trackPreferences().firstOrNull { it.syncId?.toInt() == syncId }5859/** `id:12345` (case-insensitive prefix) → `12345`; null for a free-text query. */60fun trackerSearchId(query: String): String? =61    query.trim().takeIf { it.startsWith("id:", ignoreCase = true) }?.substring(3)?.trim()?.takeIf { it.isNotEmpty() }6263/** [raw] is either a bare value or a pasted callback URL carrying `name=value`. */64fun callbackParameter(raw: String, name: String): String {65    val value = raw.trim()66    if (!value.contains("$name=")) return value67    return value.substringAfter('?', value).replace('#', '&').split('&')68        .firstOrNull { it.startsWith("$name=") }?.substringAfter('=')69        ?.let { runCatching { it.decodeURLQueryComponent(plusIsSpace = true) }.getOrDefault(it) } ?: value70}7172/** Required non-blank login value, or a user-readable failure. */73fun Map<TrackerLoginField, String>.required(field: TrackerLoginField): String =74    this[field]?.trim()?.takeIf { it.isNotEmpty() } ?: throw IllegalArgumentException("${field.label} is required")7576fun Map<TrackerLoginField, String>.optional(field: TrackerLoginField): String? =77    this[field]?.trim()?.takeIf { it.isNotEmpty() }7879/** A non-2xx tracker response; [status] 401/403 means the stored credentials were rejected. */80class TrackerHttpException(val tracker: String, val status: Int, body: String) :81    Exception("$tracker returned HTTP $status${body.trim().take(200).takeIf { it.isNotEmpty() }?.let { ": $it" }.orEmpty()}") {82    val unauthorized: Boolean get() = status == 401 || status == 40383}8485fun HttpResponse.requireSuccess(tracker: String): HttpResponse =86    if (statusCode in 200..299) this else throw TrackerHttpException(tracker, statusCode, body)8788fun HttpResponse.json(tracker: String): JsonElement = trackerJson.parseToJsonElement(requireSuccess(tracker).body)8990/** `application/x-www-form-urlencoded` body. */91fun formBody(vararg fields: Pair<String, String>): String =92    fields.joinToString("&") { (k, v) -> "${k.encodeURLParameter()}=${v.encodeURLParameter()}" }9394/** OAuth token response expiry in epoch millis (one minute early), or null without `expires_in`. */95internal fun JsonObject.oauthExpiresAt(): Long? =96    (this["expires_in"] as? JsonPrimitive)?.longOrNull?.let { nowMillis() + (it - 60) * 1000 }9798/**99 * Bearer-token calls for a tracker signed in with the user's own OAuth application, whose client id/secret and100 * refresh token live in [TrackerCredentials]. [refreshFields] are extra form fields the provider's refresh grant101 * needs (Bangumi's `redirect_uri`).102 */103internal class TrackerOAuthClient(104    private val tracker: String,105    private val syncId: Int,106    private val tokenUrl: String,107    private val database: YokanDatabase,108    private val http: HttpService,109    private val refreshFields: List<Pair<String, String>> = emptyList(),110) {111    /** Form POST to the token endpoint; returns the token response. */112    suspend fun tokenRequest(vararg fields: Pair<String, String>): JsonObject = http.request(113        HttpRequest(114            url = tokenUrl,115            method = "POST",116            headers = mapOf("User-Agent" to UserAgent, "Content-Type" to "application/x-www-form-urlencoded"),117            body = formBody(*fields),118        ),119    ).json(tracker) as JsonObject120121    /** Authorized call; a login with a refresh token refreshes an expired token up front, or once after a 401. */122    suspend fun api(method: String, url: String, body: String? = null): HttpResponse {123        val pref = database.trackPreference(syncId)124        val token = pref?.oauth?.takeIf { it.isNotBlank() } ?: throw IllegalStateException("Not logged in to $tracker")125        val credentials = pref.credentials()126        val canRefresh = credentials.refreshToken != null127        val expiresAt = credentials.expiresAt128        if (canRefresh && expiresAt != null && nowMillis() >= expiresAt) return send(method, url, refresh(pref), body)129        val response = send(method, url, token, body)130        if (response.statusCode != 401 || !canRefresh) return response131        return send(method, url, refresh(pref), body)132    }133134    suspend fun send(method: String, url: String, token: String, body: String? = null): HttpResponse =135        http.request(136            HttpRequest(137                url = url,138                method = method,139                headers = mapOf("User-Agent" to UserAgent, "Authorization" to "Bearer $token"),140                body = body,141            ),142        )143144    /** Exchanges the stored refresh token, stores the new token and returns it. */145    private suspend fun refresh(pref: DbTrackPreference): String {146        val credentials = pref.credentials()147        val response = tokenRequest(148            "grant_type" to "refresh_token",149            "client_id" to credentials.clientId.orEmpty(),150            "client_secret" to credentials.clientSecret.orEmpty(),151            "refresh_token" to credentials.refreshToken.orEmpty(),152            *refreshFields.toTypedArray(),153        )154        val token = response.string("access_token") ?: throw TrackerHttpException(tracker, 401, "No access token")155        database.upsertTrackPreference(156            pref.copy(157                oauth = token,158                prefs = credentials.copy(159                    refreshToken = response.string("refresh_token") ?: credentials.refreshToken,160                    expiresAt = response.oauthExpiresAt(),161                ).encode(),162            ),163        )164        return token165    }166167    private fun JsonObject.string(key: String): String? = (this[key] as? JsonPrimitive)?.contentOrNull168169    private companion object {170        const val UserAgent = "Yokan"171    }172}173174/** Trailing-slash-free server origin a user typed, with `https://` assumed when no scheme is given. */175fun normalizeServerUrl(raw: String): String {176    val trimmed = raw.trim().trimEnd('/')177    require(trimmed.isNotEmpty()) { "Server URL is required" }178    return if ("://" in trimmed) trimmed else "https://$trimmed"179}180

Search chapters, reference and source filenames.