etherpad-lite/node/MessageHandler.js

559 lines
17 KiB
JavaScript
Raw Normal View History

2011-03-26 14:10:41 +01:00
/**
2011-03-26 22:29:33 +01:00
* Copyright 2009 Google Inc., 2011 Peter 'Pita' Martischka
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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*/
var padManager = require("./PadManager");
var Changeset = require("./Changeset");
var AttributePoolFactory = require("./AttributePoolFactory");
var authorManager = require("./AuthorManager");
2011-03-26 22:29:33 +01:00
/**
* A associative array that translates a session to a pad
*/
2011-03-26 14:10:41 +01:00
var session2pad = {};
2011-03-26 22:29:33 +01:00
/**
* A associative array that saves which sessions belong to a pad
*/
2011-03-26 14:10:41 +01:00
var pad2sessions = {};
2011-03-26 22:29:33 +01:00
/**
* A associative array that saves some general informations about a session
* key = sessionId
* values = author, rev
* rev = That last revision that was send to this client
* author = the author name of this session
*/
2011-03-26 14:10:41 +01:00
var sessioninfos = {};
2011-03-26 22:29:33 +01:00
/**
* Saves the Socket class we need to send and recieve data from the client
*/
2011-03-26 14:10:41 +01:00
var socketio;
2011-03-26 22:29:33 +01:00
/**
* This Method is called by server.js to tell the message handler on which socket it should send
* @param socket_io The Socket
*/
2011-03-26 14:10:41 +01:00
exports.setSocketIO = function(socket_io)
{
socketio=socket_io;
}
2011-03-26 22:29:33 +01:00
/**
* Handles the connection of a new user
* @param client the new client
*/
2011-03-26 14:10:41 +01:00
exports.handleConnect = function(client)
{
2011-03-26 22:29:33 +01:00
//check if all ok
2011-03-26 14:10:41 +01:00
throwExceptionIfClientOrIOisInvalid(client);
2011-03-26 22:29:33 +01:00
//Initalize session2pad and sessioninfos for this new session
2011-03-26 14:10:41 +01:00
session2pad[client.sessionId]=null;
sessioninfos[client.sessionId]={};
}
2011-03-26 22:29:33 +01:00
/**
* Handles the disconnection of a user
* @param client the client that leaves
*/
2011-03-26 14:10:41 +01:00
exports.handleDisconnect = function(client)
{
2011-03-26 22:29:33 +01:00
//check if all ok
2011-03-26 14:10:41 +01:00
throwExceptionIfClientOrIOisInvalid(client);
2011-03-26 22:29:33 +01:00
//save the padname of this session
2011-03-26 14:10:41 +01:00
var sessionPad=session2pad[client.sessionId];
2011-03-29 00:07:35 +02:00
var author = sessioninfos[client.sessionId].author;
//prepare the notification for the other users on the pad, that this user joined
var messageToTheOtherUsers = {
"type": "COLLABROOM",
"data": {
type: "USER_LEAVE",
userInfo: {
"ip": "127.0.0.1",
"colorId": authorManager.getAuthorColorId(author),
"userAgent": "Anonymous",
"userId": author
}
}
};
2011-03-26 22:29:33 +01:00
//Go trough all sessions of this pad, search and destroy the entry of this client
2011-03-26 14:10:41 +01:00
for(i in pad2sessions[sessionPad])
{
if(pad2sessions[sessionPad][i] == client.sessionId)
{
delete pad2sessions[sessionPad][i];
break;
}
}
2011-03-29 00:07:35 +02:00
//Go trough all user that are still on the pad, and send them the USER_LEAVE message
for(i in pad2sessions[sessionPad])
{
socketio.clients[pad2sessions[sessionPad][i]].send(messageToTheOtherUsers);
}
2011-03-26 22:29:33 +01:00
//Delete the session2pad and sessioninfos entrys of this session
2011-03-26 14:10:41 +01:00
delete session2pad[client.sessionId];
delete sessioninfos[client.sessionId];
}
2011-03-26 22:29:33 +01:00
/**
* Handles a message from a user
* @param client the client that send this message
* @param message the message from the client
*/
2011-03-26 14:10:41 +01:00
exports.handleMessage = function(client, message)
2011-03-26 22:29:33 +01:00
{
//check if all ok
2011-03-26 14:10:41 +01:00
throwExceptionIfClientOrIOisInvalid(client);
if(message == null)
{
throw "Message is null!";
}
2011-03-26 22:29:33 +01:00
//Etherpad sometimes send JSON and sometimes a JSONstring...
2011-03-26 14:10:41 +01:00
if(typeof message == "string")
{
message = JSON.parse(message);
}
if(!message.type)
{
throw "Message have no type attribute!";
}
2011-03-26 22:29:33 +01:00
//Check what type of message we get and delegate to the other methodes
2011-03-26 14:10:41 +01:00
if(message.type == "CLIENT_READY")
{
handleClientReady(client, message);
}
else if(message.type == "COLLABROOM" &&
message.data.type == "USER_CHANGES")
{
console.error(JSON.stringify(message));
handleUserChanges(client, message);
}
else if(message.type == "COLLABROOM" &&
message.data.type == "USERINFO_UPDATE")
{
console.error(JSON.stringify(message));
handleUserInfoUpdate(client, message);
}
2011-03-26 22:29:33 +01:00
//if the message type is unkown, throw an exception
2011-03-26 14:10:41 +01:00
else
{
console.error(message);
throw "unkown Message Type: '" + message.type + "'";
}
}
2011-03-26 22:29:33 +01:00
/**
* Handles a USERINFO_UPDATE, that means that a user have changed his color or name. Anyway, we get both informations
* @param client the client that send this message
* @param message the message from the client
*/
2011-03-26 14:10:41 +01:00
function handleUserInfoUpdate(client, message)
{
2011-03-26 22:29:33 +01:00
//check if all ok
2011-03-26 14:10:41 +01:00
if(message.data.userInfo.colorId == null)
{
throw "USERINFO_UPDATE Message have no colorId!";
}
2011-03-26 22:29:33 +01:00
//Find out the author name of this session
2011-03-26 14:10:41 +01:00
var author = sessioninfos[client.sessionId].author;
2011-03-26 22:29:33 +01:00
//Tell the authorManager about the new attributes
2011-03-26 14:10:41 +01:00
authorManager.setAuthorColorId(author, message.data.userInfo.colorId);
authorManager.setAuthorName(author, message.data.userInfo.name);
var padId = session2pad[client.sessionId];
//set a null name, when there is no name set. cause the client wants it null
if(message.data.userInfo.name == null)
{
message.data.userInfo.name = null;
}
//The Client don't know about a USERINFO_UPDATE, it can handle only new user_newinfo, so change the message type
message.data.type = "USER_NEWINFO";
//Send the other clients on the pad the update message
for(i in pad2sessions[padId])
{
if(pad2sessions[padId][i] != client.sessionId)
{
socketio.clients[pad2sessions[padId][i]].send(message);
}
}
2011-03-26 14:10:41 +01:00
}
2011-03-28 15:15:00 +02:00
function errlog(name, value)
{
console.error(name+"=" + JSON.stringify(value));
}
2011-03-26 22:29:33 +01:00
/**
* Handles a USERINFO_UPDATE, that means that a user have changed his color or name. Anyway, we get both informations
* This Method is nearly 90% copied out of the Etherpad Source Code. So I can't tell you what happens here exactly
* Look at https://github.com/ether/pad/blob/master/etherpad/src/etherpad/collab/collab_server.js in the function applyUserChanges()
* @param client the client that send this message
* @param message the message from the client
*/
2011-03-26 14:10:41 +01:00
function handleUserChanges(client, message)
{
2011-03-26 22:29:33 +01:00
//check if all ok
2011-03-26 14:10:41 +01:00
if(message.data.baseRev == null)
{
throw "USER_CHANGES Message have no baseRev!";
}
if(message.data.apool == null)
{
throw "USER_CHANGES Message have no apool!";
}
if(message.data.changeset == null)
{
throw "USER_CHANGES Message have no changeset!";
}
2011-03-26 22:29:33 +01:00
//get all Vars we need
2011-03-26 14:10:41 +01:00
var baseRev = message.data.baseRev;
var wireApool = (AttributePoolFactory.createAttributePool()).fromJsonable(message.data.apool);
var changeset = message.data.changeset;
var pad = padManager.getPad(session2pad[client.sessionId], false);
//ex. _checkChangesetAndPool
2011-03-26 22:29:33 +01:00
//Copied from Etherpad, don't know what it does exactly
2011-03-26 14:10:41 +01:00
Changeset.checkRep(changeset);
Changeset.eachAttribNumber(changeset, function(n) {
if (! wireApool.getAttrib(n)) {
throw "Attribute pool is missing attribute "+n+" for changeset "+changeset;
}
});
//ex. adoptChangesetAttribs
2011-03-26 22:29:33 +01:00
//Afaik, it copies the new attributes from the changeset, to the global Attribute Pool
2011-03-28 15:15:00 +02:00
changeset = Changeset.moveOpsToNewPool(changeset, wireApool, pad.pool());
2011-03-26 14:10:41 +01:00
//ex. applyUserChanges
var apool = pad.pool();
var r = baseRev;
while (r < pad.getHeadRevisionNumber()) {
r++;
var c = pad.getRevisionChangeset(r);
changeset = Changeset.follow(c, changeset, false, apool);
}
var prevText = pad.text();
if (Changeset.oldLen(changeset) != prevText.length) {
throw "Can't apply USER_CHANGES "+changeset+" with oldLen "
+ Changeset.oldLen(changeset) + " to document of length " + prevText.length;
}
var thisAuthor = sessioninfos[client.sessionId].author;
pad.appendRevision(changeset, thisAuthor);
var correctionChangeset = _correctMarkersInPad(pad.atext(), pad.pool());
if (correctionChangeset) {
pad.appendRevision(correctionChangeset);
}
if (pad.text().lastIndexOf("\n\n") != pad.text().length-2) {
var nlChangeset = Changeset.makeSplice(
pad.text(), pad.text().length-1, 0, "\n");
pad.appendRevision(nlChangeset);
}
//ex. updatePadClients
for(i in pad2sessions[pad.id])
{
var session = pad2sessions[pad.id][i];
var lastRev = sessioninfos[session].rev;
while (lastRev < pad.getHeadRevisionNumber())
{
var r = ++lastRev;
var author = pad.getRevisionAuthor(r);
if(author == sessioninfos[session].author)
{
socketio.clients[session].send({"type":"COLLABROOM","data":{type:"ACCEPT_COMMIT", newRev:r}});
}
else
{
var forWire = Changeset.prepareForWire(pad.getRevisionChangeset(r), pad.pool());
var wireMsg = {"type":"COLLABROOM","data":{type:"NEW_CHANGES", newRev:r,
changeset: forWire.translated,
apool: forWire.pool,
2011-03-28 15:15:00 +02:00
author: author}};
2011-03-26 14:10:41 +01:00
socketio.clients[session].send(wireMsg);
}
}
sessioninfos[session].rev = pad.getHeadRevisionNumber();
}
}
2011-03-26 22:29:33 +01:00
/**
* Copied from the Etherpad Source Code. Don't know what this methode does excatly...
*/
2011-03-26 14:10:41 +01:00
function _correctMarkersInPad(atext, apool) {
var text = atext.text;
// collect char positions of line markers (e.g. bullets) in new atext
// that aren't at the start of a line
var badMarkers = [];
var iter = Changeset.opIterator(atext.attribs);
var offset = 0;
while (iter.hasNext()) {
var op = iter.next();
var listValue = Changeset.opAttributeValue(op, 'list', apool);
if (listValue) {
for(var i=0;i<op.chars;i++) {
if (offset > 0 && text.charAt(offset-1) != '\n') {
badMarkers.push(offset);
}
offset++;
}
}
else {
offset += op.chars;
}
}
if (badMarkers.length == 0) {
return null;
}
// create changeset that removes these bad markers
offset = 0;
var builder = Changeset.builder(text.length);
badMarkers.forEach(function(pos) {
builder.keepText(text.substring(offset, pos));
builder.remove(1);
offset = pos+1;
});
return builder.toString();
}
2011-03-26 22:29:33 +01:00
/**
* Handles a CLIENT_READY. A CLIENT_READY is the first message from the client to the server. The Client sends his token
* and the pad it wants to enter. The Server answers with the inital values (clientVars) of the pad
* @param client the client that send this message
* @param message the message from the client
*/
2011-03-26 14:10:41 +01:00
function handleClientReady(client, message)
{
2011-03-26 22:29:33 +01:00
//check if all ok
2011-03-26 14:10:41 +01:00
if(!message.token)
{
throw "CLIENT_READY Message have no token!";
}
if(!message.padId)
{
throw "CLIENT_READY Message have no padId!";
}
if(!message.protocolVersion)
{
throw "CLIENT_READY Message have no protocolVersion!";
}
if(message.protocolVersion != 1)
{
throw "CLIENT_READY Message have a unkown protocolVersion '" + protocolVersion + "'!";
}
2011-03-26 22:29:33 +01:00
//Ask the author Manager for a authorname of this token.
2011-03-26 14:10:41 +01:00
var author = authorManager.getAuthor4Token(message.token);
//Check if this author is already on the pad, if yes, kick him!
if(pad2sessions[message.padId])
{
for(var i in pad2sessions[message.padId])
{
if(sessioninfos[pad2sessions[message.padId][i]].author == author)
{
client.send({disconnect:"doublelogin"});
return;
}
}
}
2011-03-26 22:29:33 +01:00
//Save in session2pad that this session belonges to this pad
2011-03-26 14:10:41 +01:00
var sessionId=String(client.sessionId);
session2pad[sessionId] = message.padId;
2011-03-26 22:29:33 +01:00
//check if there is already a pad2sessions entry, if not, create one
2011-03-26 14:10:41 +01:00
if(!pad2sessions[message.padId])
{
pad2sessions[message.padId] = [];
}
2011-03-26 22:29:33 +01:00
//Saves in pad2sessions that this session belongs to this pad
2011-03-26 14:10:41 +01:00
pad2sessions[message.padId].push(sessionId);
2011-03-26 22:29:33 +01:00
//Tell the PadManager that it should ensure that this Pad exist
padManager.ensurePadExists(message.padId);
2011-03-26 14:10:41 +01:00
2011-03-26 22:29:33 +01:00
//Ask the PadManager for a function Wrapper for this Pad
2011-03-26 14:10:41 +01:00
var pad = padManager.getPad(message.padId, false);
2011-03-26 22:29:33 +01:00
//prepare all values for the wire
2011-03-26 14:10:41 +01:00
atext = pad.atext();
var attribsForWire = Changeset.prepareForWire(atext.attribs, pad.pool());
var apool = attribsForWire.pool.toJsonable();
atext.attribs = attribsForWire.translated;
var clientVars = {
"accountPrivs": {
"maxRevisions": 100
},
"initialRevisionList": [],
"initialOptions": {
"guestPolicy": "deny"
},
"collab_client_vars": {
"initialAttributedText": atext,
2011-04-06 22:59:57 +02:00
"clientIp": (client.request && client.request.connection) ? client.request.connection.remoteAddress : "127.0.0.1",
2011-03-26 14:10:41 +01:00
//"clientAgent": "Anonymous Agent",
"padId": message.padId,
"historicalAuthorData": {},
"apool": apool,
"rev": pad.getHeadRevisionNumber(),
"globalPadId": message.padId
},
"colorPalette": ["#ffc7c7", "#fff1c7", "#e3ffc7", "#c7ffd5", "#c7ffff", "#c7d5ff", "#e3c7ff", "#ffc7f1", "#ff8f8f", "#ffe38f", "#c7ff8f", "#8fffab", "#8fffff", "#8fabff", "#c78fff", "#ff8fe3", "#d97979", "#d9c179", "#a9d979", "#79d991", "#79d9d9", "#7991d9", "#a979d9", "#d979c1", "#d9a9a9", "#d9cda9", "#c1d9a9", "#a9d9b5", "#a9d9d9", "#a9b5d9", "#c1a9d9", "#d9a9cd"],
2011-04-06 22:59:57 +02:00
"clientIp": (client.request && client.request.connection) ? client.request.connection.remoteAddress : "127.0.0.1",
2011-03-26 14:10:41 +01:00
"userIsGuest": true,
"userColor": authorManager.getAuthorColorId(author),
"padId": message.padId,
"initialTitle": "Pad: " + message.padId,
"opts": {},
"chatHistory": {
"start": 0,
"historicalAuthorData": {},
"end": 0,
"lines": []
},
"numConnectedUsers": pad2sessions[message.padId].length,
"isProPad": false,
"serverTimestamp": new Date().getTime(),
"globalPadId": message.padId,
"userId": author,
"cookiePrefsToSet": {
"fullWidth": false,
"hideSidebar": false
},
"hooks": {}
}
2011-03-26 22:29:33 +01:00
//Add a username to the clientVars if one avaiable
2011-03-26 14:10:41 +01:00
if(authorManager.getAuthorName(author) != null)
{
clientVars.userName = authorManager.getAuthorName(author);
}
2011-03-26 22:29:33 +01:00
//Add all authors that worked on this pad, to the historicalAuthorData on clientVars
2011-03-26 14:10:41 +01:00
var allAuthors = pad.getAllAuthors();
for(i in allAuthors)
{
clientVars.collab_client_vars.historicalAuthorData[allAuthors[i]] = {};
if(authorManager.getAuthorName(author) != null)
clientVars.collab_client_vars.historicalAuthorData[allAuthors[i]].name = authorManager.getAuthorName(author);
clientVars.collab_client_vars.historicalAuthorData[allAuthors[i]].colorId = authorManager.getAuthorColorId(author);
}
2011-03-26 22:29:33 +01:00
//Send the clientVars to the Client
2011-03-26 14:10:41 +01:00
client.send(clientVars);
2011-03-26 22:29:33 +01:00
//Save the revision and the author id in sessioninfos
2011-03-26 14:10:41 +01:00
sessioninfos[client.sessionId].rev = pad.getHeadRevisionNumber();
sessioninfos[client.sessionId].author = author;
2011-03-26 22:29:33 +01:00
//prepare the notification for the other users on the pad, that this user joined
2011-03-26 14:10:41 +01:00
var messageToTheOtherUsers = {
"type": "COLLABROOM",
"data": {
type: "USER_NEWINFO",
userInfo: {
"ip": "127.0.0.1",
"colorId": authorManager.getAuthorColorId(author),
"userAgent": "Anonymous",
"userId": author
}
}
};
2011-03-26 22:29:33 +01:00
//Add the authorname of this new User, if avaiable
2011-03-26 14:10:41 +01:00
if(authorManager.getAuthorName(author) != null)
{
messageToTheOtherUsers.data.userInfo.name = authorManager.getAuthorName(author);
}
2011-03-26 22:29:33 +01:00
//Run trough all sessions of this pad
2011-03-26 14:10:41 +01:00
for(i in pad2sessions[message.padId])
{
2011-03-26 22:29:33 +01:00
//Jump over, if this session is the connection session
2011-03-26 14:10:41 +01:00
if(pad2sessions[message.padId][i] != client.sessionId)
{
2011-03-26 22:29:33 +01:00
//Send this Session the Notification about the new user
2011-03-26 14:10:41 +01:00
socketio.clients[pad2sessions[message.padId][i]].send(messageToTheOtherUsers);
2011-03-26 22:29:33 +01:00
//Send the new User a Notification about this other user
2011-03-26 14:10:41 +01:00
var messageToNotifyTheClientAboutTheOthers = {
"type": "COLLABROOM",
"data": {
type: "USER_NEWINFO",
userInfo: {
"ip": "127.0.0.1",
"colorId": authorManager.getAuthorColorId(sessioninfos[pad2sessions[message.padId][i]].author),
2011-04-07 21:05:55 +02:00
"name": authorManager.getAuthorName(sessioninfos[pad2sessions[message.padId][i]].author),
2011-03-26 14:10:41 +01:00
"userAgent": "Anonymous",
"userId": sessioninfos[pad2sessions[message.padId][i]].author
}
}
};
client.send(messageToNotifyTheClientAboutTheOthers);
}
}
}
2011-03-26 22:29:33 +01:00
/**
* A internal function that simply checks if client or socketio is null and throws a exception if yes
*/
2011-03-26 14:10:41 +01:00
function throwExceptionIfClientOrIOisInvalid(client)
{
if(client == null)
{
throw "Client is null!";
}
if(socketio == null)
{
throw "SocketIO is not set or null! Please use setSocketIO(io) to set it";
}
}