diff --git a/lib/client/edit.js b/lib/client/edit.js index 72c87e88..c65562ce 100644 --- a/lib/client/edit.js +++ b/lib/client/edit.js @@ -1,4 +1,4 @@ -var CloudCmd, Util, DOM, CloudFunc, ace, DiffProto, diff_match_patch, Zip, MenuIO, Format; +var CloudCmd, Util, DOM, CloudFunc, io, ace, DiffProto, diff_match_patch, Zip, MenuIO, Format; (function(CloudCmd, Util, DOM, CloudFunc) { 'use strict'; @@ -45,10 +45,52 @@ var CloudCmd, Util, DOM, CloudFunc, ace, DiffProto, diff_match_patch, Zip, MenuI exec.series([ CloudCmd.View, load, - Edit.show.bind(null, callback) + Edit.show.bind(null, callback), + function() { + initSocket(); + } ]); } + function getHost() { + var l = location, + href = l.origin || l.protocol + '//' + l.host; + + return href; + } + + function initSocket(error) { + var socket, + href = getHost(), + FIVE_SECONDS = 5000, + patch = function(path, patch) { + socket.emit('patch', path, patch); + }; + + if (!error) { + socket = io.connect(href + '/config', { + 'max reconnection attempts' : Math.pow(2, 32), + 'reconnection limit' : FIVE_SECONDS + }); + + socket.on('connect', function() { + Edit.save.patch = patch; + }); + + socket.on('message', function(msg) { + onSave(msg); + }); + + socket.on('disconnect', function() { + Edit.save.patch = patchHttp; + }); + + socket.on('err', function(error) { + Util.log(error); + }); + } + } + this.show = function(callback) { var func = exec.ret(callback); @@ -310,13 +352,16 @@ var CloudCmd, Util, DOM, CloudFunc, ace, DiffProto, diff_match_patch, Zip, MenuI }); }; - Edit.save.patch = function(path, patch) { - RESTful.patch(path, patch, onSave); - }; + Edit.save.patch = patchHttp; + Edit.save.write = writeHttp; - Edit.save.write = function(path, result) { + function patchHttp(path, patch) { + RESTful.patch(path, patch, onSave); + } + + function writeHttp(path, result) { RESTful.write(path, result, onSave); - }; + } function doDiff(path, callback) { var value = Ace.getValue(); diff --git a/lib/server/edit.js b/lib/server/edit.js new file mode 100644 index 00000000..1184544b --- /dev/null +++ b/lib/server/edit.js @@ -0,0 +1,34 @@ +(function() { + 'use strict'; + + var DIR_SERVER = __dirname + '/', + DIR_LIB = DIR_SERVER + '../', + + path = require('path'), + Util = require(DIR_LIB + 'util'), + CloudFunc = require(DIR_LIB + 'cloudfunc'), + patch = require(DIR_SERVER + 'patch'); + + module.exports = function(sock) { + Util.check(arguments, ['socket']); + + sock.of('/config') + .on('connection', function(socket) { + socket.on('patch', function(data) { + var options = { + size: CloudFunc.MAX_FILE_SIZE + }; + + patch(name, data, options, function(error) { + var baseName = path.basename(name), + msg = CloudFunc.formatMsg('patch', baseName); + + if (error) + socket.emit('err', error); + else + socket.emit('message', msg); + }); + }); + }); + }; +})();