From fded0fd08d3d4999f9d60dd06f456a58feb530cb Mon Sep 17 00:00:00 2001 From: FooIbar <118464521+FooIbar@users.noreply.github.com> Date: Wed, 7 Aug 2024 12:06:36 +0800 Subject: [PATCH] Fix GitHub authorization and clean up code --- .../com/hippo/ehviewer/client/EhEngine.kt | 13 ++-- .../hippo/ehviewer/client/EhRequestBuilder.kt | 7 ++- .../hippo/ehviewer/client/EhTagDatabase.kt | 10 +-- .../com/hippo/ehviewer/updater/AppUpdater.kt | 13 ++-- .../com/hippo/ehviewer/util/ExceptionUtils.kt | 6 -- .../com/hippo/ehviewer/util/KtorExtensions.kt | 6 ++ .../ehviewer/util/StatusCodeException.kt | 62 ------------------- .../tachiyomi/data/release/GithubWorkflow.kt | 5 ++ app/src/main/res/values-de/strings.xml | 1 - app/src/main/res/values-es/strings.xml | 1 - app/src/main/res/values-fr/strings.xml | 1 - app/src/main/res/values-ja/strings.xml | 1 - app/src/main/res/values-ko/strings.xml | 1 - app/src/main/res/values-nb-rNO/strings.xml | 1 - app/src/main/res/values-th/strings.xml | 1 - app/src/main/res/values-tr/strings.xml | 1 - app/src/main/res/values-zh-rCN/strings.xml | 1 - app/src/main/res/values-zh-rHK/strings.xml | 1 - app/src/main/res/values-zh-rTW/strings.xml | 1 - app/src/main/res/values/strings.xml | 25 -------- 20 files changed, 33 insertions(+), 125 deletions(-) delete mode 100644 app/src/main/kotlin/com/hippo/ehviewer/util/StatusCodeException.kt diff --git a/app/src/main/kotlin/com/hippo/ehviewer/client/EhEngine.kt b/app/src/main/kotlin/com/hippo/ehviewer/client/EhEngine.kt index 8eb743fb5..83a3ab8e2 100644 --- a/app/src/main/kotlin/com/hippo/ehviewer/client/EhEngine.kt +++ b/app/src/main/kotlin/com/hippo/ehviewer/client/EhEngine.kt @@ -55,11 +55,12 @@ import com.hippo.ehviewer.dailycheck.showEventNotification import com.hippo.ehviewer.dailycheck.today import com.hippo.ehviewer.util.AppConfig import com.hippo.ehviewer.util.ReadableTime -import com.hippo.ehviewer.util.StatusCodeException import com.hippo.ehviewer.util.bodyAsUtf8Text +import com.hippo.ehviewer.util.ensureSuccess import eu.kanade.tachiyomi.util.system.logcat import io.ktor.client.statement.HttpStatement import io.ktor.client.statement.bodyAsChannel +import io.ktor.http.HttpStatusCode import io.ktor.utils.io.pool.DirectByteBufferPool import io.ktor.utils.io.pool.useInstance import java.io.File @@ -96,7 +97,7 @@ fun Either.saveParseError(e: Throwable) { } } -fun rethrowExactly(code: Int, body: Either, e: Throwable): Nothing { +fun rethrowExactly(status: HttpStatusCode, body: Either, e: Throwable): Nothing { // Don't translate coroutine cancellation if (e is CancellationException) throw e @@ -124,9 +125,7 @@ fun rethrowExactly(code: Int, body: Either, e: Throwable): N } // Check bad response code - if (code >= 400) { - throw StatusCodeException(code) - } + status.ensureSuccess() if (e is ParseException || e is SerializationException) { body.onLeft { if ("<" !in it) throw EhException(it) } @@ -151,7 +150,7 @@ suspend inline fun HttpStatement.fetchUsingAsText(crossinline block: suspend runSuspendCatching { block(body) }.onFailure { - rethrowExactly(response.status.value, body.left(), it) + rethrowExactly(response.status, body.left(), it) }.getOrThrow() } @@ -163,7 +162,7 @@ suspend inline fun HttpStatement.fetchUsingAsByteBuffer(crossinline block: s block(buffer) }.onFailure { buffer.rewind() - rethrowExactly(response.status.value, buffer.right(), it) + rethrowExactly(response.status, buffer.right(), it) }.getOrThrow() } } diff --git a/app/src/main/kotlin/com/hippo/ehviewer/client/EhRequestBuilder.kt b/app/src/main/kotlin/com/hippo/ehviewer/client/EhRequestBuilder.kt index 945336e45..40b583208 100644 --- a/app/src/main/kotlin/com/hippo/ehviewer/client/EhRequestBuilder.kt +++ b/app/src/main/kotlin/com/hippo/ehviewer/client/EhRequestBuilder.kt @@ -20,6 +20,7 @@ import com.hippo.ehviewer.EhApplication.Companion.ktorClient import com.hippo.ehviewer.EhApplication.Companion.noRedirectKtorClient import com.hippo.ehviewer.Settings import com.hippo.ehviewer.util.bodyAsUtf8Text +import com.hippo.ehviewer.util.ensureSuccess import eu.kanade.tachiyomi.util.system.logcat import io.ktor.client.request.HttpRequestBuilder import io.ktor.client.request.forms.FormDataContent @@ -45,7 +46,11 @@ import okio.BufferedSource inline fun JsonObjectBuilder.array(name: String, builder: JsonArrayBuilder.() -> Unit) = put(name, buildJsonArray(builder)) -suspend inline fun HttpStatement.executeAndParseAs() = executeSafely { it.bodyAsUtf8Text().parseAs() } +suspend inline fun HttpStatement.executeAndParseAs() = executeSafely { + it.status.ensureSuccess() + it.bodyAsUtf8Text().parseAs() +} + inline fun BufferedSource.parseAs(): T = json.decodeFromBufferedSource(this) inline fun String.parseAs(): T = json.decodeFromString(this) diff --git a/app/src/main/kotlin/com/hippo/ehviewer/client/EhTagDatabase.kt b/app/src/main/kotlin/com/hippo/ehviewer/client/EhTagDatabase.kt index a7067e322..6e331e2b3 100644 --- a/app/src/main/kotlin/com/hippo/ehviewer/client/EhTagDatabase.kt +++ b/app/src/main/kotlin/com/hippo/ehviewer/client/EhTagDatabase.kt @@ -24,14 +24,13 @@ import com.hippo.ehviewer.R import com.hippo.ehviewer.client.data.TagNamespace import com.hippo.ehviewer.util.AppConfig import com.hippo.ehviewer.util.FileUtils -import com.hippo.ehviewer.util.StatusCodeException import com.hippo.ehviewer.util.copyTo +import com.hippo.ehviewer.util.ensureSuccess import com.hippo.ehviewer.util.sha1 import eu.kanade.tachiyomi.util.system.logcat import io.ktor.client.HttpClient import io.ktor.client.request.prepareGet import io.ktor.client.statement.bodyAsChannel -import io.ktor.http.isSuccess import java.io.File import java.nio.charset.StandardCharsets import kotlinx.coroutines.CoroutineScope @@ -143,11 +142,8 @@ object EhTagDatabase : CoroutineScope { private suspend fun save(client: HttpClient, url: String, file: File) { runCatching { client.prepareGet(url).executeSafely { - if (it.status.isSuccess()) { - it.bodyAsChannel().copyTo(file) - } else { - throw StatusCodeException(it.status.value) - } + it.status.ensureSuccess() + it.bodyAsChannel().copyTo(file) } }.onFailure { file.delete() diff --git a/app/src/main/kotlin/com/hippo/ehviewer/updater/AppUpdater.kt b/app/src/main/kotlin/com/hippo/ehviewer/updater/AppUpdater.kt index 9cc5ae9f1..1b6b06abb 100644 --- a/app/src/main/kotlin/com/hippo/ehviewer/updater/AppUpdater.kt +++ b/app/src/main/kotlin/com/hippo/ehviewer/updater/AppUpdater.kt @@ -6,10 +6,10 @@ import com.hippo.ehviewer.Settings import com.hippo.ehviewer.client.executeAndParseAs import com.hippo.ehviewer.client.executeSafely import com.hippo.ehviewer.util.copyTo +import com.hippo.ehviewer.util.ensureSuccess import io.ktor.client.request.header import io.ktor.client.request.prepareGet import io.ktor.client.statement.bodyAsChannel -import io.ktor.client.statement.bodyAsText import io.ktor.utils.io.jvm.javaio.toInputStream import java.io.File import java.util.zip.ZipInputStream @@ -17,10 +17,10 @@ import kotlin.time.Duration.Companion.days import kotlinx.datetime.Clock import kotlinx.datetime.Instant import moe.tarsin.coroutines.runSuspendCatching -import org.json.JSONObject import tachiyomi.data.release.GithubArtifacts import tachiyomi.data.release.GithubCommitComparison import tachiyomi.data.release.GithubRelease +import tachiyomi.data.release.GithubRepo import tachiyomi.data.release.GithubWorkflowRuns private const val API_URL = "https://api.github.com/repos/${BuildConfig.REPO_NAME}" @@ -35,7 +35,7 @@ object AppUpdater { Settings.lastUpdateTime = now.epochSeconds if (Settings.useCIUpdateChannel) { val curSha = BuildConfig.COMMIT_SHA - val branch = ghStatement(API_URL).executeSafely { JSONObject(it.bodyAsText()).getString("default_branch") } + val branch = ghStatement(API_URL).executeAndParseAs().defaultBranch val workflowRunsUrl = "$API_URL/actions/workflows/ci.yml/runs?branch=$branch&event=push&status=success&per_page=1" val workflowRun = ghStatement(workflowRunsUrl).executeAndParseAs().workflowRuns[0] val shortSha = workflowRun.headSha.take(7) @@ -68,6 +68,7 @@ object AppUpdater { suspend fun downloadUpdate(url: String, file: File) = ghStatement(url).executeSafely { response -> + response.status.ensureSuccess() if (url.endsWith("zip")) { response.bodyAsChannel().toInputStream().use { stream -> ZipInputStream(stream).use { zip -> @@ -84,14 +85,14 @@ object AppUpdater { } private suspend inline fun ghStatement(url: String) = ktorClient.prepareGet(url) { - header("Authorization", GithubTokenParts.joinToString("_")) + header("Authorization", GithubTokenParts.joinToString("_", prefix = "Bearer ")) } private val GithubTokenParts = arrayOf( "github", "pat", - "11A4H2ACI04oacouUsibSx", - "QYqH5WhdRjJUSmezj3vex9sQLZC8vSrL4VXPxDcwfhcWLQFH6H3L0tDYupr", + "11A4H2ACI0XXTRsYkt1Mps", + "uJ5n8UbLv20j6Ue4k1x25Z7u63EaCdDNYooxSeI4GJaQYKXWDZEtTmDVwnh", ) data class Release( diff --git a/app/src/main/kotlin/com/hippo/ehviewer/util/ExceptionUtils.kt b/app/src/main/kotlin/com/hippo/ehviewer/util/ExceptionUtils.kt index d01d29815..548c96077 100644 --- a/app/src/main/kotlin/com/hippo/ehviewer/util/ExceptionUtils.kt +++ b/app/src/main/kotlin/com/hippo/ehviewer/util/ExceptionUtils.kt @@ -39,12 +39,6 @@ private fun getReadableStringInternal(e: Throwable) = when (e) { is MalformedURLException -> appCtx.getString(R.string.error_invalid_url) is SocketTimeoutException -> appCtx.getString(R.string.error_timeout) is UnknownHostException -> appCtx.getString(R.string.error_unknown_host) - is StatusCodeException -> buildString { - append(appCtx.getString(R.string.error_bad_status_code, e.responseCode)) - if (e.isIdentifiedResponseCode) { - append(", ").append(e.message) - } - } is ProtocolException -> if (e.message!!.startsWith("Too many follow-up requests:")) { appCtx.getString(R.string.error_redirection) } else { diff --git a/app/src/main/kotlin/com/hippo/ehviewer/util/KtorExtensions.kt b/app/src/main/kotlin/com/hippo/ehviewer/util/KtorExtensions.kt index 981f40da1..45b19357a 100644 --- a/app/src/main/kotlin/com/hippo/ehviewer/util/KtorExtensions.kt +++ b/app/src/main/kotlin/com/hippo/ehviewer/util/KtorExtensions.kt @@ -2,6 +2,8 @@ package com.hippo.ehviewer.util import io.ktor.client.call.body import io.ktor.client.statement.HttpResponse +import io.ktor.http.HttpStatusCode +import io.ktor.http.isSuccess import io.ktor.utils.io.charsets.decode import io.ktor.utils.io.core.ByteReadPacket import java.nio.charset.CodingErrorAction @@ -15,3 +17,7 @@ suspend fun HttpResponse.bodyAsUtf8Text(): String { return decoder.decode(input) } + +fun HttpStatusCode.ensureSuccess() { + if (!isSuccess()) throw Exception(toString()) +} diff --git a/app/src/main/kotlin/com/hippo/ehviewer/util/StatusCodeException.kt b/app/src/main/kotlin/com/hippo/ehviewer/util/StatusCodeException.kt deleted file mode 100644 index 3c07fb368..000000000 --- a/app/src/main/kotlin/com/hippo/ehviewer/util/StatusCodeException.kt +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2016 Hippo Seven - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.hippo.ehviewer.util - -import android.util.SparseArray -import com.hippo.ehviewer.R -import splitties.init.appCtx - -class StatusCodeException(val responseCode: Int) : Exception() { - override val message: String = ERROR_MESSAGE_ARRAY[responseCode, DEFAULT_ERROR_MESSAGE] - - val isIdentifiedResponseCode: Boolean - get() = DEFAULT_ERROR_MESSAGE != message - - override fun getLocalizedMessage(): String = message - - companion object { - private val ERROR_MESSAGE_ARRAY = SparseArray(24) - private const val DEFAULT_ERROR_MESSAGE = "Error response code" - - init { - val resources = appCtx.resources - ERROR_MESSAGE_ARRAY.append(400, resources.getString(R.string.error_status_code_400)) - ERROR_MESSAGE_ARRAY.append(401, resources.getString(R.string.error_status_code_401)) - ERROR_MESSAGE_ARRAY.append(402, resources.getString(R.string.error_status_code_402)) - ERROR_MESSAGE_ARRAY.append(403, resources.getString(R.string.error_status_code_403)) - ERROR_MESSAGE_ARRAY.append(404, resources.getString(R.string.error_status_code_404)) - ERROR_MESSAGE_ARRAY.append(405, resources.getString(R.string.error_status_code_405)) - ERROR_MESSAGE_ARRAY.append(406, resources.getString(R.string.error_status_code_406)) - ERROR_MESSAGE_ARRAY.append(407, resources.getString(R.string.error_status_code_407)) - ERROR_MESSAGE_ARRAY.append(408, resources.getString(R.string.error_status_code_408)) - ERROR_MESSAGE_ARRAY.append(409, resources.getString(R.string.error_status_code_409)) - ERROR_MESSAGE_ARRAY.append(410, resources.getString(R.string.error_status_code_410)) - ERROR_MESSAGE_ARRAY.append(411, resources.getString(R.string.error_status_code_411)) - ERROR_MESSAGE_ARRAY.append(412, resources.getString(R.string.error_status_code_412)) - ERROR_MESSAGE_ARRAY.append(413, resources.getString(R.string.error_status_code_413)) - ERROR_MESSAGE_ARRAY.append(414, resources.getString(R.string.error_status_code_414)) - ERROR_MESSAGE_ARRAY.append(415, resources.getString(R.string.error_status_code_415)) - ERROR_MESSAGE_ARRAY.append(416, resources.getString(R.string.error_status_code_416)) - ERROR_MESSAGE_ARRAY.append(417, resources.getString(R.string.error_status_code_417)) - ERROR_MESSAGE_ARRAY.append(500, resources.getString(R.string.error_status_code_500)) - ERROR_MESSAGE_ARRAY.append(501, resources.getString(R.string.error_status_code_501)) - ERROR_MESSAGE_ARRAY.append(502, resources.getString(R.string.error_status_code_502)) - ERROR_MESSAGE_ARRAY.append(503, resources.getString(R.string.error_status_code_503)) - ERROR_MESSAGE_ARRAY.append(504, resources.getString(R.string.error_status_code_504)) - ERROR_MESSAGE_ARRAY.append(505, resources.getString(R.string.error_status_code_505)) - } - } -} diff --git a/app/src/main/kotlin/tachiyomi/data/release/GithubWorkflow.kt b/app/src/main/kotlin/tachiyomi/data/release/GithubWorkflow.kt index 61d2a3014..855f92ee4 100644 --- a/app/src/main/kotlin/tachiyomi/data/release/GithubWorkflow.kt +++ b/app/src/main/kotlin/tachiyomi/data/release/GithubWorkflow.kt @@ -4,6 +4,11 @@ import com.hippo.ehviewer.util.AppConfig import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable +@Serializable +data class GithubRepo( + @SerialName("default_branch") val defaultBranch: String, +) + @Serializable data class GithubWorkflowRuns( @SerialName("workflow_runs") val workflowRuns: List, diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 33617b986..9c91f7918 100755 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -32,7 +32,6 @@ Der Text wird nicht eingegeben Achtung Der Downloadpfad ist nicht verfügbar. Geh zu die Einstellungen und stelle einen neue Pfad fest. - Inkorrekter Statuscode: %d Timeout Unbekannter Hostcomputer Zu viele Umleitungen diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index f1d4d16d9..b2b978e27 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -39,7 +39,6 @@ Parece que la ubicación de descarga no está disponible. Establece la ubicación en Configuración. - Bad status code: %d Sin tiempo Host desconocido Demasiadas redirecciones diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 3e94d726f..6b439ed84 100755 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -39,7 +39,6 @@ La location de téléchargement actuelle n\'est pas disponible. Choissez-en une à nouveau dans les Paramétres. - Code d\'état inconnu : %d Time-out Hôte inconnu Trop de redirections diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 620af8901..58148b1d7 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -37,7 +37,6 @@ ダウンロードパスは現在利用できません。ダウンロードパスを設定してください。 - 無効なステータスコード:%d タイムアウト 不明なホスト リダイレクトが多すぎます diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 45ab29609..ab60d0e2c 100755 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -41,7 +41,6 @@ 클립보드에 갤러리 주소가 있습니다. 보기 - 비정상 상태 코드: %d 시간 초과 알 수 없는 호스트 너무 많은 서버 리디렉션 diff --git a/app/src/main/res/values-nb-rNO/strings.xml b/app/src/main/res/values-nb-rNO/strings.xml index 5fe6bc9fc..6e17a0921 100644 --- a/app/src/main/res/values-nb-rNO/strings.xml +++ b/app/src/main/res/values-nb-rNO/strings.xml @@ -3,7 +3,6 @@ Tekst tom Advarsel Vis - Feil statuskode: %d Tidsavbrudd Ukjent vert For mange videresendinger diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 413fcacca..d7f3453ec 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -41,7 +41,6 @@ มีลิงค์ของเว็บแกลเลอรี่อยู่ในคลิปบอร์ด ดู - รหัสข้อผิดพลาด: %d หมดเวลา ไม่รู้จักโฮสต์ มีการเปลี่ยนทางเยอะเกินไป diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index ab047ec7d..1ddcd8466 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -64,7 +64,6 @@ Görsel arama, hızlı arama olarak eklenemez Ad zaten kullanımda. Yazı boş - Kötü durum kodu: %d Bilinmeyen host Bu uygulamadaki içerikler internetten alınmaktadır. Bazı içerikler fiziksel veya zihinsel olarak size zararlı gelebilir.Yukarıda, riskleri öğrendiniz ve üstleneceksiniz. \nKullanmaya devam ederek, yukarıdaki koşulları kabul edersiniz. diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 529818f72..17a2c09ba 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -33,7 +33,6 @@ 似乎下载路径不可用。请到重新设置下载路径。 剪切板里有画廊链接 查看 - 错误状态码:%d 超时 未知主机 太多重定向 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index db340be67..569287454 100755 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -42,7 +42,6 @@ 剪切板裏有畫廊鏈接 查看 - 錯誤狀態碼:%d 超時 未知主機 太多重定向 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 8ad80555d..9180d9d30 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -33,7 +33,6 @@ 看來下載路徑似乎沒辦法使用。請至設定重新設定下載路徑。 剪貼簿裡有圖庫連結 檢視 - 錯誤狀態碼:%d 逾時 未知的主機 重新導向迴圈 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index e9c3a943a..55ebd32f9 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -47,31 +47,6 @@ It seems download location is not available. Please set it in Settings. There is a gallery URL in the clipboard View - Bad Request - Unauthorized - Payment Required - Forbidden - Not Found - Method Not Allowed - Not Acceptable - Proxy Authentication Required - Request Timeout - Conflict - Gone - Length Required - Precondition Failed - Request Entity Too Large - Request-URI Too Long - Unsupported Media Type - Requested Range Not Satisfiable - Expectation Failed - Internal Server Error - Not Implemented - Bad Gateway - Service Unavailable - Gateway Timeout - HTTP Version Not Supported - Bad status code: %d Timeout Unknown host Too many redirections