All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.stormbit.vksdk.vkapi.Requests.kt Maven / Gradle / Ivy

The newest version!
package com.github.stormbit.vksdk.vkapi

import com.github.stormbit.vksdk.clients.Client
import com.github.stormbit.vksdk.objects.models.Response
import com.github.stormbit.vksdk.utils.BASE_API_URL
import com.github.stormbit.vksdk.utils.formPart
import com.github.stormbit.vksdk.utils.json
import io.ktor.client.request.*
import io.ktor.client.request.forms.*
import io.ktor.http.*
import io.ktor.util.*
import kotlinx.serialization.KSerializer

class FileContent(
    val filename: String,
    val bytes: ByteArray
)

class UploadableFile(
    val key: String,
    val content: FileContent
)

sealed interface Request {
    val serializer: KSerializer
}

class VkApiRequest(
    val client: Client,
    val httpMethod: HttpMethod,
    val method: String,
    val parameters: Parameters,
    override val serializer: KSerializer
) : Request

class UploadFilesRequest(
    val client: Client,
    val uploadUrl: String,
    val files: List,
    val parameters: Parameters,
    override val serializer: KSerializer
) : Request


private suspend operator fun  Request.invoke(): Response = when (this) {
    is VkApiRequest -> {
        client.httpClient.get(BASE_API_URL + method) {
            method = httpMethod

            val parameters = client.baseParams + parameters
            if (httpMethod == HttpMethod.Post) {
                body = FormDataContent(parameters)
            } else {
                url.parameters.appendAll(parameters)
            }

            headers.appendAll(client.headers)
        }
    }

    is UploadFilesRequest -> {
        client.httpClient.submitFormWithBinaryData(uploadUrl, formData {
            parameters.flattenEntries()
                .map { it.formPart }
                .forEach { append(it) }

            files.map { it.formPart }
                .forEach { append(it) }
        })
    }
}

suspend fun  Request.execute(): T = when (val response = this()) {
    is Response.Success -> json.decodeFromJsonElement(serializer, response.response)
    is Response.Error -> throw Exception(response.error)
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy