-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathifttt.js
535 lines (447 loc) · 14.9 KB
/
ifttt.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
var _ = require('underscore');
var util = require('util');
var ActionResource = require('./lib/resource/actionResource');
var ACTION_RESOURCE = 'action';
var TriggerResource = require('./lib/resource/triggerResource');
var TRIGGER_RESOURCE = 'trigger';
/**
* Ifttt
*
* @param config
* @param config.apiVersion
* @param config.authMode
* @param config.channelKey
* @param config.logger
* @param config.testAccessToken
*
* @constructor
* @see https://developers.ifttt.com/docs/api_reference
*/
function Ifttt(config) {
config = _.defaults(config || {}, {
apiVersion: 'v1',
authMode: 'header', // 'header', 'oauth2'
logger: console,
testAccessToken: ''
});
if (_.isUndefined(config.channelKey)) {
throw new Error('Property `channelKey` is required.');
}
this.iftttApiVersion = config.apiVersion;
// IFTTT channel key, needed for test setup verification.
this.iftttChannelKey = config.channelKey;
// IFTTT version basepath
this.iftttBasepath = '/ifttt/' + this.iftttApiVersion;
// IFTTT auth mode
this.iftttAuthMode = config.authMode;
// IFTTT test access token
this.iftttTestAccessToken = config.testAccessToken;
// Internal reference to desired logger.
this.logger = config.logger; // Must support `info`, `error`, `warn`
// Internal registry for actions & triggers.
this.registry = {
action: {},
trigger: {}
};
// Internal registry for generic handlers.
this.handlers = {
status: null,
user_info: null,
test_setup_fake: null
};
// Internal storage of current user data for triggers / triggerFields.
this.currentUserData = null;
}
Ifttt.prototype.addExpressRoutes = function(app) {
var that = this;
// Header check middleware wrapper.
var headerCheck = function(req, res, next){
that.accessCheck(req, res, next, {forceHeaderCheck: true});
};
// Auth check middleware wrapper.
var authCheck = function(req, res, next){
that.accessCheck(req, res, next);
};
/**
* Implements IFTTT Channel status:
*
* Provide an API endpoint which IFTTT can periodically check for your
* channel’s availability. This endpoint is not user-specific, and thus does
* not require an access token.
*
* @see https://developers.ifttt.com/docs/api_reference#channel-status
*/
app.get(this.iftttBasepath + '/status', headerCheck, function(req, res){
if (!_.isFunction(that.handlers.status)) {
return res.status(503).send();
}
that.handlers.status(req, function(err, available){
if (available) {
return res.status(200).send();
}
else {
return res.status(503).send();
}
});
});
/**
* Implements IFTTT User information:
*
* After acquiring an access token, IFTTT will make a request to your user
* information endpoint. This information is considered private, and will only
* be displayed to the user who activated your channel. Occasionally, IFTTT
* will make requests to this endpoint to verify that the user’s access token
* is still valid.
*
* @see https://developers.ifttt.com/docs/api_reference#user-information
*/
app.get(this.iftttBasepath + '/user/info', authCheck, function(req, res){
if (!_.isFunction(that.handlers.user_info)) {
return res.status(500).send();
}
that.handlers.user_info(req, function(err, data){
var response = that._handleResponse(err, data);
that._sendExpressResponse(res, response);
});
});
/**
* Implements IFTTT Test setup:
*
* Before starting an automated test, the endpoint testing tool will send a
* POST request to your channel API’s test/setup endpoint. This serves as a
* signal to your API that a test is about to begin.
*
* For security, the endpoint testing tool will send your Channel Key in the
* request to test/setup as a bearer token. Before performing any of the
* above operations, you should verify that the value of the bearer token
* matches the value for your Channel Key, as displayed in the Developer UI.
*
* @see https://developers.ifttt.com/docs/testing#the-testsetup-endpoint
*/
app.post(this.iftttBasepath + '/test/setup', headerCheck, function(req, res){
if (req.get('IFTTT-Channel-Key') !== that.iftttChannelKey) {
return res.status(401).send('Unauthorized');
}
that.generateTestSetupSample(function(samples){
var setupResponse = {
accessToken: that.iftttTestAccessToken,
samples: samples
};
var response = that._handleResponse(null, setupResponse);
that._sendExpressResponse(res, response);
});
});
/**
* Implements IFTTT Triggers:
*
* Each trigger requires a unique API endpoint. For each recipe using a given
* trigger, IFTTT will poll that trigger’s endpoint once about every 15
* minutes. For each new item returned by the trigger, IFTTT will fire the
* recipe’s associated action.
*
* @see https://developers.ifttt.com/docs/api_reference#triggers
*/
app.post(this.iftttBasepath + '/triggers/:trigger_slug', authCheck, function(req, res){
var trigger_slug = req.param('trigger_slug');
var payload = req.body;
that.getTriggerResponse(trigger_slug, req, payload, function(response){
that._sendExpressResponse(res, response);
});
});
/**
* Implements IFTTT Trigger fields:
*
* Trigger fields can have dynamic options and dynamic validation. Each dynamic
* option and validation requires a unique endpoint.
*
* @see https://developers.ifttt.com/docs/api_reference#trigger-fields
*/
app.post(this.iftttBasepath + '/triggers/:trigger_slug/fields/:trigger_field_slug/options', authCheck, function(req, res){
var trigger_slug = req.param('trigger_slug');
var trigger_field_slug = req.param('trigger_field_slug');
that.getTriggerFieldOptionsResponse(trigger_slug, trigger_field_slug, req, function(response){
that._sendExpressResponse(res, response);
});
});
app.post(this.iftttBasepath + '/triggers/:trigger_slug/fields/:trigger_field_slug/validate', authCheck, function(req, res){
var trigger_slug = req.param('trigger_slug');
var trigger_field_slug = req.param('trigger_field_slug');
var payload = req.body;
that.getTriggerFieldValidateResponse(trigger_slug, trigger_field_slug, req, payload, function(response){
that._sendExpressResponse(res, response);
});
});
/**
* Implements IFTTT Actions:
*
* Each action requires a unique API endpoint.
*
* @see https://developers.ifttt.com/docs/api_reference#actions
*/
app.post(this.iftttBasepath + '/actions/:action_slug', authCheck, function(req, res){
var action_slug = req.param('action_slug');
var payload = req.body;
that.getActionResponse(action_slug, req, payload, function(response){
that._sendExpressResponse(res, response);
});
});
/**
* Implements IFTTT Action fields:
*
* Action fields can have dynamic options. Each dynamic option requires a
* unique endpoint. Unlike trigger fields, action fields do not currently
* support dynamic validation.
*
* @see https://developers.ifttt.com/docs/api_reference#action-fields
*/
app.post(this.iftttBasepath + '/actions/:action_slug/fields/:action_field_slug/options', authCheck, function(req, res){
var action_slug = req.param('action_slug');
var action_field_slug = req.param('action_field_slug');
that.getActionFieldOptionsResponse(action_slug, action_field_slug, req, function(response){
that._sendExpressResponse(res, response);
});
});
this.logger.info('Added IFTTT express routes.');
};
Ifttt.prototype.accessCheck = function(req, res, next, options) {
var that = this;
options = _.defaults(options || {}, {
forceHeaderCheck: false
});
// Either we run auth mode 'header' and we check the header for each request,
// or we force this header check for specific endpoints (status, test/setup).
if (this.iftttAuthMode === 'header' || options.forceHeaderCheck) {
if (req.get('IFTTT-Channel-Key') !== this.iftttChannelKey) {
this.logger.warn('Invalid IFTTT-Channel-Key header.');
return res.status(401).send('Unauthorized');
}
}
// If we run auth mode 'oauth2', we use the provided middleware to check the
// oauth2 session. If no middleware is provided, we assume the check was
// already done earlier in the request.
if (this.iftttAuthMode === 'oauth2' && !options.forceHeaderCheck && !_.isUndefined(this.oauth2middleware)) {
this.oauth2middleware(req, res, function(err){
if (err) {
var response = that._handleResponse(err, null);
return that._sendExpressResponse(res, response);
}
next();
});
}
else {
next();
}
};
Ifttt.prototype._sendExpressResponse = function(res, response) {
return res.status(response.status).send(response.body);
};
/**
* Prepare an response for IFTTT.
*
* @param err
* @param data
* @see https://developers.ifttt.com/docs/api_reference#general-api-requirements
*/
Ifttt.prototype._handleResponse = function(err, data) {
var response = {
status: null,
body: {}
};
if (err) {
var errResponse = {};
// Make sure we get a valid error object, otherwise we create one.
if (!_.isObject(err) || !err.message) {
errResponse = {
message: err.toString()
};
}
else {
errResponse.message = err.message;
if (err.status) {
errResponse.status = err.status;
}
}
response.status = err.statusCode || 500;
response.body.errors = [errResponse];
}
else {
response.status = 200;
response.body.data = data;
}
return response;
};
/**
* Registers a resource.
*
* @param type
* @param resource
*/
Ifttt.prototype._registerResource = function(type, resource) {
this.registry[type][resource.getSlug()] = resource;
};
/**
* Returns all resources of given type.
*
* @param type
*/
Ifttt.prototype._getResources = function(type) {
return this.registry[type];
};
/**
* Returns a resource.
*
* @param type
* @param slug
*/
Ifttt.prototype._getResource = function(type, slug) {
return this.registry[type][slug];
};
/**
* Returns a resource.
*
* @param type
* @param slug
*/
Ifttt.prototype._getResource = function(type, slug) {
return this.registry[type][slug];
};
/**
* Get the response for a resource.
*/
Ifttt.prototype._getResourceResponse = function(type, slug, req, payload, cb) {
var that = this;
var resource = this._getResource(type, slug);
if (!resource) {
var err = new Error('Unknown ' + type + '.');
this.logger.error(err);
var response = this._handleResponse(err);
return cb(response);
}
this.logger.log(util.format('_getResourceResponse - type: %s, slug: %s, payload: %j', type, slug, payload));
resource.getResponse(req, payload, function(err, data){
var response = that._handleResponse(err, data);
return cb(response);
});
};
/**
* Get response for a field method.
*/
Ifttt.prototype._getFieldMethodResponse = function(type, slug, field_slug, method, req, payload, cb) {
var that = this;
var resource = this._getResource(type, slug);
if (!resource) {
var err = new Error('Unknown ' + type + '.');
this.logger.error(err);
var response = this._handleResponse(err);
return cb(response);
}
var field = resource.getField(field_slug);
if (!field) {
var err = new Error('Unknown ' + type + ' field.');
this.logger.error(err);
var response = this._handleResponse(err);
return cb(response);
}
switch (method) {
case 'options':
field.options(req, function(err, data){
var response = that._handleResponse(err, data);
return cb(response);
});
break;
case 'validate':
field.validate(req, payload, function(err, data){
var response = that._handleResponse(err, data);
return cb(response);
});
break;
}
};
/**
* Generate sample data for test/setup endpoint.
*/
Ifttt.prototype.generateTestSetupSample = function(cb) {
var samples = {
triggers: {},
triggerFieldValidations: {},
actions: {},
actionRecordSkipping: {}
};
var triggers = this.getTriggers();
_.each(triggers, function(trigger){
var fields = trigger.getFields();
if (fields) {
samples.triggers[trigger.getSlug()] = {};
_.each(fields, function(field){
var sampleData = field.getOptionsSampleData();
if (!_.isUndefined(sampleData.valid)) {
samples.triggers[trigger.getSlug()][field.getSlug()] = sampleData.valid;
}
if (!_.isUndefined(sampleData.invalid)) {
samples.triggerFieldValidations[trigger.getSlug()] = samples.triggerFieldValidations[trigger.getSlug()] || {};
samples.triggerFieldValidations[trigger.getSlug()][field.getSlug()] = sampleData;
}
});
}
});
var actions = this.getActions();
_.each(actions, function(action){
var fields = action.getFields();
if (fields) {
samples.actions[action.getSlug()] = {};
_.each(fields, function(field){
var sampleData = field.getOptionsSampleData();
if (!_.isUndefined(sampleData.valid)) {
samples.actions[action.getSlug()][field.getSlug()] = sampleData.valid;
}
if (field.isRequired()) {
samples.actionRecordSkipping[action.getSlug()] = samples.actionRecordSkipping[action.getSlug()] || {};
samples.actionRecordSkipping[action.getSlug()][field.getSlug()] = '';
}
});
}
});
return cb(samples);
};
/**
* Action shortcuts:
*/
Ifttt.prototype.registerAction = function(action) {
this._registerResource(ACTION_RESOURCE, action);
};
Ifttt.prototype.getActions = function() {
return this._getResources(ACTION_RESOURCE);
};
Ifttt.prototype.getAction = function(slug) {
return this._getResource(ACTION_RESOURCE, slug);
};
Ifttt.prototype.getActionResponse = function(slug, req, payload, cb) {
this._getResourceResponse(ACTION_RESOURCE, slug, req, payload, cb);
};
Ifttt.prototype.getActionFieldOptionsResponse = function(slug, field_slug, req, cb) {
this._getFieldMethodResponse(ACTION_RESOURCE, slug, field_slug, 'options', req, null, cb);
};
Ifttt.Action = ActionResource;
/**
* Trigger shortcuts:
*/
Ifttt.prototype.registerTrigger = function(trigger) {
this._registerResource(TRIGGER_RESOURCE, trigger);
};
Ifttt.prototype.getTriggers = function() {
return this._getResources(TRIGGER_RESOURCE);
};
Ifttt.prototype.getTrigger = function(slug) {
return this._getResource(TRIGGER_RESOURCE, slug);
};
Ifttt.prototype.getTriggerResponse = function(slug, req, payload, cb) {
this._getResourceResponse(TRIGGER_RESOURCE, slug, req, payload, cb);
};
Ifttt.prototype.getTriggerFieldOptionsResponse = function(slug, field_slug, req, cb) {
this._getFieldMethodResponse(TRIGGER_RESOURCE, slug, field_slug, 'options', req, null, cb);
};
Ifttt.prototype.getTriggerFieldValidateResponse = function(slug, field_slug, req, value, cb) {
this._getFieldMethodResponse(TRIGGER_RESOURCE, slug, field_slug, 'validate', req, value, cb);
};
Ifttt.Trigger = TriggerResource;
module.exports = Ifttt;