/
GABuilders.kt
344 lines (308 loc) · 11.4 KB
/
GABuilders.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
/*
* Copyright (C) 2017/2021 e-voyageurs technologies
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.tock.bot.connector.ga
import ai.tock.bot.connector.ConnectorMessage
import ai.tock.bot.connector.ConnectorType
import ai.tock.bot.connector.ga.model.GAIntent
import ai.tock.bot.connector.ga.model.request.GAPermission
import ai.tock.bot.connector.ga.model.response.GABasicCard
import ai.tock.bot.connector.ga.model.response.GAButton
import ai.tock.bot.connector.ga.model.response.GACarouselSelect
import ai.tock.bot.connector.ga.model.response.GAExpectedInput
import ai.tock.bot.connector.ga.model.response.GAExpectedIntent
import ai.tock.bot.connector.ga.model.response.GAFinalResponse
import ai.tock.bot.connector.ga.model.response.GAImage
import ai.tock.bot.connector.ga.model.response.GAInputPrompt
import ai.tock.bot.connector.ga.model.response.GAItem
import ai.tock.bot.connector.ga.model.response.GALinkOutSuggestion
import ai.tock.bot.connector.ga.model.response.GAListSelect
import ai.tock.bot.connector.ga.model.response.GAOpenUrlAction
import ai.tock.bot.connector.ga.model.response.GAOptionInfo
import ai.tock.bot.connector.ga.model.response.GAOptionValueSpec
import ai.tock.bot.connector.ga.model.response.GAPermissionValueSpec
import ai.tock.bot.connector.ga.model.response.GARichResponse
import ai.tock.bot.connector.ga.model.response.GASimpleResponse
import ai.tock.bot.connector.ga.model.response.GASimpleSelect
import ai.tock.bot.connector.ga.model.response.GAStructuredResponse
import ai.tock.bot.connector.ga.model.response.GAUpdatePermissionValueSpec
import ai.tock.bot.definition.IntentAware
import ai.tock.bot.definition.StoryHandlerDefinition
import ai.tock.bot.definition.StoryStep
import ai.tock.bot.engine.Bus
import ai.tock.bot.engine.I18nTranslator
import ai.tock.bot.engine.action.SendChoice
import ai.tock.translator.UserInterfaceType.textAndVoiceAssistant
import ai.tock.translator.UserInterfaceType.textChat
import com.vdurmont.emoji.EmojiParser
import mu.KotlinLogging
private val logger = KotlinLogging.logger {}
internal const val GA_CONNECTOR_TYPE_ID = "ga"
/**
* The Google Assistant [ConnectorType].
*/
val gaConnectorType = ConnectorType(GA_CONNECTOR_TYPE_ID, textAndVoiceAssistant)
/**
* Sends a Google Assistant message only if the [ConnectorType] of the current [BotBus] is [gaConnectorType].
*/
fun <T : Bus<T>> T.sendToGoogleAssistant(
messageProvider: T.() -> GAResponseConnectorMessage,
delay: Long = defaultDelay(currentAnswerIndex)
): T {
if (targetConnectorType == gaConnectorType) {
withMessage(messageProvider(this))
send(delay)
}
return this
}
/**
* Sends a Google Assistant message as last bot answer, only if the [ConnectorType] of the current [BotBus] is [gaConnectorType].
*/
fun <T : Bus<T>> T.endForGoogleAssistant(
messageProvider: T.() -> GAResponseConnectorMessage,
delay: Long = defaultDelay(currentAnswerIndex)
): T {
if (targetConnectorType == gaConnectorType) {
withMessage(messageProvider(this))
end(delay)
}
return this
}
/**
* Adds a Google Assistant [ConnectorMessage] if the current connector is Google Assistant.
* You need to call [BotBus.send] or [BotBus.end] later to send this message.
*/
fun <T : Bus<T>> T.withGoogleAssistant(messageProvider: () -> GAResponseConnectorMessage): T {
return withMessage(gaConnectorType, messageProvider)
}
/**
* If the device supports audio, adds a Google Assistant [ConnectorMessage] if the current connector is Google Assistant.
* You need to call [BotBus.send] or [BotBus.end] later to send this message.
*/
fun <T : Bus<T>> T.withGoogleVoiceAssistant(messageProvider: () -> GAResponseConnectorMessage): T {
if (userInterfaceType != textChat) {
withMessage(gaConnectorType, messageProvider)
}
return this
}
/**
* Final Google Assistant message (end of conversation).
*/
fun I18nTranslator.gaFinalMessage(richResponse: GARichResponse): GAResponseConnectorMessage =
GAResponseConnectorMessage(finalResponse = GAFinalResponse(richResponse))
/**
* Final Google Assistant message (end of conversation).
*/
fun I18nTranslator.gaFinalMessage(text: CharSequence? = null): GAResponseConnectorMessage =
gaFinalMessage(
if (text == null)
// empty rich response
richResponse(emptyList())
else richResponse(text)
)
/**
* Google Assistant Message with all available parameters.
*/
fun I18nTranslator.gaMessage(
inputPrompt: GAInputPrompt,
possibleIntents: List<GAExpectedIntent> = listOf(
expectedTextIntent()
),
speechBiasingHints: List<String> = emptyList()
): GAResponseConnectorMessage =
GAResponseConnectorMessage(
GAExpectedInput(
inputPrompt,
if (possibleIntents.isEmpty()) listOf(expectedTextIntent()) else possibleIntents,
speechBiasingHints
)
)
fun gaLogout(): GAResponseConnectorMessage =
GAResponseConnectorMessage(
logoutEvent = true
)
/**
* Google Assistant Message with suggestions.
*/
fun I18nTranslator.gaMessage(text: CharSequence, vararg suggestions: CharSequence): GAResponseConnectorMessage =
if (suggestions.isEmpty()) gaMessage(inputPrompt(text)) else gaMessage(richResponse(text, *suggestions))
/**
* Google Assistant Message with [GABasicCard].
*/
fun I18nTranslator.gaMessage(text: CharSequence, basicCard: GABasicCard): GAResponseConnectorMessage =
gaMessage(richResponse(listOf(GAItem(simpleResponse(text)), GAItem(basicCard = basicCard))))
/**
* Google Assistant Message with [GARichResponse].
*/
fun I18nTranslator.gaMessage(richResponse: GARichResponse): GAResponseConnectorMessage =
gaMessage(inputPrompt(richResponse))
/**
* Google Assistant Message with one [GAExpectedIntent].
*/
fun I18nTranslator.gaMessage(possibleIntent: GAExpectedIntent): GAResponseConnectorMessage =
gaMessage(listOf(possibleIntent))
/**
* Google Assistant Message with multiple [GAExpectedIntent].
*/
fun I18nTranslator.gaMessage(possibleIntents: List<GAExpectedIntent>): GAResponseConnectorMessage =
gaMessage(inputPrompt(GARichResponse(emptyList())), possibleIntents)
/**
* Google Assistant Message with text and multiple [GAExpectedIntent].
*/
fun I18nTranslator.gaMessage(text: CharSequence, possibleIntents: List<GAExpectedIntent>): GAResponseConnectorMessage =
gaMessage(
inputPrompt(richResponse(text)),
possibleIntents
)
/**
* Google Assistant Message asking for [GAPermission].
*/
fun I18nTranslator.permissionIntent(
optionalContext: CharSequence? = null,
vararg permissions: GAPermission
): GAExpectedIntent {
return GAExpectedIntent(
GAIntent.permission,
GAPermissionValueSpec(
translate(optionalContext).toString(),
permissions.toSet()
)
)
}
/**
* Google Assistant Message asking for update [GAPermission].
*/
fun I18nTranslator.updatePermissionIntent(
intent: String
): GAExpectedIntent {
return GAExpectedIntent(
GAIntent.permission,
GAPermissionValueSpec(
null,
setOf(GAPermission.UPDATE),
GAUpdatePermissionValueSpec(intent)
)
)
}
/**
* Provides a [GALinkOutSuggestion].
*/
fun I18nTranslator.linkOutSuggestion(destinationName: CharSequence, url: String): GALinkOutSuggestion {
val d = translate(destinationName)
if (d.length > 20) {
logger.warn { "title $d has more than 20 chars" }
}
return GALinkOutSuggestion(d.toString(), url)
}
/**
* Provides a [GAItem] with all available parameters.
*/
fun I18nTranslator.item(
simpleResponse: GASimpleResponse? = null,
basicCard: GABasicCard? = null,
structuredResponse: GAStructuredResponse? = null
): GAItem = GAItem(simpleResponse, basicCard, structuredResponse)
/**
* Provides a [GAItem] with a [GABasicCard].
*/
fun I18nTranslator.item(basicCard: GABasicCard): GAItem = item(null, basicCard, null)
/**
* Provides a [GAItem] with a [GAStructuredResponse].
*/
fun I18nTranslator.item(structuredResponse: GAStructuredResponse): GAItem = item(null, null, structuredResponse)
/**
* Provides a [GAItem] with a [GASimpleResponse].
*/
fun I18nTranslator.item(simpleResponse: GASimpleResponse): GAItem = item(simpleResponse, null, null)
/**
* Provides a [GAImage] with all available parameters.
*/
fun I18nTranslator.gaImage(
url: String,
accessibilityText: CharSequence,
height: Int? = null,
width: Int? = null
): GAImage {
val a = translate(accessibilityText)
return GAImage(url, a.toString(), height, width)
}
/**
* Provides a [GAOptionValueSpec] with all available parameters.
*/
fun I18nTranslator.optionValueSpec(
simpleSelect: GASimpleSelect? = null,
listSelect: GAListSelect? = null,
carouselSelect: GACarouselSelect? = null
): GAOptionValueSpec = GAOptionValueSpec(simpleSelect, listSelect, carouselSelect)
/**
* Provides a [GAInputPrompt] with all available parameters.
*/
fun I18nTranslator.inputPrompt(
richResponse: GARichResponse,
noInputPrompts: List<GASimpleResponse> = emptyList()
): GAInputPrompt = GAInputPrompt(richResponse, noInputPrompts)
/**
* Provides a [GAInputPrompt] with a simple [GARichResponse] builder.
*/
fun I18nTranslator.inputPrompt(
text: CharSequence,
linkOutSuggestion: GALinkOutSuggestion? = null,
noInputPrompts: List<GASimpleResponse> = emptyList()
): GAInputPrompt = inputPrompt(richResponse(text, linkOutSuggestion), noInputPrompts)
/**
* Provides a [GAButton].
*/
fun I18nTranslator.gaButton(title: CharSequence, url: String): GAButton {
return GAButton(translate(title).toString(), GAOpenUrlAction(url))
}
/**
* Provides a [GAOptionInfo] with all available parameters.
*/
fun <T : Bus<T>> T.optionInfo(
title: CharSequence,
targetIntent: IntentAware,
step: StoryStep<out StoryHandlerDefinition>? = null,
vararg parameters: Pair<String, String>
): GAOptionInfo {
val t = translate(title)
// add the title to the parameters as we need to double check the title in WebhookActionConverter
val map = parameters.toMap() + (SendChoice.TITLE_PARAMETER to t.toString())
return GAOptionInfo(
SendChoice.encodeChoiceId(
this,
targetIntent,
step,
map
),
listOf(t.toString())
)
}
/**
* The common [GAIntent.text] [GAExpectedIntent].
*/
fun expectedTextIntent(): GAExpectedIntent = GAExpectedIntent(GAIntent.text)
internal fun String.endWithPunctuation(): Boolean =
endsWith(".") || endsWith("!") || endsWith("?") || endsWith(",") || endsWith(";") || endsWith(":")
internal fun concat(s1: String?, s2: String?): String {
val s = s1?.trim() ?: ""
return s + (if (s.isEmpty() || s.endWithPunctuation()) " " else ". ") + (s2?.trim() ?: "")
}
internal fun String.removeEmojis(): String =
EmojiParser.removeAllEmojis(
EmojiParser.parseToUnicode(this.replace("://", "_____"))
.replace("\uD83D\uDC68", ":3")
.replace("\uD83D\uDE2E", ":0")
.replace("_____", "://")
)