TelegramBotApiLibraries/cache/content/common/src/commonMain/kotlin/dev/inmo/tgbotapi/libraries/cache/media/common/MessagesFilesCache.kt

53 lines
1.8 KiB
Kotlin
Raw Normal View History

2022-03-22 12:52:23 +00:00
package dev.inmo.tgbotapi.libraries.cache.media.common
import dev.inmo.tgbotapi.types.ChatId
import dev.inmo.tgbotapi.types.MessageIdentifier
import dev.inmo.tgbotapi.utils.StorageFile
2022-04-11 15:28:53 +00:00
import io.ktor.utils.io.core.*
2022-03-22 12:52:23 +00:00
interface MessagesFilesCache {
2022-04-11 15:28:53 +00:00
suspend fun set(
chatId: ChatId,
messageIdentifier: MessageIdentifier,
filename: String,
inputAllocator: suspend () -> Input
)
2022-03-22 12:52:23 +00:00
suspend fun get(chatId: ChatId, messageIdentifier: MessageIdentifier): StorageFile?
suspend fun remove(chatId: ChatId, messageIdentifier: MessageIdentifier)
suspend fun contains(chatId: ChatId, messageIdentifier: MessageIdentifier): Boolean
}
/**
* It is not recommended to use in production realization of [MessagesFilesCache] which has been created for fast
* start of application creation with usage of [MessageContentCache] with aim to replace this realization by some
* disks-oriented one
*/
class InMemoryMessagesFilesCache : MessagesFilesCache {
private val map = mutableMapOf<Pair<ChatId, MessageIdentifier>, StorageFile>()
override suspend fun set(
chatId: ChatId,
messageIdentifier: MessageIdentifier,
filename: String,
2022-04-11 15:28:53 +00:00
inputAllocator: suspend () -> Input
2022-03-22 12:52:23 +00:00
) {
map[chatId to messageIdentifier] = StorageFile(
filename,
2022-04-11 15:28:53 +00:00
inputAllocator().readBytes()
2022-03-22 12:52:23 +00:00
)
}
override suspend fun get(chatId: ChatId, messageIdentifier: MessageIdentifier): StorageFile? {
return map[chatId to messageIdentifier]
}
override suspend fun remove(chatId: ChatId, messageIdentifier: MessageIdentifier) {
map.remove(chatId to messageIdentifier)
}
override suspend fun contains(chatId: ChatId, messageIdentifier: MessageIdentifier): Boolean {
return map.contains(chatId to messageIdentifier)
}
}