All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.insanusmokrassar.AutoPostTelegramBot.base.database.PostTransactionTable.kt Maven / Gradle / Ivy

package com.github.insanusmokrassar.AutoPostTelegramBot.base.database

import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.exceptions.NothingToSaveException
import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsMessagesTable
import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsTable
import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.PostMessage
import kotlinx.coroutines.experimental.channels.BroadcastChannel
import kotlinx.coroutines.experimental.launch

private const val broadcastSubscriptions = 256

object PostTransactionTable {
    val transactionStartedChannel = BroadcastChannel(broadcastSubscriptions)
    val transactionMessageAddedChannel = BroadcastChannel>(broadcastSubscriptions)
    val transactionMessageRemovedChannel = BroadcastChannel(broadcastSubscriptions)
    val transactionCompletedChannel = BroadcastChannel(broadcastSubscriptions)

    private val messages = ArrayList()
    var inTransaction: Boolean = false
        private set

    fun startTransaction() {
        if (inTransaction) {
            throw IllegalStateException("Already in transaction")
        }
        messages.clear()
        inTransaction = true

        launch {
            transactionStartedChannel.send(Unit)
        }
    }

    fun addMessageId(vararg message: PostMessage) {
        if (!inTransaction) {
            throw IllegalStateException("Not in transaction")
        }

        messages.addAll(message)

        launch {
            transactionMessageAddedChannel.send(message)
        }
    }

    fun removeMessageId(message: PostMessage) {
        if (!inTransaction) {
            throw IllegalStateException("Not in transaction")
        }

        messages.remove(message)

        launch {
            transactionMessageRemovedChannel.send(message)
        }
    }

    private fun completeTransaction(): List {
        return listOf(*messages.toTypedArray()).also {
            messages.clear()
            inTransaction = false
        }
    }

    @Throws(NothingToSaveException::class)
    fun saveNewPost() {
        val messagesIds = completeTransaction().toTypedArray()
        if (messagesIds.isEmpty()) {
            throw NothingToSaveException("No messages for saving")
        }
        val postId = PostsTable.allocatePost()
        PostsMessagesTable.addMessagesToPost(
            postId,
            *messagesIds
        )

        launch {
            transactionCompletedChannel.send(postId)
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy