From e2c7125f6cfc8fd5fa663d65645bef0c87f880e7 Mon Sep 17 00:00:00 2001 From: slesh Date: Sun, 23 Aug 2020 00:47:17 +0300 Subject: [PATCH] Extended PathedFile to get it as file/stream --- .../TelegramBotAPI/types/files/PathedFile.kt | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 TelegramBotAPI-extensions-utils/src/jvmMain/kotlin/com/github/insanusmokrassar/TelegramBotAPI/types/files/PathedFile.kt diff --git a/TelegramBotAPI-extensions-utils/src/jvmMain/kotlin/com/github/insanusmokrassar/TelegramBotAPI/types/files/PathedFile.kt b/TelegramBotAPI-extensions-utils/src/jvmMain/kotlin/com/github/insanusmokrassar/TelegramBotAPI/types/files/PathedFile.kt new file mode 100644 index 0000000000..964cccef6b --- /dev/null +++ b/TelegramBotAPI-extensions-utils/src/jvmMain/kotlin/com/github/insanusmokrassar/TelegramBotAPI/types/files/PathedFile.kt @@ -0,0 +1,28 @@ +package com.github.insanusmokrassar.TelegramBotAPI.types.files + +import com.github.insanusmokrassar.TelegramBotAPI.utils.TelegramAPIUrlsKeeper +import java.io.File +import java.io.FileOutputStream +import java.io.InputStream +import java.net.URL + +fun PathedFile.asStream( + telegramAPIUrlsKeeper: TelegramAPIUrlsKeeper +): InputStream = URL(this.fullUrl(telegramAPIUrlsKeeper)).openStream() + +fun PathedFile.asFile( + telegramAPIUrlsKeeper: TelegramAPIUrlsKeeper, + dest: File = File.createTempFile(this.fileUniqueId, this.filename), + defaultBufferSize: Int = 1024, + buffer: ByteArray = ByteArray(defaultBufferSize) +): File { + this.asStream(telegramAPIUrlsKeeper).use { input -> + FileOutputStream(dest).use { out -> + var read: Int + while (input.read(buffer, 0, defaultBufferSize).also { read = it } >= 0) { + out.write(buffer, 0, read) + } + } + } + return dest +}