Commit f0aae04c authored by Alexander.Trofimov's avatar Alexander.Trofimov

change codestyle

git-svn-id: svn://192.168.3.15/activex/AVS/Sources/TeamlabOffice/trunk/OfficeWeb@64653 954022d7-b5bf-4e40-9824-e11837661b57
parent 81e97606
"use strict"; "use strict";
(function (window, undefined) { (function(window, undefined) {
'use strict'; 'use strict';
var asc = window["Asc"]; var asc = window["Asc"];
var asc_coAuthV = '3.0.8'; var asc_coAuthV = '3.0.8';
// Класс надстройка, для online и offline работы // Класс надстройка, для online и offline работы
function CDocsCoApi (options) { function CDocsCoApi(options) {
this._CoAuthoringApi = new DocsCoApi(); this._CoAuthoringApi = new DocsCoApi();
this._onlineWork = false; this._onlineWork = false;
...@@ -31,88 +31,124 @@ ...@@ -31,88 +31,124 @@
} }
} }
CDocsCoApi.prototype.init = function (user, docid, documentCallbackUrl, token, callback, editorType, documentFormatSave, isViewer) { CDocsCoApi.prototype.init = function(user, docid, documentCallbackUrl, token, callback, editorType, documentFormatSave, isViewer) {
if (this._CoAuthoringApi && this._CoAuthoringApi.isRightURL()) { if (this._CoAuthoringApi && this._CoAuthoringApi.isRightURL()) {
var t = this; var t = this;
this._CoAuthoringApi.onAuthParticipantsChanged = function (e, count) {t.callback_OnAuthParticipantsChanged(e, count);}; this._CoAuthoringApi.onAuthParticipantsChanged = function(e, count) {
this._CoAuthoringApi.onParticipantsChanged = function (e, count) {t.callback_OnParticipantsChanged(e, count);}; t.callback_OnAuthParticipantsChanged(e, count);
this._CoAuthoringApi.onMessage = function (e, clear) {t.callback_OnMessage(e, clear);}; };
this._CoAuthoringApi.onLocksAcquired = function (e) {t.callback_OnLocksAcquired(e);}; this._CoAuthoringApi.onParticipantsChanged = function(e, count) {
this._CoAuthoringApi.onLocksReleased = function (e, bChanges) {t.callback_OnLocksReleased(e, bChanges);}; t.callback_OnParticipantsChanged(e, count);
this._CoAuthoringApi.onLocksReleasedEnd = function () {t.callback_OnLocksReleasedEnd();}; };
this._CoAuthoringApi.onDisconnect = function (e, isDisconnectAtAll, isCloseCoAuthoring) {t.callback_OnDisconnect(e, isDisconnectAtAll, isCloseCoAuthoring);}; this._CoAuthoringApi.onMessage = function(e, clear) {
this._CoAuthoringApi.onFirstLoadChangesEnd = function () {t.callback_OnFirstLoadChangesEnd();}; t.callback_OnMessage(e, clear);
this._CoAuthoringApi.onConnectionStateChanged = function (e) {t.callback_OnConnectionStateChanged(e);}; };
this._CoAuthoringApi.onSetIndexUser = function (e) {t.callback_OnSetIndexUser(e);}; this._CoAuthoringApi.onLocksAcquired = function(e) {
this._CoAuthoringApi.onSaveChanges = function (e, userId, bFirstLoad) {t.callback_OnSaveChanges(e, userId, bFirstLoad);}; t.callback_OnLocksAcquired(e);
};
this._CoAuthoringApi.onLocksReleased = function(e, bChanges) {
t.callback_OnLocksReleased(e, bChanges);
};
this._CoAuthoringApi.onLocksReleasedEnd = function() {
t.callback_OnLocksReleasedEnd();
};
this._CoAuthoringApi.onDisconnect = function(e, isDisconnectAtAll, isCloseCoAuthoring) {
t.callback_OnDisconnect(e, isDisconnectAtAll, isCloseCoAuthoring);
};
this._CoAuthoringApi.onFirstLoadChangesEnd = function() {
t.callback_OnFirstLoadChangesEnd();
};
this._CoAuthoringApi.onConnectionStateChanged = function(e) {
t.callback_OnConnectionStateChanged(e);
};
this._CoAuthoringApi.onSetIndexUser = function(e) {
t.callback_OnSetIndexUser(e);
};
this._CoAuthoringApi.onSaveChanges = function(e, userId, bFirstLoad) {
t.callback_OnSaveChanges(e, userId, bFirstLoad);
};
// Callback есть пользователей больше 1 // Callback есть пользователей больше 1
this._CoAuthoringApi.onStartCoAuthoring = function (e) {t.callback_OnStartCoAuthoring(e);}; this._CoAuthoringApi.onStartCoAuthoring = function(e) {
this._CoAuthoringApi.onEndCoAuthoring = function (e) {t.callback_OnEndCoAuthoring(e);}; t.callback_OnStartCoAuthoring(e);
this._CoAuthoringApi.onUnSaveLock = function () {t.callback_OnUnSaveLock();}; };
this._CoAuthoringApi.onRecalcLocks = function (e) {t.callback_OnRecalcLocks(e);}; this._CoAuthoringApi.onEndCoAuthoring = function(e) {
this._CoAuthoringApi.onDocumentOpen = function (data) {t.callback_OnDocumentOpen(data);}; t.callback_OnEndCoAuthoring(e);
};
this._CoAuthoringApi.onUnSaveLock = function() {
t.callback_OnUnSaveLock();
};
this._CoAuthoringApi.onRecalcLocks = function(e) {
t.callback_OnRecalcLocks(e);
};
this._CoAuthoringApi.onDocumentOpen = function(data) {
t.callback_OnDocumentOpen(data);
};
this._CoAuthoringApi.init(user, docid, documentCallbackUrl, token, callback, editorType, documentFormatSave, isViewer); this._CoAuthoringApi.init(user, docid, documentCallbackUrl, token, callback, editorType, documentFormatSave, isViewer);
this._onlineWork = true; this._onlineWork = true;
} } else {
else {
// Фиктивные вызовы // Фиктивные вызовы
this.callback_OnSetIndexUser ("123"); this.callback_OnSetIndexUser("123");
this.onFirstLoadChangesEnd (); this.onFirstLoadChangesEnd();
callback(); callback();
} }
}; };
CDocsCoApi.prototype.set_url = function (url) { CDocsCoApi.prototype.set_url = function(url) {
if (this._CoAuthoringApi) if (this._CoAuthoringApi) {
this._CoAuthoringApi.set_url(url); this._CoAuthoringApi.set_url(url);
}
}; };
CDocsCoApi.prototype.get_onlineWork = function () { CDocsCoApi.prototype.get_onlineWork = function() {
return this._onlineWork; return this._onlineWork;
}; };
CDocsCoApi.prototype.get_state = function () { CDocsCoApi.prototype.get_state = function() {
if (this._CoAuthoringApi) if (this._CoAuthoringApi) {
return this._CoAuthoringApi.get_state(); return this._CoAuthoringApi.get_state();
}
return 0; return 0;
}; };
CDocsCoApi.prototype.openDocument = function (data) { CDocsCoApi.prototype.openDocument = function(data) {
if (this._CoAuthoringApi && this._onlineWork) if (this._CoAuthoringApi && this._onlineWork) {
this._CoAuthoringApi.openDocument(data); this._CoAuthoringApi.openDocument(data);
}
}; };
CDocsCoApi.prototype.sendRawData = function (data) { CDocsCoApi.prototype.sendRawData = function(data) {
if (this._CoAuthoringApi && this._onlineWork) if (this._CoAuthoringApi && this._onlineWork) {
this._CoAuthoringApi.sendRawData(data); this._CoAuthoringApi.sendRawData(data);
}
}; };
CDocsCoApi.prototype.getMessages = function () { CDocsCoApi.prototype.getMessages = function() {
if (this._CoAuthoringApi && this._onlineWork) if (this._CoAuthoringApi && this._onlineWork) {
this._CoAuthoringApi.getMessages(); this._CoAuthoringApi.getMessages();
}
}; };
CDocsCoApi.prototype.sendMessage = function (message) { CDocsCoApi.prototype.sendMessage = function(message) {
if (this._CoAuthoringApi && this._onlineWork) if (this._CoAuthoringApi && this._onlineWork) {
this._CoAuthoringApi.sendMessage(message); this._CoAuthoringApi.sendMessage(message);
}
}; };
CDocsCoApi.prototype.askLock = function (arrayBlockId, callback) { CDocsCoApi.prototype.askLock = function(arrayBlockId, callback) {
if (this._CoAuthoringApi && this._onlineWork) { if (this._CoAuthoringApi && this._onlineWork) {
this._CoAuthoringApi.askLock(arrayBlockId, callback); this._CoAuthoringApi.askLock(arrayBlockId, callback);
} } else {
else {
var t = this; var t = this;
window.setTimeout(function () { window.setTimeout(function() {
if (callback && _.isFunction(callback)) { if (callback && _.isFunction(callback)) {
var lengthArray = (arrayBlockId) ? arrayBlockId.length : 0; var lengthArray = (arrayBlockId) ? arrayBlockId.length : 0;
if (0 < lengthArray) { if (0 < lengthArray) {
callback({"lock": arrayBlockId[0]}); callback({"lock": arrayBlockId[0]});
// Фиктивные вызовы // Фиктивные вызовы
for (var i = 0; i < lengthArray; ++i) { for (var i = 0; i < lengthArray; ++i) {
t.callback_OnLocksAcquired ({"state" : 2, "block": arrayBlockId[i]}); t.callback_OnLocksAcquired({"state": 2, "block": arrayBlockId[i]});
} }
} }
} }
...@@ -120,11 +156,11 @@ ...@@ -120,11 +156,11 @@
} }
}; };
CDocsCoApi.prototype.askSaveChanges = function (callback) { CDocsCoApi.prototype.askSaveChanges = function(callback) {
if (this._CoAuthoringApi && this._onlineWork) { if (this._CoAuthoringApi && this._onlineWork) {
this._CoAuthoringApi.askSaveChanges(callback); this._CoAuthoringApi.askSaveChanges(callback);
} else { } else {
window.setTimeout(function () { window.setTimeout(function() {
if (callback && _.isFunction(callback)) { if (callback && _.isFunction(callback)) {
// Фиктивные вызовы // Фиктивные вызовы
callback({"saveLock": false}); callback({"saveLock": false});
...@@ -133,88 +169,96 @@ ...@@ -133,88 +169,96 @@
} }
}; };
CDocsCoApi.prototype.unSaveLock = function () { CDocsCoApi.prototype.unSaveLock = function() {
if (this._CoAuthoringApi && this._onlineWork) { if (this._CoAuthoringApi && this._onlineWork) {
this._CoAuthoringApi.unSaveLock(); this._CoAuthoringApi.unSaveLock();
} else { } else {
var t = this; var t = this;
window.setTimeout(function () { window.setTimeout(function() {
// Фиктивные вызовы // Фиктивные вызовы
t.callback_OnUnSaveLock(); t.callback_OnUnSaveLock();
}, 100); }, 100);
} }
}; };
CDocsCoApi.prototype.saveChanges = function (arrayChanges, deleteIndex, excelAdditionalInfo) { CDocsCoApi.prototype.saveChanges = function(arrayChanges, deleteIndex, excelAdditionalInfo) {
if (this._CoAuthoringApi && this._onlineWork) { if (this._CoAuthoringApi && this._onlineWork) {
this._CoAuthoringApi.saveChanges(arrayChanges, null, deleteIndex, excelAdditionalInfo); this._CoAuthoringApi.saveChanges(arrayChanges, null, deleteIndex, excelAdditionalInfo);
} }
}; };
CDocsCoApi.prototype.unLockDocument = function (isSave) { CDocsCoApi.prototype.unLockDocument = function(isSave) {
if (this._CoAuthoringApi && this._onlineWork) { if (this._CoAuthoringApi && this._onlineWork) {
this._CoAuthoringApi.unLockDocument(isSave); this._CoAuthoringApi.unLockDocument(isSave);
} }
}; };
CDocsCoApi.prototype.getUsers = function () { CDocsCoApi.prototype.getUsers = function() {
if (this._CoAuthoringApi && this._onlineWork) { if (this._CoAuthoringApi && this._onlineWork) {
this._CoAuthoringApi.getUsers(); this._CoAuthoringApi.getUsers();
} }
}; };
CDocsCoApi.prototype.getUser = function (userId) { CDocsCoApi.prototype.getUser = function(userId) {
if (this._CoAuthoringApi && this._onlineWork) if (this._CoAuthoringApi && this._onlineWork) {
return this._CoAuthoringApi.getUser(userId); return this._CoAuthoringApi.getUser(userId);
}
return null; return null;
}; };
CDocsCoApi.prototype.getUserConnectionId = function () { CDocsCoApi.prototype.getUserConnectionId = function() {
if (this._CoAuthoringApi && this._onlineWork) if (this._CoAuthoringApi && this._onlineWork) {
return this._CoAuthoringApi.getUserConnectionId(); return this._CoAuthoringApi.getUserConnectionId();
}
return null; return null;
}; };
CDocsCoApi.prototype.releaseLocks = function (blockId) { CDocsCoApi.prototype.releaseLocks = function(blockId) {
if (this._CoAuthoringApi && this._onlineWork) { if (this._CoAuthoringApi && this._onlineWork) {
this._CoAuthoringApi.releaseLocks(blockId); this._CoAuthoringApi.releaseLocks(blockId);
} }
}; };
CDocsCoApi.prototype.disconnect = function () { CDocsCoApi.prototype.disconnect = function() {
if (this._CoAuthoringApi && this._onlineWork) { if (this._CoAuthoringApi && this._onlineWork) {
this._CoAuthoringApi.disconnect(); this._CoAuthoringApi.disconnect();
} }
}; };
CDocsCoApi.prototype.callback_OnAuthParticipantsChanged = function (e, count) { CDocsCoApi.prototype.callback_OnAuthParticipantsChanged = function(e, count) {
if (this.onAuthParticipantsChanged) if (this.onAuthParticipantsChanged) {
this.onAuthParticipantsChanged(e, count); this.onAuthParticipantsChanged(e, count);
}
}; };
CDocsCoApi.prototype.callback_OnParticipantsChanged = function (e, count) { CDocsCoApi.prototype.callback_OnParticipantsChanged = function(e, count) {
if (this.onParticipantsChanged) if (this.onParticipantsChanged) {
this.onParticipantsChanged(e, count); this.onParticipantsChanged(e, count);
}
}; };
CDocsCoApi.prototype.callback_OnMessage = function (e, clear) { CDocsCoApi.prototype.callback_OnMessage = function(e, clear) {
if (this.onMessage) if (this.onMessage) {
this.onMessage(e, clear); this.onMessage(e, clear);
}
}; };
CDocsCoApi.prototype.callback_OnLocksAcquired = function (e) { CDocsCoApi.prototype.callback_OnLocksAcquired = function(e) {
if (this.onLocksAcquired) if (this.onLocksAcquired) {
this.onLocksAcquired(e); this.onLocksAcquired(e);
}
}; };
CDocsCoApi.prototype.callback_OnLocksReleased = function (e, bChanges) { CDocsCoApi.prototype.callback_OnLocksReleased = function(e, bChanges) {
if (this.onLocksReleased) if (this.onLocksReleased) {
this.onLocksReleased(e, bChanges); this.onLocksReleased(e, bChanges);
}
}; };
CDocsCoApi.prototype.callback_OnLocksReleasedEnd = function () { CDocsCoApi.prototype.callback_OnLocksReleasedEnd = function() {
if (this.onLocksReleasedEnd) if (this.onLocksReleasedEnd) {
this.onLocksReleasedEnd(); this.onLocksReleasedEnd();
}
}; };
/** /**
...@@ -223,59 +267,69 @@ ...@@ -223,59 +267,69 @@
* @param {Bool} isDisconnectAtAll окончательно ли отсоединяемся(true) или будем пробовать сделать reconnect(false) + сами отключились * @param {Bool} isDisconnectAtAll окончательно ли отсоединяемся(true) или будем пробовать сделать reconnect(false) + сами отключились
* @param {Bool} isCloseCoAuthoring * @param {Bool} isCloseCoAuthoring
*/ */
CDocsCoApi.prototype.callback_OnDisconnect = function (e, isDisconnectAtAll, isCloseCoAuthoring) { CDocsCoApi.prototype.callback_OnDisconnect = function(e, isDisconnectAtAll, isCloseCoAuthoring) {
if (this.onDisconnect) if (this.onDisconnect) {
this.onDisconnect(e, isDisconnectAtAll, isCloseCoAuthoring); this.onDisconnect(e, isDisconnectAtAll, isCloseCoAuthoring);
}
}; };
CDocsCoApi.prototype.callback_OnFirstLoadChangesEnd = function () { CDocsCoApi.prototype.callback_OnFirstLoadChangesEnd = function() {
if (this.onFirstLoadChangesEnd) if (this.onFirstLoadChangesEnd) {
this.onFirstLoadChangesEnd(); this.onFirstLoadChangesEnd();
}
}; };
CDocsCoApi.prototype.callback_OnConnectionStateChanged = function (e) { CDocsCoApi.prototype.callback_OnConnectionStateChanged = function(e) {
if (this.onConnectionStateChanged) if (this.onConnectionStateChanged) {
this.onConnectionStateChanged(e); this.onConnectionStateChanged(e);
}
}; };
CDocsCoApi.prototype.callback_OnSetIndexUser = function (e) { CDocsCoApi.prototype.callback_OnSetIndexUser = function(e) {
if (this.onSetIndexUser) if (this.onSetIndexUser) {
this.onSetIndexUser(e); this.onSetIndexUser(e);
}
}; };
CDocsCoApi.prototype.callback_OnSaveChanges = function (e, userId, bFirstLoad) { CDocsCoApi.prototype.callback_OnSaveChanges = function(e, userId, bFirstLoad) {
if (this.onSaveChanges) if (this.onSaveChanges) {
this.onSaveChanges(e, userId, bFirstLoad); this.onSaveChanges(e, userId, bFirstLoad);
}
}; };
CDocsCoApi.prototype.callback_OnStartCoAuthoring = function (e) { CDocsCoApi.prototype.callback_OnStartCoAuthoring = function(e) {
if (this.onStartCoAuthoring) if (this.onStartCoAuthoring) {
this.onStartCoAuthoring(e); this.onStartCoAuthoring(e);
}
}; };
CDocsCoApi.prototype.callback_OnEndCoAuthoring = function (e) { CDocsCoApi.prototype.callback_OnEndCoAuthoring = function(e) {
if (this.onEndCoAuthoring) if (this.onEndCoAuthoring) {
this.onEndCoAuthoring(e); this.onEndCoAuthoring(e);
}
}; };
CDocsCoApi.prototype.callback_OnUnSaveLock = function () { CDocsCoApi.prototype.callback_OnUnSaveLock = function() {
if (this.onUnSaveLock) if (this.onUnSaveLock) {
this.onUnSaveLock(); this.onUnSaveLock();
}
}; };
CDocsCoApi.prototype.callback_OnRecalcLocks = function (e) { CDocsCoApi.prototype.callback_OnRecalcLocks = function(e) {
if (this.onRecalcLocks) if (this.onRecalcLocks) {
this.onRecalcLocks(e); this.onRecalcLocks(e);
}
}; };
CDocsCoApi.prototype.callback_OnDocumentOpen = function (e) { CDocsCoApi.prototype.callback_OnDocumentOpen = function(e) {
if (this.onDocumentOpen) if (this.onDocumentOpen) {
this.onDocumentOpen(e); this.onDocumentOpen(e);
}
}; };
function LockBufferElement (arrayBlockId, callback) { function LockBufferElement(arrayBlockId, callback) {
this._arrayBlockId = arrayBlockId; this._arrayBlockId = arrayBlockId;
this._callback = callback; this._callback = callback;
} }
function DocsCoApi (options) { function DocsCoApi(options) {
if (options) { if (options) {
this.onAuthParticipantsChanged = options.onAuthParticipantsChanged; this.onAuthParticipantsChanged = options.onAuthParticipantsChanged;
this.onParticipantsChanged = options.onParticipantsChanged; this.onParticipantsChanged = options.onParticipantsChanged;
...@@ -356,39 +410,39 @@ ...@@ -356,39 +410,39 @@
this._lockBuffer = []; this._lockBuffer = [];
} }
DocsCoApi.prototype.isRightURL = function () { DocsCoApi.prototype.isRightURL = function() {
return ("" != this._url); return ("" != this._url);
}; };
DocsCoApi.prototype.set_url = function (url) { DocsCoApi.prototype.set_url = function(url) {
this._url = url; this._url = url;
}; };
DocsCoApi.prototype.get_state = function () { DocsCoApi.prototype.get_state = function() {
return this._state; return this._state;
}; };
DocsCoApi.prototype.get_indexUser = function () { DocsCoApi.prototype.get_indexUser = function() {
return this._indexUser; return this._indexUser;
}; };
DocsCoApi.prototype.getSessionId = function () { DocsCoApi.prototype.getSessionId = function() {
return this._id; return this._id;
}; };
DocsCoApi.prototype.getUserConnectionId = function () { DocsCoApi.prototype.getUserConnectionId = function() {
return this._userId; return this._userId;
}; };
DocsCoApi.prototype.getUser = function () { DocsCoApi.prototype.getUser = function() {
return this._user; return this._user;
}; };
DocsCoApi.prototype.getLocks = function () { DocsCoApi.prototype.getLocks = function() {
return this._locks; return this._locks;
}; };
DocsCoApi.prototype._sendBufferedLocks = function () { DocsCoApi.prototype._sendBufferedLocks = function() {
var elem; var elem;
for (var i = 0, length = this._lockBuffer.length; i < length; ++i) { for (var i = 0, length = this._lockBuffer.length; i < length; ++i) {
elem = this._lockBuffer[i]; elem = this._lockBuffer[i];
...@@ -397,7 +451,7 @@ ...@@ -397,7 +451,7 @@
this._lockBuffer = []; this._lockBuffer = [];
}; };
DocsCoApi.prototype.askLock = function (arrayBlockId, callback) { DocsCoApi.prototype.askLock = function(arrayBlockId, callback) {
if (ConnectionState.SaveChanges === this._state) { if (ConnectionState.SaveChanges === this._state) {
// Мы в режиме сохранения. Lock-и запросим после окончания. // Мы в режиме сохранения. Lock-и запросим после окончания.
this._lockBuffer.push(new LockBufferElement(arrayBlockId, callback)); this._lockBuffer.push(new LockBufferElement(arrayBlockId, callback));
...@@ -416,8 +470,9 @@ ...@@ -416,8 +470,9 @@
break; break;
} }
} }
if (0 === lengthArray) if (0 === lengthArray) {
isLock = true; isLock = true;
}
idLockInArray = (this._isExcel || this._isPresentation) ? arrayBlockId[0]['guid'] : arrayBlockId[0]; idLockInArray = (this._isExcel || this._isPresentation) ? arrayBlockId[0]['guid'] : arrayBlockId[0];
...@@ -429,7 +484,7 @@ ...@@ -429,7 +484,7 @@
var lockCalbacks = this._lockCallbacks; var lockCalbacks = this._lockCallbacks;
//Set reconnectTimeout //Set reconnectTimeout
window.setTimeout(function () { window.setTimeout(function() {
if (lockCalbacks.hasOwnProperty(idLockInArray)) { if (lockCalbacks.hasOwnProperty(idLockInArray)) {
//Not signaled already //Not signaled already
callback({error: 'Timed out'}); callback({error: 'Timed out'});
...@@ -440,7 +495,7 @@ ...@@ -440,7 +495,7 @@
this._send({"type": 'getLock', 'editorType': this.editorType, 'block': arrayBlockId}); this._send({"type": 'getLock', 'editorType': this.editorType, 'block': arrayBlockId});
} else { } else {
// Вернем ошибку, т.к. залочены элементы // Вернем ошибку, т.к. залочены элементы
window.setTimeout(function () { window.setTimeout(function() {
if (callback && _.isFunction(callback)) { if (callback && _.isFunction(callback)) {
callback({error: idLockInArray + '-lock'}); callback({error: idLockInArray + '-lock'});
} }
...@@ -448,19 +503,20 @@ ...@@ -448,19 +503,20 @@
} }
}; };
DocsCoApi.prototype.askSaveChanges = function (callback) { DocsCoApi.prototype.askSaveChanges = function(callback) {
if (this._saveCallback[this._saveCallback.length - 1]) { if (this._saveCallback[this._saveCallback.length - 1]) {
// Мы еще не отработали старый callback и ждем ответа // Мы еще не отработали старый callback и ждем ответа
return; return;
} }
// Очищаем предыдущий таймер // Очищаем предыдущий таймер
if (null !== this.saveLockCallbackErrorTimeOutId) if (null !== this.saveLockCallbackErrorTimeOutId) {
clearTimeout(this.saveLockCallbackErrorTimeOutId); clearTimeout(this.saveLockCallbackErrorTimeOutId);
}
// Проверим состояние, если мы не подсоединились, то сразу отправим ошибку // Проверим состояние, если мы не подсоединились, то сразу отправим ошибку
if (ConnectionState.Reconnect === this._state) { if (ConnectionState.Reconnect === this._state) {
this.saveLockCallbackErrorTimeOutId = window.setTimeout(function () { this.saveLockCallbackErrorTimeOutId = window.setTimeout(function() {
if (callback && _.isFunction(callback)) { if (callback && _.isFunction(callback)) {
// Фиктивные вызовы // Фиктивные вызовы
callback({error: "No connection"}); callback({error: "No connection"});
...@@ -474,7 +530,7 @@ ...@@ -474,7 +530,7 @@
this._saveCallback[indexCallback] = callback; this._saveCallback[indexCallback] = callback;
//Set reconnectTimeout //Set reconnectTimeout
this.saveLockCallbackErrorTimeOutId = window.setTimeout(function () { this.saveLockCallbackErrorTimeOutId = window.setTimeout(function() {
t.saveLockCallbackErrorTimeOutId = null; t.saveLockCallbackErrorTimeOutId = null;
var oTmpCallback = t._saveCallback[indexCallback]; var oTmpCallback = t._saveCallback[indexCallback];
if (oTmpCallback) { if (oTmpCallback) {
...@@ -487,32 +543,33 @@ ...@@ -487,32 +543,33 @@
this._send({"type": "isSaveLock"}); this._send({"type": "isSaveLock"});
}; };
DocsCoApi.prototype.unSaveLock = function () { DocsCoApi.prototype.unSaveLock = function() {
// ToDo при разрыве соединения нужно перестать делать unSaveLock! // ToDo при разрыве соединения нужно перестать делать unSaveLock!
var t = this; var t = this;
this.unSaveLockCallbackErrorTimeOutId = window.setTimeout(function () { this.unSaveLockCallbackErrorTimeOutId = window.setTimeout(function() {
t.unSaveLockCallbackErrorTimeOutId = null; t.unSaveLockCallbackErrorTimeOutId = null;
t.unSaveLock(); t.unSaveLock();
}, this.errorTimeOut); }, this.errorTimeOut);
this._send({"type": "unSaveLock"}); this._send({"type": "unSaveLock"});
}; };
DocsCoApi.prototype.releaseLocks = function (blockId) { DocsCoApi.prototype.releaseLocks = function(blockId) {
if (this._locks[blockId] && 2 === this._locks[blockId].state /*lock is ours*/) { if (this._locks[blockId] && 2 === this._locks[blockId].state /*lock is ours*/) {
//Ask //Ask
this._locks[blockId] = {"state": 0};//0-released this._locks[blockId] = {"state": 0};//0-released
} }
}; };
DocsCoApi.prototype._reSaveChanges = function () { DocsCoApi.prototype._reSaveChanges = function() {
this.saveChanges(this.arrayChanges, this.currentIndex); this.saveChanges(this.arrayChanges, this.currentIndex);
}; };
DocsCoApi.prototype.saveChanges = function (arrayChanges, currentIndex, deleteIndex, excelAdditionalInfo) { DocsCoApi.prototype.saveChanges = function(arrayChanges, currentIndex, deleteIndex, excelAdditionalInfo) {
if (null === currentIndex) { if (null === currentIndex) {
this.deleteIndex = deleteIndex; this.deleteIndex = deleteIndex;
if (null != this.deleteIndex && -1 !== this.deleteIndex) if (null != this.deleteIndex && -1 !== this.deleteIndex) {
this.deleteIndex += this.changesIndex; this.deleteIndex += this.changesIndex;
}
this.currentIndex = 0; this.currentIndex = 0;
this.arrayChanges = arrayChanges; this.arrayChanges = arrayChanges;
this.excelAdditionalInfo = excelAdditionalInfo; this.excelAdditionalInfo = excelAdditionalInfo;
...@@ -523,14 +580,15 @@ ...@@ -523,14 +580,15 @@
var endIndex = Math.min(this.maxCountSaveChanges * (this.currentIndex + 1), arrayChanges.length); var endIndex = Math.min(this.maxCountSaveChanges * (this.currentIndex + 1), arrayChanges.length);
if (endIndex === arrayChanges.length) { if (endIndex === arrayChanges.length) {
for (var key in this._locks) if (this._locks.hasOwnProperty(key)) { for (var key in this._locks) if (this._locks.hasOwnProperty(key)) {
if (2 === this._locks[key].state /*lock is ours*/) if (2 === this._locks[key].state /*lock is ours*/) {
delete this._locks[key]; delete this._locks[key];
} }
} }
}
//Set errorTimeout //Set errorTimeout
var t = this; var t = this;
this.saveCallbackErrorTimeOutId = window.setTimeout(function () { this.saveCallbackErrorTimeOutId = window.setTimeout(function() {
t.saveCallbackErrorTimeOutId = null; t.saveCallbackErrorTimeOutId = null;
t._reSaveChanges(); t._reSaveChanges();
}, this.errorTimeOutSave); }, this.errorTimeOutSave);
...@@ -544,108 +602,104 @@ ...@@ -544,108 +602,104 @@
'excelAdditionalInfo': this.excelAdditionalInfo ? JSON.stringify(this.excelAdditionalInfo) : null}); 'excelAdditionalInfo': this.excelAdditionalInfo ? JSON.stringify(this.excelAdditionalInfo) : null});
}; };
DocsCoApi.prototype.unLockDocument = function (isSave) { DocsCoApi.prototype.unLockDocument = function(isSave) {
this._send({'type': 'unLockDocument', 'isSave' : isSave}); this._send({'type': 'unLockDocument', 'isSave': isSave});
}; };
DocsCoApi.prototype.getUsers = function () { DocsCoApi.prototype.getUsers = function() {
// Специально для возможности получения после прохождения авторизации (Стоит переделать) // Специально для возможности получения после прохождения авторизации (Стоит переделать)
if (this.onAuthParticipantsChanged) if (this.onAuthParticipantsChanged) {
this.onAuthParticipantsChanged(this._participants, this._countUsers); this.onAuthParticipantsChanged(this._participants, this._countUsers);
}
}; };
DocsCoApi.prototype.getUser = function (userId) { DocsCoApi.prototype.getUser = function(userId) {
return this._participants[userId]; return this._participants[userId];
}; };
DocsCoApi.prototype.disconnect = function () { DocsCoApi.prototype.disconnect = function() {
// Отключаемся сами // Отключаемся сами
this.isCloseCoAuthoring = true; this.isCloseCoAuthoring = true;
return this.sockjs.close(); return this.sockjs.close();
}; };
DocsCoApi.prototype.openDocument = function (data) { DocsCoApi.prototype.openDocument = function(data) {
this._send({"type": "openDocument", "message": data}); this._send({"type": "openDocument", "message": data});
}; };
DocsCoApi.prototype.sendRawData = function (data) { DocsCoApi.prototype.sendRawData = function(data) {
this._sendRaw(data); this._sendRaw(data);
}; };
DocsCoApi.prototype.getMessages = function () { DocsCoApi.prototype.getMessages = function() {
this._send({"type": "getMessages"}); this._send({"type": "getMessages"});
}; };
DocsCoApi.prototype.sendMessage = function (message) { DocsCoApi.prototype.sendMessage = function(message) {
if (typeof message === 'string') { if (typeof message === 'string') {
this._send({"type": "message", "message": message}); this._send({"type": "message", "message": message});
} }
}; };
DocsCoApi.prototype.ping = function () { DocsCoApi.prototype.ping = function() {
this._send({"type": "ping"}); this._send({"type": "ping"});
}; };
DocsCoApi.prototype._sendPrebuffered = function () { DocsCoApi.prototype._sendPrebuffered = function() {
for (var i = 0; i < this._msgBuffer.length; i++) { for (var i = 0; i < this._msgBuffer.length; i++) {
this._sendRaw(this._msgBuffer[i]); this._sendRaw(this._msgBuffer[i]);
} }
this._msgBuffer = []; this._msgBuffer = [];
}; };
DocsCoApi.prototype._send = function (data) { DocsCoApi.prototype._send = function(data) {
if (data !== null && typeof data === "object") { if (data !== null && typeof data === "object") {
if (this._state > 0) if (this._state > 0) {
this.sockjs.send(JSON.stringify(data)); this.sockjs.send(JSON.stringify(data));
else } else {
this._msgBuffer.push(JSON.stringify(data)); this._msgBuffer.push(JSON.stringify(data));
} }
}
}; };
DocsCoApi.prototype._sendRaw = function (data) { DocsCoApi.prototype._sendRaw = function(data) {
if (data !== null && typeof data === "string") { if (data !== null && typeof data === "string") {
if (this._state > 0) if (this._state > 0) {
this.sockjs.send(data); this.sockjs.send(data);
else } else {
this._msgBuffer.push(data); this._msgBuffer.push(data);
} }
}
}; };
DocsCoApi.prototype._onMessages = function (data, clear) { DocsCoApi.prototype._onMessages = function(data, clear) {
if (data["messages"] && this.onMessage) if (data["messages"] && this.onMessage) {
this.onMessage(data["messages"], clear); this.onMessage(data["messages"], clear);
}
}; };
DocsCoApi.prototype._onGetLock = function (data) { DocsCoApi.prototype._onGetLock = function(data) {
if (data["locks"]) { if (data["locks"]) {
for (var key in data["locks"]) { for (var key in data["locks"]) {
if (data["locks"].hasOwnProperty(key)) { if (data["locks"].hasOwnProperty(key)) {
var lock = data["locks"][key], var lock = data["locks"][key], blockTmp = (this._isExcel || this._isPresentation) ? lock["block"]["guid"] : key, blockValue = (this._isExcel || this._isPresentation) ? lock["block"] : key;
blockTmp = (this._isExcel || this._isPresentation) ? lock["block"]["guid"] : key,
blockValue = (this._isExcel || this._isPresentation) ? lock["block"] : key;
if (lock !== null) { if (lock !== null) {
var changed = true; var changed = true;
if (this._locks[blockTmp] && 1 !== this._locks[blockTmp].state /*asked for it*/) { if (this._locks[blockTmp] && 1 !== this._locks[blockTmp].state /*asked for it*/) {
//Exists //Exists
//Check lock state //Check lock state
changed = !(this._locks[blockTmp].state === (lock["sessionId"] === this._id ? 2 : 3) && changed = !(this._locks[blockTmp].state === (lock["sessionId"] === this._id ? 2 : 3) && this._locks[blockTmp]["user"] === lock["user"] && this._locks[blockTmp]["time"] === lock["time"] && this._locks[blockTmp]["block"] === blockTmp);
this._locks[blockTmp]["user"] === lock["user"] &&
this._locks[blockTmp]["time"] === lock["time"] &&
this._locks[blockTmp]["block"] === blockTmp);
} }
if (changed) { if (changed) {
this._locks[blockTmp] = {"state":lock["sessionId"] === this._id ? 2 : 3, "user":lock["user"], "time":lock["time"], "block": blockTmp, "blockValue": blockValue};//2-acquired by me! this._locks[blockTmp] = {"state": lock["sessionId"] === this._id ? 2 : 3, "user": lock["user"], "time": lock["time"], "block": blockTmp, "blockValue": blockValue};//2-acquired by me!
} }
if (this._lockCallbacks.hasOwnProperty(blockTmp) && if (this._lockCallbacks.hasOwnProperty(blockTmp) && this._lockCallbacks[blockTmp] !== null && _.isFunction(this._lockCallbacks[blockTmp])) {
this._lockCallbacks[blockTmp] !== null &&
_.isFunction(this._lockCallbacks[blockTmp])) {
if (lock["sessionId"] === this._id) { if (lock["sessionId"] === this._id) {
//Do call back //Do call back
this._lockCallbacks[blockTmp]({"lock":this._locks[blockTmp]}); this._lockCallbacks[blockTmp]({"lock": this._locks[blockTmp]});
} } else {
else { this._lockCallbacks[blockTmp]({"error": "Already locked by " + lock["user"]});
this._lockCallbacks[blockTmp]({"error":"Already locked by " + lock["user"]});
} }
delete this._lockCallbacks[blockTmp]; delete this._lockCallbacks[blockTmp];
} }
...@@ -658,15 +712,14 @@ ...@@ -658,15 +712,14 @@
} }
}; };
DocsCoApi.prototype._onReleaseLock = function (data) { DocsCoApi.prototype._onReleaseLock = function(data) {
if (data["locks"]) { if (data["locks"]) {
var bSendEnd = false; var bSendEnd = false;
for (var block in data["locks"]) { for (var block in data["locks"]) {
if (data["locks"].hasOwnProperty(block)) { if (data["locks"].hasOwnProperty(block)) {
var lock = data["locks"][block], var lock = data["locks"][block], blockTmp = (this._isExcel || this._isPresentation) ? lock["block"]["guid"] : lock["block"];
blockTmp = (this._isExcel || this._isPresentation) ? lock["block"]["guid"] : lock["block"];
if (lock !== null) { if (lock !== null) {
this._locks[blockTmp] = {"state":0, "user":lock["user"], "time":lock["time"], "changes":lock["changes"], "block":lock["block"]}; this._locks[blockTmp] = {"state": 0, "user": lock["user"], "time": lock["time"], "changes": lock["changes"], "block": lock["block"]};
if (this.onLocksReleased) { if (this.onLocksReleased) {
// false - user not save changes // false - user not save changes
this.onLocksReleased(this._locks[blockTmp], false); this.onLocksReleased(this._locks[blockTmp], false);
...@@ -675,24 +728,24 @@ ...@@ -675,24 +728,24 @@
} }
} }
} }
if (bSendEnd && this.onLocksReleasedEnd) if (bSendEnd && this.onLocksReleasedEnd) {
this.onLocksReleasedEnd(); this.onLocksReleasedEnd();
} }
}
}; };
DocsCoApi.prototype._documentOpen = function (data) { DocsCoApi.prototype._documentOpen = function(data) {
this.onDocumentOpen(data); this.onDocumentOpen(data);
}; };
DocsCoApi.prototype._onSaveChanges = function (data) { DocsCoApi.prototype._onSaveChanges = function(data) {
if (data["locks"]) { if (data["locks"]) {
var bSendEnd = false; var bSendEnd = false;
for (var block in data["locks"]) { for (var block in data["locks"]) {
if (data["locks"].hasOwnProperty(block)) { if (data["locks"].hasOwnProperty(block)) {
var lock = data["locks"][block], var lock = data["locks"][block], blockTmp = (this._isExcel || this._isPresentation) ? lock["block"]["guid"] : lock["block"];
blockTmp = (this._isExcel || this._isPresentation) ? lock["block"]["guid"] : lock["block"];
if (lock !== null) { if (lock !== null) {
this._locks[blockTmp] = {"state":0, "user":lock["user"], "time":lock["time"], "changes":lock["changes"], "block":lock["block"]}; this._locks[blockTmp] = {"state": 0, "user": lock["user"], "time": lock["time"], "changes": lock["changes"], "block": lock["block"]};
if (this.onLocksReleased) { if (this.onLocksReleased) {
// true - lock with save // true - lock with save
this.onLocksReleased(this._locks[blockTmp], true); this.onLocksReleased(this._locks[blockTmp], true);
...@@ -701,15 +754,17 @@ ...@@ -701,15 +754,17 @@
} }
} }
} }
if (bSendEnd && this.onLocksReleasedEnd) if (bSendEnd && this.onLocksReleasedEnd) {
this.onLocksReleasedEnd(); this.onLocksReleasedEnd();
} }
}
this._updateChanges(data["changes"], data["changesIndex"], false); this._updateChanges(data["changes"], data["changesIndex"], false);
if (this.onRecalcLocks) if (this.onRecalcLocks) {
this.onRecalcLocks(data["excelAdditionalInfo"]); this.onRecalcLocks(data["excelAdditionalInfo"]);
}
}; };
DocsCoApi.prototype._onStartCoAuthoring = function (isStartEvent) { DocsCoApi.prototype._onStartCoAuthoring = function(isStartEvent) {
if (false === this.isCoAuthoring) { if (false === this.isCoAuthoring) {
this.isCoAuthoring = true; this.isCoAuthoring = true;
if (this.onStartCoAuthoring) { if (this.onStartCoAuthoring) {
...@@ -718,7 +773,7 @@ ...@@ -718,7 +773,7 @@
} }
}; };
DocsCoApi.prototype._onEndCoAuthoring = function (isStartEvent) { DocsCoApi.prototype._onEndCoAuthoring = function(isStartEvent) {
if (true === this.isCoAuthoring) { if (true === this.isCoAuthoring) {
this.isCoAuthoring = false; this.isCoAuthoring = false;
if (this.onEndCoAuthoring) { if (this.onEndCoAuthoring) {
...@@ -727,14 +782,15 @@ ...@@ -727,14 +782,15 @@
} }
}; };
DocsCoApi.prototype._onSaveLock = function (data) { DocsCoApi.prototype._onSaveLock = function(data) {
if (undefined != data["saveLock"] && null != data["saveLock"]) { if (undefined != data["saveLock"] && null != data["saveLock"]) {
var indexCallback = this._saveCallback.length - 1; var indexCallback = this._saveCallback.length - 1;
var oTmpCallback = this._saveCallback[indexCallback]; var oTmpCallback = this._saveCallback[indexCallback];
if (oTmpCallback) { if (oTmpCallback) {
// Очищаем предыдущий таймер // Очищаем предыдущий таймер
if (null !== this.saveLockCallbackErrorTimeOutId) if (null !== this.saveLockCallbackErrorTimeOutId) {
clearTimeout(this.saveLockCallbackErrorTimeOutId); clearTimeout(this.saveLockCallbackErrorTimeOutId);
}
this._saveCallback[indexCallback] = null; this._saveCallback[indexCallback] = null;
oTmpCallback(data); oTmpCallback(data);
...@@ -742,13 +798,15 @@ ...@@ -742,13 +798,15 @@
} }
}; };
DocsCoApi.prototype._onUnSaveLock = function (data) { DocsCoApi.prototype._onUnSaveLock = function(data) {
// Очищаем предыдущий таймер сохранения // Очищаем предыдущий таймер сохранения
if (null !== this.saveCallbackErrorTimeOutId) if (null !== this.saveCallbackErrorTimeOutId) {
clearTimeout(this.saveCallbackErrorTimeOutId); clearTimeout(this.saveCallbackErrorTimeOutId);
}
// Очищаем предыдущий таймер снятия блокировки // Очищаем предыдущий таймер снятия блокировки
if (null !== this.unSaveLockCallbackErrorTimeOutId) if (null !== this.unSaveLockCallbackErrorTimeOutId) {
clearTimeout(this.unSaveLockCallbackErrorTimeOutId); clearTimeout(this.unSaveLockCallbackErrorTimeOutId);
}
// Возвращаем состояние // Возвращаем состояние
this._state = ConnectionState.Authorized; this._state = ConnectionState.Authorized;
...@@ -756,14 +814,16 @@ ...@@ -756,14 +814,16 @@
// Делаем отложенные lock-и // Делаем отложенные lock-и
this._sendBufferedLocks(); this._sendBufferedLocks();
if (-1 !== data['index']) if (-1 !== data['index']) {
this.changesIndex = data['index']; this.changesIndex = data['index'];
}
if (this.onUnSaveLock) if (this.onUnSaveLock) {
this.onUnSaveLock(); this.onUnSaveLock();
}
}; };
DocsCoApi.prototype._updateChanges = function (allServerChanges, changesIndex, bFirstLoad) { DocsCoApi.prototype._updateChanges = function(allServerChanges, changesIndex, bFirstLoad) {
if (this.onSaveChanges) { if (this.onSaveChanges) {
this.changesIndex = changesIndex; this.changesIndex = changesIndex;
if (allServerChanges) { if (allServerChanges) {
...@@ -771,8 +831,9 @@ ...@@ -771,8 +831,9 @@
var change = allServerChanges[i]; var change = allServerChanges[i];
var changesOneUser = change['change']; var changesOneUser = change['change'];
if (changesOneUser) { if (changesOneUser) {
if (change['user'] !== this._userId) if (change['user'] !== this._userId) {
this.lastOtherSaveTime = change['time']; this.lastOtherSaveTime = change['time'];
}
this.onSaveChanges(JSON.parse(changesOneUser), change['user'], bFirstLoad); this.onSaveChanges(JSON.parse(changesOneUser), change['user'], bFirstLoad);
} }
} }
...@@ -780,31 +841,34 @@ ...@@ -780,31 +841,34 @@
} }
}; };
DocsCoApi.prototype._onSetIndexUser = function (data) { DocsCoApi.prototype._onSetIndexUser = function(data) {
if (this.onSetIndexUser) if (this.onSetIndexUser) {
this.onSetIndexUser(data); this.onSetIndexUser(data);
}
}; };
DocsCoApi.prototype._onSavePartChanges = function (data) { DocsCoApi.prototype._onSavePartChanges = function(data) {
// Очищаем предыдущий таймер // Очищаем предыдущий таймер
if (null !== this.saveCallbackErrorTimeOutId) if (null !== this.saveCallbackErrorTimeOutId) {
clearTimeout(this.saveCallbackErrorTimeOutId); clearTimeout(this.saveCallbackErrorTimeOutId);
}
if (-1 !== data['changesIndex']) if (-1 !== data['changesIndex']) {
this.changesIndex = data['changesIndex']; this.changesIndex = data['changesIndex'];
}
this.saveChanges(this.arrayChanges, this.currentIndex + 1); this.saveChanges(this.arrayChanges, this.currentIndex + 1);
}; };
DocsCoApi.prototype._onPreviousLocks = function (locks, previousLocks) { DocsCoApi.prototype._onPreviousLocks = function(locks, previousLocks) {
var i=0; var i = 0;
if (locks && previousLocks) { if (locks && previousLocks) {
for (var block in locks) { for (var block in locks) {
if (locks.hasOwnProperty(block)) { if (locks.hasOwnProperty(block)) {
var lock = locks[block]; var lock = locks[block];
if (lock !== null && lock["block"]) { if (lock !== null && lock["block"]) {
//Find in previous //Find in previous
for (i=0; i < previousLocks.length; i++) { for (i = 0; i < previousLocks.length; i++) {
if (previousLocks[i] === lock["block"] && lock["sessionId"] === this._id) { if (previousLocks[i] === lock["block"] && lock["sessionId"] === this._id) {
//Lock is ours //Lock is ours
previousLocks.remove(i); previousLocks.remove(i);
...@@ -814,14 +878,14 @@ ...@@ -814,14 +878,14 @@
} }
} }
} }
if (previousLocks.length>0 && this.onRelockFailed) { if (previousLocks.length > 0 && this.onRelockFailed) {
this.onRelockFailed(previousLocks); this.onRelockFailed(previousLocks);
} }
previousLocks=[]; previousLocks = [];
} }
}; };
DocsCoApi.prototype._onAuthParticipantsChanged = function (participants) { DocsCoApi.prototype._onAuthParticipantsChanged = function(participants) {
this._participants = {}; this._participants = {};
this._countEditUsers = 0; this._countEditUsers = 0;
this._countUsers = 0; this._countUsers = 0;
...@@ -832,23 +896,26 @@ ...@@ -832,23 +896,26 @@
tmpUser = new asc.asc_CUser(participants[i]); tmpUser = new asc.asc_CUser(participants[i]);
this._participants[tmpUser.asc_getId()] = tmpUser; this._participants[tmpUser.asc_getId()] = tmpUser;
// Считаем только число редакторов // Считаем только число редакторов
if (!tmpUser.asc_getView()) if (!tmpUser.asc_getView()) {
++this._countEditUsers; ++this._countEditUsers;
}
++this._countUsers; ++this._countUsers;
} }
if (this.onAuthParticipantsChanged) if (this.onAuthParticipantsChanged) {
this.onAuthParticipantsChanged(this._participants, this._countUsers); this.onAuthParticipantsChanged(this._participants, this._countUsers);
}
// Посылаем эвент о совместном редактировании // Посылаем эвент о совместном редактировании
if (1 < this._countEditUsers) if (1 < this._countEditUsers) {
this._onStartCoAuthoring(/*isStartEvent*/true); this._onStartCoAuthoring(/*isStartEvent*/true);
else } else {
this._onEndCoAuthoring(/*isStartEvent*/true); this._onEndCoAuthoring(/*isStartEvent*/true);
} }
}
}; };
DocsCoApi.prototype._onConnectionStateChanged = function (data) { DocsCoApi.prototype._onConnectionStateChanged = function(data) {
var userStateChanged = null, userId, stateChanged = false, isEditUser = true; var userStateChanged = null, userId, stateChanged = false, isEditUser = true;
if (undefined !== data["state"] && this.onConnectionStateChanged) { if (undefined !== data["state"] && this.onConnectionStateChanged) {
userStateChanged = new asc.asc_CUser(data); userStateChanged = new asc.asc_CUser(data);
...@@ -858,23 +925,26 @@ ...@@ -858,23 +925,26 @@
if (userStateChanged.asc_getState()) { if (userStateChanged.asc_getState()) {
this._participants[userId] = userStateChanged; this._participants[userId] = userStateChanged;
++this._countUsers; ++this._countUsers;
if (isEditUser) if (isEditUser) {
++this._countEditUsers; ++this._countEditUsers;
}
stateChanged = true; stateChanged = true;
} else if (this._participants.hasOwnProperty(userId)){ } else if (this._participants.hasOwnProperty(userId)) {
delete this._participants[userId]; delete this._participants[userId];
--this._countUsers; --this._countUsers;
if (isEditUser) if (isEditUser) {
--this._countEditUsers; --this._countEditUsers;
}
stateChanged = true; stateChanged = true;
} }
if (stateChanged) { if (stateChanged) {
// Посылаем эвент о совместном редактировании // Посылаем эвент о совместном редактировании
if (1 < this._countEditUsers) if (1 < this._countEditUsers) {
this._onStartCoAuthoring(/*isStartEvent*/false); this._onStartCoAuthoring(/*isStartEvent*/false);
else } else {
this._onEndCoAuthoring(/*isStartEvent*/false); this._onEndCoAuthoring(/*isStartEvent*/false);
}
this.onParticipantsChanged(this._participants, this._countUsers); this.onParticipantsChanged(this._participants, this._countUsers);
this.onConnectionStateChanged(userStateChanged); this.onConnectionStateChanged(userStateChanged);
...@@ -882,12 +952,12 @@ ...@@ -882,12 +952,12 @@
} }
}; };
DocsCoApi.prototype._onDrop = function (data) { DocsCoApi.prototype._onDrop = function(data) {
this.disconnect(); this.disconnect();
this.onDisconnect(data ? data['description'] : '', true, this.isCloseCoAuthoring); this.onDisconnect(data ? data['description'] : '', true, this.isCloseCoAuthoring);
}; };
DocsCoApi.prototype._onAuth = function (data) { DocsCoApi.prototype._onAuth = function(data) {
var t = this; var t = this;
if (true === this._isAuth) { if (true === this._isAuth) {
this._state = ConnectionState.Authorized; this._state = ConnectionState.Authorized;
...@@ -901,11 +971,11 @@ ...@@ -901,11 +971,11 @@
this._onGetLock(data); this._onGetLock(data);
if (this._isReSaveAfterAuth) { if (this._isReSaveAfterAuth) {
var callbackAskSaveChanges = function (e) { var callbackAskSaveChanges = function(e) {
if (false == e["saveLock"]) { if (false == e["saveLock"]) {
t._reSaveChanges(); t._reSaveChanges();
} else { } else {
setTimeout(function () { setTimeout(function() {
t.askSaveChanges(callbackAskSaveChanges); t.askSaveChanges(callbackAskSaveChanges);
}, 1000); }, 1000);
} }
...@@ -942,19 +1012,20 @@ ...@@ -942,19 +1012,20 @@
} }
this._updateChanges(data["changes"], data["changesIndex"], true); this._updateChanges(data["changes"], data["changesIndex"], true);
// Посылать нужно всегда, т.к. на это рассчитываем при открытии // Посылать нужно всегда, т.к. на это рассчитываем при открытии
if (this.onFirstLoadChangesEnd) if (this.onFirstLoadChangesEnd) {
this.onFirstLoadChangesEnd(); this.onFirstLoadChangesEnd();
}
//Send prebuffered //Send prebuffered
this._sendPrebuffered(); this._sendPrebuffered();
} }
//TODO: Add errors //TODO: Add errors
if (this._initCallback) { if (this._initCallback) {
this._initCallback({result:data["result"]}); this._initCallback({result: data["result"]});
} }
//ping //ping
var fPing = function(){ var fPing = function() {
setTimeout(function () { setTimeout(function() {
t.ping(); t.ping();
fPing(); fPing();
}, 60000); }, 60000);
...@@ -962,14 +1033,14 @@ ...@@ -962,14 +1033,14 @@
fPing(); fPing();
}; };
DocsCoApi.prototype.init = function (user, docid, documentCallbackUrl, token, callback, editorType, documentFormatSave, isViewer) { DocsCoApi.prototype.init = function(user, docid, documentCallbackUrl, token, callback, editorType, documentFormatSave, isViewer) {
this._user = user; this._user = user;
this._docid = docid; this._docid = docid;
this._documentCallbackUrl = documentCallbackUrl; this._documentCallbackUrl = documentCallbackUrl;
this._token = token; this._token = token;
this._initCallback = callback; this._initCallback = callback;
this.ownedLockBlocks = []; this.ownedLockBlocks = [];
this.sockjs_url = '/doc/'+docid+'/c'; this.sockjs_url = '/doc/' + docid + '/c';
this.editorType = editorType; this.editorType = editorType;
this._isExcel = c_oEditorId.Spreadsheet === editorType; this._isExcel = c_oEditorId.Spreadsheet === editorType;
this._isPresentation = c_oEditorId.Presentation === editorType; this._isPresentation = c_oEditorId.Presentation === editorType;
...@@ -980,11 +1051,11 @@ ...@@ -980,11 +1051,11 @@
this._initSocksJs(); this._initSocksJs();
}; };
DocsCoApi.prototype._initSocksJs = function () { DocsCoApi.prototype._initSocksJs = function() {
var t = this; var t = this;
var sockjs = this.sockjs = new SockJS(this.sockjs_url, null, {debug: true}); var sockjs = this.sockjs = new SockJS(this.sockjs_url, null, {debug: true});
sockjs.onopen = function () { sockjs.onopen = function() {
if (t.reconnectTimeout) { if (t.reconnectTimeout) {
clearTimeout(t.reconnectTimeout); clearTimeout(t.reconnectTimeout);
t.attemptCount = 0; t.attemptCount = 0;
...@@ -1006,65 +1077,93 @@ ...@@ -1006,65 +1077,93 @@
} }
t._locks = {}; t._locks = {};
} }
t._send( t._send({
{ 'type': 'auth',
'type' : 'auth', 'docid': t._docid,
'docid' : t._docid, 'documentCallbackUrl': t._documentCallbackUrl,
'documentCallbackUrl' : t._documentCallbackUrl, 'token': t._token,
'token' : t._token, 'user': {
'user' : { 'id': t._user.asc_getId(),
'id' : t._user.asc_getId(), 'name': t._user.asc_getUserName(),
'name' : t._user.asc_getUserName(), 'indexUser': t._indexUser
'indexUser' : t._indexUser
}, },
'editorType': t.editorType, 'editorType': t.editorType,
'lastOtherSaveTime' : t.lastOtherSaveTime, 'lastOtherSaveTime': t.lastOtherSaveTime,
'block' : t.ownedLockBlocks, 'block': t.ownedLockBlocks,
'sessionId' : t._id, 'sessionId': t._id,
//'server' : window.location.protocol + '//' + window.location.host + g_sMainServiceLocalUrl, //'server' : window.location.protocol + '//' + window.location.host + g_sMainServiceLocalUrl,
'documentFormatSave' : t._documentFormatSave, 'documentFormatSave': t._documentFormatSave,
'isViewer' : t._isViewer, 'isViewer': t._isViewer,
'version' : asc_coAuthV 'version': asc_coAuthV
}); });
}; };
sockjs.onmessage = function (e) { sockjs.onmessage = function(e) {
//TODO: add checks and error handling //TODO: add checks and error handling
//Get data type //Get data type
var dataObject = JSON.parse(e.data); var dataObject = JSON.parse(e.data);
var type = dataObject.type; var type = dataObject.type;
switch (type) { switch (type) {
case 'auth' : t._onAuth(dataObject); break; case 'auth' :
case 'message' : t._onMessages(dataObject, false); break; t._onAuth(dataObject);
case 'getLock' : t._onGetLock(dataObject); break; break;
case 'releaseLock' : t._onReleaseLock(dataObject); break; case 'message' :
case 'connectState' : t._onConnectionStateChanged(dataObject); break; t._onMessages(dataObject, false);
case 'saveChanges' : t._onSaveChanges(dataObject); break; break;
case 'saveLock' : t._onSaveLock(dataObject); break; case 'getLock' :
case 'unSaveLock' : t._onUnSaveLock(dataObject); break; t._onGetLock(dataObject);
case 'savePartChanges' : t._onSavePartChanges(dataObject); break; break;
case 'drop' : t._onDrop(dataObject); break; case 'releaseLock' :
case 'waitAuth' : /*Ждем, когда придет auth, документ залочен*/break; t._onReleaseLock(dataObject);
case 'error' : /*Старая версия sdk*/t._onDrop(dataObject); break; break;
case 'documentOpen' : t._documentOpen(dataObject); break; case 'connectState' :
} t._onConnectionStateChanged(dataObject);
}; break;
sockjs.onclose = function (evt) { case 'saveChanges' :
t._onSaveChanges(dataObject);
break;
case 'saveLock' :
t._onSaveLock(dataObject);
break;
case 'unSaveLock' :
t._onUnSaveLock(dataObject);
break;
case 'savePartChanges' :
t._onSavePartChanges(dataObject);
break;
case 'drop' :
t._onDrop(dataObject);
break;
case 'waitAuth' : /*Ждем, когда придет auth, документ залочен*/
break;
case 'error' : /*Старая версия sdk*/
t._onDrop(dataObject);
break;
case 'documentOpen' :
t._documentOpen(dataObject);
break;
}
};
sockjs.onclose = function(evt) {
if (ConnectionState.SaveChanges === t._state) { if (ConnectionState.SaveChanges === t._state) {
// Мы сохраняли изменения и разорвалось соединение // Мы сохраняли изменения и разорвалось соединение
t._isReSaveAfterAuth = true; t._isReSaveAfterAuth = true;
// Очищаем предыдущий таймер // Очищаем предыдущий таймер
if (null !== t.saveCallbackErrorTimeOutId) if (null !== t.saveCallbackErrorTimeOutId) {
clearTimeout(t.saveCallbackErrorTimeOutId); clearTimeout(t.saveCallbackErrorTimeOutId);
} }
}
t._state = ConnectionState.Reconnect; t._state = ConnectionState.Reconnect;
var bIsDisconnectAtAll = t.attemptCount >= t.maxAttemptCount || t.isCloseCoAuthoring; var bIsDisconnectAtAll = t.attemptCount >= t.maxAttemptCount || t.isCloseCoAuthoring;
if (bIsDisconnectAtAll) if (bIsDisconnectAtAll) {
t._state = ConnectionState.Closed; t._state = ConnectionState.Closed;
if (t.isCloseCoAuthoring) }
if (t.isCloseCoAuthoring) {
return; return;
if (t.onDisconnect) }
if (t.onDisconnect) {
t.onDisconnect(evt.reason, bIsDisconnectAtAll, t.isCloseCoAuthoring); t.onDisconnect(evt.reason, bIsDisconnectAtAll, t.isCloseCoAuthoring);
}
//Try reconect //Try reconect
if (t.attemptCount < t.maxAttemptCount) { if (t.attemptCount < t.maxAttemptCount) {
t._tryReconnect(); t._tryReconnect();
...@@ -1074,13 +1173,13 @@ ...@@ -1074,13 +1173,13 @@
return sockjs; return sockjs;
}; };
DocsCoApi.prototype._tryReconnect = function () { DocsCoApi.prototype._tryReconnect = function() {
var t = this; var t = this;
if (this.reconnectTimeout) { if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout); clearTimeout(this.reconnectTimeout);
} }
++this.attemptCount; ++this.attemptCount;
this.reconnectTimeout = setTimeout(function () { this.reconnectTimeout = setTimeout(function() {
delete t.sockjs; delete t.sockjs;
t._initSocksJs(); t._initSocksJs();
}, this.reconnectInterval); }, this.reconnectInterval);
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment