diff --git a/CHANGELOG.md b/CHANGELOG.md index c1693d3fcd..de906bdf97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ * `Core`: * New function `regularln` for simple creating of `RegularTextSource` with new line in the end +* `API`: + * New function `downloadFileToTemp` for simple downloading of file in filesystem and manipulation with avoiding of direct using input streams and other low-level things * `Versions`: * `MicroUtils`: `0.11.0` -> `0.11.3` diff --git a/tgbotapi.api/src/jvmMain/kotlin/dev/inmo/tgbotapi/extensions/api/files/DownloadFileToTempFile.kt b/tgbotapi.api/src/jvmMain/kotlin/dev/inmo/tgbotapi/extensions/api/files/DownloadFileToTempFile.kt new file mode 100644 index 0000000000..299e9d1ddd --- /dev/null +++ b/tgbotapi.api/src/jvmMain/kotlin/dev/inmo/tgbotapi/extensions/api/files/DownloadFileToTempFile.kt @@ -0,0 +1,57 @@ +package dev.inmo.tgbotapi.extensions.api.files + +import com.benasher44.uuid.uuid4 +import dev.inmo.micro_utils.common.filename +import dev.inmo.micro_utils.coroutines.doOutsideOfCoroutine +import dev.inmo.tgbotapi.bot.TelegramBot +import dev.inmo.tgbotapi.extensions.api.get.getFileAdditionalInfo +import dev.inmo.tgbotapi.requests.abstracts.FileId +import dev.inmo.tgbotapi.types.files.PathedFile +import dev.inmo.tgbotapi.types.files.TelegramMediaFile +import dev.inmo.tgbotapi.types.message.content.MediaContent +import dev.inmo.tgbotapi.utils.fileExtension +import io.ktor.util.cio.use +import io.ktor.util.cio.writeChannel +import io.ktor.utils.io.copyTo +import kotlinx.coroutines.job +import java.io.File +import kotlin.coroutines.coroutineContext + +suspend fun TelegramBot.downloadFileToTemp( + filePath: String +): File { + return downloadFile( + filePath, + File.createTempFile(uuid4().toString(), "_temp").apply { + deleteOnExit() + } + ) +} + +suspend fun TelegramBot.downloadFileToTemp( + pathedFile: PathedFile +) = downloadFileToTemp( + pathedFile.filePath +).apply { + runCatching { + renameTo(File(parentFile, "$nameWithoutExtension.${pathedFile.fileName.fileExtension}")) + } +} + +suspend fun TelegramBot.downloadFileToTemp( + fileId: FileId +) = downloadFileToTemp( + getFileAdditionalInfo(fileId) +) + +suspend fun TelegramBot.downloadFileToTemp( + file: TelegramMediaFile +): File = downloadFileToTemp( + getFileAdditionalInfo(file) +) + +suspend fun TelegramBot.downloadFileToTemp( + file: MediaContent +) = downloadFileToTemp( + getFileAdditionalInfo(file.media) +)