-
Notifications
You must be signed in to change notification settings - Fork 132
/
IntentHandler.ts
509 lines (433 loc) · 20.2 KB
/
IntentHandler.ts
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
import { MessageHandler } from "../BasicFDC3Server";
import { AppRegistration, InstanceID, ServerContext } from "../ServerContext";
import { Directory, DirectoryIntent } from "../directory/DirectoryInterface";
import { Context } from "@kite9/fdc3-context";
import { AppIntent, ResolveError, AppIdentifier, } from "@kite9/fdc3-standard";
import { errorResponse, errorResponseId, successResponse, successResponseId } from "./support";
import { BrowserTypes } from "@kite9/fdc3-schema";
type AddIntentListenerRequest = BrowserTypes.AddIntentListenerRequest
type FindIntentRequest = BrowserTypes.FindIntentRequest
type FindIntentsByContextRequest = BrowserTypes.FindIntentsByContextRequest
type IntentEvent = BrowserTypes.IntentEvent
type IntentListenerUnsubscribeRequest = BrowserTypes.IntentListenerUnsubscribeRequest
type RaiseIntentRequest = BrowserTypes.RaiseIntentRequest
type RaiseIntentForContextRequest = BrowserTypes.RaiseIntentForContextRequest
type IntentResultRequest = BrowserTypes.IntentResultRequest
type ListenerRegistration = {
appId: string | undefined,
instanceId: string | undefined,
intentName: string | undefined,
listenerUUID: string
}
type IntentRequest = {
intent: string,
context: Context,
requestUuid: string,
from: AppIdentifier,
type: 'raiseIntentResponse' | 'raiseIntentForContextResponse'
}
/**
* Re-writes the request to forward it on to the target application
*/
async function forwardRequest(arg0: IntentRequest, to: AppIdentifier, sc: ServerContext<AppRegistration>, ih: IntentHandler): Promise<void> {
const out: IntentEvent = {
type: 'intentEvent',
payload: {
context: arg0.context,
intent: arg0.intent,
originatingApp: {
appId: arg0.from.appId,
instanceId: arg0.from.instanceId
},
raiseIntentRequestUuid: arg0.requestUuid
},
meta: {
eventUuid: sc.createUUID(),
timestamp: new Date()
}
}
// register the resolution destination
ih.pendingResolutions.set(arg0.requestUuid, arg0.from)
await sc.post(out, to.instanceId!!)
successResponseId(sc, arg0.requestUuid, arg0.from, {
intentResolution: {
intent: arg0.intent,
source: to
}
}, arg0.type)
}
/**
* A pending intent is one for an app that hasn't registered it's intent listener yet.
* (Possibly it is being opened)
*
* Pending intents wait for that registration and then message the app.
*/
class PendingIntent {
complete: boolean = false
r: IntentRequest
appId: AppIdentifier
sc: ServerContext<AppRegistration>
ih: IntentHandler
constructor(r: IntentRequest, sc: ServerContext<AppRegistration>, ih: IntentHandler, appId: AppIdentifier) {
this.r = r
this.appId = appId
this.sc = sc
this.ih = ih
// handle the timeout
setTimeout(() => {
if (!this.complete) {
errorResponseId(sc, r.requestUuid, r.from, ResolveError.IntentDeliveryFailed, r.type)
this.ih.pendingIntents.delete(this)
}
}, ih.timeoutMs)
}
async accept(arg0: ListenerRegistration): Promise<void> {
if ((arg0.appId == this.appId.appId) &&
(arg0.intentName == this.r.intent) &&
((arg0.instanceId == this.appId.instanceId) || (this.appId.instanceId == undefined))) {
this.complete = true
this.ih.pendingIntents.delete(this)
forwardRequest(this.r, { appId: arg0.appId, instanceId: arg0.instanceId }, this.sc, this.ih)
}
}
}
export class IntentHandler implements MessageHandler {
private readonly directory: Directory
private readonly regs: ListenerRegistration[] = []
readonly pendingIntents: Set<PendingIntent> = new Set()
readonly pendingResolutions: Map<string, AppIdentifier> = new Map()
readonly timeoutMs: number
constructor(d: Directory, timeoutMs: number) {
this.directory = d
this.timeoutMs = timeoutMs
}
shutdown(): void {
}
async narrowIntents(raiser: AppIdentifier, appIntents: AppIntent[], context: Context, sc: ServerContext<AppRegistration>): Promise<AppIntent[]> {
const out = await sc.narrowIntents(raiser, appIntents, context)
return out
}
async accept(msg: any, sc: ServerContext<AppRegistration>, uuid: InstanceID): Promise<void> {
const from = sc.getInstanceDetails(uuid)
if (from == null) {
// this handler only deals with connected apps
return
}
try {
switch (msg.type as string) {
// finding intents
case 'findIntentsByContextRequest': return this.findIntentsByContextRequest(msg as FindIntentsByContextRequest, sc, from)
case 'findIntentRequest': return this.findIntentRequest(msg as FindIntentRequest, sc, from)
// listeners
case 'addIntentListenerRequest': return this.onAddIntentListener(msg as AddIntentListenerRequest, sc, from)
case 'intentListenerUnsubscribeRequest': return this.onUnsubscribe(msg as IntentListenerUnsubscribeRequest, sc, from)
// raising intents and returning results
case 'raiseIntentRequest': return this.raiseIntentRequest(msg as RaiseIntentRequest, sc, from)
case 'raiseIntentForContextRequest': return this.raiseIntentForContextRequest(msg as RaiseIntentForContextRequest, sc, from)
case 'intentResultRequest': return this.intentResultRequest(msg as IntentResultRequest, sc, from)
}
} catch (e: any) {
const responseType = msg.type.replace(new RegExp("Request$"), 'Response')
errorResponse(sc, msg, from, e.message ?? e, responseType)
}
}
/**
* Called when target app handles an intent
*/
intentResultRequest(arg0: IntentResultRequest, sc: ServerContext<AppRegistration>, from: AppIdentifier): void | PromiseLike<void> {
const requestId = arg0.payload.raiseIntentRequestUuid
const to = this.pendingResolutions.get(requestId)
if (to) {
// post the result to the app that raised the intent
successResponseId(sc, requestId, to!!, {
intentResult: arg0.payload.intentResult
}, 'raiseIntentResultResponse')
// respond to the app that handled the intent
successResponse(sc, arg0, from, {}, 'intentResultResponse')
this.pendingResolutions.delete(requestId)
} else {
// no-one waiting for this result
errorResponse(sc, arg0, from, "No-one waiting for this result", 'intentResultResponse')
}
}
onUnsubscribe(arg0: IntentListenerUnsubscribeRequest, sc: ServerContext<AppRegistration>, from: AppIdentifier): void {
const id = arg0.payload.listenerUUID
const fi = this.regs.findIndex((e) => e.listenerUUID == id)
if (fi > -1) {
this.regs.splice(fi, 1)
successResponse(sc, arg0, from, {}, 'intentListenerUnsubscribeResponse')
} else {
errorResponse(sc, arg0, from, "Non-Existent Listener", 'intentListenerUnsubscribeResponse')
}
}
onAddIntentListener(arg0: AddIntentListenerRequest, sc: ServerContext<AppRegistration>, from: AppIdentifier): void {
const lr = {
appId: from.appId,
instanceId: from.instanceId,
intentName: arg0.payload.intent,
listenerUUID: sc.createUUID()
} as ListenerRegistration
this.regs.push(lr)
successResponse(sc, arg0, from, {
listenerUUID: lr.listenerUUID
}, 'addIntentListenerResponse')
// see if this intent listener is the destination for any pending intents
for (let x of this.pendingIntents) {
x.accept(lr)
if (x.complete) {
this.pendingIntents.delete(x)
}
}
}
hasListener(instanceId: string, intentName: string): boolean {
return this.regs.find(r => (r.instanceId == instanceId) && (r.intentName == intentName)) != null
}
async getRunningApps(appId: string, sc: ServerContext<AppRegistration>): Promise<AppIdentifier[]> {
return (await sc.getConnectedApps()).filter(a => a.appId == appId)
}
async startWithPendingIntent(arg0: IntentRequest, sc: ServerContext<AppRegistration>, target: AppIdentifier): Promise<void> {
// app exists but needs starting
const pi = new PendingIntent(arg0, sc, this, target)
this.pendingIntents.add(pi)
sc.open(target?.appId!!).then(() => { return undefined })
}
createAppIntents(ir: IntentRequest[], target: AppIdentifier[]): AppIntent[] {
return ir.map(r => {
return {
intent: {
name: r.intent,
displayName: r.intent
},
apps: target
}
})
}
async raiseIntentRequestToSpecificInstance(arg0: IntentRequest[], sc: ServerContext<AppRegistration>, target: AppIdentifier): Promise<void> {
if (!(await sc.isAppConnected(target.instanceId!!))) {
// instance doesn't exist
return errorResponseId(sc, arg0[0].requestUuid, arg0[0].from, ResolveError.TargetInstanceUnavailable, arg0[0].type)
}
const requestsWithListeners = arg0.filter(r => this.hasListener(target.instanceId!!, r.intent))
if (requestsWithListeners.length == 0) {
this.createPendingIntentIfAllowed(arg0[0], sc, target)
} else {
// ok, deliver to the current running app.
return forwardRequest(requestsWithListeners[0], target, sc, this)
}
}
async createPendingIntentIfAllowed(ir: IntentRequest, sc: ServerContext<AppRegistration>, target: AppIdentifier) {
// if this app declares that it supports the intent, we'll create a pending intent
const matchingIntents: DirectoryIntent[] = this.directory.retrieveIntents(ir.context.type, ir.intent, undefined)
const declared = matchingIntents.find(i => i.appId == target.appId)
if (declared) {
// maybe listener hasn't been registered yet - create a pending intent
const pi = new PendingIntent(ir, sc, this, target)
this.pendingIntents.add(pi)
} else {
errorResponseId(sc, ir.requestUuid, ir.from, ResolveError.NoAppsFound, ir.type)
}
}
async raiseIntentRequestToSpecificAppId(arg0: IntentRequest[], sc: ServerContext<AppRegistration>, target: AppIdentifier): Promise<void> {
// dealing with a specific app, which may or may not be open
const runningApps = await this.getRunningApps(target.appId, sc)
const appIntents = this.createAppIntents(arg0, [...runningApps, { appId: target.appId }])
const narrowedAppIntents = await this.narrowIntents(arg0[0].from, appIntents, arg0[0].context, sc)
if (narrowedAppIntents.length == 1) {
if ((narrowedAppIntents[0].apps.length == 2) && (narrowedAppIntents[0].apps[0].instanceId)) {
// single running instance
return this.raiseIntentRequestToSpecificInstance(arg0, sc, runningApps[0])
} else if (narrowedAppIntents[0].apps.length == 1) {
// no running instance, single app
const appRecords = this.directory.retrieveAppsById(target.appId)
if (appRecords.length >= 1) {
const ir: IntentRequest = {
...arg0[0],
intent: narrowedAppIntents[0].intent.name
}
return this.startWithPendingIntent(ir, sc, target)
} else {
// app doesn't exist
return errorResponseId(sc, arg0[0].requestUuid, arg0[0].from, ResolveError.TargetAppUnavailable, arg0[0].type)
}
}
}
// need to use the resolver to choose a running app instance
if (arg0[0].type == 'raiseIntentResponse') {
return successResponseId(sc, arg0[0].requestUuid, arg0[0].from, {
appIntent: narrowedAppIntents[0]
}, arg0[0].type)
} else {
// raise intent for context
return successResponseId(sc, arg0[0].requestUuid, arg0[0].from, {
appIntents: narrowedAppIntents
}, arg0[0].type)
}
}
oneAppOnly(appIntent: AppIntent): boolean {
const apps = appIntent.apps.map(a => a.appId)
const uniqueApps = apps.filter((v, i, a) => a.indexOf(v) === i).length
return (uniqueApps == 1)
}
async raiseIntentToAnyApp(arg0: IntentRequest[], sc: ServerContext<AppRegistration>): Promise<void> {
const connectedApps = await sc.getConnectedApps()
const matchingIntents = arg0.flatMap(i => this.directory.retrieveIntents(i.context.type, i.intent, undefined))
const uniqueIntentNames = matchingIntents.map(i => i.intentName).filter((v, i, a) => a.indexOf(v) === i)
const appIntents: AppIntent[] = uniqueIntentNames.map(i => {
const directoryAppsWithIntent = matchingIntents.filter(mi => mi.intentName == i).map(mi => mi.appId)
const runningApps = connectedApps.filter(ca => directoryAppsWithIntent.includes(ca.appId))
return {
intent: {
name: i,
displayName: i
},
apps: [
...runningApps,
...directoryAppsWithIntent.map(d => { return { appId: d } })
]
}
})
const narrowedAppIntents = await this.narrowIntents(arg0[0].from, appIntents, arg0[0].context, sc)
if (narrowedAppIntents.length == 0) {
// nothing can resolve the intent, fail
return errorResponseId(sc, arg0[0].requestUuid, arg0[0].from, ResolveError.NoAppsFound, arg0[0].type)
}
if (narrowedAppIntents.length == 1) {
const theAppIntent = narrowedAppIntents[0]
if (this.oneAppOnly(theAppIntent)) {
const instanceCount = theAppIntent.apps.filter(a => a.instanceId).length
const ir: IntentRequest = {
...arg0[0],
intent: narrowedAppIntents[0].intent.name
}
if (instanceCount == 1) {
// app is running
return forwardRequest(ir, theAppIntent.apps[0], sc, this)
} else if (instanceCount == 0) {
return this.startWithPendingIntent(ir, sc, theAppIntent.apps[0])
}
}
}
if (arg0[0].type == 'raiseIntentResponse') {
// raise intent
return successResponseId(sc, arg0[0].requestUuid, arg0[0].from, {
appIntent: narrowedAppIntents[0]
}, arg0[0].type)
} else {
// raise intent for context
return successResponseId(sc, arg0[0].requestUuid, arg0[0].from, { appIntents: narrowedAppIntents }, arg0[0].type)
}
}
async raiseIntentRequest(arg0: RaiseIntentRequest, sc: ServerContext<AppRegistration>, from: AppIdentifier): Promise<void> {
const intentRequest: IntentRequest = {
context: arg0.payload.context,
from,
intent: arg0.payload.intent,
requestUuid: arg0.meta.requestUuid,
type: 'raiseIntentResponse'
}
const target = arg0.payload.app!!
if (target?.instanceId) {
return this.raiseIntentRequestToSpecificInstance([intentRequest], sc, target)
} else if (target?.appId) {
return this.raiseIntentRequestToSpecificAppId([intentRequest], sc, target)
} else {
return this.raiseIntentToAnyApp([intentRequest], sc)
}
}
async raiseIntentForContextRequest(arg0: RaiseIntentForContextRequest, sc: ServerContext<AppRegistration>, from: AppIdentifier): Promise<void> {
// dealing with a specific instance of an app
const mappedIntents = this.directory.retrieveIntents(arg0.payload.context.type, undefined, undefined)
const uniqueIntentNames = mappedIntents.filter((v, i, a) => a.findIndex(v2 => v2.intentName == v.intentName) == i)
const possibleIntentRequests: IntentRequest[] = uniqueIntentNames.map(i => {
return {
context: arg0.payload.context,
from,
intent: i.intentName,
requestUuid: arg0.meta.requestUuid,
type: 'raiseIntentForContextResponse'
}
})
if (possibleIntentRequests.length == 0) {
return errorResponseId(sc, arg0.meta.requestUuid, from, ResolveError.NoAppsFound, 'raiseIntentForContextResponse')
}
const target = arg0.payload.app!!
if (target?.instanceId) {
return this.raiseIntentRequestToSpecificInstance(possibleIntentRequests, sc, target)
} else if (target?.appId) {
return this.raiseIntentRequestToSpecificAppId(possibleIntentRequests, sc, target)
} else {
return this.raiseIntentToAnyApp(possibleIntentRequests, sc)
}
}
async findIntentsByContextRequest(r: FindIntentsByContextRequest, sc: ServerContext<AppRegistration>, from: AppIdentifier): Promise<void> {
// TODO: Add result type
const { context } = r.payload
const apps1 = this.directory.retrieveIntents(context?.type, undefined, undefined)
// fold apps so same intents aren't duplicated
const apps2: AppIntent[] = []
apps1.forEach(a1 => {
const existing = apps2.find(a2 => a2.intent.name == a1.intentName)
if (existing) {
existing.apps.push({ appId: a1.appId })
} else {
apps2.push({
intent: {
name: a1.intentName,
displayName: a1.displayName ?? a1.intentName
},
apps: [
{
appId: a1.appId
}
]
})
}
})
successResponse(sc, r, from, {
appIntents: apps2
}, 'findIntentsByContextResponse')
}
async findIntentRequest(r: FindIntentRequest, sc: ServerContext<AppRegistration>, from: AppIdentifier): Promise<void> {
const { intent, context, resultType } = r.payload
// listeners for connected applications
const apps2 = (await this.retrieveListeners(intent, sc))
.map(lr => {
return {
appId: lr.appId,
instanceId: lr.instanceId
}
}) as AppIdentifier[]
// directory entries
const apps1 = this.directory.retrieveApps(context?.type, intent, resultType)
.map(a => {
return {
appId: a.appId,
}
})
.filter(i => {
// remove any directory entries that are already started
const running = apps2.find(i2 => i2.appId == i.appId)
return !running
}) as AppIdentifier[]
// just need this for the (deprecated) display name
const allMatchingIntents = this.directory.retrieveIntents(context?.type, intent, resultType)
const displayName = (allMatchingIntents.length > 0) ? allMatchingIntents[0].displayName : undefined
successResponse(sc, r, from, {
appIntent: {
intent: {
name: intent,
displayName
},
apps: [...apps1, ...apps2]
}
}, 'findIntentResponse')
}
async retrieveListeners(intentName: string | undefined, sc: ServerContext<AppRegistration>): Promise<ListenerRegistration[]> {
const activeApps = await sc.getConnectedApps()
const matching = this.regs.filter(r => r.intentName == intentName)
//console.log(`Matched listeners returned ${matching.length}`)
const active = matching.filter(r => activeApps.find(a => a.instanceId == r.instanceId))
//console.log(`Active listeners returned ${active.length}`)
return active
}
}