1
0
mirror of https://github.com/InsanusMokrassar/TelegramBotAPI.git synced 2025-09-02 22:59:48 +00:00

replace webhooks work into api subproject

This commit is contained in:
2020-05-13 21:21:07 +06:00
parent e776c5182f
commit 05e8c9c90d
7 changed files with 388 additions and 117 deletions

View File

@@ -3,6 +3,13 @@ package com.github.insanusmokrassar.TelegramBotAPI.types.update.MediaGroupUpdate
import com.github.insanusmokrassar.TelegramBotAPI.types.message.abstracts.MediaGroupMessage
import com.github.insanusmokrassar.TelegramBotAPI.types.update.abstracts.*
/**
* By default there is no instances of objects which could be deserialized from raw updates. If you want to get objects
* with this type, you should use something like [com.github.insanusmokrassar.TelegramBotAPI.extensions.api.SetWebhookKt.includeWebhookInRoute]
*
* @see com.github.insanusmokrassar.TelegramBotAPI.extensions.api.SetWebhookKt.includeWebhookInRoute
* @see com.github.insanusmokrassar.TelegramBotAPI.extensions.api.updates.UpdatesPollingKt.startGettingOfUpdates
*/
interface MediaGroupUpdate : Update
interface SentMediaGroupUpdate: MediaGroupUpdate {

View File

@@ -17,114 +17,10 @@ import io.ktor.server.engine.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
/**
* @param [scope] Will be used for mapping of media groups
* @param [exceptionsHandler] Pass this parameter to set custom exception handler for getting updates
* @param [block] Some receiver block like [com.github.insanusmokrassar.TelegramBotAPI.updateshandlers.FlowsUpdatesFilter]
*
* @see com.github.insanusmokrassar.TelegramBotAPI.updateshandlers.FlowsUpdatesFilter
* @see UpdatesFilter
* @see UpdatesFilter.asUpdateReceiver
*/
fun Route.includeWebhookInRoute(
scope: CoroutineScope,
exceptionsHandler: (suspend (Exception) -> Unit)? = null,
block: UpdateReceiver<Update>
): Job {
val updatesChannel = Channel<Update>(Channel.UNLIMITED)
val mediaGroupChannel = Channel<Pair<String, BaseMessageUpdate>>(Channel.UNLIMITED)
val mediaGroupAccumulatedChannel = mediaGroupChannel.accumulateByKey(
1000L,
scope = scope
)
post {
handleSafely(
exceptionsHandler ?: {}
) {
val asJson = nonstrictJsonFormat.parseJson(call.receiveText())
val update = nonstrictJsonFormat.fromJson(
UpdateDeserializationStrategy,
asJson
)
updatesChannel.send(update)
}
call.respond("Ok")
}
return scope.launch {
launch {
for (update in updatesChannel) {
when (val data = update.data) {
is MediaGroupMessage -> mediaGroupChannel.send("${data.mediaGroupId}${update::class.simpleName}" to update as BaseMessageUpdate)
else -> block(update)
}
}
}
launch {
for ((_, mediaGroup) in mediaGroupAccumulatedChannel) {
mediaGroup.convertWithMediaGroupUpdates().forEach {
block(it)
}
}
}
}
}
/**
* Setting up ktor server, set webhook info via [SetWebhook] request.
*
* @param port port which will be listen by bot
* @param listenRoute address to listen by bot
* @param scope Scope which will be used for
*
* @see com.github.insanusmokrassar.TelegramBotAPI.updateshandlers.FlowsUpdatesFilter
* @see UpdatesFilter
* @see UpdatesFilter.asUpdateReceiver
*/
fun setWebhook(
port: Int,
engineFactory: ApplicationEngineFactory<*, *>,
listenHost: String = "0.0.0.0",
listenRoute: String = "/",
privateKeyConfig: WebhookPrivateKeyConfig? = null,
scope: CoroutineScope = CoroutineScope(Executors.newFixedThreadPool(4).asCoroutineDispatcher()),
exceptionsHandler: (suspend (Exception) -> Unit)? = null,
block: UpdateReceiver<Update>
): ApplicationEngine {
lateinit var engine: ApplicationEngine
val env = applicationEngineEnvironment {
module {
routing {
route(listenRoute) {
includeWebhookInRoute(scope, exceptionsHandler, block)
}
}
}
privateKeyConfig ?.let {
sslConnector(
privateKeyConfig.keyStore,
privateKeyConfig.aliasName,
privateKeyConfig::keyStorePassword,
privateKeyConfig::aliasPassword
) {
host = listenHost
this.port = port
}
} ?: connector {
host = listenHost
this.port = port
}
}
engine = embeddedServer(engineFactory, env)
engine.start(false)
return engine
}
/**
* Setting up ktor server, set webhook info via [SetWebhook] request.
* Reverse proxy webhook.
*
* @param url URL of webhook WITHOUT including of [port]
* @param port port which will be listen by bot
@@ -132,11 +28,8 @@ fun setWebhook(
* @param certificate [com.github.insanusmokrassar.TelegramBotAPI.requests.abstracts.MultipartFile] or [com.github.insanusmokrassar.TelegramBotAPI.requests.abstracts.FileId]
* which will be used by telegram to send encrypted messages
* @param scope Scope which will be used for
*
* @see com.github.insanusmokrassar.TelegramBotAPI.updateshandlers.FlowsUpdatesFilter
* @see UpdatesFilter
* @see UpdatesFilter.asUpdateReceiver
*/
@Deprecated("Replaced into project TelegramBotAPI-extensions-api")
suspend fun RequestsExecutor.setWebhook(
url: String,
port: Int,
@@ -167,20 +60,84 @@ suspend fun RequestsExecutor.setWebhook(
allowedUpdates
)
)
val updatesChannel = Channel<Update>(Channel.UNLIMITED)
val mediaGroupChannel = Channel<Pair<String, BaseMessageUpdate>>(Channel.UNLIMITED)
val mediaGroupAccumulatedChannel = mediaGroupChannel.accumulateByKey(
1000L,
scope = scope
)
val env = applicationEngineEnvironment {
return try {
executeDeferred.await()
val engine = setWebhook(port, engineFactory, listenHost, listenRoute, privateKeyConfig, scope, exceptionsHandler, block)
scope.launch {
engine.environment.parentCoroutineContext[Job] ?.join()
engine.stop(1000, 5000)
module {
routing {
post(listenRoute) {
handleSafely(
{
exceptionsHandler ?.invoke(it)
}
) {
val asJson = nonstrictJsonFormat.parseJson(call.receiveText())
val update = nonstrictJsonFormat.fromJson(
UpdateDeserializationStrategy,
asJson
)
updatesChannel.send(update)
}
call.respond("Ok")
}
}
}
privateKeyConfig ?.let {
sslConnector(
privateKeyConfig.keyStore,
privateKeyConfig.aliasName,
privateKeyConfig::keyStorePassword,
privateKeyConfig::aliasPassword
) {
host = listenHost
this.port = port
}
} ?: connector {
host = listenHost
this.port = port
}
}
val engine = embeddedServer(engineFactory, env)
try {
executeDeferred.await()
} catch (e: Exception) {
env.stop()
throw e
}
return scope.launch {
launch {
for (update in updatesChannel) {
val data = update.data
when (data) {
is MediaGroupMessage -> mediaGroupChannel.send("${data.mediaGroupId}${update::class.simpleName}" to update as BaseMessageUpdate)
else -> block(update)
}
}
}
launch {
for ((_, mediaGroup) in mediaGroupAccumulatedChannel) {
mediaGroup.convertWithMediaGroupUpdates().forEach {
block(it)
}
}
}
engine.start(false)
}.also {
it.invokeOnCompletion {
engine.stop(1000L, 0L, TimeUnit.MILLISECONDS)
}
}
}
@Deprecated("Replaced into project TelegramBotAPI-extensions-api")
suspend fun RequestsExecutor.setWebhook(
url: String,
port: Int,
@@ -208,6 +165,7 @@ suspend fun RequestsExecutor.setWebhook(
block
)
@Deprecated("Replaced into project TelegramBotAPI-extensions-api")
suspend fun RequestsExecutor.setWebhook(
url: String,
port: Int,
@@ -232,6 +190,7 @@ suspend fun RequestsExecutor.setWebhook(
block
)
@Deprecated("Replaced into project TelegramBotAPI-extensions-api")
suspend fun RequestsExecutor.setWebhook(
url: String,
port: Int,