etherpad-lite/src/static/js/collab_client.js

686 lines
17 KiB
JavaScript
Raw Normal View History

/**
* This code is mostly from the old Etherpad. Please help us to comment this code.
* This helps other people to understand this code better and helps them to improve it.
* TL;DR COMMENTS ON THIS FILE ARE HIGHLY APPRECIATED
*/
2011-03-26 14:10:41 +01:00
/**
* Copyright 2009 Google Inc.
2011-07-07 19:59:34 +02:00
*
2011-03-26 14:10:41 +01:00
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
2011-07-07 19:59:34 +02:00
*
2011-03-26 14:10:41 +01:00
* http://www.apache.org/licenses/LICENSE-2.0
2011-07-07 19:59:34 +02:00
*
2011-03-26 14:10:41 +01:00
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
2012-03-07 02:27:03 +01:00
var chat = require('./chat').chat;
var hooks = require('./pluginfw/hooks');
2012-01-16 05:16:11 +01:00
// Dependency fill on init. This exists for `pad.socket` only.
// TODO: bind directly to the socket.
var pad = undefined;
function getSocket() {
return pad && pad.socket;
}
2011-03-26 14:10:41 +01:00
/** Call this when the document is ready, and a new Ace2Editor() has been created and inited.
ACE's ready callback does not need to have fired yet.
"serverVars" are from calling doc.getCollabClientVars() on the server. */
function getCollabClient(ace2editor, serverVars, initialUserInfo, options, _pad)
2011-07-07 19:59:34 +02:00
{
2011-03-26 14:10:41 +01:00
var editor = ace2editor;
pad = _pad; // Inject pad to avoid a circular dependency.
2011-03-26 14:10:41 +01:00
var rev = serverVars.rev;
var padId = serverVars.padId;
var globalPadId = serverVars.globalPadId;
var state = "IDLE";
var stateMessage;
var stateMessageSocketId;
var channelState = "CONNECTING";
var appLevelDisconnectReason = null;
var lastCommitTime = 0;
var initialStartConnectTime = 0;
var userId = initialUserInfo.userId;
var socketId;
//var socket;
var userSet = {}; // userId -> userInfo
userSet[userId] = initialUserInfo;
var reconnectTimes = [];
var caughtErrors = [];
var caughtErrorCatchers = [];
var caughtErrorTimes = [];
var debugMessages = [];
var msgQueue = [];
2011-03-26 14:10:41 +01:00
tellAceAboutHistoricalAuthors(serverVars.historicalAuthorData);
tellAceActiveAuthorInfo(initialUserInfo);
var callbacks = {
2011-07-07 19:59:34 +02:00
onUserJoin: function()
{},
onUserLeave: function()
{},
onUpdateUserInfo: function()
{},
onChannelStateChange: function()
{},
onClientMessage: function()
{},
onInternalAction: function()
{},
onConnectionTrouble: function()
{},
onServerMessage: function()
{}
2011-03-26 14:10:41 +01:00
};
2011-07-07 19:59:34 +02:00
if ($.browser.mozilla)
{
2011-03-26 14:10:41 +01:00
// Prevent "escape" from taking effect and canceling a comet connection;
// doesn't work if focus is on an iframe.
2011-07-07 19:59:34 +02:00
$(window).bind("keydown", function(evt)
{
if (evt.which == 27)
{
evt.preventDefault()
}
});
2011-03-26 14:10:41 +01:00
}
editor.setProperty("userAuthor", userId);
editor.setBaseAttributedText(serverVars.initialAttributedText, serverVars.apool);
editor.setUserChangeNotificationCallback(wrapRecordingErrors("handleUserChanges", handleUserChanges));
2011-07-07 19:59:34 +02:00
function dmesg(str)
{
if (typeof window.ajlog == "string") window.ajlog += str + '\n';
2011-03-26 14:10:41 +01:00
debugMessages.push(str);
}
2011-07-07 19:59:34 +02:00
function handleUserChanges()
{
if (editor.getInInternationalComposition()) return;
if ((!getSocket()) || channelState == "CONNECTING")
2011-07-07 19:59:34 +02:00
{
if (channelState == "CONNECTING" && (((+new Date()) - initialStartConnectTime) > 20000))
{
setChannelState("DISCONNECTED", "initsocketfail");
2011-03-26 14:10:41 +01:00
}
2011-07-07 19:59:34 +02:00
else
{
2011-03-26 14:10:41 +01:00
// check again in a bit
2011-07-07 19:59:34 +02:00
setTimeout(wrapRecordingErrors("setTimeout(handleUserChanges)", handleUserChanges), 1000);
2011-03-26 14:10:41 +01:00
}
return;
}
var t = (+new Date());
2011-07-07 19:59:34 +02:00
if (state != "IDLE")
{
if (state == "COMMITTING" && msgQueue.length == 0 && (t - lastCommitTime) > 20000)
2011-07-07 19:59:34 +02:00
{
2011-03-26 14:10:41 +01:00
// a commit is taking too long
setChannelState("DISCONNECTED", "slowcommit");
2011-03-26 14:10:41 +01:00
}
else if (state == "COMMITTING" && msgQueue.length == 0 && (t - lastCommitTime) > 5000)
2011-07-07 19:59:34 +02:00
{
2011-03-26 14:10:41 +01:00
callbacks.onConnectionTrouble("SLOW");
}
2011-07-07 19:59:34 +02:00
else
{
2011-03-26 14:10:41 +01:00
// run again in a few seconds, to detect a disconnect
2011-07-07 19:59:34 +02:00
setTimeout(wrapRecordingErrors("setTimeout(handleUserChanges)", handleUserChanges), 3000);
2011-03-26 14:10:41 +01:00
}
return;
}
var earliestCommit = lastCommitTime + 500;
2011-07-07 19:59:34 +02:00
if (t < earliestCommit)
{
setTimeout(wrapRecordingErrors("setTimeout(handleUserChanges)", handleUserChanges), earliestCommit - t);
2011-03-26 14:10:41 +01:00
return;
}
// apply msgQueue changeset.
if (msgQueue.length != 0) {
while (msg = msgQueue.shift()) {
var newRev = msg.newRev;
rev=newRev;
if (msg.type == "ACCEPT_COMMIT")
{
editor.applyPreparedChangesetToBase();
setStateIdle();
callCatchingErrors("onInternalAction", function()
{
callbacks.onInternalAction("commitAcceptedByServer");
});
callCatchingErrors("onConnectionTrouble", function()
{
callbacks.onConnectionTrouble("OK");
});
handleUserChanges();
}
else if (msg.type == "NEW_CHANGES")
{
var changeset = msg.changeset;
var author = (msg.author || '');
var apool = msg.apool;
editor.applyChangesToBase(changeset, author, apool);
}
}
}
2011-03-26 14:10:41 +01:00
var sentMessage = false;
var userChangesData = editor.prepareUserChangeset();
2011-07-07 19:59:34 +02:00
if (userChangesData.changeset)
{
2011-03-26 14:10:41 +01:00
lastCommitTime = t;
state = "COMMITTING";
2011-07-07 19:59:34 +02:00
stateMessage = {
type: "USER_CHANGES",
baseRev: rev,
changeset: userChangesData.changeset,
apool: userChangesData.apool
};
2011-03-26 14:10:41 +01:00
stateMessageSocketId = socketId;
sendMessage(stateMessage);
sentMessage = true;
callbacks.onInternalAction("commitPerformed");
}
2011-07-07 19:59:34 +02:00
if (sentMessage)
{
2011-03-26 14:10:41 +01:00
// run again in a few seconds, to detect a disconnect
2011-07-07 19:59:34 +02:00
setTimeout(wrapRecordingErrors("setTimeout(handleUserChanges)", handleUserChanges), 3000);
2011-03-26 14:10:41 +01:00
}
}
2011-07-07 19:59:34 +02:00
function getStats()
{
2011-03-26 14:10:41 +01:00
var stats = {};
2011-07-07 19:59:34 +02:00
stats.screen = [$(window).width(), $(window).height(), window.screen.availWidth, window.screen.availHeight, window.screen.width, window.screen.height].join(',');
2011-03-26 14:10:41 +01:00
stats.ip = serverVars.clientIp;
stats.useragent = serverVars.clientAgent;
return stats;
}
2011-07-07 19:59:34 +02:00
function setUpSocket()
2011-03-26 14:10:41 +01:00
{
2011-07-07 19:59:34 +02:00
hiccupCount = 0;
setChannelState("CONNECTED");
doDeferredActions();
initialStartConnectTime = +new Date();
2011-03-26 14:10:41 +01:00
}
2011-07-07 19:59:34 +02:00
2011-03-26 14:10:41 +01:00
var hiccupCount = 0;
2011-07-07 19:59:34 +02:00
function sendMessage(msg)
{
getSocket().json.send(
2011-07-07 19:59:34 +02:00
{
type: "COLLABROOM",
component: "pad",
data: msg
});
2011-03-26 14:10:41 +01:00
}
2011-07-07 19:59:34 +02:00
function wrapRecordingErrors(catcher, func)
{
return function()
{
try
{
2011-03-26 14:10:41 +01:00
return func.apply(this, Array.prototype.slice.call(arguments));
}
2011-07-07 19:59:34 +02:00
catch (e)
{
2011-03-26 14:10:41 +01:00
caughtErrors.push(e);
caughtErrorCatchers.push(catcher);
caughtErrorTimes.push(+new Date());
//console.dir({catcher: catcher, e: e});
throw e;
}
};
}
2011-07-07 19:59:34 +02:00
function callCatchingErrors(catcher, func)
{
try
{
2011-03-26 14:10:41 +01:00
wrapRecordingErrors(catcher, func)();
}
2011-07-07 19:59:34 +02:00
catch (e)
{ /*absorb*/
}
2011-03-26 14:10:41 +01:00
}
2011-07-07 19:59:34 +02:00
function handleMessageFromServer(evt)
{
if (window.console) console.log(evt);
if (!getSocket()) return;
2011-07-07 19:59:34 +02:00
if (!evt.data) return;
2011-03-26 14:10:41 +01:00
var wrapper = evt;
2011-07-07 19:59:34 +02:00
if (wrapper.type != "COLLABROOM") return;
2011-03-26 14:10:41 +01:00
var msg = wrapper.data;
2011-07-07 19:59:34 +02:00
if (msg.type == "NEW_CHANGES")
{
2011-03-26 14:10:41 +01:00
var newRev = msg.newRev;
var changeset = msg.changeset;
var author = (msg.author || '');
var apool = msg.apool;
// When inInternationalComposition, msg pushed msgQueue.
if (msgQueue.length > 0 || editor.getInInternationalComposition()) {
if (msgQueue.length > 0) oldRev = msgQueue[msgQueue.length - 1].newRev;
else oldRev = rev;
if (newRev != (oldRev + 1))
{
top.console.warn("bad message revision on NEW_CHANGES: " + newRev + " not " + (oldRev + 1));
// setChannelState("DISCONNECTED", "badmessage_newchanges");
return;
}
msgQueue.push(msg);
return;
}
2011-07-07 19:59:34 +02:00
if (newRev != (rev + 1))
{
top.console.warn("bad message revision on NEW_CHANGES: " + newRev + " not " + (rev + 1));
// setChannelState("DISCONNECTED", "badmessage_newchanges");
2011-03-26 14:10:41 +01:00
return;
}
rev = newRev;
editor.applyChangesToBase(changeset, author, apool);
}
2011-07-07 19:59:34 +02:00
else if (msg.type == "ACCEPT_COMMIT")
{
2011-03-26 14:10:41 +01:00
var newRev = msg.newRev;
if (msgQueue.length > 0)
{
if (newRev != (msgQueue[msgQueue.length - 1].newRev + 1))
{
top.console.warn("bad message revision on ACCEPT_COMMIT: " + newRev + " not " + (msgQueue[msgQueue.length - 1][0] + 1));
// setChannelState("DISCONNECTED", "badmessage_acceptcommit");
return;
}
msgQueue.push(msg);
return;
}
2011-07-07 19:59:34 +02:00
if (newRev != (rev + 1))
{
top.console.warn("bad message revision on ACCEPT_COMMIT: " + newRev + " not " + (rev + 1));
// setChannelState("DISCONNECTED", "badmessage_acceptcommit");
2011-03-26 14:10:41 +01:00
return;
}
rev = newRev;
editor.applyPreparedChangesetToBase();
setStateIdle();
2011-07-07 19:59:34 +02:00
callCatchingErrors("onInternalAction", function()
{
2011-03-26 14:10:41 +01:00
callbacks.onInternalAction("commitAcceptedByServer");
});
2011-07-07 19:59:34 +02:00
callCatchingErrors("onConnectionTrouble", function()
{
2011-03-26 14:10:41 +01:00
callbacks.onConnectionTrouble("OK");
});
handleUserChanges();
}
2011-07-07 19:59:34 +02:00
else if (msg.type == "NO_COMMIT_PENDING")
{
if (state == "COMMITTING")
{
2011-03-26 14:10:41 +01:00
// server missed our commit message; abort that commit
setStateIdle();
handleUserChanges();
}
}
2011-07-07 19:59:34 +02:00
else if (msg.type == "USER_NEWINFO")
{
2011-03-26 14:10:41 +01:00
var userInfo = msg.userInfo;
var id = userInfo.userId;
// Avoid a race condition when setting colors. If our color was set by a
// query param, ignore our own "new user" message's color value.
if (id === initialUserInfo.userId && initialUserInfo.globalUserColor)
{
msg.userInfo.colorId = initialUserInfo.globalUserColor;
}
2011-07-07 19:59:34 +02:00
if (userSet[id])
{
2011-03-26 14:10:41 +01:00
userSet[id] = userInfo;
callbacks.onUpdateUserInfo(userInfo);
}
2011-07-07 19:59:34 +02:00
else
{
2011-03-26 14:10:41 +01:00
userSet[id] = userInfo;
callbacks.onUserJoin(userInfo);
}
tellAceActiveAuthorInfo(userInfo);
}
2011-07-07 19:59:34 +02:00
else if (msg.type == "USER_LEAVE")
{
2011-03-26 14:10:41 +01:00
var userInfo = msg.userInfo;
var id = userInfo.userId;
2011-07-07 19:59:34 +02:00
if (userSet[id])
{
2011-03-26 14:10:41 +01:00
delete userSet[userInfo.userId];
fadeAceAuthorInfo(userInfo);
callbacks.onUserLeave(userInfo);
}
}
2011-07-07 19:59:34 +02:00
else if (msg.type == "DISCONNECT_REASON")
{
2011-03-26 14:10:41 +01:00
appLevelDisconnectReason = msg.reason;
}
2011-07-07 19:59:34 +02:00
else if (msg.type == "CLIENT_MESSAGE")
{
2011-03-26 14:10:41 +01:00
callbacks.onClientMessage(msg.payload);
}
2011-07-14 17:15:38 +02:00
else if (msg.type == "CHAT_MESSAGE")
{
chat.addMessage(msg, true, false);
}
else if (msg.type == "CHAT_MESSAGES")
{
for(var i = msg.messages.length - 1; i >= 0; i--)
{
chat.addMessage(msg.messages[i], true, true);
}
if(!chat.gotInitalMessages)
{
chat.scrollDown();
chat.gotInitalMessages = true;
chat.historyPointer = clientVars.chatHead - msg.messages.length;
}
// messages are loaded, so hide the loading-ball
$("#chatloadmessagesball").css("display", "none");
// there are less than 100 messages or we reached the top
if(chat.historyPointer <= 0)
$("#chatloadmessagesbutton").css("display", "none");
else // there are still more messages, re-show the load-button
$("#chatloadmessagesbutton").css("display", "block");
2011-07-14 17:15:38 +02:00
}
2011-07-07 19:59:34 +02:00
else if (msg.type == "SERVER_MESSAGE")
{
2011-03-26 14:10:41 +01:00
callbacks.onServerMessage(msg.payload);
}
hooks.callAll('handleClientMessage_' + msg.type, {payload: msg.payload});
2011-03-26 14:10:41 +01:00
}
2011-07-07 19:59:34 +02:00
function updateUserInfo(userInfo)
{
2011-03-26 14:10:41 +01:00
userInfo.userId = userId;
userSet[userId] = userInfo;
tellAceActiveAuthorInfo(userInfo);
if (!getSocket()) return;
2011-07-07 19:59:34 +02:00
sendMessage(
{
type: "USERINFO_UPDATE",
userInfo: userInfo
});
2011-03-26 14:10:41 +01:00
}
2011-07-07 19:59:34 +02:00
function tellAceActiveAuthorInfo(userInfo)
{
2011-03-26 14:10:41 +01:00
tellAceAuthorInfo(userInfo.userId, userInfo.colorId);
}
2011-07-07 19:59:34 +02:00
function tellAceAuthorInfo(userId, colorId, inactive)
{
if(typeof colorId == "number")
{
colorId = clientVars.colorPalette[colorId];
}
2011-08-20 19:22:10 +02:00
var cssColor = colorId;
if (inactive)
2011-07-07 19:59:34 +02:00
{
2011-08-20 19:22:10 +02:00
editor.setAuthorInfo(userId, {
bgcolor: cssColor,
fade: 0.5
});
}
else
{
editor.setAuthorInfo(userId, {
bgcolor: cssColor
});
2011-03-26 14:10:41 +01:00
}
}
2011-07-07 19:59:34 +02:00
function fadeAceAuthorInfo(userInfo)
{
2011-03-26 14:10:41 +01:00
tellAceAuthorInfo(userInfo.userId, userInfo.colorId, true);
}
2011-07-07 19:59:34 +02:00
function getConnectedUsers()
{
2011-03-26 14:10:41 +01:00
return valuesArray(userSet);
}
2011-07-07 19:59:34 +02:00
function tellAceAboutHistoricalAuthors(hadata)
{
for (var author in hadata)
{
2011-03-26 14:10:41 +01:00
var data = hadata[author];
2011-07-07 19:59:34 +02:00
if (!userSet[author])
{
2011-03-26 14:10:41 +01:00
tellAceAuthorInfo(author, data.colorId, true);
}
}
}
2011-07-07 19:59:34 +02:00
function setChannelState(newChannelState, moreInfo)
{
if (newChannelState != channelState)
{
2011-03-26 14:10:41 +01:00
channelState = newChannelState;
callbacks.onChannelStateChange(channelState, moreInfo);
}
}
2011-07-07 19:59:34 +02:00
function keys(obj)
{
2011-03-26 14:10:41 +01:00
var array = [];
2011-07-07 19:59:34 +02:00
$.each(obj, function(k, v)
{
array.push(k);
});
2011-03-26 14:10:41 +01:00
return array;
}
2011-07-07 19:59:34 +02:00
function valuesArray(obj)
{
2011-03-26 14:10:41 +01:00
var array = [];
2011-07-07 19:59:34 +02:00
$.each(obj, function(k, v)
{
array.push(v);
});
2011-03-26 14:10:41 +01:00
return array;
}
// We need to present a working interface even before the socket
// is connected for the first time.
var deferredActions = [];
2011-07-07 19:59:34 +02:00
function defer(func, tag)
{
return function()
{
2011-03-26 14:10:41 +01:00
var that = this;
var args = arguments;
2011-07-07 19:59:34 +02:00
function action()
{
2011-03-26 14:10:41 +01:00
func.apply(that, args);
}
action.tag = tag;
2011-07-07 19:59:34 +02:00
if (channelState == "CONNECTING")
{
2011-03-26 14:10:41 +01:00
deferredActions.push(action);
}
2011-07-07 19:59:34 +02:00
else
{
2011-03-26 14:10:41 +01:00
action();
}
}
}
2011-07-07 19:59:34 +02:00
function doDeferredActions(tag)
{
2011-03-26 14:10:41 +01:00
var newArray = [];
2011-07-07 19:59:34 +02:00
for (var i = 0; i < deferredActions.length; i++)
{
2011-03-26 14:10:41 +01:00
var a = deferredActions[i];
2011-07-07 19:59:34 +02:00
if ((!tag) || (tag == a.tag))
{
2011-03-26 14:10:41 +01:00
a();
}
2011-07-07 19:59:34 +02:00
else
{
2011-03-26 14:10:41 +01:00
newArray.push(a);
}
}
deferredActions = newArray;
}
2011-07-07 19:59:34 +02:00
function sendClientMessage(msg)
{
sendMessage(
{
type: "CLIENT_MESSAGE",
payload: msg
});
2011-03-26 14:10:41 +01:00
}
2011-07-07 19:59:34 +02:00
function getCurrentRevisionNumber()
{
2011-03-26 14:10:41 +01:00
return rev;
}
2011-07-07 19:59:34 +02:00
function getMissedChanges()
{
2011-03-26 14:10:41 +01:00
var obj = {};
obj.userInfo = userSet[userId];
obj.baseRev = rev;
2011-07-07 19:59:34 +02:00
if (state == "COMMITTING" && stateMessage)
{
2011-03-26 14:10:41 +01:00
obj.committedChangeset = stateMessage.changeset;
obj.committedChangesetAPool = stateMessage.apool;
obj.committedChangesetSocketId = stateMessageSocketId;
editor.applyPreparedChangesetToBase();
}
var userChangesData = editor.prepareUserChangeset();
2011-07-07 19:59:34 +02:00
if (userChangesData.changeset)
{
2011-03-26 14:10:41 +01:00
obj.furtherChangeset = userChangesData.changeset;
obj.furtherChangesetAPool = userChangesData.apool;
}
return obj;
}
2011-07-07 19:59:34 +02:00
function setStateIdle()
{
2011-03-26 14:10:41 +01:00
state = "IDLE";
callbacks.onInternalAction("newlyIdle");
schedulePerhapsCallIdleFuncs();
}
2011-07-07 19:59:34 +02:00
function callWhenNotCommitting(func)
{
2011-03-26 14:10:41 +01:00
idleFuncs.push(func);
schedulePerhapsCallIdleFuncs();
}
var idleFuncs = [];
2011-07-07 19:59:34 +02:00
function schedulePerhapsCallIdleFuncs()
{
setTimeout(function()
{
if (state == "IDLE")
{
while (idleFuncs.length > 0)
{
2011-03-26 14:10:41 +01:00
var f = idleFuncs.shift();
f();
}
}
}, 0);
}
var self = {
2011-07-07 19:59:34 +02:00
setOnUserJoin: function(cb)
{
callbacks.onUserJoin = cb;
},
setOnUserLeave: function(cb)
{
callbacks.onUserLeave = cb;
},
setOnUpdateUserInfo: function(cb)
{
callbacks.onUpdateUserInfo = cb;
},
setOnChannelStateChange: function(cb)
{
callbacks.onChannelStateChange = cb;
},
setOnClientMessage: function(cb)
{
callbacks.onClientMessage = cb;
},
setOnInternalAction: function(cb)
{
callbacks.onInternalAction = cb;
},
setOnConnectionTrouble: function(cb)
{
callbacks.onConnectionTrouble = cb;
},
setOnServerMessage: function(cb)
{
callbacks.onServerMessage = cb;
},
2011-03-26 14:10:41 +01:00
updateUserInfo: defer(updateUserInfo),
handleMessageFromServer: handleMessageFromServer,
2011-03-26 14:10:41 +01:00
getConnectedUsers: getConnectedUsers,
sendClientMessage: sendClientMessage,
2011-07-14 17:15:38 +02:00
sendMessage: sendMessage,
2011-03-26 14:10:41 +01:00
getCurrentRevisionNumber: getCurrentRevisionNumber,
getMissedChanges: getMissedChanges,
callWhenNotCommitting: callWhenNotCommitting,
addHistoricalAuthors: tellAceAboutHistoricalAuthors,
setChannelState: setChannelState
};
$(document).ready(setUpSocket);
return self;
2011-03-26 14:10:41 +01:00
}
exports.getCollabClient = getCollabClient;