From ea537da8314ff2ec79c22dc907647cec441e2a74 Mon Sep 17 00:00:00 2001 From: Arjix <53124886+ArjixWasTaken@users.noreply.github.com> Date: Sat, 2 Oct 2021 23:54:16 +0300 Subject: [PATCH] added a wrapper for the okhttp Response --- .../cloudstream3/network/Requests.kt | 63 ++++++++++++++++++- 1 file changed, 60 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/lagradost/cloudstream3/network/Requests.kt b/app/src/main/java/com/lagradost/cloudstream3/network/Requests.kt index 5da06d1d..ab3d3964 100644 --- a/app/src/main/java/com/lagradost/cloudstream3/network/Requests.kt +++ b/app/src/main/java/com/lagradost/cloudstream3/network/Requests.kt @@ -16,6 +16,63 @@ private val DEFAULT_COOKIES: Map = mapOf() private val DEFAULT_REFERER: String? = null +// lowercase to avoid conflicts +class response(response: Response) { + companion object { + private var responseText: String? = null + private var responseBody: ResponseBody? = null + } + + public val rawResponse: Response = response + + val text: String + get() { + if (responseText != null) return responseText!! + if (responseBody == null) responseBody = rawResponse.body + + responseText = responseBody.toString() + return responseText!! + } + + val body: ResponseBody + get() { + if (responseBody == null) responseBody = rawResponse.body + return responseBody!! + } + + val url: String + get() { + return rawResponse.request.url.toString() + } + + val cookies: Map + get() { + val cookieList = + rawResponse.headers.filter { it.first.equals("set-cookie", ignoreCase = true) }.getOrNull(0)?.second?.split(";") + return cookieList?.associate { + val split = it.split("=") + (split.getOrNull(0)?.trim() ?: "") to (split.getOrNull(1)?.trim() ?: "") + }?.filter { it.key.isNotBlank() && it.value.isNotBlank() } ?: mapOf() + } + + val headers: Headers + get() { + return rawResponse.headers + } + + val ok: Boolean + get() { + return rawResponse.isSuccessful + } + + val status: Int + get() { + return rawResponse.code + } + +} + + /** WARNING! CAN ONLY BE READ ONCE */ val Response.text: String get() { @@ -98,7 +155,7 @@ fun get( .build() val request = getRequestCreator(url, headers, referer, params, cookies, cacheTime, cacheUnit) - return client.newCall(request).execute() + return response(client.newCall(request).execute()) } @@ -120,7 +177,7 @@ fun post( .callTimeout(timeout, TimeUnit.SECONDS) .build() val request = postRequestCreator(url, headers, referer, params, cookies, data, cacheTime, cacheUnit) - return client.newCall(request).execute() + return response(client.newCall(request).execute()) } @@ -156,4 +213,4 @@ fun postRequestCreator( .headers(getHeaders(headers, referer, cookies)) .post(getData(data)) .build() -} \ No newline at end of file +}