Skip to content

Commit

Permalink
new handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
Данила Беляков authored and Данила Беляков committed Nov 19, 2024
1 parent e33fa1d commit 569926e
Show file tree
Hide file tree
Showing 27 changed files with 272 additions and 85 deletions.
19 changes: 9 additions & 10 deletions alice-ktx/src/main/kotlin/com/github/alice/ktx/Skill.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import com.github.alice.ktx.middleware.MiddlewareType
import com.github.alice.ktx.fsm.models.FSMStrategy
import com.github.alice.ktx.models.request.MessageRequest
import com.github.alice.ktx.models.response.MessageResponse
import com.github.alice.ktx.server.WebServer
import com.github.alice.ktx.server.WebServerListener
import com.github.alice.ktx.webhook.WebhookServer
import com.github.alice.ktx.webhook.WebhookServerListener
import com.github.alice.ktx.fsm.FSMContext
import com.github.alice.ktx.fsm.MutableFSMContext
import com.github.alice.ktx.fsm.impl.BaseFSMContext
Expand All @@ -30,11 +30,11 @@ fun skill(body: Skill.Builder.() -> Unit): Skill = Skill.Builder().apply(body).b
/**
* Класс `Skill` представляет собой навык, который обрабатывает запросы и управляет состоянием.
*
* @property webServer Сервер для прослушивания запросов.
* @property webhookServer Сервер для прослушивания запросов.
* @property dispatcher Объект для управления обработчиками команд, мидлварами и обработчиками сетевых ошибок.
*/
class Skill internal constructor(
private val webServer: WebServer,
private val webhookServer: WebhookServer,
private val dispatcher: Dispatcher,
private val dialogApi: DialogApi?,
private val defaultFSMStrategy: FSMStrategy,
Expand All @@ -48,7 +48,7 @@ class Skill internal constructor(
@AliceDsl
class Builder {

lateinit var webServer: WebServer
lateinit var webhookServer: WebhookServer

var skillId: String? = null
var json: Json = Json {
Expand All @@ -69,7 +69,7 @@ class Skill internal constructor(

fun build(): Skill {
return Skill(
webServer = webServer,
webhookServer = webhookServer,
dialogApi = dialogApi,
defaultFSMStrategy = defaultFSMStrategy,
fsmContext = fsmContext,
Expand All @@ -83,16 +83,15 @@ class Skill internal constructor(
* Запускает сервер и начинает обработку входящих запросов.
*/
fun run() {
val webServerCallback = webServerResponseCallback()
webServer.run(webServerCallback)
webhookServer.run(webhookServerListener())
}

/**
* Создает слушатель для обработки запросов и ошибок от веб-сервера.
*
* @return Реализованный объект `WebServerResponseListener`, который обрабатывает входящие сообщения и ошибки.
* @return Реализованный объект `WebhookServerListener`, который обрабатывает входящие сообщения и ошибки.
*/
private fun webServerResponseCallback(): WebServerListener = object : WebServerListener {
private fun webhookServerListener(): WebhookServerListener = object : WebhookServerListener {
override suspend fun handleRequest(model: MessageRequest): MessageResponse? {
val requestEnvironment = createRequestEnvironment(model)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ interface ShouldRequestEnvironment {
val context: ReadOnlyFSMContext
val dialogApi: DialogApi?

fun filter(filter: Filter): Boolean {
fun isValidFor(filter: Filter): Boolean {
return filter.checkFor(this)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package com.github.alice.ktx.handlers.impl

import com.github.alice.ktx.Dispatcher
import com.github.alice.ktx.common.AliceDsl
import com.github.alice.ktx.handlers.Handler
import com.github.alice.ktx.handlers.environments.ProcessRequestEnvironment
import com.github.alice.ktx.handlers.environments.ShouldRequestEnvironment
import com.github.alice.ktx.models.request.content.RequestContentType
import com.github.alice.ktx.models.response.MessageResponse

@AliceDsl
data class AudioPlayerShouldRequestEnvironment(
private val request: ShouldRequestEnvironment
) : ShouldRequestEnvironment by request {

val type = message.request.type
val error = message.request.error
}

@AliceDsl
data class AudioPlayerProcessRequestEnvironment(
private val request: ProcessRequestEnvironment
) : ProcessRequestEnvironment by request {

val type = message.request.type
val error = message.request.error
}

@AliceDsl
fun Dispatcher.audioPlayer(
shouldHandle: suspend AudioPlayerShouldRequestEnvironment.() -> Boolean = { true },
processRequest: suspend AudioPlayerProcessRequestEnvironment.() -> MessageResponse
) {
addHandler(
AudioPlayerHandler(
shouldHandleBlock = shouldHandle,
processRequestBlock = processRequest
)
)
}

internal class AudioPlayerHandler (
private val shouldHandleBlock: suspend AudioPlayerShouldRequestEnvironment.() -> Boolean,
private val processRequestBlock: suspend AudioPlayerProcessRequestEnvironment.() -> MessageResponse
): Handler {
override suspend fun shouldHandle(request: ShouldRequestEnvironment): Boolean {
val audioPlayerTypes = setOf(
RequestContentType.AudioPlayerPlaybackStarted,
RequestContentType.AudioPlayerPlaybackFinished,
RequestContentType.AudioPlayerPlaybackNearlyFinished,
RequestContentType.AudioPlayerPlaybackStopped,
RequestContentType.AudioPlayerPlaybackFailed,
)

return request.message.request.type in audioPlayerTypes && shouldHandleBlock(AudioPlayerShouldRequestEnvironment(request))
}

override suspend fun processRequest(request: ProcessRequestEnvironment): MessageResponse {
return processRequestBlock(AudioPlayerProcessRequestEnvironment(request))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import com.github.alice.ktx.common.AliceDsl
import com.github.alice.ktx.handlers.Handler
import com.github.alice.ktx.handlers.environments.ProcessRequestEnvironment
import com.github.alice.ktx.handlers.environments.ShouldRequestEnvironment
import com.github.alice.ktx.handlers.filters.Filter
import com.github.alice.ktx.models.request.content.RequestContentType
import com.github.alice.ktx.models.response.MessageResponse

/**
Expand All @@ -17,6 +19,7 @@ data class MessageShouldHandleEnvironment(

val command = request.message.request.command ?: ""
val messageText = request.message.request.originalUtterance ?: ""
val nlu = request.message.request.nlu
}

/**
Expand All @@ -29,6 +32,18 @@ data class MessageProcessRequestEnvironment(

val command = request.message.request.command ?: ""
val messageText = request.message.request.originalUtterance ?: ""
val nlu = request.message.request.nlu
}

@AliceDsl
fun Dispatcher.message(
filter: Filter,
processRequest: suspend MessageProcessRequestEnvironment.() -> MessageResponse
) {
message(
shouldHandle = { filter.checkFor(this) },
processRequest = processRequest
)
}

/**
Expand Down Expand Up @@ -67,9 +82,7 @@ internal class MessageHandler(
* @return `true`, если обработчик должен сработать, в противном случае `false`.
*/
override suspend fun shouldHandle(request: ShouldRequestEnvironment): Boolean {
return request.message.request.command != null &&
request.message.request.originalUtterance != null &&
shouldHandleBlock(MessageShouldHandleEnvironment(request))
return request.message.request.type == RequestContentType.SimpleUtterance && shouldHandleBlock(MessageShouldHandleEnvironment(request))
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package com.github.alice.ktx.handlers.impl

import com.github.alice.ktx.Dispatcher
import com.github.alice.ktx.common.AliceDsl
import com.github.alice.ktx.handlers.Handler
import com.github.alice.ktx.handlers.environments.ProcessRequestEnvironment
import com.github.alice.ktx.handlers.environments.ShouldRequestEnvironment
import com.github.alice.ktx.models.request.content.RequestContentType
import com.github.alice.ktx.models.response.MessageResponse

@AliceDsl
data class PurchaseConfirmationShouldRequestEnvironment(
private val request: ShouldRequestEnvironment
) : ShouldRequestEnvironment by request {

val purchaseRequestId = message.request.purchaseRequestId
val purchaseToken = message.request.purchaseToken
val orderId = message.request.orderId
val purchaseTimestamp = message.request.purchaseTimestamp
val purchasePayload = message.request.purchasePayload
val signedData = message.request.signedData
val signature = message.request.signature
}

@AliceDsl
data class PurchaseConfirmationProcessRequestEnvironment(
private val request: ProcessRequestEnvironment
) : ProcessRequestEnvironment by request {

val purchaseRequestId = message.request.purchaseRequestId
val purchaseToken = message.request.purchaseToken
val orderId = message.request.orderId
val purchaseTimestamp = message.request.purchaseTimestamp
val purchasePayload = message.request.purchasePayload
val signedData = message.request.signedData
val signature = message.request.signature
}

@AliceDsl
fun Dispatcher.purchaseConfirmation(
shouldHandle: suspend PurchaseConfirmationShouldRequestEnvironment.() -> Boolean = { true },
processRequest: suspend PurchaseConfirmationProcessRequestEnvironment.() -> MessageResponse
) {
addHandler(
PurchaseConfirmationHandler(
shouldHandleBlock = shouldHandle,
processRequestBlock = processRequest
)
)
}

internal class PurchaseConfirmationHandler(
private val shouldHandleBlock: suspend PurchaseConfirmationShouldRequestEnvironment.() -> Boolean,
private val processRequestBlock: suspend PurchaseConfirmationProcessRequestEnvironment.() -> MessageResponse
): Handler {
override suspend fun shouldHandle(request: ShouldRequestEnvironment): Boolean {
return request.message.request.type == RequestContentType.PurchaseConfirmation
&& shouldHandleBlock(PurchaseConfirmationShouldRequestEnvironment(request))
}

override suspend fun processRequest(request: ProcessRequestEnvironment): MessageResponse {
return processRequestBlock(PurchaseConfirmationProcessRequestEnvironment(request))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.github.alice.ktx.handlers.impl

import com.github.alice.ktx.Dispatcher
import com.github.alice.ktx.common.AliceDsl
import com.github.alice.ktx.handlers.Handler
import com.github.alice.ktx.handlers.environments.ProcessRequestEnvironment
import com.github.alice.ktx.handlers.environments.ShouldRequestEnvironment
import com.github.alice.ktx.models.request.content.RequestContentType
import com.github.alice.ktx.models.response.MessageResponse

@AliceDsl
data class ShowPullShouldRequestEnvironment(
private val request: ShouldRequestEnvironment
) : ShouldRequestEnvironment by request {

val showType = checkNotNull(request.message.request.showType)
}

@AliceDsl
data class ShowPullProcessRequestEnvironment(
private val request: ProcessRequestEnvironment
) : ProcessRequestEnvironment by request {

val showType = checkNotNull(request.message.request.showType)
}

@AliceDsl
fun Dispatcher.showPull(
shouldHandle: suspend ShowPullShouldRequestEnvironment.() -> Boolean = { true },
processRequest: suspend ShowPullProcessRequestEnvironment.() -> MessageResponse
) {
addHandler(
ShowPullHandler(
shouldHandleBlock = shouldHandle,
processRequestBlock = processRequest
)
)
}

internal class ShowPullHandler(
private val shouldHandleBlock: suspend ShowPullShouldRequestEnvironment.() -> Boolean,
private val processRequestBlock: suspend ShowPullProcessRequestEnvironment.() -> MessageResponse
) : Handler {
override suspend fun shouldHandle(request: ShouldRequestEnvironment): Boolean {
return request.message.request.type == RequestContentType.ShowPull
&& shouldHandleBlock(ShowPullShouldRequestEnvironment(request))
}

override suspend fun processRequest(request: ProcessRequestEnvironment): MessageResponse {
return processRequestBlock(ShowPullProcessRequestEnvironment(request))
}
}
15 changes: 0 additions & 15 deletions alice-ktx/src/main/kotlin/com/github/alice/ktx/server/WebServer.kt

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import com.github.alice.ktx.storage.key.KeyBuilder
import com.github.alice.ktx.storage.key.impl.baseKeyBuilder
import com.github.alice.ktx.storage.models.*
import kotlinx.serialization.InternalSerializationApi
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.serializer
import kotlin.reflect.KClass
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.github.alice.ktx.webhook

/**
* Интерфейс `WebhookServer` определяет контракт для веб-сервера, который может быть запущен и обрабатывать запросы.
*/
interface WebhookServer {

/**
* Запускает веб-сервер и начинает обработку запросов.
*
* @param listener Обработчик, который будет вызван при получении запроса.
*/
fun run(listener: WebhookServerListener)

}
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package com.github.alice.ktx.server
package com.github.alice.ktx.webhook

import com.github.alice.ktx.models.request.MessageRequest
import com.github.alice.ktx.models.response.MessageResponse
import java.lang.Exception

/**
* Интерфейс `WebServerListener` представляет собой обработчик, который будет вызываться при получении запроса веб-сервером.
* Интерфейс `WebhookServerListener` представляет собой обработчик, который будет вызываться при получении запроса веб-сервером.
*/
interface WebServerListener {
interface WebhookServerListener {

/**
* Вызывается при получении запроса от Яндекс Диалогов
Expand Down
Loading

0 comments on commit 569926e

Please sign in to comment.