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

close InputStreams used for attachments #309

Merged
merged 1 commit into from
Jun 8, 2021
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
20 changes: 10 additions & 10 deletions rest/src/main/kotlin/request/Request.kt
Original file line number Diff line number Diff line change
Expand Up @@ -82,17 +82,17 @@ class MultipartRequest<B : Any, R>(
body?.let {
append("payload_json", Json.encodeToString(it.strategy, it.body))
}
if (files.size == 1) append("file", filename = files[0].first) {
files[0].second.copyTo(outputStream())
} else files.forEachIndexed { index, pair ->
val name = pair.first
val inputStream = pair.second
append("file$index", name) { inputStream.copyTo(outputStream()) }
try {
if (files.size == 1) append("file", filename = files[0].first) {
files[0].second.copyTo(outputStream())
} else files.forEachIndexed { index, pair ->
val name = pair.first
val inputStream = pair.second
append("file$index", name) { inputStream.copyTo(outputStream()) }
}
} finally {
files.forEach { it.second.close() }
}
}

}




26 changes: 26 additions & 0 deletions rest/src/test/kotlin/request/MessageRequests.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package dev.kord.rest.request

import dev.kord.rest.json.response.GatewayResponse
import dev.kord.rest.route.Route
import io.ktor.util.*
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.*
import java.io.InputStream

@TestMethodOrder(MethodOrderer.MethodName::class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class MessageRequests {
@Test
fun `attachment stream closed`() = runBlocking {
val linusStream = object : InputStream() {
val stream = ClassLoader.getSystemResourceAsStream("images/kord.png")!!
var closed = false; private set
override fun read() = stream.read()
override fun close() { stream.close(); closed = true }
}

MultipartRequest<Any, GatewayResponse>(Route.GatewayGet, mapOf(), StringValues.Empty, StringValues.Empty, null, listOf("linus.png" to linusStream))

assert(linusStream.closed)
}
}