Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: kotlin multipart #944

Merged
merged 21 commits into from
Sep 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion mock-server/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,4 @@ networks:
name: mockapi

volumes:
mockapi-cache:
mockapi-cache:
4 changes: 0 additions & 4 deletions src/SDK/Language/Go.php
Original file line number Diff line number Diff line change
Expand Up @@ -312,10 +312,6 @@ public function getFilters(): array

protected function getPropertyType(array $property, array $spec, string $generic = 'map[string]interface{}'): string
{

if (strpos($property['description'], 'HTTP response body. This will return empty unless execution') !== false) {
return '*payload.Payload';
}
if (\array_key_exists('sub_schema', $property)) {
$type = $this->toPascalCase($property['sub_schema']);

Expand Down
220 changes: 115 additions & 105 deletions src/SDK/Language/Kotlin.php

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ class {{ service.name | caseUcfirst }}(client: Client) : Service(client) {
.domain(Uri.parse(client.endpoint).host!!)
.httpOnly()
.build()

client.http.cookieJar.saveFromResponse(
client.endpoint.toHttpUrl(),
listOf(cookie)
Expand All @@ -129,9 +129,12 @@ class {{ service.name | caseUcfirst }}(client: Client) : Service(client) {
responseType = {{ method | returnType(spec, sdk.namespace | caseDot) | raw }}::class.java
)
{%~ else %}
val apiHeaders = mutableMapOf(
val apiHeaders = mutableMapOf<String, String>(
{%~ for key, header in method.headers %}
"{{ key }}" to "{{ header }}",
{%~ if 'multipart/form-data' in method.consumes and method.type != "upload" %}
"accept" to "multipart/form-data",
{%~ endif %}
{%~ endfor %}
)
{%~ if method.responseModel %}
Expand All @@ -146,7 +149,7 @@ class {{ service.name | caseUcfirst }}(client: Client) : Service(client) {
{%~ endif %}
{%~ if 'multipart/form-data' in method.consumes %}
val idParamName: String? = {% if method.parameters.all | filter(p => p.isUploadID) | length > 0 %}{% for parameter in method.parameters.all | filter(parameter => parameter.isUploadID) %}"{{ parameter.name }}"{% endfor %}{% else %}null{% endif %}

{%~ for parameter in method.parameters.all %}
{%~ if parameter.type == 'file' %}
val paramName = "{{ parameter.name }}"
Expand Down Expand Up @@ -227,4 +230,4 @@ class {{ service.name | caseUcfirst }}(client: Client) : Service(client) {
{%~ endif %}

{%~ endfor %}
}
}
4 changes: 2 additions & 2 deletions templates/kotlin/docs/java/example.md.twig
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {{ sdk.namespace | caseDot }}.Client;
import {{ sdk.namespace | caseDot }}.coroutines.CoroutineCallback;
{% if method.parameters.all | filter((param) => param.type == 'file') | length > 0 %}
import {{ sdk.namespace | caseDot }}.models.InputFile;
import {{ sdk.namespace | caseDot }}.models.Payload;
{% endif %}
import {{ sdk.namespace | caseDot }}.services.{{ service.name | caseUcfirst }};
{% set added = [] %}
Expand Down Expand Up @@ -55,4 +55,4 @@ Client client = new Client()
);
{% endif %}

{% endfor %}
{% endfor %}
4 changes: 2 additions & 2 deletions templates/kotlin/docs/kotlin/example.md.twig
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {{ sdk.namespace | caseDot }}.Client
import {{ sdk.namespace | caseDot }}.coroutines.CoroutineCallback
{% if method.parameters.all | filter((param) => param.type == 'file') | length > 0 %}
import {{ sdk.namespace | caseDot }}.models.InputFile
import {{ sdk.namespace | caseDot }}.models.Payload
{% endif %}
import {{ sdk.namespace | caseDot }}.services.{{ service.name | caseUcfirst }}
{% set added = [] %}
Expand Down Expand Up @@ -43,4 +43,4 @@ val {{ service.name | caseCamel }} = {{ service.name | caseUcfirst }}(client)
{% if loop.last %}
)
{% endif %}
{% endfor %}
{% endfor %}
42 changes: 26 additions & 16 deletions templates/kotlin/src/main/kotlin/io/appwrite/Client.kt.twig
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ package {{ sdk.namespace | caseDot }}
import {{ sdk.namespace | caseDot }}.exceptions.{{ spec.title | caseUcfirst }}Exception
import {{ sdk.namespace | caseDot }}.extensions.fromJson
import {{ sdk.namespace | caseDot }}.extensions.toJson
import {{ sdk.namespace | caseDot }}.models.InputFile
import {{ sdk.namespace | caseDot }}.extensions.fromMultiPart
import {{ sdk.namespace | caseDot }}.models.Payload
import {{ sdk.namespace | caseDot }}.models.UploadProgress
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
Expand Down Expand Up @@ -172,7 +173,7 @@ class Client @JvmOverloads constructor(

/**
* Prepare the HTTP request
*
*
* @param method
* @param path
* @param headers
Expand Down Expand Up @@ -267,7 +268,7 @@ class Client @JvmOverloads constructor(
* @param headers
* @param params
*
* @return [T]
* @return [T]
*/
@Throws({{ spec.title | caseUcfirst }}Exception::class)
suspend fun <T> call(
Expand All @@ -290,7 +291,7 @@ class Client @JvmOverloads constructor(
* @param headers
* @param params
*
* @return [T]
* @return [T]
*/
@Throws({{ spec.title | caseUcfirst }}Exception::class)
suspend fun redirect(
Expand Down Expand Up @@ -325,22 +326,22 @@ class Client @JvmOverloads constructor(
onProgress: ((UploadProgress) -> Unit)? = null,
): T {
var file: RandomAccessFile? = null
val input = params[paramName] as InputFile
val input = params[paramName] as Payload
val size: Long = when(input.sourceType) {
"path", "file" -> {
file = RandomAccessFile(input.path, "r")
file.length()
}
"bytes" -> {
(input.data as ByteArray).size.toLong()
input.toBinary().size.toLong()
}
else -> throw UnsupportedOperationException()
}

if (size < CHUNK_SIZE) {
val data = when(input.sourceType) {
"file", "path" -> File(input.path).asRequestBody()
"bytes" -> (input.data as ByteArray).toRequestBody(input.mimeType.toMediaType())
"bytes" -> input.toBinary().toRequestBody(input.mimeType?.toMediaType())
else -> throw UnsupportedOperationException()
}
params[paramName] = MultipartBody.Part.createFormData(
Expand Down Expand Up @@ -387,7 +388,7 @@ class Client @JvmOverloads constructor(
} else {
size - 1
}
(input.data as ByteArray).copyInto(
input.toBinary().copyInto(
buffer,
startIndex = offset.toInt(),
endIndex = end.toInt()
Expand Down Expand Up @@ -429,7 +430,7 @@ class Client @JvmOverloads constructor(
return converter(result as Map<String, Any>)
}

/**
/**
* Await Redirect
*
* @param request
Expand All @@ -456,14 +457,14 @@ class Client @JvmOverloads constructor(
.charStream()
.buffered()
.use(BufferedReader::readText)

val error = if (response.headers["content-type"]?.contains("application/json") == true) {
val map = body.fromJson<Map<String, Any>>()

{{ spec.title | caseUcfirst }}Exception(
map["message"] as? String ?: "",
map["message"] as? String ?: "",
(map["code"] as Number).toInt(),
map["type"] as? String ?: "",
map["type"] as? String ?: "",
body
)
} else {
Expand Down Expand Up @@ -507,14 +508,14 @@ class Client @JvmOverloads constructor(
.charStream()
.buffered()
.use(BufferedReader::readText)

val error = if (response.headers["content-type"]?.contains("application/json") == true) {
val map = body.fromJson<Map<String, Any>>()

{{ spec.title | caseUcfirst }}Exception(
map["message"] as? String ?: "",
map["message"] as? String ?: "",
(map["code"] as Number).toInt(),
map["type"] as? String ?: "",
map["type"] as? String ?: "",
body
)
} else {
Expand Down Expand Up @@ -549,6 +550,14 @@ class Client @JvmOverloads constructor(
return
}
}
if (response.headers["content-type"]?.contains("multipart/form-data") == true) {
val binaryBody = response.body!!.bytes()
val body = String(binaryBody)
val map = body.fromMultiPart(binaryBody)
it.resume(converter?.invoke(map) ?: map as T)
return
}

val body = response.body!!
.charStream()
.buffered()
Expand All @@ -557,11 +566,12 @@ class Client @JvmOverloads constructor(
it.resume(true as T)
return
}

val map = body.fromJson<Map<String, Any>>()
it.resume(
converter?.invoke(map) ?: map as T
)
}
})
}
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,107 @@
package {{ sdk.namespace | caseDot }}.extensions

import {{ sdk.namespace | caseDot }}.models.Payload
import kotlin.reflect.KClass
import kotlin.reflect.typeOf

inline fun <reified T : Any> classOf(): Class<T> {
return (typeOf<T>().classifier!! as KClass<T>).java
}
}

fun String.fromMultiPart(binaryBody: ByteArray): Map<String, Any> {
val match = Regex("(-+\\w+)--").find(this) ?: return emptyMap()
// For kotlin

val boundary = match.groupValues[1]

var map =
mutableMapOf<String, Any>(
"\$id" to "",
"\$createdAt" to "",
"\$updatedAt" to "",
"\$permissions" to emptyList<String>(),
"functionId" to "",
"trigger" to "",
"status" to "",
"requestMethod" to "",
"requestPath" to "",
"requestHeaders" to emptyList<HashMap<String, Any>>(),
"responseStatusCode" to 0,
"responseBody" to Payload.fromBinary(ByteArray(0)),
"responseHeaders" to emptyList<HashMap<String, Any>>(),
"logs" to "",
"errors" to "",
"duration" to 0.0,
"scheduledAt" to "",
)

val parts = this.split(boundary)
for (part in parts) {
var lines = part.split("\r\n")

val name = Regex("name=\"?(\\w+)").find(part) ?: continue

lines =
lines
.dropWhile { it.isEmpty() }
.drop(1)
.dropWhile { it.isEmpty() }
.dropLastWhile { it.isEmpty() }
val key = name.groupValues[1]

if (lines.isEmpty()) {
continue
}

if (key == "responseBody") {
val needle = "name=\"responseBody\"\r\n\r\n"
val indexOf = this.indexOf(needle) + needle.length
val endBytes = "\r\n-------".toByteArray()

val list = ByteArray(binaryBody.size - indexOf)
val multipart = binaryBody.drop(indexOf)

var weHitTheEnd = false
var j = 0
for (i in multipart) {
if (multipart.size > j + endBytes.size) {
var jj = 0
for (byte in endBytes) {
if (byte != multipart[j + jj]) break
jj++
if (jj != endBytes.size - 1) continue
weHitTheEnd = true
}
}
if (weHitTheEnd) {
break
}

list[j] = multipart[j]
j++
}

map["responseBody"] =
Payload.fromBinary(list.dropLastWhile { it == 0.toByte() }.toByteArray())
continue
}

if (lines[0] == "Content-Type: application/json") {
lines = lines.drop(1).dropWhile { it.isEmpty() }
val list = lines.joinToString("\r\n").fromJson<List<String>>()
map[key] = list
continue
}

val value = lines.joinToString("\r\n")

map[key] =
when (key) {
"responseStatusCode" -> value.toInt()
"duration" -> value.toFloat()
else -> value
}
}

return map
}

This file was deleted.

Loading
Loading