-
Notifications
You must be signed in to change notification settings - Fork 2
/
swimlane.js
528 lines (457 loc) · 14.9 KB
/
swimlane.js
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
const crypto = require('crypto');
const _ = require('lodash');
const htmlEscape = require('./html-escape');
const FIELD_VALUE_TRUNCATION_LENGTH = 2000; // number of characters to truncate to for the field value
class Swimlane {
constructor(request, logger) {
this.accessTokenCache = new Map();
// appCache is a map of maps. There is a map per application keyed on the appId. Each app then has a map keyed
// on field ids with the value being a field object. The field object contains the field name and the layout name.
this.appCache = new Map();
this.appIdToName = new Map();
this.appNameToId = new Map();
this.swimlaneInstanceId = null;
this.isCaching = true;
this.cachingAppFailed = false;
this.log = logger;
this.request = request;
}
cacheApps(options, cb) {
let self = this;
if (this._doReload(options)) {
this.log.info('Caching Swimlane Applications');
this._resetCaches();
this._cacheApps(options, (err) => {
if (!err) {
this.log.info(
{ cachedApps: Array.from(this.appNameToId.keys()) },
'Successfully Cached Apps'
);
} else {
this.log.error(err);
}
self.cachingAppFailed = err ? true : false;
self.isCaching = false;
return cb(err);
});
} else {
cb(null);
}
}
search(entityValue, options, cb) {
const self = this;
const appIds = [];
const results = [];
// The app cache did not build correctly we return an error
if (this.cachingAppFailed) {
return cb({
detail: 'Cannot run searches due to a failure to load the Swimlane application'
});
}
// The caching operation can take a couple seconds which means search requests can come in before
// the app is fully cached. As a result, we simply return empty results until the app is fully
// cached.
if (this.isCaching) {
this.log.debug(`Cache is still building, skipping search on [${entityValue}]`);
return cb(null, []);
}
let appNames = options.applications.split(',');
for (let i = 0; i < appNames.length; i++) {
let appId = this._getAppId(appNames[i].trim());
if (appId) {
appIds.push(appId);
} else {
// the appName could not be mapped to an app ID
return cb({
detail: 'The Application [' + appNames[i].trim() + '] could not be found',
availableApps: Array.from(this.appNameToId.keys()),
note: 'The app names are case insensitive so you do not need to match the casing provided in `availableApps`'
});
}
}
if (appIds.length === 0) {
return cb('You must specify a valid application name');
}
const requestOptions = {
url: options.url + '/api/search/keyword',
json: true,
method: 'POST',
body: {
applicationIds: appIds,
keywords: `${entityValue}`,
countByApplicationFacet: true,
sorts: {
modifiedDate: 'Descending'
}
},
qs: {
page: 1,
size: options.maxResults
}
};
this.log.debug({ requestOptions: requestOptions }, 'HTTP Request Options');
this._executeRequest(
options,
requestOptions,
self._handleRequestError('Searching SwimLane', cb, (response, body) => {
this.log.trace({ body }, 'Search Response');
const entityRegEx = new RegExp(entityValue, 'gi');
let records;
if(Array.isArray(body.records)){
records = body.records;
} else if(body.results && Array.isArray(body.results.items)){
records = body.results.items;
} else {
//unexpected response format
return cb({
detail: 'Unexpected response payload format. Missing top level `records` or `results.items` keys.'
});
}
records.forEach((record) => {
const appId = record.applicationId;
const keys = Object.keys(record.values);
keys.forEach((key) => {
let value = record.values[key];
if (
typeof value === 'string' &&
value.toLowerCase().includes(entityValue.toLowerCase())
) {
const fieldValue = this._parseFieldValue(value, entityRegEx);
const app = self._getApp(appId);
const fieldName = self._getFieldName(appId, key);
if (!app) {
// the appId could not be found so we log it
this.log.debug(
{
appId: appId,
fieldId: key,
entityValue: entityValue
},
`Could not find the app ${appId}`
);
return;
}
if (!fieldName) {
// the field could not be found so we log it. This can happen when a field in the app
// is deleted but records legacy records still exist which contain the field
// TODO: This can also happen if the app has been updated and the record match comes
// from a new field. In this case, we need to reload our app by restarting the
// integration.
this.log.debug(
{
appId: appId,
fieldId: key,
entityValue: entityValue
},
`Could not find field id ${key} in app ${appId}`
);
return;
}
results.push({
appName: app.name,
appAcronym: app.acronym,
appId: appId,
fieldId: key,
fieldName: fieldName,
layoutPath: self._getLayoutPath(appId, key),
fieldValue: fieldValue,
recordTrackingId: record.trackingId,
recordCreatedDate: record.createdDate,
recordModifiedDate: record.modifiedDate,
recordTotalTimeSpent: record.totalTimeSpent,
timeTrackingEnabled: record.timeTrackingEnabled,
modifiedByUser: record.modifiedByUser.name,
createdByUser: record.createdByUser.name,
recordId: record.id,
recordUrl: self._createRecordUrl(options.url, appId, record.id)
});
}
});
});
cb(null, results);
})
);
}
_getAppId(appName) {
return this.appNameToId.get(appName.toLowerCase());
}
_getApp(appId) {
return this.appIdToName.get(appId);
}
_doReload(options) {
if (this.swimlaneInstanceId === null || this.swimlaneInstanceId !== options.url) {
this.swimlaneInstanceId = options.url;
return true;
}
return false;
}
_parseFieldValue(value, entityRegex) {
let fieldValue = value;
if (value.length > FIELD_VALUE_TRUNCATION_LENGTH) {
fieldValue = value.substring(0, FIELD_VALUE_TRUNCATION_LENGTH);
}
fieldValue = htmlEscape(fieldValue).replace(entityRegex, '<span class="match">$&</span>');
if (value.length > FIELD_VALUE_TRUNCATION_LENGTH) {
fieldValue += '<span class="truncated">... [content truncated]</span>';
}
return fieldValue;
}
_cacheApps(options, cb) {
let self = this;
this._executeRequest(
options,
{
url: options.url + '/api/app',
json: true
},
self._handleRequestError('Retrieving Apps', cb, (response, body) => {
body.forEach((app) => {
self.appIdToName.set(app.id, {
name: app.name,
acronym: app.acronym
});
self.appNameToId.set(app.name.toLowerCase(), app.id);
app.fields.forEach((field) => {
self._setFieldName(app.id, field.id, field.name);
});
self._buildLayoutPath(app.id, app.layout);
});
cb(null);
})
);
}
_buildLayoutPath(appId, layout) {
layout.forEach((item) => {
this._parseLayoutItem(appId, item, []);
});
}
_parseLayoutItem(appId, item, path) {
if (item['$type'] === 'Core.Models.Layouts.SectionLayout, Core') {
this._parseSectionLayout(appId, item, path);
} else if (item['$type'] === 'Core.Models.Layouts.FieldLayout, Core') {
this._parseFieldsLayout(appId, item, path);
} else if (item['$type'] === 'Core.Models.Layouts.TabLayout, Core') {
this._parseTabLayout(appId, item, path);
} else if (item['$type'] === 'Core.Models.Layouts.Tabs, Core') {
this._parseTab(appId, item, path);
}
}
_parseFieldsLayout(appId, field, path) {
if (field.fieldId) {
path.push({
id: field.fieldId,
name: this._getFieldName(appId, field.fieldId),
layoutType: field.layoutType
});
this._setLayoutPath(appId, field.fieldId, path);
}
}
_parseSectionLayout(appId, section, path) {
if (Array.isArray(section.children)) {
path.push({
id: section.id,
name: section.name,
layoutType: section.layoutType
});
section.children.forEach((item) => {
const clonedPath = path.slice(0);
this._parseLayoutItem(appId, item, clonedPath);
});
}
}
_parseTabLayout(appId, tabLayout, path) {
if (Array.isArray(tabLayout.tabs)) {
tabLayout.tabs.forEach((item) => {
const clonedPath = path.slice(0);
this._parseLayoutItem(appId, item, clonedPath);
});
}
}
_parseTab(appId, tab, path) {
if (Array.isArray(tab.children)) {
path.push({
id: tab.id,
name: tab.name,
layoutType: tab.layoutType
});
tab.children.forEach((item) => {
const clonedPath = path.slice(0);
this._parseLayoutItem(appId, item, clonedPath);
});
}
}
/**
* Returns the field for the provided fieldId within the given appId
* @param appId {String} The application id you want to lookup the field in
* @param fieldId {String} The id of the field you want to return
* @returns {*}
* @private
*/
_getField(appId, fieldId) {
let app = this.appCache.get(appId);
if (app && app.has(fieldId)) {
return app.get(fieldId);
} else {
return null;
}
}
/**
* Maps a field id for a given app to a field name
* @param appId {String} The application id you want to lookup the field in
* @param fieldId {String} The field id you want to return the name for
* @returns {*}
* @private
*/
_getFieldName(appId, fieldId) {
let app = this.appCache.get(appId);
// It is possible for a field to be deleted out of an app but to still have records that exist with that
// data in the backend. As a result, we need to validate that we have a fieldId in the app cache. If we don't
// we can safely ignore this field.
if (app && app.has(fieldId)) {
return app.get(fieldId).fieldName;
} else {
return null;
}
}
_getLayoutPath(appId, fieldId) {
let app = this.appCache.get(appId);
if (app) {
return app.get(fieldId).layoutPath;
} else {
return null;
}
}
_setFieldName(appId, fieldId, fieldName) {
if (!this.appCache.has(appId)) {
this.appCache.set(appId, new Map());
}
let app = this.appCache.get(appId);
let field = {};
if (app.has(fieldId)) {
field = app.get(fieldId);
}
app.set(fieldId, _.merge(field, { fieldName: fieldName }));
}
_setLayoutPath(appId, fieldId, layoutPath) {
if (!this.appCache.has(appId)) {
this.appCache.set(appId, new Map());
}
let app = this.appCache.get(appId);
let field = {};
if (app.has(fieldId)) {
field = app.get(fieldId);
}
app.set(fieldId, _.merge(field, { layoutPath: layoutPath }));
}
_createRecordUrl(host, appId, recordId) {
return host + '/record/' + appId + '/' + recordId;
}
_resetCaches() {
this.appNameToId.clear();
this.appIdToName.clear();
this.appCache.clear();
}
_executeRequest(options, requestOptions, cb, requestCount) {
let self = this;
if (typeof requestCount === 'undefined') {
requestCount = 0;
}
this._getAccessToken(options, (err, accessToken) => {
if (err) {
cb(err);
return;
}
requestOptions.headers = {
Authorization: `Bearer ${accessToken}`
};
self.request(requestOptions, (err, response, body) => {
if (response.statusCode === 401 && requestCount < 2) {
// accessToken has expired
self.accessTokenCache.delete(self._getAccessTokenCacheKey(options));
//repeat this function to get a new access token
self._executeRequest(options, requestOptions, cb, requestCount ? ++requestCount : 1);
return;
}
cb(err, response, body);
});
});
}
_handleRequestError(errorMessage, errorCb, cb) {
let self = this;
return function (err, response, body) {
if (err) {
self.log.error({
err: err,
statusCode: response ? response.statusCode : null,
body: body
});
errorCb({
err: err,
detail: err && err.detail ? err.detail : 'HTTP Error: ' + errorMessage,
body: body
});
return;
}
if (response.statusCode !== 200) {
self.log.error({
err: err,
statusCode: response ? response.statusCode : null,
body: body
});
errorCb({
err: err,
detail: err && err.detail ? err.detail : 'HTTP Error: ' + errorMessage,
body: body
});
return;
}
cb(response, body);
};
}
_getAccessToken(options, cb) {
let cacheKey = this._getAccessTokenCacheKey(options);
if (this.accessTokenCache.has(cacheKey)) {
cb(null, this.accessTokenCache.get(cacheKey));
} else {
// We have to generate the token
this._generateAccessToken(options, cb);
}
}
_generateAccessToken(options, cb) {
let self = this;
let requestOptions = {
json: true,
url: options.url + '/api/user/login',
method: 'POST',
body: {
username: options.username,
password: options.password
}
};
this.request(requestOptions, (err, response, body) => {
if (err || response.statusCode != 200 || !body || !body.token) {
let detail = 'Error generating access token';
if (err) {
detail = err.message ? err.message : err.code;
} else if (response.statusCode === 401) {
detail = 'Authentication error: Validate your username and password.';
}
cb({
err: err,
response: response,
body: body,
detail
});
return;
}
// Cache the new token
self.accessTokenCache.set(self._getAccessTokenCacheKey(options), body.token);
cb(null, body.token);
});
}
_getAccessTokenCacheKey(options) {
let key = options.url + options.username + options.password;
return crypto.createHash('sha1').update(key).digest('hex');
}
}
module.exports = Swimlane;