|
| 1 | + |
| 2 | +const azureStorage = require('azure-storage'); |
| 3 | +const cfg = require('../common/config') |
| 4 | + |
| 5 | +module.exports = function (context, data) { |
| 6 | + context.log('Calendar Webhook Handler was triggered!'); |
| 7 | + |
| 8 | + // Handle subscription request |
| 9 | + if (data.query.validationToken) { |
| 10 | + context.log('registering new hook'); |
| 11 | + context.res = { |
| 12 | + status: 200, |
| 13 | + body: data.query.validationToken |
| 14 | + }; |
| 15 | + context.done(); |
| 16 | + return; |
| 17 | + } |
| 18 | + |
| 19 | + const storageConnectionString = process.env.storageConnectionString || 'DefaultEndpointsProtocol=https;AccountName=travelerbot;AccountKey=b2cmbtSrWvJ2ebxO0PD1CQ+svlaxjUY3xtC8DdzJyeFXRGVgnsGhZkqU82rvgMiXE0ybEaWlTZpEsf/65drmNA==;EndpointSuffix=core.windows.net'; |
| 20 | + const queueSvc = azureStorage.createQueueService(storageConnectionString); |
| 21 | + // Write incoming notifications onto a queue. |
| 22 | + queueSvc.createQueueIfNotExists('hook-recieved', (err, result, response) => { |
| 23 | + if (err){ |
| 24 | + // this should be a log for the dev, not a message to the user |
| 25 | + session.send('There was an error creating the hook-recieved queue: '+ err); |
| 26 | + context.done(err); |
| 27 | + return; |
| 28 | + } |
| 29 | + // enqueue a message to process the webhook request. |
| 30 | + const request = data.body; |
| 31 | + context.log(request); |
| 32 | + const notificationCount = request.value.length; |
| 33 | + let processed = 0; |
| 34 | + // web hook requests can contain multiple notifications |
| 35 | + for (let hook of request.value) { |
| 36 | + let msg = JSON.stringify(hook); |
| 37 | + context.log(msg); |
| 38 | + var queueMessageBuffer = new Buffer(msg).toString('base64'); |
| 39 | + // only take action when the clientState is vaild. |
| 40 | + // return the 202 and do notthing if the clientState is vaild. |
| 41 | + if (hook.clientState !== cfg.CLIENT_STATE) { |
| 42 | + // add a log entry so that this can be investigated |
| 43 | + context.log('Unknown sender! Investigate the source of this message') |
| 44 | + context.log(data); |
| 45 | + context.res = { status: 202, body: 'All notifications processed' }; |
| 46 | + context.done(); |
| 47 | + return; |
| 48 | + break; |
| 49 | + } |
| 50 | + queueSvc.createMessage('hook-recieved', queueMessageBuffer, (err, result, response) => { |
| 51 | + processed++; |
| 52 | + // fail on any message not getting queued properly |
| 53 | + if (err) { |
| 54 | + context.log('error sending webhook messge on hook-recieved queue'); |
| 55 | + context.done(err); |
| 56 | + return; |
| 57 | + } |
| 58 | + context.log('webhook messge on put onto hook-recieved queue'); |
| 59 | + if (processed == notificationCount) { |
| 60 | + context.res = { status: 202, body: 'All notifications processed' }; |
| 61 | + context.done(); |
| 62 | + } |
| 63 | + }); |
| 64 | + } |
| 65 | + }); |
| 66 | +} |
0 commit comments