com.github.insanusmokrassar.AutoPostTelegramBot.plugins.base.PostsUsedTable.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of AutoPostTelegramBot Show documentation
Show all versions of AutoPostTelegramBot Show documentation
It is base library for creating smart bot for simple management of channels posts
package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.base
import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsTable
import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.PluginName
import com.github.insanusmokrassar.AutoPostTelegramBot.utils.NewDefaultCoroutineScope
import com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions.subscribe
import kotlinx.coroutines.channels.BroadcastChannel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.transaction
typealias PostIdToPluginName = Pair
private val PostsUsedTableScope = NewDefaultCoroutineScope()
class PostsUsedTable internal constructor() : Table() {
val registeredLinkChannel = BroadcastChannel(Channel.CONFLATED)
val unregisteredLinkChannel = BroadcastChannel(Channel.CONFLATED)
private val id = integer("id").primaryKey().autoIncrement()
private val postId = integer("postId")
private val pluginName = text("pluginName")
init {
transaction {
SchemaUtils.createMissingTablesAndColumns(this@PostsUsedTable)
}
PostsTable.postRemovedChannel.subscribe {
transaction {
val wasRegistered = getLinks(it)
if (deleteWhere { postId.eq(it) } > 0) {
PostsUsedTableScope.launch {
wasRegistered.minus(getLinks(it)).forEach { pluginName ->
unregisteredLinkChannel.send(it to pluginName)
}
}
}
}
}
}
private fun PluginName.isLinked(postId: Int): Boolean {
return transaction {
select {
[email protected](postId).and(pluginName.eq(this@isLinked))
}.count() > 0
}
}
fun registerLink(postId: Int, pluginName: PluginName): Boolean {
return transaction {
if (!pluginName.isLinked(postId)) {
insert {
it[[email protected]] = pluginName
it[[email protected]] = postId
}[id] != null
} else {
false
}
}.apply {
if (this) {
PostsUsedTableScope.launch {
registeredLinkChannel.send(postId to pluginName)
}
}
}
}
fun unregisterLink(postId: Int, pluginName: PluginName): Boolean {
return transaction {
if (pluginName.isLinked(postId)) {
deleteWhere {
[email protected](postId).and([email protected](pluginName))
} > 0
} else {
false
}
}.apply {
if (this) {
PostsUsedTableScope.launch {
unregisteredLinkChannel.send(postId to pluginName)
}
}
}
}
fun getLinks(postId: Int): List {
return transaction {
select {
[email protected](postId)
}.map {
it[pluginName]
}
}
}
fun getPluginLinks(pluginName: PluginName): List {
return transaction {
select {
[email protected](pluginName)
}.map {
it[postId]
}
}
}
}