Skip to content

Commit

Permalink
Refinds
Browse files Browse the repository at this point in the history
  • Loading branch information
nekohasekai committed Sep 19, 2020
1 parent 5112291 commit 09cb60a
Show file tree
Hide file tree
Showing 36 changed files with 250 additions and 251 deletions.
6 changes: 1 addition & 5 deletions _pm.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,4 @@ BOT_LANG: zh_CN
B0T_OWNER:
PM_MODE: private
PM_WHITE_LIST:
LOG_LEVEL: INFO
BOT_LANG_LIST:
- en_US
- zh_CN
- zh_TW
LOG_LEVEL: INFO
2 changes: 1 addition & 1 deletion bot/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

<properties>

<mainClass>io.nekohasekai.pm.Launcher</mainClass>
<mainClass>io.nekohasekai.pm.TdPmBot</mainClass>

</properties>

Expand Down
12 changes: 11 additions & 1 deletion bot/src/main/java/io/nekohasekai/pm/IdDefs.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package io.nekohasekai.pm

import io.nekohasekai.ktlib.td.core.TdHandler
import io.nekohasekai.pm.instance.PmBot

const val PERSIST_BOT_CREATE = 0
const val PERSIST_SET_START_MESSAGES = 2
const val PERSIST_NEW_FUNCTION = 3
Expand All @@ -15,4 +18,11 @@ const val DATA_DELETE_BOT_MENU = 5L
const val DATA_DELETE_MESSAGE = 6L
const val DATA_EDIT_OPTIONS = 7L
const val DATA_EDIT_COMMANDS = 8L
const val DATA_EDIT_COMMAND = 9L
const val DATA_EDIT_COMMAND = 9L

val TdHandler.launcher
get() = when (val sudo = sudo) {
is TdPmBot -> sudo
is PmBot -> sudo.launcher
else -> error("invalid handler")
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import cn.hutool.core.date.DateUtil
import cn.hutool.core.date.SystemClock
import cn.hutool.core.io.FileUtil
import io.nekohasekai.ktlib.compress.*
import io.nekohasekai.ktlib.core.*
import io.nekohasekai.ktlib.core.getValue
import io.nekohasekai.ktlib.core.input
import io.nekohasekai.ktlib.db.IdTableCacheMap
import io.nekohasekai.ktlib.db.forceCreateTables
import io.nekohasekai.ktlib.td.cli.TdCli
import io.nekohasekai.ktlib.td.core.extensions.*
import io.nekohasekai.ktlib.td.core.i18n.*
Expand All @@ -17,14 +20,34 @@ import io.nekohasekai.pm.database.*
import io.nekohasekai.pm.instance.*
import io.nekohasekai.pm.manage.*
import kotlinx.coroutines.*
import org.jetbrains.exposed.dao.id.IdTable
import org.jetbrains.exposed.sql.*
import td.TdApi
import java.io.File
import java.util.*
import kotlin.concurrent.schedule
import kotlin.system.exitProcess

object Launcher : TdCli(), PmInstance {
open class TdPmBot(tag: String = "main", name: String = "TdPmBot") : TdCli(tag, name), PmInstance {

companion object : TdPmBot() {

const val repoName = "TdPmBot"
const val repoUrl = "https://github.com/TdBotProject/TdPmBot"
const val licenseUrl = "https://github.com/TdBotProject/TdPmBot/blob/master/LICENSE"

@JvmStatic
fun main(args: Array<String>) {

launch(args)

loadConfig()

start()

}

}

var public = false
lateinit var whiteList: IntArray
Expand All @@ -43,40 +66,52 @@ object Launcher : TdCli(), PmInstance {

@Suppress("ObjectPropertyName")
private var _admin = 0L

override val admin by ::_admin

lateinit var users: Array<Long>

override val integration get() = BotIntegration.Cache.fetch(me.id).value
override val settings get() = BotSetting.Cache.fetch(me.id).value
override val blocks by lazy { UserBlocks.Cache(me.id) }
val botIntegrations by lazy { IdTableCacheMap(database, BotIntegration) }
val botSettings by lazy { IdTableCacheMap(database, BotSetting) }
val actionMessages by lazy { IdTableCacheMap(database, ActionMessage) }
val startMessages by lazy { StartMessages.Cache(database) }
val botCommands by lazy { BotCommands.Cache(database) }

override var configFile = File("pm.yml")
override val integration get() = botIntegrations.fetch(me.id).value
override val settings get() = botSettings.fetch(me.id).value
override val blocks by lazy { UserBlocks.Cache(database, me.id) }

@JvmStatic
fun main(args: Array<String>) {
val instanceMap = HashMap<Int, PmBot>()

launch(args)
fun initBot(userBot: UserBot): PmBot {

loadConfig()
return instanceMap[userBot.botId] ?: synchronized(instanceMap) {

start()
PmBot(userBot.botToken, userBot, this).apply {

if (admin == 0L) {
instanceMap[botUserId] = this

defaultLog.warn("Bot owner not specified, send /id to bot to get your userId.")
start()

}

}

}

override var configFile = File("pm.yml")

override fun onLoadConfig() {

super.onLoadConfig()

_admin = intConfig("B0T_OWNER")?.toLong() ?: _admin

if (admin == 0L) {

clientLog.warn("Bot owner not specified, send /id to bot to get your userId.")

}

when (val pmMode = stringConfig("PM_MODE")?.toLowerCase() ?: "public") {

"public" -> {
Expand All @@ -95,7 +130,7 @@ object Launcher : TdCli(), PmInstance {

runCatching { item.toInt() }.onFailure {

defaultLog.warn(">> Invalid white-list user-id item: $item", it)
clientLog.warn(">> Invalid white-list user-id item: $item", it)

}.getOrNull()

Expand All @@ -111,7 +146,7 @@ object Launcher : TdCli(), PmInstance {

else -> {

defaultLog.error(">> Invalid mode defined: $pmMode")
clientLog.error(">> Invalid mode defined: $pmMode")

exitProcess(100)

Expand All @@ -136,7 +171,7 @@ object Launcher : TdCli(), PmInstance {

} else if (!backupTo.name.endsWith(".tar.xz")) {

defaultLog.error(">> File name must ends with .tar.xz")
clientLog.error(">> File name must ends with .tar.xz")

exitProcess(100)

Expand Down Expand Up @@ -178,7 +213,7 @@ object Launcher : TdCli(), PmInstance {

output.close()

defaultLog.info(">> Saved to ${backupTo.path}")
clientLog.info(">> Saved to ${backupTo.path}")

exitProcess(0)

Expand All @@ -190,7 +225,7 @@ object Launcher : TdCli(), PmInstance {

super.onLoad()

defaultLog.debug("Init databases")
clientLog.debug("Init databases")

initDatabase("pm_data.db")

Expand All @@ -204,7 +239,7 @@ object Launcher : TdCli(), PmInstance {

database.write {

SchemaUtils.createMissingTablesAndColumns(
forceCreateTables(
UserBots,
StartMessages,
ActionMessages,
Expand Down Expand Up @@ -276,7 +311,9 @@ object Launcher : TdCli(), PmInstance {

database {

BotInstances.loadAll()
clientLog.trace("Loading PM Bots")

UserBot.all().forEach { initBot(it) }

}

Expand All @@ -290,18 +327,19 @@ object Launcher : TdCli(), PmInstance {

override suspend fun gc() {

defaultLog.debug(">> 执行垃圾回收")
clientLog.debug(">> 执行垃圾回收")

defaultLog.debug(">> 内存缓存")
clientLog.debug(">> 内存缓存")

super.gc()

BotIntegration.Cache.clear()
BotSetting.Cache.clear()
ActionMessage.Cache.clear()
StartMessages.Cache.clear()
botIntegrations.gc()
botSettings.gc()
actionMessages.gc()
startMessages.gc()
botCommands.gc()

defaultLog.debug(">> 清理数据库")
clientLog.debug(">> 清理数据库")

val time = (SystemClock.now() / 1000L).toInt() - 24 * 60 * 60

Expand All @@ -327,37 +365,51 @@ object Launcher : TdCli(), PmInstance {

ActionMessages.deleteWhere { ActionMessages.createAt less time }

val existsBots = UserBot.all().map { it.botId }.toMutableLinkedList().apply { add(me.id) }
@Suppress("UNCHECKED_CAST")
fun deleteUnusedBotData(
vararg tables: Table
) {

for (table in tables) {

BotCommands.deleteWhere { BotCommands.botId notInList existsBots }
BotIntegrations.deleteWhere { BotIntegrations.botId notInList existsBots }
BotSettings.deleteWhere { BotSettings.botId notInList existsBots }
MessageRecords.deleteWhere { MessageRecords.botId notInList existsBots }
StartMessages.deleteWhere { StartMessages.botId notInList existsBots }
UserBlocks.deleteWhere { UserBlocks.botId notInList existsBots }
val idColumn: Column<Int> = (table.indices
.find { it.columns.size == 1 && it.columns[0].name == "bot_id" }
?.columns?.get(0)
?: ((table as? IdTable<Int>)!!.id.columnType as EntityIDColumnType<*>).idColumn) as Column<Int>

table.deleteWhere { (idColumn neq me.id) and (idColumn notInSubQuery UserBots.selectAll().adjustSlice { slice(UserBots.botId) }) }

}

}

deleteUnusedBotData(
BotCommands,
BotIntegrations,
BotSettings,
MessageRecords,
StartMessages,
UserBlocks
)

}

defaultLog.trace(">> ${me.displayNameFormatted}")
clientLog.trace(">> ${me.displayNameFormatted}")

gc(this)

BotInstances.instanceMap.forEach {
instanceMap.forEach {

defaultLog.trace(">> ${it.value.me.displayNameFormatted}")
clientLog.trace(">> ${it.value.me.displayNameFormatted}")

it.value.gc()

}

defaultLog.debug("<< 执行垃圾回收")
clientLog.debug("<< 执行垃圾回收")

}

const val repoName = "TdPmBot"
const val repoUrl = "https://github.com/TdBotProject/TdPmBot"
const val licenseUrl = "https://github.com/TdBotProject/TdPmBot/blob/master/LICENSE"

override suspend fun userBlocked(userId: Int) = blocks.fetch(userId).value == true

override suspend fun onUndefinedFunction(userId: Int, chatId: Long, message: TdApi.Message, function: String, param: String, params: Array<String>, originParams: Array<String>) {
Expand All @@ -372,13 +424,13 @@ object Launcher : TdCli(), PmInstance {

}

val command = BotCommands.Cache.fetch(me.id to function).value?.takeIf { !it.hide }
val command = botCommands.fetch(me.id to function).value?.takeIf { !it.hide }

if (message.fromPrivate) {

if (command == null) {

if (chatId != admin) onLaunch(userId, chatId, message)
onLaunch(userId, chatId, message)

finishEvent()

Expand All @@ -405,7 +457,7 @@ object Launcher : TdCli(), PmInstance {

if (message.fromPrivate) {

val command = BotCommands.Cache.fetch(me.id to payload).value?.takeIf { !it.hide } ?: rejectFunction()
val command = botCommands.fetch(me.id to payload).value?.takeIf { !it.hide } ?: rejectFunction()

command.messages.forEach { sudo make it syncTo chatId }

Expand All @@ -421,7 +473,7 @@ object Launcher : TdCli(), PmInstance {

val L = localeFor(userId)

val startMessages = StartMessages.Cache.fetch(me.id).value
val startMessages = startMessages.fetch(me.id).value

if (!public && chatId != admin) {

Expand Down
4 changes: 0 additions & 4 deletions bot/src/main/java/io/nekohasekai/pm/database/ActionMessage.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package io.nekohasekai.pm.database

import io.nekohasekai.ktlib.db.IdTableCacheMap
import io.nekohasekai.pm.Launcher
import org.jetbrains.exposed.dao.Entity
import org.jetbrains.exposed.dao.EntityClass
import org.jetbrains.exposed.dao.id.EntityID
Expand All @@ -20,6 +18,4 @@ class ActionMessage(id: EntityID<Int>) : Entity<Int>(id) {

companion object : EntityClass<Int, ActionMessage>(ActionMessages)

object Cache : IdTableCacheMap<Int, ActionMessage>(Launcher.database, ActionMessage)

}
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,9 @@ object ActionMessages : KeyValueTable<Int, Long>("action_messages") {
val userId = integer("user_id").entityId()

val messageId = long("message_id")

val createAt = integer("create_at").default(0).index()

override val id = userId

override val value = messageId

}
Loading

0 comments on commit 09cb60a

Please sign in to comment.