aboutsummaryrefslogtreecommitdiff
path: root/lib/controllers/recordings.js
blob: c7a75843779efabbc307ed25721e8b8b9c91c399 (plain)
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
'use strict';

const Joi = require('joi');
const Pify = require('pify');
const Redis = require('redis');
const Twilio = require('twilio');

const internals = {};

internals.kContentType = 'application/xml'; // The content type used to respond
internals.kLanguage = 'es-mx'; // the language to use
internals.kMaxMessageLength = 30; // max message length in seconds
internals.kRecordingsSet = 'recordings';
internals.kRecordMessage = 'Graba tu mensaje despues del bip y ' +
                           'presiona cualquier tecla para finalizar. '; // the recording message
internals.kConfirmationMessage = 'Gracias. Tu mensaje es el número: ';
internals.kNotFoundMessage = 'Mensaje no encontrado. Adiós!';

internals.kRecordingSchema = Joi.object().keys({
  url: Joi.string().required()
});

/**
 * Handles the HTTP requests for the recording menu
 *
 * @class RecordingsController
 * @param {DeadDrop.tConfiguration} config The configuration to
 * initialize.
 */
module.exports = internals.RecordingsController = class RecordingsController {
  constructor(config) {

    this._redis = Redis.createClient(config.redis);

    // Log an error if it happens.
    this._redis.on('error', (err) => {

      console.error(err);
    });
  }

  /**
   * Start recording process
   *
   * @function startRecording
   * @memberof RecordingsController
   * @instance
   * @return {generator} a koa compatible handler generator function
   */
  startRecording() {

    return function * () {

      const response = new Twilio.TwimlResponse();

      // the action will default to post in the same URL, so no change
      // required there.
      response.say(internals.kRecordMessage, { language: internals.kLanguage })
      .record({
        maxLength: internals.kMaxMessageLength
      });

      this.type = internals.kContentType;
      this.body = response.toString();
    };
  }

  /**
   * Saves the recording for later use
   *
   * @function saveRecording
   * @memberof RecordingsController
   * @instance
   * @return {generator} a koa compatible handler generator function
   */
  saveRecording() {

    const self = this;

    return function * () {

      const zadd = Pify(self._redis.zadd.bind(self._redis));

      const response = new Twilio.TwimlResponse();

      const id = Date.now().toString().substr(2,10);
      const url = this.request.body.RecordingUrl;
      const separatedId = id.split('').join('. ');
      const recording = {
        url
      };

      yield self._validate(recording).catch((err) => {

        this.throw(err.message, 422);
      });

      // Add to ordered set for quick fetches, and set for random fetches
      yield zadd(internals.kRecordingsSet, parseInt(id), url);

      response.say(`${internals.kConfirmationMessage}${separatedId}`, { language: internals.kLanguage });

      this.type = internals.kContentType;
      this.body = response.toString();
    };
  }

  /**
   * Gets a recording.
   *
   * @function getRecording
   * @memberof RecordingsController
   * @instance
   * @return {generator} a koa compatible handler generator function
   */
  getRecording() {

    const self = this;

    return function * (id) {

      id = parseInt(id);

      const zcard = Pify(self._redis.zcard.bind(self._redis));
      const zrange = Pify(self._redis.zrange.bind(self._redis));
      const zscore = Pify(self._redis.zscore.bind(self._redis));
      const zrangebyscore = Pify(self._redis.zrangebyscore.bind(self._redis));

      const response = new Twilio.TwimlResponse();
      let location = null;

      if (!id) {
        const maxNumber = yield zcard(internals.kRecordingsSet);
        const index = Math.floor(Math.random() * maxNumber); // get random between 0 and cardinality
        location = yield zrange(internals.kRecordingsSet, index, index);
      }
      else {
        location = yield zrangebyscore(internals.kRecordingsSet, id, id);
      }

      if (location && location.length > 0) {
        if (!id) {
          id = yield zscore(internals.kRecordingsSet, location[0]);
        }

        const separatedId = id.toString().split('').join('. ');
        response.play(location[0]).say(separatedId, { language: internals.kLanguage });
      }
      else {
        response.say(internals.kNotFoundMessage, { language: internals.kLanguage });
      }

      this.type = internals.kContentType;
      this.body = response.toString();
    };
  }

  // Validates the post schema

  _validate(post) {

    const validate = Pify(Joi.validate.bind(Joi));
    return validate(post, internals.kRecordingSchema);
  }
};