diff --git a/.github/workflows/publish_packages.yml b/.github/workflows/publish_packages.yml new file mode 100644 index 0000000..310bb19 --- /dev/null +++ b/.github/workflows/publish_packages.yml @@ -0,0 +1,22 @@ + +name: Publish package to GitHub Packages +on: [push] +jobs: + publishing: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-java@v1 + with: + java-version: 1.8 + - name: Update version + run: | + branch="`echo "${{ github.ref }}" | grep -o "[^/]*$"`" + sed -i -e "s/^version=\([0-9\.]*\)/version=\1-branch_$branch-build${{ github.run_number }}/" gradle.properties + - name: prebuild + run: ./gradlew clean build + - name: Publish package + run: ./gradlew --no-parallel publishAllPublicationsToGithubPackagesRepository -x signMavenPublication + env: + GITHUBPACKAGES_USER: ${{ github.actor }} + GITHUBPACKAGES_PASSWORD: ${{ secrets.GITHUB_TOKEN }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 84d4fa3..8af4eca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Auto Post Telegram Bot Changelog +## 1.9.0 + +* Versions updates: + * Kotlin: `1.3.61` -> `1.3.72` + * Coroutines: `1.3.3` -> `1.3.8` + * Kotlin Serialization: `0.14.0` -> `0.20.0` + * `TelegramBotAPI` -> `TelegramBotAPI-all` + version change: `0.23.2` -> `0.27.10` + * Ktor: `1.3.1` -> `1.3.2` +* `BroadcastChannel` and `ReceiveChannel` extensions were removed +* Transaction flows added + ## 1.8.0 * Version updates: @@ -8,6 +19,10 @@ * `TimerTriggerStrategy` now have new extension `getPostsInRange` and `getTriggersInRange` * `MostRatedChooser` now correctly work with exceptions list +### 1.8.3 + +* Hotfix for scheduler plugin and its table + ### 1.8.2 * `DatabaseConfig#connect` now is deprecated. It is recommended to use `DatabaseConfig#database` property diff --git a/build.gradle b/build.gradle index 82c9b19..c2005dd 100644 --- a/build.gradle +++ b/build.gradle @@ -1,6 +1,3 @@ -project.version = "1.8.2" -project.group = "com.github.insanusmokrassar" - buildscript { repositories { mavenLocal() @@ -11,7 +8,6 @@ buildscript { dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version" - classpath "com.jfrog.bintray.gradle:gradle-bintray-plugin:$gradle_bintray_plugin_version" } } @@ -20,9 +16,12 @@ apply plugin: 'application' apply plugin: 'kotlin' apply plugin: 'kotlinx-serialization' +project.version = "$version" +project.group = "dev.inmo" + apply from: "publish.gradle" -mainClassName="com.github.insanusmokrassar.AutoPostTelegramBot.LaunchKt" +mainClassName="dev.inmo.AutoPostTelegramBot.LaunchKt" repositories { mavenLocal() @@ -35,14 +34,16 @@ repositories { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" api "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlin_coroutines_version" - api "org.jetbrains.kotlinx:kotlinx-serialization-runtime:$kotlin_serialisation_runtime_version" - api "com.github.insanusmokrassar:TelegramBotAPI:$telegram_bot_api_version" + api "org.jetbrains.kotlinx:kotlinx-serialization-json:$kotlin_serialisation_runtime_version" + api "dev.inmo:tgbotapi:$telegram_bot_api_version" implementation "io.ktor:ktor-server-cio:$ktor_version" implementation "io.ktor:ktor-client-okhttp:$ktor_version" - api "org.jetbrains.exposed:exposed:$kotlin_exposed_version" + api "org.jetbrains.exposed:exposed-jdbc:$kotlin_exposed_version" + api "org.jetbrains.exposed:exposed-jodatime:$kotlin_exposed_version" implementation "com.h2database:h2:$h2_version" + api "joda-time:joda-time:$joda_time_version" // Use JUnit test framework testImplementation 'junit:junit:4.12' diff --git a/gradle.properties b/gradle.properties index bcf1694..3bb7301 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,11 +1,12 @@ kotlin.code.style=official -kotlin_version=1.3.61 -kotlin_coroutines_version=1.3.3 -kotlin_serialisation_runtime_version=0.14.0 -kotlin_exposed_version=0.10.2 -telegram_bot_api_version=0.23.2 -ktor_version=1.3.1 +kotlin_version=1.5.20 +kotlin_coroutines_version=1.5.0 +kotlin_serialisation_runtime_version=1.2.1 +kotlin_exposed_version=0.32.1 +telegram_bot_api_version=0.35.1 +ktor_version=1.6.1 +joda_time_version=2.10.10 -h2_version=1.4.196 +h2_version=1.4.200 -gradle_bintray_plugin_version=1.8.4 +version=1.9.0 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 9c53caf..dd1c5ba 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.2.1-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-bin.zip diff --git a/maven.publish.gradle b/maven.publish.gradle deleted file mode 100644 index 66be172..0000000 --- a/maven.publish.gradle +++ /dev/null @@ -1,57 +0,0 @@ -apply plugin: 'maven-publish' - -task sourcesJar(type: Jar) { - from sourceSets.main.allSource - classifier = 'sources' -} - -task javadocJar(type: Jar) { - from javadoc - classifier = 'javadoc' -} - -publishing { - publications { - maven(MavenPublication) { - from components.java - groupId "${project.group}" - artifactId "${project.name}" - version "${project.version}" - - artifact sourcesJar - artifact javadocJar - - pom.withXml { - asNode().children().last() + { - resolveStrategy = Closure.DELEGATE_FIRST - name 'Auto post Telegram Bot' - description 'It is base library for creating smart bot for simple management of channels posts' - url "https://insanusmokrassar.github.io/${project.name}" - - scm { - connection "scm:git:git://github.com/insanusmokrassar/${project.name}.git" - developerConnection "scm:git:[fetch=]https://github.com/insanusmokrassar/${project.name}.git[push=]ssh:git@github.com:insanusmokrassar/${project.name}.git" - url "https://github.com/insanusmokrassar/${project.name}" - - } - - developers { - developer { - id "InsanusMokrassar" - name "Ovsyannikov Alexey" - email "ovsyannikov.alexey95@gmail.com" - } - } - - licenses { - license { - name 'The Apache Software License, Version 2.0' - url "https://github.com/InsanusMokrassar/${project.name}/blob/master/LICENSE" - distribution 'repo' - } - } - } - } - } - } -} diff --git a/publish.gradle b/publish.gradle index 0ec565e..751ab99 100644 --- a/publish.gradle +++ b/publish.gradle @@ -1,37 +1,82 @@ -apply plugin: 'com.jfrog.bintray' +apply plugin: 'maven-publish' +apply plugin: 'signing' -ext { - projectBintrayDir = "${project.group}/".replace(".", "/") + "${project.name}/${project.version}" + +task javadocJar(type: Jar) { + from javadoc + classifier = 'javadoc' +} +task sourcesJar(type: Jar) { + from sourceSets.main.allSource + classifier = 'sources' } -bintray { - user = project.hasProperty('BINTRAY_USER') ? project.property('BINTRAY_USER') : System.getenv('BINTRAY_USER') - key = project.hasProperty('BINTRAY_KEY') ? project.property('BINTRAY_KEY') : System.getenv('BINTRAY_KEY') - publications = ["maven"] - filesSpec { - into "$projectBintrayDir" - from("build/libs") { - include "**/*.asc" - } - from("build/publications/maven") { - rename 'pom-default.xml(.*)', "${project.name}-${project.version}.pom\$1" - } - } - pkg { - repo = 'StandardRepository' - name = "${project.name}" - vcsUrl = "https://github.com/InsanusMokrassar/${project.name}" - licenses = ['Apache-2.0'] - version { - name = "${project.version}" - released = new Date() - vcsTag = name - gpg { - sign = true - passphrase = project.hasProperty('signing.gnupg.passphrase') ? project.property('signing.gnupg.passphrase') : System.getenv('signing.gnupg.passphrase') +publishing { + publications { + maven(MavenPublication) { + from components.java + + artifact javadocJar + artifact sourcesJar + + pom { + resolveStrategy = Closure.DELEGATE_FIRST + + description = "It is base library for creating smart bot for simple management of channels posts" + name = "Auto post Telegram Bot" + url = "https://insanusmokrassar.github.io/AutoPostTelegramBot" + + scm { + developerConnection = "scm:git:[fetch=]https://github.com/insanusmokrassar/AutoPostTelegramBot[push=]https://github.com/insanusmokrassar/AutoPostTelegramBot" + url = "https://github.com/insanusmokrassar/AutoPostTelegramBot" + } + + developers { + + developer { + id = "InsanusMokrassar" + name = "Ovsyannikov Alexey" + email = "ovsyannikov.alexey95@gmail.com" + } + + } + + licenses { + + license { + name = "Apache Software License 2.0" + url = "https://github.com/InsanusMokrassar/${project.name}/blob/master/LICENSE" + } + + } + } + repositories { + if ((project.hasProperty('GITHUBPACKAGES_USER') || System.getenv('GITHUBPACKAGES_USER') != null) && (project.hasProperty('GITHUBPACKAGES_PASSWORD') || System.getenv('GITHUBPACKAGES_PASSWORD') != null)) { + maven { + name = "GithubPackages" + url = uri("https://maven.pkg.github.com/InsanusMokrassar/AutoPostTelegramBot") + credentials { + username = project.hasProperty('GITHUBPACKAGES_USER') ? project.property('GITHUBPACKAGES_USER') : System.getenv('GITHUBPACKAGES_USER') + password = project.hasProperty('GITHUBPACKAGES_PASSWORD') ? project.property('GITHUBPACKAGES_PASSWORD') : System.getenv('GITHUBPACKAGES_PASSWORD') + } + } + } + if ((project.hasProperty('SONATYPE_USER') || System.getenv('SONATYPE_USER') != null) && (project.hasProperty('SONATYPE_PASSWORD') || System.getenv('SONATYPE_PASSWORD') != null)) { + maven { + name = "sonatype" + url = uri("https://oss.sonatype.org/service/local/staging/deploy/maven2/") + credentials { + username = project.hasProperty('SONATYPE_USER') ? project.property('SONATYPE_USER') : System.getenv('SONATYPE_USER') + password = project.hasProperty('SONATYPE_PASSWORD') ? project.property('SONATYPE_PASSWORD') : System.getenv('SONATYPE_PASSWORD') + } + } + } } } } } -apply from: "maven.publish.gradle" +signing { + useGpgCmd() + sign publishing.publications +} diff --git a/publish_config.kpsb b/publish_config.kpsb new file mode 100644 index 0000000..b0743f3 --- /dev/null +++ b/publish_config.kpsb @@ -0,0 +1 @@ +{"licenses":[{"id":"Apache-2.0","title":"Apache Software License 2.0","url":"https://github.com/InsanusMokrassar/${project.name}/blob/master/LICENSE"}],"mavenConfig":{"name":"Auto post Telegram Bot","description":"It is base library for creating smart bot for simple management of channels posts","url":"https://insanusmokrassar.github.io/AutoPostTelegramBot","vcsUrl":"https://github.com/insanusmokrassar/AutoPostTelegramBot","includeGpgSigning":true,"developers":[{"id":"InsanusMokrassar","name":"Ovsyannikov Alexey","eMail":"ovsyannikov.alexey95@gmail.com"}],"repositories":[{"name":"GithubPackages","url":"https://maven.pkg.github.com/InsanusMokrassar/AutoPostTelegramBot"},{"name":"sonatype","url":"https://oss.sonatype.org/service/local/staging/deploy/maven2/"}]},"type":"JVM"} \ No newline at end of file diff --git a/settings.gradle b/settings.gradle index 7a82d11..73e80ac 100644 --- a/settings.gradle +++ b/settings.gradle @@ -15,4 +15,4 @@ include 'api' include 'services:webservice' */ -rootProject.name = 'AutoPostTelegramBot' +rootProject.name = 'autoposttelegrambot' diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/Launch.kt b/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/Launch.kt deleted file mode 100644 index 6744732..0000000 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/Launch.kt +++ /dev/null @@ -1,122 +0,0 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot - -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.Config -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.FinalConfig -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.DefaultPluginManager -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.commonLogger -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.NewDefaultCoroutineScope -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.flow.collectWithErrors -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.load -import com.github.insanusmokrassar.TelegramBotAPI.requests.chat.get.GetChat -import com.github.insanusmokrassar.TelegramBotAPI.types.CallbackQuery.MessageDataCallbackQuery -import com.github.insanusmokrassar.TelegramBotAPI.types.message.abstracts.MediaGroupMessage -import com.github.insanusmokrassar.TelegramBotAPI.types.update.CallbackQueryUpdate -import com.github.insanusmokrassar.TelegramBotAPI.types.update.MediaGroupUpdates.SentMediaGroupUpdate -import com.github.insanusmokrassar.TelegramBotAPI.types.update.abstracts.BaseMessageUpdate -import com.github.insanusmokrassar.TelegramBotAPI.updateshandlers.FlowsUpdatesFilter -import com.github.insanusmokrassar.TelegramBotAPI.utils.extensions.UpdateReceiver -import kotlinx.coroutines.channels.BroadcastChannel -import kotlinx.coroutines.channels.Channel -import kotlinx.coroutines.flow.asFlow -import kotlinx.coroutines.launch -import kotlinx.coroutines.runBlocking - -const val extraSmallBroadcastCapacity = 4 -const val smallBroadcastCapacity = 8 -const val mediumBroadcastCapacity = 16 -const val largeBroadcastCapacity = 32 -const val extraLargeBroadcastCapacity = 64 - -const val commonListenersCapacity = mediumBroadcastCapacity - -val flowFilter = FlowsUpdatesFilter() - -private val messagesListener = BroadcastChannel(Channel.CONFLATED) -private val editedMessagesListener = BroadcastChannel(Channel.CONFLATED) -private val callbackQueryListener = BroadcastChannel(Channel.CONFLATED) -private val mediaGroupsListener = BroadcastChannel(Channel.CONFLATED) - -val checkedMessagesFlow = messagesListener.asFlow() -val checkedEditedMessagesFlow = editedMessagesListener.asFlow() -val checkedCallbacksQueriesFlow = callbackQueryListener.asFlow() -val checkedMediaGroupsFlow = mediaGroupsListener.asFlow() - -fun main(args: Array) { - val config: FinalConfig = load(args[0], Config.serializer()).finalConfig - - val bot = config.bot - - config.also { - PostsTable = it.postsTable - PostsMessagesTable = it.postsMessagesTable - } - - runBlocking { - commonLogger.info("Source chat: ${bot.execute(GetChat(config.sourceChatId))}") - commonLogger.info("Target chat: ${bot.execute(GetChat(config.targetChatId))}") - - val pluginManager = DefaultPluginManager( - config.pluginsConfigs - ) - - pluginManager.onInit( - bot, - config - ) - - NewDefaultCoroutineScope(8).apply { - val messageUpdatesCollector: UpdateReceiver = { - if (it.data.chat.id == config.sourceChatId && it.data !is MediaGroupMessage) { - messagesListener.send(it) - } - } - val editMessageUpdatesCollector: UpdateReceiver = { - if (it.data.chat.id == config.sourceChatId && it.data !is MediaGroupMessage) { - editedMessagesListener.send(it) - } - } - launch { - flowFilter.messageFlow.collectWithErrors(messageUpdatesCollector) - } - launch { - flowFilter.editedMessageFlow.collectWithErrors(editMessageUpdatesCollector) - } - launch { - flowFilter.channelPostFlow.collectWithErrors(messageUpdatesCollector) - } - launch { - flowFilter.editedChannelPostFlow.collectWithErrors(editMessageUpdatesCollector) - } - - launch { - flowFilter.callbackQueryFlow.collectWithErrors { - (it.data as? MessageDataCallbackQuery) ?.also { query -> - if (query.message.chat.id == config.sourceChatId) { - callbackQueryListener.send(it) - } - } - } - } - - val mediaGroupUpdatesCollector: UpdateReceiver = { mediaGroup -> - val mediaGroupChatId = mediaGroup.data.first().chat.id - if (mediaGroupChatId == config.sourceChatId) { - mediaGroupsListener.send(mediaGroup) - } - } - launch { - flowFilter.messageMediaGroupFlow.collectWithErrors(mediaGroupUpdatesCollector) - } - launch { - flowFilter.channelPostMediaGroupFlow.collectWithErrors(mediaGroupUpdatesCollector) - } - - config.subscribe( - flowFilter.filter, - this - ) - } - } -} diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/database/exceptions/CreationException.kt b/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/database/exceptions/CreationException.kt deleted file mode 100644 index df6a36e..0000000 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/database/exceptions/CreationException.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.base.database.exceptions - -class CreationException(message: String?) : Exception(message) diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/database/exceptions/NoRowFoundException.kt b/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/database/exceptions/NoRowFoundException.kt deleted file mode 100644 index b9e404a..0000000 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/database/exceptions/NoRowFoundException.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.base.database.exceptions - -class NoRowFoundException(message: String?) : Exception(message) diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/database/exceptions/NothingToSaveException.kt b/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/database/exceptions/NothingToSaveException.kt deleted file mode 100644 index 5918db0..0000000 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/database/exceptions/NothingToSaveException.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.base.database.exceptions - -class NothingToSaveException(message: String?) : Exception(message) diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/Config.kt b/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/Config.kt deleted file mode 100644 index af1c02b..0000000 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/Config.kt +++ /dev/null @@ -1,77 +0,0 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.base.models - -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.Plugin -import com.github.insanusmokrassar.AutoPostTelegramBot.plugins.base.commands.CommonKnownPostsTransactions -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.NewDefaultCoroutineScope -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor -import com.github.insanusmokrassar.TelegramBotAPI.types.ChatId -import com.github.insanusmokrassar.TelegramBotAPI.types.toChatId -import com.github.insanusmokrassar.TelegramBotAPI.updateshandlers.UpdatesFilter -import kotlinx.coroutines.CoroutineScope -import kotlinx.serialization.Serializable -import org.h2.Driver - -@Serializable -class Config ( - val targetChatId: Long, - val sourceChatId: Long, - val logsChatId: Long? = null, - val databaseConfig: DatabaseConfig = DatabaseConfig( - "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", - Driver::class.java.canonicalName, - "sa", - "" - ), - val clientConfig: HttpClientConfig? = null, - val plugins: List = emptyList(), - val commonBot: BotConfig? = null -) { - private val botConfig: BotConfig by lazy { - commonBot ?: throw IllegalStateException("You must set up \"commonBot\" field") - } - - val finalConfig: FinalConfig - @Throws(IllegalArgumentException::class) - get() = FinalConfig( - targetChatId.toChatId(), - sourceChatId.toChatId(), - (logsChatId ?: sourceChatId).toChatId(), - botConfig.createBot(), - databaseConfig, - plugins, - botConfig.webhookConfig, - botConfig.longPollingConfig() - ) -} - -data class FinalConfig ( - val targetChatId: ChatId, - val sourceChatId: ChatId, - val logsChatId: ChatId, - val bot: RequestsExecutor, - val databaseConfig: DatabaseConfig, - val pluginsConfigs: List = emptyList(), - private val webhookConfig: WebhookConfig? = null, - private val longPollingConfig: LongPollingConfig? = null -) { - val postsMessagesTable = PostsMessagesInfoTable(databaseConfig.database) - val postsTable = PostsBaseInfoTable(databaseConfig.database, postsMessagesTable) - - init { - CommonKnownPostsTransactions.updatePostsAndPostsMessagesTables(postsTable, postsMessagesTable) - } - - suspend fun subscribe(filter: UpdatesFilter, scope: CoroutineScope = NewDefaultCoroutineScope(4)) { - webhookConfig ?.setWebhook( - bot, - filter, - scope - ) ?: longPollingConfig ?.applyTo( - bot, - filter.asUpdateReceiver, - filter.allowedUpdates - ) ?.start(scope) - } -} diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/LongPollingConfig.kt b/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/LongPollingConfig.kt deleted file mode 100644 index 05b3ab7..0000000 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/LongPollingConfig.kt +++ /dev/null @@ -1,31 +0,0 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.base.models - -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor -import com.github.insanusmokrassar.TelegramBotAPI.bot.UpdatesPoller -import com.github.insanusmokrassar.TelegramBotAPI.types.ALL_UPDATES_LIST -import com.github.insanusmokrassar.TelegramBotAPI.types.update.abstracts.Update -import com.github.insanusmokrassar.TelegramBotAPI.updateshandlers.KtorUpdatesPoller -import com.github.insanusmokrassar.TelegramBotAPI.utils.extensions.UpdateReceiver -import kotlinx.serialization.Serializable - -@Serializable -data class LongPollingConfig( - val oneTimeLimit: Byte? = null, - val responseAwaitMillis: Long? = null -) { - fun applyTo( - bot: RequestsExecutor, - updatesReceiver: UpdateReceiver, - allowedUpdates: List = ALL_UPDATES_LIST, - exceptionsReceiver: (Exception) -> Boolean = { true } - ): UpdatesPoller { - return KtorUpdatesPoller( - bot, - (responseAwaitMillis ?.div(1000)) ?.toInt() ?: 30, - oneTimeLimit ?.toInt(), - allowedUpdates, - exceptionsReceiver, - updatesReceiver - ) - } -} diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/PostId.kt b/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/PostId.kt deleted file mode 100644 index 534b4d4..0000000 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/PostId.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.base.models - -typealias PostId = Int diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/PostMessage.kt b/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/PostMessage.kt deleted file mode 100644 index 1d785bf..0000000 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/PostMessage.kt +++ /dev/null @@ -1,23 +0,0 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.base.models - -import com.github.insanusmokrassar.TelegramBotAPI.types.MediaGroupIdentifier -import com.github.insanusmokrassar.TelegramBotAPI.types.MessageIdentifier -import com.github.insanusmokrassar.TelegramBotAPI.types.message.abstracts.MediaGroupMessage -import com.github.insanusmokrassar.TelegramBotAPI.types.message.abstracts.Message - -data class PostMessage( - val messageId: MessageIdentifier, - val mediaGroupId: MediaGroupIdentifier? = null -) { - var message: Message? = null - set(value) { - field ?.let { - throw IllegalStateException("Message already initialized") - } - field = value - } - - constructor(message: Message) : this(message.messageId, (message as? MediaGroupMessage) ?.mediaGroupId) { - this.message = message - } -} diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/WebhookConfig.kt b/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/WebhookConfig.kt deleted file mode 100644 index 2bd2063..0000000 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/WebhookConfig.kt +++ /dev/null @@ -1,37 +0,0 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.base.models - -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.NewDefaultCoroutineScope -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor -import com.github.insanusmokrassar.TelegramBotAPI.requests.abstracts.toInputFile -import com.github.insanusmokrassar.TelegramBotAPI.updateshandlers.UpdatesFilter -import com.github.insanusmokrassar.TelegramBotAPI.updateshandlers.webhook.WebhookPrivateKeyConfig -import com.github.insanusmokrassar.TelegramBotAPI.utils.extensions.setWebhook -import io.ktor.server.cio.CIO -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Job -import kotlinx.serialization.Serializable -import java.io.File - -@Serializable -data class WebhookConfig( - val url: String, - val port: Int, - val certificatePath: String? = null, - val maxConnections: Int? = null, - val privateKeyConfig: WebhookPrivateKeyConfig? = null -) { - suspend fun setWebhook( - requestsExecutor: RequestsExecutor, - filter: UpdatesFilter, - scope: CoroutineScope = NewDefaultCoroutineScope(4) - ): Job = requestsExecutor.setWebhook( - url, - port, - filter, - CIO, - certificatePath ?.let { File(it).toInputFile() }, - privateKeyConfig, - scope, - maxConnections - ) -} \ No newline at end of file diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/BotLogger.kt b/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/BotLogger.kt deleted file mode 100644 index 06c8e5e..0000000 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/BotLogger.kt +++ /dev/null @@ -1,20 +0,0 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins - -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.BotConfig -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.FinalConfig -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.Plugin -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.PluginManager -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.initHandler -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor -import kotlinx.serialization.Serializable - -@Serializable -class BotLogger( - private val config: BotConfig? = null -) : Plugin { - override suspend fun onInit(executor: RequestsExecutor, baseConfig: FinalConfig, pluginManager: PluginManager) { - val logExecutor = config ?.createBot() ?: executor - super.onInit(logExecutor, baseConfig, pluginManager) - initHandler(logExecutor, baseConfig.logsChatId) - } -} \ No newline at end of file diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/callbacks/OnMediaGroup.kt b/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/callbacks/OnMediaGroup.kt deleted file mode 100644 index c0f8e7d..0000000 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/callbacks/OnMediaGroup.kt +++ /dev/null @@ -1,44 +0,0 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.base.callbacks - -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.PostTransaction -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.PostMessage -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.commonLogger -import com.github.insanusmokrassar.AutoPostTelegramBot.checkedMediaGroupsFlow -import com.github.insanusmokrassar.AutoPostTelegramBot.plugins.base.commands.CommonKnownPostsTransactions -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.flow.collectWithErrors -import kotlinx.coroutines.* - -internal fun CoroutineScope.enableOnMediaGroupsCallback( - postsTable: PostsBaseInfoTable, - postsMessagesTable: PostsMessagesInfoTable -): Job = launch { - checkedMediaGroupsFlow.collectWithErrors( - { update, e -> - commonLogger.throwing( - "Media groups AutoPost callback", - "Perform update: $update", - e - ) - } - ) { - val messages = it.data - val id = messages.first().chat.id - CommonKnownPostsTransactions[id] ?.also { - messages.forEach { message -> - it.addMessageId(PostMessage(message)) - } - return@collectWithErrors - } ?:also { - PostTransaction( - postsTable, - postsMessagesTable - ).use { transaction -> - messages.forEach { message -> - transaction.addMessageId(PostMessage(message)) - } - } - } - } -} diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/callbacks/OnMessage.kt b/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/callbacks/OnMessage.kt deleted file mode 100644 index bca4b85..0000000 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/callbacks/OnMessage.kt +++ /dev/null @@ -1,52 +0,0 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.base.callbacks - -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.PostTransaction -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.PostMessage -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.commonLogger -import com.github.insanusmokrassar.AutoPostTelegramBot.checkedMessagesFlow -import com.github.insanusmokrassar.AutoPostTelegramBot.plugins.base.commands.CommonKnownPostsTransactions -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.flow.collectWithErrors -import com.github.insanusmokrassar.TelegramBotAPI.types.ChatIdentifier -import com.github.insanusmokrassar.TelegramBotAPI.types.MessageEntity.textsources.BotCommandTextSource -import com.github.insanusmokrassar.TelegramBotAPI.types.message.abstracts.ContentMessage -import com.github.insanusmokrassar.TelegramBotAPI.types.message.content.TextContent -import kotlinx.coroutines.* - -internal fun CoroutineScope.enableOnMessageCallback( - postsTable: PostsBaseInfoTable, - postsMessagesTable: PostsMessagesInfoTable -): Job = launch { - checkedMessagesFlow.collectWithErrors( - { message, e -> - commonLogger.throwing( - "On message AutoPost callback", - "Perform message: $message", - e - ) - } - ) { - val message = it.data - if (message is ContentMessage<*>) { - (message.content as? TextContent) ?.also { content -> - if (content.entities.firstOrNull { it.source is BotCommandTextSource } != null) { - return@collectWithErrors - } - } - } - - val chatId: ChatIdentifier = message.chat.id - CommonKnownPostsTransactions[chatId] ?.also { transaction -> - transaction.addMessageId(PostMessage(message)) - return@collectWithErrors - } ?: also { - PostTransaction( - postsTable, - postsMessagesTable - ).use { transaction -> - transaction.addMessageId(PostMessage(message)) - } - } - } -} diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/commands/FixPost.kt b/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/commands/FixPost.kt deleted file mode 100644 index 7a6695e..0000000 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/commands/FixPost.kt +++ /dev/null @@ -1,24 +0,0 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.base.commands - -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.exceptions.NothingToSaveException -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.commonLogger -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.commands.buildCommandFlow -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.flow.collectWithErrors -import com.github.insanusmokrassar.TelegramBotAPI.types.ChatIdentifier -import com.github.insanusmokrassar.TelegramBotAPI.types.message.abstracts.FromUserMessage -import kotlinx.coroutines.* - -val fixPostRegex: Regex = Regex("^fixPost$") - -internal fun CoroutineScope.enableFixPostCommand(): Job = launch { - buildCommandFlow(fixPostRegex).collectWithErrors { message -> - try { - val userId: ChatIdentifier? = (message as? FromUserMessage) ?.user ?.id ?: message.chat.id - userId ?.let { - CommonKnownPostsTransactions[it] ?.saveNewPost() ?: throw NothingToSaveException("Transaction was not started") - } - } catch (e: NothingToSaveException) { - commonLogger.warning("Nothing to save: ${e.message}") - } - } -} diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/choosers/RateChooser.kt b/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/choosers/RateChooser.kt deleted file mode 100644 index d859b66..0000000 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/choosers/RateChooser.kt +++ /dev/null @@ -1,26 +0,0 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.choosers - -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.FinalConfig -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.PluginManager -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.abstractions.Chooser -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.abstractions.RatingPlugin -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.findFirstPlugin -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor - - -abstract class RateChooser : Chooser { - protected lateinit var ratingPlugin: RatingPlugin - private set - - protected lateinit var postsTable: PostsBaseInfoTable - protected lateinit var postsMessagesTable: PostsMessagesInfoTable - - override suspend fun onInit(executor: RequestsExecutor, baseConfig: FinalConfig, pluginManager: PluginManager) { - super.onInit(executor, baseConfig, pluginManager) - ratingPlugin = pluginManager.findFirstPlugin() ?: return - postsTable = baseConfig.postsTable - postsMessagesTable = baseConfig.postsMessagesTable - } -} \ No newline at end of file diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/publishers/Publisher.kt b/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/publishers/Publisher.kt deleted file mode 100644 index a20f44d..0000000 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/publishers/Publisher.kt +++ /dev/null @@ -1,7 +0,0 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.publishers - -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.Plugin - -interface Publisher : Plugin { - suspend fun publishPost(postId: Int) -} \ No newline at end of file diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/CallbackQueryReceivers/CallbackQueryReceiver.kt b/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/CallbackQueryReceivers/CallbackQueryReceiver.kt deleted file mode 100644 index 534a80e..0000000 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/CallbackQueryReceivers/CallbackQueryReceiver.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.utils.CallbackQueryReceivers - -import com.github.insanusmokrassar.AutoPostTelegramBot.checkedCallbacksQueriesFlow -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.NewDefaultCoroutineScope -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.flow.collectWithErrors -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor -import com.github.insanusmokrassar.TelegramBotAPI.types.update.CallbackQueryUpdate -import kotlinx.coroutines.launch -import java.lang.ref.WeakReference - -private val CallbackQueryReceiversScope = NewDefaultCoroutineScope() - -abstract class CallbackQueryReceiver( - executor: RequestsExecutor -) { - protected val executorWR = WeakReference(executor) - - init { - CallbackQueryReceiversScope.launch { - checkedCallbacksQueriesFlow.collectWithErrors(action = ::invoke) - } - } - - abstract suspend fun invoke(update: CallbackQueryUpdate) -} \ No newline at end of file diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/PluginsSerializer.kt b/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/PluginsSerializer.kt deleted file mode 100644 index 219ef88..0000000 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/PluginsSerializer.kt +++ /dev/null @@ -1,41 +0,0 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.utils - -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.Plugin -import com.github.insanusmokrassar.TelegramBotAPI.utils.toJson -import kotlinx.serialization.* -import kotlinx.serialization.internal.ArrayListSerializer -import kotlinx.serialization.internal.StringDescriptor -import kotlinx.serialization.json.* - -@Serializer(Plugin::class) -internal object PluginSerializer : KSerializer { - override val descriptor: SerialDescriptor = StringDescriptor.withName(Plugin::class.simpleName ?: "Plugin") - - override fun serialize(encoder: Encoder, obj: Plugin) { - val array = JsonArray( - listOf( - JsonPrimitive(obj::class.java.canonicalName), - obj.toJson(serializerByTypeToken(obj::class.java)) - ) - ) - JsonArraySerializer.serialize( - encoder, - array - ) - } - - @ImplicitReflectionSerializer - override fun deserialize(decoder: Decoder): Plugin { - val decoded = decoder.decode(JsonArraySerializer) - val expectedClass = decoded.getPrimitive(0).content - val expectedArgumentObject = decoded.getObjectOrNull(1) - val serializer = Class.forName(expectedClass).kotlin.serializer() - val argumentsObject = expectedArgumentObject ?.toString() ?: JsonObject(emptyMap()).toString() - return Json.nonstrict.parse( - serializer, - argumentsObject - ) as Plugin - } -} - -object PluginsListSerializer: KSerializer> by ArrayListSerializer(PluginSerializer) diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/commands/Command.kt b/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/commands/Command.kt deleted file mode 100644 index 2416ef6..0000000 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/commands/Command.kt +++ /dev/null @@ -1,61 +0,0 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.utils.commands - -import com.github.insanusmokrassar.AutoPostTelegramBot.checkedMessagesFlow -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.flow.collectWithErrors -import com.github.insanusmokrassar.TelegramBotAPI.types.MessageEntity.textsources.BotCommandTextSource -import com.github.insanusmokrassar.TelegramBotAPI.types.UpdateIdentifier -import com.github.insanusmokrassar.TelegramBotAPI.types.message.abstracts.CommonMessage -import com.github.insanusmokrassar.TelegramBotAPI.types.message.content.TextContent -import com.github.insanusmokrassar.TelegramBotAPI.types.update.abstracts.BaseMessageUpdate -import com.github.insanusmokrassar.TelegramBotAPI.utils.extensions.UpdateReceiver -import kotlinx.coroutines.* -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.mapNotNull - -abstract class Command { - val callback: UpdateReceiver - get() = this::invoke - protected abstract val commandRegex: Regex - - init { - CoroutineScope(Dispatchers.Default).launch { - checkedMessagesFlow.collectWithErrors { - invoke(it) - } - } - } - - suspend fun invoke(p1: BaseMessageUpdate) { - (p1.data as? CommonMessage<*>) ?.let { message -> - (message.content as? TextContent) ?.also { - it.entities.firstOrNull { textPart -> - val source = textPart.source - source is BotCommandTextSource && (commandRegex.matches(source.command)) - } ?.also { - onCommand(p1.updateId, message) - } ?: if (commandRegex.matches(it.text)) { - onCommand(p1.updateId, message) - } - } - } - } - - abstract suspend fun onCommand(updateId: UpdateIdentifier, message: CommonMessage<*>) -} - -fun buildCommandFlow( - commandRegex: Regex -): Flow> = checkedMessagesFlow.mapNotNull { - val data = it.data - if (data is CommonMessage<*>) { - val contentAsText = data.content as? TextContent ?: return@mapNotNull null - val contentEntities = contentAsText.entities - contentEntities.firstOrNull { textPart -> - val source = textPart.source - source is BotCommandTextSource && commandRegex.matches(source.command) - } ?.let { - return@mapNotNull data as CommonMessage - } - } - null -} diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/commands/CommandPlugin.kt b/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/commands/CommandPlugin.kt deleted file mode 100644 index ef6822e..0000000 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/commands/CommandPlugin.kt +++ /dev/null @@ -1,20 +0,0 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.utils.commands - -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.FinalConfig -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.Plugin -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.PluginManager -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor - -import java.lang.ref.WeakReference - -abstract class CommandPlugin : Command(), Plugin { - protected var botWR: WeakReference? = null - - override suspend fun onInit( - executor: RequestsExecutor, - baseConfig: FinalConfig, - pluginManager: PluginManager - ) { - botWR = WeakReference(executor) - } -} \ No newline at end of file diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/BroadcastChannel.kt b/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/BroadcastChannel.kt deleted file mode 100644 index 7dcdb8b..0000000 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/BroadcastChannel.kt +++ /dev/null @@ -1,114 +0,0 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions - -import com.github.insanusmokrassar.AutoPostTelegramBot.extraSmallBroadcastCapacity -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.NewDefaultCoroutineScope -import kotlinx.coroutines.* -import kotlinx.coroutines.channels.BroadcastChannel -import kotlinx.coroutines.channels.ReceiveChannel -import java.util.concurrent.TimeUnit - -fun ReceiveChannel.subscribeChecking( - throwableHandler: (Throwable) -> Boolean = { - it.printStackTrace() - true - }, - scope: CoroutineScope = NewDefaultCoroutineScope(1), - by: suspend (T) -> Boolean -) { - val channel = this - scope.launch { - for (data in channel) { - launch { - try { - if (!by(data)) { - channel.cancel() - } - } catch (e: Throwable) { - if (!throwableHandler(e)) { - channel.cancel() - } - } - } - } - } -} - -fun ReceiveChannel.subscribe( - throwableHandler: (Throwable) -> Boolean = { - it.printStackTrace() - true - }, - scope: CoroutineScope = NewDefaultCoroutineScope(1), - by: suspend (T) -> Unit -) { - return subscribeChecking(throwableHandler, scope) { - by(it) - true - } -} - -fun ReceiveChannel.debounce( - delay: Long, - timeUnit: TimeUnit = TimeUnit.MILLISECONDS, - scope: CoroutineScope = NewDefaultCoroutineScope(1), - resultBroadcastChannelCapacity: Int = extraSmallBroadcastCapacity -): BroadcastChannel { - return BroadcastChannel(resultBroadcastChannelCapacity).also { outBroadcast -> - var lastReceived: Job? = null - subscribe(scope = scope) { - lastReceived ?.cancel() - lastReceived = scope.launch { - delay(timeUnit.toMillis(delay)) - - outBroadcast.send(it) - } - } - } -} - -fun BroadcastChannel.subscribeChecking( - throwableHandler: (Throwable) -> Boolean = { - it.printStackTrace() - true - }, - scope: CoroutineScope = NewDefaultCoroutineScope(1), - by: suspend (T) -> Boolean -): ReceiveChannel { - return openSubscription().apply { - subscribeChecking( - throwableHandler, - scope, - by - ) - } -} - -fun BroadcastChannel.subscribe( - throwableHandler: (Throwable) -> Boolean = { - it.printStackTrace() - true - }, - scope: CoroutineScope = NewDefaultCoroutineScope(1), - by: suspend (T) -> Unit -): ReceiveChannel { - return openSubscription().apply { - subscribe(throwableHandler, scope) { - by(it) - } - } -} - - -fun BroadcastChannel.debounce( - delay: Long, - timeUnit: TimeUnit = TimeUnit.MILLISECONDS, - scope: CoroutineScope = NewDefaultCoroutineScope(1), - resultBroadcastChannelCapacity: Int = extraSmallBroadcastCapacity -): BroadcastChannel { - return openSubscription().debounce( - delay, - timeUnit, - scope, - resultBroadcastChannelCapacity - ) -} diff --git a/src/main/kotlin/dev/inmo/AutoPostTelegramBot/Launch.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/Launch.kt new file mode 100644 index 0000000..0874938 --- /dev/null +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/Launch.kt @@ -0,0 +1,89 @@ +package dev.inmo.AutoPostTelegramBot + +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsMessagesTable +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsTable +import dev.inmo.AutoPostTelegramBot.base.models.Config +import dev.inmo.AutoPostTelegramBot.base.models.FinalConfig +import dev.inmo.AutoPostTelegramBot.base.plugins.DefaultPluginManager +import dev.inmo.AutoPostTelegramBot.base.plugins.commonLogger +import dev.inmo.AutoPostTelegramBot.utils.load +import dev.inmo.micro_utils.coroutines.* +import dev.inmo.tgbotapi.extensions.api.chat.get.getChat +import dev.inmo.tgbotapi.extensions.utils.updates.* +import dev.inmo.tgbotapi.types.CallbackQuery.MessageDataCallbackQuery +import dev.inmo.tgbotapi.types.message.abstracts.MediaGroupMessage +import dev.inmo.tgbotapi.types.update.CallbackQueryUpdate +import dev.inmo.tgbotapi.types.update.MediaGroupUpdates.* +import dev.inmo.tgbotapi.types.update.abstracts.* +import dev.inmo.tgbotapi.updateshandlers.FlowsUpdatesFilter +import kotlinx.coroutines.* +import kotlinx.coroutines.flow.* + +const val extraSmallBroadcastCapacity = 4 +const val smallBroadcastCapacity = 8 +const val mediumBroadcastCapacity = 16 +const val largeBroadcastCapacity = 32 +const val extraLargeBroadcastCapacity = 64 + +const val commonListenersCapacity = mediumBroadcastCapacity + +private val scope = CoroutineScope(Dispatchers.Default) + +val flowFilter = FlowsUpdatesFilter() + +lateinit var checkedMessagesFlow: Flow + private set +lateinit var checkedEditedMessagesFlow: Flow + private set +lateinit var checkedCallbacksQueriesFlow: Flow + private set +lateinit var checkedMediaGroupsFlow: Flow + private set + +fun main(args: Array) { + val config: FinalConfig = load(args[0], Config.serializer()).finalConfig + + checkedMessagesFlow = (flowFilter.messageFlow + flowFilter.channelPostFlow).filterBaseMessageUpdatesByChatId( + config.sourceChatId + ).filter { it.data !is MediaGroupMessage<*> } + checkedEditedMessagesFlow = (flowFilter.editedMessageFlow + flowFilter.editedChannelPostFlow).filterBaseMessageUpdatesByChatId( + config.sourceChatId + ).filter { it.data !is MediaGroupMessage<*> } + checkedCallbacksQueriesFlow = flowFilter.callbackQueryFlow.filter { + (it.data as? MessageDataCallbackQuery) ?.let { query -> + query.message.chat.id == config.sourceChatId + } ?: false + } + checkedMediaGroupsFlow = (flowFilter.channelPostMediaGroupFlow + flowFilter.messageMediaGroupFlow).filterSentMediaGroupUpdatesByChatId( + config.sourceChatId + ) + + val bot = config.bot + + config.also { + PostsTable = it.postsTable + PostsMessagesTable = it.postsMessagesTable + } + + scope.launch { + commonLogger.info("Source chat: ${bot.getChat(config.sourceChatId)}") + commonLogger.info("Target chat: ${bot.getChat(config.targetChatId)}") + + val pluginManager = DefaultPluginManager( + config.pluginsConfigs + ) + + pluginManager.onInit( + bot, + config + ) + + config.startGettingUpdates( + flowFilter, + scope + ) + } + runBlocking { + scope.coroutineContext.job.join() + } +} diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/database/PostTransaction.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/database/PostTransaction.kt similarity index 61% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/database/PostTransaction.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/database/PostTransaction.kt index 449a1e0..f3ab97c 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/database/PostTransaction.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/database/PostTransaction.kt @@ -1,19 +1,24 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.base.database +package dev.inmo.AutoPostTelegramBot.base.database -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.exceptions.NothingToSaveException -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.* -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.PostId -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.PostMessage -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.NewDefaultCoroutineScope +import dev.inmo.AutoPostTelegramBot.base.database.exceptions.NothingToSaveException +import dev.inmo.AutoPostTelegramBot.base.database.tables.* +import dev.inmo.AutoPostTelegramBot.base.models.PostId +import dev.inmo.AutoPostTelegramBot.base.models.PostMessage +import dev.inmo.AutoPostTelegramBot.extraLargeBroadcastCapacity +import dev.inmo.AutoPostTelegramBot.utils.NewDefaultCoroutineScope import kotlinx.coroutines.channels.BroadcastChannel -import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.launch import java.io.Closeable -val transactionStartedChannel = BroadcastChannel(Channel.CONFLATED) -val transactionMessageAddedChannel = BroadcastChannel>(Channel.CONFLATED) -val transactionMessageRemovedChannel = BroadcastChannel(Channel.CONFLATED) -val transactionCompletedChannel = BroadcastChannel(Channel.CONFLATED) +private val transactionStartedChannel = BroadcastChannel(extraLargeBroadcastCapacity) +val transactionStartedFlow = transactionStartedChannel.asFlow() +private val transactionMessageAddedChannel = BroadcastChannel>(extraLargeBroadcastCapacity) +val transactionMessageAddedFlow = transactionMessageAddedChannel.asFlow() +private val transactionMessageRemovedChannel = BroadcastChannel(extraLargeBroadcastCapacity) +val transactionMessageRemovedFlow = transactionMessageRemovedChannel.asFlow() +private val transactionCompletedChannel = BroadcastChannel(extraLargeBroadcastCapacity) +val transactionCompletedFlow = transactionCompletedChannel.asFlow() val PostTransactionsScope = NewDefaultCoroutineScope() @@ -28,7 +33,7 @@ class PostTransaction( init { PostTransactionsScope.launch { - transactionStartedChannel.send(Unit) + transactionStartedChannel.send(this@PostTransaction) } } diff --git a/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/database/exceptions/CreationException.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/database/exceptions/CreationException.kt new file mode 100644 index 0000000..c56db29 --- /dev/null +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/database/exceptions/CreationException.kt @@ -0,0 +1,3 @@ +package dev.inmo.AutoPostTelegramBot.base.database.exceptions + +class CreationException(message: String?) : Exception(message) diff --git a/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/database/exceptions/NoRowFoundException.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/database/exceptions/NoRowFoundException.kt new file mode 100644 index 0000000..2b5e201 --- /dev/null +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/database/exceptions/NoRowFoundException.kt @@ -0,0 +1,3 @@ +package dev.inmo.AutoPostTelegramBot.base.database.exceptions + +class NoRowFoundException(message: String?) : Exception(message) diff --git a/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/database/exceptions/NothingToSaveException.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/database/exceptions/NothingToSaveException.kt new file mode 100644 index 0000000..0eb20d8 --- /dev/null +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/database/exceptions/NothingToSaveException.kt @@ -0,0 +1,3 @@ +package dev.inmo.AutoPostTelegramBot.base.database.exceptions + +class NothingToSaveException(message: String?) : Exception(message) diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/database/tables/PostsMessagesTable.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/database/tables/PostsMessagesTable.kt similarity index 83% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/database/tables/PostsMessagesTable.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/database/tables/PostsMessagesTable.kt index fd36af9..3d3e678 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/database/tables/PostsMessagesTable.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/database/tables/PostsMessagesTable.kt @@ -1,10 +1,11 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables +package dev.inmo.AutoPostTelegramBot.base.database.tables -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.PostId -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.PostMessage -import com.github.insanusmokrassar.AutoPostTelegramBot.mediumBroadcastCapacity -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.NewDefaultCoroutineScope -import com.github.insanusmokrassar.TelegramBotAPI.types.MessageIdentifier +import dev.inmo.AutoPostTelegramBot.base.models.PostId +import dev.inmo.AutoPostTelegramBot.base.models.PostMessage +import dev.inmo.AutoPostTelegramBot.mediumBroadcastCapacity +import dev.inmo.AutoPostTelegramBot.utils.NewDefaultCoroutineScope +import dev.inmo.tgbotapi.types.MediaGroupIdentifier +import dev.inmo.tgbotapi.types.MessageIdentifier import kotlinx.coroutines.channels.BroadcastChannel import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.launch @@ -28,9 +29,10 @@ class PostsMessagesInfoTable(private val database: Database) : Table() { val removedMessagesOfPostFlow = removedMessagesOfPost.asFlow() val removedMessageOfPostFlow = removedMessageOfPost.asFlow() - private val messageIdColumn = long("messageId").primaryKey() - private val mediaGroupIdColumn = text("mediaGroupId").nullable() - private val postIdColumn = integer("postId") + private val messageIdColumn: Column = long("messageId") + override val primaryKey: PrimaryKey = PrimaryKey(messageIdColumn) + private val mediaGroupIdColumn: Column = text("mediaGroupId").nullable() + private val postIdColumn: Column = integer("postId") init { transaction(database) { diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/database/tables/PostsTable.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/database/tables/PostsTable.kt similarity index 85% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/database/tables/PostsTable.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/database/tables/PostsTable.kt index 211c438..f9eb975 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/database/tables/PostsTable.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/database/tables/PostsTable.kt @@ -1,15 +1,16 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables +package dev.inmo.AutoPostTelegramBot.base.database.tables -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.exceptions.CreationException -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.exceptions.NoRowFoundException -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.PostId -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.NewDefaultCoroutineScope -import com.github.insanusmokrassar.TelegramBotAPI.types.MessageIdentifier +import dev.inmo.AutoPostTelegramBot.base.database.exceptions.CreationException +import dev.inmo.AutoPostTelegramBot.base.database.exceptions.NoRowFoundException +import dev.inmo.AutoPostTelegramBot.base.models.PostId +import dev.inmo.AutoPostTelegramBot.utils.NewDefaultCoroutineScope +import dev.inmo.tgbotapi.types.MessageIdentifier import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.channels.BroadcastChannel import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.launch import org.jetbrains.exposed.sql.* +import org.jetbrains.exposed.sql.jodatime.datetime import org.jetbrains.exposed.sql.transactions.transaction import org.joda.time.DateTime @@ -32,7 +33,8 @@ class PostsBaseInfoTable( val postRemovedChannel = BroadcastChannel(Channel.CONFLATED) val postMessageRegisteredChannel = BroadcastChannel(Channel.CONFLATED) - private val idColumn = integer("id").primaryKey().autoIncrement() + private val idColumn = integer("id").autoIncrement() + override val primaryKey: PrimaryKey = PrimaryKey(idColumn) private val postRegisteredMessageIdColumn = long("postRegistered").nullable() private val postDateTimeColumn = datetime("postDateTime").default(DateTime.now()) @@ -47,7 +49,7 @@ class PostsBaseInfoTable( return transaction(database) { insert { it[postDateTimeColumn] = DateTime.now() - }[idColumn] ?.also { + }[idColumn].also { coroutinesScope.launch { postAllocatedChannel.send(it) } @@ -111,4 +113,4 @@ class PostsBaseInfoTable( }.firstOrNull() ?.get(postDateTimeColumn) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/BotConfig.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/BotConfig.kt similarity index 69% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/BotConfig.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/BotConfig.kt index cde7432..57b5788 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/BotConfig.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/BotConfig.kt @@ -1,8 +1,9 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.base.models +package dev.inmo.AutoPostTelegramBot.base.models -import com.github.insanusmokrassar.TelegramBotAPI.bot.Ktor.KtorRequestsExecutor -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor -import com.github.insanusmokrassar.TelegramBotAPI.utils.TelegramAPIUrlsKeeper +import dev.inmo.tgbotapi.bot.Ktor.KtorRequestsExecutor +import dev.inmo.tgbotapi.bot.RequestsExecutor +import dev.inmo.tgbotapi.utils.TelegramAPIUrlsKeeper +import dev.inmo.tgbotapi.utils.telegramBotAPIDefaultUrl import io.ktor.client.HttpClient import io.ktor.client.engine.okhttp.OkHttp import kotlinx.serialization.Serializable @@ -11,19 +12,19 @@ import kotlinx.serialization.Transient @Serializable data class BotConfig( val botToken: String, + val apiUrl: String = telegramBotAPIDefaultUrl, val clientConfig: HttpClientConfig? = null, val webhookConfig: WebhookConfig? = null, private var longPollingConfig: LongPollingConfig? = null ) { @Transient - val telegramAPIUrlsKeeper = TelegramAPIUrlsKeeper(botToken) + val telegramAPIUrlsKeeper = TelegramAPIUrlsKeeper(botToken, apiUrl) fun longPollingConfig(): LongPollingConfig = longPollingConfig ?.let { it.copy( responseAwaitMillis = it.responseAwaitMillis ?: clientConfig ?.readTimeout ) } ?: LongPollingConfig( - null, clientConfig ?.readTimeout ).also { longPollingConfig = it diff --git a/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/Config.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/Config.kt new file mode 100644 index 0000000..459d664 --- /dev/null +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/Config.kt @@ -0,0 +1,93 @@ +package dev.inmo.AutoPostTelegramBot.base.models + +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable +import dev.inmo.AutoPostTelegramBot.base.plugins.Plugin +import dev.inmo.AutoPostTelegramBot.plugins.base.commands.CommonKnownPostsTransactions +import dev.inmo.AutoPostTelegramBot.plugins.base.commands.PostsTransactions +import dev.inmo.AutoPostTelegramBot.utils.NewDefaultCoroutineScope +import dev.inmo.AutoPostTelegramBot.utils.extensions.sendToLogger +import dev.inmo.micro_utils.coroutines.ExceptionHandler +import dev.inmo.tgbotapi.bot.RequestsExecutor +import dev.inmo.tgbotapi.types.ChatId +import dev.inmo.tgbotapi.types.toChatId +import dev.inmo.tgbotapi.updateshandlers.UpdatesFilter +import kotlinx.coroutines.CoroutineScope +import kotlinx.serialization.Serializable +import org.h2.Driver + +@Serializable +class Config ( + val targetChatId: Long, + val sourceChatId: Long, + val logsChatId: Long? = null, + val databaseConfig: DatabaseConfig = DatabaseConfig( + "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", + Driver::class.java.canonicalName, + "sa", + "" + ), + val clientConfig: HttpClientConfig? = null, + val plugins: List = emptyList(), + val commonBot: BotConfig? = null +) { + private val botConfig: BotConfig by lazy { + commonBot ?: throw IllegalStateException("You must set up \"commonBot\" field") + } + + val finalConfig: FinalConfig + @Throws(IllegalArgumentException::class) + get() = FinalConfig( + targetChatId.toChatId(), + sourceChatId.toChatId(), + (logsChatId ?: sourceChatId).toChatId(), + botConfig.createBot(), + databaseConfig, + plugins, + botConfig.webhookConfig, + botConfig.longPollingConfig() + ) +} + +data class FinalConfig ( + val targetChatId: ChatId, + val sourceChatId: ChatId, + val logsChatId: ChatId, + val bot: RequestsExecutor, + val databaseConfig: DatabaseConfig, + val pluginsConfigs: List = emptyList(), + private val webhookConfig: WebhookConfig? = null, + private val longPollingConfig: LongPollingConfig? = null, + private val errorsVerbose: Boolean = false +) { + val postsMessagesTable = PostsMessagesInfoTable(databaseConfig.database) + val postsTable = PostsBaseInfoTable(databaseConfig.database, postsMessagesTable) + + init { + CommonKnownPostsTransactions = PostsTransactions(postsTable, postsMessagesTable) + } + + private val exceptionHandler: ExceptionHandler? = if (errorsVerbose) { + { bot.sendToLogger(it, "Long polling getting updates") } + } else { + null + } + + suspend fun startGettingUpdates(filter: UpdatesFilter, scope: CoroutineScope = NewDefaultCoroutineScope(4)) { + webhookConfig ?.apply { + startWebhookServer( + bot, + filter, + scope, + exceptionHandler + ) + } ?: longPollingConfig ?.apply { + startLongPollingListening( + bot, + filter, + scope, + exceptionHandler + ) + } ?: error("Webhooks or long polling way for updates retrieving must be used, but nothing configured") + } +} diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/DatabaseConfig.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/DatabaseConfig.kt similarity index 93% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/DatabaseConfig.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/DatabaseConfig.kt index 6c63c84..cabb45e 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/DatabaseConfig.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/DatabaseConfig.kt @@ -1,4 +1,4 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.base.models +package dev.inmo.AutoPostTelegramBot.base.models import kotlinx.serialization.Serializable import kotlinx.serialization.Transient diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/HttpClientConfig.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/HttpClientConfig.kt similarity index 63% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/HttpClientConfig.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/HttpClientConfig.kt index 7f6e8f0..c6ddf5d 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/HttpClientConfig.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/HttpClientConfig.kt @@ -1,9 +1,9 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.base.models +package dev.inmo.AutoPostTelegramBot.base.models import io.ktor.client.engine.okhttp.OkHttpConfig import kotlinx.serialization.Serializable import kotlinx.serialization.Transient -import okhttp3.Credentials +import okhttp3.* import java.net.InetSocketAddress import java.net.Proxy import java.util.concurrent.TimeUnit @@ -30,14 +30,17 @@ data class HttpClientConfig( ) ) proxy.password ?.let { password -> - proxyAuthenticator { _, response -> - response.request().newBuilder().apply { - addHeader( - "Proxy-Authorization", - Credentials.basic(proxy.username ?: "", password) - ) - }.build() - } + proxyAuthenticator ( + object : Authenticator { + override fun authenticate(route: Route?, response: Response): Request? { + return response.request.newBuilder().apply { + addHeader( + "Proxy-Authorization", Credentials.basic(proxy.username ?: "", password) + ) + }.build() + } + } + ) } } connectTimeout(connectTimeout, TimeUnit.MILLISECONDS) diff --git a/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/LongPollingConfig.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/LongPollingConfig.kt new file mode 100644 index 0000000..bad0af4 --- /dev/null +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/LongPollingConfig.kt @@ -0,0 +1,30 @@ +package dev.inmo.AutoPostTelegramBot.base.models + +import dev.inmo.micro_utils.coroutines.ExceptionHandler +import dev.inmo.tgbotapi.bot.RequestsExecutor +import dev.inmo.tgbotapi.extensions.api.webhook.deleteWebhook +import dev.inmo.tgbotapi.extensions.utils.updates.retrieving.startGettingOfUpdatesByLongPolling +import dev.inmo.tgbotapi.updateshandlers.UpdatesFilter +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.serialization.Serializable + +@Serializable +data class LongPollingConfig( + val responseAwaitMillis: Long? = null +) { + suspend fun startLongPollingListening( + bot: RequestsExecutor, + updatesFilter: UpdatesFilter, + scope: CoroutineScope, + exceptionsReceiver: ExceptionHandler? = null + ): Job { + bot.deleteWebhook() + return bot.startGettingOfUpdatesByLongPolling( + updatesFilter, + (responseAwaitMillis ?.div(1000)) ?.toInt() ?: 30, + exceptionsReceiver, + scope + ) + } +} diff --git a/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/PostId.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/PostId.kt new file mode 100644 index 0000000..4b59962 --- /dev/null +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/PostId.kt @@ -0,0 +1,3 @@ +package dev.inmo.AutoPostTelegramBot.base.models + +typealias PostId = Int diff --git a/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/PostMessage.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/PostMessage.kt new file mode 100644 index 0000000..419cd58 --- /dev/null +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/PostMessage.kt @@ -0,0 +1,24 @@ +package dev.inmo.AutoPostTelegramBot.base.models + +import dev.inmo.tgbotapi.extensions.utils.asMediaGroupMessage +import dev.inmo.tgbotapi.types.MediaGroupIdentifier +import dev.inmo.tgbotapi.types.MessageIdentifier +import dev.inmo.tgbotapi.types.message.abstracts.MediaGroupMessage +import dev.inmo.tgbotapi.types.message.abstracts.Message + +data class PostMessage( + val messageId: MessageIdentifier, + val mediaGroupId: MediaGroupIdentifier? = null +) { + var message: Message? = null + set(value) { + field ?.let { + throw IllegalStateException("Message already initialized") + } + field = value + } + + constructor(message: Message) : this(message.messageId, message.asMediaGroupMessage() ?.mediaGroupId) { + this.message = message + } +} diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/ProxySettings.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/ProxySettings.kt similarity index 75% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/ProxySettings.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/ProxySettings.kt index eb78282..cfd0d2d 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/models/ProxySettings.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/ProxySettings.kt @@ -1,4 +1,4 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.base.models +package dev.inmo.AutoPostTelegramBot.base.models import kotlinx.serialization.Serializable diff --git a/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/WebhookConfig.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/WebhookConfig.kt new file mode 100644 index 0000000..fec11e2 --- /dev/null +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/models/WebhookConfig.kt @@ -0,0 +1,58 @@ +package dev.inmo.AutoPostTelegramBot.base.models + +import dev.inmo.AutoPostTelegramBot.utils.NewDefaultCoroutineScope +import dev.inmo.micro_utils.coroutines.ExceptionHandler +import dev.inmo.tgbotapi.bot.RequestsExecutor +import dev.inmo.tgbotapi.extensions.utils.updates.retrieving.setWebhookInfoAndStartListenWebhooks +import dev.inmo.tgbotapi.requests.abstracts.toInputFile +import dev.inmo.tgbotapi.requests.webhook.SetWebhook +import dev.inmo.tgbotapi.updateshandlers.UpdatesFilter +import dev.inmo.tgbotapi.updateshandlers.webhook.WebhookPrivateKeyConfig +import io.ktor.server.cio.CIO +import io.ktor.server.engine.ApplicationEngine +import kotlinx.coroutines.CoroutineScope +import kotlinx.serialization.Serializable +import java.io.File + +@Serializable +data class WebhookConfig( + val url: String, + val port: Int, + val certificatePath: String? = null, + val maxConnections: Int? = null, + val privateKeyConfig: WebhookPrivateKeyConfig? = null +) { + suspend fun startWebhookServer( + bot: RequestsExecutor, + filter: UpdatesFilter, + scope: CoroutineScope = NewDefaultCoroutineScope(4), + exceptionsHandler: ExceptionHandler? = null + ): ApplicationEngine = certificatePath ?.let { File(it).toInputFile() } ?.let { + bot.setWebhookInfoAndStartListenWebhooks( + port, + CIO, + SetWebhook( + url, + it, + allowedUpdates = filter.allowedUpdates, + maxAllowedConnections = maxConnections + ), + exceptionsHandler ?: {}, + privateKeyConfig = privateKeyConfig, + scope = scope, + block = filter.asUpdateReceiver + ) + } ?: bot.setWebhookInfoAndStartListenWebhooks( + port, + CIO, + SetWebhook( + url, + allowedUpdates = filter.allowedUpdates, + maxAllowedConnections = maxConnections + ), + exceptionsHandler ?: {}, + privateKeyConfig = privateKeyConfig, + scope = scope, + block = filter.asUpdateReceiver + ) +} \ No newline at end of file diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/plugins/DefaultPluginManager.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/plugins/DefaultPluginManager.kt similarity index 76% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/plugins/DefaultPluginManager.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/plugins/DefaultPluginManager.kt index 79f66d2..e2ac8e2 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/plugins/DefaultPluginManager.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/plugins/DefaultPluginManager.kt @@ -1,7 +1,7 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins +package dev.inmo.AutoPostTelegramBot.base.plugins -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.FinalConfig -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor +import dev.inmo.AutoPostTelegramBot.base.models.FinalConfig +import dev.inmo.tgbotapi.bot.RequestsExecutor import kotlinx.coroutines.* class DefaultPluginManager( diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/plugins/Plugin.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/plugins/Plugin.kt similarity index 52% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/plugins/Plugin.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/plugins/Plugin.kt index 236d2f0..ff5d726 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/plugins/Plugin.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/plugins/Plugin.kt @@ -1,8 +1,8 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins +package dev.inmo.AutoPostTelegramBot.base.plugins -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.FinalConfig -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.PluginSerializer -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor +import dev.inmo.AutoPostTelegramBot.base.models.FinalConfig +import dev.inmo.AutoPostTelegramBot.utils.PluginSerializer +import dev.inmo.tgbotapi.bot.RequestsExecutor import kotlinx.serialization.Serializable import java.util.logging.Level @@ -10,8 +10,11 @@ import java.util.logging.Logger typealias PluginName = String -val commonLogger = Logger.getLogger("common").also { - it.level = Level.FINER +val commonLogger = Logger.getLogger("common").also { logger -> + logger.level = Level.ALL + logger.handlers.forEach { + it.level = logger.level + } } @Serializable(PluginSerializer::class) diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/plugins/PluginManager.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/plugins/PluginManager.kt similarity index 62% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/plugins/PluginManager.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/plugins/PluginManager.kt index 1f5b4b3..6b7bdc1 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/plugins/PluginManager.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/plugins/PluginManager.kt @@ -1,7 +1,7 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins +package dev.inmo.AutoPostTelegramBot.base.plugins -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.FinalConfig -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor +import dev.inmo.AutoPostTelegramBot.base.models.FinalConfig +import dev.inmo.tgbotapi.bot.RequestsExecutor interface PluginManager { val plugins: List diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/plugins/abstractions/Chooser.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/plugins/abstractions/Chooser.kt similarity index 50% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/plugins/abstractions/Chooser.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/plugins/abstractions/Chooser.kt index 97bfd0a..efed874 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/plugins/abstractions/Chooser.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/plugins/abstractions/Chooser.kt @@ -1,7 +1,7 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.abstractions +package dev.inmo.AutoPostTelegramBot.base.plugins.abstractions -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.PostId -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.Plugin +import dev.inmo.AutoPostTelegramBot.base.models.PostId +import dev.inmo.AutoPostTelegramBot.base.plugins.Plugin import org.joda.time.DateTime interface Chooser : Plugin { diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/plugins/abstractions/RatingPlugin.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/plugins/abstractions/RatingPlugin.kt similarity index 85% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/plugins/abstractions/RatingPlugin.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/plugins/abstractions/RatingPlugin.kt index 9107cad..9fefe9e 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/base/plugins/abstractions/RatingPlugin.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/base/plugins/abstractions/RatingPlugin.kt @@ -1,7 +1,7 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.abstractions +package dev.inmo.AutoPostTelegramBot.base.plugins.abstractions -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.PostId -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.Plugin +import dev.inmo.AutoPostTelegramBot.base.models.PostId +import dev.inmo.AutoPostTelegramBot.base.plugins.Plugin import kotlinx.coroutines.flow.Flow typealias RatingId = Long diff --git a/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/BotLogger.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/BotLogger.kt new file mode 100644 index 0000000..f4f5a97 --- /dev/null +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/BotLogger.kt @@ -0,0 +1,19 @@ +package dev.inmo.AutoPostTelegramBot.plugins + +import dev.inmo.AutoPostTelegramBot.base.models.BotConfig +import dev.inmo.AutoPostTelegramBot.base.models.FinalConfig +import dev.inmo.AutoPostTelegramBot.base.plugins.Plugin +import dev.inmo.AutoPostTelegramBot.base.plugins.PluginManager +import dev.inmo.AutoPostTelegramBot.utils.initHandler +import dev.inmo.tgbotapi.bot.RequestsExecutor +import kotlinx.serialization.Serializable + +@Serializable +class BotLogger( + private val config: BotConfig? = null +) : Plugin { + override suspend fun onInit(executor: RequestsExecutor, baseConfig: FinalConfig, pluginManager: PluginManager) { + val logExecutor = config ?.createBot() ?: executor + initHandler(logExecutor, baseConfig.logsChatId) + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/GarbageCollector.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/GarbageCollector.kt similarity index 82% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/GarbageCollector.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/GarbageCollector.kt index 3c3af54..63244eb 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/GarbageCollector.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/GarbageCollector.kt @@ -1,16 +1,16 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins +package dev.inmo.AutoPostTelegramBot.plugins -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.FinalConfig -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.* -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.abstractions.RatingPair -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.abstractions.RatingPlugin -import com.github.insanusmokrassar.AutoPostTelegramBot.plugins.base.commands.deletePost -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.* -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions.* -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.flow.collectWithErrors -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable +import dev.inmo.AutoPostTelegramBot.base.models.FinalConfig +import dev.inmo.AutoPostTelegramBot.base.plugins.* +import dev.inmo.AutoPostTelegramBot.base.plugins.abstractions.RatingPair +import dev.inmo.AutoPostTelegramBot.base.plugins.abstractions.RatingPlugin +import dev.inmo.AutoPostTelegramBot.plugins.base.commands.deletePost +import dev.inmo.AutoPostTelegramBot.utils.* +import dev.inmo.AutoPostTelegramBot.utils.extensions.* +import dev.inmo.AutoPostTelegramBot.utils.flow.collectWithErrors +import dev.inmo.tgbotapi.bot.RequestsExecutor import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.serialization.Serializable diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/RatingTimerAutoDisablePlugin.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/RatingTimerAutoDisablePlugin.kt similarity index 68% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/RatingTimerAutoDisablePlugin.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/RatingTimerAutoDisablePlugin.kt index 791e7cd..c89d75d 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/RatingTimerAutoDisablePlugin.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/RatingTimerAutoDisablePlugin.kt @@ -1,11 +1,11 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins +package dev.inmo.AutoPostTelegramBot.plugins -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.FinalConfig -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.* -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.abstractions.MutableRatingPlugin -import com.github.insanusmokrassar.AutoPostTelegramBot.plugins.scheduler.SchedulerPlugin -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.flow.collectWithErrors -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor +import dev.inmo.AutoPostTelegramBot.base.models.FinalConfig +import dev.inmo.AutoPostTelegramBot.base.plugins.* +import dev.inmo.AutoPostTelegramBot.base.plugins.abstractions.MutableRatingPlugin +import dev.inmo.AutoPostTelegramBot.plugins.scheduler.SchedulerPlugin +import dev.inmo.AutoPostTelegramBot.utils.flow.collectWithErrors +import dev.inmo.tgbotapi.bot.RequestsExecutor import kotlinx.coroutines.* import kotlinx.serialization.Serializable @@ -24,7 +24,7 @@ class RatingTimerAutoDisablePlugin : Plugin { CoroutineScope(Dispatchers.Default).apply { launch { - schedulerPlugin.timerSchedulesTable.postTimeRegisteredFlow.collectWithErrors( + schedulerPlugin.getSchedulesTable().postTimeRegisteredFlow.collectWithErrors( { _, error -> commonLogger.throwing( name, @@ -40,7 +40,7 @@ class RatingTimerAutoDisablePlugin : Plugin { } launch { ratingPlugin.allocateRatingAddedFlow().collectWithErrors { - schedulerPlugin.timerSchedulesTable.unregisterPost(it.first) + schedulerPlugin.getSchedulesTable().unregisterPost(it.first) } } } diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/BasePlugin.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/BasePlugin.kt similarity index 65% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/BasePlugin.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/BasePlugin.kt index fa60e97..bca8b5c 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/BasePlugin.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/BasePlugin.kt @@ -1,13 +1,13 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.base +package dev.inmo.AutoPostTelegramBot.plugins.base -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.FinalConfig -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.Plugin -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.PluginManager -import com.github.insanusmokrassar.AutoPostTelegramBot.plugins.base.callbacks.enableOnMediaGroupsCallback -import com.github.insanusmokrassar.AutoPostTelegramBot.plugins.base.callbacks.enableOnMessageCallback -import com.github.insanusmokrassar.AutoPostTelegramBot.plugins.base.commands.* -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.NewDefaultCoroutineScope -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor +import dev.inmo.AutoPostTelegramBot.base.models.FinalConfig +import dev.inmo.AutoPostTelegramBot.base.plugins.Plugin +import dev.inmo.AutoPostTelegramBot.base.plugins.PluginManager +import dev.inmo.AutoPostTelegramBot.plugins.base.callbacks.enableOnMediaGroupsCallback +import dev.inmo.AutoPostTelegramBot.plugins.base.callbacks.enableOnMessageCallback +import dev.inmo.AutoPostTelegramBot.plugins.base.commands.* +import dev.inmo.AutoPostTelegramBot.utils.NewDefaultCoroutineScope +import dev.inmo.tgbotapi.bot.RequestsExecutor import kotlinx.coroutines.Job import kotlinx.serialization.Serializable import kotlinx.serialization.Transient @@ -47,15 +47,6 @@ class BasePlugin : Plugin { startPostJob = startPostJob ?: scope.enableStartPostCommand() fixPostJob = fixPostJob ?: scope.enableFixPostCommand() - onMediaGroupJob = onMediaGroupJob ?: scope.enableOnMediaGroupsCallback( - baseConfig.postsTable, - baseConfig.postsMessagesTable - ) - onMessageJob = onMessageJob ?: scope.enableOnMessageCallback( - baseConfig.postsTable, - baseConfig.postsMessagesTable - ) - postMessagesRegistrant = PostMessagesRegistrant( executor, baseConfig.sourceChatId, @@ -64,5 +55,12 @@ class BasePlugin : Plugin { ).also { renewRegisteredMessage = RenewRegisteredMessage(it, baseConfig.postsMessagesTable).also { it.onInit(executor, baseConfig, pluginManager) } } + + onMediaGroupJob = onMediaGroupJob ?: scope.enableOnMediaGroupsCallback( + CommonKnownPostsTransactions + ) + onMessageJob = onMessageJob ?: scope.enableOnMessageCallback( + CommonKnownPostsTransactions + ) } } diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/PostMessagesRegistrant.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/PostMessagesRegistrant.kt similarity index 60% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/PostMessagesRegistrant.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/PostMessagesRegistrant.kt index f9751c3..9378cea 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/PostMessagesRegistrant.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/PostMessagesRegistrant.kt @@ -1,19 +1,21 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.base +package dev.inmo.AutoPostTelegramBot.plugins.base -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.transactionCompletedChannel -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.commonLogger -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.NewDefaultCoroutineScope -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions.sendToLogger -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions.subscribeChecking -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor -import com.github.insanusmokrassar.TelegramBotAPI.bot.exceptions.ReplyMessageNotFoundException -import com.github.insanusmokrassar.TelegramBotAPI.requests.send.SendTextMessage -import com.github.insanusmokrassar.TelegramBotAPI.types.ChatIdentifier -import com.github.insanusmokrassar.TelegramBotAPI.types.MessageIdentifier -import com.github.insanusmokrassar.TelegramBotAPI.types.ParseMode.MarkdownParseMode -import kotlinx.coroutines.* +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable +import dev.inmo.AutoPostTelegramBot.base.database.transactionCompletedFlow +import dev.inmo.AutoPostTelegramBot.base.plugins.commonLogger +import dev.inmo.AutoPostTelegramBot.utils.NewDefaultCoroutineScope +import dev.inmo.AutoPostTelegramBot.utils.extensions.sendToLogger +import dev.inmo.tgbotapi.bot.RequestsExecutor +import dev.inmo.tgbotapi.bot.exceptions.* +import dev.inmo.tgbotapi.requests.send.SendTextMessage +import dev.inmo.tgbotapi.types.ChatIdentifier +import dev.inmo.tgbotapi.types.MessageIdentifier +import dev.inmo.tgbotapi.types.ParseMode.MarkdownParseMode +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.joinAll +import kotlinx.coroutines.launch import java.lang.ref.WeakReference class PostMessagesRegistrant( @@ -24,14 +26,10 @@ class PostMessagesRegistrant( ) { private val botWR = WeakReference(executor) init { - transactionCompletedChannel.subscribeChecking { - registerPostMessage( - it - ) - true - } - val scope = NewDefaultCoroutineScope() + transactionCompletedFlow.onEach { + registerPostMessage(it) + }.launchIn(scope) val registerJobs = postsTable.getAll().mapNotNull { if (postsTable.postRegisteredMessage(it) == null) { @@ -46,7 +44,6 @@ class PostMessagesRegistrant( } scope.launch { registerJobs.joinAll() - scope.coroutineContext.cancel() } } @@ -80,7 +77,23 @@ class PostMessagesRegistrant( ) postsMessagesTable.removePostMessage(registeredPostId, messageId) messages.removeAt(0) + } catch (e: CommonRequestException) { + if (e.plainAnswer.contains("Bad Request: replied message not found")) { + sendToLogger( + e, + "Register message" + ) + postsMessagesTable.removePostMessage(registeredPostId, messageId) + messages.removeAt(0) + } else { + sendToLogger( + e, + "Register message; Left retries: $actualRetries" + ) + actualRetries-- + } } catch (e: Exception) { + println(e::class) sendToLogger( e, "Register message; Left retries: $actualRetries" diff --git a/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/callbacks/OnMediaGroup.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/callbacks/OnMediaGroup.kt new file mode 100644 index 0000000..6ffd03d --- /dev/null +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/callbacks/OnMediaGroup.kt @@ -0,0 +1,32 @@ +package dev.inmo.AutoPostTelegramBot.plugins.base.callbacks + +import dev.inmo.AutoPostTelegramBot.base.models.PostMessage +import dev.inmo.AutoPostTelegramBot.base.plugins.commonLogger +import dev.inmo.AutoPostTelegramBot.checkedMediaGroupsFlow +import dev.inmo.AutoPostTelegramBot.plugins.base.commands.PostsTransactions +import dev.inmo.AutoPostTelegramBot.utils.flow.collectWithErrors +import dev.inmo.tgbotapi.extensions.utils.shortcuts.chat +import kotlinx.coroutines.* + +internal fun CoroutineScope.enableOnMediaGroupsCallback( + postsTransactions: PostsTransactions +): Job = launch { + checkedMediaGroupsFlow.collectWithErrors( + { update, e -> + commonLogger.throwing( + "Media groups AutoPost callback", + "Perform update: $update", + e + ) + } + ) { + val messages = it.data + val id = it.chat.id + println(postsTransactions[id]) + postsTransactions.doInTransaction(id) { + messages.forEach { message -> + it.addMessageId(PostMessage(message)) + } + } + } +} diff --git a/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/callbacks/OnMessage.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/callbacks/OnMessage.kt new file mode 100644 index 0000000..b9be45b --- /dev/null +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/callbacks/OnMessage.kt @@ -0,0 +1,42 @@ +package dev.inmo.AutoPostTelegramBot.plugins.base.callbacks + +import dev.inmo.AutoPostTelegramBot.base.models.PostMessage +import dev.inmo.AutoPostTelegramBot.base.plugins.commonLogger +import dev.inmo.AutoPostTelegramBot.checkedMessagesFlow +import dev.inmo.AutoPostTelegramBot.plugins.base.commands.PostsTransactions +import dev.inmo.AutoPostTelegramBot.utils.flow.collectWithErrors +import dev.inmo.tgbotapi.extensions.utils.asTextContent +import dev.inmo.tgbotapi.types.ChatIdentifier +import dev.inmo.tgbotapi.types.MessageEntity.textsources.BotCommandTextSource +import dev.inmo.tgbotapi.types.message.abstracts.ContentMessage +import dev.inmo.tgbotapi.types.message.abstracts.MediaGroupMessage +import kotlinx.coroutines.* + +internal fun CoroutineScope.enableOnMessageCallback( + postsTransactions: PostsTransactions +): Job = launch { + checkedMessagesFlow.collectWithErrors( + { message, e -> + commonLogger.throwing( + "On message AutoPost callback", + "Perform message: $message", + e + ) + } + ) { + val message = it.data + when (message) { + is MediaGroupMessage<*> -> return@collectWithErrors + is ContentMessage<*> -> message.content.asTextContent() ?.let { content -> + if (content.textSources.firstOrNull { it is BotCommandTextSource } != null) { + return@collectWithErrors + } + } + } + + val chatId: ChatIdentifier = message.chat.id + postsTransactions.doInTransaction(chatId) { + it.addMessageId(PostMessage(message)) + } + } +} diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/commands/CommonKnownPostsTransactions.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/commands/CommonKnownPostsTransactions.kt similarity index 56% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/commands/CommonKnownPostsTransactions.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/commands/CommonKnownPostsTransactions.kt index 100c73e..46ca2f1 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/commands/CommonKnownPostsTransactions.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/commands/CommonKnownPostsTransactions.kt @@ -1,15 +1,16 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.base.commands +package dev.inmo.AutoPostTelegramBot.plugins.base.commands -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.PostTransaction -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable -import com.github.insanusmokrassar.TelegramBotAPI.types.ChatIdentifier +import dev.inmo.AutoPostTelegramBot.base.database.PostTransaction +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable +import dev.inmo.tgbotapi.types.ChatIdentifier import java.util.concurrent.ConcurrentHashMap -object CommonKnownPostsTransactions { +class PostsTransactions( + private val postsTable: PostsBaseInfoTable, + private val postsMessagesTable: PostsMessagesInfoTable +) { private val usersTransactions = ConcurrentHashMap() - private lateinit var postsTable: PostsBaseInfoTable - private lateinit var postsMessagesTable: PostsMessagesInfoTable @Synchronized operator fun contains(chatIdentifier: ChatIdentifier): Boolean = usersTransactions[chatIdentifier] ?.let { @@ -43,11 +44,18 @@ object CommonKnownPostsTransactions { } @Synchronized - internal fun updatePostsAndPostsMessagesTables( - postsTable: PostsBaseInfoTable, - postsMessagesTable: PostsMessagesInfoTable - ) { - this.postsTable = postsTable - this.postsMessagesTable = postsMessagesTable + fun doInTransaction( + chatId: ChatIdentifier, + completeIfNewOne: Boolean = true, + block: (PostTransaction) -> Unit + ) = get(chatId) ?.let(block) ?: startTransaction(chatId) ?.let { + if (completeIfNewOne) { + it.use(block) + } else { + it.let(block) + } } } + +lateinit var CommonKnownPostsTransactions: PostsTransactions + internal set diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/commands/DeletePost.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/commands/DeletePost.kt similarity index 59% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/commands/DeletePost.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/commands/DeletePost.kt index 50a3beb..b401fe9 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/commands/DeletePost.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/commands/DeletePost.kt @@ -1,18 +1,18 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.base.commands +package dev.inmo.AutoPostTelegramBot.plugins.base.commands -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.commands.buildCommandFlow -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions.sendToLogger -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.flow.collectWithErrors -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor -import com.github.insanusmokrassar.TelegramBotAPI.requests.DeleteMessage -import com.github.insanusmokrassar.TelegramBotAPI.requests.send.SendTextMessage -import com.github.insanusmokrassar.TelegramBotAPI.types.ChatIdentifier -import com.github.insanusmokrassar.TelegramBotAPI.types.MessageIdentifier -import com.github.insanusmokrassar.TelegramBotAPI.types.ParseMode.MarkdownParseMode +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable +import dev.inmo.AutoPostTelegramBot.utils.commands.buildCommandFlow +import dev.inmo.AutoPostTelegramBot.utils.extensions.sendToLogger +import dev.inmo.AutoPostTelegramBot.utils.flow.collectWithErrors +import dev.inmo.tgbotapi.bot.RequestsExecutor +import dev.inmo.tgbotapi.extensions.utils.shortcuts.executeUnsafe +import dev.inmo.tgbotapi.requests.DeleteMessage +import dev.inmo.tgbotapi.requests.send.SendTextMessage +import dev.inmo.tgbotapi.types.ChatIdentifier +import dev.inmo.tgbotapi.types.MessageIdentifier +import dev.inmo.tgbotapi.types.ParseMode.MarkdownParseMode import kotlinx.coroutines.* -import kotlinx.io.IOException import java.lang.ref.WeakReference suspend fun deletePost( @@ -32,18 +32,18 @@ suspend fun deletePost( postsTable.removePost(postId) messagesToDelete.forEach { currentMessageToDeleteId -> - try { - executor.execute( - DeleteMessage( - chatId, - currentMessageToDeleteId - ) - ) - } catch (e: IOException) { - executor.sendToLogger( - e, - "Deleting of post" + executor.executeUnsafe( + DeleteMessage( + chatId, + currentMessageToDeleteId ) + ) { + it.forEach { e -> + executor.sendToLogger( + e, + "Deleting of post" + ) + } } } } diff --git a/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/commands/FixPost.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/commands/FixPost.kt new file mode 100644 index 0000000..c3c379f --- /dev/null +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/commands/FixPost.kt @@ -0,0 +1,26 @@ +package dev.inmo.AutoPostTelegramBot.plugins.base.commands + +import dev.inmo.AutoPostTelegramBot.base.database.exceptions.NothingToSaveException +import dev.inmo.AutoPostTelegramBot.base.plugins.commonLogger +import dev.inmo.AutoPostTelegramBot.utils.commands.buildCommandFlow +import dev.inmo.AutoPostTelegramBot.utils.flow.collectWithErrors +import dev.inmo.tgbotapi.types.ChatIdentifier +import dev.inmo.tgbotapi.types.message.abstracts.FromUserMessage +import kotlinx.coroutines.* + +val fixPostRegex: Regex = Regex("^fixPost$") + +internal fun CoroutineScope.enableFixPostCommand(): Job = launch { + buildCommandFlow(fixPostRegex).collectWithErrors({ message, it -> + commonLogger.throwing("Post fixer: $message", "fixPost", it) + }) { message -> + try { + val userId: ChatIdentifier? = (message as? FromUserMessage) ?.user ?.id ?: message.chat.id + userId ?.let { + CommonKnownPostsTransactions[it] ?.saveNewPost() ?: throw NothingToSaveException("Transaction was not started") + } + } catch (e: NothingToSaveException) { + commonLogger.warning("Nothing to save: ${e.message}") + } + } +} diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/commands/RenewRegisteredMessage.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/commands/RenewRegisteredMessage.kt similarity index 57% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/commands/RenewRegisteredMessage.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/commands/RenewRegisteredMessage.kt index 3280173..6b257b7 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/commands/RenewRegisteredMessage.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/commands/RenewRegisteredMessage.kt @@ -1,15 +1,14 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.base.commands +package dev.inmo.AutoPostTelegramBot.plugins.base.commands -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.commonLogger -import com.github.insanusmokrassar.AutoPostTelegramBot.plugins.base.PostMessagesRegistrant -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.commands.CommandPlugin -import com.github.insanusmokrassar.TelegramBotAPI.requests.DeleteMessage -import com.github.insanusmokrassar.TelegramBotAPI.requests.send.SendTextMessage -import com.github.insanusmokrassar.TelegramBotAPI.types.UpdateIdentifier -import com.github.insanusmokrassar.TelegramBotAPI.types.message.abstracts.CommonMessage -import com.github.insanusmokrassar.TelegramBotAPI.utils.extensions.executeAsync -import com.github.insanusmokrassar.TelegramBotAPI.utils.extensions.executeUnsafe +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable +import dev.inmo.AutoPostTelegramBot.base.plugins.commonLogger +import dev.inmo.AutoPostTelegramBot.plugins.base.PostMessagesRegistrant +import dev.inmo.AutoPostTelegramBot.utils.commands.CommandPlugin +import dev.inmo.tgbotapi.extensions.utils.shortcuts.executeUnsafe +import dev.inmo.tgbotapi.requests.DeleteMessage +import dev.inmo.tgbotapi.requests.send.SendTextMessage +import dev.inmo.tgbotapi.types.UpdateIdentifier +import dev.inmo.tgbotapi.types.message.abstracts.CommonMessage val renewRegisteredMessageRegex: Regex = Regex("^renewRegistered(Message)?$") @@ -44,17 +43,16 @@ class RenewRegisteredMessage( postMessagesRegistrant.registerPostMessage( postId ) ?.also { - executor.executeAsync( + executor.executeUnsafe( DeleteMessage( message.chat.id, it - ), - { - commonLogger.warning( - "Can't remove old registered message when renew: $it" - ) - } - ) + ) + ) { + commonLogger.warning( + "Can't remove old registered message when renew: $it" + ) + } } executor.executeUnsafe( DeleteMessage( diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/commands/StartPost.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/commands/StartPost.kt similarity index 51% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/commands/StartPost.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/commands/StartPost.kt index ef5d987..a20f744 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/base/commands/StartPost.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/base/commands/StartPost.kt @@ -1,8 +1,8 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.base.commands +package dev.inmo.AutoPostTelegramBot.plugins.base.commands -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.commands.buildCommandFlow -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.flow.collectWithErrors -import com.github.insanusmokrassar.TelegramBotAPI.types.ChatIdentifier +import dev.inmo.AutoPostTelegramBot.utils.commands.buildCommandFlow +import dev.inmo.AutoPostTelegramBot.utils.flow.collectWithErrors +import dev.inmo.tgbotapi.types.ChatIdentifier import kotlinx.coroutines.* val startPostRegex: Regex = Regex("^startPost$") diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/choosers/MostRatedChooser.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/choosers/MostRatedChooser.kt similarity index 77% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/choosers/MostRatedChooser.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/choosers/MostRatedChooser.kt index 68c4c46..edeaf22 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/choosers/MostRatedChooser.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/choosers/MostRatedChooser.kt @@ -1,7 +1,7 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.choosers +package dev.inmo.AutoPostTelegramBot.plugins.choosers -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.PostId -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.abstractions.RatingPair +import dev.inmo.AutoPostTelegramBot.base.models.PostId +import dev.inmo.AutoPostTelegramBot.base.plugins.abstractions.RatingPair import kotlinx.serialization.Serializable import org.joda.time.DateTime @@ -27,10 +27,10 @@ class MostRatedChooser : RateChooser() { } ?: mostRated.add(it) } } - return mostRated.minBy { (ratingId, _) -> ratingId } ?.let { (ratingId, _) -> + return mostRated.minByOrNull { (ratingId, _) -> ratingId } ?.let { (ratingId, _) -> ratingPlugin.resolvePostId(ratingId) ?.let { listOf(it) } } ?: emptyList() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/choosers/MostRatedRandomChooser.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/choosers/MostRatedRandomChooser.kt similarity index 68% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/choosers/MostRatedRandomChooser.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/choosers/MostRatedRandomChooser.kt index 4de07fe..259e221 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/choosers/MostRatedRandomChooser.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/choosers/MostRatedRandomChooser.kt @@ -1,9 +1,9 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.choosers +package dev.inmo.AutoPostTelegramBot.plugins.choosers -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.FinalConfig -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.PostId -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.PluginManager -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor +import dev.inmo.AutoPostTelegramBot.base.models.FinalConfig +import dev.inmo.AutoPostTelegramBot.base.models.PostId +import dev.inmo.AutoPostTelegramBot.base.plugins.PluginManager +import dev.inmo.tgbotapi.bot.RequestsExecutor import kotlinx.serialization.Serializable import kotlinx.serialization.Transient import org.joda.time.DateTime diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/choosers/NoneChooser.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/choosers/NoneChooser.kt similarity index 51% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/choosers/NoneChooser.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/choosers/NoneChooser.kt index 6d43916..ca94cf2 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/choosers/NoneChooser.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/choosers/NoneChooser.kt @@ -1,7 +1,7 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.choosers +package dev.inmo.AutoPostTelegramBot.plugins.choosers -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.PostId -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.abstractions.Chooser +import dev.inmo.AutoPostTelegramBot.base.models.PostId +import dev.inmo.AutoPostTelegramBot.base.plugins.abstractions.Chooser import kotlinx.serialization.Serializable import org.joda.time.DateTime diff --git a/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/choosers/RateChooser.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/choosers/RateChooser.kt new file mode 100644 index 0000000..6b21ca0 --- /dev/null +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/choosers/RateChooser.kt @@ -0,0 +1,26 @@ +package dev.inmo.AutoPostTelegramBot.plugins.choosers + +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable +import dev.inmo.AutoPostTelegramBot.base.models.FinalConfig +import dev.inmo.AutoPostTelegramBot.base.plugins.PluginManager +import dev.inmo.AutoPostTelegramBot.base.plugins.abstractions.Chooser +import dev.inmo.AutoPostTelegramBot.base.plugins.abstractions.RatingPlugin +import dev.inmo.AutoPostTelegramBot.base.plugins.findFirstPlugin +import dev.inmo.tgbotapi.bot.RequestsExecutor + + +abstract class RateChooser : Chooser { + protected lateinit var ratingPlugin: RatingPlugin + private set + + protected lateinit var postsTable: PostsBaseInfoTable + protected lateinit var postsMessagesTable: PostsMessagesInfoTable + + override suspend fun onInit(executor: RequestsExecutor, baseConfig: FinalConfig, pluginManager: PluginManager) { + super.onInit(executor, baseConfig, pluginManager) + ratingPlugin = pluginManager.findFirstPlugin() ?: return + postsTable = baseConfig.postsTable + postsMessagesTable = baseConfig.postsMessagesTable + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/choosers/SmartChooser.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/choosers/SmartChooser.kt similarity index 89% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/choosers/SmartChooser.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/choosers/SmartChooser.kt index ecd7e7b..f33b633 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/choosers/SmartChooser.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/choosers/SmartChooser.kt @@ -1,12 +1,12 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.choosers +package dev.inmo.AutoPostTelegramBot.plugins.choosers -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.PostId -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.abstractions.RatingPair -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.abstractions.getRatingRange -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.commonLogger -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions.* -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.parseDateTimes +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable +import dev.inmo.AutoPostTelegramBot.base.models.PostId +import dev.inmo.AutoPostTelegramBot.base.plugins.abstractions.RatingPair +import dev.inmo.AutoPostTelegramBot.base.plugins.abstractions.getRatingRange +import dev.inmo.AutoPostTelegramBot.base.plugins.commonLogger +import dev.inmo.AutoPostTelegramBot.utils.extensions.* +import dev.inmo.AutoPostTelegramBot.utils.parseDateTimes import kotlinx.serialization.Serializable import kotlinx.serialization.Transient import org.joda.time.DateTime diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/publishers/PostPublisher.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/publishers/PostPublisher.kt similarity index 80% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/publishers/PostPublisher.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/publishers/PostPublisher.kt index 665fd87..da1d537 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/publishers/PostPublisher.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/publishers/PostPublisher.kt @@ -1,22 +1,22 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.publishers - -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.FinalConfig -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.PostMessage -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.* -import com.github.insanusmokrassar.AutoPostTelegramBot.plugins.base.commands.deletePost -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.cacheMessagesToMap -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions.sendToLogger -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.resend -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor -import com.github.insanusmokrassar.TelegramBotAPI.requests.DeleteMessage -import com.github.insanusmokrassar.TelegramBotAPI.requests.ForwardMessage -import com.github.insanusmokrassar.TelegramBotAPI.requests.send.SendTextMessage -import com.github.insanusmokrassar.TelegramBotAPI.types.* -import com.github.insanusmokrassar.TelegramBotAPI.types.message.abstracts.ContentMessage -import com.github.insanusmokrassar.TelegramBotAPI.types.message.abstracts.Message -import com.github.insanusmokrassar.TelegramBotAPI.utils.extensions.executeUnsafe +package dev.inmo.AutoPostTelegramBot.plugins.publishers + +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable +import dev.inmo.AutoPostTelegramBot.base.models.FinalConfig +import dev.inmo.AutoPostTelegramBot.base.models.PostMessage +import dev.inmo.AutoPostTelegramBot.base.plugins.* +import dev.inmo.AutoPostTelegramBot.plugins.base.commands.deletePost +import dev.inmo.AutoPostTelegramBot.utils.cacheMessagesToMap +import dev.inmo.AutoPostTelegramBot.utils.extensions.sendToLogger +import dev.inmo.AutoPostTelegramBot.utils.resend +import dev.inmo.tgbotapi.bot.RequestsExecutor +import dev.inmo.tgbotapi.extensions.utils.shortcuts.executeUnsafe +import dev.inmo.tgbotapi.requests.DeleteMessage +import dev.inmo.tgbotapi.requests.ForwardMessage +import dev.inmo.tgbotapi.requests.send.SendTextMessage +import dev.inmo.tgbotapi.types.* +import dev.inmo.tgbotapi.types.message.abstracts.ContentMessage +import dev.inmo.tgbotapi.types.message.abstracts.Message import kotlinx.coroutines.channels.BroadcastChannel import kotlinx.coroutines.channels.Channel import kotlinx.serialization.Serializable diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/publishers/PublishPost.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/publishers/PublishPost.kt similarity index 70% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/publishers/PublishPost.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/publishers/PublishPost.kt index c9a9b09..dc29c59 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/publishers/PublishPost.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/publishers/PublishPost.kt @@ -1,19 +1,19 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.publishers +package dev.inmo.AutoPostTelegramBot.plugins.publishers -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.exceptions.NoRowFoundException -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.abstractions.Chooser -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.NewDefaultCoroutineScope -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.commands.Command -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor -import com.github.insanusmokrassar.TelegramBotAPI.requests.DeleteMessage -import com.github.insanusmokrassar.TelegramBotAPI.requests.send.SendTextMessage -import com.github.insanusmokrassar.TelegramBotAPI.types.ChatIdentifier -import com.github.insanusmokrassar.TelegramBotAPI.types.ParseMode.MarkdownParseMode -import com.github.insanusmokrassar.TelegramBotAPI.types.UpdateIdentifier -import com.github.insanusmokrassar.TelegramBotAPI.types.message.abstracts.CommonMessage -import com.github.insanusmokrassar.TelegramBotAPI.types.message.content.TextContent +import dev.inmo.AutoPostTelegramBot.base.database.exceptions.NoRowFoundException +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsTable +import dev.inmo.AutoPostTelegramBot.base.plugins.abstractions.Chooser +import dev.inmo.AutoPostTelegramBot.utils.NewDefaultCoroutineScope +import dev.inmo.AutoPostTelegramBot.utils.commands.Command +import dev.inmo.tgbotapi.bot.RequestsExecutor +import dev.inmo.tgbotapi.requests.DeleteMessage +import dev.inmo.tgbotapi.requests.send.SendTextMessage +import dev.inmo.tgbotapi.types.ChatIdentifier +import dev.inmo.tgbotapi.types.ParseMode.MarkdownParseMode +import dev.inmo.tgbotapi.types.UpdateIdentifier +import dev.inmo.tgbotapi.types.message.abstracts.CommonMessage +import dev.inmo.tgbotapi.types.message.content.TextContent import kotlinx.coroutines.launch import java.lang.ref.WeakReference diff --git a/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/publishers/Publisher.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/publishers/Publisher.kt new file mode 100644 index 0000000..09ad27b --- /dev/null +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/publishers/Publisher.kt @@ -0,0 +1,7 @@ +package dev.inmo.AutoPostTelegramBot.plugins.publishers + +import dev.inmo.AutoPostTelegramBot.base.plugins.Plugin + +interface Publisher : Plugin { + suspend fun publishPost(postId: Int) +} \ No newline at end of file diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/scheduler/DateTimeConverter.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/scheduler/DateTimeConverter.kt similarity index 69% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/scheduler/DateTimeConverter.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/scheduler/DateTimeConverter.kt index 2ed089d..b4ededa 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/scheduler/DateTimeConverter.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/scheduler/DateTimeConverter.kt @@ -1,4 +1,4 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.scheduler +package dev.inmo.AutoPostTelegramBot.plugins.scheduler import org.joda.time.DateTime diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/scheduler/PostsSchedulesTable.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/scheduler/PostsSchedulesTable.kt similarity index 90% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/scheduler/PostsSchedulesTable.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/scheduler/PostsSchedulesTable.kt index 2d4d282..11c8409 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/scheduler/PostsSchedulesTable.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/scheduler/PostsSchedulesTable.kt @@ -1,11 +1,12 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.scheduler +package dev.inmo.AutoPostTelegramBot.plugins.scheduler -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.NewDefaultCoroutineScope +import dev.inmo.AutoPostTelegramBot.utils.NewDefaultCoroutineScope import kotlinx.coroutines.channels.BroadcastChannel import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.launch import org.jetbrains.exposed.sql.* +import org.jetbrains.exposed.sql.jodatime.datetime import org.jetbrains.exposed.sql.transactions.transaction import org.joda.time.DateTime @@ -16,8 +17,9 @@ private val PostsSchedulesTableScope = NewDefaultCoroutineScope(4) class PostsSchedulesTable( private val db: Database ) : Table() { - private val postIdColumn = integer("postId").primaryKey() + private val postIdColumn = integer("postId") private val postTimeColumn = datetime("postTime") + override val primaryKey: PrimaryKey = PrimaryKey(postIdColumn) private val postTimeRegisteredChannel = BroadcastChannel(Channel.CONFLATED) private val postTimeChangedChannel = BroadcastChannel(Channel.CONFLATED) @@ -104,9 +106,9 @@ class PostsSchedulesTable( fun nearPost(): PostIdPostTime? { return transaction(db) { - registeredPostsTimes().minBy { (_, time) -> + registeredPostsTimes().minByOrNull { (_, time) -> time.millis } } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/scheduler/Scheduler.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/scheduler/Scheduler.kt similarity index 83% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/scheduler/Scheduler.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/scheduler/Scheduler.kt index 4358c9f..1e53887 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/scheduler/Scheduler.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/scheduler/Scheduler.kt @@ -1,10 +1,10 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.scheduler +package dev.inmo.AutoPostTelegramBot.plugins.scheduler -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.commonLogger -import com.github.insanusmokrassar.AutoPostTelegramBot.plugins.publishers.Publisher -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.NewDefaultCoroutineScope -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions.schedule -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.flow.collectWithErrors +import dev.inmo.AutoPostTelegramBot.base.plugins.commonLogger +import dev.inmo.AutoPostTelegramBot.plugins.publishers.Publisher +import dev.inmo.AutoPostTelegramBot.utils.NewDefaultCoroutineScope +import dev.inmo.AutoPostTelegramBot.utils.extensions.schedule +import dev.inmo.AutoPostTelegramBot.utils.flow.collectWithErrors import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/scheduler/SchedulerPlugin.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/scheduler/SchedulerPlugin.kt similarity index 57% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/scheduler/SchedulerPlugin.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/scheduler/SchedulerPlugin.kt index b889aaf..9835b91 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/scheduler/SchedulerPlugin.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/scheduler/SchedulerPlugin.kt @@ -1,10 +1,13 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.scheduler +package dev.inmo.AutoPostTelegramBot.plugins.scheduler -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.FinalConfig -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.* -import com.github.insanusmokrassar.AutoPostTelegramBot.plugins.scheduler.commands.* -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions.subscribe -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor +import dev.inmo.AutoPostTelegramBot.base.models.FinalConfig +import dev.inmo.AutoPostTelegramBot.base.plugins.* +import dev.inmo.AutoPostTelegramBot.plugins.scheduler.commands.* +import dev.inmo.AutoPostTelegramBot.utils.SafeLazy +import dev.inmo.AutoPostTelegramBot.utils.flow.collectWithErrors +import dev.inmo.tgbotapi.bot.RequestsExecutor +import kotlinx.coroutines.* +import kotlinx.coroutines.flow.asFlow import kotlinx.serialization.Serializable import kotlinx.serialization.Transient import java.lang.ref.WeakReference @@ -12,8 +15,7 @@ import java.lang.ref.WeakReference @Serializable class SchedulerPlugin : Plugin { @Transient - lateinit var timerSchedulesTable: PostsSchedulesTable - private set + private val timerSchedulesTableLazy = SafeLazy(CoroutineScope(Dispatchers.Default)) @Transient private lateinit var enableTimerCommand: EnableTimerCommand @@ -25,16 +27,22 @@ class SchedulerPlugin : Plugin { @Transient private lateinit var scheduler: Scheduler + suspend fun getSchedulesTable() = timerSchedulesTableLazy.get() + override suspend fun onInit(executor: RequestsExecutor, baseConfig: FinalConfig, pluginManager: PluginManager) { - timerSchedulesTable = PostsSchedulesTable(baseConfig.databaseConfig.database) + timerSchedulesTableLazy.set(PostsSchedulesTable(baseConfig.databaseConfig.database)) + val timerSchedulesTable = timerSchedulesTableLazy.get() + scheduler = Scheduler( timerSchedulesTable, pluginManager.findFirstPlugin() ?: return ) val executorWR = WeakReference(executor) - baseConfig.postsTable.postRemovedChannel.subscribe { - timerSchedulesTable.unregisterPost(it) + CoroutineScope(Dispatchers.Default).launch { + baseConfig.postsTable.postRemovedChannel.asFlow().collectWithErrors { + timerSchedulesTable.unregisterPost(it) + } } enableTimerCommand = EnableTimerCommand( diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/scheduler/commands/DisableTimerCommand.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/scheduler/commands/DisableTimerCommand.kt similarity index 59% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/scheduler/commands/DisableTimerCommand.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/scheduler/commands/DisableTimerCommand.kt index 21db731..eec2a1b 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/scheduler/commands/DisableTimerCommand.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/scheduler/commands/DisableTimerCommand.kt @@ -1,21 +1,21 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.scheduler.commands +package dev.inmo.AutoPostTelegramBot.plugins.scheduler.commands -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.commonLogger -import com.github.insanusmokrassar.AutoPostTelegramBot.plugins.scheduler.PostsSchedulesTable -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.commands.Command -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor -import com.github.insanusmokrassar.TelegramBotAPI.requests.send.SendTextMessage -import com.github.insanusmokrassar.TelegramBotAPI.types.ChatId -import com.github.insanusmokrassar.TelegramBotAPI.types.ParseMode.MarkdownParseMode -import com.github.insanusmokrassar.TelegramBotAPI.types.UpdateIdentifier -import com.github.insanusmokrassar.TelegramBotAPI.types.message.abstracts.CommonMessage -import com.github.insanusmokrassar.TelegramBotAPI.utils.extensions.executeAsync +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable +import dev.inmo.AutoPostTelegramBot.base.plugins.commonLogger +import dev.inmo.AutoPostTelegramBot.plugins.scheduler.PostsSchedulesTable +import dev.inmo.AutoPostTelegramBot.utils.commands.Command +import dev.inmo.tgbotapi.bot.RequestsExecutor +import dev.inmo.tgbotapi.extensions.utils.shortcuts.executeAsync +import dev.inmo.tgbotapi.requests.send.SendTextMessage +import dev.inmo.tgbotapi.types.ChatId +import dev.inmo.tgbotapi.types.ParseMode.MarkdownParseMode +import dev.inmo.tgbotapi.types.UpdateIdentifier +import dev.inmo.tgbotapi.types.message.abstracts.CommonMessage import java.lang.ref.WeakReference private const val disableSchedulePublishCommand = "disableSchedulePublish" -private fun sendHelpForUsage( +private suspend fun sendHelpForUsage( executor: RequestsExecutor, chatId: ChatId ) { diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/scheduler/commands/EnableTimerCommand.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/scheduler/commands/EnableTimerCommand.kt similarity index 70% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/scheduler/commands/EnableTimerCommand.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/scheduler/commands/EnableTimerCommand.kt index 652cb7e..6d13f27 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/scheduler/commands/EnableTimerCommand.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/scheduler/commands/EnableTimerCommand.kt @@ -1,27 +1,27 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.scheduler.commands +package dev.inmo.AutoPostTelegramBot.plugins.scheduler.commands -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.exceptions.NoRowFoundException -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.plugins.scheduler.PostsSchedulesTable -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.NewDefaultCoroutineScope -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.commands.Command -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.parseDateTimes -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor -import com.github.insanusmokrassar.TelegramBotAPI.requests.DeleteMessage -import com.github.insanusmokrassar.TelegramBotAPI.requests.ForwardMessage -import com.github.insanusmokrassar.TelegramBotAPI.requests.send.SendTextMessage -import com.github.insanusmokrassar.TelegramBotAPI.types.* -import com.github.insanusmokrassar.TelegramBotAPI.types.ParseMode.MarkdownParseMode -import com.github.insanusmokrassar.TelegramBotAPI.types.message.abstracts.CommonMessage -import com.github.insanusmokrassar.TelegramBotAPI.types.message.content.TextContent -import com.github.insanusmokrassar.TelegramBotAPI.utils.extensions.executeAsync +import dev.inmo.AutoPostTelegramBot.base.database.exceptions.NoRowFoundException +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable +import dev.inmo.AutoPostTelegramBot.plugins.scheduler.PostsSchedulesTable +import dev.inmo.AutoPostTelegramBot.utils.NewDefaultCoroutineScope +import dev.inmo.AutoPostTelegramBot.utils.commands.Command +import dev.inmo.AutoPostTelegramBot.utils.parseDateTimes +import dev.inmo.tgbotapi.bot.RequestsExecutor +import dev.inmo.tgbotapi.extensions.utils.shortcuts.executeAsync +import dev.inmo.tgbotapi.requests.DeleteMessage +import dev.inmo.tgbotapi.requests.ForwardMessage +import dev.inmo.tgbotapi.requests.send.SendTextMessage +import dev.inmo.tgbotapi.types.* +import dev.inmo.tgbotapi.types.ParseMode.MarkdownParseMode +import dev.inmo.tgbotapi.types.message.abstracts.CommonMessage +import dev.inmo.tgbotapi.types.message.content.TextContent import kotlinx.coroutines.launch import java.lang.ref.WeakReference private const val setPostTimeCommandName = "setPublishTime" -private fun sendHelpForUsage( +private suspend fun sendHelpForUsage( executor: RequestsExecutor, chatId: ChatId ) { @@ -75,7 +75,7 @@ class EnableTimerCommand( preparsedText.parseDateTimes().asSequence().map { it.asFuture - }.min() ?.also { + }.minOrNull() ?.also { parsed -> parsed.also { postsSchedulesTable.registerPostTime(postId, parsed) @@ -116,4 +116,4 @@ class EnableTimerCommand( ) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/scheduler/commands/GetSchedulesCommand.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/scheduler/commands/GetSchedulesCommand.kt similarity index 73% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/scheduler/commands/GetSchedulesCommand.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/scheduler/commands/GetSchedulesCommand.kt index b0dfd79..d38ebf4 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/scheduler/commands/GetSchedulesCommand.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/scheduler/commands/GetSchedulesCommand.kt @@ -1,20 +1,20 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.scheduler.commands +package dev.inmo.AutoPostTelegramBot.plugins.scheduler.commands -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.commonLogger -import com.github.insanusmokrassar.AutoPostTelegramBot.plugins.scheduler.PostsSchedulesTable -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.* -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.commands.Command -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions.asPairs -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor -import com.github.insanusmokrassar.TelegramBotAPI.requests.ForwardMessage -import com.github.insanusmokrassar.TelegramBotAPI.requests.send.SendTextMessage -import com.github.insanusmokrassar.TelegramBotAPI.types.ChatIdentifier -import com.github.insanusmokrassar.TelegramBotAPI.types.UpdateIdentifier -import com.github.insanusmokrassar.TelegramBotAPI.types.message.abstracts.CommonMessage -import com.github.insanusmokrassar.TelegramBotAPI.types.message.abstracts.FromUserMessage -import com.github.insanusmokrassar.TelegramBotAPI.types.message.content.TextContent -import com.github.insanusmokrassar.TelegramBotAPI.utils.extensions.executeAsync +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable +import dev.inmo.AutoPostTelegramBot.base.plugins.commonLogger +import dev.inmo.AutoPostTelegramBot.plugins.scheduler.PostsSchedulesTable +import dev.inmo.AutoPostTelegramBot.utils.* +import dev.inmo.AutoPostTelegramBot.utils.commands.Command +import dev.inmo.AutoPostTelegramBot.utils.extensions.asPairs +import dev.inmo.tgbotapi.bot.RequestsExecutor +import dev.inmo.tgbotapi.extensions.utils.shortcuts.executeAsync +import dev.inmo.tgbotapi.requests.ForwardMessage +import dev.inmo.tgbotapi.requests.send.SendTextMessage +import dev.inmo.tgbotapi.types.ChatIdentifier +import dev.inmo.tgbotapi.types.UpdateIdentifier +import dev.inmo.tgbotapi.types.message.abstracts.CommonMessage +import dev.inmo.tgbotapi.types.message.abstracts.FromUserMessage +import dev.inmo.tgbotapi.types.message.content.TextContent import kotlinx.coroutines.delay import kotlinx.coroutines.launch import java.lang.ref.WeakReference diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/triggers/TimerTriggerStrategy.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/triggers/TimerTriggerStrategy.kt similarity index 76% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/triggers/TimerTriggerStrategy.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/triggers/TimerTriggerStrategy.kt index 336ea38..43ca09f 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/plugins/triggers/TimerTriggerStrategy.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/plugins/triggers/TimerTriggerStrategy.kt @@ -1,29 +1,29 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.plugins.triggers +package dev.inmo.AutoPostTelegramBot.plugins.triggers -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.FinalConfig -import com.github.insanusmokrassar.AutoPostTelegramBot.base.models.PostId -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.* -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.abstractions.Chooser -import com.github.insanusmokrassar.AutoPostTelegramBot.mediumBroadcastCapacity -import com.github.insanusmokrassar.AutoPostTelegramBot.plugins.publishers.Publisher -import com.github.insanusmokrassar.AutoPostTelegramBot.plugins.scheduler.SchedulerPlugin -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.CalculatedDateTime -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.commands.Command -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions.nearDateTime -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions.sendToLogger -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.flow.collectWithErrors -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.parseDateTimes -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor -import com.github.insanusmokrassar.TelegramBotAPI.requests.ForwardMessage -import com.github.insanusmokrassar.TelegramBotAPI.requests.send.SendTextMessage -import com.github.insanusmokrassar.TelegramBotAPI.types.ChatId -import com.github.insanusmokrassar.TelegramBotAPI.types.ParseMode.MarkdownParseMode -import com.github.insanusmokrassar.TelegramBotAPI.types.UpdateIdentifier -import com.github.insanusmokrassar.TelegramBotAPI.types.message.abstracts.CommonMessage -import com.github.insanusmokrassar.TelegramBotAPI.types.message.content.TextContent -import com.github.insanusmokrassar.TelegramBotAPI.utils.extensions.executeUnsafe +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsBaseInfoTable +import dev.inmo.AutoPostTelegramBot.base.database.tables.PostsMessagesInfoTable +import dev.inmo.AutoPostTelegramBot.base.models.FinalConfig +import dev.inmo.AutoPostTelegramBot.base.models.PostId +import dev.inmo.AutoPostTelegramBot.base.plugins.* +import dev.inmo.AutoPostTelegramBot.base.plugins.abstractions.Chooser +import dev.inmo.AutoPostTelegramBot.mediumBroadcastCapacity +import dev.inmo.AutoPostTelegramBot.plugins.publishers.Publisher +import dev.inmo.AutoPostTelegramBot.plugins.scheduler.SchedulerPlugin +import dev.inmo.AutoPostTelegramBot.utils.CalculatedDateTime +import dev.inmo.AutoPostTelegramBot.utils.commands.Command +import dev.inmo.AutoPostTelegramBot.utils.extensions.nearDateTime +import dev.inmo.AutoPostTelegramBot.utils.extensions.sendToLogger +import dev.inmo.AutoPostTelegramBot.utils.flow.collectWithErrors +import dev.inmo.AutoPostTelegramBot.utils.parseDateTimes +import dev.inmo.tgbotapi.bot.RequestsExecutor +import dev.inmo.tgbotapi.extensions.utils.shortcuts.executeUnsafe +import dev.inmo.tgbotapi.requests.ForwardMessage +import dev.inmo.tgbotapi.requests.send.SendTextMessage +import dev.inmo.tgbotapi.types.ChatId +import dev.inmo.tgbotapi.types.ParseMode.MarkdownParseMode +import dev.inmo.tgbotapi.types.UpdateIdentifier +import dev.inmo.tgbotapi.types.message.abstracts.CommonMessage +import dev.inmo.tgbotapi.types.message.content.TextContent import kotlinx.coroutines.* import kotlinx.coroutines.channels.BroadcastChannel import kotlinx.coroutines.flow.asFlow @@ -101,6 +101,7 @@ private fun getPlusTwentyFourHours() = System.currentTimeMillis() + twentyFourHo class TimerTriggerStrategy ( private val delay: Long? = null, private val time: String = "00:00-00:00 01:00", + private val times: List? = null, private val substitutedByScheduler: Boolean = false ) : Plugin { @Transient @@ -114,16 +115,18 @@ class TimerTriggerStrategy ( private var lastTime = DateTime.now() private val timesOfTriggering: List by lazy { - time.parseDateTimes() + (times ?: listOf(time)).flatMap { it.parseDateTimes() } } fun getNextTime(after: DateTime = DateTime.now()): DateTime? { val near = timesOfTriggering.nearDateTime(after) ?: return null schedulerPluginToCheckCollision ?.let { val afterNear = near + 1000L - val thereIsScheduled = it.timerSchedulesTable.registeredPostsTimes( - near - 1000L to afterNear - ).any { (_, dateTime) -> - dateTime == near + val thereIsScheduled = runBlocking { + it.getSchedulesTable().registeredPostsTimes( + near - 1000L to afterNear + ).any { (_, dateTime) -> + dateTime == near + } } if (thereIsScheduled) { return getNextTime(afterNear) @@ -149,12 +152,12 @@ class TimerTriggerStrategy ( pluginManager.findFirstPlugin() ?.let { schedulerPluginToCheckCollision = it TimerTriggerStrategyScope.launch { - it.timerSchedulesTable.postTimeRegisteredFlow.collectWithErrors { (_, dateTime) -> + it.getSchedulesTable().postTimeRegisteredFlow.collectWithErrors { (_, dateTime) -> publicationTimesPossiblyChangedBroadcastChannel.send(dateTime) } } TimerTriggerStrategyScope.launch { - it.timerSchedulesTable.postTimeChangedFlow.collectWithErrors { (_, dateTime) -> + it.getSchedulesTable().postTimeChangedFlow.collectWithErrors { (_, dateTime) -> publicationTimesPossiblyChangedBroadcastChannel.send(dateTime) } } diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/BotLogger.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/BotLogger.kt similarity index 75% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/BotLogger.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/BotLogger.kt index f540db5..482fe6b 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/BotLogger.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/BotLogger.kt @@ -1,12 +1,12 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.utils +package dev.inmo.AutoPostTelegramBot.utils -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.commonLogger -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions.splitForMessageWithAdditionalStep -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor -import com.github.insanusmokrassar.TelegramBotAPI.bot.exceptions.RequestException -import com.github.insanusmokrassar.TelegramBotAPI.requests.send.SendTextMessage -import com.github.insanusmokrassar.TelegramBotAPI.types.ChatIdentifier -import com.github.insanusmokrassar.TelegramBotAPI.types.ParseMode.MarkdownParseMode +import dev.inmo.AutoPostTelegramBot.base.plugins.commonLogger +import dev.inmo.AutoPostTelegramBot.utils.extensions.splitForMessageWithAdditionalStep +import dev.inmo.tgbotapi.bot.RequestsExecutor +import dev.inmo.tgbotapi.bot.exceptions.RequestException +import dev.inmo.tgbotapi.requests.send.SendTextMessage +import dev.inmo.tgbotapi.types.ChatIdentifier +import dev.inmo.tgbotapi.types.ParseMode.MarkdownParseMode import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import java.lang.ref.WeakReference diff --git a/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/CallbackQueryReceivers/CallbackQueryReceiver.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/CallbackQueryReceivers/CallbackQueryReceiver.kt new file mode 100644 index 0000000..c1139e0 --- /dev/null +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/CallbackQueryReceivers/CallbackQueryReceiver.kt @@ -0,0 +1,25 @@ +package dev.inmo.AutoPostTelegramBot.utils.CallbackQueryReceivers + +import dev.inmo.AutoPostTelegramBot.checkedCallbacksQueriesFlow +import dev.inmo.AutoPostTelegramBot.utils.NewDefaultCoroutineScope +import dev.inmo.AutoPostTelegramBot.utils.flow.collectWithErrors +import dev.inmo.tgbotapi.bot.RequestsExecutor +import dev.inmo.tgbotapi.types.update.CallbackQueryUpdate +import kotlinx.coroutines.launch +import java.lang.ref.WeakReference + +private val CallbackQueryReceiversScope = NewDefaultCoroutineScope() + +abstract class CallbackQueryReceiver( + executor: RequestsExecutor +) { + protected val executorWR = WeakReference(executor) + + init { + CallbackQueryReceiversScope.launch { + checkedCallbacksQueriesFlow.collectWithErrors(action = ::invoke) + } + } + + abstract suspend fun invoke(update: CallbackQueryUpdate) +} \ No newline at end of file diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/CallbackQueryReceivers/SafeCallbackQueryReceiver.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/CallbackQueryReceivers/SafeCallbackQueryReceiver.kt similarity index 53% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/CallbackQueryReceivers/SafeCallbackQueryReceiver.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/CallbackQueryReceivers/SafeCallbackQueryReceiver.kt index 5fb8300..e648c9d 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/CallbackQueryReceivers/SafeCallbackQueryReceiver.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/CallbackQueryReceivers/SafeCallbackQueryReceiver.kt @@ -1,9 +1,9 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.utils.CallbackQueryReceivers +package dev.inmo.AutoPostTelegramBot.utils.CallbackQueryReceivers -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor -import com.github.insanusmokrassar.TelegramBotAPI.types.CallbackQuery.MessageDataCallbackQuery -import com.github.insanusmokrassar.TelegramBotAPI.types.ChatIdentifier -import com.github.insanusmokrassar.TelegramBotAPI.types.update.CallbackQueryUpdate +import dev.inmo.tgbotapi.bot.RequestsExecutor +import dev.inmo.tgbotapi.types.CallbackQuery.MessageDataCallbackQuery +import dev.inmo.tgbotapi.types.ChatIdentifier +import dev.inmo.tgbotapi.types.update.CallbackQueryUpdate abstract class SafeCallbackQueryReceiver( executor: RequestsExecutor, diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/CallbackQueryReceivers/UnsafeCallbackQueryReceiver.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/CallbackQueryReceivers/UnsafeCallbackQueryReceiver.kt similarity index 52% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/CallbackQueryReceivers/UnsafeCallbackQueryReceiver.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/CallbackQueryReceivers/UnsafeCallbackQueryReceiver.kt index 248b032..13c1688 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/CallbackQueryReceivers/UnsafeCallbackQueryReceiver.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/CallbackQueryReceivers/UnsafeCallbackQueryReceiver.kt @@ -1,8 +1,8 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.utils.CallbackQueryReceivers +package dev.inmo.AutoPostTelegramBot.utils.CallbackQueryReceivers -import com.github.insanusmokrassar.AutoPostTelegramBot.flowFilter -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.flow.collectWithErrors -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor +import dev.inmo.AutoPostTelegramBot.flowFilter +import dev.inmo.AutoPostTelegramBot.utils.flow.collectWithErrors +import dev.inmo.tgbotapi.bot.RequestsExecutor import kotlinx.coroutines.* abstract class UnsafeCallbackQueryReceiver( diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/DateTime.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/DateTime.kt similarity index 98% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/DateTime.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/DateTime.kt index da12285..c529831 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/DateTime.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/DateTime.kt @@ -1,6 +1,6 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.utils +package dev.inmo.AutoPostTelegramBot.utils -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions.withoutTimeZoneOffset +import dev.inmo.AutoPostTelegramBot.utils.extensions.withoutTimeZoneOffset import org.joda.time.* import org.joda.time.format.DateTimeFormat @@ -106,7 +106,7 @@ private object CommonConverter : Converter { CalculatedDateTime( from, dateTime, - calculated.maxBy { + calculated.maxByOrNull { it.changeDifference } ?.changeDifference ?: throw IllegalStateException(), importantFields, diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/Files.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/Files.kt similarity index 85% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/Files.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/Files.kt index 27d01ea..b4ba4fe 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/Files.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/Files.kt @@ -1,4 +1,4 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.utils +package dev.inmo.AutoPostTelegramBot.utils import kotlinx.serialization.KSerializer import kotlinx.serialization.json.Json @@ -10,7 +10,7 @@ fun load( serializer: KSerializer, deserializationMethod: (InputStream) -> T = { val data = it.reader().readText() - Json.parse( + Json.Default.decodeFromString( serializer, data ) diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/MessagesResending.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/MessagesResending.kt similarity index 80% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/MessagesResending.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/MessagesResending.kt index 239ee8f..276f726 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/MessagesResending.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/MessagesResending.kt @@ -1,16 +1,15 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.utils +package dev.inmo.AutoPostTelegramBot.utils -import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor -import com.github.insanusmokrassar.TelegramBotAPI.requests.DeleteMessage -import com.github.insanusmokrassar.TelegramBotAPI.requests.ForwardMessage -import com.github.insanusmokrassar.TelegramBotAPI.requests.abstracts.Request -import com.github.insanusmokrassar.TelegramBotAPI.requests.send.media.SendMediaGroup -import com.github.insanusmokrassar.TelegramBotAPI.requests.send.media.membersCountInMediaGroup -import com.github.insanusmokrassar.TelegramBotAPI.types.* -import com.github.insanusmokrassar.TelegramBotAPI.types.message.abstracts.* -import com.github.insanusmokrassar.TelegramBotAPI.types.message.content.abstracts.MediaGroupContent -import com.github.insanusmokrassar.TelegramBotAPI.utils.extensions.executeAsync -import com.github.insanusmokrassar.TelegramBotAPI.utils.extensions.executeUnsafe +import dev.inmo.tgbotapi.bot.RequestsExecutor +import dev.inmo.tgbotapi.extensions.utils.shortcuts.executeAsync +import dev.inmo.tgbotapi.extensions.utils.shortcuts.executeUnsafe +import dev.inmo.tgbotapi.requests.DeleteMessage +import dev.inmo.tgbotapi.requests.ForwardMessage +import dev.inmo.tgbotapi.requests.abstracts.Request +import dev.inmo.tgbotapi.requests.send.media.SendMediaGroup +import dev.inmo.tgbotapi.types.* +import dev.inmo.tgbotapi.types.message.abstracts.* +import dev.inmo.tgbotapi.types.message.content.abstracts.MediaGroupContent private typealias ChatIdMessageIdPair = Pair @@ -105,7 +104,7 @@ suspend fun resend( when (it) { // media group is List<*> -> it.mapNotNull { - val asMediaGroupMessage = (it as MediaGroupMessage) + val asMediaGroupMessage = (it as MediaGroupMessage<*>) val fileUniqueId = asMediaGroupMessage.content.media.fileUniqueId sourceMessages.firstOrNull { sourceMessage -> (sourceMessage.content as? MediaGroupContent) ?.media ?.fileUniqueId == fileUniqueId @@ -148,18 +147,18 @@ private suspend fun sendMediaGroup( ) to listOf(content) ) } - contents.size in membersCountInMediaGroup -> { + contents.size in mediaCountInMediaGroup -> { val mediaGroupContent = contents.map { it to it.toMediaGroupMemberInputMedia() }.toMap() listOf( - SendMediaGroup( + SendMediaGroup( targetChatId, mediaGroupContent.values.toList() ) to contents.toList() ) } - else -> contents.chunked(membersCountInMediaGroup.endInclusive).flatMap { postMessages -> + else -> contents.chunked(mediaCountInMediaGroup.last).flatMap { postMessages -> sendMediaGroup(executor, targetChatId, postMessages) } } diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/NewDefaultCoroutineScope.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/NewDefaultCoroutineScope.kt similarity index 82% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/NewDefaultCoroutineScope.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/NewDefaultCoroutineScope.kt index 4f8721d..fe35a14 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/NewDefaultCoroutineScope.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/NewDefaultCoroutineScope.kt @@ -1,4 +1,4 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.utils +package dev.inmo.AutoPostTelegramBot.utils import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.asCoroutineDispatcher diff --git a/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/PluginsSerializer.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/PluginsSerializer.kt new file mode 100644 index 0000000..98f74d7 --- /dev/null +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/PluginsSerializer.kt @@ -0,0 +1,45 @@ +package dev.inmo.AutoPostTelegramBot.utils + +import dev.inmo.AutoPostTelegramBot.base.plugins.Plugin +import dev.inmo.AutoPostTelegramBot.utils.extensions.nonstrict +import dev.inmo.tgbotapi.utils.toJson +import kotlinx.serialization.* +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.json.* + +@Serializer(Plugin::class) +internal object PluginSerializer : KSerializer { + override val descriptor: SerialDescriptor = JsonArray.serializer().descriptor + + @InternalSerializationApi + override fun serialize(encoder: Encoder, value: Plugin) { + val array = JsonArray( + listOf( + JsonPrimitive(value::class.java.canonicalName), + value.toJson(value::class.serializer() as KSerializer) + ) + ) + JsonArray.serializer().serialize( + encoder, + array + ) + } + + @InternalSerializationApi + override fun deserialize(decoder: Decoder): Plugin { + val decoded = decoder.decodeSerializableValue(JsonArray.serializer()) + val expectedClass = decoded[0].jsonPrimitive.content + val expectedArgumentObject = decoded.getOrNull(1) as? JsonObject + val serializer = Class.forName(expectedClass).kotlin.serializer() + val argumentsObject = expectedArgumentObject ?.toString() ?: JsonObject(emptyMap()).toString() + return Json.nonstrict.decodeFromString( + serializer, + argumentsObject + ) as Plugin + } +} + +object PluginsListSerializer: KSerializer> by ListSerializer(PluginSerializer) diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/SafeLazy.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/SafeLazy.kt similarity index 90% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/SafeLazy.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/SafeLazy.kt index b60200d..90a7ec8 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/SafeLazy.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/SafeLazy.kt @@ -1,4 +1,4 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.utils +package dev.inmo.AutoPostTelegramBot.utils import io.ktor.utils.io.core.Closeable import kotlinx.coroutines.* @@ -37,7 +37,7 @@ class SafeLazy ( return try { value } catch (e: UninitializedPropertyAccessException) { - suspendCoroutine { requestsToGetValue.offer(it) } + suspendCoroutine { requestsToGetValue.trySend(it) } } } diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/SemaphoreK.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/SemaphoreK.kt similarity index 94% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/SemaphoreK.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/SemaphoreK.kt index 758251f..8240d7b 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/SemaphoreK.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/SemaphoreK.kt @@ -1,6 +1,6 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.utils +package dev.inmo.AutoPostTelegramBot.utils -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.commonLogger +import dev.inmo.AutoPostTelegramBot.base.plugins.commonLogger import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.isActive import kotlinx.coroutines.launch diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/Telegram.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/Telegram.kt similarity index 65% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/Telegram.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/Telegram.kt index f5b325f..e76d26d 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/Telegram.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/Telegram.kt @@ -1,6 +1,6 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.utils +package dev.inmo.AutoPostTelegramBot.utils -import com.github.insanusmokrassar.TelegramBotAPI.types.MessageIdentifier +import dev.inmo.tgbotapi.types.MessageIdentifier fun makeLinkToMessage( username: String, diff --git a/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/commands/Command.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/commands/Command.kt new file mode 100644 index 0000000..a226159 --- /dev/null +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/commands/Command.kt @@ -0,0 +1,51 @@ +package dev.inmo.AutoPostTelegramBot.utils.commands + +import dev.inmo.AutoPostTelegramBot.checkedMessagesFlow +import dev.inmo.AutoPostTelegramBot.utils.flow.collectWithErrors +import dev.inmo.tgbotapi.extensions.utils.updates.filterCommandsInsideTextMessages +import dev.inmo.tgbotapi.extensions.utils.updates.onlySentMessageUpdates +import dev.inmo.tgbotapi.types.MessageEntity.textsources.BotCommandTextSource +import dev.inmo.tgbotapi.types.UpdateIdentifier +import dev.inmo.tgbotapi.types.message.abstracts.CommonMessage +import dev.inmo.tgbotapi.types.message.content.TextContent +import dev.inmo.tgbotapi.types.update.abstracts.BaseMessageUpdate +import dev.inmo.tgbotapi.updateshandlers.UpdateReceiver +import kotlinx.coroutines.* +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.mapNotNull + +abstract class Command { + val callback: UpdateReceiver + get() = this::invoke + protected abstract val commandRegex: Regex + + init { + CoroutineScope(Dispatchers.Default).launch { + checkedMessagesFlow.collectWithErrors { + invoke(it) + } + } + } + + suspend fun invoke(p1: BaseMessageUpdate) { + (p1.data as? CommonMessage<*>) ?.let { message -> + (message.content as? TextContent) ?.also { + it.textSources.firstOrNull { source -> + source is BotCommandTextSource && (commandRegex.matches(source.command)) + } ?.also { + onCommand(p1.updateId, message) + } ?: if (commandRegex.matches(it.text)) { + onCommand(p1.updateId, message) + } + } + } + } + + abstract suspend fun onCommand(updateId: UpdateIdentifier, message: CommonMessage<*>) +} + +fun buildCommandFlow( + commandRegex: Regex +): Flow> = checkedMessagesFlow.onlySentMessageUpdates().filterCommandsInsideTextMessages( + commandRegex +).mapNotNull { it as? CommonMessage } diff --git a/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/commands/CommandPlugin.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/commands/CommandPlugin.kt new file mode 100644 index 0000000..aa5c0b3 --- /dev/null +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/commands/CommandPlugin.kt @@ -0,0 +1,20 @@ +package dev.inmo.AutoPostTelegramBot.utils.commands + +import dev.inmo.AutoPostTelegramBot.base.models.FinalConfig +import dev.inmo.AutoPostTelegramBot.base.plugins.Plugin +import dev.inmo.AutoPostTelegramBot.base.plugins.PluginManager +import dev.inmo.tgbotapi.bot.RequestsExecutor + +import java.lang.ref.WeakReference + +abstract class CommandPlugin : Command(), Plugin { + protected var botWR: WeakReference? = null + + override suspend fun onInit( + executor: RequestsExecutor, + baseConfig: FinalConfig, + pluginManager: PluginManager + ) { + botWR = WeakReference(executor) + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/Any.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/Any.kt similarity index 68% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/Any.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/Any.kt index a10187f..16e1844 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/Any.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/Any.kt @@ -1,10 +1,10 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions +package dev.inmo.AutoPostTelegramBot.utils.extensions -import com.github.insanusmokrassar.AutoPostTelegramBot.base.plugins.commonLogger -import com.github.insanusmokrassar.TelegramBotAPI.bot.exceptions.RequestException -import com.github.insanusmokrassar.TelegramBotAPI.types.buttons.Matrix -import com.github.insanusmokrassar.TelegramBotAPI.utils.matrix -import com.github.insanusmokrassar.TelegramBotAPI.utils.row +import dev.inmo.AutoPostTelegramBot.base.plugins.commonLogger +import dev.inmo.tgbotapi.bot.exceptions.RequestException +import dev.inmo.tgbotapi.types.buttons.Matrix +import dev.inmo.tgbotapi.utils.matrix +import dev.inmo.tgbotapi.utils.row import kotlin.math.ceil inline fun List.toTable(columns: Int): Matrix { diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/CalculatedDateTime.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/CalculatedDateTime.kt similarity index 86% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/CalculatedDateTime.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/CalculatedDateTime.kt index 744e1ed..957774e 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/CalculatedDateTime.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/CalculatedDateTime.kt @@ -1,7 +1,7 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions +package dev.inmo.AutoPostTelegramBot.utils.extensions -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.CalculatedDateTime -import com.github.insanusmokrassar.AutoPostTelegramBot.utils.NewDefaultCoroutineScope +import dev.inmo.AutoPostTelegramBot.utils.CalculatedDateTime +import dev.inmo.AutoPostTelegramBot.utils.NewDefaultCoroutineScope import kotlinx.coroutines.* import org.joda.time.DateTime diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/CoroutineScope.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/CoroutineScope.kt similarity index 84% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/CoroutineScope.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/CoroutineScope.kt index 946966a..0c1e90d 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/CoroutineScope.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/CoroutineScope.kt @@ -1,4 +1,4 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions +package dev.inmo.AutoPostTelegramBot.utils.extensions import kotlinx.coroutines.* diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/DateTime.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/DateTime.kt similarity index 75% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/DateTime.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/DateTime.kt index 4559cde..be75a81 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/DateTime.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/DateTime.kt @@ -1,4 +1,4 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions +package dev.inmo.AutoPostTelegramBot.utils.extensions import org.joda.time.DateTime import org.joda.time.DateTimeZone diff --git a/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/JsonNonstrict.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/JsonNonstrict.kt new file mode 100644 index 0000000..2cfe18f --- /dev/null +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/JsonNonstrict.kt @@ -0,0 +1,9 @@ +package dev.inmo.AutoPostTelegramBot.utils.extensions + +import kotlinx.serialization.json.Json + +val JsonNonstrict = Json { + ignoreUnknownKeys = false +} +val (Json.Default).nonstrict + get() = JsonNonstrict diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/String.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/String.kt similarity index 90% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/String.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/String.kt index f2c0adc..27ed5f8 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/String.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/String.kt @@ -1,4 +1,4 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions +package dev.inmo.AutoPostTelegramBot.utils.extensions fun String.splitByStep(step: Int): List { return (0 until length step step).map { diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/TelegramBot.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/TelegramBot.kt similarity index 98% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/TelegramBot.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/TelegramBot.kt index 2fb45d8..661b221 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/TelegramBot.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/TelegramBot.kt @@ -1,4 +1,4 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions +package dev.inmo.AutoPostTelegramBot.utils.extensions import org.slf4j.LoggerFactory diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/Throwable.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/Throwable.kt similarity index 76% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/Throwable.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/Throwable.kt index a531df4..5cb6183 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/extensions/Throwable.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/extensions/Throwable.kt @@ -1,4 +1,4 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions +package dev.inmo.AutoPostTelegramBot.utils.extensions import java.io.ByteArrayOutputStream import java.io.PrintStream diff --git a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/flow/CollectWithErrors.kt b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/flow/CollectWithErrors.kt similarity index 75% rename from src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/flow/CollectWithErrors.kt rename to src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/flow/CollectWithErrors.kt index ee5c3a6..efe3663 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/AutoPostTelegramBot/utils/flow/CollectWithErrors.kt +++ b/src/main/kotlin/dev/inmo/AutoPostTelegramBot/utils/flow/CollectWithErrors.kt @@ -1,14 +1,17 @@ -package com.github.insanusmokrassar.AutoPostTelegramBot.utils.flow +package dev.inmo.AutoPostTelegramBot.utils.flow import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect +import kotlinx.coroutines.supervisorScope suspend fun Flow.collectWithErrors( - onError: (suspend (value: T, throwable: Throwable) -> Unit)? = null, + onError: (suspend (value: T, throwable: Throwable) -> Unit)?, action: suspend (value: T) -> Unit ) = collect { try { - action(it) + supervisorScope { + action(it) + } } catch (e: Throwable) { onError ?.invoke(it, e) }