-
Notifications
You must be signed in to change notification settings - Fork 0
/
go-app-sms.js
696 lines (581 loc) · 22.5 KB
/
go-app-sms.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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
// WARNING: This is a generated file.
// If you edit it you will be sad.
// Edit src/app.js instead.
var go = {};
go;
/*jshint -W083 */
var vumigo = require('vumigo_v02');
var moment = require('moment');
var assert = require('assert');
var _ = require('lodash');
var JsonApi = vumigo.http.api.JsonApi;
var Choice = vumigo.states.Choice;
var ChoiceState = vumigo.states.ChoiceState;
go.states = {
MessengerChoiceState: ChoiceState.extend(function(self, name, opts) {
/*
Automatically add the necessary helper metadata for
ChoiceStates when using the Messenger transport
*/
opts = _.defaults(opts || {}, {
helper_metadata: function () {
// disable for now
if(true) {
return {};
}
var i18n = self.im.user.i18n;
return {
messenger: {
template_type: 'generic',
title: i18n(opts.title),
subtitle: i18n(opts.question),
image_url: opts.image_url || '',
buttons: opts.choices.map(function(choice, index) {
return {
title: i18n(choice.label),
payload: {
content: (index + 1) + '',
in_reply_to: self.im.msg.message_id || null,
}
};
})
}
};
}
});
ChoiceState.call(self, name, opts);
}),
"trailing": "comma"
};
// GENERIC UTILS
go.utils = {
// FB HELPERS
get_user_profile: function(msg) {
return msg.helper_metadata.messenger || {};
},
// FIXTURES HELPERS
// function checks fixtures used against fixture expected
// if multiple_possibilities is true, expected_used can be an array of arrays
// representing possible valid combinations of fixtures
check_fixtures_used: function(api, expected_used, multiple_possibilities) {
var fixts = api.http.fixtures.fixtures;
var fixts_used = [];
fixts.forEach(function(f, i) {
f.uses > 0 ? fixts_used.push(i) : null;
});
if (multiple_possibilities) {
for(var i = 0; i < expected_used.length; i++) {
try {
assert.deepEqual(fixts_used, expected_used[i]);
break; // break if used fixtures match any of the valid_fixture_possibilities
}
catch(AssertionError) {
//console.log(AssertionError.message);
}
}
}
else {
assert.deepEqual(fixts_used, expected_used);
}
},
// TIMEOUT HELPERS
timed_out: function(im) {
return im.msg.session_event === 'new'
&& im.user.state.name
&& im.config.no_timeout_redirects.indexOf(im.user.state.name) === -1;
},
timeout_redirect: function(im) {
return im.config.timeout_redirects.indexOf(im.user.state.name) !== -1;
},
// SERVICE API CALL HELPERS
service_api_call: function (service, method, params, payload, endpoint, im) {
var http = new JsonApi(im, {
headers: {
'Authorization': ['Token ' + im.config.services[service].api_token]
}
});
switch (method) {
case "post":
return http.post(im.config.services[service].url + endpoint, {
data: payload
})
.then(go.utils.log_service_api_call(service, method, params, payload, endpoint, im));
case "get":
return http.get(im.config.services[service].url + endpoint, {
params: params
})
.then(go.utils.log_service_api_call(service, method, params, payload, endpoint, im));
case "patch":
return http.patch(im.config.services[service].url + endpoint, {
data: payload
})
.then(go.utils.log_service_api_call(service, method, params, payload, endpoint, im));
case "put":
return http.put(im.config.services[service].url + endpoint, {
params: params,
data: payload
})
.then(go.utils.log_service_api_call(service, method, params, payload, endpoint, im));
case "delete":
return http
.delete(im.config.services[service].url + endpoint)
.then(go.utils.log_service_api_call(service, method, params, payload, endpoint, im));
}
},
log_service_api_call: function(service, method, params, payload, endpoint, im) {
return function (response) {
return im
.log([
'Request: ' + method + ' ' + im.config.services[service].url + endpoint,
'Payload: ' + JSON.stringify(payload),
'Params: ' + JSON.stringify(params),
'Response: ' + JSON.stringify(response),
].join('\n'))
.then(function () {
return response;
});
};
},
// MSISDN HELPERS
// Check that it's a number and starts with 0 and approximate length
// TODO: refactor to take length, explicitly deal with '+'
is_valid_msisdn: function(content) {
return go.utils.check_valid_number(content)
&& content[0] === '0'
&& content.length >= 10
&& content.length <= 13;
},
normalize_msisdn: function(raw, country_code) {
// don't touch shortcodes
if (raw.length <= 5) {
return raw;
}
// remove chars that are not numbers or +
raw = raw.replace(/[^0-9+]/g);
if (raw.substr(0,2) === '00') {
return '+' + raw.substr(2);
}
if (raw.substr(0,1) === '0') {
return '+' + country_code + raw.substr(1);
}
if (raw.substr(0,1) === '+') {
return raw;
}
if (raw.substr(0, country_code.length) === country_code) {
return '+' + raw;
}
return raw;
},
// NUMBER HELPERS
// An attempt to solve the insanity of JavaScript numbers
check_valid_number: function(content) {
var numbers_only = new RegExp('^\\d+$');
return content !== ''
&& numbers_only.test(content)
&& !Number.isNaN(Number(content));
},
double_digit_number: function(input) {
input_numeric = parseInt(input, 10);
if (parseInt(input, 10) < 10) {
return "0" + input_numeric.toString();
} else {
return input_numeric.toString();
}
},
// DATE HELPERS
get_now: function(config) {
if (config.testing_today) {
return new moment(config.testing_today).format('YYYY-MM-DD HH:mm:ss');
} else {
return new moment().format('YYYY-MM-DD HH:mm:ss');
}
},
get_today: function(config) {
if (config.testing_today) {
return new moment(config.testing_today, 'YYYY-MM-DD');
} else {
return new moment();
}
},
get_january: function(config) {
// returns current year january 1st moment date
return go.utils.get_today(config).startOf('year');
},
is_valid_date: function(date, format) {
// implements strict validation with 'true' below
return moment(date, format, true).isValid();
},
is_valid_year: function(year, minYear, maxYear) {
// expects string parameters
// checks that the number is within the range determined by the
// minYear & maxYear parameters
return go.utils.check_valid_number(year)
&& parseInt(year, 10) >= parseInt(minYear, 10)
&& parseInt(year, 10) <= parseInt(maxYear, 10);
},
is_valid_day_of_month: function(input) {
// check that it is a number and between 1 and 31
return go.utils.check_valid_number(input)
&& parseInt(input, 10) >= 1
&& parseInt(input, 10) <= 31;
},
// TEXT HELPERS
check_valid_alpha: function(input) {
// check that all chars are in standard alphabet
var alpha_only = new RegExp('^[A-Za-z]+$');
return input !== '' && alpha_only.test(input);
},
is_valid_name: function(input, min, max) {
// check that the string does not include the characters listed in the
// regex, and min <= input string length <= max
var name_check = new RegExp(
'(^[^±!@£$%^&*_+§¡€#¢§¶•ªº«\\/<>?:;|=.,0123456789]{min,max}$)'
.replace('min', min.toString())
.replace('max', max.toString())
);
return input !== '' && name_check.test(input);
},
get_clean_first_word: function(user_message) {
return user_message
.split(" ")[0] // split off first word
.replace(/\W/g, '') // remove non letters
.toUpperCase(); // capitalise
},
// CHOICE HELPERS
make_month_choices: function($, startDate, limit, increment, valueFormat, labelFormat) {
var choices = [];
var monthIterator = startDate;
for (var i=0; i<limit; i++) {
choices.push(new Choice(monthIterator.format(valueFormat),
monthIterator.format(labelFormat)));
monthIterator.add(increment, 'months');
}
return choices;
},
// REGISTRATION HELPERS
create_registration: function(im, reg_info) {
return go.utils
.service_api_call("registrations", "post", null, reg_info, "registration/", im)
.then(function(result) {
return result.id;
});
},
// IDENTITY HELPERS
get_identity_by_address: function(address, im) {
// Searches the Identity Store for all identities with the provided address.
// Returns the first identity object found
// Address should be an object {address_type: address}, eg.
// {'msisdn': '0821234444'}, {'email': '[email protected]'}
var address_type = Object.keys(address)[0];
var address_val = address[address_type];
var params = {};
var search_string = 'details__addresses__' + address_type;
params[search_string] = address_val;
return im
.log('Getting identity for: ' + JSON.stringify(params))
.then(function() {
return go.utils
.service_api_call('identities', 'get', params, null, 'identities/search/', im)
.then(function(json_get_response) {
var identities_found = json_get_response.data.results;
// Return the first identity in the list of identities
return (identities_found.length > 0)
? identities_found[0]
: null;
});
});
},
get_identity: function(identity_id, im) {
// Gets the identity from the Identity Store
// Returns the identity object
var endpoint = 'identities/' + identity_id + '/';
return go.utils
.service_api_call('identities', 'get', {}, null, endpoint, im)
.then(function(json_get_response) {
return json_get_response.data;
});
},
create_identity: function(im, address, communicate_through_id, operator_id) {
// Create a new identity
// Returns the identity object
var payload = {
"details": {
"default_addr_type": null,
"addresses": {}
}
};
// compile base payload
if (address) {
var address_type = Object.keys(address)[0];
var addresses = {};
addresses[address_type] = {};
addresses[address_type][address[address_type]] = {};
payload.details = {
"default_addr_type": address_type,
"addresses": addresses
};
}
if (communicate_through_id) {
payload.communicate_through = communicate_through_id;
}
// add operator_id if available
if (operator_id) {
payload.operator = operator_id;
}
return go.utils
.service_api_call("identities", "post", null, payload, 'identities/', im)
.then(function(json_post_response) {
return json_post_response.data;
});
},
get_or_create_identity: function(address, im, operator_id) {
// Gets a identity if it exists, otherwise creates a new one
if (address.msisdn) {
address.msisdn = go.utils
.normalize_msisdn(address.msisdn, im.config.country_code);
}
return go.utils
// Get identity id using address
.get_identity_by_address(address, im)
.then(function(identity) {
if (identity !== null) {
// If identity exists, return the id
return identity;
} else {
// If identity doesn't exist, create it
return go.utils
.create_identity(im, address, null, operator_id)
.then(function(identity) {
return identity;
});
}
});
},
update_identity: function(im, identity) {
// Update an identity by passing in the full updated identity object
// Removes potentially added fields that auto-complete and should not
// be submitted
// Returns the id (which should be the same as the identity's id)
auto_fields = ["url", "created_at", "updated_at", "created_by", "updated_by", "user"];
for (var i in auto_fields) {
field = auto_fields[i];
if (field in identity) {
delete identity[field];
}
}
var endpoint = 'identities/' + identity.id + '/';
return go.utils
.service_api_call('identities', 'patch', {}, identity, endpoint, im)
.then(function(response) {
return response.data.id;
});
},
// SUBSCRIPTION HELPERS
get_subscription: function(im, subscription_id) {
// Gets the subscription from the Stage-base Store
// Returns the subscription object
var endpoint = 'subscriptions/' + subscription_id + '/';
return go.utils
.service_api_call('subscriptions', 'get', {}, null, endpoint, im)
.then(function(response) {
return response.data;
});
},
get_active_subscriptions_by_identity: function(im, identity_id) {
// Searches the Stage-base Store for all active subscriptions with the provided identity_id
// Returns the first subscription object found or null if none are found
var params = {
identity: identity_id,
active: true
};
var endpoint = 'subscriptions/';
return go.utils
.service_api_call('subscriptions', 'get', params, null, endpoint, im)
.then(function(response) {
return response.data.results;
});
},
get_active_subscription_by_identity: function(im, identity_id) {
// Searches the Stage-base Store for all active subscriptions with the provided identity_id
// Returns the first subscription object found or null if none are found
return go.utils
.get_active_subscriptions_by_identity(im, identity_id)
.then(function(subscriptions_found) {
return (subscriptions_found.length > 0)
? subscriptions_found[0]
: null;
});
},
has_active_subscription: function(identity_id, im) {
// Returns whether an identity has an active subscription
// Returns true / false
return go.utils
.get_active_subscriptions_by_identity(im, identity_id)
.then(function(subscriptions) {
return subscriptions.length > 0;
});
},
update_subscription: function(im, subscription) {
// Update a subscription by passing in the full updated subscription object
// Returns the id (which should be the same as the subscription's id)
var endpoint = 'subscriptions/' + subscription.id + '/';
return go.utils
.service_api_call('subscriptions', 'patch', {}, subscription, endpoint, im)
.then(function(response) {
return response.data.id;
});
},
// MESSAGESET HELPERS
get_messageset: function(im, messageset_id) {
// Gets the messageset from the Stage-base Store
// Returns the messageset object
var endpoint = 'messageset/' + messageset_id + '/';
return go.utils
.service_api_call('subscriptions', 'get', {}, null, endpoint, im)
.then(function(response) {
return response.data;
});
},
// MESSAGE_SENDER HELPERS
save_inbound_message: function(im, from_addr, content) {
// Saves the inbound messages to seed-message-sender
var payload = {
"message_id": im.config.testing_message_id || im.msg.message_id,
"in_reply_to": null,
"to_addr": im.config.channel,
"from_addr": from_addr,
"content": content,
"transport_name": im.config.transport_name,
"transport_type": im.config.transport_type,
"helper_metadata": {}
};
return go.utils
.service_api_call("message_sender", "post", null, payload, 'inbound/', im)
.then(function(json_post_response) {
var inbound_response = json_post_response.data;
// Return the inbound id
return inbound_response.id;
});
},
// OPTOUT & OPTIN HELPERS
optout: function(im, identity_id, optout_reason, address_type, address,
request_source, requestor_source_id, optout_type, config) {
// Posts an optout to the identity store optout endpoint
var optout_info = {
optout_type: optout_type || 'stop', // default to 'stop'
identity: identity_id,
reason: optout_reason || 'unknown', // default to 'unknown'
address_type: address_type || 'msisdn', // default to 'msisdn'
address: address,
request_source: request_source,
requestor_source_id: requestor_source_id
};
return go.utils
.service_api_call("identities", "post", null, optout_info, "optout/", im)
.then(function(response) {
return response;
});
},
"commas": "commas"
};
go.app = function() {
var vumigo = require('vumigo_v02');
var MetricsHelper = require('go-jsbox-metrics-helper');
var App = vumigo.App;
var EndState = vumigo.states.EndState;
var GoUOPBMOH = App.extend(function(self) {
App.call(self, 'state_start');
var $ = self.$;
self.init = function() {
// Use the metrics helper to add some metrics
mh = new MetricsHelper(self.im);
mh
// Total unique users
.add.total_unique_users('total.sms.unique_users')
// Total opt-outs
.add.total_state_actions(
{
state: 'state_opt_out',
action: 'enter'
},
'total.optouts'
)
// Total opt-ins
.add.total_state_actions(
{
state: 'state_opt_in',
action: 'enter'
},
'total.optins'
)
// Total opt-ins
.add.total_state_actions(
{
state: 'state_unrecognised',
action: 'enter'
},
'total.unrecognised_sms'
);
// Load self.contact
return self.im.contacts
.for_user()
.then(function(user_contact) {
self.contact = user_contact;
});
};
self.states.add('state_start', function() {
var user_first_word = go.utils.get_clean_first_word(self.im.msg.content);
switch (user_first_word) {
case "STOP":
return self.states.create("state_stop");
case "HELP":
return self.states.create("state_help");
default:
return self.states.create("state_unrecognised");
}
});
self.states.add('state_stop', function(name) {
return self.states.create('state_stop_completed');
});
self.states.add('state_stop_completed', function(name, creator_opts) {
return new EndState(name, {
text: $('Removed! You will no longer recieve messages from us.'),
next: 'state_start'
});
});
// HELP
self.states.add('state_help', function(name) {
return new EndState(name, {
text: $(["You can send me the following commands:",
"stop"
].join('\n')),
next: 'state_start'
});
});
// UNRECOGNISED
self.states.add('state_unrecognised', function(name) {
return new EndState(name, {
text: $('Oh no! We did not recognise the command you sent us. Reply "help" to get a list.'),
next: 'state_start'
});
});
// ERROR
self.states.add('state_error', function(name) {
return new EndState(name, {
text: $('Ooops! Something went wrong with your request. Try sending it again in a moment please.'),
next: 'state_start'
});
});
});
return {
GoUOPBMOH: GoUOPBMOH
};
}();
go.init = function() {
var vumigo = require('vumigo_v02');
var InteractionMachine = vumigo.InteractionMachine;
var GoUOPBMOH = go.app.GoUOPBMOH;
return {
im: new InteractionMachine(api, new GoUOPBMOH())
};
}();