a8737f4a6f691e42beb1ec652ef30a2b3b9ec572
[motion.git] / server / api / voice_context / voice_context.ami.js
1 'use strict';
2
3 var VoiceContext = require('../../models').VoiceContext;
4 var fs = require('fs');
5 var util = require('util');
6 var path = require('path');
7 var config = require('../../config/environment');
8
9 exports.register = function(ami) {
10   VoiceContext.beforeUpdate(function(updatedContext) {
11     if (updatedContext.changed('name')) {
12       throw new Error("You can't modify a context name");
13     }
14     if (updatedContext.defaultEntry) {
15       throw new Error("You can't modify a default context");
16     }
17   });
18
19   VoiceContext.beforeDelete(function(context) {
20     if (context.defaultEntry) {
21       throw new Error("You can't delete a default context");
22     }
23   });
24
25   VoiceContext.afterCreate(function(doc) {
26     rewriteContexts(doc, ami, false);
27   })
28
29   VoiceContext.afterDelete(function(doc) {
30     rewriteContexts(doc, ami, true);
31   })
32 }
33
34 function rewriteContexts(doc, ami, deleteContext) {
35   var contextValues = '';
36   if (!deleteContext) {
37     contextValues = util.format('[%s]\nswitch => Realtime\n', doc.name);
38   }
39   VoiceContext
40     .findAll({
41       where: {
42         id: {
43           $ne: doc.id
44         }
45       }
46     })
47     .then(function(contexts) {
48       contexts.forEach(function(element) {
49         contextValues += util.format('[%s]\nswitch => Realtime\n', element.name);
50       });
51       fs.writeFile(path.join(config.root, 'server/files/asterisk/sip_xcally_contexts.conf'), contextValues, {
52         flags: 'w',
53         mode: parseInt('0777', 8)
54       }, function(err) {
55         if (err) throw err;
56         console.log("Contexts file saved!");
57         ami.action({
58           Action: 'Reload',
59         }, function(err, res) {
60           if (err) {
61             console.error(err);
62           } else {
63             console.log(res);
64           }
65         });
66       });
67     })
68     .catch(function(err) {
69       console.log(err);
70     });
71 }