UNPKG

5.6 kBJavaScriptView Raw
1var mensaje = require('js2xmlparser');
2var xml2js = require('xml2js').parseString;
3var stripBom = require('strip-bom');
4var net = require('net');
5var colors = require('colors');
6var global = { conn: new net.Socket(),
7 last_id: '',
8 last_cmd: '',
9 filename: '',
10 fullmap: '',
11 curr_state: 'wait',
12 buffer: ''
13 };
14var changes = {}; // node ids struct and its changes.
15var defaults = {
16 'receive_lock' : function(data, callback) {
17 global.last_id = data['$'].id;
18 console.log('*** recibimos lock id: ****',global.last_id);
19 if (callback) callback(data);
20 },
21 'welcome' : function(data, callback) {
22 console.log('welcome in concepto',data);
23 if ('$' in data && 'map' in data['$']) {
24 global.filename = data['$'].filename;
25 global.fullmap = data['$'].map;
26 }
27 if (callback) callback(data);
28 }
29};
30
31exports.getLastID = function() {
32 return global.last_id;
33};
34
35exports.getMap = function(callback) {
36 if (callback) {
37 xml2js(global.fullmap, function(err, result) {
38 try {
39 var parent_tag = Object.keys(result)[0].toString();
40 result._filename = global.filename;
41 callback(result);
42 } catch(e) {
43 }
44 });
45 } else {
46 return { filename:global.filename, map:global.fullmap };
47 }
48}
49
50exports.parseXml = function(xml, callback) {
51 xml2js(xml, function(err, result) {
52 var parent_tag = Object.keys(result)[0].toString();
53 callback(parent_tag, result[parent_tag]);
54 });
55};
56
57exports.init = function(callback, options) {
58 if (options) {
59 // definimos valores default, en caso de haber options definidos
60 if ('retry' in options) {
61 if (options.retry==true) {
62 defaults['goodbye'] = function() {
63 console.log('conn:retrying connecting as requested in options.');
64 exports.init();
65 }
66 }
67 }
68 //
69 }
70 global.conn.connect(9000, 'localhost', function() {
71 callback();
72 });
73};
74
75exports.on = function(events) {
76 global.conn.on('error', function(data) {
77 if ('_error' in events) {
78 events['_error'](data);
79 }
80 });
81 global.conn.on('data', function(data) {
82 data = stripBom(data);
83 var xmlheader = 'encoding="UTF-8"?>';
84 var msg_continues = false;
85 if (data.toString().indexOf('<cont>')!=-1) {
86 // este pack de datos necesita sumarse al buffer
87 var tt = data.toString().split('<cont>').join('');
88 global.buffer += tt;
89 msg_continues = true;
90 } else {
91 global.buffer = data.toString();
92 }
93 var justcmd = global.buffer;
94 /*justcmd = justcmd.split('&lt;').join('<')
95 .split('&quot;').join('"')
96 .split('&lt;').join('<');*/
97 //console.log(justcmd.toString().magenta);
98 var pos = justcmd.toString().indexOf(xmlheader)+xmlheader.length; //
99 //console.log('pos de utf-8:'.yellow,pos);
100 if (pos!=-1) {
101 justcmd = justcmd.slice(pos);
102 }
103 if (msg_continues==false) {
104 try {
105 var recibido = xml2js(justcmd, function(err, result) {
106 if (isObject(result)) {
107 var cmd = Object.keys(result)[0].toString();
108 var scmd = cmd.split('collaboration_').join('');
109 if (err) console.log('error en xml2js:',err);
110 global.last_cmd = scmd;
111 if (scmd in events) {
112 //console.log('conn:llamando cmd:'+scmd+' definido en param events');
113 if (scmd in defaults) { // si habia un default, tambien lo ejecutamos.
114 defaults[scmd](result[cmd],function(x) {
115 events[scmd](result[cmd],cmd);
116 });
117 } else {
118 events[scmd](result[cmd]);
119 }
120 } else if ('*' in events) {
121 // evento fallback en si mismo detectado
122 if (scmd in defaults) {
123 defaults[scmd](result[cmd],function(x) {
124 events['*'](result[cmd],cmd);
125 });
126 } else {
127 events['*'](result[cmd],cmd);
128 }
129 } else if (scmd in defaults) {
130 defaults[scmd](result[cmd]);
131 //console.log('conn:cmd:'+scmd+' no ha sido definido en param events. se omite.');
132 }
133 } else {
134 console.log('smart:result is not object'.red,result);
135 }
136 });
137 } catch(e) {
138 console.log('error procesando respuesta xml a JS. xml:'.yellow, justcmd);
139 console.log(e);
140 }
141 }
142 });
143};
144
145exports.write = function(cmd, obj) {
146 var tmp = { cmd: 'collaboration_'+cmd, data:obj };
147 var msg = mensaje(tmp.cmd, obj);
148 //msg = msg.split('&gt;').join('>');
149 msg = msg.split('\n').join('');
150 //console.log('\nconn:send:enviando:',msg);
151 global.conn.write(msg+'\r\n','utf-8', function() {
152 //global.conn.end();
153 });
154};
155
156exports.send = {
157 login : function(name) {
158 exports.write('hello', { "@" : { "user_id" : name+"@MacBookdeX.home",
159 "password" : "depurador123",
160 }
161 }
162 );
163 },
164 getlock : function() {
165 exports.write('require_lock',{});
166 },
167 transaction : function(action,undo) {
168 var espera = 50;
169 if (global.last_cmd!='receive_lock' || global.last_id=='') {
170 exports.send.getlock();
171 espera = 1000;
172 }
173 setTimeout(function() {
174 // ejecutamos con desfase segun si hay o no lock.
175 exports.write('transaction',{
176 '@' : {
177 'id' : global.last_id,
178 'do_action' : mensaje('compound_action',action),
179 'undo_action' : mensaje('compound_action',undo)
180 }
181 });
182 }, espera);
183 }
184};
185
186exports.getNodeAfterAction = function(action) {
187 // returns node struct with attributes and content, after applying transaction.
188 /*
189 edit_node_action SOLICITADA SOBRE NODE ID: ID_444377458: { '$': { node: 'ID_444377458' }, text: [ 'animalito1' ] }
190 retorna:
191 changes['ID_444377458'] = {
192 text : 'animalito1',
193 attributes : {},
194 icons : ''
195 }
196 */
197};
198
199exports.destroy = function() {
200 global.conn.destroy();
201};
202
203isObject = function(a) {
204 return (!!a) && (a.constructor === Object);
205};
\No newline at end of file