|
| 1 | +require('dotenv').config(); |
| 2 | +const app = require('express')(); |
| 3 | +const bodyParser = require('body-parser'); |
| 4 | + |
| 5 | +app.use(bodyParser.json()); |
| 6 | +app.use(bodyParser.urlencoded({ extended: true })); |
| 7 | + |
| 8 | +app |
| 9 | + .route('/webhooks/inbound-sms') |
| 10 | + .get(handleInboundSms) |
| 11 | + .post(handleInboundSms); |
| 12 | + |
| 13 | +let concat_sms = []; // Array of message objects |
| 14 | + |
| 15 | +function handleInboundSms(request, response) { |
| 16 | + const params = Object.assign(request.query, request.body); |
| 17 | + |
| 18 | + if (params['concat'] === 'true') { |
| 19 | + /* This is a concatenated message. Add it to an array |
| 20 | + so that we can process it later. */ |
| 21 | + concat_sms.push({ |
| 22 | + ref: params['concat-ref'], |
| 23 | + part: params['concat-part'], |
| 24 | + from: params.msisdn, |
| 25 | + message: params.text |
| 26 | + }); |
| 27 | + |
| 28 | + /* Do we have all the message parts yet? They might |
| 29 | + not arrive consecutively. */ |
| 30 | + let parts_for_ref = concat_sms.filter(function (part) { |
| 31 | + return part.ref == params['concat-ref']; |
| 32 | + }); |
| 33 | + |
| 34 | + // Is this the last message part for this reference? |
| 35 | + if (parts_for_ref.length == params['concat-total']) { |
| 36 | + console.dir(parts_for_ref); |
| 37 | + processConcatSms(parts_for_ref); |
| 38 | + } |
| 39 | + } else { |
| 40 | + // Not a concatenated message, so just display it |
| 41 | + displaySms(params.msisdn, params.text); |
| 42 | + } |
| 43 | + |
| 44 | + // Send OK status |
| 45 | + response.status(204).send(); |
| 46 | +} |
| 47 | + |
| 48 | +function processConcatSms(all_parts) { |
| 49 | + |
| 50 | + // Order all the message parts |
| 51 | + all_parts.sort(function (a, b) { |
| 52 | + if (Number(a.part) < Number(b.part)) { |
| 53 | + return -1; |
| 54 | + } else { |
| 55 | + return 1; |
| 56 | + } |
| 57 | + }) |
| 58 | + |
| 59 | + let concat_message = ''; |
| 60 | + |
| 61 | + // Reassemble the message from the parts |
| 62 | + for (i = 0; i < all_parts.length; i++) { |
| 63 | + concat_message += all_parts[i].message; |
| 64 | + } |
| 65 | + |
| 66 | + displaySms(all_parts[0].from, concat_message); |
| 67 | +} |
| 68 | + |
| 69 | +function displaySms(msisdn, text) { |
| 70 | + console.log('FROM: ' + msisdn); |
| 71 | + console.log('MESSAGE: ' + text); |
| 72 | + console.log('---'); |
| 73 | +} |
| 74 | + |
| 75 | +app.listen(process.env.PORT); |
0 commit comments