2d69e427228db10382e7bdfd80ac1464c3158024
[motion.git] / server / api / fax_message / fax_message.ami.js
1 'use strict';
2
3 var _ = require('lodash');
4 var util = require('util');
5
6 var FaxMessage = require('../../models').FaxMessage;
7 var Trunk = require('../../models').User;
8
9 exports.register = function(ami) {
10
11   FaxMessage.afterCreate(function(doc) {
12     console.log('FaxMessage afterCreate');
13     onSave(ami, doc);
14   });
15 };
16
17 function onSave(ami, doc, cb) {
18   if (doc.status === 'NOT SENT' && !doc.actionid) {
19     // I have to send the fax with the Originate
20     var faxBody = JSON.parse(doc.body);
21     console.log('faxBody', faxBody);
22
23     Trunk
24       .findById(faxBody.trunk.id)
25       .then(function(trunk) {
26         var action = {
27           Action: 'originate',
28           CallerID: faxBody.from,
29           Channel: util.format('%s/%s@%s', faxBody.technology, faxBody.to, trunk.name),
30           Context: 'outbound-fax',
31           Exten: 's',
32           Priority: 1,
33           Async: 'true',
34           Variable: {
35             MAXRATE: faxBody.maxrate,
36             MINRATE: faxBody.minrate,
37             ECM: faxBody.ecm ? 'yes' : 'no',
38             LOCALID: faxBody.fax_localid,
39             FAXFILE: faxBody.fax_file,
40             // 'FAXFILE': 'test.tiff', // Scommentare se si fanno prove in locale!
41             FAXHEADER: faxBody.fax_header,
42             FAXUUID: faxBody.uuid
43           }
44         };
45
46         ami.action(action, function(err, res) {
47           if (err) {
48             doc.updateAttributes({
49               status: 'FAILED'
50             });
51           } else {
52             if (res.response && res.actionid) {
53               doc.updateAttributes({
54                 actionid: res.actionid
55               });
56             }
57           }
58         });
59       })
60       .catch(function(err) {
61         console.error(err);
62       });
63   }
64 }