The Big Renaming - etherpad is now an NPM module
13
src/node/README.md
Normal file
|
@ -0,0 +1,13 @@
|
|||
# About the folder structure
|
||||
|
||||
* **db** - all modules that are accesing the data structure and are communicating directly to the database
|
||||
* **handler** - all modules that responds directly to requests/messages of the browser
|
||||
* **utils** - helper modules
|
||||
|
||||
# Module name conventions
|
||||
|
||||
Module file names starts with a capital letter and uses camelCase
|
||||
|
||||
# Where does it start?
|
||||
|
||||
server.js is started directly
|
520
src/node/db/API.js
Normal file
|
@ -0,0 +1,520 @@
|
|||
/**
|
||||
* This module provides all API functions
|
||||
*/
|
||||
|
||||
/*
|
||||
* 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
|
||||
*
|
||||
* 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 ERR = require("async-stacktrace");
|
||||
var customError = require("../utils/customError");
|
||||
var padManager = require("./PadManager");
|
||||
var padMessageHandler = require("../handler/PadMessageHandler");
|
||||
var readOnlyManager = require("./ReadOnlyManager");
|
||||
var groupManager = require("./GroupManager");
|
||||
var authorManager = require("./AuthorManager");
|
||||
var sessionManager = require("./SessionManager");
|
||||
var async = require("async");
|
||||
var exportHtml = require("../utils/ExportHtml");
|
||||
var importHtml = require("../utils/ImportHtml");
|
||||
var cleanText = require("./Pad").cleanText;
|
||||
|
||||
/**********************/
|
||||
/**GROUP FUNCTIONS*****/
|
||||
/**********************/
|
||||
|
||||
exports.createGroup = groupManager.createGroup;
|
||||
exports.createGroupIfNotExistsFor = groupManager.createGroupIfNotExistsFor;
|
||||
exports.deleteGroup = groupManager.deleteGroup;
|
||||
exports.listPads = groupManager.listPads;
|
||||
exports.createGroupPad = groupManager.createGroupPad;
|
||||
|
||||
/**********************/
|
||||
/**AUTHOR FUNCTIONS****/
|
||||
/**********************/
|
||||
|
||||
exports.createAuthor = authorManager.createAuthor;
|
||||
exports.createAuthorIfNotExistsFor = authorManager.createAuthorIfNotExistsFor;
|
||||
|
||||
/**********************/
|
||||
/**SESSION FUNCTIONS***/
|
||||
/**********************/
|
||||
|
||||
exports.createSession = sessionManager.createSession;
|
||||
exports.deleteSession = sessionManager.deleteSession;
|
||||
exports.getSessionInfo = sessionManager.getSessionInfo;
|
||||
exports.listSessionsOfGroup = sessionManager.listSessionsOfGroup;
|
||||
exports.listSessionsOfAuthor = sessionManager.listSessionsOfAuthor;
|
||||
|
||||
/************************/
|
||||
/**PAD CONTENT FUNCTIONS*/
|
||||
/************************/
|
||||
|
||||
/**
|
||||
getText(padID, [rev]) returns the text of a pad
|
||||
|
||||
Example returns:
|
||||
|
||||
{code: 0, message:"ok", data: {text:"Welcome Text"}}
|
||||
{code: 1, message:"padID does not exist", data: null}
|
||||
*/
|
||||
exports.getText = function(padID, rev, callback)
|
||||
{
|
||||
//check if rev is set
|
||||
if(typeof rev == "function")
|
||||
{
|
||||
callback = rev;
|
||||
rev = undefined;
|
||||
}
|
||||
|
||||
//check if rev is a number
|
||||
if(rev !== undefined && typeof rev != "number")
|
||||
{
|
||||
//try to parse the number
|
||||
if(!isNaN(parseInt(rev)))
|
||||
{
|
||||
rev = parseInt(rev);
|
||||
}
|
||||
else
|
||||
{
|
||||
callback(new customError("rev is not a number", "apierror"));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
//ensure this is not a negativ number
|
||||
if(rev !== undefined && rev < 0)
|
||||
{
|
||||
callback(new customError("rev is a negativ number","apierror"));
|
||||
return;
|
||||
}
|
||||
|
||||
//ensure this is not a float value
|
||||
if(rev !== undefined && !is_int(rev))
|
||||
{
|
||||
callback(new customError("rev is a float value","apierror"));
|
||||
return;
|
||||
}
|
||||
|
||||
//get the pad
|
||||
getPadSafe(padID, true, function(err, pad)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//the client asked for a special revision
|
||||
if(rev !== undefined)
|
||||
{
|
||||
//check if this is a valid revision
|
||||
if(rev > pad.getHeadRevisionNumber())
|
||||
{
|
||||
callback(new customError("rev is higher than the head revision of the pad","apierror"));
|
||||
return;
|
||||
}
|
||||
|
||||
//get the text of this revision
|
||||
pad.getInternalRevisionAText(rev, function(err, atext)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
data = {text: atext.text};
|
||||
|
||||
callback(null, data);
|
||||
})
|
||||
}
|
||||
//the client wants the latest text, lets return it to him
|
||||
else
|
||||
{
|
||||
callback(null, {"text": pad.text()});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
setText(padID, text) sets the text of a pad
|
||||
|
||||
Example returns:
|
||||
|
||||
{code: 0, message:"ok", data: null}
|
||||
{code: 1, message:"padID does not exist", data: null}
|
||||
{code: 1, message:"text too long", data: null}
|
||||
*/
|
||||
exports.setText = function(padID, text, callback)
|
||||
{
|
||||
//get the pad
|
||||
getPadSafe(padID, true, function(err, pad)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//set the text
|
||||
pad.setText(text);
|
||||
|
||||
//update the clients on the pad
|
||||
padMessageHandler.updatePadClients(pad, callback);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
getHTML(padID, [rev]) returns the html of a pad
|
||||
|
||||
Example returns:
|
||||
|
||||
{code: 0, message:"ok", data: {text:"Welcome <strong>Text</strong>"}}
|
||||
{code: 1, message:"padID does not exist", data: null}
|
||||
*/
|
||||
exports.getHTML = function(padID, rev, callback)
|
||||
{
|
||||
if(typeof rev == "function")
|
||||
{
|
||||
callback = rev;
|
||||
rev = undefined;
|
||||
}
|
||||
|
||||
if (rev !== undefined && typeof rev != "number")
|
||||
{
|
||||
if (!isNaN(parseInt(rev)))
|
||||
{
|
||||
rev = parseInt(rev);
|
||||
}
|
||||
else
|
||||
{
|
||||
callback(new customError("rev is not a number","apierror"));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if(rev !== undefined && rev < 0)
|
||||
{
|
||||
callback(new customError("rev is a negative number","apierror"));
|
||||
return;
|
||||
}
|
||||
|
||||
if(rev !== undefined && !is_int(rev))
|
||||
{
|
||||
callback(new customError("rev is a float value","apierror"));
|
||||
return;
|
||||
}
|
||||
|
||||
getPadSafe(padID, true, function(err, pad)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//the client asked for a special revision
|
||||
if(rev !== undefined)
|
||||
{
|
||||
//check if this is a valid revision
|
||||
if(rev > pad.getHeadRevisionNumber())
|
||||
{
|
||||
callback(new customError("rev is higher than the head revision of the pad","apierror"));
|
||||
return;
|
||||
}
|
||||
|
||||
//get the html of this revision
|
||||
exportHtml.getPadHTML(pad, rev, function(err, html)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
data = {html: html};
|
||||
callback(null, data);
|
||||
});
|
||||
}
|
||||
//the client wants the latest text, lets return it to him
|
||||
else
|
||||
{
|
||||
exportHtml.getPadHTML(pad, undefined, function (err, html)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
data = {html: html};
|
||||
|
||||
callback(null, data);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
exports.setHTML = function(padID, html, callback)
|
||||
{
|
||||
//get the pad
|
||||
getPadSafe(padID, true, function(err, pad)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
// add a new changeset with the new html to the pad
|
||||
importHtml.setPadHTML(pad, cleanText(html));
|
||||
|
||||
//update the clients on the pad
|
||||
padMessageHandler.updatePadClients(pad, callback);
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
/*****************/
|
||||
/**PAD FUNCTIONS */
|
||||
/*****************/
|
||||
|
||||
/**
|
||||
getRevisionsCount(padID) returns the number of revisions of this pad
|
||||
|
||||
Example returns:
|
||||
|
||||
{code: 0, message:"ok", data: {revisions: 56}}
|
||||
{code: 1, message:"padID does not exist", data: null}
|
||||
*/
|
||||
exports.getRevisionsCount = function(padID, callback)
|
||||
{
|
||||
//get the pad
|
||||
getPadSafe(padID, true, function(err, pad)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
callback(null, {revisions: pad.getHeadRevisionNumber()});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
createPad(padName [, text]) creates a new pad in this group
|
||||
|
||||
Example returns:
|
||||
|
||||
{code: 0, message:"ok", data: null}
|
||||
{code: 1, message:"pad does already exist", data: null}
|
||||
*/
|
||||
exports.createPad = function(padID, text, callback)
|
||||
{
|
||||
//ensure there is no $ in the padID
|
||||
if(padID && padID.indexOf("$") != -1)
|
||||
{
|
||||
callback(new customError("createPad can't create group pads","apierror"));
|
||||
return;
|
||||
}
|
||||
|
||||
//create pad
|
||||
getPadSafe(padID, false, text, function(err)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
callback();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
deletePad(padID) deletes a pad
|
||||
|
||||
Example returns:
|
||||
|
||||
{code: 0, message:"ok", data: null}
|
||||
{code: 1, message:"padID does not exist", data: null}
|
||||
*/
|
||||
exports.deletePad = function(padID, callback)
|
||||
{
|
||||
getPadSafe(padID, true, function(err, pad)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
pad.remove(callback);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
getReadOnlyLink(padID) returns the read only link of a pad
|
||||
|
||||
Example returns:
|
||||
|
||||
{code: 0, message:"ok", data: null}
|
||||
{code: 1, message:"padID does not exist", data: null}
|
||||
*/
|
||||
exports.getReadOnlyID = function(padID, callback)
|
||||
{
|
||||
//we don't need the pad object, but this function does all the security stuff for us
|
||||
getPadSafe(padID, true, function(err)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//get the readonlyId
|
||||
readOnlyManager.getReadOnlyId(padID, function(err, readOnlyId)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
callback(null, {readOnlyID: readOnlyId});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
setPublicStatus(padID, publicStatus) sets a boolean for the public status of a pad
|
||||
|
||||
Example returns:
|
||||
|
||||
{code: 0, message:"ok", data: null}
|
||||
{code: 1, message:"padID does not exist", data: null}
|
||||
*/
|
||||
exports.setPublicStatus = function(padID, publicStatus, callback)
|
||||
{
|
||||
//ensure this is a group pad
|
||||
if(padID && padID.indexOf("$") == -1)
|
||||
{
|
||||
callback(new customError("You can only get/set the publicStatus of pads that belong to a group","apierror"));
|
||||
return;
|
||||
}
|
||||
|
||||
//get the pad
|
||||
getPadSafe(padID, true, function(err, pad)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//convert string to boolean
|
||||
if(typeof publicStatus == "string")
|
||||
publicStatus = publicStatus == "true" ? true : false;
|
||||
|
||||
//set the password
|
||||
pad.setPublicStatus(publicStatus);
|
||||
|
||||
callback();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
getPublicStatus(padID) return true of false
|
||||
|
||||
Example returns:
|
||||
|
||||
{code: 0, message:"ok", data: {publicStatus: true}}
|
||||
{code: 1, message:"padID does not exist", data: null}
|
||||
*/
|
||||
exports.getPublicStatus = function(padID, callback)
|
||||
{
|
||||
//ensure this is a group pad
|
||||
if(padID && padID.indexOf("$") == -1)
|
||||
{
|
||||
callback(new customError("You can only get/set the publicStatus of pads that belong to a group","apierror"));
|
||||
return;
|
||||
}
|
||||
|
||||
//get the pad
|
||||
getPadSafe(padID, true, function(err, pad)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
callback(null, {publicStatus: pad.getPublicStatus()});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
setPassword(padID, password) returns ok or a error message
|
||||
|
||||
Example returns:
|
||||
|
||||
{code: 0, message:"ok", data: null}
|
||||
{code: 1, message:"padID does not exist", data: null}
|
||||
*/
|
||||
exports.setPassword = function(padID, password, callback)
|
||||
{
|
||||
//ensure this is a group pad
|
||||
if(padID && padID.indexOf("$") == -1)
|
||||
{
|
||||
callback(new customError("You can only get/set the password of pads that belong to a group","apierror"));
|
||||
return;
|
||||
}
|
||||
|
||||
//get the pad
|
||||
getPadSafe(padID, true, function(err, pad)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//set the password
|
||||
pad.setPassword(password);
|
||||
|
||||
callback();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
isPasswordProtected(padID) returns true or false
|
||||
|
||||
Example returns:
|
||||
|
||||
{code: 0, message:"ok", data: {passwordProtection: true}}
|
||||
{code: 1, message:"padID does not exist", data: null}
|
||||
*/
|
||||
exports.isPasswordProtected = function(padID, callback)
|
||||
{
|
||||
//ensure this is a group pad
|
||||
if(padID && padID.indexOf("$") == -1)
|
||||
{
|
||||
callback(new customError("You can only get/set the password of pads that belong to a group","apierror"));
|
||||
return;
|
||||
}
|
||||
|
||||
//get the pad
|
||||
getPadSafe(padID, true, function(err, pad)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
callback(null, {isPasswordProtected: pad.isPasswordProtected()});
|
||||
});
|
||||
}
|
||||
|
||||
/******************************/
|
||||
/** INTERNAL HELPER FUNCTIONS */
|
||||
/******************************/
|
||||
|
||||
//checks if a number is an int
|
||||
function is_int(value)
|
||||
{
|
||||
return (parseFloat(value) == parseInt(value)) && !isNaN(value)
|
||||
}
|
||||
|
||||
//gets a pad safe
|
||||
function getPadSafe(padID, shouldExist, text, callback)
|
||||
{
|
||||
if(typeof text == "function")
|
||||
{
|
||||
callback = text;
|
||||
text = null;
|
||||
}
|
||||
|
||||
//check if padID is a string
|
||||
if(typeof padID != "string")
|
||||
{
|
||||
callback(new customError("padID is not a string","apierror"));
|
||||
return;
|
||||
}
|
||||
|
||||
//check if the padID maches the requirements
|
||||
if(!padManager.isValidPadId(padID))
|
||||
{
|
||||
callback(new customError("padID did not match requirements","apierror"));
|
||||
return;
|
||||
}
|
||||
|
||||
//check if the pad exists
|
||||
padManager.doesPadExists(padID, function(err, exists)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//does not exist, but should
|
||||
if(exists == false && shouldExist == true)
|
||||
{
|
||||
callback(new customError("padID does not exist","apierror"));
|
||||
}
|
||||
//does exists, but shouldn't
|
||||
else if(exists == true && shouldExist == false)
|
||||
{
|
||||
callback(new customError("padID does already exist","apierror"));
|
||||
}
|
||||
//pad exists, let's get it
|
||||
else
|
||||
{
|
||||
padManager.getPad(padID, text, callback);
|
||||
}
|
||||
});
|
||||
}
|
181
src/node/db/AuthorManager.js
Normal file
|
@ -0,0 +1,181 @@
|
|||
/**
|
||||
* The AuthorManager controlls all information about the Pad authors
|
||||
*/
|
||||
|
||||
/*
|
||||
* 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
|
||||
*
|
||||
* 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 CommonCode = require('../utils/common_code');
|
||||
var ERR = require("async-stacktrace");
|
||||
var db = require("./DB").db;
|
||||
var async = require("async");
|
||||
var randomString = CommonCode.require('/pad_utils').randomString;
|
||||
|
||||
/**
|
||||
* Checks if the author exists
|
||||
*/
|
||||
exports.doesAuthorExists = function (authorID, callback)
|
||||
{
|
||||
//check if the database entry of this author exists
|
||||
db.get("globalAuthor:" + authorID, function (err, author)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
callback(null, author != null);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the AuthorID for a token.
|
||||
* @param {String} token The token
|
||||
* @param {Function} callback callback (err, author)
|
||||
*/
|
||||
exports.getAuthor4Token = function (token, callback)
|
||||
{
|
||||
mapAuthorWithDBKey("token2author", token, function(err, author)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
//return only the sub value authorID
|
||||
callback(null, author ? author.authorID : author);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the AuthorID for a mapper.
|
||||
* @param {String} token The mapper
|
||||
* @param {Function} callback callback (err, author)
|
||||
*/
|
||||
exports.createAuthorIfNotExistsFor = function (authorMapper, name, callback)
|
||||
{
|
||||
mapAuthorWithDBKey("mapper2author", authorMapper, function(err, author)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//set the name of this author
|
||||
if(name)
|
||||
exports.setAuthorName(author.authorID, name);
|
||||
|
||||
//return the authorID
|
||||
callback(null, author);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the AuthorID for a mapper. We can map using a mapperkey,
|
||||
* so far this is token2author and mapper2author
|
||||
* @param {String} mapperkey The database key name for this mapper
|
||||
* @param {String} mapper The mapper
|
||||
* @param {Function} callback callback (err, author)
|
||||
*/
|
||||
function mapAuthorWithDBKey (mapperkey, mapper, callback)
|
||||
{
|
||||
//try to map to an author
|
||||
db.get(mapperkey + ":" + mapper, function (err, author)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//there is no author with this mapper, so create one
|
||||
if(author == null)
|
||||
{
|
||||
exports.createAuthor(null, function(err, author)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//create the token2author relation
|
||||
db.set(mapperkey + ":" + mapper, author.authorID);
|
||||
|
||||
//return the author
|
||||
callback(null, author);
|
||||
});
|
||||
}
|
||||
//there is a author with this mapper
|
||||
else
|
||||
{
|
||||
//update the timestamp of this author
|
||||
db.setSub("globalAuthor:" + author, ["timestamp"], new Date().getTime());
|
||||
|
||||
//return the author
|
||||
callback(null, {authorID: author});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal function that creates the database entry for an author
|
||||
* @param {String} name The name of the author
|
||||
*/
|
||||
exports.createAuthor = function(name, callback)
|
||||
{
|
||||
//create the new author name
|
||||
var author = "a." + randomString(16);
|
||||
|
||||
//create the globalAuthors db entry
|
||||
var authorObj = {"colorId" : Math.floor(Math.random()*32), "name": name, "timestamp": new Date().getTime()};
|
||||
|
||||
//set the global author db entry
|
||||
db.set("globalAuthor:" + author, authorObj);
|
||||
|
||||
callback(null, {authorID: author});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Author Obj of the author
|
||||
* @param {String} author The id of the author
|
||||
* @param {Function} callback callback(err, authorObj)
|
||||
*/
|
||||
exports.getAuthor = function (author, callback)
|
||||
{
|
||||
db.get("globalAuthor:" + author, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the color Id of the author
|
||||
* @param {String} author The id of the author
|
||||
* @param {Function} callback callback(err, colorId)
|
||||
*/
|
||||
exports.getAuthorColorId = function (author, callback)
|
||||
{
|
||||
db.getSub("globalAuthor:" + author, ["colorId"], callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the color Id of the author
|
||||
* @param {String} author The id of the author
|
||||
* @param {Function} callback (optional)
|
||||
*/
|
||||
exports.setAuthorColorId = function (author, colorId, callback)
|
||||
{
|
||||
db.setSub("globalAuthor:" + author, ["colorId"], colorId, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name of the author
|
||||
* @param {String} author The id of the author
|
||||
* @param {Function} callback callback(err, name)
|
||||
*/
|
||||
exports.getAuthorName = function (author, callback)
|
||||
{
|
||||
db.getSub("globalAuthor:" + author, ["name"], callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the name of the author
|
||||
* @param {String} author The id of the author
|
||||
* @param {Function} callback (optional)
|
||||
*/
|
||||
exports.setAuthorName = function (author, name, callback)
|
||||
{
|
||||
db.setSub("globalAuthor:" + author, ["name"], name, callback);
|
||||
}
|
57
src/node/db/DB.js
Normal file
|
@ -0,0 +1,57 @@
|
|||
/**
|
||||
* The DB Module provides a database initalized with the settings
|
||||
* provided by the settings module
|
||||
*/
|
||||
|
||||
/*
|
||||
* 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
|
||||
*
|
||||
* 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 ueberDB = require("ueberDB");
|
||||
var settings = require("../utils/Settings");
|
||||
var log4js = require('log4js');
|
||||
|
||||
//set database settings
|
||||
var db = new ueberDB.database(settings.dbType, settings.dbSettings, null, log4js.getLogger("ueberDB"));
|
||||
|
||||
/**
|
||||
* The UeberDB Object that provides the database functions
|
||||
*/
|
||||
exports.db = null;
|
||||
|
||||
/**
|
||||
* Initalizes the database with the settings provided by the settings module
|
||||
* @param {Function} callback
|
||||
*/
|
||||
exports.init = function(callback)
|
||||
{
|
||||
//initalize the database async
|
||||
db.init(function(err)
|
||||
{
|
||||
//there was an error while initializing the database, output it and stop
|
||||
if(err)
|
||||
{
|
||||
console.error("ERROR: Problem while initalizing the database");
|
||||
console.error(err.stack ? err.stack : err);
|
||||
process.exit(1);
|
||||
}
|
||||
//everything ok
|
||||
else
|
||||
{
|
||||
exports.db = db;
|
||||
callback(null);
|
||||
}
|
||||
});
|
||||
}
|
263
src/node/db/GroupManager.js
Normal file
|
@ -0,0 +1,263 @@
|
|||
/**
|
||||
* The Group Manager provides functions to manage groups in the database
|
||||
*/
|
||||
|
||||
/*
|
||||
* 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
|
||||
*
|
||||
* 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 CommonCode = require('../utils/common_code');
|
||||
var ERR = require("async-stacktrace");
|
||||
var customError = require("../utils/customError");
|
||||
var randomString = CommonCode.require('/pad_utils').randomString;
|
||||
var db = require("./DB").db;
|
||||
var async = require("async");
|
||||
var padManager = require("./PadManager");
|
||||
var sessionManager = require("./SessionManager");
|
||||
|
||||
exports.deleteGroup = function(groupID, callback)
|
||||
{
|
||||
var group;
|
||||
|
||||
async.series([
|
||||
//ensure group exists
|
||||
function (callback)
|
||||
{
|
||||
//try to get the group entry
|
||||
db.get("group:" + groupID, function (err, _group)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//group does not exist
|
||||
if(_group == null)
|
||||
{
|
||||
callback(new customError("groupID does not exist","apierror"));
|
||||
}
|
||||
//group exists, everything is fine
|
||||
else
|
||||
{
|
||||
group = _group;
|
||||
callback();
|
||||
}
|
||||
});
|
||||
},
|
||||
//iterate trough all pads of this groups and delete them
|
||||
function(callback)
|
||||
{
|
||||
//collect all padIDs in an array, that allows us to use async.forEach
|
||||
var padIDs = [];
|
||||
for(var i in group.pads)
|
||||
{
|
||||
padIDs.push(i);
|
||||
}
|
||||
|
||||
//loop trough all pads and delete them
|
||||
async.forEach(padIDs, function(padID, callback)
|
||||
{
|
||||
padManager.getPad(padID, function(err, pad)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
pad.remove(callback);
|
||||
});
|
||||
}, callback);
|
||||
},
|
||||
//iterate trough group2sessions and delete all sessions
|
||||
function(callback)
|
||||
{
|
||||
//try to get the group entry
|
||||
db.get("group2sessions:" + groupID, function (err, group2sessions)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//skip if there is no group2sessions entry
|
||||
if(group2sessions == null) {callback(); return}
|
||||
|
||||
//collect all sessions in an array, that allows us to use async.forEach
|
||||
var sessions = [];
|
||||
for(var i in group2sessions.sessionsIDs)
|
||||
{
|
||||
sessions.push(i);
|
||||
}
|
||||
|
||||
//loop trough all sessions and delete them
|
||||
async.forEach(sessions, function(session, callback)
|
||||
{
|
||||
sessionManager.deleteSession(session, callback);
|
||||
}, callback);
|
||||
});
|
||||
},
|
||||
//remove group and group2sessions entry
|
||||
function(callback)
|
||||
{
|
||||
db.remove("group2sessions:" + groupID);
|
||||
db.remove("group:" + groupID);
|
||||
callback();
|
||||
}
|
||||
], function(err)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
callback();
|
||||
});
|
||||
}
|
||||
|
||||
exports.doesGroupExist = function(groupID, callback)
|
||||
{
|
||||
//try to get the group entry
|
||||
db.get("group:" + groupID, function (err, group)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
callback(null, group != null);
|
||||
});
|
||||
}
|
||||
|
||||
exports.createGroup = function(callback)
|
||||
{
|
||||
//search for non existing groupID
|
||||
var groupID = "g." + randomString(16);
|
||||
|
||||
//create the group
|
||||
db.set("group:" + groupID, {pads: {}});
|
||||
callback(null, {groupID: groupID});
|
||||
}
|
||||
|
||||
exports.createGroupIfNotExistsFor = function(groupMapper, callback)
|
||||
{
|
||||
//ensure mapper is optional
|
||||
if(typeof groupMapper != "string")
|
||||
{
|
||||
callback(new customError("groupMapper is no string","apierror"));
|
||||
return;
|
||||
}
|
||||
|
||||
//try to get a group for this mapper
|
||||
db.get("mapper2group:"+groupMapper, function(err, groupID)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//there is no group for this mapper, let's create a group
|
||||
if(groupID == null)
|
||||
{
|
||||
exports.createGroup(function(err, responseObj)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//create the mapper entry for this group
|
||||
db.set("mapper2group:"+groupMapper, responseObj.groupID);
|
||||
|
||||
callback(null, responseObj);
|
||||
});
|
||||
}
|
||||
//there is a group for this mapper, let's return it
|
||||
else
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
callback(null, {groupID: groupID});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
exports.createGroupPad = function(groupID, padName, text, callback)
|
||||
{
|
||||
//create the padID
|
||||
var padID = groupID + "$" + padName;
|
||||
|
||||
async.series([
|
||||
//ensure group exists
|
||||
function (callback)
|
||||
{
|
||||
exports.doesGroupExist(groupID, function(err, exists)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//group does not exist
|
||||
if(exists == false)
|
||||
{
|
||||
callback(new customError("groupID does not exist","apierror"));
|
||||
}
|
||||
//group exists, everything is fine
|
||||
else
|
||||
{
|
||||
callback();
|
||||
}
|
||||
});
|
||||
},
|
||||
//ensure pad does not exists
|
||||
function (callback)
|
||||
{
|
||||
padManager.doesPadExists(padID, function(err, exists)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//pad exists already
|
||||
if(exists == true)
|
||||
{
|
||||
callback(new customError("padName does already exist","apierror"));
|
||||
}
|
||||
//pad does not exist, everything is fine
|
||||
else
|
||||
{
|
||||
callback();
|
||||
}
|
||||
});
|
||||
},
|
||||
//create the pad
|
||||
function (callback)
|
||||
{
|
||||
padManager.getPad(padID, text, function(err)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
callback();
|
||||
});
|
||||
},
|
||||
//create an entry in the group for this pad
|
||||
function (callback)
|
||||
{
|
||||
db.setSub("group:" + groupID, ["pads", padID], 1);
|
||||
callback();
|
||||
}
|
||||
], function(err)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
callback(null, {padID: padID});
|
||||
});
|
||||
}
|
||||
|
||||
exports.listPads = function(groupID, callback)
|
||||
{
|
||||
exports.doesGroupExist(groupID, function(err, exists)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//group does not exist
|
||||
if(exists == false)
|
||||
{
|
||||
callback(new customError("groupID does not exist","apierror"));
|
||||
}
|
||||
//group exists, let's get the pads
|
||||
else
|
||||
{
|
||||
db.getSub("group:" + groupID, ["pads"], function(err, result)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
var pads = [];
|
||||
for ( var padId in result ) {
|
||||
pads.push(padId);
|
||||
}
|
||||
callback(null, {padIDs: pads});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
488
src/node/db/Pad.js
Normal file
|
@ -0,0 +1,488 @@
|
|||
/**
|
||||
* The pad object, defined with joose
|
||||
*/
|
||||
|
||||
var CommonCode = require('../utils/common_code');
|
||||
var ERR = require("async-stacktrace");
|
||||
var Changeset = CommonCode.require("/Changeset");
|
||||
var AttributePoolFactory = CommonCode.require("/AttributePoolFactory");
|
||||
var randomString = CommonCode.require('/pad_utils').randomString;
|
||||
var db = require("./DB").db;
|
||||
var async = require("async");
|
||||
var settings = require('../utils/Settings');
|
||||
var authorManager = require("./AuthorManager");
|
||||
var padManager = require("./PadManager");
|
||||
var padMessageHandler = require("../handler/PadMessageHandler");
|
||||
var readOnlyManager = require("./ReadOnlyManager");
|
||||
var crypto = require("crypto");
|
||||
|
||||
/**
|
||||
* Copied from the Etherpad source code. It converts Windows line breaks to Unix line breaks and convert Tabs to spaces
|
||||
* @param txt
|
||||
*/
|
||||
exports.cleanText = function (txt) {
|
||||
return txt.replace(/\r\n/g,'\n').replace(/\r/g,'\n').replace(/\t/g, ' ').replace(/\xa0/g, ' ');
|
||||
};
|
||||
|
||||
|
||||
var Pad = function Pad(id) {
|
||||
|
||||
this.atext = Changeset.makeAText("\n");
|
||||
this.pool = AttributePoolFactory.createAttributePool();
|
||||
this.head = -1;
|
||||
this.chatHead = -1;
|
||||
this.publicStatus = false;
|
||||
this.passwordHash = null;
|
||||
this.id = id;
|
||||
|
||||
};
|
||||
|
||||
exports.Pad = Pad;
|
||||
|
||||
Pad.prototype.apool = function apool() {
|
||||
return this.pool;
|
||||
};
|
||||
|
||||
Pad.prototype.getHeadRevisionNumber = function getHeadRevisionNumber() {
|
||||
return this.head;
|
||||
};
|
||||
|
||||
Pad.prototype.getPublicStatus = function getPublicStatus() {
|
||||
return this.publicStatus;
|
||||
};
|
||||
|
||||
Pad.prototype.appendRevision = function appendRevision(aChangeset, author) {
|
||||
if(!author)
|
||||
author = '';
|
||||
|
||||
var newAText = Changeset.applyToAText(aChangeset, this.atext, this.pool);
|
||||
Changeset.copyAText(newAText, this.atext);
|
||||
|
||||
var newRev = ++this.head;
|
||||
|
||||
var newRevData = {};
|
||||
newRevData.changeset = aChangeset;
|
||||
newRevData.meta = {};
|
||||
newRevData.meta.author = author;
|
||||
newRevData.meta.timestamp = new Date().getTime();
|
||||
|
||||
//ex. getNumForAuthor
|
||||
if(author != '')
|
||||
this.pool.putAttrib(['author', author || '']);
|
||||
|
||||
if(newRev % 100 == 0)
|
||||
{
|
||||
newRevData.meta.atext = this.atext;
|
||||
}
|
||||
|
||||
db.set("pad:"+this.id+":revs:"+newRev, newRevData);
|
||||
db.set("pad:"+this.id, {atext: this.atext,
|
||||
pool: this.pool.toJsonable(),
|
||||
head: this.head,
|
||||
chatHead: this.chatHead,
|
||||
publicStatus: this.publicStatus,
|
||||
passwordHash: this.passwordHash});
|
||||
};
|
||||
|
||||
Pad.prototype.getRevisionChangeset = function getRevisionChangeset(revNum, callback) {
|
||||
db.getSub("pad:"+this.id+":revs:"+revNum, ["changeset"], callback);
|
||||
};
|
||||
|
||||
Pad.prototype.getRevisionAuthor = function getRevisionAuthor(revNum, callback) {
|
||||
db.getSub("pad:"+this.id+":revs:"+revNum, ["meta", "author"], callback);
|
||||
};
|
||||
|
||||
Pad.prototype.getRevisionDate = function getRevisionDate(revNum, callback) {
|
||||
db.getSub("pad:"+this.id+":revs:"+revNum, ["meta", "timestamp"], callback);
|
||||
};
|
||||
|
||||
Pad.prototype.getAllAuthors = function getAllAuthors() {
|
||||
var authors = [];
|
||||
|
||||
for(key in this.pool.numToAttrib)
|
||||
{
|
||||
if(this.pool.numToAttrib[key][0] == "author" && this.pool.numToAttrib[key][1] != "")
|
||||
{
|
||||
authors.push(this.pool.numToAttrib[key][1]);
|
||||
}
|
||||
}
|
||||
|
||||
return authors;
|
||||
};
|
||||
|
||||
Pad.prototype.getInternalRevisionAText = function getInternalRevisionAText(targetRev, callback) {
|
||||
var _this = this;
|
||||
|
||||
var keyRev = this.getKeyRevisionNumber(targetRev);
|
||||
var atext;
|
||||
var changesets = [];
|
||||
|
||||
//find out which changesets are needed
|
||||
var neededChangesets = [];
|
||||
var curRev = keyRev;
|
||||
while (curRev < targetRev)
|
||||
{
|
||||
curRev++;
|
||||
neededChangesets.push(curRev);
|
||||
}
|
||||
|
||||
async.series([
|
||||
//get all needed data out of the database
|
||||
function(callback)
|
||||
{
|
||||
async.parallel([
|
||||
//get the atext of the key revision
|
||||
function (callback)
|
||||
{
|
||||
db.getSub("pad:"+_this.id+":revs:"+keyRev, ["meta", "atext"], function(err, _atext)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
atext = Changeset.cloneAText(_atext);
|
||||
callback();
|
||||
});
|
||||
},
|
||||
//get all needed changesets
|
||||
function (callback)
|
||||
{
|
||||
async.forEach(neededChangesets, function(item, callback)
|
||||
{
|
||||
_this.getRevisionChangeset(item, function(err, changeset)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
changesets[item] = changeset;
|
||||
callback();
|
||||
});
|
||||
}, callback);
|
||||
}
|
||||
], callback);
|
||||
},
|
||||
//apply all changesets to the key changeset
|
||||
function(callback)
|
||||
{
|
||||
var apool = _this.apool();
|
||||
var curRev = keyRev;
|
||||
|
||||
while (curRev < targetRev)
|
||||
{
|
||||
curRev++;
|
||||
var cs = changesets[curRev];
|
||||
atext = Changeset.applyToAText(cs, atext, apool);
|
||||
}
|
||||
|
||||
callback(null);
|
||||
}
|
||||
], function(err)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
callback(null, atext);
|
||||
});
|
||||
};
|
||||
|
||||
Pad.prototype.getKeyRevisionNumber = function getKeyRevisionNumber(revNum) {
|
||||
return Math.floor(revNum / 100) * 100;
|
||||
};
|
||||
|
||||
Pad.prototype.text = function text() {
|
||||
return this.atext.text;
|
||||
};
|
||||
|
||||
Pad.prototype.setText = function setText(newText) {
|
||||
//clean the new text
|
||||
newText = exports.cleanText(newText);
|
||||
|
||||
var oldText = this.text();
|
||||
|
||||
//create the changeset
|
||||
var changeset = Changeset.makeSplice(oldText, 0, oldText.length-1, newText);
|
||||
|
||||
//append the changeset
|
||||
this.appendRevision(changeset);
|
||||
};
|
||||
|
||||
Pad.prototype.appendChatMessage = function appendChatMessage(text, userId, time) {
|
||||
this.chatHead++;
|
||||
//save the chat entry in the database
|
||||
db.set("pad:"+this.id+":chat:"+this.chatHead, {"text": text, "userId": userId, "time": time});
|
||||
//save the new chat head
|
||||
db.setSub("pad:"+this.id, ["chatHead"], this.chatHead);
|
||||
};
|
||||
|
||||
Pad.prototype.getChatMessage = function getChatMessage(entryNum, callback) {
|
||||
var _this = this;
|
||||
var entry;
|
||||
|
||||
async.series([
|
||||
//get the chat entry
|
||||
function(callback)
|
||||
{
|
||||
db.get("pad:"+_this.id+":chat:"+entryNum, function(err, _entry)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
entry = _entry;
|
||||
callback();
|
||||
});
|
||||
},
|
||||
//add the authorName
|
||||
function(callback)
|
||||
{
|
||||
//this chat message doesn't exist, return null
|
||||
if(entry == null)
|
||||
{
|
||||
callback();
|
||||
return;
|
||||
}
|
||||
|
||||
//get the authorName
|
||||
authorManager.getAuthorName(entry.userId, function(err, authorName)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
entry.userName = authorName;
|
||||
callback();
|
||||
});
|
||||
}
|
||||
], function(err)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
callback(null, entry);
|
||||
});
|
||||
};
|
||||
|
||||
Pad.prototype.getLastChatMessages = function getLastChatMessages(count, callback) {
|
||||
//return an empty array if there are no chat messages
|
||||
if(this.chatHead == -1)
|
||||
{
|
||||
callback(null, []);
|
||||
return;
|
||||
}
|
||||
|
||||
var _this = this;
|
||||
|
||||
//works only if we decrement the amount, for some reason
|
||||
count--;
|
||||
|
||||
//set the startpoint
|
||||
var start = this.chatHead-count;
|
||||
if(start < 0)
|
||||
start = 0;
|
||||
|
||||
//set the endpoint
|
||||
var end = this.chatHead;
|
||||
|
||||
//collect the numbers of chat entries and in which order we need them
|
||||
var neededEntries = [];
|
||||
var order = 0;
|
||||
for(var i=start;i<=end; i++)
|
||||
{
|
||||
neededEntries.push({entryNum:i, order: order});
|
||||
order++;
|
||||
}
|
||||
|
||||
//get all entries out of the database
|
||||
var entries = [];
|
||||
async.forEach(neededEntries, function(entryObject, callback)
|
||||
{
|
||||
_this.getChatMessage(entryObject.entryNum, function(err, entry)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
entries[entryObject.order] = entry;
|
||||
callback();
|
||||
});
|
||||
}, function(err)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//sort out broken chat entries
|
||||
//it looks like in happend in the past that the chat head was
|
||||
//incremented, but the chat message wasn't added
|
||||
var cleanedEntries = [];
|
||||
for(var i=0;i<entries.length;i++)
|
||||
{
|
||||
if(entries[i]!=null)
|
||||
cleanedEntries.push(entries[i]);
|
||||
else
|
||||
console.warn("WARNING: Found broken chat entry in pad " + _this.id);
|
||||
}
|
||||
|
||||
callback(null, cleanedEntries);
|
||||
});
|
||||
};
|
||||
|
||||
Pad.prototype.init = function init(text, callback) {
|
||||
var _this = this;
|
||||
|
||||
//replace text with default text if text isn't set
|
||||
if(text == null)
|
||||
{
|
||||
text = settings.defaultPadText;
|
||||
}
|
||||
|
||||
//try to load the pad
|
||||
db.get("pad:"+this.id, function(err, value)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//if this pad exists, load it
|
||||
if(value != null)
|
||||
{
|
||||
_this.head = value.head;
|
||||
_this.atext = value.atext;
|
||||
_this.pool = _this.pool.fromJsonable(value.pool);
|
||||
|
||||
//ensure we have a local chatHead variable
|
||||
if(value.chatHead != null)
|
||||
_this.chatHead = value.chatHead;
|
||||
else
|
||||
_this.chatHead = -1;
|
||||
|
||||
//ensure we have a local publicStatus variable
|
||||
if(value.publicStatus != null)
|
||||
_this.publicStatus = value.publicStatus;
|
||||
else
|
||||
_this.publicStatus = false;
|
||||
|
||||
//ensure we have a local passwordHash variable
|
||||
if(value.passwordHash != null)
|
||||
_this.passwordHash = value.passwordHash;
|
||||
else
|
||||
_this.passwordHash = null;
|
||||
}
|
||||
//this pad doesn't exist, so create it
|
||||
else
|
||||
{
|
||||
var firstChangeset = Changeset.makeSplice("\n", 0, 0, exports.cleanText(text));
|
||||
|
||||
_this.appendRevision(firstChangeset, '');
|
||||
}
|
||||
|
||||
callback(null);
|
||||
});
|
||||
};
|
||||
|
||||
Pad.prototype.remove = function remove(callback) {
|
||||
var padID = this.id;
|
||||
var _this = this;
|
||||
|
||||
//kick everyone from this pad
|
||||
padMessageHandler.kickSessionsFromPad(padID);
|
||||
|
||||
async.series([
|
||||
//delete all relations
|
||||
function(callback)
|
||||
{
|
||||
async.parallel([
|
||||
//is it a group pad? -> delete the entry of this pad in the group
|
||||
function(callback)
|
||||
{
|
||||
//is it a group pad?
|
||||
if(padID.indexOf("$")!=-1)
|
||||
{
|
||||
var groupID = padID.substring(0,padID.indexOf("$"));
|
||||
|
||||
db.get("group:" + groupID, function (err, group)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//remove the pad entry
|
||||
delete group.pads[padID];
|
||||
|
||||
//set the new value
|
||||
db.set("group:" + groupID, group);
|
||||
|
||||
callback();
|
||||
});
|
||||
}
|
||||
//its no group pad, nothing to do here
|
||||
else
|
||||
{
|
||||
callback();
|
||||
}
|
||||
},
|
||||
//remove the readonly entries
|
||||
function(callback)
|
||||
{
|
||||
readOnlyManager.getReadOnlyId(padID, function(err, readonlyID)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
db.remove("pad2readonly:" + padID);
|
||||
db.remove("readonly2pad:" + readonlyID);
|
||||
|
||||
callback();
|
||||
});
|
||||
},
|
||||
//delete all chat messages
|
||||
function(callback)
|
||||
{
|
||||
var chatHead = _this.chatHead;
|
||||
|
||||
for(var i=0;i<=chatHead;i++)
|
||||
{
|
||||
db.remove("pad:"+padID+":chat:"+i);
|
||||
}
|
||||
|
||||
callback();
|
||||
},
|
||||
//delete all revisions
|
||||
function(callback)
|
||||
{
|
||||
var revHead = _this.head;
|
||||
|
||||
for(var i=0;i<=revHead;i++)
|
||||
{
|
||||
db.remove("pad:"+padID+":revs:"+i);
|
||||
}
|
||||
|
||||
callback();
|
||||
}
|
||||
], callback);
|
||||
},
|
||||
//delete the pad entry and delete pad from padManager
|
||||
function(callback)
|
||||
{
|
||||
db.remove("pad:"+padID);
|
||||
padManager.unloadPad(padID);
|
||||
callback();
|
||||
}
|
||||
], function(err)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
callback();
|
||||
});
|
||||
};
|
||||
//set in db
|
||||
Pad.prototype.setPublicStatus = function setPublicStatus(publicStatus) {
|
||||
this.publicStatus = publicStatus;
|
||||
db.setSub("pad:"+this.id, ["publicStatus"], this.publicStatus);
|
||||
};
|
||||
|
||||
Pad.prototype.setPassword = function setPassword(password) {
|
||||
this.passwordHash = password == null ? null : hash(password, generateSalt());
|
||||
db.setSub("pad:"+this.id, ["passwordHash"], this.passwordHash);
|
||||
};
|
||||
|
||||
Pad.prototype.isCorrectPassword = function isCorrectPassword(password) {
|
||||
return compare(this.passwordHash, password);
|
||||
};
|
||||
|
||||
Pad.prototype.isPasswordProtected = function isPasswordProtected() {
|
||||
return this.passwordHash != null;
|
||||
};
|
||||
|
||||
/* Crypto helper methods */
|
||||
|
||||
function hash(password, salt)
|
||||
{
|
||||
var shasum = crypto.createHash('sha512');
|
||||
shasum.update(password + salt);
|
||||
return shasum.digest("hex") + "$" + salt;
|
||||
}
|
||||
|
||||
function generateSalt()
|
||||
{
|
||||
return randomString(86);
|
||||
}
|
||||
|
||||
function compare(hashStr, password)
|
||||
{
|
||||
return hash(password, hashStr.split("$")[1]) === hashStr;
|
||||
}
|
164
src/node/db/PadManager.js
Normal file
|
@ -0,0 +1,164 @@
|
|||
/**
|
||||
* The Pad Manager is a Factory for pad Objects
|
||||
*/
|
||||
|
||||
/*
|
||||
* 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
|
||||
*
|
||||
* 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 ERR = require("async-stacktrace");
|
||||
var customError = require("../utils/customError");
|
||||
var Pad = require("../db/Pad").Pad;
|
||||
var db = require("./DB").db;
|
||||
|
||||
/**
|
||||
* An Object containing all known Pads. Provides "get" and "set" functions,
|
||||
* which should be used instead of indexing with brackets. These prepend a
|
||||
* colon to the key, to avoid conflicting with built-in Object methods or with
|
||||
* these functions themselves.
|
||||
*
|
||||
* If this is needed in other places, it would be wise to make this a prototype
|
||||
* that's defined somewhere more sensible.
|
||||
*/
|
||||
var globalPads = {
|
||||
get: function (name) { return this[':'+name]; },
|
||||
set: function (name, value) { this[':'+name] = value; },
|
||||
remove: function (name) { delete this[':'+name]; }
|
||||
};
|
||||
|
||||
/**
|
||||
* An array of padId transformations. These represent changes in pad name policy over
|
||||
* time, and allow us to "play back" these changes so legacy padIds can be found.
|
||||
*/
|
||||
var padIdTransforms = [
|
||||
[/\s+/g, '_']
|
||||
];
|
||||
|
||||
/**
|
||||
* Returns a Pad Object with the callback
|
||||
* @param id A String with the id of the pad
|
||||
* @param {Function} callback
|
||||
*/
|
||||
exports.getPad = function(id, text, callback)
|
||||
{
|
||||
//check if this is a valid padId
|
||||
if(!exports.isValidPadId(id))
|
||||
{
|
||||
callback(new customError(id + " is not a valid padId","apierror"));
|
||||
return;
|
||||
}
|
||||
|
||||
//make text an optional parameter
|
||||
if(typeof text == "function")
|
||||
{
|
||||
callback = text;
|
||||
text = null;
|
||||
}
|
||||
|
||||
//check if this is a valid text
|
||||
if(text != null)
|
||||
{
|
||||
//check if text is a string
|
||||
if(typeof text != "string")
|
||||
{
|
||||
callback(new customError("text is not a string","apierror"));
|
||||
return;
|
||||
}
|
||||
|
||||
//check if text is less than 100k chars
|
||||
if(text.length > 100000)
|
||||
{
|
||||
callback(new customError("text must be less than 100k chars","apierror"));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
var pad = globalPads.get(id);
|
||||
|
||||
//return pad if its already loaded
|
||||
if(pad != null)
|
||||
{
|
||||
callback(null, pad);
|
||||
}
|
||||
//try to load pad
|
||||
else
|
||||
{
|
||||
pad = new Pad(id);
|
||||
|
||||
//initalize the pad
|
||||
pad.init(text, function(err)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
globalPads.set(id, pad);
|
||||
callback(null, pad);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//checks if a pad exists
|
||||
exports.doesPadExists = function(padId, callback)
|
||||
{
|
||||
db.get("pad:"+padId, function(err, value)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
callback(null, value != null);
|
||||
});
|
||||
}
|
||||
|
||||
//returns a sanitized padId, respecting legacy pad id formats
|
||||
exports.sanitizePadId = function(padId, callback) {
|
||||
var transform_index = arguments[2] || 0;
|
||||
//we're out of possible transformations, so just return it
|
||||
if(transform_index >= padIdTransforms.length)
|
||||
{
|
||||
callback(padId);
|
||||
}
|
||||
//check if padId exists
|
||||
else
|
||||
{
|
||||
exports.doesPadExists(padId, function(junk, exists)
|
||||
{
|
||||
if(exists)
|
||||
{
|
||||
callback(padId);
|
||||
}
|
||||
else
|
||||
{
|
||||
//get the next transformation *that's different*
|
||||
var transformedPadId = padId;
|
||||
while(transformedPadId == padId && transform_index < padIdTransforms.length)
|
||||
{
|
||||
transformedPadId = padId.replace(padIdTransforms[transform_index][0], padIdTransforms[transform_index][1]);
|
||||
transform_index += 1;
|
||||
}
|
||||
//check the next transform
|
||||
exports.sanitizePadId(transformedPadId, callback, transform_index);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
exports.isValidPadId = function(padId)
|
||||
{
|
||||
return /^(g.[a-zA-Z0-9]{16}\$)?[^$]{1,50}$/.test(padId);
|
||||
}
|
||||
|
||||
//removes a pad from the array
|
||||
exports.unloadPad = function(padId)
|
||||
{
|
||||
if(globalPads.get(padId))
|
||||
globalPads.remove(padId);
|
||||
}
|
74
src/node/db/ReadOnlyManager.js
Normal file
|
@ -0,0 +1,74 @@
|
|||
/**
|
||||
* The ReadOnlyManager manages the database and rendering releated to read only pads
|
||||
*/
|
||||
|
||||
/*
|
||||
* 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
|
||||
*
|
||||
* 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 CommonCode = require('../utils/common_code');
|
||||
var ERR = require("async-stacktrace");
|
||||
var db = require("./DB").db;
|
||||
var async = require("async");
|
||||
var randomString = CommonCode.require('/pad_utils').randomString;
|
||||
|
||||
/**
|
||||
* returns a read only id for a pad
|
||||
* @param {String} padId the id of the pad
|
||||
*/
|
||||
exports.getReadOnlyId = function (padId, callback)
|
||||
{
|
||||
var readOnlyId;
|
||||
|
||||
async.waterfall([
|
||||
//check if there is a pad2readonly entry
|
||||
function(callback)
|
||||
{
|
||||
db.get("pad2readonly:" + padId, callback);
|
||||
},
|
||||
function(dbReadOnlyId, callback)
|
||||
{
|
||||
//there is no readOnly Entry in the database, let's create one
|
||||
if(dbReadOnlyId == null)
|
||||
{
|
||||
readOnlyId = "r." + randomString(16);
|
||||
|
||||
db.set("pad2readonly:" + padId, readOnlyId);
|
||||
db.set("readonly2pad:" + readOnlyId, padId);
|
||||
}
|
||||
//there is a readOnly Entry in the database, let's take this one
|
||||
else
|
||||
{
|
||||
readOnlyId = dbReadOnlyId;
|
||||
}
|
||||
|
||||
callback();
|
||||
}
|
||||
], function(err)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
//return the results
|
||||
callback(null, readOnlyId);
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* returns a the padId for a read only id
|
||||
* @param {String} readOnlyId read only id
|
||||
*/
|
||||
exports.getPadId = function(readOnlyId, callback)
|
||||
{
|
||||
db.get("readonly2pad:" + readOnlyId, callback);
|
||||
}
|
280
src/node/db/SecurityManager.js
Normal file
|
@ -0,0 +1,280 @@
|
|||
/**
|
||||
* Controls the security of pad access
|
||||
*/
|
||||
|
||||
/*
|
||||
* 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
|
||||
*
|
||||
* 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 CommonCode = require('../utils/common_code');
|
||||
var ERR = require("async-stacktrace");
|
||||
var db = require("./DB").db;
|
||||
var async = require("async");
|
||||
var authorManager = require("./AuthorManager");
|
||||
var padManager = require("./PadManager");
|
||||
var sessionManager = require("./SessionManager");
|
||||
var settings = require("../utils/Settings")
|
||||
var randomString = CommonCode.require('/pad_utils').randomString;
|
||||
|
||||
/**
|
||||
* This function controlls the access to a pad, it checks if the user can access a pad.
|
||||
* @param padID the pad the user wants to access
|
||||
* @param sesssionID the session the user has (set via api)
|
||||
* @param token the token of the author (randomly generated at client side, used for public pads)
|
||||
* @param password the password the user has given to access this pad, can be null
|
||||
* @param callback will be called with (err, {accessStatus: grant|deny|wrongPassword|needPassword, authorID: a.xxxxxx})
|
||||
*/
|
||||
exports.checkAccess = function (padID, sessionID, token, password, callback)
|
||||
{
|
||||
var statusObject;
|
||||
|
||||
// a valid session is required (api-only mode)
|
||||
if(settings.requireSession)
|
||||
{
|
||||
// no sessionID, access is denied
|
||||
if(!sessionID)
|
||||
{
|
||||
callback(null, {accessStatus: "deny"});
|
||||
return;
|
||||
}
|
||||
}
|
||||
// a session is not required, so we'll check if it's a public pad
|
||||
else
|
||||
{
|
||||
// it's not a group pad, means we can grant access
|
||||
if(padID.indexOf("$") == -1)
|
||||
{
|
||||
//get author for this token
|
||||
authorManager.getAuthor4Token(token, function(err, author)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
// assume user has access
|
||||
statusObject = {accessStatus: "grant", authorID: author};
|
||||
// user can't create pads
|
||||
if(settings.editOnly)
|
||||
{
|
||||
// check if pad exists
|
||||
padManager.doesPadExists(padID, function(err, exists)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
// pad doesn't exist - user can't have access
|
||||
if(!exists) statusObject.accessStatus = "deny";
|
||||
// grant or deny access, with author of token
|
||||
callback(null, statusObject);
|
||||
});
|
||||
}
|
||||
// user may create new pads - no need to check anything
|
||||
else
|
||||
{
|
||||
// grant access, with author of token
|
||||
callback(null, statusObject);
|
||||
}
|
||||
})
|
||||
|
||||
//don't continue
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
var groupID = padID.split("$")[0];
|
||||
var padExists = false;
|
||||
var validSession = false;
|
||||
var sessionAuthor;
|
||||
var tokenAuthor;
|
||||
var isPublic;
|
||||
var isPasswordProtected;
|
||||
var passwordStatus = password == null ? "notGiven" : "wrong"; // notGiven, correct, wrong
|
||||
|
||||
async.series([
|
||||
//get basic informations from the database
|
||||
function(callback)
|
||||
{
|
||||
async.parallel([
|
||||
//does pad exists
|
||||
function(callback)
|
||||
{
|
||||
padManager.doesPadExists(padID, function(err, exists)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
padExists = exists;
|
||||
callback();
|
||||
});
|
||||
},
|
||||
//get informations about this session
|
||||
function(callback)
|
||||
{
|
||||
sessionManager.getSessionInfo(sessionID, function(err, sessionInfo)
|
||||
{
|
||||
//skip session validation if the session doesn't exists
|
||||
if(err && err.message == "sessionID does not exist")
|
||||
{
|
||||
callback();
|
||||
return;
|
||||
}
|
||||
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
var now = Math.floor(new Date().getTime()/1000);
|
||||
|
||||
//is it for this group? and is validUntil still ok? --> validSession
|
||||
if(sessionInfo.groupID == groupID && sessionInfo.validUntil > now)
|
||||
{
|
||||
validSession = true;
|
||||
}
|
||||
|
||||
sessionAuthor = sessionInfo.authorID;
|
||||
|
||||
callback();
|
||||
});
|
||||
},
|
||||
//get author for token
|
||||
function(callback)
|
||||
{
|
||||
//get author for this token
|
||||
authorManager.getAuthor4Token(token, function(err, author)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
tokenAuthor = author;
|
||||
callback();
|
||||
});
|
||||
}
|
||||
], callback);
|
||||
},
|
||||
//get more informations of this pad, if avaiable
|
||||
function(callback)
|
||||
{
|
||||
//skip this if the pad doesn't exists
|
||||
if(padExists == false)
|
||||
{
|
||||
callback();
|
||||
return;
|
||||
}
|
||||
|
||||
padManager.getPad(padID, function(err, pad)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//is it a public pad?
|
||||
isPublic = pad.getPublicStatus();
|
||||
|
||||
//is it password protected?
|
||||
isPasswordProtected = pad.isPasswordProtected();
|
||||
|
||||
//is password correct?
|
||||
if(isPasswordProtected && password && pad.isCorrectPassword(password))
|
||||
{
|
||||
passwordStatus = "correct";
|
||||
}
|
||||
|
||||
callback();
|
||||
});
|
||||
},
|
||||
function(callback)
|
||||
{
|
||||
//- a valid session for this group is avaible AND pad exists
|
||||
if(validSession && padExists)
|
||||
{
|
||||
//- the pad is not password protected
|
||||
if(!isPasswordProtected)
|
||||
{
|
||||
//--> grant access
|
||||
statusObject = {accessStatus: "grant", authorID: sessionAuthor};
|
||||
}
|
||||
//- the pad is password protected and password is correct
|
||||
else if(isPasswordProtected && passwordStatus == "correct")
|
||||
{
|
||||
//--> grant access
|
||||
statusObject = {accessStatus: "grant", authorID: sessionAuthor};
|
||||
}
|
||||
//- the pad is password protected but wrong password given
|
||||
else if(isPasswordProtected && passwordStatus == "wrong")
|
||||
{
|
||||
//--> deny access, ask for new password and tell them that the password is wrong
|
||||
statusObject = {accessStatus: "wrongPassword"};
|
||||
}
|
||||
//- the pad is password protected but no password given
|
||||
else if(isPasswordProtected && passwordStatus == "notGiven")
|
||||
{
|
||||
//--> ask for password
|
||||
statusObject = {accessStatus: "needPassword"};
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Error("Ops, something wrong happend");
|
||||
}
|
||||
}
|
||||
//- a valid session for this group avaible but pad doesn't exists
|
||||
else if(validSession && !padExists)
|
||||
{
|
||||
//--> grant access
|
||||
statusObject = {accessStatus: "grant", authorID: sessionAuthor};
|
||||
//--> deny access if user isn't allowed to create the pad
|
||||
if(settings.editOnly) statusObject.accessStatus = "deny";
|
||||
}
|
||||
// there is no valid session avaiable AND pad exists
|
||||
else if(!validSession && padExists)
|
||||
{
|
||||
//-- its public and not password protected
|
||||
if(isPublic && !isPasswordProtected)
|
||||
{
|
||||
//--> grant access, with author of token
|
||||
statusObject = {accessStatus: "grant", authorID: tokenAuthor};
|
||||
}
|
||||
//- its public and password protected and password is correct
|
||||
else if(isPublic && isPasswordProtected && passwordStatus == "correct")
|
||||
{
|
||||
//--> grant access, with author of token
|
||||
statusObject = {accessStatus: "grant", authorID: tokenAuthor};
|
||||
}
|
||||
//- its public and the pad is password protected but wrong password given
|
||||
else if(isPublic && isPasswordProtected && passwordStatus == "wrong")
|
||||
{
|
||||
//--> deny access, ask for new password and tell them that the password is wrong
|
||||
statusObject = {accessStatus: "wrongPassword"};
|
||||
}
|
||||
//- its public and the pad is password protected but no password given
|
||||
else if(isPublic && isPasswordProtected && passwordStatus == "notGiven")
|
||||
{
|
||||
//--> ask for password
|
||||
statusObject = {accessStatus: "needPassword"};
|
||||
}
|
||||
//- its not public
|
||||
else if(!isPublic)
|
||||
{
|
||||
//--> deny access
|
||||
statusObject = {accessStatus: "deny"};
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Error("Ops, something wrong happend");
|
||||
}
|
||||
}
|
||||
// there is no valid session avaiable AND pad doesn't exists
|
||||
else
|
||||
{
|
||||
//--> deny access
|
||||
statusObject = {accessStatus: "deny"};
|
||||
}
|
||||
|
||||
callback();
|
||||
}
|
||||
], function(err)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
callback(null, statusObject);
|
||||
});
|
||||
}
|
367
src/node/db/SessionManager.js
Normal file
|
@ -0,0 +1,367 @@
|
|||
/**
|
||||
* The Session Manager provides functions to manage session in the database
|
||||
*/
|
||||
|
||||
/*
|
||||
* 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
|
||||
*
|
||||
* 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 CommonCode = require('../utils/common_code');
|
||||
var ERR = require("async-stacktrace");
|
||||
var customError = require("../utils/customError");
|
||||
var randomString = CommonCode.require('/pad_utils').randomString;
|
||||
var db = require("./DB").db;
|
||||
var async = require("async");
|
||||
var groupMangager = require("./GroupManager");
|
||||
var authorMangager = require("./AuthorManager");
|
||||
|
||||
exports.doesSessionExist = function(sessionID, callback)
|
||||
{
|
||||
//check if the database entry of this session exists
|
||||
db.get("session:" + sessionID, function (err, session)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
callback(null, session != null);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new session between an author and a group
|
||||
*/
|
||||
exports.createSession = function(groupID, authorID, validUntil, callback)
|
||||
{
|
||||
var sessionID;
|
||||
|
||||
async.series([
|
||||
//check if group exists
|
||||
function(callback)
|
||||
{
|
||||
groupMangager.doesGroupExist(groupID, function(err, exists)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//group does not exist
|
||||
if(exists == false)
|
||||
{
|
||||
callback(new customError("groupID does not exist","apierror"));
|
||||
}
|
||||
//everything is fine, continue
|
||||
else
|
||||
{
|
||||
callback();
|
||||
}
|
||||
});
|
||||
},
|
||||
//check if author exists
|
||||
function(callback)
|
||||
{
|
||||
authorMangager.doesAuthorExists(authorID, function(err, exists)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//author does not exist
|
||||
if(exists == false)
|
||||
{
|
||||
callback(new customError("authorID does not exist","apierror"));
|
||||
}
|
||||
//everything is fine, continue
|
||||
else
|
||||
{
|
||||
callback();
|
||||
}
|
||||
});
|
||||
},
|
||||
//check validUntil and create the session db entry
|
||||
function(callback)
|
||||
{
|
||||
//check if rev is a number
|
||||
if(typeof validUntil != "number")
|
||||
{
|
||||
//try to parse the number
|
||||
if(!isNaN(parseInt(validUntil)))
|
||||
{
|
||||
validUntil = parseInt(validUntil);
|
||||
}
|
||||
else
|
||||
{
|
||||
callback(new customError("validUntil is not a number","apierror"));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
//ensure this is not a negativ number
|
||||
if(validUntil < 0)
|
||||
{
|
||||
callback(new customError("validUntil is a negativ number","apierror"));
|
||||
return;
|
||||
}
|
||||
|
||||
//ensure this is not a float value
|
||||
if(!is_int(validUntil))
|
||||
{
|
||||
callback(new customError("validUntil is a float value","apierror"));
|
||||
return;
|
||||
}
|
||||
|
||||
//check if validUntil is in the future
|
||||
if(Math.floor(new Date().getTime()/1000) > validUntil)
|
||||
{
|
||||
callback(new customError("validUntil is in the past","apierror"));
|
||||
return;
|
||||
}
|
||||
|
||||
//generate sessionID
|
||||
sessionID = "s." + randomString(16);
|
||||
|
||||
//set the session into the database
|
||||
db.set("session:" + sessionID, {"groupID": groupID, "authorID": authorID, "validUntil": validUntil});
|
||||
|
||||
callback();
|
||||
},
|
||||
//set the group2sessions entry
|
||||
function(callback)
|
||||
{
|
||||
//get the entry
|
||||
db.get("group2sessions:" + groupID, function(err, group2sessions)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//the entry doesn't exist so far, let's create it
|
||||
if(group2sessions == null)
|
||||
{
|
||||
group2sessions = {sessionIDs : {}};
|
||||
}
|
||||
|
||||
//add the entry for this session
|
||||
group2sessions.sessionIDs[sessionID] = 1;
|
||||
|
||||
//save the new element back
|
||||
db.set("group2sessions:" + groupID, group2sessions);
|
||||
|
||||
callback();
|
||||
});
|
||||
},
|
||||
//set the author2sessions entry
|
||||
function(callback)
|
||||
{
|
||||
//get the entry
|
||||
db.get("author2sessions:" + authorID, function(err, author2sessions)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//the entry doesn't exist so far, let's create it
|
||||
if(author2sessions == null)
|
||||
{
|
||||
author2sessions = {sessionIDs : {}};
|
||||
}
|
||||
|
||||
//add the entry for this session
|
||||
author2sessions.sessionIDs[sessionID] = 1;
|
||||
|
||||
//save the new element back
|
||||
db.set("author2sessions:" + authorID, author2sessions);
|
||||
|
||||
callback();
|
||||
});
|
||||
}
|
||||
], function(err)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//return error and sessionID
|
||||
callback(null, {sessionID: sessionID});
|
||||
})
|
||||
}
|
||||
|
||||
exports.getSessionInfo = function(sessionID, callback)
|
||||
{
|
||||
//check if the database entry of this session exists
|
||||
db.get("session:" + sessionID, function (err, session)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//session does not exists
|
||||
if(session == null)
|
||||
{
|
||||
callback(new customError("sessionID does not exist","apierror"))
|
||||
}
|
||||
//everything is fine, return the sessioninfos
|
||||
else
|
||||
{
|
||||
callback(null, session);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a session
|
||||
*/
|
||||
exports.deleteSession = function(sessionID, callback)
|
||||
{
|
||||
var authorID, groupID;
|
||||
var group2sessions, author2sessions;
|
||||
|
||||
async.series([
|
||||
function(callback)
|
||||
{
|
||||
//get the session entry
|
||||
db.get("session:" + sessionID, function (err, session)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//session does not exists
|
||||
if(session == null)
|
||||
{
|
||||
callback(new customError("sessionID does not exist","apierror"))
|
||||
}
|
||||
//everything is fine, return the sessioninfos
|
||||
else
|
||||
{
|
||||
authorID = session.authorID;
|
||||
groupID = session.groupID;
|
||||
|
||||
callback();
|
||||
}
|
||||
});
|
||||
},
|
||||
//get the group2sessions entry
|
||||
function(callback)
|
||||
{
|
||||
db.get("group2sessions:" + groupID, function (err, _group2sessions)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
group2sessions = _group2sessions;
|
||||
callback();
|
||||
});
|
||||
},
|
||||
//get the author2sessions entry
|
||||
function(callback)
|
||||
{
|
||||
db.get("author2sessions:" + authorID, function (err, _author2sessions)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
author2sessions = _author2sessions;
|
||||
callback();
|
||||
});
|
||||
},
|
||||
//remove the values from the database
|
||||
function(callback)
|
||||
{
|
||||
//remove the session
|
||||
db.remove("session:" + sessionID);
|
||||
|
||||
//remove session from group2sessions
|
||||
delete group2sessions.sessionIDs[sessionID];
|
||||
db.set("group2sessions:" + groupID, group2sessions);
|
||||
|
||||
//remove session from author2sessions
|
||||
delete author2sessions.sessionIDs[sessionID];
|
||||
db.set("author2sessions:" + authorID, author2sessions);
|
||||
|
||||
callback();
|
||||
}
|
||||
], function(err)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
callback();
|
||||
})
|
||||
}
|
||||
|
||||
exports.listSessionsOfGroup = function(groupID, callback)
|
||||
{
|
||||
groupMangager.doesGroupExist(groupID, function(err, exists)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//group does not exist
|
||||
if(exists == false)
|
||||
{
|
||||
callback(new customError("groupID does not exist","apierror"));
|
||||
}
|
||||
//everything is fine, continue
|
||||
else
|
||||
{
|
||||
listSessionsWithDBKey("group2sessions:" + groupID, callback);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
exports.listSessionsOfAuthor = function(authorID, callback)
|
||||
{
|
||||
authorMangager.doesAuthorExists(authorID, function(err, exists)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//group does not exist
|
||||
if(exists == false)
|
||||
{
|
||||
callback(new customError("authorID does not exist","apierror"));
|
||||
}
|
||||
//everything is fine, continue
|
||||
else
|
||||
{
|
||||
listSessionsWithDBKey("author2sessions:" + authorID, callback);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
//this function is basicly the code listSessionsOfAuthor and listSessionsOfGroup has in common
|
||||
function listSessionsWithDBKey (dbkey, callback)
|
||||
{
|
||||
var sessions;
|
||||
|
||||
async.series([
|
||||
function(callback)
|
||||
{
|
||||
//get the group2sessions entry
|
||||
db.get(dbkey, function(err, sessionObject)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
sessions = sessionObject ? sessionObject.sessionIDs : null;
|
||||
callback();
|
||||
});
|
||||
},
|
||||
function(callback)
|
||||
{
|
||||
//collect all sessionIDs in an arrary
|
||||
var sessionIDs = [];
|
||||
for (var i in sessions)
|
||||
{
|
||||
sessionIDs.push(i);
|
||||
}
|
||||
|
||||
//foreach trough the sessions and get the sessioninfos
|
||||
async.forEach(sessionIDs, function(sessionID, callback)
|
||||
{
|
||||
exports.getSessionInfo(sessionID, function(err, sessionInfo)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
sessions[sessionID] = sessionInfo;
|
||||
callback();
|
||||
});
|
||||
}, callback);
|
||||
}
|
||||
], function(err)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
callback(null, sessions);
|
||||
});
|
||||
}
|
||||
|
||||
//checks if a number is an int
|
||||
function is_int(value)
|
||||
{
|
||||
return (parseFloat(value) == parseInt(value)) && !isNaN(value)
|
||||
}
|
949
src/node/easysync_tests.js
Normal file
|
@ -0,0 +1,949 @@
|
|||
/**
|
||||
* I found this tests in the old Etherpad and used it to test if the Changeset library can be run on node.js.
|
||||
* It has no use for ep-lite, but I thought I keep it cause it may help someone to understand the Changeset library
|
||||
* https://github.com/ether/pad/blob/master/infrastructure/ace/www/easysync2_tests.js
|
||||
*/
|
||||
|
||||
/*
|
||||
* Copyright 2009 Google Inc., 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
|
||||
*
|
||||
* 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 CommonCode = require('./utils/common_code');
|
||||
var Changeset = CommonCode.require("/Changeset");
|
||||
var AttributePoolFactory = CommonCode.require("/AttributePoolFactory");
|
||||
|
||||
function random() {
|
||||
this.nextInt = function (maxValue) {
|
||||
return Math.floor(Math.random() * maxValue);
|
||||
}
|
||||
|
||||
this.nextDouble = function (maxValue) {
|
||||
return Math.random();
|
||||
}
|
||||
}
|
||||
|
||||
function runTests() {
|
||||
|
||||
function print(str) {
|
||||
console.log(str);
|
||||
}
|
||||
|
||||
function assert(code, optMsg) {
|
||||
if (!eval(code)) throw new Error("FALSE: " + (optMsg || code));
|
||||
}
|
||||
|
||||
function literal(v) {
|
||||
if ((typeof v) == "string") {
|
||||
return '"' + v.replace(/[\\\"]/g, '\\$1').replace(/\n/g, '\\n') + '"';
|
||||
} else
|
||||
return JSON.stringify(v);
|
||||
}
|
||||
|
||||
function assertEqualArrays(a, b) {
|
||||
assert("JSON.stringify(" + literal(a) + ") == JSON.stringify(" + literal(b) + ")");
|
||||
}
|
||||
|
||||
function assertEqualStrings(a, b) {
|
||||
assert(literal(a) + " == " + literal(b));
|
||||
}
|
||||
|
||||
function throughIterator(opsStr) {
|
||||
var iter = Changeset.opIterator(opsStr);
|
||||
var assem = Changeset.opAssembler();
|
||||
while (iter.hasNext()) {
|
||||
assem.append(iter.next());
|
||||
}
|
||||
return assem.toString();
|
||||
}
|
||||
|
||||
function throughSmartAssembler(opsStr) {
|
||||
var iter = Changeset.opIterator(opsStr);
|
||||
var assem = Changeset.smartOpAssembler();
|
||||
while (iter.hasNext()) {
|
||||
assem.append(iter.next());
|
||||
}
|
||||
assem.endDocument();
|
||||
return assem.toString();
|
||||
}
|
||||
|
||||
(function () {
|
||||
print("> throughIterator");
|
||||
var x = '-c*3*4+6|3=az*asdf0*1*2*3+1=1-1+1*0+1=1-1+1|c=c-1';
|
||||
assert("throughIterator(" + literal(x) + ") == " + literal(x));
|
||||
})();
|
||||
|
||||
(function () {
|
||||
print("> throughSmartAssembler");
|
||||
var x = '-c*3*4+6|3=az*asdf0*1*2*3+1=1-1+1*0+1=1-1+1|c=c-1';
|
||||
assert("throughSmartAssembler(" + literal(x) + ") == " + literal(x));
|
||||
})();
|
||||
|
||||
function applyMutations(mu, arrayOfArrays) {
|
||||
arrayOfArrays.forEach(function (a) {
|
||||
var result = mu[a[0]].apply(mu, a.slice(1));
|
||||
if (a[0] == 'remove' && a[3]) {
|
||||
assertEqualStrings(a[3], result);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function mutationsToChangeset(oldLen, arrayOfArrays) {
|
||||
var assem = Changeset.smartOpAssembler();
|
||||
var op = Changeset.newOp();
|
||||
var bank = Changeset.stringAssembler();
|
||||
var oldPos = 0;
|
||||
var newLen = 0;
|
||||
arrayOfArrays.forEach(function (a) {
|
||||
if (a[0] == 'skip') {
|
||||
op.opcode = '=';
|
||||
op.chars = a[1];
|
||||
op.lines = (a[2] || 0);
|
||||
assem.append(op);
|
||||
oldPos += op.chars;
|
||||
newLen += op.chars;
|
||||
} else if (a[0] == 'remove') {
|
||||
op.opcode = '-';
|
||||
op.chars = a[1];
|
||||
op.lines = (a[2] || 0);
|
||||
assem.append(op);
|
||||
oldPos += op.chars;
|
||||
} else if (a[0] == 'insert') {
|
||||
op.opcode = '+';
|
||||
bank.append(a[1]);
|
||||
op.chars = a[1].length;
|
||||
op.lines = (a[2] || 0);
|
||||
assem.append(op);
|
||||
newLen += op.chars;
|
||||
}
|
||||
});
|
||||
newLen += oldLen - oldPos;
|
||||
assem.endDocument();
|
||||
return Changeset.pack(oldLen, newLen, assem.toString(), bank.toString());
|
||||
}
|
||||
|
||||
function runMutationTest(testId, origLines, muts, correct) {
|
||||
print("> runMutationTest#" + testId);
|
||||
var lines = origLines.slice();
|
||||
var mu = Changeset.textLinesMutator(lines);
|
||||
applyMutations(mu, muts);
|
||||
mu.close();
|
||||
assertEqualArrays(correct, lines);
|
||||
|
||||
var inText = origLines.join('');
|
||||
var cs = mutationsToChangeset(inText.length, muts);
|
||||
lines = origLines.slice();
|
||||
Changeset.mutateTextLines(cs, lines);
|
||||
assertEqualArrays(correct, lines);
|
||||
|
||||
var correctText = correct.join('');
|
||||
//print(literal(cs));
|
||||
var outText = Changeset.applyToText(cs, inText);
|
||||
assertEqualStrings(correctText, outText);
|
||||
}
|
||||
|
||||
runMutationTest(1, ["apple\n", "banana\n", "cabbage\n", "duffle\n", "eggplant\n"], [
|
||||
['remove', 1, 0, "a"],
|
||||
['insert', "tu"],
|
||||
['remove', 1, 0, "p"],
|
||||
['skip', 4, 1],
|
||||
['skip', 7, 1],
|
||||
['insert', "cream\npie\n", 2],
|
||||
['skip', 2],
|
||||
['insert', "bot"],
|
||||
['insert', "\n", 1],
|
||||
['insert', "bu"],
|
||||
['skip', 3],
|
||||
['remove', 3, 1, "ge\n"],
|
||||
['remove', 6, 0, "duffle"]
|
||||
], ["tuple\n", "banana\n", "cream\n", "pie\n", "cabot\n", "bubba\n", "eggplant\n"]);
|
||||
|
||||
runMutationTest(2, ["apple\n", "banana\n", "cabbage\n", "duffle\n", "eggplant\n"], [
|
||||
['remove', 1, 0, "a"],
|
||||
['remove', 1, 0, "p"],
|
||||
['insert', "tu"],
|
||||
['skip', 11, 2],
|
||||
['insert', "cream\npie\n", 2],
|
||||
['skip', 2],
|
||||
['insert', "bot"],
|
||||
['insert', "\n", 1],
|
||||
['insert', "bu"],
|
||||
['skip', 3],
|
||||
['remove', 3, 1, "ge\n"],
|
||||
['remove', 6, 0, "duffle"]
|
||||
], ["tuple\n", "banana\n", "cream\n", "pie\n", "cabot\n", "bubba\n", "eggplant\n"]);
|
||||
|
||||
runMutationTest(3, ["apple\n", "banana\n", "cabbage\n", "duffle\n", "eggplant\n"], [
|
||||
['remove', 6, 1, "apple\n"],
|
||||
['skip', 15, 2],
|
||||
['skip', 6],
|
||||
['remove', 1, 1, "\n"],
|
||||
['remove', 8, 0, "eggplant"],
|
||||
['skip', 1, 1]
|
||||
], ["banana\n", "cabbage\n", "duffle\n"]);
|
||||
|
||||
runMutationTest(4, ["15\n"], [
|
||||
['skip', 1],
|
||||
['insert', "\n2\n3\n4\n", 4],
|
||||
['skip', 2, 1]
|
||||
], ["1\n", "2\n", "3\n", "4\n", "5\n"]);
|
||||
|
||||
runMutationTest(5, ["1\n", "2\n", "3\n", "4\n", "5\n"], [
|
||||
['skip', 1],
|
||||
['remove', 7, 4, "\n2\n3\n4\n"],
|
||||
['skip', 2, 1]
|
||||
], ["15\n"]);
|
||||
|
||||
runMutationTest(6, ["123\n", "abc\n", "def\n", "ghi\n", "xyz\n"], [
|
||||
['insert', "0"],
|
||||
['skip', 4, 1],
|
||||
['skip', 4, 1],
|
||||
['remove', 8, 2, "def\nghi\n"],
|
||||
['skip', 4, 1]
|
||||
], ["0123\n", "abc\n", "xyz\n"]);
|
||||
|
||||
runMutationTest(7, ["apple\n", "banana\n", "cabbage\n", "duffle\n", "eggplant\n"], [
|
||||
['remove', 6, 1, "apple\n"],
|
||||
['skip', 15, 2, true],
|
||||
['skip', 6, 0, true],
|
||||
['remove', 1, 1, "\n"],
|
||||
['remove', 8, 0, "eggplant"],
|
||||
['skip', 1, 1, true]
|
||||
], ["banana\n", "cabbage\n", "duffle\n"]);
|
||||
|
||||
function poolOrArray(attribs) {
|
||||
if (attribs.getAttrib) {
|
||||
return attribs; // it's already an attrib pool
|
||||
} else {
|
||||
// assume it's an array of attrib strings to be split and added
|
||||
var p = AttributePoolFactory.createAttributePool();
|
||||
attribs.forEach(function (kv) {
|
||||
p.putAttrib(kv.split(','));
|
||||
});
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
function runApplyToAttributionTest(testId, attribs, cs, inAttr, outCorrect) {
|
||||
print("> applyToAttribution#" + testId);
|
||||
var p = poolOrArray(attribs);
|
||||
var result = Changeset.applyToAttribution(
|
||||
Changeset.checkRep(cs), inAttr, p);
|
||||
assertEqualStrings(outCorrect, result);
|
||||
}
|
||||
|
||||
// turn c<b>a</b>ctus\n into a<b>c</b>tusabcd\n
|
||||
runApplyToAttributionTest(1, ['bold,', 'bold,true'], "Z:7>3-1*0=1*1=1=3+4$abcd", "+1*1+1|1+5", "+1*1+1|1+8");
|
||||
|
||||
// turn "david\ngreenspan\n" into "<b>david\ngreen</b>\n"
|
||||
runApplyToAttributionTest(2, ['bold,', 'bold,true'], "Z:g<4*1|1=6*1=5-4$", "|2+g", "*1|1+6*1+5|1+1");
|
||||
|
||||
(function () {
|
||||
print("> mutatorHasMore");
|
||||
var lines = ["1\n", "2\n", "3\n", "4\n"];
|
||||
var mu;
|
||||
|
||||
mu = Changeset.textLinesMutator(lines);
|
||||
assert(mu.hasMore() + ' == true');
|
||||
mu.skip(8, 4);
|
||||
assert(mu.hasMore() + ' == false');
|
||||
mu.close();
|
||||
assert(mu.hasMore() + ' == false');
|
||||
|
||||
// still 1,2,3,4
|
||||
mu = Changeset.textLinesMutator(lines);
|
||||
assert(mu.hasMore() + ' == true');
|
||||
mu.remove(2, 1);
|
||||
assert(mu.hasMore() + ' == true');
|
||||
mu.skip(2, 1);
|
||||
assert(mu.hasMore() + ' == true');
|
||||
mu.skip(2, 1);
|
||||
assert(mu.hasMore() + ' == true');
|
||||
mu.skip(2, 1);
|
||||
assert(mu.hasMore() + ' == false');
|
||||
mu.insert("5\n", 1);
|
||||
assert(mu.hasMore() + ' == false');
|
||||
mu.close();
|
||||
assert(mu.hasMore() + ' == false');
|
||||
|
||||
// 2,3,4,5 now
|
||||
mu = Changeset.textLinesMutator(lines);
|
||||
assert(mu.hasMore() + ' == true');
|
||||
mu.remove(6, 3);
|
||||
assert(mu.hasMore() + ' == true');
|
||||
mu.remove(2, 1);
|
||||
assert(mu.hasMore() + ' == false');
|
||||
mu.insert("hello\n", 1);
|
||||
assert(mu.hasMore() + ' == false');
|
||||
mu.close();
|
||||
assert(mu.hasMore() + ' == false');
|
||||
|
||||
})();
|
||||
|
||||
function runMutateAttributionTest(testId, attribs, cs, alines, outCorrect) {
|
||||
print("> runMutateAttributionTest#" + testId);
|
||||
var p = poolOrArray(attribs);
|
||||
var alines2 = Array.prototype.slice.call(alines);
|
||||
var result = Changeset.mutateAttributionLines(
|
||||
Changeset.checkRep(cs), alines2, p);
|
||||
assertEqualArrays(outCorrect, alines2);
|
||||
|
||||
print("> runMutateAttributionTest#" + testId + ".applyToAttribution");
|
||||
|
||||
function removeQuestionMarks(a) {
|
||||
return a.replace(/\?/g, '');
|
||||
}
|
||||
var inMerged = Changeset.joinAttributionLines(alines.map(removeQuestionMarks));
|
||||
var correctMerged = Changeset.joinAttributionLines(outCorrect.map(removeQuestionMarks));
|
||||
var mergedResult = Changeset.applyToAttribution(cs, inMerged, p);
|
||||
assertEqualStrings(correctMerged, mergedResult);
|
||||
}
|
||||
|
||||
// turn 123\n 456\n 789\n into 123\n 4<b>5</b>6\n 789\n
|
||||
runMutateAttributionTest(1, ["bold,true"], "Z:c>0|1=4=1*0=1$", ["|1+4", "|1+4", "|1+4"], ["|1+4", "+1*0+1|1+2", "|1+4"]);
|
||||
|
||||
// make a document bold
|
||||
runMutateAttributionTest(2, ["bold,true"], "Z:c>0*0|3=c$", ["|1+4", "|1+4", "|1+4"], ["*0|1+4", "*0|1+4", "*0|1+4"]);
|
||||
|
||||
// clear bold on document
|
||||
runMutateAttributionTest(3, ["bold,", "bold,true"], "Z:c>0*0|3=c$", ["*1+1+1*1+1|1+1", "+1*1+1|1+2", "*1+1+1*1+1|1+1"], ["|1+4", "|1+4", "|1+4"]);
|
||||
|
||||
// add a character on line 3 of a document with 5 blank lines, and make sure
|
||||
// the optimization that skips purely-kept lines is working; if any attribution string
|
||||
// with a '?' is parsed it will cause an error.
|
||||
runMutateAttributionTest(4, ['foo,bar', 'line,1', 'line,2', 'line,3', 'line,4', 'line,5'], "Z:5>1|2=2+1$x", ["?*1|1+1", "?*2|1+1", "*3|1+1", "?*4|1+1", "?*5|1+1"], ["?*1|1+1", "?*2|1+1", "+1*3|1+1", "?*4|1+1", "?*5|1+1"]);
|
||||
|
||||
var testPoolWithChars = (function () {
|
||||
var p = AttributePoolFactory.createAttributePool();
|
||||
p.putAttrib(['char', 'newline']);
|
||||
for (var i = 1; i < 36; i++) {
|
||||
p.putAttrib(['char', Changeset.numToString(i)]);
|
||||
}
|
||||
p.putAttrib(['char', '']);
|
||||
return p;
|
||||
})();
|
||||
|
||||
// based on runMutationTest#1
|
||||
runMutateAttributionTest(5, testPoolWithChars, "Z:11>7-2*t+1*u+1|2=b|2+a=2*b+1*o+1*t+1*0|1+1*b+1*u+1=3|1-3-6$" + "tucream\npie\nbot\nbu", ["*a+1*p+2*l+1*e+1*0|1+1", "*b+1*a+1*n+1*a+1*n+1*a+1*0|1+1", "*c+1*a+1*b+2*a+1*g+1*e+1*0|1+1", "*d+1*u+1*f+2*l+1*e+1*0|1+1", "*e+1*g+2*p+1*l+1*a+1*n+1*t+1*0|1+1"], ["*t+1*u+1*p+1*l+1*e+1*0|1+1", "*b+1*a+1*n+1*a+1*n+1*a+1*0|1+1", "|1+6", "|1+4", "*c+1*a+1*b+1*o+1*t+1*0|1+1", "*b+1*u+1*b+2*a+1*0|1+1", "*e+1*g+2*p+1*l+1*a+1*n+1*t+1*0|1+1"]);
|
||||
|
||||
// based on runMutationTest#3
|
||||
runMutateAttributionTest(6, testPoolWithChars, "Z:11<f|1-6|2=f=6|1-1-8$", ["*a|1+6", "*b|1+7", "*c|1+8", "*d|1+7", "*e|1+9"], ["*b|1+7", "*c|1+8", "*d+6*e|1+1"]);
|
||||
|
||||
// based on runMutationTest#4
|
||||
runMutateAttributionTest(7, testPoolWithChars, "Z:3>7=1|4+7$\n2\n3\n4\n", ["*1+1*5|1+2"], ["*1+1|1+1", "|1+2", "|1+2", "|1+2", "*5|1+2"]);
|
||||
|
||||
// based on runMutationTest#5
|
||||
runMutateAttributionTest(8, testPoolWithChars, "Z:a<7=1|4-7$", ["*1|1+2", "*2|1+2", "*3|1+2", "*4|1+2", "*5|1+2"], ["*1+1*5|1+2"]);
|
||||
|
||||
// based on runMutationTest#6
|
||||
runMutateAttributionTest(9, testPoolWithChars, "Z:k<7*0+1*10|2=8|2-8$0", ["*1+1*2+1*3+1|1+1", "*a+1*b+1*c+1|1+1", "*d+1*e+1*f+1|1+1", "*g+1*h+1*i+1|1+1", "?*x+1*y+1*z+1|1+1"], ["*0+1|1+4", "|1+4", "?*x+1*y+1*z+1|1+1"]);
|
||||
|
||||
runMutateAttributionTest(10, testPoolWithChars, "Z:6>4=1+1=1+1|1=1+1=1*0+1$abcd", ["|1+3", "|1+3"], ["|1+5", "+2*0+1|1+2"]);
|
||||
|
||||
|
||||
runMutateAttributionTest(11, testPoolWithChars, "Z:s>1|1=4=6|1+1$\n", ["*0|1+4", "*0|1+8", "*0+5|1+1", "*0|1+1", "*0|1+5", "*0|1+1", "*0|1+1", "*0|1+1", "|1+1"], ["*0|1+4", "*0+6|1+1", "*0|1+2", "*0+5|1+1", "*0|1+1", "*0|1+5", "*0|1+1", "*0|1+1", "*0|1+1", "|1+1"]);
|
||||
|
||||
function randomInlineString(len, rand) {
|
||||
var assem = Changeset.stringAssembler();
|
||||
for (var i = 0; i < len; i++) {
|
||||
assem.append(String.fromCharCode(rand.nextInt(26) + 97));
|
||||
}
|
||||
return assem.toString();
|
||||
}
|
||||
|
||||
function randomMultiline(approxMaxLines, approxMaxCols, rand) {
|
||||
var numParts = rand.nextInt(approxMaxLines * 2) + 1;
|
||||
var txt = Changeset.stringAssembler();
|
||||
txt.append(rand.nextInt(2) ? '\n' : '');
|
||||
for (var i = 0; i < numParts; i++) {
|
||||
if ((i % 2) == 0) {
|
||||
if (rand.nextInt(10)) {
|
||||
txt.append(randomInlineString(rand.nextInt(approxMaxCols) + 1, rand));
|
||||
} else {
|
||||
txt.append('\n');
|
||||
}
|
||||
} else {
|
||||
txt.append('\n');
|
||||
}
|
||||
}
|
||||
return txt.toString();
|
||||
}
|
||||
|
||||
function randomStringOperation(numCharsLeft, rand) {
|
||||
var result;
|
||||
switch (rand.nextInt(9)) {
|
||||
case 0:
|
||||
{
|
||||
// insert char
|
||||
result = {
|
||||
insert: randomInlineString(1, rand)
|
||||
};
|
||||
break;
|
||||
}
|
||||
case 1:
|
||||
{
|
||||
// delete char
|
||||
result = {
|
||||
remove: 1
|
||||
};
|
||||
break;
|
||||
}
|
||||
case 2:
|
||||
{
|
||||
// skip char
|
||||
result = {
|
||||
skip: 1
|
||||
};
|
||||
break;
|
||||
}
|
||||
case 3:
|
||||
{
|
||||
// insert small
|
||||
result = {
|
||||
insert: randomInlineString(rand.nextInt(4) + 1, rand)
|
||||
};
|
||||
break;
|
||||
}
|
||||
case 4:
|
||||
{
|
||||
// delete small
|
||||
result = {
|
||||
remove: rand.nextInt(4) + 1
|
||||
};
|
||||
break;
|
||||
}
|
||||
case 5:
|
||||
{
|
||||
// skip small
|
||||
result = {
|
||||
skip: rand.nextInt(4) + 1
|
||||
};
|
||||
break;
|
||||
}
|
||||
case 6:
|
||||
{
|
||||
// insert multiline;
|
||||
result = {
|
||||
insert: randomMultiline(5, 20, rand)
|
||||
};
|
||||
break;
|
||||
}
|
||||
case 7:
|
||||
{
|
||||
// delete multiline
|
||||
result = {
|
||||
remove: Math.round(numCharsLeft * rand.nextDouble() * rand.nextDouble())
|
||||
};
|
||||
break;
|
||||
}
|
||||
case 8:
|
||||
{
|
||||
// skip multiline
|
||||
result = {
|
||||
skip: Math.round(numCharsLeft * rand.nextDouble() * rand.nextDouble())
|
||||
};
|
||||
break;
|
||||
}
|
||||
case 9:
|
||||
{
|
||||
// delete to end
|
||||
result = {
|
||||
remove: numCharsLeft
|
||||
};
|
||||
break;
|
||||
}
|
||||
case 10:
|
||||
{
|
||||
// skip to end
|
||||
result = {
|
||||
skip: numCharsLeft
|
||||
};
|
||||
break;
|
||||
}
|
||||
}
|
||||
var maxOrig = numCharsLeft - 1;
|
||||
if ('remove' in result) {
|
||||
result.remove = Math.min(result.remove, maxOrig);
|
||||
} else if ('skip' in result) {
|
||||
result.skip = Math.min(result.skip, maxOrig);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function randomTwoPropAttribs(opcode, rand) {
|
||||
// assumes attrib pool like ['apple,','apple,true','banana,','banana,true']
|
||||
if (opcode == '-' || rand.nextInt(3)) {
|
||||
return '';
|
||||
} else if (rand.nextInt(3)) {
|
||||
if (opcode == '+' || rand.nextInt(2)) {
|
||||
return '*' + Changeset.numToString(rand.nextInt(2) * 2 + 1);
|
||||
} else {
|
||||
return '*' + Changeset.numToString(rand.nextInt(2) * 2);
|
||||
}
|
||||
} else {
|
||||
if (opcode == '+' || rand.nextInt(4) == 0) {
|
||||
return '*1*3';
|
||||
} else {
|
||||
return ['*0*2', '*0*3', '*1*2'][rand.nextInt(3)];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function randomTestChangeset(origText, rand, withAttribs) {
|
||||
var charBank = Changeset.stringAssembler();
|
||||
var textLeft = origText; // always keep final newline
|
||||
var outTextAssem = Changeset.stringAssembler();
|
||||
var opAssem = Changeset.smartOpAssembler();
|
||||
var oldLen = origText.length;
|
||||
|
||||
var nextOp = Changeset.newOp();
|
||||
|
||||
function appendMultilineOp(opcode, txt) {
|
||||
nextOp.opcode = opcode;
|
||||
if (withAttribs) {
|
||||
nextOp.attribs = randomTwoPropAttribs(opcode, rand);
|
||||
}
|
||||
txt.replace(/\n|[^\n]+/g, function (t) {
|
||||
if (t == '\n') {
|
||||
nextOp.chars = 1;
|
||||
nextOp.lines = 1;
|
||||
opAssem.append(nextOp);
|
||||
} else {
|
||||
nextOp.chars = t.length;
|
||||
nextOp.lines = 0;
|
||||
opAssem.append(nextOp);
|
||||
}
|
||||
return '';
|
||||
});
|
||||
}
|
||||
|
||||
function doOp() {
|
||||
var o = randomStringOperation(textLeft.length, rand);
|
||||
if (o.insert) {
|
||||
var txt = o.insert;
|
||||
charBank.append(txt);
|
||||
outTextAssem.append(txt);
|
||||
appendMultilineOp('+', txt);
|
||||
} else if (o.skip) {
|
||||
var txt = textLeft.substring(0, o.skip);
|
||||
textLeft = textLeft.substring(o.skip);
|
||||
outTextAssem.append(txt);
|
||||
appendMultilineOp('=', txt);
|
||||
} else if (o.remove) {
|
||||
var txt = textLeft.substring(0, o.remove);
|
||||
textLeft = textLeft.substring(o.remove);
|
||||
appendMultilineOp('-', txt);
|
||||
}
|
||||
}
|
||||
|
||||
while (textLeft.length > 1) doOp();
|
||||
for (var i = 0; i < 5; i++) doOp(); // do some more (only insertions will happen)
|
||||
var outText = outTextAssem.toString() + '\n';
|
||||
opAssem.endDocument();
|
||||
var cs = Changeset.pack(oldLen, outText.length, opAssem.toString(), charBank.toString());
|
||||
Changeset.checkRep(cs);
|
||||
return [cs, outText];
|
||||
}
|
||||
|
||||
function testCompose(randomSeed) {
|
||||
var rand = new random();
|
||||
print("> testCompose#" + randomSeed);
|
||||
|
||||
var p = AttributePoolFactory.createAttributePool();
|
||||
|
||||
var startText = randomMultiline(10, 20, rand) + '\n';
|
||||
|
||||
var x1 = randomTestChangeset(startText, rand);
|
||||
var change1 = x1[0];
|
||||
var text1 = x1[1];
|
||||
|
||||
var x2 = randomTestChangeset(text1, rand);
|
||||
var change2 = x2[0];
|
||||
var text2 = x2[1];
|
||||
|
||||
var x3 = randomTestChangeset(text2, rand);
|
||||
var change3 = x3[0];
|
||||
var text3 = x3[1];
|
||||
|
||||
//print(literal(Changeset.toBaseTen(startText)));
|
||||
//print(literal(Changeset.toBaseTen(change1)));
|
||||
//print(literal(Changeset.toBaseTen(change2)));
|
||||
var change12 = Changeset.checkRep(Changeset.compose(change1, change2, p));
|
||||
var change23 = Changeset.checkRep(Changeset.compose(change2, change3, p));
|
||||
var change123 = Changeset.checkRep(Changeset.compose(change12, change3, p));
|
||||
var change123a = Changeset.checkRep(Changeset.compose(change1, change23, p));
|
||||
assertEqualStrings(change123, change123a);
|
||||
|
||||
assertEqualStrings(text2, Changeset.applyToText(change12, startText));
|
||||
assertEqualStrings(text3, Changeset.applyToText(change23, text1));
|
||||
assertEqualStrings(text3, Changeset.applyToText(change123, startText));
|
||||
}
|
||||
|
||||
for (var i = 0; i < 30; i++) testCompose(i);
|
||||
|
||||
(function simpleComposeAttributesTest() {
|
||||
print("> simpleComposeAttributesTest");
|
||||
var p = AttributePoolFactory.createAttributePool();
|
||||
p.putAttrib(['bold', '']);
|
||||
p.putAttrib(['bold', 'true']);
|
||||
var cs1 = Changeset.checkRep("Z:2>1*1+1*1=1$x");
|
||||
var cs2 = Changeset.checkRep("Z:3>0*0|1=3$");
|
||||
var cs12 = Changeset.checkRep(Changeset.compose(cs1, cs2, p));
|
||||
assertEqualStrings("Z:2>1+1*0|1=2$x", cs12);
|
||||
})();
|
||||
|
||||
(function followAttributesTest() {
|
||||
var p = AttributePoolFactory.createAttributePool();
|
||||
p.putAttrib(['x', '']);
|
||||
p.putAttrib(['x', 'abc']);
|
||||
p.putAttrib(['x', 'def']);
|
||||
p.putAttrib(['y', '']);
|
||||
p.putAttrib(['y', 'abc']);
|
||||
p.putAttrib(['y', 'def']);
|
||||
|
||||
function testFollow(a, b, afb, bfa, merge) {
|
||||
assertEqualStrings(afb, Changeset.followAttributes(a, b, p));
|
||||
assertEqualStrings(bfa, Changeset.followAttributes(b, a, p));
|
||||
assertEqualStrings(merge, Changeset.composeAttributes(a, afb, true, p));
|
||||
assertEqualStrings(merge, Changeset.composeAttributes(b, bfa, true, p));
|
||||
}
|
||||
|
||||
testFollow('', '', '', '', '');
|
||||
testFollow('*0', '', '', '*0', '*0');
|
||||
testFollow('*0', '*0', '', '', '*0');
|
||||
testFollow('*0', '*1', '', '*0', '*0');
|
||||
testFollow('*1', '*2', '', '*1', '*1');
|
||||
testFollow('*0*1', '', '', '*0*1', '*0*1');
|
||||
testFollow('*0*4', '*2*3', '*3', '*0', '*0*3');
|
||||
testFollow('*0*4', '*2', '', '*0*4', '*0*4');
|
||||
})();
|
||||
|
||||
function testFollow(randomSeed) {
|
||||
var rand = new random();
|
||||
print("> testFollow#" + randomSeed);
|
||||
|
||||
var p = AttributePoolFactory.createAttributePool();
|
||||
|
||||
var startText = randomMultiline(10, 20, rand) + '\n';
|
||||
|
||||
var cs1 = randomTestChangeset(startText, rand)[0];
|
||||
var cs2 = randomTestChangeset(startText, rand)[0];
|
||||
|
||||
var afb = Changeset.checkRep(Changeset.follow(cs1, cs2, false, p));
|
||||
var bfa = Changeset.checkRep(Changeset.follow(cs2, cs1, true, p));
|
||||
|
||||
var merge1 = Changeset.checkRep(Changeset.compose(cs1, afb));
|
||||
var merge2 = Changeset.checkRep(Changeset.compose(cs2, bfa));
|
||||
|
||||
assertEqualStrings(merge1, merge2);
|
||||
}
|
||||
|
||||
for (var i = 0; i < 30; i++) testFollow(i);
|
||||
|
||||
function testSplitJoinAttributionLines(randomSeed) {
|
||||
var rand = new random();
|
||||
print("> testSplitJoinAttributionLines#" + randomSeed);
|
||||
|
||||
var doc = randomMultiline(10, 20, rand) + '\n';
|
||||
|
||||
function stringToOps(str) {
|
||||
var assem = Changeset.mergingOpAssembler();
|
||||
var o = Changeset.newOp('+');
|
||||
o.chars = 1;
|
||||
for (var i = 0; i < str.length; i++) {
|
||||
var c = str.charAt(i);
|
||||
o.lines = (c == '\n' ? 1 : 0);
|
||||
o.attribs = (c == 'a' || c == 'b' ? '*' + c : '');
|
||||
assem.append(o);
|
||||
}
|
||||
return assem.toString();
|
||||
}
|
||||
|
||||
var theJoined = stringToOps(doc);
|
||||
var theSplit = doc.match(/[^\n]*\n/g).map(stringToOps);
|
||||
|
||||
assertEqualArrays(theSplit, Changeset.splitAttributionLines(theJoined, doc));
|
||||
assertEqualStrings(theJoined, Changeset.joinAttributionLines(theSplit));
|
||||
}
|
||||
|
||||
for (var i = 0; i < 10; i++) testSplitJoinAttributionLines(i);
|
||||
|
||||
(function testMoveOpsToNewPool() {
|
||||
print("> testMoveOpsToNewPool");
|
||||
|
||||
var pool1 = AttributePoolFactory.createAttributePool();
|
||||
var pool2 = AttributePoolFactory.createAttributePool();
|
||||
|
||||
pool1.putAttrib(['baz', 'qux']);
|
||||
pool1.putAttrib(['foo', 'bar']);
|
||||
|
||||
pool2.putAttrib(['foo', 'bar']);
|
||||
|
||||
assertEqualStrings(Changeset.moveOpsToNewPool('Z:1>2*1+1*0+1$ab', pool1, pool2), 'Z:1>2*0+1*1+1$ab');
|
||||
assertEqualStrings(Changeset.moveOpsToNewPool('*1+1*0+1', pool1, pool2), '*0+1*1+1');
|
||||
})();
|
||||
|
||||
|
||||
(function testMakeSplice() {
|
||||
print("> testMakeSplice");
|
||||
|
||||
var t = "a\nb\nc\n";
|
||||
var t2 = Changeset.applyToText(Changeset.makeSplice(t, 5, 0, "def"), t);
|
||||
assertEqualStrings("a\nb\ncdef\n", t2);
|
||||
|
||||
})();
|
||||
|
||||
(function testToSplices() {
|
||||
print("> testToSplices");
|
||||
|
||||
var cs = Changeset.checkRep('Z:z>9*0=1=4-3+9=1|1-4-4+1*0+a$123456789abcdefghijk');
|
||||
var correctSplices = [
|
||||
[5, 8, "123456789"],
|
||||
[9, 17, "abcdefghijk"]
|
||||
];
|
||||
assertEqualArrays(correctSplices, Changeset.toSplices(cs));
|
||||
})();
|
||||
|
||||
function testCharacterRangeFollow(testId, cs, oldRange, insertionsAfter, correctNewRange) {
|
||||
print("> testCharacterRangeFollow#" + testId);
|
||||
|
||||
var cs = Changeset.checkRep(cs);
|
||||
assertEqualArrays(correctNewRange, Changeset.characterRangeFollow(cs, oldRange[0], oldRange[1], insertionsAfter));
|
||||
|
||||
}
|
||||
|
||||
testCharacterRangeFollow(1, 'Z:z>9*0=1=4-3+9=1|1-4-4+1*0+a$123456789abcdefghijk', [7, 10], false, [14, 15]);
|
||||
testCharacterRangeFollow(2, "Z:bc<6|x=b4|2-6$", [400, 407], false, [400, 401]);
|
||||
testCharacterRangeFollow(3, "Z:4>0-3+3$abc", [0, 3], false, [3, 3]);
|
||||
testCharacterRangeFollow(4, "Z:4>0-3+3$abc", [0, 3], true, [0, 0]);
|
||||
testCharacterRangeFollow(5, "Z:5>1+1=1-3+3$abcd", [1, 4], false, [5, 5]);
|
||||
testCharacterRangeFollow(6, "Z:5>1+1=1-3+3$abcd", [1, 4], true, [2, 2]);
|
||||
testCharacterRangeFollow(7, "Z:5>1+1=1-3+3$abcd", [0, 6], false, [1, 7]);
|
||||
testCharacterRangeFollow(8, "Z:5>1+1=1-3+3$abcd", [0, 3], false, [1, 2]);
|
||||
testCharacterRangeFollow(9, "Z:5>1+1=1-3+3$abcd", [2, 5], false, [5, 6]);
|
||||
testCharacterRangeFollow(10, "Z:2>1+1$a", [0, 0], false, [1, 1]);
|
||||
testCharacterRangeFollow(11, "Z:2>1+1$a", [0, 0], true, [0, 0]);
|
||||
|
||||
(function testOpAttributeValue() {
|
||||
print("> testOpAttributeValue");
|
||||
|
||||
var p = AttributePoolFactory.createAttributePool();
|
||||
p.putAttrib(['name', 'david']);
|
||||
p.putAttrib(['color', 'green']);
|
||||
|
||||
assertEqualStrings("david", Changeset.opAttributeValue(Changeset.stringOp('*0*1+1'), 'name', p));
|
||||
assertEqualStrings("david", Changeset.opAttributeValue(Changeset.stringOp('*0+1'), 'name', p));
|
||||
assertEqualStrings("", Changeset.opAttributeValue(Changeset.stringOp('*1+1'), 'name', p));
|
||||
assertEqualStrings("", Changeset.opAttributeValue(Changeset.stringOp('+1'), 'name', p));
|
||||
assertEqualStrings("green", Changeset.opAttributeValue(Changeset.stringOp('*0*1+1'), 'color', p));
|
||||
assertEqualStrings("green", Changeset.opAttributeValue(Changeset.stringOp('*1+1'), 'color', p));
|
||||
assertEqualStrings("", Changeset.opAttributeValue(Changeset.stringOp('*0+1'), 'color', p));
|
||||
assertEqualStrings("", Changeset.opAttributeValue(Changeset.stringOp('+1'), 'color', p));
|
||||
})();
|
||||
|
||||
function testAppendATextToAssembler(testId, atext, correctOps) {
|
||||
print("> testAppendATextToAssembler#" + testId);
|
||||
|
||||
var assem = Changeset.smartOpAssembler();
|
||||
Changeset.appendATextToAssembler(atext, assem);
|
||||
assertEqualStrings(correctOps, assem.toString());
|
||||
}
|
||||
|
||||
testAppendATextToAssembler(1, {
|
||||
text: "\n",
|
||||
attribs: "|1+1"
|
||||
}, "");
|
||||
testAppendATextToAssembler(2, {
|
||||
text: "\n\n",
|
||||
attribs: "|2+2"
|
||||
}, "|1+1");
|
||||
testAppendATextToAssembler(3, {
|
||||
text: "\n\n",
|
||||
attribs: "*x|2+2"
|
||||
}, "*x|1+1");
|
||||
testAppendATextToAssembler(4, {
|
||||
text: "\n\n",
|
||||
attribs: "*x|1+1|1+1"
|
||||
}, "*x|1+1");
|
||||
testAppendATextToAssembler(5, {
|
||||
text: "foo\n",
|
||||
attribs: "|1+4"
|
||||
}, "+3");
|
||||
testAppendATextToAssembler(6, {
|
||||
text: "\nfoo\n",
|
||||
attribs: "|2+5"
|
||||
}, "|1+1+3");
|
||||
testAppendATextToAssembler(7, {
|
||||
text: "\nfoo\n",
|
||||
attribs: "*x|2+5"
|
||||
}, "*x|1+1*x+3");
|
||||
testAppendATextToAssembler(8, {
|
||||
text: "\n\n\nfoo\n",
|
||||
attribs: "|2+2*x|2+5"
|
||||
}, "|2+2*x|1+1*x+3");
|
||||
|
||||
function testMakeAttribsString(testId, pool, opcode, attribs, correctString) {
|
||||
print("> testMakeAttribsString#" + testId);
|
||||
|
||||
var p = poolOrArray(pool);
|
||||
var str = Changeset.makeAttribsString(opcode, attribs, p);
|
||||
assertEqualStrings(correctString, str);
|
||||
}
|
||||
|
||||
testMakeAttribsString(1, ['bold,'], '+', [
|
||||
['bold', '']
|
||||
], '');
|
||||
testMakeAttribsString(2, ['abc,def', 'bold,'], '=', [
|
||||
['bold', '']
|
||||
], '*1');
|
||||
testMakeAttribsString(3, ['abc,def', 'bold,true'], '+', [
|
||||
['abc', 'def'],
|
||||
['bold', 'true']
|
||||
], '*0*1');
|
||||
testMakeAttribsString(4, ['abc,def', 'bold,true'], '+', [
|
||||
['bold', 'true'],
|
||||
['abc', 'def']
|
||||
], '*0*1');
|
||||
|
||||
function testSubattribution(testId, astr, start, end, correctOutput) {
|
||||
print("> testSubattribution#" + testId);
|
||||
|
||||
var str = Changeset.subattribution(astr, start, end);
|
||||
assertEqualStrings(correctOutput, str);
|
||||
}
|
||||
|
||||
testSubattribution(1, "+1", 0, 0, "");
|
||||
testSubattribution(2, "+1", 0, 1, "+1");
|
||||
testSubattribution(3, "+1", 0, undefined, "+1");
|
||||
testSubattribution(4, "|1+1", 0, 0, "");
|
||||
testSubattribution(5, "|1+1", 0, 1, "|1+1");
|
||||
testSubattribution(6, "|1+1", 0, undefined, "|1+1");
|
||||
testSubattribution(7, "*0+1", 0, 0, "");
|
||||
testSubattribution(8, "*0+1", 0, 1, "*0+1");
|
||||
testSubattribution(9, "*0+1", 0, undefined, "*0+1");
|
||||
testSubattribution(10, "*0|1+1", 0, 0, "");
|
||||
testSubattribution(11, "*0|1+1", 0, 1, "*0|1+1");
|
||||
testSubattribution(12, "*0|1+1", 0, undefined, "*0|1+1");
|
||||
testSubattribution(13, "*0+2+1*1+3", 0, 1, "*0+1");
|
||||
testSubattribution(14, "*0+2+1*1+3", 0, 2, "*0+2");
|
||||
testSubattribution(15, "*0+2+1*1+3", 0, 3, "*0+2+1");
|
||||
testSubattribution(16, "*0+2+1*1+3", 0, 4, "*0+2+1*1+1");
|
||||
testSubattribution(17, "*0+2+1*1+3", 0, 5, "*0+2+1*1+2");
|
||||
testSubattribution(18, "*0+2+1*1+3", 0, 6, "*0+2+1*1+3");
|
||||
testSubattribution(19, "*0+2+1*1+3", 0, 7, "*0+2+1*1+3");
|
||||
testSubattribution(20, "*0+2+1*1+3", 0, undefined, "*0+2+1*1+3");
|
||||
testSubattribution(21, "*0+2+1*1+3", 1, undefined, "*0+1+1*1+3");
|
||||
testSubattribution(22, "*0+2+1*1+3", 2, undefined, "+1*1+3");
|
||||
testSubattribution(23, "*0+2+1*1+3", 3, undefined, "*1+3");
|
||||
testSubattribution(24, "*0+2+1*1+3", 4, undefined, "*1+2");
|
||||
testSubattribution(25, "*0+2+1*1+3", 5, undefined, "*1+1");
|
||||
testSubattribution(26, "*0+2+1*1+3", 6, undefined, "");
|
||||
testSubattribution(27, "*0+2+1*1|1+3", 0, 1, "*0+1");
|
||||
testSubattribution(28, "*0+2+1*1|1+3", 0, 2, "*0+2");
|
||||
testSubattribution(29, "*0+2+1*1|1+3", 0, 3, "*0+2+1");
|
||||
testSubattribution(30, "*0+2+1*1|1+3", 0, 4, "*0+2+1*1+1");
|
||||
testSubattribution(31, "*0+2+1*1|1+3", 0, 5, "*0+2+1*1+2");
|
||||
testSubattribution(32, "*0+2+1*1|1+3", 0, 6, "*0+2+1*1|1+3");
|
||||
testSubattribution(33, "*0+2+1*1|1+3", 0, 7, "*0+2+1*1|1+3");
|
||||
testSubattribution(34, "*0+2+1*1|1+3", 0, undefined, "*0+2+1*1|1+3");
|
||||
testSubattribution(35, "*0+2+1*1|1+3", 1, undefined, "*0+1+1*1|1+3");
|
||||
testSubattribution(36, "*0+2+1*1|1+3", 2, undefined, "+1*1|1+3");
|
||||
testSubattribution(37, "*0+2+1*1|1+3", 3, undefined, "*1|1+3");
|
||||
testSubattribution(38, "*0+2+1*1|1+3", 4, undefined, "*1|1+2");
|
||||
testSubattribution(39, "*0+2+1*1|1+3", 5, undefined, "*1|1+1");
|
||||
testSubattribution(40, "*0+2+1*1|1+3", 1, 5, "*0+1+1*1+2");
|
||||
testSubattribution(41, "*0+2+1*1|1+3", 2, 6, "+1*1|1+3");
|
||||
testSubattribution(42, "*0+2+1*1+3", 2, 6, "+1*1+3");
|
||||
|
||||
function testFilterAttribNumbers(testId, cs, filter, correctOutput) {
|
||||
print("> testFilterAttribNumbers#" + testId);
|
||||
|
||||
var str = Changeset.filterAttribNumbers(cs, filter);
|
||||
assertEqualStrings(correctOutput, str);
|
||||
}
|
||||
|
||||
testFilterAttribNumbers(1, "*0*1+1+2+3*1+4*2+5*0*2*1*b*c+6", function (n) {
|
||||
return (n % 2) == 0;
|
||||
}, "*0+1+2+3+4*2+5*0*2*c+6");
|
||||
testFilterAttribNumbers(2, "*0*1+1+2+3*1+4*2+5*0*2*1*b*c+6", function (n) {
|
||||
return (n % 2) == 1;
|
||||
}, "*1+1+2+3*1+4+5*1*b+6");
|
||||
|
||||
function testInverse(testId, cs, lines, alines, pool, correctOutput) {
|
||||
print("> testInverse#" + testId);
|
||||
|
||||
pool = poolOrArray(pool);
|
||||
var str = Changeset.inverse(Changeset.checkRep(cs), lines, alines, pool);
|
||||
assertEqualStrings(correctOutput, str);
|
||||
}
|
||||
|
||||
// take "FFFFTTTTT" and apply "-FT--FFTT", the inverse of which is "--F--TT--"
|
||||
testInverse(1, "Z:9>0=1*0=1*1=1=2*0=2*1|1=2$", null, ["+4*1+5"], ['bold,', 'bold,true'], "Z:9>0=2*0=1=2*1=2$");
|
||||
|
||||
function testMutateTextLines(testId, cs, lines, correctLines) {
|
||||
print("> testMutateTextLines#" + testId);
|
||||
|
||||
var a = lines.slice();
|
||||
Changeset.mutateTextLines(cs, a);
|
||||
assertEqualArrays(correctLines, a);
|
||||
}
|
||||
|
||||
testMutateTextLines(1, "Z:4<1|1-2-1|1+1+1$\nc", ["a\n", "b\n"], ["\n", "c\n"]);
|
||||
testMutateTextLines(2, "Z:4>0|1-2-1|2+3$\nc\n", ["a\n", "b\n"], ["\n", "c\n", "\n"]);
|
||||
|
||||
function testInverseRandom(randomSeed) {
|
||||
var rand = new random();
|
||||
print("> testInverseRandom#" + randomSeed);
|
||||
|
||||
var p = poolOrArray(['apple,', 'apple,true', 'banana,', 'banana,true']);
|
||||
|
||||
var startText = randomMultiline(10, 20, rand) + '\n';
|
||||
var alines = Changeset.splitAttributionLines(Changeset.makeAttribution(startText), startText);
|
||||
var lines = startText.slice(0, -1).split('\n').map(function (s) {
|
||||
return s + '\n';
|
||||
});
|
||||
|
||||
var stylifier = randomTestChangeset(startText, rand, true)[0];
|
||||
|
||||
//print(alines.join('\n'));
|
||||
Changeset.mutateAttributionLines(stylifier, alines, p);
|
||||
//print(stylifier);
|
||||
//print(alines.join('\n'));
|
||||
Changeset.mutateTextLines(stylifier, lines);
|
||||
|
||||
var changeset = randomTestChangeset(lines.join(''), rand, true)[0];
|
||||
var inverseChangeset = Changeset.inverse(changeset, lines, alines, p);
|
||||
|
||||
var origLines = lines.slice();
|
||||
var origALines = alines.slice();
|
||||
|
||||
Changeset.mutateTextLines(changeset, lines);
|
||||
Changeset.mutateAttributionLines(changeset, alines, p);
|
||||
//print(origALines.join('\n'));
|
||||
//print(changeset);
|
||||
//print(inverseChangeset);
|
||||
//print(origLines.map(function(s) { return '1: '+s.slice(0,-1); }).join('\n'));
|
||||
//print(lines.map(function(s) { return '2: '+s.slice(0,-1); }).join('\n'));
|
||||
//print(alines.join('\n'));
|
||||
Changeset.mutateTextLines(inverseChangeset, lines);
|
||||
Changeset.mutateAttributionLines(inverseChangeset, alines, p);
|
||||
//print(lines.map(function(s) { return '3: '+s.slice(0,-1); }).join('\n'));
|
||||
assertEqualArrays(origLines, lines);
|
||||
assertEqualArrays(origALines, alines);
|
||||
}
|
||||
|
||||
for (var i = 0; i < 30; i++) testInverseRandom(i);
|
||||
}
|
||||
|
||||
runTests();
|
161
src/node/handler/APIHandler.js
Normal file
|
@ -0,0 +1,161 @@
|
|||
/**
|
||||
* The API Handler handles all API http requests
|
||||
*/
|
||||
|
||||
/*
|
||||
* 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
|
||||
*
|
||||
* 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 CommonCode = require('../utils/common_code');
|
||||
var ERR = require("async-stacktrace");
|
||||
var fs = require("fs");
|
||||
var api = require("../db/API");
|
||||
var padManager = require("../db/PadManager");
|
||||
var randomString = CommonCode.require('/pad_utils').randomString;
|
||||
|
||||
//ensure we have an apikey
|
||||
var apikey = null;
|
||||
try
|
||||
{
|
||||
apikey = fs.readFileSync("../APIKEY.txt","utf8");
|
||||
}
|
||||
catch(e)
|
||||
{
|
||||
apikey = randomString(32);
|
||||
fs.writeFileSync("../APIKEY.txt",apikey,"utf8");
|
||||
}
|
||||
|
||||
//a list of all functions
|
||||
var functions = {
|
||||
"createGroup" : [],
|
||||
"createGroupIfNotExistsFor" : ["groupMapper"],
|
||||
"deleteGroup" : ["groupID"],
|
||||
"listPads" : ["groupID"],
|
||||
"createPad" : ["padID", "text"],
|
||||
"createGroupPad" : ["groupID", "padName", "text"],
|
||||
"createAuthor" : ["name"],
|
||||
"createAuthorIfNotExistsFor": ["authorMapper" , "name"],
|
||||
"createSession" : ["groupID", "authorID", "validUntil"],
|
||||
"deleteSession" : ["sessionID"],
|
||||
"getSessionInfo" : ["sessionID"],
|
||||
"listSessionsOfGroup" : ["groupID"],
|
||||
"listSessionsOfAuthor" : ["authorID"],
|
||||
"getText" : ["padID", "rev"],
|
||||
"setText" : ["padID", "text"],
|
||||
"getHTML" : ["padID", "rev"],
|
||||
"setHTML" : ["padID", "html"],
|
||||
"getRevisionsCount" : ["padID"],
|
||||
"deletePad" : ["padID"],
|
||||
"getReadOnlyID" : ["padID"],
|
||||
"setPublicStatus" : ["padID", "publicStatus"],
|
||||
"getPublicStatus" : ["padID"],
|
||||
"setPassword" : ["padID", "password"],
|
||||
"isPasswordProtected" : ["padID"]
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles a HTTP API call
|
||||
* @param functionName the name of the called function
|
||||
* @param fields the params of the called function
|
||||
* @req express request object
|
||||
* @res express response object
|
||||
*/
|
||||
exports.handle = function(functionName, fields, req, res)
|
||||
{
|
||||
//check the api key!
|
||||
if(fields["apikey"] != apikey.trim())
|
||||
{
|
||||
res.send({code: 4, message: "no or wrong API Key", data: null});
|
||||
return;
|
||||
}
|
||||
|
||||
//check if this is a valid function name
|
||||
var isKnownFunctionname = false;
|
||||
for(var knownFunctionname in functions)
|
||||
{
|
||||
if(knownFunctionname == functionName)
|
||||
{
|
||||
isKnownFunctionname = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
//say goodbye if this is a unkown function
|
||||
if(!isKnownFunctionname)
|
||||
{
|
||||
res.send({code: 3, message: "no such function", data: null});
|
||||
return;
|
||||
}
|
||||
|
||||
//sanitize any pad id's before continuing
|
||||
if(fields["padID"])
|
||||
{
|
||||
padManager.sanitizePadId(fields["padID"], function(padId)
|
||||
{
|
||||
fields["padID"] = padId;
|
||||
callAPI(functionName, fields, req, res);
|
||||
});
|
||||
}
|
||||
else if(fields["padName"])
|
||||
{
|
||||
padManager.sanitizePadId(fields["padName"], function(padId)
|
||||
{
|
||||
fields["padName"] = padId;
|
||||
callAPI(functionName, fields, req, res);
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
callAPI(functionName, fields, req, res);
|
||||
}
|
||||
}
|
||||
|
||||
//calls the api function
|
||||
function callAPI(functionName, fields, req, res)
|
||||
{
|
||||
//put the function parameters in an array
|
||||
var functionParams = [];
|
||||
for(var i=0;i<functions[functionName].length;i++)
|
||||
{
|
||||
functionParams.push(fields[functions[functionName][i]]);
|
||||
}
|
||||
|
||||
//add a callback function to handle the response
|
||||
functionParams.push(function(err, data)
|
||||
{
|
||||
// no error happend, everything is fine
|
||||
if(err == null)
|
||||
{
|
||||
if(!data)
|
||||
data = null;
|
||||
|
||||
res.send({code: 0, message: "ok", data: data});
|
||||
}
|
||||
// parameters were wrong and the api stopped execution, pass the error
|
||||
else if(err.name == "apierror")
|
||||
{
|
||||
res.send({code: 1, message: err.message, data: null});
|
||||
}
|
||||
//an unkown error happend
|
||||
else
|
||||
{
|
||||
res.send({code: 2, message: "internal error", data: null});
|
||||
ERR(err);
|
||||
}
|
||||
});
|
||||
|
||||
//call the api function
|
||||
api[functionName](functionParams[0],functionParams[1],functionParams[2],functionParams[3],functionParams[4]);
|
||||
}
|
165
src/node/handler/ExportHandler.js
Normal file
|
@ -0,0 +1,165 @@
|
|||
/**
|
||||
* Handles the export requests
|
||||
*/
|
||||
|
||||
/*
|
||||
* 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
|
||||
*
|
||||
* 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 ERR = require("async-stacktrace");
|
||||
var exporthtml = require("../utils/ExportHtml");
|
||||
var exportdokuwiki = require("../utils/ExportDokuWiki");
|
||||
var padManager = require("../db/PadManager");
|
||||
var async = require("async");
|
||||
var fs = require("fs");
|
||||
var settings = require('../utils/Settings');
|
||||
var os = require('os');
|
||||
|
||||
//load abiword only if its enabled
|
||||
if(settings.abiword != null)
|
||||
var abiword = require("../utils/Abiword");
|
||||
|
||||
var tempDirectory = "/tmp";
|
||||
|
||||
//tempDirectory changes if the operating system is windows
|
||||
if(os.type().indexOf("Windows") > -1)
|
||||
{
|
||||
tempDirectory = process.env.TEMP;
|
||||
}
|
||||
|
||||
/**
|
||||
* do a requested export
|
||||
*/
|
||||
exports.doExport = function(req, res, padId, type)
|
||||
{
|
||||
//tell the browser that this is a downloadable file
|
||||
res.attachment(padId + "." + type);
|
||||
|
||||
//if this is a plain text export, we can do this directly
|
||||
if(type == "txt")
|
||||
{
|
||||
padManager.getPad(padId, function(err, pad)
|
||||
{
|
||||
ERR(err);
|
||||
if(req.params.rev){
|
||||
pad.getInternalRevisionAText(req.params.rev, function(junk, text)
|
||||
{
|
||||
res.send(text.text ? text.text : null);
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
res.send(pad.text());
|
||||
}
|
||||
});
|
||||
}
|
||||
else if(type == 'dokuwiki')
|
||||
{
|
||||
var randNum;
|
||||
var srcFile, destFile;
|
||||
|
||||
async.series([
|
||||
//render the dokuwiki document
|
||||
function(callback)
|
||||
{
|
||||
exportdokuwiki.getPadDokuWikiDocument(padId, req.params.rev, function(err, dokuwiki)
|
||||
{
|
||||
res.send(dokuwiki);
|
||||
callback("stop");
|
||||
});
|
||||
},
|
||||
], function(err)
|
||||
{
|
||||
if(err && err != "stop") throw err;
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
var html;
|
||||
var randNum;
|
||||
var srcFile, destFile;
|
||||
|
||||
async.series([
|
||||
//render the html document
|
||||
function(callback)
|
||||
{
|
||||
exporthtml.getPadHTMLDocument(padId, req.params.rev, false, function(err, _html)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
html = _html;
|
||||
callback();
|
||||
});
|
||||
},
|
||||
//decide what to do with the html export
|
||||
function(callback)
|
||||
{
|
||||
//if this is a html export, we can send this from here directly
|
||||
if(type == "html")
|
||||
{
|
||||
res.send(html);
|
||||
callback("stop");
|
||||
}
|
||||
else //write the html export to a file
|
||||
{
|
||||
randNum = Math.floor(Math.random()*0xFFFFFFFF);
|
||||
srcFile = tempDirectory + "/eplite_export_" + randNum + ".html";
|
||||
fs.writeFile(srcFile, html, callback);
|
||||
}
|
||||
},
|
||||
//send the convert job to abiword
|
||||
function(callback)
|
||||
{
|
||||
//ensure html can be collected by the garbage collector
|
||||
html = null;
|
||||
|
||||
destFile = tempDirectory + "/eplite_export_" + randNum + "." + type;
|
||||
abiword.convertFile(srcFile, destFile, type, callback);
|
||||
},
|
||||
//send the file
|
||||
function(callback)
|
||||
{
|
||||
res.sendfile(destFile, null, callback);
|
||||
},
|
||||
//clean up temporary files
|
||||
function(callback)
|
||||
{
|
||||
async.parallel([
|
||||
function(callback)
|
||||
{
|
||||
fs.unlink(srcFile, callback);
|
||||
},
|
||||
function(callback)
|
||||
{
|
||||
//100ms delay to accomidate for slow windows fs
|
||||
if(os.type().indexOf("Windows") > -1)
|
||||
{
|
||||
setTimeout(function()
|
||||
{
|
||||
fs.unlink(destFile, callback);
|
||||
}, 100);
|
||||
}
|
||||
else
|
||||
{
|
||||
fs.unlink(destFile, callback);
|
||||
}
|
||||
}
|
||||
], callback);
|
||||
}
|
||||
], function(err)
|
||||
{
|
||||
if(err && err != "stop") ERR(err);
|
||||
})
|
||||
}
|
||||
};
|
191
src/node/handler/ImportHandler.js
Normal file
|
@ -0,0 +1,191 @@
|
|||
/**
|
||||
* Handles the import requests
|
||||
*/
|
||||
|
||||
/*
|
||||
* 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
|
||||
*
|
||||
* 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 ERR = require("async-stacktrace");
|
||||
var padManager = require("../db/PadManager");
|
||||
var padMessageHandler = require("./PadMessageHandler");
|
||||
var async = require("async");
|
||||
var fs = require("fs");
|
||||
var settings = require('../utils/Settings');
|
||||
var formidable = require('formidable');
|
||||
var os = require("os");
|
||||
|
||||
//load abiword only if its enabled
|
||||
if(settings.abiword != null)
|
||||
var abiword = require("../utils/Abiword");
|
||||
|
||||
var tempDirectory = "/tmp/";
|
||||
|
||||
//tempDirectory changes if the operating system is windows
|
||||
if(os.type().indexOf("Windows") > -1)
|
||||
{
|
||||
tempDirectory = process.env.TEMP;
|
||||
}
|
||||
|
||||
/**
|
||||
* do a requested import
|
||||
*/
|
||||
exports.doImport = function(req, res, padId)
|
||||
{
|
||||
//pipe to a file
|
||||
//convert file to text via abiword
|
||||
//set text in the pad
|
||||
|
||||
var srcFile, destFile;
|
||||
var pad;
|
||||
var text;
|
||||
|
||||
async.series([
|
||||
//save the uploaded file to /tmp
|
||||
function(callback)
|
||||
{
|
||||
var form = new formidable.IncomingForm();
|
||||
form.keepExtensions = true;
|
||||
form.uploadDir = tempDirectory;
|
||||
|
||||
form.parse(req, function(err, fields, files)
|
||||
{
|
||||
//the upload failed, stop at this point
|
||||
if(err || files.file === undefined)
|
||||
{
|
||||
console.warn("Uploading Error: " + err.stack);
|
||||
callback("uploadFailed");
|
||||
}
|
||||
//everything ok, continue
|
||||
else
|
||||
{
|
||||
//save the path of the uploaded file
|
||||
srcFile = files.file.path;
|
||||
callback();
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
//ensure this is a file ending we know, else we change the file ending to .txt
|
||||
//this allows us to accept source code files like .c or .java
|
||||
function(callback)
|
||||
{
|
||||
var fileEnding = srcFile.split(".")[1].toLowerCase();
|
||||
var knownFileEndings = ["txt", "doc", "docx", "pdf", "odt", "html", "htm"];
|
||||
|
||||
//find out if this is a known file ending
|
||||
var fileEndingKnown = false;
|
||||
for(var i in knownFileEndings)
|
||||
{
|
||||
if(fileEnding == knownFileEndings[i])
|
||||
{
|
||||
fileEndingKnown = true;
|
||||
}
|
||||
}
|
||||
|
||||
//if the file ending is known, continue as normal
|
||||
if(fileEndingKnown)
|
||||
{
|
||||
callback();
|
||||
}
|
||||
//we need to rename this file with a .txt ending
|
||||
else
|
||||
{
|
||||
var oldSrcFile = srcFile;
|
||||
srcFile = srcFile.split(".")[0] + ".txt";
|
||||
|
||||
fs.rename(oldSrcFile, srcFile, callback);
|
||||
}
|
||||
},
|
||||
|
||||
//convert file to text
|
||||
function(callback)
|
||||
{
|
||||
var randNum = Math.floor(Math.random()*0xFFFFFFFF);
|
||||
destFile = tempDirectory + "eplite_import_" + randNum + ".txt";
|
||||
abiword.convertFile(srcFile, destFile, "txt", callback);
|
||||
},
|
||||
|
||||
//get the pad object
|
||||
function(callback)
|
||||
{
|
||||
padManager.getPad(padId, function(err, _pad)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
pad = _pad;
|
||||
callback();
|
||||
});
|
||||
},
|
||||
|
||||
//read the text
|
||||
function(callback)
|
||||
{
|
||||
fs.readFile(destFile, "utf8", function(err, _text)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
text = _text;
|
||||
|
||||
//node on windows has a delay on releasing of the file lock.
|
||||
//We add a 100ms delay to work around this
|
||||
if(os.type().indexOf("Windows") > -1)
|
||||
{
|
||||
setTimeout(function()
|
||||
{
|
||||
callback();
|
||||
}, 100);
|
||||
}
|
||||
else
|
||||
{
|
||||
callback();
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
//change text of the pad and broadcast the changeset
|
||||
function(callback)
|
||||
{
|
||||
pad.setText(text);
|
||||
padMessageHandler.updatePadClients(pad, callback);
|
||||
},
|
||||
|
||||
//clean up temporary files
|
||||
function(callback)
|
||||
{
|
||||
async.parallel([
|
||||
function(callback)
|
||||
{
|
||||
fs.unlink(srcFile, callback);
|
||||
},
|
||||
function(callback)
|
||||
{
|
||||
fs.unlink(destFile, callback);
|
||||
}
|
||||
], callback);
|
||||
}
|
||||
], function(err)
|
||||
{
|
||||
//the upload failed, there is nothing we can do, send a 500
|
||||
if(err == "uploadFailed")
|
||||
{
|
||||
res.send(500);
|
||||
return;
|
||||
}
|
||||
|
||||
ERR(err);
|
||||
|
||||
//close the connection
|
||||
res.send("ok");
|
||||
});
|
||||
}
|
926
src/node/handler/PadMessageHandler.js
Normal file
|
@ -0,0 +1,926 @@
|
|||
/**
|
||||
* The MessageHandler handles all Messages that comes from Socket.IO and controls the sessions
|
||||
*/
|
||||
|
||||
/*
|
||||
* Copyright 2009 Google Inc., 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
|
||||
*
|
||||
* 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 CommonCode = require('../utils/common_code');
|
||||
var ERR = require("async-stacktrace");
|
||||
var async = require("async");
|
||||
var padManager = require("../db/PadManager");
|
||||
var Changeset = CommonCode.require("/Changeset");
|
||||
var AttributePoolFactory = CommonCode.require("/AttributePoolFactory");
|
||||
var authorManager = require("../db/AuthorManager");
|
||||
var readOnlyManager = require("../db/ReadOnlyManager");
|
||||
var settings = require('../utils/Settings');
|
||||
var securityManager = require("../db/SecurityManager");
|
||||
var log4js = require('log4js');
|
||||
var messageLogger = log4js.getLogger("message");
|
||||
|
||||
/**
|
||||
* A associative array that translates a session to a pad
|
||||
*/
|
||||
var session2pad = {};
|
||||
/**
|
||||
* A associative array that saves which sessions belong to a pad
|
||||
*/
|
||||
var pad2sessions = {};
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
var sessioninfos = {};
|
||||
|
||||
/**
|
||||
* Saves the Socket class we need to send and recieve data from the client
|
||||
*/
|
||||
var socketio;
|
||||
|
||||
/**
|
||||
* This Method is called by server.js to tell the message handler on which socket it should send
|
||||
* @param socket_io The Socket
|
||||
*/
|
||||
exports.setSocketIO = function(socket_io)
|
||||
{
|
||||
socketio=socket_io;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the connection of a new user
|
||||
* @param client the new client
|
||||
*/
|
||||
exports.handleConnect = function(client)
|
||||
{
|
||||
//Initalize session2pad and sessioninfos for this new session
|
||||
session2pad[client.id]=null;
|
||||
sessioninfos[client.id]={};
|
||||
}
|
||||
|
||||
/**
|
||||
* Kicks all sessions from a pad
|
||||
* @param client the new client
|
||||
*/
|
||||
exports.kickSessionsFromPad = function(padID)
|
||||
{
|
||||
//skip if there is nobody on this pad
|
||||
if(!pad2sessions[padID])
|
||||
return;
|
||||
|
||||
//disconnect everyone from this pad
|
||||
for(var i in pad2sessions[padID])
|
||||
{
|
||||
socketio.sockets.sockets[pad2sessions[padID][i]].json.send({disconnect:"deleted"});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the disconnection of a user
|
||||
* @param client the client that leaves
|
||||
*/
|
||||
exports.handleDisconnect = function(client)
|
||||
{
|
||||
//save the padname of this session
|
||||
var sessionPad=session2pad[client.id];
|
||||
|
||||
//if this connection was already etablished with a handshake, send a disconnect message to the others
|
||||
if(sessioninfos[client.id] && sessioninfos[client.id].author)
|
||||
{
|
||||
var author = sessioninfos[client.id].author;
|
||||
|
||||
//get the author color out of the db
|
||||
authorManager.getAuthorColorId(author, function(err, color)
|
||||
{
|
||||
ERR(err);
|
||||
|
||||
//prepare the notification for the other users on the pad, that this user left
|
||||
var messageToTheOtherUsers = {
|
||||
"type": "COLLABROOM",
|
||||
"data": {
|
||||
type: "USER_LEAVE",
|
||||
userInfo: {
|
||||
"ip": "127.0.0.1",
|
||||
"colorId": color,
|
||||
"userAgent": "Anonymous",
|
||||
"userId": author
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
//Go trough all user that are still on the pad, and send them the USER_LEAVE message
|
||||
for(i in pad2sessions[sessionPad])
|
||||
{
|
||||
socketio.sockets.sockets[pad2sessions[sessionPad][i]].json.send(messageToTheOtherUsers);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
//Go trough all sessions of this pad, search and destroy the entry of this client
|
||||
for(i in pad2sessions[sessionPad])
|
||||
{
|
||||
if(pad2sessions[sessionPad][i] == client.id)
|
||||
{
|
||||
pad2sessions[sessionPad].splice(i, 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
//Delete the session2pad and sessioninfos entrys of this session
|
||||
delete session2pad[client.id];
|
||||
delete sessioninfos[client.id];
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles a message from a user
|
||||
* @param client the client that send this message
|
||||
* @param message the message from the client
|
||||
*/
|
||||
exports.handleMessage = function(client, message)
|
||||
{
|
||||
if(message == null)
|
||||
{
|
||||
messageLogger.warn("Message is null!");
|
||||
return;
|
||||
}
|
||||
if(!message.type)
|
||||
{
|
||||
messageLogger.warn("Message has no type attribute!");
|
||||
return;
|
||||
}
|
||||
|
||||
//Check what type of message we get and delegate to the other methodes
|
||||
if(message.type == "CLIENT_READY")
|
||||
{
|
||||
handleClientReady(client, message);
|
||||
}
|
||||
else if(message.type == "COLLABROOM" &&
|
||||
message.data.type == "USER_CHANGES")
|
||||
{
|
||||
handleUserChanges(client, message);
|
||||
}
|
||||
else if(message.type == "COLLABROOM" &&
|
||||
message.data.type == "USERINFO_UPDATE")
|
||||
{
|
||||
handleUserInfoUpdate(client, message);
|
||||
}
|
||||
else if(message.type == "COLLABROOM" &&
|
||||
message.data.type == "CHAT_MESSAGE")
|
||||
{
|
||||
handleChatMessage(client, message);
|
||||
}
|
||||
else if(message.type == "COLLABROOM" &&
|
||||
message.data.type == "CLIENT_MESSAGE" &&
|
||||
message.data.payload.type == "suggestUserName")
|
||||
{
|
||||
handleSuggestUserName(client, message);
|
||||
}
|
||||
//if the message type is unknown, throw an exception
|
||||
else
|
||||
{
|
||||
messageLogger.warn("Dropped message, unknown Message Type " + message.type);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles a Chat Message
|
||||
* @param client the client that send this message
|
||||
* @param message the message from the client
|
||||
*/
|
||||
function handleChatMessage(client, message)
|
||||
{
|
||||
var time = new Date().getTime();
|
||||
var userId = sessioninfos[client.id].author;
|
||||
var text = message.data.text;
|
||||
var padId = session2pad[client.id];
|
||||
|
||||
var pad;
|
||||
var userName;
|
||||
|
||||
async.series([
|
||||
//get the pad
|
||||
function(callback)
|
||||
{
|
||||
padManager.getPad(padId, function(err, _pad)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
pad = _pad;
|
||||
callback();
|
||||
});
|
||||
},
|
||||
function(callback)
|
||||
{
|
||||
authorManager.getAuthorName(userId, function(err, _userName)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
userName = _userName;
|
||||
callback();
|
||||
});
|
||||
},
|
||||
//save the chat message and broadcast it
|
||||
function(callback)
|
||||
{
|
||||
//save the chat message
|
||||
pad.appendChatMessage(text, userId, time);
|
||||
|
||||
var msg = {
|
||||
type: "COLLABROOM",
|
||||
data: {
|
||||
type: "CHAT_MESSAGE",
|
||||
userId: userId,
|
||||
userName: userName,
|
||||
time: time,
|
||||
text: text
|
||||
}
|
||||
};
|
||||
|
||||
//broadcast the chat message to everyone on the pad
|
||||
for(var i in pad2sessions[padId])
|
||||
{
|
||||
socketio.sockets.sockets[pad2sessions[padId][i]].json.send(msg);
|
||||
}
|
||||
|
||||
callback();
|
||||
}
|
||||
], function(err)
|
||||
{
|
||||
ERR(err);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Handles a handleSuggestUserName, that means a user have suggest a userName for a other user
|
||||
* @param client the client that send this message
|
||||
* @param message the message from the client
|
||||
*/
|
||||
function handleSuggestUserName(client, message)
|
||||
{
|
||||
//check if all ok
|
||||
if(message.data.payload.newName == null)
|
||||
{
|
||||
messageLogger.warn("Dropped message, suggestUserName Message has no newName!");
|
||||
return;
|
||||
}
|
||||
if(message.data.payload.unnamedId == null)
|
||||
{
|
||||
messageLogger.warn("Dropped message, suggestUserName Message has no unnamedId!");
|
||||
return;
|
||||
}
|
||||
|
||||
var padId = session2pad[client.id];
|
||||
|
||||
//search the author and send him this message
|
||||
for(var i in pad2sessions[padId])
|
||||
{
|
||||
if(sessioninfos[pad2sessions[padId][i]].author == message.data.payload.unnamedId)
|
||||
{
|
||||
socketio.sockets.sockets[pad2sessions[padId][i]].send(message);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
function handleUserInfoUpdate(client, message)
|
||||
{
|
||||
//check if all ok
|
||||
if(message.data.userInfo.colorId == null)
|
||||
{
|
||||
messageLogger.warn("Dropped message, USERINFO_UPDATE Message has no colorId!");
|
||||
return;
|
||||
}
|
||||
|
||||
//Find out the author name of this session
|
||||
var author = sessioninfos[client.id].author;
|
||||
|
||||
//Tell the authorManager about the new attributes
|
||||
authorManager.setAuthorColorId(author, message.data.userInfo.colorId);
|
||||
authorManager.setAuthorName(author, message.data.userInfo.name);
|
||||
|
||||
var padId = session2pad[client.id];
|
||||
|
||||
//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(var i in pad2sessions[padId])
|
||||
{
|
||||
if(pad2sessions[padId][i] != client.id)
|
||||
{
|
||||
socketio.sockets.sockets[pad2sessions[padId][i]].json.send(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
function handleUserChanges(client, message)
|
||||
{
|
||||
//check if all ok
|
||||
if(message.data.baseRev == null)
|
||||
{
|
||||
messageLogger.warn("Dropped message, USER_CHANGES Message has no baseRev!");
|
||||
return;
|
||||
}
|
||||
if(message.data.apool == null)
|
||||
{
|
||||
messageLogger.warn("Dropped message, USER_CHANGES Message has no apool!");
|
||||
return;
|
||||
}
|
||||
if(message.data.changeset == null)
|
||||
{
|
||||
messageLogger.warn("Dropped message, USER_CHANGES Message has no changeset!");
|
||||
return;
|
||||
}
|
||||
|
||||
//get all Vars we need
|
||||
var baseRev = message.data.baseRev;
|
||||
var wireApool = (AttributePoolFactory.createAttributePool()).fromJsonable(message.data.apool);
|
||||
var changeset = message.data.changeset;
|
||||
|
||||
var r, apool, pad;
|
||||
|
||||
async.series([
|
||||
//get the pad
|
||||
function(callback)
|
||||
{
|
||||
padManager.getPad(session2pad[client.id], function(err, value)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
pad = value;
|
||||
callback();
|
||||
});
|
||||
},
|
||||
//create the changeset
|
||||
function(callback)
|
||||
{
|
||||
//ex. _checkChangesetAndPool
|
||||
|
||||
//Copied from Etherpad, don't know what it does exactly
|
||||
try
|
||||
{
|
||||
//this looks like a changeset check, it throws errors sometimes
|
||||
Changeset.checkRep(changeset);
|
||||
|
||||
Changeset.eachAttribNumber(changeset, function(n) {
|
||||
if (! wireApool.getAttrib(n)) {
|
||||
throw "Attribute pool is missing attribute "+n+" for changeset "+changeset;
|
||||
}
|
||||
});
|
||||
}
|
||||
//there is an error in this changeset, so just refuse it
|
||||
catch(e)
|
||||
{
|
||||
console.warn("Can't apply USER_CHANGES "+changeset+", cause it faild checkRep");
|
||||
client.json.send({disconnect:"badChangeset"});
|
||||
return;
|
||||
}
|
||||
|
||||
//ex. adoptChangesetAttribs
|
||||
|
||||
//Afaik, it copies the new attributes from the changeset, to the global Attribute Pool
|
||||
changeset = Changeset.moveOpsToNewPool(changeset, wireApool, pad.pool);
|
||||
|
||||
//ex. applyUserChanges
|
||||
apool = pad.pool;
|
||||
r = baseRev;
|
||||
|
||||
//https://github.com/caolan/async#whilst
|
||||
async.whilst(
|
||||
function() { return r < pad.getHeadRevisionNumber(); },
|
||||
function(callback)
|
||||
{
|
||||
r++;
|
||||
|
||||
pad.getRevisionChangeset(r, function(err, c)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
changeset = Changeset.follow(c, changeset, false, apool);
|
||||
callback(null);
|
||||
});
|
||||
},
|
||||
//use the callback of the series function
|
||||
callback
|
||||
);
|
||||
},
|
||||
//do correction changesets, and send it to all users
|
||||
function (callback)
|
||||
{
|
||||
var prevText = pad.text();
|
||||
|
||||
if (Changeset.oldLen(changeset) != prevText.length)
|
||||
{
|
||||
console.warn("Can't apply USER_CHANGES "+changeset+" with oldLen " + Changeset.oldLen(changeset) + " to document of length " + prevText.length);
|
||||
client.json.send({disconnect:"badChangeset"});
|
||||
callback();
|
||||
return;
|
||||
}
|
||||
|
||||
var thisAuthor = sessioninfos[client.id].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);
|
||||
}
|
||||
|
||||
exports.updatePadClients(pad, callback);
|
||||
}
|
||||
], function(err)
|
||||
{
|
||||
ERR(err);
|
||||
});
|
||||
}
|
||||
|
||||
exports.updatePadClients = function(pad, callback)
|
||||
{
|
||||
//skip this step if noone is on this pad
|
||||
if(!pad2sessions[pad.id])
|
||||
{
|
||||
callback();
|
||||
return;
|
||||
}
|
||||
|
||||
//go trough all sessions on this pad
|
||||
async.forEach(pad2sessions[pad.id], function(session, callback)
|
||||
{
|
||||
var lastRev = sessioninfos[session].rev;
|
||||
|
||||
//https://github.com/caolan/async#whilst
|
||||
//send them all new changesets
|
||||
async.whilst(
|
||||
function (){ return lastRev < pad.getHeadRevisionNumber()},
|
||||
function(callback)
|
||||
{
|
||||
var author, revChangeset;
|
||||
|
||||
var r = ++lastRev;
|
||||
|
||||
async.parallel([
|
||||
function (callback)
|
||||
{
|
||||
pad.getRevisionAuthor(r, function(err, value)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
author = value;
|
||||
callback();
|
||||
});
|
||||
},
|
||||
function (callback)
|
||||
{
|
||||
pad.getRevisionChangeset(r, function(err, value)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
revChangeset = value;
|
||||
callback();
|
||||
});
|
||||
}
|
||||
], function(err)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
// next if session has not been deleted
|
||||
if(sessioninfos[session] == null)
|
||||
{
|
||||
callback(null);
|
||||
return;
|
||||
}
|
||||
if(author == sessioninfos[session].author)
|
||||
{
|
||||
socketio.sockets.sockets[session].json.send({"type":"COLLABROOM","data":{type:"ACCEPT_COMMIT", newRev:r}});
|
||||
}
|
||||
else
|
||||
{
|
||||
var forWire = Changeset.prepareForWire(revChangeset, pad.pool);
|
||||
var wireMsg = {"type":"COLLABROOM","data":{type:"NEW_CHANGES", newRev:r,
|
||||
changeset: forWire.translated,
|
||||
apool: forWire.pool,
|
||||
author: author}};
|
||||
|
||||
socketio.sockets.sockets[session].json.send(wireMsg);
|
||||
}
|
||||
|
||||
callback(null);
|
||||
});
|
||||
},
|
||||
callback
|
||||
);
|
||||
|
||||
if(sessioninfos[session] != null)
|
||||
{
|
||||
sessioninfos[session].rev = pad.getHeadRevisionNumber();
|
||||
}
|
||||
},callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copied from the Etherpad Source Code. Don't know what this methode does excatly...
|
||||
*/
|
||||
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();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
function handleClientReady(client, message)
|
||||
{
|
||||
//check if all ok
|
||||
if(!message.token)
|
||||
{
|
||||
messageLogger.warn("Dropped message, CLIENT_READY Message has no token!");
|
||||
return;
|
||||
}
|
||||
if(!message.padId)
|
||||
{
|
||||
messageLogger.warn("Dropped message, CLIENT_READY Message has no padId!");
|
||||
return;
|
||||
}
|
||||
if(!message.protocolVersion)
|
||||
{
|
||||
messageLogger.warn("Dropped message, CLIENT_READY Message has no protocolVersion!");
|
||||
return;
|
||||
}
|
||||
if(message.protocolVersion != 2)
|
||||
{
|
||||
messageLogger.warn("Dropped message, CLIENT_READY Message has a unknown protocolVersion '" + message.protocolVersion + "'!");
|
||||
return;
|
||||
}
|
||||
|
||||
var author;
|
||||
var authorName;
|
||||
var authorColorId;
|
||||
var pad;
|
||||
var historicalAuthorData = {};
|
||||
var readOnlyId;
|
||||
var chatMessages;
|
||||
|
||||
async.series([
|
||||
//check permissions
|
||||
function(callback)
|
||||
{
|
||||
securityManager.checkAccess (message.padId, message.sessionID, message.token, message.password, function(err, statusObject)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//access was granted
|
||||
if(statusObject.accessStatus == "grant")
|
||||
{
|
||||
author = statusObject.authorID;
|
||||
callback();
|
||||
}
|
||||
//no access, send the client a message that tell him why
|
||||
else
|
||||
{
|
||||
client.json.send({accessStatus: statusObject.accessStatus})
|
||||
}
|
||||
});
|
||||
},
|
||||
//get all authordata of this new user
|
||||
function(callback)
|
||||
{
|
||||
async.parallel([
|
||||
//get colorId
|
||||
function(callback)
|
||||
{
|
||||
authorManager.getAuthorColorId(author, function(err, value)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
authorColorId = value;
|
||||
callback();
|
||||
});
|
||||
},
|
||||
//get author name
|
||||
function(callback)
|
||||
{
|
||||
authorManager.getAuthorName(author, function(err, value)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
authorName = value;
|
||||
callback();
|
||||
});
|
||||
},
|
||||
function(callback)
|
||||
{
|
||||
padManager.getPad(message.padId, function(err, value)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
pad = value;
|
||||
callback();
|
||||
});
|
||||
},
|
||||
function(callback)
|
||||
{
|
||||
readOnlyManager.getReadOnlyId(message.padId, function(err, value)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
readOnlyId = value;
|
||||
callback();
|
||||
});
|
||||
}
|
||||
], callback);
|
||||
},
|
||||
//these db requests all need the pad object
|
||||
function(callback)
|
||||
{
|
||||
var authors = pad.getAllAuthors();
|
||||
|
||||
async.parallel([
|
||||
//get all author data out of the database
|
||||
function(callback)
|
||||
{
|
||||
async.forEach(authors, function(authorId, callback)
|
||||
{
|
||||
authorManager.getAuthor(authorId, function(err, author)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
delete author.timestamp;
|
||||
historicalAuthorData[authorId] = author;
|
||||
callback();
|
||||
});
|
||||
}, callback);
|
||||
},
|
||||
//get the latest chat messages
|
||||
function(callback)
|
||||
{
|
||||
pad.getLastChatMessages(100, function(err, _chatMessages)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
chatMessages = _chatMessages;
|
||||
callback();
|
||||
});
|
||||
}
|
||||
], callback);
|
||||
|
||||
|
||||
},
|
||||
function(callback)
|
||||
{
|
||||
//Check if this author is already on the pad, if yes, kick the other sessions!
|
||||
if(pad2sessions[message.padId])
|
||||
{
|
||||
for(var i in pad2sessions[message.padId])
|
||||
{
|
||||
if(sessioninfos[pad2sessions[message.padId][i]].author == author)
|
||||
{
|
||||
socketio.sockets.sockets[pad2sessions[message.padId][i]].json.send({disconnect:"userdup"});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Save in session2pad that this session belonges to this pad
|
||||
var sessionId=String(client.id);
|
||||
session2pad[sessionId] = message.padId;
|
||||
|
||||
//check if there is already a pad2sessions entry, if not, create one
|
||||
if(!pad2sessions[message.padId])
|
||||
{
|
||||
pad2sessions[message.padId] = [];
|
||||
}
|
||||
|
||||
//Saves in pad2sessions that this session belongs to this pad
|
||||
pad2sessions[message.padId].push(sessionId);
|
||||
|
||||
//prepare all values for the wire
|
||||
var atext = Changeset.cloneAText(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,
|
||||
"clientIp": "127.0.0.1",
|
||||
//"clientAgent": "Anonymous Agent",
|
||||
"padId": message.padId,
|
||||
"historicalAuthorData": 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", "#4c9c82", "#12d1ad", "#2d8e80", "#7485c3", "#a091c7", "#3185ab", "#6818b4", "#e6e76d", "#a42c64", "#f386e5", "#4ecc0c", "#c0c236", "#693224", "#b5de6a", "#9b88fd", "#358f9b", "#496d2f", "#e267fe", "#d23056", "#1a1a64", "#5aa335", "#d722bb", "#86dc6c", "#b5a714", "#955b6a", "#9f2985", "#4b81c8", "#3d6a5b", "#434e16", "#d16084", "#af6a0e", "#8c8bd8"],
|
||||
"clientIp": "127.0.0.1",
|
||||
"userIsGuest": true,
|
||||
"userColor": authorColorId,
|
||||
"padId": message.padId,
|
||||
"initialTitle": "Pad: " + message.padId,
|
||||
"opts": {},
|
||||
"chatHistory": chatMessages,
|
||||
"numConnectedUsers": pad2sessions[message.padId].length,
|
||||
"isProPad": false,
|
||||
"readOnlyId": readOnlyId,
|
||||
"serverTimestamp": new Date().getTime(),
|
||||
"globalPadId": message.padId,
|
||||
"userId": author,
|
||||
"cookiePrefsToSet": {
|
||||
"fullWidth": false,
|
||||
"hideSidebar": false
|
||||
},
|
||||
"abiwordAvailable": settings.abiwordAvailable(),
|
||||
"hooks": {}
|
||||
}
|
||||
|
||||
//Add a username to the clientVars if one avaiable
|
||||
if(authorName != null)
|
||||
{
|
||||
clientVars.userName = authorName;
|
||||
}
|
||||
|
||||
if(sessioninfos[client.id] !== undefined)
|
||||
{
|
||||
//This is a reconnect, so we don't have to send the client the ClientVars again
|
||||
if(message.reconnect == true)
|
||||
{
|
||||
//Save the revision in sessioninfos, we take the revision from the info the client send to us
|
||||
sessioninfos[client.id].rev = message.client_rev;
|
||||
}
|
||||
//This is a normal first connect
|
||||
else
|
||||
{
|
||||
//Send the clientVars to the Client
|
||||
client.json.send(clientVars);
|
||||
//Save the revision in sessioninfos
|
||||
sessioninfos[client.id].rev = pad.getHeadRevisionNumber();
|
||||
}
|
||||
|
||||
//Save the revision and the author id in sessioninfos
|
||||
sessioninfos[client.id].author = author;
|
||||
}
|
||||
|
||||
//prepare the notification for the other users on the pad, that this user joined
|
||||
var messageToTheOtherUsers = {
|
||||
"type": "COLLABROOM",
|
||||
"data": {
|
||||
type: "USER_NEWINFO",
|
||||
userInfo: {
|
||||
"ip": "127.0.0.1",
|
||||
"colorId": authorColorId,
|
||||
"userAgent": "Anonymous",
|
||||
"userId": author
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
//Add the authorname of this new User, if avaiable
|
||||
if(authorName != null)
|
||||
{
|
||||
messageToTheOtherUsers.data.userInfo.name = authorName;
|
||||
}
|
||||
|
||||
//Run trough all sessions of this pad
|
||||
async.forEach(pad2sessions[message.padId], function(sessionID, callback)
|
||||
{
|
||||
var author, socket, sessionAuthorName, sessionAuthorColorId;
|
||||
|
||||
//Since sessioninfos might change while being enumerated, check if the
|
||||
//sessionID is still assigned to a valid session
|
||||
if(sessioninfos[sessionID] !== undefined &&
|
||||
socketio.sockets.sockets[sessionID] !== undefined){
|
||||
author = sessioninfos[sessionID].author;
|
||||
socket = socketio.sockets.sockets[sessionID];
|
||||
}else {
|
||||
// If the sessionID is not valid, callback();
|
||||
callback();
|
||||
return;
|
||||
}
|
||||
async.series([
|
||||
//get the authorname & colorId
|
||||
function(callback)
|
||||
{
|
||||
async.parallel([
|
||||
function(callback)
|
||||
{
|
||||
authorManager.getAuthorColorId(author, function(err, value)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
sessionAuthorColorId = value;
|
||||
callback();
|
||||
})
|
||||
},
|
||||
function(callback)
|
||||
{
|
||||
authorManager.getAuthorName(author, function(err, value)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
sessionAuthorName = value;
|
||||
callback();
|
||||
})
|
||||
}
|
||||
],callback);
|
||||
},
|
||||
function (callback)
|
||||
{
|
||||
//Jump over, if this session is the connection session
|
||||
if(sessionID != client.id)
|
||||
{
|
||||
//Send this Session the Notification about the new user
|
||||
socket.json.send(messageToTheOtherUsers);
|
||||
|
||||
//Send the new User a Notification about this other user
|
||||
var messageToNotifyTheClientAboutTheOthers = {
|
||||
"type": "COLLABROOM",
|
||||
"data": {
|
||||
type: "USER_NEWINFO",
|
||||
userInfo: {
|
||||
"ip": "127.0.0.1",
|
||||
"colorId": sessionAuthorColorId,
|
||||
"name": sessionAuthorName,
|
||||
"userAgent": "Anonymous",
|
||||
"userId": author
|
||||
}
|
||||
}
|
||||
};
|
||||
client.json.send(messageToNotifyTheClientAboutTheOthers);
|
||||
}
|
||||
}
|
||||
], callback);
|
||||
}, callback);
|
||||
}
|
||||
],function(err)
|
||||
{
|
||||
ERR(err);
|
||||
});
|
||||
}
|
163
src/node/handler/SocketIORouter.js
Normal file
|
@ -0,0 +1,163 @@
|
|||
/**
|
||||
* This is the Socket.IO Router. It routes the Messages between the
|
||||
* components of the Server. The components are at the moment: pad and timeslider
|
||||
*/
|
||||
|
||||
/*
|
||||
* 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
|
||||
*
|
||||
* 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 ERR = require("async-stacktrace");
|
||||
var log4js = require('log4js');
|
||||
var messageLogger = log4js.getLogger("message");
|
||||
var securityManager = require("../db/SecurityManager");
|
||||
|
||||
/**
|
||||
* Saves all components
|
||||
* key is the component name
|
||||
* value is the component module
|
||||
*/
|
||||
var components = {};
|
||||
|
||||
var socket;
|
||||
|
||||
/**
|
||||
* adds a component
|
||||
*/
|
||||
exports.addComponent = function(moduleName, module)
|
||||
{
|
||||
//save the component
|
||||
components[moduleName] = module;
|
||||
|
||||
//give the module the socket
|
||||
module.setSocketIO(socket);
|
||||
}
|
||||
|
||||
/**
|
||||
* sets the socket.io and adds event functions for routing
|
||||
*/
|
||||
exports.setSocketIO = function(_socket)
|
||||
{
|
||||
//save this socket internaly
|
||||
socket = _socket;
|
||||
|
||||
socket.sockets.on('connection', function(client)
|
||||
{
|
||||
var clientAuthorized = false;
|
||||
|
||||
//wrap the original send function to log the messages
|
||||
client._send = client.send;
|
||||
client.send = function(message)
|
||||
{
|
||||
messageLogger.info("to " + client.id + ": " + stringifyWithoutPassword(message));
|
||||
client._send(message);
|
||||
}
|
||||
|
||||
//tell all components about this connect
|
||||
for(var i in components)
|
||||
{
|
||||
components[i].handleConnect(client);
|
||||
}
|
||||
|
||||
//try to handle the message of this client
|
||||
function handleMessage(message)
|
||||
{
|
||||
if(message.component && components[message.component])
|
||||
{
|
||||
//check if component is registered in the components array
|
||||
if(components[message.component])
|
||||
{
|
||||
messageLogger.info("from " + client.id + ": " + stringifyWithoutPassword(message));
|
||||
components[message.component].handleMessage(client, message);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
messageLogger.error("Can't route the message:" + stringifyWithoutPassword(message));
|
||||
}
|
||||
}
|
||||
|
||||
client.on('message', function(message)
|
||||
{
|
||||
if(message.protocolVersion && message.protocolVersion != 2)
|
||||
{
|
||||
messageLogger.warn("Protocolversion header is not correct:" + stringifyWithoutPassword(message));
|
||||
return;
|
||||
}
|
||||
|
||||
//client is authorized, everything ok
|
||||
if(clientAuthorized)
|
||||
{
|
||||
handleMessage(message);
|
||||
}
|
||||
//try to authorize the client
|
||||
else
|
||||
{
|
||||
//this message has everything to try an authorization
|
||||
if(message.padId !== undefined && message.sessionID !== undefined && message.token !== undefined && message.password !== undefined)
|
||||
{
|
||||
securityManager.checkAccess (message.padId, message.sessionID, message.token, message.password, function(err, statusObject)
|
||||
{
|
||||
ERR(err);
|
||||
|
||||
//access was granted, mark the client as authorized and handle the message
|
||||
if(statusObject.accessStatus == "grant")
|
||||
{
|
||||
clientAuthorized = true;
|
||||
handleMessage(message);
|
||||
}
|
||||
//no access, send the client a message that tell him why
|
||||
else
|
||||
{
|
||||
messageLogger.warn("Authentication try failed:" + stringifyWithoutPassword(message));
|
||||
client.json.send({accessStatus: statusObject.accessStatus});
|
||||
}
|
||||
});
|
||||
}
|
||||
//drop message
|
||||
else
|
||||
{
|
||||
messageLogger.warn("Dropped message cause of bad permissions:" + stringifyWithoutPassword(message));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
client.on('disconnect', function()
|
||||
{
|
||||
//tell all components about this disconnect
|
||||
for(var i in components)
|
||||
{
|
||||
components[i].handleDisconnect(client);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
//returns a stringified representation of a message, removes the password
|
||||
//this ensures there are no passwords in the log
|
||||
function stringifyWithoutPassword(message)
|
||||
{
|
||||
var newMessage = {};
|
||||
|
||||
for(var i in message)
|
||||
{
|
||||
if(i == "password" && message[i] != null)
|
||||
newMessage["password"] = "xxx";
|
||||
else
|
||||
newMessage[i]=message[i];
|
||||
}
|
||||
|
||||
return JSON.stringify(newMessage);
|
||||
}
|
529
src/node/handler/TimesliderMessageHandler.js
Normal file
|
@ -0,0 +1,529 @@
|
|||
/**
|
||||
* The MessageHandler handles all Messages that comes from Socket.IO and controls the sessions
|
||||
*/
|
||||
|
||||
/*
|
||||
* Copyright 2009 Google Inc., 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
|
||||
*
|
||||
* 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 CommonCode = require('../utils/common_code');
|
||||
var ERR = require("async-stacktrace");
|
||||
var async = require("async");
|
||||
var padManager = require("../db/PadManager");
|
||||
var Changeset = CommonCode.require("/Changeset");
|
||||
var AttributePoolFactory = CommonCode.require("/AttributePoolFactory");
|
||||
var settings = require('../utils/Settings');
|
||||
var authorManager = require("../db/AuthorManager");
|
||||
var log4js = require('log4js');
|
||||
var messageLogger = log4js.getLogger("message");
|
||||
|
||||
/**
|
||||
* Saves the Socket class we need to send and recieve data from the client
|
||||
*/
|
||||
var socketio;
|
||||
|
||||
/**
|
||||
* This Method is called by server.js to tell the message handler on which socket it should send
|
||||
* @param socket_io The Socket
|
||||
*/
|
||||
exports.setSocketIO = function(socket_io)
|
||||
{
|
||||
socketio=socket_io;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the connection of a new user
|
||||
* @param client the new client
|
||||
*/
|
||||
exports.handleConnect = function(client)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the disconnection of a user
|
||||
* @param client the client that leaves
|
||||
*/
|
||||
exports.handleDisconnect = function(client)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles a message from a user
|
||||
* @param client the client that send this message
|
||||
* @param message the message from the client
|
||||
*/
|
||||
exports.handleMessage = function(client, message)
|
||||
{
|
||||
//Check what type of message we get and delegate to the other methodes
|
||||
if(message.type == "CLIENT_READY")
|
||||
{
|
||||
handleClientReady(client, message);
|
||||
}
|
||||
else if(message.type == "CHANGESET_REQ")
|
||||
{
|
||||
handleChangesetRequest(client, message);
|
||||
}
|
||||
//if the message type is unkown, throw an exception
|
||||
else
|
||||
{
|
||||
messageLogger.warn("Dropped message, unknown Message Type: '" + message.type + "'");
|
||||
}
|
||||
}
|
||||
|
||||
function handleClientReady(client, message)
|
||||
{
|
||||
if(message.padId == null)
|
||||
{
|
||||
messageLogger.warn("Dropped message, changeset request has no padId!");
|
||||
return;
|
||||
}
|
||||
|
||||
//send the timeslider client the clientVars, with this values its able to start
|
||||
createTimesliderClientVars (message.padId, function(err, clientVars)
|
||||
{
|
||||
ERR(err);
|
||||
|
||||
client.json.send({type: "CLIENT_VARS", data: clientVars});
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles a request for a rough changeset, the timeslider client needs it
|
||||
*/
|
||||
function handleChangesetRequest(client, message)
|
||||
{
|
||||
//check if all ok
|
||||
if(message.data == null)
|
||||
{
|
||||
messageLogger.warn("Dropped message, changeset request has no data!");
|
||||
return;
|
||||
}
|
||||
if(message.padId == null)
|
||||
{
|
||||
messageLogger.warn("Dropped message, changeset request has no padId!");
|
||||
return;
|
||||
}
|
||||
if(message.data.granularity == null)
|
||||
{
|
||||
messageLogger.warn("Dropped message, changeset request has no granularity!");
|
||||
return;
|
||||
}
|
||||
if(message.data.start == null)
|
||||
{
|
||||
messageLogger.warn("Dropped message, changeset request has no start!");
|
||||
return;
|
||||
}
|
||||
if(message.data.requestID == null)
|
||||
{
|
||||
messageLogger.warn("Dropped message, changeset request has no requestID!");
|
||||
return;
|
||||
}
|
||||
|
||||
var granularity = message.data.granularity;
|
||||
var start = message.data.start;
|
||||
var end = start + (100 * granularity);
|
||||
var padId = message.padId;
|
||||
|
||||
//build the requested rough changesets and send them back
|
||||
getChangesetInfo(padId, start, end, granularity, function(err, changesetInfo)
|
||||
{
|
||||
ERR(err);
|
||||
|
||||
var data = changesetInfo;
|
||||
data.requestID = message.data.requestID;
|
||||
|
||||
client.json.send({type: "CHANGESET_REQ", data: data});
|
||||
});
|
||||
}
|
||||
|
||||
function createTimesliderClientVars (padId, callback)
|
||||
{
|
||||
var clientVars = {
|
||||
viewId: 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"],
|
||||
sliderEnabled : true,
|
||||
supportsSlider: true,
|
||||
savedRevisions: [],
|
||||
padIdForUrl: padId,
|
||||
fullWidth: false,
|
||||
disableRightBar: false,
|
||||
initialChangesets: [],
|
||||
abiwordAvailable: settings.abiwordAvailable(),
|
||||
hooks: [],
|
||||
initialStyledContents: {}
|
||||
};
|
||||
var pad;
|
||||
var initialChangesets = [];
|
||||
|
||||
async.series([
|
||||
//get the pad from the database
|
||||
function(callback)
|
||||
{
|
||||
padManager.getPad(padId, function(err, _pad)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
pad = _pad;
|
||||
callback();
|
||||
});
|
||||
},
|
||||
//get all authors and add them to
|
||||
function(callback)
|
||||
{
|
||||
var historicalAuthorData = {};
|
||||
//get all authors out of the attribut pool
|
||||
var authors = pad.getAllAuthors();
|
||||
|
||||
//get all author data out of the database
|
||||
async.forEach(authors, function(authorId, callback)
|
||||
{
|
||||
authorManager.getAuthor(authorId, function(err, author)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
historicalAuthorData[authorId] = author;
|
||||
callback();
|
||||
});
|
||||
}, function(err)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
//add historicalAuthorData to the clientVars and continue
|
||||
clientVars.historicalAuthorData = historicalAuthorData;
|
||||
clientVars.initialStyledContents.historicalAuthorData = historicalAuthorData;
|
||||
callback();
|
||||
});
|
||||
},
|
||||
//get the timestamp of the last revision
|
||||
function(callback)
|
||||
{
|
||||
pad.getRevisionDate(pad.getHeadRevisionNumber(), function(err, date)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
clientVars.currentTime = date;
|
||||
callback();
|
||||
});
|
||||
},
|
||||
function(callback)
|
||||
{
|
||||
//get the head revision Number
|
||||
var lastRev = pad.getHeadRevisionNumber();
|
||||
|
||||
//add the revNum to the client Vars
|
||||
clientVars.revNum = lastRev;
|
||||
clientVars.totalRevs = lastRev;
|
||||
|
||||
var atext = Changeset.cloneAText(pad.atext);
|
||||
var attribsForWire = Changeset.prepareForWire(atext.attribs, pad.pool);
|
||||
var apool = attribsForWire.pool.toJsonable();
|
||||
atext.attribs = attribsForWire.translated;
|
||||
|
||||
clientVars.initialStyledContents.apool = apool;
|
||||
clientVars.initialStyledContents.atext = atext;
|
||||
|
||||
var granularities = [100, 10, 1];
|
||||
|
||||
//get the latest rough changesets
|
||||
async.forEach(granularities, function(granularity, callback)
|
||||
{
|
||||
var topGranularity = granularity*10;
|
||||
|
||||
getChangesetInfo(padId, Math.floor(lastRev / topGranularity)*topGranularity,
|
||||
Math.floor(lastRev / topGranularity)*topGranularity+topGranularity, granularity,
|
||||
function(err, changeset)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
clientVars.initialChangesets.push(changeset);
|
||||
callback();
|
||||
});
|
||||
}, callback);
|
||||
}
|
||||
], function(err)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
callback(null, clientVars);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to rebuild the getChangestInfo function of the original Etherpad
|
||||
* https://github.com/ether/pad/blob/master/etherpad/src/etherpad/control/pad/pad_changeset_control.js#L144
|
||||
*/
|
||||
function getChangesetInfo(padId, startNum, endNum, granularity, callback)
|
||||
{
|
||||
var forwardsChangesets = [];
|
||||
var backwardsChangesets = [];
|
||||
var timeDeltas = [];
|
||||
var apool = AttributePoolFactory.createAttributePool();
|
||||
var pad;
|
||||
var composedChangesets = {};
|
||||
var revisionDate = [];
|
||||
var lines;
|
||||
|
||||
async.series([
|
||||
//get the pad from the database
|
||||
function(callback)
|
||||
{
|
||||
padManager.getPad(padId, function(err, _pad)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
pad = _pad;
|
||||
callback();
|
||||
});
|
||||
},
|
||||
function(callback)
|
||||
{
|
||||
//calculate the last full endnum
|
||||
var lastRev = pad.getHeadRevisionNumber();
|
||||
if (endNum > lastRev+1) {
|
||||
endNum = lastRev+1;
|
||||
}
|
||||
endNum = Math.floor(endNum / granularity)*granularity;
|
||||
|
||||
var compositesChangesetNeeded = [];
|
||||
var revTimesNeeded = [];
|
||||
|
||||
//figure out which composite Changeset and revTimes we need, to load them in bulk
|
||||
var compositeStart = startNum;
|
||||
while (compositeStart < endNum)
|
||||
{
|
||||
var compositeEnd = compositeStart + granularity;
|
||||
|
||||
//add the composite Changeset we needed
|
||||
compositesChangesetNeeded.push({start: compositeStart, end: compositeEnd});
|
||||
|
||||
//add the t1 time we need
|
||||
revTimesNeeded.push(compositeStart == 0 ? 0 : compositeStart - 1);
|
||||
//add the t2 time we need
|
||||
revTimesNeeded.push(compositeEnd - 1);
|
||||
|
||||
compositeStart += granularity;
|
||||
}
|
||||
|
||||
//get all needed db values parallel
|
||||
async.parallel([
|
||||
function(callback)
|
||||
{
|
||||
//get all needed composite Changesets
|
||||
async.forEach(compositesChangesetNeeded, function(item, callback)
|
||||
{
|
||||
composePadChangesets(padId, item.start, item.end, function(err, changeset)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
composedChangesets[item.start + "/" + item.end] = changeset;
|
||||
callback();
|
||||
});
|
||||
}, callback);
|
||||
},
|
||||
function(callback)
|
||||
{
|
||||
//get all needed revision Dates
|
||||
async.forEach(revTimesNeeded, function(revNum, callback)
|
||||
{
|
||||
pad.getRevisionDate(revNum, function(err, revDate)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
revisionDate[revNum] = Math.floor(revDate/1000);
|
||||
callback();
|
||||
});
|
||||
}, callback);
|
||||
},
|
||||
//get the lines
|
||||
function(callback)
|
||||
{
|
||||
getPadLines(padId, startNum-1, function(err, _lines)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
lines = _lines;
|
||||
callback();
|
||||
});
|
||||
}
|
||||
], callback);
|
||||
},
|
||||
//doesn't know what happens here excatly :/
|
||||
function(callback)
|
||||
{
|
||||
var compositeStart = startNum;
|
||||
|
||||
while (compositeStart < endNum)
|
||||
{
|
||||
if (compositeStart + granularity > endNum)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
var compositeEnd = compositeStart + granularity;
|
||||
|
||||
var forwards = composedChangesets[compositeStart + "/" + compositeEnd];
|
||||
var backwards = Changeset.inverse(forwards, lines.textlines, lines.alines, pad.apool());
|
||||
|
||||
Changeset.mutateAttributionLines(forwards, lines.alines, pad.apool());
|
||||
Changeset.mutateTextLines(forwards, lines.textlines);
|
||||
|
||||
var forwards2 = Changeset.moveOpsToNewPool(forwards, pad.apool(), apool);
|
||||
var backwards2 = Changeset.moveOpsToNewPool(backwards, pad.apool(), apool);
|
||||
|
||||
var t1, t2;
|
||||
if (compositeStart == 0)
|
||||
{
|
||||
t1 = revisionDate[0];
|
||||
}
|
||||
else
|
||||
{
|
||||
t1 = revisionDate[compositeStart - 1];
|
||||
}
|
||||
|
||||
t2 = revisionDate[compositeEnd - 1];
|
||||
|
||||
timeDeltas.push(t2 - t1);
|
||||
forwardsChangesets.push(forwards2);
|
||||
backwardsChangesets.push(backwards2);
|
||||
|
||||
compositeStart += granularity;
|
||||
}
|
||||
|
||||
callback();
|
||||
}
|
||||
], function(err)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
callback(null, {forwardsChangesets: forwardsChangesets,
|
||||
backwardsChangesets: backwardsChangesets,
|
||||
apool: apool.toJsonable(),
|
||||
actualEndNum: endNum,
|
||||
timeDeltas: timeDeltas,
|
||||
start: startNum,
|
||||
granularity: granularity });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to rebuild the getPadLines function of the original Etherpad
|
||||
* https://github.com/ether/pad/blob/master/etherpad/src/etherpad/control/pad/pad_changeset_control.js#L263
|
||||
*/
|
||||
function getPadLines(padId, revNum, callback)
|
||||
{
|
||||
var atext;
|
||||
var result = {};
|
||||
var pad;
|
||||
|
||||
async.series([
|
||||
//get the pad from the database
|
||||
function(callback)
|
||||
{
|
||||
padManager.getPad(padId, function(err, _pad)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
pad = _pad;
|
||||
callback();
|
||||
});
|
||||
},
|
||||
//get the atext
|
||||
function(callback)
|
||||
{
|
||||
if(revNum >= 0)
|
||||
{
|
||||
pad.getInternalRevisionAText(revNum, function(err, _atext)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
atext = _atext;
|
||||
callback();
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
atext = Changeset.makeAText("\n");
|
||||
callback(null);
|
||||
}
|
||||
},
|
||||
function(callback)
|
||||
{
|
||||
result.textlines = Changeset.splitTextLines(atext.text);
|
||||
result.alines = Changeset.splitAttributionLines(atext.attribs, atext.text);
|
||||
callback(null);
|
||||
}
|
||||
], function(err)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
callback(null, result);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to rebuild the composePadChangeset function of the original Etherpad
|
||||
* https://github.com/ether/pad/blob/master/etherpad/src/etherpad/control/pad/pad_changeset_control.js#L241
|
||||
*/
|
||||
function composePadChangesets(padId, startNum, endNum, callback)
|
||||
{
|
||||
var pad;
|
||||
var changesets = [];
|
||||
var changeset;
|
||||
|
||||
async.series([
|
||||
//get the pad from the database
|
||||
function(callback)
|
||||
{
|
||||
padManager.getPad(padId, function(err, _pad)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
pad = _pad;
|
||||
callback();
|
||||
});
|
||||
},
|
||||
//fetch all changesets we need
|
||||
function(callback)
|
||||
{
|
||||
var changesetsNeeded=[];
|
||||
|
||||
//create a array for all changesets, we will
|
||||
//replace the values with the changeset later
|
||||
for(var r=startNum;r<endNum;r++)
|
||||
{
|
||||
changesetsNeeded.push(r);
|
||||
}
|
||||
|
||||
//get all changesets
|
||||
async.forEach(changesetsNeeded, function(revNum,callback)
|
||||
{
|
||||
pad.getRevisionChangeset(revNum, function(err, value)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
changesets[revNum] = value;
|
||||
callback();
|
||||
});
|
||||
},callback);
|
||||
},
|
||||
//compose Changesets
|
||||
function(callback)
|
||||
{
|
||||
changeset = changesets[startNum];
|
||||
var pool = pad.apool();
|
||||
|
||||
for(var r=startNum+1;r<endNum;r++)
|
||||
{
|
||||
var cs = changesets[r];
|
||||
changeset = Changeset.compose(changeset, cs, pool);
|
||||
}
|
||||
|
||||
callback(null);
|
||||
}
|
||||
],
|
||||
//return err and changeset
|
||||
function(err)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
callback(null, changeset);
|
||||
});
|
||||
}
|
58
src/node/hooks/express/apicalls.js
Normal file
|
@ -0,0 +1,58 @@
|
|||
var log4js = require('log4js');
|
||||
var apiLogger = log4js.getLogger("API");
|
||||
var formidable = require('formidable');
|
||||
var apiHandler = require('../../handler/APIHandler');
|
||||
|
||||
//This is for making an api call, collecting all post information and passing it to the apiHandler
|
||||
exports.apiCaller = function(req, res, fields) {
|
||||
res.header("Content-Type", "application/json; charset=utf-8");
|
||||
|
||||
apiLogger.info("REQUEST, " + req.params.func + ", " + JSON.stringify(fields));
|
||||
|
||||
//wrap the send function so we can log the response
|
||||
res._send = res.send;
|
||||
res.send = function (response) {
|
||||
response = JSON.stringify(response);
|
||||
apiLogger.info("RESPONSE, " + req.params.func + ", " + response);
|
||||
|
||||
//is this a jsonp call, if yes, add the function call
|
||||
if(req.query.jsonp)
|
||||
response = req.query.jsonp + "(" + response + ")";
|
||||
|
||||
res._send(response);
|
||||
}
|
||||
|
||||
//call the api handler
|
||||
apiHandler.handle(req.params.func, fields, req, res);
|
||||
}
|
||||
|
||||
|
||||
exports.expressCreateServer = function (hook_name, args, cb) {
|
||||
//This is a api GET call, collect all post informations and pass it to the apiHandler
|
||||
args.app.get('/api/1/:func', function (req, res) {
|
||||
apiCaller(req, res, req.query)
|
||||
});
|
||||
|
||||
//This is a api POST call, collect all post informations and pass it to the apiHandler
|
||||
args.app.post('/api/1/:func', function(req, res) {
|
||||
new formidable.IncomingForm().parse(req, function (err, fields, files) {
|
||||
apiCaller(req, res, fields)
|
||||
});
|
||||
});
|
||||
|
||||
//The Etherpad client side sends information about how a disconnect happen
|
||||
args.app.post('/ep/pad/connection-diagnostic-info', function(req, res) {
|
||||
new formidable.IncomingForm().parse(req, function(err, fields, files) {
|
||||
console.log("DIAGNOSTIC-INFO: " + fields.diagnosticInfo);
|
||||
res.end("OK");
|
||||
});
|
||||
});
|
||||
|
||||
//The Etherpad client side sends information about client side javscript errors
|
||||
args.app.post('/jserror', function(req, res) {
|
||||
new formidable.IncomingForm().parse(req, function(err, fields, files) {
|
||||
console.error("CLIENT SIDE JAVASCRIPT ERROR: " + fields.errorInfo);
|
||||
res.end("OK");
|
||||
});
|
||||
});
|
||||
}
|
52
src/node/hooks/express/errorhandling.js
Normal file
|
@ -0,0 +1,52 @@
|
|||
var os = require("os");
|
||||
var db = require('../../db/DB');
|
||||
|
||||
|
||||
exports.onShutdown = false;
|
||||
exports.gracefulShutdown = function(err) {
|
||||
if(err && err.stack) {
|
||||
console.error(err.stack);
|
||||
} else if(err) {
|
||||
console.error(err);
|
||||
}
|
||||
|
||||
//ensure there is only one graceful shutdown running
|
||||
if(exports.onShutdown) return;
|
||||
exports.onShutdown = true;
|
||||
|
||||
console.log("graceful shutdown...");
|
||||
|
||||
//stop the http server
|
||||
exports.app.close();
|
||||
|
||||
//do the db shutdown
|
||||
db.db.doShutdown(function() {
|
||||
console.log("db sucessfully closed.");
|
||||
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
setTimeout(function(){
|
||||
process.exit(1);
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
|
||||
exports.expressCreateServer = function (hook_name, args, cb) {
|
||||
exports.app = args.app;
|
||||
|
||||
args.app.error(function(err, req, res, next){
|
||||
res.send(500);
|
||||
console.error(err.stack ? err.stack : err.toString());
|
||||
exports.gracefulShutdown();
|
||||
});
|
||||
|
||||
//connect graceful shutdown with sigint and uncaughtexception
|
||||
if(os.type().indexOf("Windows") == -1) {
|
||||
//sigint is so far not working on windows
|
||||
//https://github.com/joyent/node/issues/1553
|
||||
process.on('SIGINT', exports.gracefulShutdown);
|
||||
}
|
||||
|
||||
process.on('uncaughtException', exports.gracefulShutdown);
|
||||
}
|
41
src/node/hooks/express/importexport.js
Normal file
|
@ -0,0 +1,41 @@
|
|||
var hasPadAccess = require("../../padaccess");
|
||||
var settings = require('../../utils/Settings');
|
||||
var exportHandler = require('../../handler/ExportHandler');
|
||||
var importHandler = require('../../handler/ImportHandler');
|
||||
|
||||
exports.expressCreateServer = function (hook_name, args, cb) {
|
||||
args.app.get('/p/:pad/:rev?/export/:type', function(req, res, next) {
|
||||
var types = ["pdf", "doc", "txt", "html", "odt", "dokuwiki"];
|
||||
//send a 404 if we don't support this filetype
|
||||
if (types.indexOf(req.params.type) == -1) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
//if abiword is disabled, and this is a format we only support with abiword, output a message
|
||||
if (settings.abiword == null &&
|
||||
["odt", "pdf", "doc"].indexOf(req.params.type) !== -1) {
|
||||
res.send("Abiword is not enabled at this Etherpad Lite instance. Set the path to Abiword in settings.json to enable this feature");
|
||||
return;
|
||||
}
|
||||
|
||||
res.header("Access-Control-Allow-Origin", "*");
|
||||
|
||||
hasPadAccess(req, res, function() {
|
||||
exportHandler.doExport(req, res, req.params.pad, req.params.type);
|
||||
});
|
||||
});
|
||||
|
||||
//handle import requests
|
||||
args.app.post('/p/:pad/import', function(req, res, next) {
|
||||
//if abiword is disabled, skip handling this request
|
||||
if(settings.abiword == null) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
hasPadAccess(req, res, function() {
|
||||
importHandler.doImport(req, res, req.params.pad);
|
||||
});
|
||||
});
|
||||
}
|
6
src/node/hooks/express/minified.js
Normal file
|
@ -0,0 +1,6 @@
|
|||
var minify = require('../../utils/Minify');
|
||||
|
||||
exports.expressCreateServer = function (hook_name, args, cb) {
|
||||
//serve minified files
|
||||
args.app.get('/minified/:filename', minify.minifyJS);
|
||||
}
|
65
src/node/hooks/express/padreadonly.js
Normal file
|
@ -0,0 +1,65 @@
|
|||
var async = require('async');
|
||||
var ERR = require("async-stacktrace");
|
||||
var readOnlyManager = require("../../db/ReadOnlyManager");
|
||||
var hasPadAccess = require("../../padaccess");
|
||||
var exporthtml = require("../../utils/ExportHtml");
|
||||
|
||||
exports.expressCreateServer = function (hook_name, args, cb) {
|
||||
//serve read only pad
|
||||
args.app.get('/ro/:id', function(req, res)
|
||||
{
|
||||
var html;
|
||||
var padId;
|
||||
var pad;
|
||||
|
||||
async.series([
|
||||
//translate the read only pad to a padId
|
||||
function(callback)
|
||||
{
|
||||
readOnlyManager.getPadId(req.params.id, function(err, _padId)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
padId = _padId;
|
||||
|
||||
//we need that to tell hasPadAcess about the pad
|
||||
req.params.pad = padId;
|
||||
|
||||
callback();
|
||||
});
|
||||
},
|
||||
//render the html document
|
||||
function(callback)
|
||||
{
|
||||
//return if the there is no padId
|
||||
if(padId == null)
|
||||
{
|
||||
callback("notfound");
|
||||
return;
|
||||
}
|
||||
|
||||
hasPadAccess(req, res, function()
|
||||
{
|
||||
//render the html document
|
||||
exporthtml.getPadHTMLDocument(padId, null, false, function(err, _html)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
html = _html;
|
||||
callback();
|
||||
});
|
||||
});
|
||||
}
|
||||
], function(err)
|
||||
{
|
||||
//throw any unexpected error
|
||||
if(err && err != "notfound")
|
||||
ERR(err);
|
||||
|
||||
if(err == "notfound")
|
||||
res.send('404 - Not Found', 404);
|
||||
else
|
||||
res.send(html);
|
||||
});
|
||||
});
|
||||
|
||||
}
|
29
src/node/hooks/express/padurlsanitize.js
Normal file
|
@ -0,0 +1,29 @@
|
|||
var padManager = require('../../db/PadManager');
|
||||
|
||||
exports.expressCreateServer = function (hook_name, args, cb) {
|
||||
//redirects browser to the pad's sanitized url if needed. otherwise, renders the html
|
||||
args.app.param('pad', function (req, res, next, padId) {
|
||||
//ensure the padname is valid and the url doesn't end with a /
|
||||
if(!padManager.isValidPadId(padId) || /\/$/.test(req.url))
|
||||
{
|
||||
res.send('Such a padname is forbidden', 404);
|
||||
}
|
||||
else
|
||||
{
|
||||
padManager.sanitizePadId(padId, function(sanitizedPadId) {
|
||||
//the pad id was sanitized, so we redirect to the sanitized version
|
||||
if(sanitizedPadId != padId)
|
||||
{
|
||||
var real_path = req.path.replace(/^\/p\/[^\/]+/, '/p/' + sanitizedPadId);
|
||||
res.header('Location', real_path);
|
||||
res.send('You should be redirected to <a href="' + real_path + '">' + real_path + '</a>', 302);
|
||||
}
|
||||
//the pad id was fine, so just render it
|
||||
else
|
||||
{
|
||||
next();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
49
src/node/hooks/express/socketio.js
Normal file
|
@ -0,0 +1,49 @@
|
|||
var log4js = require('log4js');
|
||||
var socketio = require('socket.io');
|
||||
var settings = require('../../utils/Settings');
|
||||
var socketIORouter = require("../../handler/SocketIORouter");
|
||||
var hooks = require("../../pluginfw/hooks");
|
||||
|
||||
var padMessageHandler = require("../../handler/PadMessageHandler");
|
||||
var timesliderMessageHandler = require("../../handler/TimesliderMessageHandler");
|
||||
|
||||
|
||||
exports.expressCreateServer = function (hook_name, args, cb) {
|
||||
//init socket.io and redirect all requests to the MessageHandler
|
||||
var io = socketio.listen(args.app);
|
||||
|
||||
//this is only a workaround to ensure it works with all browers behind a proxy
|
||||
//we should remove this when the new socket.io version is more stable
|
||||
io.set('transports', ['xhr-polling']);
|
||||
|
||||
var socketIOLogger = log4js.getLogger("socket.io");
|
||||
io.set('logger', {
|
||||
debug: function (str)
|
||||
{
|
||||
socketIOLogger.debug.apply(socketIOLogger, arguments);
|
||||
},
|
||||
info: function (str)
|
||||
{
|
||||
socketIOLogger.info.apply(socketIOLogger, arguments);
|
||||
},
|
||||
warn: function (str)
|
||||
{
|
||||
socketIOLogger.warn.apply(socketIOLogger, arguments);
|
||||
},
|
||||
error: function (str)
|
||||
{
|
||||
socketIOLogger.error.apply(socketIOLogger, arguments);
|
||||
},
|
||||
});
|
||||
|
||||
//minify socket.io javascript
|
||||
if(settings.minify)
|
||||
io.enable('browser client minification');
|
||||
|
||||
//Initalize the Socket.IO Router
|
||||
socketIORouter.setSocketIO(io);
|
||||
socketIORouter.addComponent("pad", padMessageHandler);
|
||||
socketIORouter.addComponent("timeslider", timesliderMessageHandler);
|
||||
|
||||
hooks.callAll("socketio", {"app": args.app, "io": io});
|
||||
}
|
48
src/node/hooks/express/specialpages.js
Normal file
|
@ -0,0 +1,48 @@
|
|||
var path = require('path');
|
||||
|
||||
exports.expressCreateServer = function (hook_name, args, cb) {
|
||||
|
||||
//serve index.html under /
|
||||
args.app.get('/', function(req, res)
|
||||
{
|
||||
var filePath = path.normalize(__dirname + "/../../../static/index.html");
|
||||
res.sendfile(filePath, { maxAge: exports.maxAge });
|
||||
});
|
||||
|
||||
//serve robots.txt
|
||||
args.app.get('/robots.txt', function(req, res)
|
||||
{
|
||||
var filePath = path.normalize(__dirname + "/../../../static/robots.txt");
|
||||
res.sendfile(filePath, { maxAge: exports.maxAge });
|
||||
});
|
||||
|
||||
//serve favicon.ico
|
||||
args.app.get('/favicon.ico', function(req, res)
|
||||
{
|
||||
var filePath = path.normalize(__dirname + "/../../../static/custom/favicon.ico");
|
||||
res.sendfile(filePath, { maxAge: exports.maxAge }, function(err)
|
||||
{
|
||||
//there is no custom favicon, send the default favicon
|
||||
if(err)
|
||||
{
|
||||
filePath = path.normalize(__dirname + "/../../../static/favicon.ico");
|
||||
res.sendfile(filePath, { maxAge: exports.maxAge });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
//serve pad.html under /p
|
||||
args.app.get('/p/:pad', function(req, res, next)
|
||||
{
|
||||
var filePath = path.normalize(__dirname + "/../../../static/pad.html");
|
||||
res.sendfile(filePath, { maxAge: exports.maxAge });
|
||||
});
|
||||
|
||||
//serve timeslider.html under /p/$padname/timeslider
|
||||
args.app.get('/p/:pad/timeslider', function(req, res, next)
|
||||
{
|
||||
var filePath = path.normalize(__dirname + "/../../../static/timeslider.html");
|
||||
res.sendfile(filePath, { maxAge: exports.maxAge });
|
||||
});
|
||||
|
||||
}
|
32
src/node/hooks/express/static.js
Normal file
|
@ -0,0 +1,32 @@
|
|||
var path = require('path');
|
||||
var minify = require('../../utils/Minify');
|
||||
var plugins = require("../../pluginfw/plugins");
|
||||
|
||||
exports.expressCreateServer = function (hook_name, args, cb) {
|
||||
//serve static files
|
||||
args.app.get('/static/js/require-kernel.js', function (req, res, next) {
|
||||
res.header("Content-Type","application/javascript; charset: utf-8");
|
||||
res.write(minify.requireDefinition());
|
||||
res.end();
|
||||
});
|
||||
|
||||
/* Handle paths like "/static/js/plugins/pluginomatic_myplugin/test.js"
|
||||
by rewriting it to ROOT_PATH_OF_MYPLUGIN/static/js/test.js,
|
||||
commonly ETHERPAD_ROOT/node_modules/pluginomatic_myplugin/static/js/test.js
|
||||
*/
|
||||
args.app.get(/^\/static\/([^\/]+)\/plugins\/([^\/]+)\/(.*)/, function(req, res) {
|
||||
var type_dir = req.params[0].replace(/\.\./g, '').split("?")[0];
|
||||
var plugin_name = req.params[1];
|
||||
var url = req.params[2].replace(/\.\./g, '').split("?")[0];
|
||||
|
||||
var filePath = path.normalize(path.join(plugins.plugins[plugin_name].package.path, "static", type_dir, url));
|
||||
res.sendfile(filePath, { maxAge: exports.maxAge });
|
||||
});
|
||||
|
||||
// Handle normal static files
|
||||
args.app.get('/static/*', function(req, res) {
|
||||
var filePath = path.normalize(__dirname + "/../../.." +
|
||||
req.url.replace(/\.\./g, '').split("?")[0]);
|
||||
res.sendfile(filePath, { maxAge: exports.maxAge });
|
||||
});
|
||||
}
|
36
src/node/hooks/express/webaccess.js
Normal file
|
@ -0,0 +1,36 @@
|
|||
var express = require('express');
|
||||
var log4js = require('log4js');
|
||||
var httpLogger = log4js.getLogger("http");
|
||||
var settings = require('../../utils/Settings');
|
||||
|
||||
|
||||
//checks for basic http auth
|
||||
exports.basicAuth = function (req, res, next) {
|
||||
if (req.headers.authorization && req.headers.authorization.search('Basic ') === 0) {
|
||||
// fetch login and password
|
||||
if (new Buffer(req.headers.authorization.split(' ')[1], 'base64').toString() == settings.httpAuth) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
res.header('WWW-Authenticate', 'Basic realm="Protected Area"');
|
||||
if (req.headers.authorization) {
|
||||
setTimeout(function () {
|
||||
res.send('Authentication required', 401);
|
||||
}, 1000);
|
||||
} else {
|
||||
res.send('Authentication required', 401);
|
||||
}
|
||||
}
|
||||
|
||||
exports.expressConfigure = function (hook_name, args, cb) {
|
||||
// Activate http basic auth if it has been defined in settings.json
|
||||
if(settings.httpAuth != null) args.app.use(exports.basicAuth);
|
||||
|
||||
// If the log level specified in the config file is WARN or ERROR the application server never starts listening to requests as reported in issue #158.
|
||||
// Not installing the log4js connect logger when the log level has a higher severity than INFO since it would not log at that level anyway.
|
||||
if (!(settings.loglevel === "WARN" || settings.loglevel == "ERROR"))
|
||||
args.app.use(log4js.connectLogger(httpLogger, { level: log4js.levels.INFO, format: ':status, :method :url'}));
|
||||
args.app.use(express.cookieParser());
|
||||
}
|
21
src/node/padaccess.js
Normal file
|
@ -0,0 +1,21 @@
|
|||
var ERR = require("async-stacktrace");
|
||||
var securityManager = require('./db/SecurityManager');
|
||||
|
||||
//checks for padAccess
|
||||
module.exports = function (req, res, callback) {
|
||||
|
||||
// FIXME: Why is this ever undefined??
|
||||
if (req.cookies === undefined) req.cookies = {};
|
||||
|
||||
securityManager.checkAccess(req.params.pad, req.cookies.sessionid, req.cookies.token, req.cookies.password, function(err, accessObj) {
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//there is access, continue
|
||||
if(accessObj.accessStatus == "grant") {
|
||||
callback();
|
||||
//no access
|
||||
} else {
|
||||
res.send("403 - Can't touch this", 403);
|
||||
}
|
||||
});
|
||||
}
|
58
src/node/pluginfw/hooks.js
Normal file
|
@ -0,0 +1,58 @@
|
|||
var plugins = require("./plugins");
|
||||
var async = require("async");
|
||||
|
||||
|
||||
var hookCallWrapper = function (hook, hook_name, args, cb) {
|
||||
if (cb === undefined) cb = function (x) { return x; };
|
||||
try {
|
||||
return hook.hook_fn(hook_name, args, cb);
|
||||
} catch (ex) {
|
||||
console.error([hook_name, hook.part.full_name, ex]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Don't use Array.concat as it flatterns arrays within the array */
|
||||
exports.flatten = function (lst) {
|
||||
var res = [];
|
||||
if (lst != undefined && lst != null) {
|
||||
for (var i = 0; i < lst.length; i++) {
|
||||
if (lst[i] != undefined && lst[i] != null) {
|
||||
for (var j = 0; j < lst[i].length; j++) {
|
||||
res.push(lst[i][j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
exports.callAll = function (hook_name, args) {
|
||||
if (plugins.hooks[hook_name] === undefined) return [];
|
||||
return exports.flatten(plugins.hooks[hook_name].map(function (hook) {
|
||||
return hookCallWrapper(hook, hook_name, args);
|
||||
}));
|
||||
}
|
||||
|
||||
exports.aCallAll = function (hook_name, args, cb) {
|
||||
if (plugins.hooks[hook_name] === undefined) cb([]);
|
||||
async.map(
|
||||
plugins.hooks[hook_name],
|
||||
function (hook, cb) {
|
||||
hookCallWrapper(hook, hook_name, args, function (res) { cb(null, res); });
|
||||
},
|
||||
function (err, res) {
|
||||
cb(exports.flatten(res));
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
exports.callFirst = function (hook_name, args) {
|
||||
if (plugins.hooks[hook_name][0] === undefined) return [];
|
||||
return exports.flatten(hookCallWrapper(plugins.hooks[hook_name][0], hook_name, args));
|
||||
}
|
||||
|
||||
exports.aCallFirst = function (hook_name, args, cb) {
|
||||
if (plugins.hooks[hook_name][0] === undefined) cb([]);
|
||||
hookCallWrapper(plugins.hooks[hook_name][0], hook_name, args, function (res) { cb(exports.flatten(res)); });
|
||||
}
|
159
src/node/pluginfw/plugins.js
Normal file
|
@ -0,0 +1,159 @@
|
|||
var npm = require("npm/lib/npm.js");
|
||||
var readInstalled = require("npm/lib/utils/read-installed.js");
|
||||
var relativize = require("npm/lib/utils/relativize.js");
|
||||
var readJson = require("npm/lib/utils/read-json.js");
|
||||
var path = require("path");
|
||||
var async = require("async");
|
||||
var fs = require("fs");
|
||||
var tsort = require("./tsort");
|
||||
var util = require("util");
|
||||
|
||||
exports.prefix = 'pluginomatic_';
|
||||
exports.loaded = false;
|
||||
exports.plugins = {};
|
||||
exports.parts = [];
|
||||
exports.hooks = {};
|
||||
|
||||
exports.ensure = function (cb) {
|
||||
if (!exports.loaded)
|
||||
exports.update(cb);
|
||||
else
|
||||
cb();
|
||||
}
|
||||
|
||||
exports.formatPlugins = function () {
|
||||
return Object.keys(exports.plugins).join(", ");
|
||||
}
|
||||
|
||||
exports.formatParts = function () {
|
||||
return exports.parts.map(function (part) { return part.full_name; }).join("\n");
|
||||
}
|
||||
|
||||
exports.formatHooks = function () {
|
||||
var res = [];
|
||||
Object.keys(exports.hooks).forEach(function (hook_name) {
|
||||
exports.hooks[hook_name].forEach(function (hook) {
|
||||
res.push(hook.hook_name + ": " + hook.hook_fn_name + " from " + hook.part.full_name);
|
||||
});
|
||||
});
|
||||
return res.join("\n");
|
||||
}
|
||||
|
||||
exports.update = function (cb) {
|
||||
exports.getPackages(function (er, packages) {
|
||||
var parts = [];
|
||||
var plugins = {};
|
||||
// Load plugin metadata pluginomatic.json
|
||||
async.forEach(
|
||||
Object.keys(packages),
|
||||
function (plugin_name, cb) {
|
||||
exports.loadPlugin(packages, plugin_name, plugins, parts, cb);
|
||||
},
|
||||
function (err) {
|
||||
exports.plugins = plugins;
|
||||
exports.parts = exports.sortParts(parts);
|
||||
exports.hooks = exports.extractHooks(exports.parts);
|
||||
exports.loaded = true;
|
||||
cb(err);
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
exports.getPackages = function (cb) {
|
||||
// Load list of installed NPM packages, flatten it to a list, and filter out only packages with names that
|
||||
var dir = path.resolve(npm.dir, '..');
|
||||
readInstalled(dir, function (er, data) {
|
||||
if (er) cb(er, null);
|
||||
var packages = {};
|
||||
function flatten(deps) {
|
||||
Object.keys(deps).forEach(function (name) {
|
||||
if (name.indexOf(exports.prefix) == 0) {
|
||||
packages[name] = deps[name];
|
||||
}
|
||||
if (deps[name].dependencies !== undefined)
|
||||
flatten(deps[name].dependencies);
|
||||
});
|
||||
}
|
||||
flatten([data]);
|
||||
cb(null, packages);
|
||||
});
|
||||
}
|
||||
|
||||
exports.extractHooks = function (parts) {
|
||||
var hooks = {};
|
||||
parts.forEach(function (part) {
|
||||
Object.keys(part.hooks || {}).forEach(function (hook_name) {
|
||||
if (hooks[hook_name] === undefined) hooks[hook_name] = [];
|
||||
var hook_fn_name = part.hooks[hook_name];
|
||||
var hook_fn = exports.loadFn(part.hooks[hook_name]);
|
||||
if (hook_fn) {
|
||||
hooks[hook_name].push({"hook_name": hook_name, "hook_fn": hook_fn, "hook_fn_name": hook_fn_name, "part": part});
|
||||
} else {
|
||||
console.error("Unable to load hook function for " + part.full_name + " for hook " + hook_name + ": " + part.hooks[hook_name]);
|
||||
}
|
||||
});
|
||||
});
|
||||
return hooks;
|
||||
}
|
||||
|
||||
exports.loadPlugin = function (packages, plugin_name, plugins, parts, cb) {
|
||||
var plugin_path = path.resolve(packages[plugin_name].path, "pluginomatic.json");
|
||||
fs.readFile(
|
||||
plugin_path,
|
||||
function (er, data) {
|
||||
if (er) {
|
||||
console.error("Unable to load plugin definition file " + plugin_path);
|
||||
return cb();
|
||||
}
|
||||
try {
|
||||
var plugin = JSON.parse(data);
|
||||
plugin.package = packages[plugin_name];
|
||||
plugins[plugin_name] = plugin;
|
||||
plugin.parts.forEach(function (part) {
|
||||
part.plugin = plugin_name;
|
||||
part.full_name = plugin_name + "/" + part.name;
|
||||
parts[part.full_name] = part;
|
||||
});
|
||||
} catch (ex) {
|
||||
console.error("Unable to parse plugin definition file " + plugin_path + ": " + ex.toString());
|
||||
}
|
||||
cb();
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
exports.partsToParentChildList = function (parts) {
|
||||
var res = [];
|
||||
Object.keys(parts).forEach(function (name) {
|
||||
(parts[name].post || []).forEach(function (child_name) {
|
||||
res.push([name, child_name]);
|
||||
});
|
||||
(parts[name].pre || []).forEach(function (parent_name) {
|
||||
res.push([parent_name, name]);
|
||||
});
|
||||
if (!parts[name].pre && !parts[name].post) {
|
||||
res.push([name, ":" + name]); // Include apps with no dependency info
|
||||
}
|
||||
});
|
||||
return res;
|
||||
}
|
||||
|
||||
exports.sortParts = function(parts) {
|
||||
return tsort(
|
||||
exports.partsToParentChildList(parts)
|
||||
).filter(
|
||||
function (name) { return parts[name] !== undefined; }
|
||||
).map(
|
||||
function (name) { return parts[name]; }
|
||||
);
|
||||
};
|
||||
|
||||
exports.loadFn = function (path) {
|
||||
var x = path.split(":");
|
||||
var fn = require(x[0]);
|
||||
x[1].split(".").forEach(function (name) {
|
||||
fn = fn[name];
|
||||
});
|
||||
return fn;
|
||||
}
|
42
src/node/pluginfw/require.js
Normal file
|
@ -0,0 +1,42 @@
|
|||
var plugins = require('./plugins');
|
||||
var path = require('path');
|
||||
|
||||
var SERVER_JS_SRC = path.normalize(path.join(__dirname, '../../'));
|
||||
var CLIENT_JS_SRC = path.normalize(path.join(__dirname, '../../static/js'));
|
||||
|
||||
global.ep_require = function (url) {
|
||||
if (url.indexOf("/plugins/") == 0) {
|
||||
/* Handle paths like "/plugins/pluginomatic_myplugin/test.js"
|
||||
by rewriting it to ROOT_PATH_OF_MYPLUGIN/test.js,
|
||||
commonly ETHERPAD_ROOT/node_modules/pluginomatic_myplugin/test.js
|
||||
*/
|
||||
url = url.split("/");
|
||||
url.splice(0, 1);
|
||||
var plugin_name = url.splice(0, 1)[0];
|
||||
url = url.join("/");
|
||||
url = path.normalize(path.join(plugins.plugins[plugin_name].package.path, url));
|
||||
} else if (url.indexOf("/") == 0) {
|
||||
/* Handle all non-plugin paths for files in / */
|
||||
url = path.normalize(path.join(SERVER_JS_SRC, url))
|
||||
}
|
||||
return require(url);
|
||||
}
|
||||
|
||||
global.ep_client_require = function (url) {
|
||||
if (url.indexOf("/plugins/") == 0) {
|
||||
/* Handle paths like "/plugins/pluginomatic_myplugin/test.js"
|
||||
by rewriting it to ROOT_PATH_OF_MYPLUGIN/static/js/test.js,
|
||||
commonly ETHERPAD_ROOT/node_modules/pluginomatic_myplugin/static/js/test.js
|
||||
For more information see hooks/express/static.js
|
||||
*/
|
||||
url = url.split("/");
|
||||
url.splice(0, 2);
|
||||
var plugin_name = url.splice(0, 1)[0];
|
||||
url = url.join("/");
|
||||
url = path.normalize(path.join(plugins.plugins[plugin_name].package.path, "static/js", url));
|
||||
} else if (url.indexOf("/") == 0) {
|
||||
/* Handle all non-plugin paths for files in /static */
|
||||
url = path.normalize(path.join(CLIENT_JS_SRC, url))
|
||||
}
|
||||
return require(url);
|
||||
}
|
112
src/node/pluginfw/tsort.js
Normal file
|
@ -0,0 +1,112 @@
|
|||
/**
|
||||
* general topological sort
|
||||
* from https://gist.github.com/1232505
|
||||
* @author SHIN Suzuki (shinout310@gmail.com)
|
||||
* @param Array<Array> edges : list of edges. each edge forms Array<ID,ID> e.g. [12 , 3]
|
||||
*
|
||||
* @returns Array : topological sorted list of IDs
|
||||
**/
|
||||
|
||||
function tsort(edges) {
|
||||
var nodes = {}, // hash: stringified id of the node => { id: id, afters: lisf of ids }
|
||||
sorted = [], // sorted list of IDs ( returned value )
|
||||
visited = {}; // hash: id of already visited node => true
|
||||
|
||||
var Node = function(id) {
|
||||
this.id = id;
|
||||
this.afters = [];
|
||||
}
|
||||
|
||||
// 1. build data structures
|
||||
edges.forEach(function(v) {
|
||||
var from = v[0], to = v[1];
|
||||
if (!nodes[from]) nodes[from] = new Node(from);
|
||||
if (!nodes[to]) nodes[to] = new Node(to);
|
||||
nodes[from].afters.push(to);
|
||||
});
|
||||
|
||||
// 2. topological sort
|
||||
Object.keys(nodes).forEach(function visit(idstr, ancestors) {
|
||||
var node = nodes[idstr],
|
||||
id = node.id;
|
||||
|
||||
// if already exists, do nothing
|
||||
if (visited[idstr]) return;
|
||||
|
||||
if (!Array.isArray(ancestors)) ancestors = [];
|
||||
|
||||
ancestors.push(id);
|
||||
|
||||
visited[idstr] = true;
|
||||
|
||||
node.afters.forEach(function(afterID) {
|
||||
if (ancestors.indexOf(afterID) >= 0) // if already in ancestors, a closed chain exists.
|
||||
throw new Error('closed chain : ' + afterID + ' is in ' + id);
|
||||
|
||||
visit(afterID.toString(), ancestors.map(function(v) { return v })); // recursive call
|
||||
});
|
||||
|
||||
sorted.unshift(id);
|
||||
});
|
||||
|
||||
return sorted;
|
||||
}
|
||||
|
||||
/**
|
||||
* TEST
|
||||
**/
|
||||
function tsortTest() {
|
||||
|
||||
// example 1: success
|
||||
var edges = [
|
||||
[1, 2],
|
||||
[1, 3],
|
||||
[2, 4],
|
||||
[3, 4]
|
||||
];
|
||||
|
||||
var sorted = tsort(edges);
|
||||
console.log(sorted);
|
||||
|
||||
// example 2: failure ( A > B > C > A )
|
||||
edges = [
|
||||
['A', 'B'],
|
||||
['B', 'C'],
|
||||
['C', 'A']
|
||||
];
|
||||
|
||||
try {
|
||||
sorted = tsort(edges);
|
||||
}
|
||||
catch (e) {
|
||||
console.log(e.message);
|
||||
}
|
||||
|
||||
// example 3: generate random edges
|
||||
var max = 100, iteration = 30;
|
||||
function randomInt(max) {
|
||||
return Math.floor(Math.random() * max) + 1;
|
||||
}
|
||||
|
||||
edges = (function() {
|
||||
var ret = [], i = 0;
|
||||
while (i++ < iteration) ret.push( [randomInt(max), randomInt(max)] );
|
||||
return ret;
|
||||
})();
|
||||
|
||||
try {
|
||||
sorted = tsort(edges);
|
||||
console.log("succeeded", sorted);
|
||||
}
|
||||
catch (e) {
|
||||
console.log("failed", e.message);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
// for node.js
|
||||
if (typeof exports == 'object' && exports === this) {
|
||||
module.exports = tsort;
|
||||
if (process.argv[1] === __filename) tsortTest();
|
||||
}
|
96
src/node/server.js
Normal file
|
@ -0,0 +1,96 @@
|
|||
/**
|
||||
* This module is started with bin/run.sh. It sets up a Express HTTP and a Socket.IO Server.
|
||||
* Static file Requests are answered directly from this module, Socket.IO messages are passed
|
||||
* to MessageHandler and minfied requests are passed to minified.
|
||||
*/
|
||||
|
||||
/*
|
||||
* 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
|
||||
*
|
||||
* 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 log4js = require('log4js');
|
||||
var fs = require('fs');
|
||||
var settings = require('./utils/Settings');
|
||||
var db = require('./db/DB');
|
||||
var async = require('async');
|
||||
var express = require('express');
|
||||
var path = require('path');
|
||||
require("./pluginfw/require"); // Load globals
|
||||
var plugins = require("./pluginfw/plugins");
|
||||
var hooks = require("./pluginfw/hooks");
|
||||
|
||||
//try to get the git version
|
||||
var version = "";
|
||||
try
|
||||
{
|
||||
var rootPath = path.normalize(__dirname + "/../")
|
||||
var ref = fs.readFileSync(rootPath + ".git/HEAD", "utf-8");
|
||||
var refPath = rootPath + ".git/" + ref.substring(5, ref.indexOf("\n"));
|
||||
version = fs.readFileSync(refPath, "utf-8");
|
||||
version = version.substring(0, 7);
|
||||
console.log("Your Etherpad Lite git version is " + version);
|
||||
}
|
||||
catch(e)
|
||||
{
|
||||
console.warn("Can't get git version for server header\n" + e.message)
|
||||
}
|
||||
|
||||
console.log("Report bugs at https://github.com/Pita/etherpad-lite/issues")
|
||||
|
||||
var serverName = "Etherpad-Lite " + version + " (http://j.mp/ep-lite)";
|
||||
|
||||
//cache 6 hours
|
||||
exports.maxAge = 1000*60*60*6;
|
||||
|
||||
//set loglevel
|
||||
log4js.setGlobalLogLevel(settings.loglevel);
|
||||
|
||||
async.waterfall([
|
||||
//initalize the database
|
||||
function (callback)
|
||||
{
|
||||
db.init(callback);
|
||||
},
|
||||
|
||||
plugins.update,
|
||||
|
||||
function (callback) {
|
||||
console.log("Installed plugins: " + plugins.formatPlugins());
|
||||
console.log("Installed parts:\n" + plugins.formatParts());
|
||||
console.log("Installed hooks:\n" + plugins.formatHooks());
|
||||
callback();
|
||||
},
|
||||
|
||||
//initalize the http server
|
||||
function (callback)
|
||||
{
|
||||
//create server
|
||||
var app = express.createServer();
|
||||
hooks.callAll("expressCreateServer", {"app": app});
|
||||
|
||||
app.use(function (req, res, next) {
|
||||
res.header("Server", serverName);
|
||||
next();
|
||||
});
|
||||
|
||||
app.configure(function() { hooks.callAll("expressConfigure", {"app": app}); });
|
||||
|
||||
//let the server listen
|
||||
app.listen(settings.port, settings.ip);
|
||||
console.log("Server is listening at " + settings.ip + ":" + settings.port);
|
||||
|
||||
callback(null);
|
||||
}
|
||||
]);
|
144
src/node/utils/Abiword.js
Normal file
|
@ -0,0 +1,144 @@
|
|||
/**
|
||||
* Controls the communication with the Abiword application
|
||||
*/
|
||||
|
||||
/*
|
||||
* 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
|
||||
*
|
||||
* 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 util = require('util');
|
||||
var spawn = require('child_process').spawn;
|
||||
var async = require("async");
|
||||
var settings = require("./Settings");
|
||||
var os = require('os');
|
||||
|
||||
var doConvertTask;
|
||||
|
||||
//on windows we have to spawn a process for each convertion, cause the plugin abicommand doesn't exist on this platform
|
||||
if(os.type().indexOf("Windows") > -1)
|
||||
{
|
||||
var stdoutBuffer = "";
|
||||
|
||||
doConvertTask = function(task, callback)
|
||||
{
|
||||
//span an abiword process to perform the conversion
|
||||
var abiword = spawn(settings.abiword, ["--to=" + task.destFile, task.srcFile]);
|
||||
|
||||
//delegate the processing of stdout to another function
|
||||
abiword.stdout.on('data', function (data)
|
||||
{
|
||||
//add data to buffer
|
||||
stdoutBuffer+=data.toString();
|
||||
});
|
||||
|
||||
//append error messages to the buffer
|
||||
abiword.stderr.on('data', function (data)
|
||||
{
|
||||
stdoutBuffer += data.toString();
|
||||
});
|
||||
|
||||
//throw exceptions if abiword is dieing
|
||||
abiword.on('exit', function (code)
|
||||
{
|
||||
if(code != 0) {
|
||||
throw "Abiword died with exit code " + code;
|
||||
}
|
||||
|
||||
if(stdoutBuffer != "")
|
||||
{
|
||||
console.log(stdoutBuffer);
|
||||
}
|
||||
|
||||
callback();
|
||||
});
|
||||
}
|
||||
|
||||
exports.convertFile = function(srcFile, destFile, type, callback)
|
||||
{
|
||||
doConvertTask({"srcFile": srcFile, "destFile": destFile, "type": type}, callback);
|
||||
};
|
||||
}
|
||||
//on unix operating systems, we can start abiword with abicommand and communicate with it via stdin/stdout
|
||||
//thats much faster, about factor 10
|
||||
else
|
||||
{
|
||||
//spawn the abiword process
|
||||
var abiword = spawn(settings.abiword, ["--plugin", "AbiCommand"]);
|
||||
|
||||
//append error messages to the buffer
|
||||
abiword.stderr.on('data', function (data)
|
||||
{
|
||||
stdoutBuffer += data.toString();
|
||||
});
|
||||
|
||||
//throw exceptions if abiword is dieing
|
||||
abiword.on('exit', function (code)
|
||||
{
|
||||
throw "Abiword died with exit code " + code;
|
||||
});
|
||||
|
||||
//delegate the processing of stdout to a other function
|
||||
abiword.stdout.on('data',onAbiwordStdout);
|
||||
|
||||
var stdoutCallback = null;
|
||||
var stdoutBuffer = "";
|
||||
var firstPrompt = true;
|
||||
|
||||
function onAbiwordStdout(data)
|
||||
{
|
||||
//add data to buffer
|
||||
stdoutBuffer+=data.toString();
|
||||
|
||||
//we're searching for the prompt, cause this means everything we need is in the buffer
|
||||
if(stdoutBuffer.search("AbiWord:>") != -1)
|
||||
{
|
||||
//filter the feedback message
|
||||
var err = stdoutBuffer.search("OK") != -1 ? null : stdoutBuffer;
|
||||
|
||||
//reset the buffer
|
||||
stdoutBuffer = "";
|
||||
|
||||
//call the callback with the error message
|
||||
//skip the first prompt
|
||||
if(stdoutCallback != null && !firstPrompt)
|
||||
{
|
||||
stdoutCallback(err);
|
||||
stdoutCallback = null;
|
||||
}
|
||||
|
||||
firstPrompt = false;
|
||||
}
|
||||
}
|
||||
|
||||
doConvertTask = function(task, callback)
|
||||
{
|
||||
abiword.stdin.write("convert " + task.srcFile + " " + task.destFile + " " + task.type + "\n");
|
||||
|
||||
//create a callback that calls the task callback and the caller callback
|
||||
stdoutCallback = function (err)
|
||||
{
|
||||
callback();
|
||||
task.callback(err);
|
||||
};
|
||||
}
|
||||
|
||||
//Queue with the converts we have to do
|
||||
var queue = async.queue(doConvertTask, 1);
|
||||
|
||||
exports.convertFile = function(srcFile, destFile, type, callback)
|
||||
{
|
||||
queue.push({"srcFile": srcFile, "destFile": destFile, "type": type, "callback": callback});
|
||||
};
|
||||
}
|
38
src/node/utils/Cli.js
Normal file
|
@ -0,0 +1,38 @@
|
|||
/**
|
||||
* The CLI module handles command line parameters
|
||||
*/
|
||||
|
||||
/*
|
||||
* 2012 Jordan Hollinger
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
// An object containing the parsed command-line options
|
||||
exports.argv = {};
|
||||
|
||||
var argv = process.argv.slice(2);
|
||||
var arg, prevArg;
|
||||
|
||||
// Loop through args
|
||||
for ( var i = 0; i < argv.length; i++ ) {
|
||||
arg = argv[i];
|
||||
|
||||
// Override location of settings.json file
|
||||
if ( prevArg == '--settings' || prevArg == '-s' ) {
|
||||
exports.argv.settings = arg;
|
||||
}
|
||||
|
||||
prevArg = arg;
|
||||
}
|
345
src/node/utils/ExportDokuWiki.js
Normal file
|
@ -0,0 +1,345 @@
|
|||
/**
|
||||
* Copyright 2011 Adrian Lang
|
||||
*
|
||||
* 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 async = require("async");
|
||||
var CommonCode = require('./common_code');
|
||||
var Changeset = CommonCode.require("/Changeset");
|
||||
var padManager = require("../db/PadManager");
|
||||
|
||||
function getPadDokuWiki(pad, revNum, callback)
|
||||
{
|
||||
var atext = pad.atext;
|
||||
var dokuwiki;
|
||||
async.waterfall([
|
||||
// fetch revision atext
|
||||
|
||||
|
||||
function (callback)
|
||||
{
|
||||
if (revNum != undefined)
|
||||
{
|
||||
pad.getInternalRevisionAText(revNum, function (err, revisionAtext)
|
||||
{
|
||||
atext = revisionAtext;
|
||||
callback(err);
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
callback(null);
|
||||
}
|
||||
},
|
||||
|
||||
// convert atext to dokuwiki text
|
||||
|
||||
function (callback)
|
||||
{
|
||||
dokuwiki = getDokuWikiFromAtext(pad, atext);
|
||||
callback(null);
|
||||
}],
|
||||
// run final callback
|
||||
|
||||
|
||||
function (err)
|
||||
{
|
||||
callback(err, dokuwiki);
|
||||
});
|
||||
}
|
||||
|
||||
function getDokuWikiFromAtext(pad, atext)
|
||||
{
|
||||
var apool = pad.apool();
|
||||
var textLines = atext.text.slice(0, -1).split('\n');
|
||||
var attribLines = Changeset.splitAttributionLines(atext.attribs, atext.text);
|
||||
|
||||
var tags = ['======', '=====', '**', '//', '__', 'del>'];
|
||||
var props = ['heading1', 'heading2', 'bold', 'italic', 'underline', 'strikethrough'];
|
||||
var anumMap = {};
|
||||
|
||||
props.forEach(function (propName, i)
|
||||
{
|
||||
var propTrueNum = apool.putAttrib([propName, true], true);
|
||||
if (propTrueNum >= 0)
|
||||
{
|
||||
anumMap[propTrueNum] = i;
|
||||
}
|
||||
});
|
||||
|
||||
function getLineDokuWiki(text, attribs)
|
||||
{
|
||||
var propVals = [false, false, false];
|
||||
var ENTER = 1;
|
||||
var STAY = 2;
|
||||
var LEAVE = 0;
|
||||
|
||||
// Use order of tags (b/i/u) as order of nesting, for simplicity
|
||||
// and decent nesting. For example,
|
||||
// <b>Just bold<b> <b><i>Bold and italics</i></b> <i>Just italics</i>
|
||||
// becomes
|
||||
// <b>Just bold <i>Bold and italics</i></b> <i>Just italics</i>
|
||||
var taker = Changeset.stringIterator(text);
|
||||
var assem = Changeset.stringAssembler();
|
||||
|
||||
function emitOpenTag(i)
|
||||
{
|
||||
if (tags[i].indexOf('>') !== -1) {
|
||||
assem.append('<');
|
||||
}
|
||||
assem.append(tags[i]);
|
||||
}
|
||||
|
||||
function emitCloseTag(i)
|
||||
{
|
||||
if (tags[i].indexOf('>') !== -1) {
|
||||
assem.append('</');
|
||||
}
|
||||
assem.append(tags[i]);
|
||||
}
|
||||
|
||||
var urls = _findURLs(text);
|
||||
|
||||
var idx = 0;
|
||||
|
||||
function processNextChars(numChars)
|
||||
{
|
||||
if (numChars <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var iter = Changeset.opIterator(Changeset.subattribution(attribs, idx, idx + numChars));
|
||||
idx += numChars;
|
||||
|
||||
while (iter.hasNext())
|
||||
{
|
||||
var o = iter.next();
|
||||
var propChanged = false;
|
||||
Changeset.eachAttribNumber(o.attribs, function (a)
|
||||
{
|
||||
if (a in anumMap)
|
||||
{
|
||||
var i = anumMap[a]; // i = 0 => bold, etc.
|
||||
if (!propVals[i])
|
||||
{
|
||||
propVals[i] = ENTER;
|
||||
propChanged = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
propVals[i] = STAY;
|
||||
}
|
||||
}
|
||||
});
|
||||
for (var i = 0; i < propVals.length; i++)
|
||||
{
|
||||
if (propVals[i] === true)
|
||||
{
|
||||
propVals[i] = LEAVE;
|
||||
propChanged = true;
|
||||
}
|
||||
else if (propVals[i] === STAY)
|
||||
{
|
||||
propVals[i] = true; // set it back
|
||||
}
|
||||
}
|
||||
// now each member of propVal is in {false,LEAVE,ENTER,true}
|
||||
// according to what happens at start of span
|
||||
if (propChanged)
|
||||
{
|
||||
// leaving bold (e.g.) also leaves italics, etc.
|
||||
var left = false;
|
||||
for (var i = 0; i < propVals.length; i++)
|
||||
{
|
||||
var v = propVals[i];
|
||||
if (!left)
|
||||
{
|
||||
if (v === LEAVE)
|
||||
{
|
||||
left = true;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (v === true)
|
||||
{
|
||||
propVals[i] = STAY; // tag will be closed and re-opened
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = propVals.length - 1; i >= 0; i--)
|
||||
{
|
||||
if (propVals[i] === LEAVE)
|
||||
{
|
||||
emitCloseTag(i);
|
||||
propVals[i] = false;
|
||||
}
|
||||
else if (propVals[i] === STAY)
|
||||
{
|
||||
emitCloseTag(i);
|
||||
}
|
||||
}
|
||||
for (var i = 0; i < propVals.length; i++)
|
||||
{
|
||||
if (propVals[i] === ENTER || propVals[i] === STAY)
|
||||
{
|
||||
emitOpenTag(i);
|
||||
propVals[i] = true;
|
||||
}
|
||||
}
|
||||
// propVals is now all {true,false} again
|
||||
} // end if (propChanged)
|
||||
var chars = o.chars;
|
||||
if (o.lines)
|
||||
{
|
||||
chars--; // exclude newline at end of line, if present
|
||||
}
|
||||
var s = taker.take(chars);
|
||||
|
||||
assem.append(_escapeDokuWiki(s));
|
||||
} // end iteration over spans in line
|
||||
for (var i = propVals.length - 1; i >= 0; i--)
|
||||
{
|
||||
if (propVals[i])
|
||||
{
|
||||
emitCloseTag(i);
|
||||
propVals[i] = false;
|
||||
}
|
||||
}
|
||||
} // end processNextChars
|
||||
if (urls)
|
||||
{
|
||||
urls.forEach(function (urlData)
|
||||
{
|
||||
var startIndex = urlData[0];
|
||||
var url = urlData[1];
|
||||
var urlLength = url.length;
|
||||
processNextChars(startIndex - idx);
|
||||
assem.append('[[');
|
||||
|
||||
// Do not use processNextChars since a link does not contain syntax and
|
||||
// needs no escaping
|
||||
var iter = Changeset.opIterator(Changeset.subattribution(attribs, idx, idx + urlLength));
|
||||
idx += urlLength;
|
||||
assem.append(taker.take(iter.next().chars));
|
||||
|
||||
assem.append(']]');
|
||||
});
|
||||
}
|
||||
processNextChars(text.length - idx);
|
||||
|
||||
return assem.toString() + "\n";
|
||||
} // end getLineDokuWiki
|
||||
var pieces = [];
|
||||
|
||||
for (var i = 0; i < textLines.length; i++)
|
||||
{
|
||||
var line = _analyzeLine(textLines[i], attribLines[i], apool);
|
||||
var lineContent = getLineDokuWiki(line.text, line.aline);
|
||||
|
||||
if (line.listLevel && lineContent)
|
||||
{
|
||||
pieces.push(new Array(line.listLevel + 1).join(' ') + '* ');
|
||||
}
|
||||
pieces.push(lineContent);
|
||||
}
|
||||
|
||||
return pieces.join('');
|
||||
}
|
||||
|
||||
function _analyzeLine(text, aline, apool)
|
||||
{
|
||||
var line = {};
|
||||
|
||||
// identify list
|
||||
var lineMarker = 0;
|
||||
line.listLevel = 0;
|
||||
if (aline)
|
||||
{
|
||||
var opIter = Changeset.opIterator(aline);
|
||||
if (opIter.hasNext())
|
||||
{
|
||||
var listType = Changeset.opAttributeValue(opIter.next(), 'list', apool);
|
||||
if (listType)
|
||||
{
|
||||
lineMarker = 1;
|
||||
listType = /([a-z]+)([12345678])/.exec(listType);
|
||||
if (listType)
|
||||
{
|
||||
line.listTypeName = listType[1];
|
||||
line.listLevel = Number(listType[2]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (lineMarker)
|
||||
{
|
||||
line.text = text.substring(1);
|
||||
line.aline = Changeset.subattribution(aline, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
line.text = text;
|
||||
line.aline = aline;
|
||||
}
|
||||
|
||||
return line;
|
||||
}
|
||||
|
||||
exports.getPadDokuWikiDocument = function (padId, revNum, callback)
|
||||
{
|
||||
padManager.getPad(padId, function (err, pad)
|
||||
{
|
||||
if (err)
|
||||
{
|
||||
callback(err);
|
||||
return;
|
||||
}
|
||||
|
||||
getPadDokuWiki(pad, revNum, callback);
|
||||
});
|
||||
}
|
||||
|
||||
function _escapeDokuWiki(s)
|
||||
{
|
||||
s = s.replace(/(\/\/|\*\*|__)/g, '%%$1%%');
|
||||
return s;
|
||||
}
|
||||
|
||||
// copied from ACE
|
||||
var _REGEX_WORDCHAR = /[\u0030-\u0039\u0041-\u005A\u0061-\u007A\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0100-\u1FFF\u3040-\u9FFF\uF900-\uFDFF\uFE70-\uFEFE\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFDC]/;
|
||||
var _REGEX_SPACE = /\s/;
|
||||
var _REGEX_URLCHAR = new RegExp('(' + /[-:@a-zA-Z0-9_.,~%+\/\\?=&#;()$]/.source + '|' + _REGEX_WORDCHAR.source + ')');
|
||||
var _REGEX_URL = new RegExp(/(?:(?:https?|s?ftp|ftps|file|smb|afp|nfs|(x-)?man|gopher|txmt):\/\/|mailto:)/.source + _REGEX_URLCHAR.source + '*(?![:.,;])' + _REGEX_URLCHAR.source, 'g');
|
||||
|
||||
// returns null if no URLs, or [[startIndex1, url1], [startIndex2, url2], ...]
|
||||
|
||||
|
||||
function _findURLs(text)
|
||||
{
|
||||
_REGEX_URL.lastIndex = 0;
|
||||
var urls = null;
|
||||
var execResult;
|
||||
while ((execResult = _REGEX_URL.exec(text)))
|
||||
{
|
||||
urls = (urls || []);
|
||||
var startIndex = execResult.index;
|
||||
var url = execResult[0];
|
||||
urls.push([startIndex, url]);
|
||||
}
|
||||
|
||||
return urls;
|
||||
}
|
595
src/node/utils/ExportHtml.js
Normal file
|
@ -0,0 +1,595 @@
|
|||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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 CommonCode = require('./common_code');
|
||||
var async = require("async");
|
||||
var Changeset = CommonCode.require("/Changeset");
|
||||
var padManager = require("../db/PadManager");
|
||||
var ERR = require("async-stacktrace");
|
||||
var Security = CommonCode.require('/security');
|
||||
|
||||
function getPadPlainText(pad, revNum)
|
||||
{
|
||||
var atext = ((revNum !== undefined) ? pad.getInternalRevisionAText(revNum) : pad.atext());
|
||||
var textLines = atext.text.slice(0, -1).split('\n');
|
||||
var attribLines = Changeset.splitAttributionLines(atext.attribs, atext.text);
|
||||
var apool = pad.pool();
|
||||
|
||||
var pieces = [];
|
||||
for (var i = 0; i < textLines.length; i++)
|
||||
{
|
||||
var line = _analyzeLine(textLines[i], attribLines[i], apool);
|
||||
if (line.listLevel)
|
||||
{
|
||||
var numSpaces = line.listLevel * 2 - 1;
|
||||
var bullet = '*';
|
||||
pieces.push(new Array(numSpaces + 1).join(' '), bullet, ' ', line.text, '\n');
|
||||
}
|
||||
else
|
||||
{
|
||||
pieces.push(line.text, '\n');
|
||||
}
|
||||
}
|
||||
|
||||
return pieces.join('');
|
||||
}
|
||||
|
||||
function getPadHTML(pad, revNum, callback)
|
||||
{
|
||||
var atext = pad.atext;
|
||||
var html;
|
||||
async.waterfall([
|
||||
// fetch revision atext
|
||||
|
||||
|
||||
function (callback)
|
||||
{
|
||||
if (revNum != undefined)
|
||||
{
|
||||
pad.getInternalRevisionAText(revNum, function (err, revisionAtext)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
atext = revisionAtext;
|
||||
callback();
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
callback(null);
|
||||
}
|
||||
},
|
||||
|
||||
// convert atext to html
|
||||
|
||||
|
||||
function (callback)
|
||||
{
|
||||
html = getHTMLFromAtext(pad, atext);
|
||||
callback(null);
|
||||
}],
|
||||
// run final callback
|
||||
|
||||
|
||||
function (err)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
callback(null, html);
|
||||
});
|
||||
}
|
||||
|
||||
exports.getPadHTML = getPadHTML;
|
||||
|
||||
function getHTMLFromAtext(pad, atext)
|
||||
{
|
||||
var apool = pad.apool();
|
||||
var textLines = atext.text.slice(0, -1).split('\n');
|
||||
var attribLines = Changeset.splitAttributionLines(atext.attribs, atext.text);
|
||||
|
||||
var tags = ['h1', 'h2', 'strong', 'em', 'u', 's'];
|
||||
var props = ['heading1', 'heading2', 'bold', 'italic', 'underline', 'strikethrough'];
|
||||
var anumMap = {};
|
||||
|
||||
props.forEach(function (propName, i)
|
||||
{
|
||||
var propTrueNum = apool.putAttrib([propName, true], true);
|
||||
if (propTrueNum >= 0)
|
||||
{
|
||||
anumMap[propTrueNum] = i;
|
||||
}
|
||||
});
|
||||
|
||||
function getLineHTML(text, attribs)
|
||||
{
|
||||
var propVals = [false, false, false];
|
||||
var ENTER = 1;
|
||||
var STAY = 2;
|
||||
var LEAVE = 0;
|
||||
|
||||
// Use order of tags (b/i/u) as order of nesting, for simplicity
|
||||
// and decent nesting. For example,
|
||||
// <b>Just bold<b> <b><i>Bold and italics</i></b> <i>Just italics</i>
|
||||
// becomes
|
||||
// <b>Just bold <i>Bold and italics</i></b> <i>Just italics</i>
|
||||
var taker = Changeset.stringIterator(text);
|
||||
var assem = Changeset.stringAssembler();
|
||||
|
||||
var openTags = [];
|
||||
function emitOpenTag(i)
|
||||
{
|
||||
openTags.unshift(i);
|
||||
assem.append('<');
|
||||
assem.append(tags[i]);
|
||||
assem.append('>');
|
||||
}
|
||||
|
||||
function emitCloseTag(i)
|
||||
{
|
||||
openTags.shift();
|
||||
assem.append('</');
|
||||
assem.append(tags[i]);
|
||||
assem.append('>');
|
||||
}
|
||||
|
||||
function orderdCloseTags(tags2close)
|
||||
{
|
||||
for(var i=0;i<openTags.length;i++)
|
||||
{
|
||||
for(var j=0;j<tags2close.length;j++)
|
||||
{
|
||||
if(tags2close[j] == openTags[i])
|
||||
{
|
||||
emitCloseTag(tags2close[j]);
|
||||
i--;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var urls = _findURLs(text);
|
||||
|
||||
var idx = 0;
|
||||
|
||||
function processNextChars(numChars)
|
||||
{
|
||||
if (numChars <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var iter = Changeset.opIterator(Changeset.subattribution(attribs, idx, idx + numChars));
|
||||
idx += numChars;
|
||||
|
||||
while (iter.hasNext())
|
||||
{
|
||||
var o = iter.next();
|
||||
var propChanged = false;
|
||||
Changeset.eachAttribNumber(o.attribs, function (a)
|
||||
{
|
||||
if (a in anumMap)
|
||||
{
|
||||
var i = anumMap[a]; // i = 0 => bold, etc.
|
||||
if (!propVals[i])
|
||||
{
|
||||
propVals[i] = ENTER;
|
||||
propChanged = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
propVals[i] = STAY;
|
||||
}
|
||||
}
|
||||
});
|
||||
for (var i = 0; i < propVals.length; i++)
|
||||
{
|
||||
if (propVals[i] === true)
|
||||
{
|
||||
propVals[i] = LEAVE;
|
||||
propChanged = true;
|
||||
}
|
||||
else if (propVals[i] === STAY)
|
||||
{
|
||||
propVals[i] = true; // set it back
|
||||
}
|
||||
}
|
||||
// now each member of propVal is in {false,LEAVE,ENTER,true}
|
||||
// according to what happens at start of span
|
||||
if (propChanged)
|
||||
{
|
||||
// leaving bold (e.g.) also leaves italics, etc.
|
||||
var left = false;
|
||||
for (var i = 0; i < propVals.length; i++)
|
||||
{
|
||||
var v = propVals[i];
|
||||
if (!left)
|
||||
{
|
||||
if (v === LEAVE)
|
||||
{
|
||||
left = true;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (v === true)
|
||||
{
|
||||
propVals[i] = STAY; // tag will be closed and re-opened
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var tags2close = [];
|
||||
|
||||
for (var i = propVals.length - 1; i >= 0; i--)
|
||||
{
|
||||
if (propVals[i] === LEAVE)
|
||||
{
|
||||
//emitCloseTag(i);
|
||||
tags2close.push(i);
|
||||
propVals[i] = false;
|
||||
}
|
||||
else if (propVals[i] === STAY)
|
||||
{
|
||||
//emitCloseTag(i);
|
||||
tags2close.push(i);
|
||||
}
|
||||
}
|
||||
|
||||
orderdCloseTags(tags2close);
|
||||
|
||||
for (var i = 0; i < propVals.length; i++)
|
||||
{
|
||||
if (propVals[i] === ENTER || propVals[i] === STAY)
|
||||
{
|
||||
emitOpenTag(i);
|
||||
propVals[i] = true;
|
||||
}
|
||||
}
|
||||
// propVals is now all {true,false} again
|
||||
} // end if (propChanged)
|
||||
var chars = o.chars;
|
||||
if (o.lines)
|
||||
{
|
||||
chars--; // exclude newline at end of line, if present
|
||||
}
|
||||
|
||||
var s = taker.take(chars);
|
||||
|
||||
//removes the characters with the code 12. Don't know where they come
|
||||
//from but they break the abiword parser and are completly useless
|
||||
s = s.replace(String.fromCharCode(12), "");
|
||||
|
||||
assem.append(_encodeWhitespace(Security.escapeHTML(s)));
|
||||
} // end iteration over spans in line
|
||||
|
||||
var tags2close = [];
|
||||
for (var i = propVals.length - 1; i >= 0; i--)
|
||||
{
|
||||
if (propVals[i])
|
||||
{
|
||||
tags2close.push(i);
|
||||
propVals[i] = false;
|
||||
}
|
||||
}
|
||||
|
||||
orderdCloseTags(tags2close);
|
||||
} // end processNextChars
|
||||
if (urls)
|
||||
{
|
||||
urls.forEach(function (urlData)
|
||||
{
|
||||
var startIndex = urlData[0];
|
||||
var url = urlData[1];
|
||||
var urlLength = url.length;
|
||||
processNextChars(startIndex - idx);
|
||||
assem.append('<a href="' + Security.escapeHTMLAttribute(url) + '">');
|
||||
processNextChars(urlLength);
|
||||
assem.append('</a>');
|
||||
});
|
||||
}
|
||||
processNextChars(text.length - idx);
|
||||
|
||||
return _processSpaces(assem.toString());
|
||||
} // end getLineHTML
|
||||
var pieces = [];
|
||||
|
||||
// Need to deal with constraints imposed on HTML lists; can
|
||||
// only gain one level of nesting at once, can't change type
|
||||
// mid-list, etc.
|
||||
// People might use weird indenting, e.g. skip a level,
|
||||
// so we want to do something reasonable there. We also
|
||||
// want to deal gracefully with blank lines.
|
||||
// => keeps track of the parents level of indentation
|
||||
var lists = []; // e.g. [[1,'bullet'], [3,'bullet'], ...]
|
||||
for (var i = 0; i < textLines.length; i++)
|
||||
{
|
||||
var line = _analyzeLine(textLines[i], attribLines[i], apool);
|
||||
var lineContent = getLineHTML(line.text, line.aline);
|
||||
|
||||
if (line.listLevel)//If we are inside a list
|
||||
{
|
||||
// do list stuff
|
||||
var whichList = -1; // index into lists or -1
|
||||
if (line.listLevel)
|
||||
{
|
||||
whichList = lists.length;
|
||||
for (var j = lists.length - 1; j >= 0; j--)
|
||||
{
|
||||
if (line.listLevel <= lists[j][0])
|
||||
{
|
||||
whichList = j;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (whichList >= lists.length)//means we are on a deeper level of indentation than the previous line
|
||||
{
|
||||
lists.push([line.listLevel, line.listTypeName]);
|
||||
if(line.listTypeName == "number")
|
||||
{
|
||||
pieces.push('<ol class="'+line.listTypeName+'"><li>', lineContent || '<br>');
|
||||
}
|
||||
else
|
||||
{
|
||||
pieces.push('<ul class="'+line.listTypeName+'"><li>', lineContent || '<br>');
|
||||
}
|
||||
}
|
||||
//the following code *seems* dead after my patch.
|
||||
//I keep it just in case I'm wrong...
|
||||
/*else if (whichList == -1)//means we are not inside a list
|
||||
{
|
||||
if (line.text)
|
||||
{
|
||||
console.log('trace 1');
|
||||
// non-blank line, end all lists
|
||||
if(line.listTypeName == "number")
|
||||
{
|
||||
pieces.push(new Array(lists.length + 1).join('</li></ol>'));
|
||||
}
|
||||
else
|
||||
{
|
||||
pieces.push(new Array(lists.length + 1).join('</li></ul>'));
|
||||
}
|
||||
lists.length = 0;
|
||||
pieces.push(lineContent, '<br>');
|
||||
}
|
||||
else
|
||||
{
|
||||
console.log('trace 2');
|
||||
pieces.push('<br><br>');
|
||||
}
|
||||
}*/
|
||||
else//means we are getting closer to the lowest level of indentation
|
||||
{
|
||||
while (whichList < lists.length - 1)
|
||||
{
|
||||
if(lists[lists.length - 1][1] == "number")
|
||||
{
|
||||
pieces.push('</li></ol>');
|
||||
}
|
||||
else
|
||||
{
|
||||
pieces.push('</li></ul>');
|
||||
}
|
||||
lists.length--;
|
||||
}
|
||||
pieces.push('</li><li>', lineContent || '<br>');
|
||||
}
|
||||
}
|
||||
else//outside any list
|
||||
{
|
||||
while (lists.length > 0)//if was in a list: close it before
|
||||
{
|
||||
if(lists[lists.length - 1][1] == "number")
|
||||
{
|
||||
pieces.push('</li></ol>');
|
||||
}
|
||||
else
|
||||
{
|
||||
pieces.push('</li></ul>');
|
||||
}
|
||||
lists.length--;
|
||||
}
|
||||
pieces.push(lineContent, '<br>');
|
||||
}
|
||||
}
|
||||
|
||||
for (var k = lists.length - 1; k >= 0; k--)
|
||||
{
|
||||
if(lists[k][1] == "number")
|
||||
{
|
||||
pieces.push('</li></ol>');
|
||||
}
|
||||
else
|
||||
{
|
||||
pieces.push('</li></ul>');
|
||||
}
|
||||
}
|
||||
|
||||
return pieces.join('');
|
||||
}
|
||||
|
||||
function _analyzeLine(text, aline, apool)
|
||||
{
|
||||
var line = {};
|
||||
|
||||
// identify list
|
||||
var lineMarker = 0;
|
||||
line.listLevel = 0;
|
||||
if (aline)
|
||||
{
|
||||
var opIter = Changeset.opIterator(aline);
|
||||
if (opIter.hasNext())
|
||||
{
|
||||
var listType = Changeset.opAttributeValue(opIter.next(), 'list', apool);
|
||||
if (listType)
|
||||
{
|
||||
lineMarker = 1;
|
||||
listType = /([a-z]+)([12345678])/.exec(listType);
|
||||
if (listType)
|
||||
{
|
||||
line.listTypeName = listType[1];
|
||||
line.listLevel = Number(listType[2]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (lineMarker)
|
||||
{
|
||||
line.text = text.substring(1);
|
||||
line.aline = Changeset.subattribution(aline, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
line.text = text;
|
||||
line.aline = aline;
|
||||
}
|
||||
|
||||
return line;
|
||||
}
|
||||
|
||||
exports.getPadHTMLDocument = function (padId, revNum, noDocType, callback)
|
||||
{
|
||||
padManager.getPad(padId, function (err, pad)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
var head =
|
||||
(noDocType ? '' : '<!doctype html>\n') +
|
||||
'<html lang="en">\n' + (noDocType ? '' : '<head>\n' +
|
||||
'<meta charset="utf-8">\n' +
|
||||
'<style> * { font-family: arial, sans-serif;\n' +
|
||||
'font-size: 13px;\n' +
|
||||
'line-height: 17px; }' +
|
||||
'ul.indent { list-style-type: none; }' +
|
||||
'ol { list-style-type: decimal; }' +
|
||||
'ol ol { list-style-type: lower-latin; }' +
|
||||
'ol ol ol { list-style-type: lower-roman; }' +
|
||||
'ol ol ol ol { list-style-type: decimal; }' +
|
||||
'ol ol ol ol ol { list-style-type: lower-latin; }' +
|
||||
'ol ol ol ol ol ol{ list-style-type: lower-roman; }' +
|
||||
'ol ol ol ol ol ol ol { list-style-type: decimal; }' +
|
||||
'ol ol ol ol ol ol ol ol{ list-style-type: lower-latin; }' +
|
||||
'</style>\n' + '</head>\n') +
|
||||
'<body>';
|
||||
|
||||
var foot = '</body>\n</html>\n';
|
||||
|
||||
getPadHTML(pad, revNum, function (err, html)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
callback(null, head + html + foot);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function _encodeWhitespace(s) {
|
||||
return s.replace(/[^\x21-\x7E\s\t\n\r]/g, function(c)
|
||||
{
|
||||
return "&#" +c.charCodeAt(0) + ";"
|
||||
});
|
||||
}
|
||||
|
||||
// copied from ACE
|
||||
|
||||
|
||||
function _processSpaces(s)
|
||||
{
|
||||
var doesWrap = true;
|
||||
if (s.indexOf("<") < 0 && !doesWrap)
|
||||
{
|
||||
// short-cut
|
||||
return s.replace(/ /g, ' ');
|
||||
}
|
||||
var parts = [];
|
||||
s.replace(/<[^>]*>?| |[^ <]+/g, function (m)
|
||||
{
|
||||
parts.push(m);
|
||||
});
|
||||
if (doesWrap)
|
||||
{
|
||||
var endOfLine = true;
|
||||
var beforeSpace = false;
|
||||
// last space in a run is normal, others are nbsp,
|
||||
// end of line is nbsp
|
||||
for (var i = parts.length - 1; i >= 0; i--)
|
||||
{
|
||||
var p = parts[i];
|
||||
if (p == " ")
|
||||
{
|
||||
if (endOfLine || beforeSpace) parts[i] = ' ';
|
||||
endOfLine = false;
|
||||
beforeSpace = true;
|
||||
}
|
||||
else if (p.charAt(0) != "<")
|
||||
{
|
||||
endOfLine = false;
|
||||
beforeSpace = false;
|
||||
}
|
||||
}
|
||||
// beginning of line is nbsp
|
||||
for (var i = 0; i < parts.length; i++)
|
||||
{
|
||||
var p = parts[i];
|
||||
if (p == " ")
|
||||
{
|
||||
parts[i] = ' ';
|
||||
break;
|
||||
}
|
||||
else if (p.charAt(0) != "<")
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (var i = 0; i < parts.length; i++)
|
||||
{
|
||||
var p = parts[i];
|
||||
if (p == " ")
|
||||
{
|
||||
parts[i] = ' ';
|
||||
}
|
||||
}
|
||||
}
|
||||
return parts.join('');
|
||||
}
|
||||
|
||||
|
||||
// copied from ACE
|
||||
var _REGEX_WORDCHAR = /[\u0030-\u0039\u0041-\u005A\u0061-\u007A\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0100-\u1FFF\u3040-\u9FFF\uF900-\uFDFF\uFE70-\uFEFE\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFDC]/;
|
||||
var _REGEX_SPACE = /\s/;
|
||||
var _REGEX_URLCHAR = new RegExp('(' + /[-:@a-zA-Z0-9_.,~%+\/\\?=&#;()$]/.source + '|' + _REGEX_WORDCHAR.source + ')');
|
||||
var _REGEX_URL = new RegExp(/(?:(?:https?|s?ftp|ftps|file|smb|afp|nfs|(x-)?man|gopher|txmt):\/\/|mailto:)/.source + _REGEX_URLCHAR.source + '*(?![:.,;])' + _REGEX_URLCHAR.source, 'g');
|
||||
|
||||
// returns null if no URLs, or [[startIndex1, url1], [startIndex2, url2], ...]
|
||||
|
||||
|
||||
function _findURLs(text)
|
||||
{
|
||||
_REGEX_URL.lastIndex = 0;
|
||||
var urls = null;
|
||||
var execResult;
|
||||
while ((execResult = _REGEX_URL.exec(text)))
|
||||
{
|
||||
urls = (urls || []);
|
||||
var startIndex = execResult.index;
|
||||
var url = execResult[0];
|
||||
urls.push([startIndex, url]);
|
||||
}
|
||||
|
||||
return urls;
|
||||
}
|
93
src/node/utils/ImportHtml.js
Normal file
|
@ -0,0 +1,93 @@
|
|||
/**
|
||||
* Copyright Yaco Sistemas S.L. 2011.
|
||||
*
|
||||
* 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 jsdom = require('jsdom-nocontextifiy').jsdom;
|
||||
var log4js = require('log4js');
|
||||
|
||||
var CommonCode = require('../utils/common_code');
|
||||
var Changeset = CommonCode.require("/Changeset");
|
||||
var contentcollector = CommonCode.require("/contentcollector");
|
||||
var map = CommonCode.require("/ace2_common").map;
|
||||
|
||||
function setPadHTML(pad, html, callback)
|
||||
{
|
||||
var apiLogger = log4js.getLogger("ImportHtml");
|
||||
|
||||
// Clean the pad. This makes the rest of the code easier
|
||||
// by several orders of magnitude.
|
||||
pad.setText("");
|
||||
var padText = pad.text();
|
||||
|
||||
// Parse the incoming HTML with jsdom
|
||||
var doc = jsdom(html.replace(/>\n+</g, '><'));
|
||||
apiLogger.debug('html:');
|
||||
apiLogger.debug(html);
|
||||
|
||||
// Convert a dom tree into a list of lines and attribute liens
|
||||
// using the content collector object
|
||||
var cc = contentcollector.makeContentCollector(true, null, pad.pool);
|
||||
cc.collectContent(doc.childNodes[0]);
|
||||
var result = cc.finish();
|
||||
apiLogger.debug('Lines:');
|
||||
var i;
|
||||
for (i = 0; i < result.lines.length; i += 1)
|
||||
{
|
||||
apiLogger.debug('Line ' + (i + 1) + ' text: ' + result.lines[i]);
|
||||
apiLogger.debug('Line ' + (i + 1) + ' attributes: ' + result.lineAttribs[i]);
|
||||
}
|
||||
|
||||
// Get the new plain text and its attributes
|
||||
var newText = map(result.lines, function (e) {
|
||||
return e + '\n';
|
||||
}).join('');
|
||||
apiLogger.debug('newText:');
|
||||
apiLogger.debug(newText);
|
||||
var newAttribs = result.lineAttribs.join('|1+1') + '|1+1';
|
||||
|
||||
function eachAttribRun(attribs, func /*(startInNewText, endInNewText, attribs)*/ )
|
||||
{
|
||||
var attribsIter = Changeset.opIterator(attribs);
|
||||
var textIndex = 0;
|
||||
var newTextStart = 0;
|
||||
var newTextEnd = newText.length - 1;
|
||||
while (attribsIter.hasNext())
|
||||
{
|
||||
var op = attribsIter.next();
|
||||
var nextIndex = textIndex + op.chars;
|
||||
if (!(nextIndex <= newTextStart || textIndex >= newTextEnd))
|
||||
{
|
||||
func(Math.max(newTextStart, textIndex), Math.min(newTextEnd, nextIndex), op.attribs);
|
||||
}
|
||||
textIndex = nextIndex;
|
||||
}
|
||||
}
|
||||
|
||||
// create a new changeset with a helper builder object
|
||||
var builder = Changeset.builder(1);
|
||||
|
||||
// assemble each line into the builder
|
||||
eachAttribRun(newAttribs, function(start, end, attribs)
|
||||
{
|
||||
builder.insert(newText.substring(start, end), attribs);
|
||||
});
|
||||
|
||||
// the changeset is ready!
|
||||
var theChangeset = builder.toString();
|
||||
apiLogger.debug('The changeset: ' + theChangeset);
|
||||
pad.appendRevision(theChangeset);
|
||||
}
|
||||
|
||||
exports.setPadHTML = setPadHTML;
|
338
src/node/utils/Minify.js
Normal file
|
@ -0,0 +1,338 @@
|
|||
/**
|
||||
* This Module manages all /minified/* requests. It controls the
|
||||
* minification && compression of Javascript and CSS.
|
||||
*/
|
||||
|
||||
/*
|
||||
* 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
|
||||
*
|
||||
* 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 ERR = require("async-stacktrace");
|
||||
var settings = require('./Settings');
|
||||
var async = require('async');
|
||||
var fs = require('fs');
|
||||
var cleanCSS = require('clean-css');
|
||||
var jsp = require("uglify-js").parser;
|
||||
var pro = require("uglify-js").uglify;
|
||||
var path = require('path');
|
||||
var Buffer = require('buffer').Buffer;
|
||||
var zlib = require('zlib');
|
||||
var RequireKernel = require('require-kernel');
|
||||
var server = require('../server');
|
||||
var os = require('os');
|
||||
|
||||
var ROOT_DIR = path.normalize(__dirname + "/../" );
|
||||
var JS_DIR = ROOT_DIR + '../static/js/';
|
||||
var CSS_DIR = ROOT_DIR + '../static/css/';
|
||||
var CACHE_DIR = path.join(settings.root, 'var');
|
||||
var TAR_PATH = path.join(__dirname, 'tar.json');
|
||||
var tar = JSON.parse(fs.readFileSync(TAR_PATH, 'utf8'));
|
||||
|
||||
/**
|
||||
* creates the minifed javascript for the given minified name
|
||||
* @param req the Express request
|
||||
* @param res the Express response
|
||||
*/
|
||||
exports.minifyJS = function(req, res, next)
|
||||
{
|
||||
var jsFilename = req.params['filename'];
|
||||
|
||||
//choose the js files we need
|
||||
var jsFiles = undefined;
|
||||
if (Object.prototype.hasOwnProperty.call(tar, jsFilename)) {
|
||||
jsFiles = tar[jsFilename];
|
||||
_handle(req, res, jsFilename, jsFiles)
|
||||
} else {
|
||||
// Not in tar list, but try anyways, if it fails, pass to `next`.
|
||||
jsFiles = [jsFilename];
|
||||
fs.stat(JS_DIR + jsFilename, function (error, stats) {
|
||||
if (error || !stats.isFile()) {
|
||||
next();
|
||||
} else {
|
||||
_handle(req, res, jsFilename, jsFiles);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function _handle(req, res, jsFilename, jsFiles) {
|
||||
res.header("Content-Type","text/javascript");
|
||||
|
||||
//minifying is enabled
|
||||
if(settings.minify)
|
||||
{
|
||||
var result = undefined;
|
||||
var latestModification = 0;
|
||||
|
||||
async.series([
|
||||
//find out the highest modification date
|
||||
function(callback)
|
||||
{
|
||||
var folders2check = [CSS_DIR, JS_DIR];
|
||||
|
||||
//go trough this two folders
|
||||
async.forEach(folders2check, function(path, callback)
|
||||
{
|
||||
//read the files in the folder
|
||||
fs.readdir(path, function(err, files)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//we wanna check the directory itself for changes too
|
||||
files.push(".");
|
||||
|
||||
//go trough all files in this folder
|
||||
async.forEach(files, function(filename, callback)
|
||||
{
|
||||
//get the stat data of this file
|
||||
fs.stat(path + "/" + filename, function(err, stats)
|
||||
{
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
//get the modification time
|
||||
var modificationTime = stats.mtime.getTime();
|
||||
|
||||
//compare the modification time to the highest found
|
||||
if(modificationTime > latestModification)
|
||||
{
|
||||
latestModification = modificationTime;
|
||||
}
|
||||
|
||||
callback();
|
||||
});
|
||||
}, callback);
|
||||
});
|
||||
}, callback);
|
||||
},
|
||||
function(callback)
|
||||
{
|
||||
//check the modification time of the minified js
|
||||
fs.stat(CACHE_DIR + "/minified_" + jsFilename, function(err, stats)
|
||||
{
|
||||
if(err && err.code != "ENOENT")
|
||||
{
|
||||
ERR(err, callback);
|
||||
return;
|
||||
}
|
||||
|
||||
//there is no minfied file or there new changes since this file was generated, so continue generating this file
|
||||
if((err && err.code == "ENOENT") || stats.mtime.getTime() < latestModification)
|
||||
{
|
||||
callback();
|
||||
}
|
||||
//the minified file is still up to date, stop minifying
|
||||
else
|
||||
{
|
||||
callback("stop");
|
||||
}
|
||||
});
|
||||
},
|
||||
//load all js files
|
||||
function (callback)
|
||||
{
|
||||
var values = [];
|
||||
tarCode(
|
||||
jsFiles
|
||||
, function (content) {values.push(content)}
|
||||
, function (err) {
|
||||
if(ERR(err)) return;
|
||||
|
||||
result = values.join('');
|
||||
callback();
|
||||
});
|
||||
},
|
||||
//put all together and write it into a file
|
||||
function(callback)
|
||||
{
|
||||
async.parallel([
|
||||
//write the results plain in a file
|
||||
function(callback)
|
||||
{
|
||||
fs.writeFile(CACHE_DIR + "/minified_" + jsFilename, result, "utf8", callback);
|
||||
},
|
||||
//write the results compressed in a file
|
||||
function(callback)
|
||||
{
|
||||
zlib.gzip(result, function(err, compressedResult){
|
||||
//weird gzip bug that returns 0 instead of null if everything is ok
|
||||
err = err === 0 ? null : err;
|
||||
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
fs.writeFile(CACHE_DIR + "/minified_" + jsFilename + ".gz", compressedResult, callback);
|
||||
});
|
||||
}
|
||||
],callback);
|
||||
}
|
||||
], function(err)
|
||||
{
|
||||
if(err && err != "stop")
|
||||
{
|
||||
if(ERR(err)) return;
|
||||
}
|
||||
|
||||
//check if gzip is supported by this browser
|
||||
var gzipSupport = req.header('Accept-Encoding', '').indexOf('gzip') != -1;
|
||||
|
||||
var pathStr;
|
||||
if(gzipSupport && os.type().indexOf("Windows") == -1)
|
||||
{
|
||||
pathStr = path.normalize(CACHE_DIR + "/minified_" + jsFilename + ".gz");
|
||||
res.header('Content-Encoding', 'gzip');
|
||||
}
|
||||
else
|
||||
{
|
||||
pathStr = path.normalize(CACHE_DIR + "/minified_" + jsFilename );
|
||||
}
|
||||
|
||||
res.sendfile(pathStr, { maxAge: server.maxAge });
|
||||
})
|
||||
}
|
||||
//minifying is disabled, so put the files together in one file
|
||||
else
|
||||
{
|
||||
tarCode(
|
||||
jsFiles
|
||||
, function (content) {res.write(content)}
|
||||
, function (err) {
|
||||
if(ERR(err)) return;
|
||||
res.end();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// find all includes in ace.js and embed them.
|
||||
function getAceFile(callback) {
|
||||
fs.readFile(JS_DIR + 'ace.js', "utf8", function(err, data) {
|
||||
if(ERR(err, callback)) return;
|
||||
|
||||
// Find all includes in ace.js and embed them
|
||||
var founds = data.match(/\$\$INCLUDE_[a-zA-Z_]+\([a-zA-Z0-9.\/_"-]+\)/gi);
|
||||
if (!settings.minify) {
|
||||
founds = [];
|
||||
}
|
||||
founds.push('$$INCLUDE_JS("../static/js/require-kernel.js")');
|
||||
|
||||
data += ';\n';
|
||||
data += 'Ace2Editor.EMBEDED = Ace2Editor.EMBEDED || {};\n';
|
||||
|
||||
//go trough all includes
|
||||
async.forEach(founds, function (item, callback) {
|
||||
var filename = item.match(/"([^"]*)"/)[1];
|
||||
var type = item.match(/INCLUDE_([A-Z]+)/)[1];
|
||||
var shortFilename = (filename.match(/^..\/static\/js\/(.*)$/, '')||[])[1];
|
||||
|
||||
//read the included files
|
||||
if (shortFilename) {
|
||||
if (shortFilename == 'require-kernel.js') {
|
||||
// the kernel isn’t actually on the file system.
|
||||
handleEmbed(null, requireDefinition());
|
||||
} else {
|
||||
var contents = '';
|
||||
tarCode(tar[shortFilename] || shortFilename
|
||||
, function (content) {
|
||||
contents += content;
|
||||
}
|
||||
, function () {
|
||||
handleEmbed(null, contents);
|
||||
}
|
||||
);
|
||||
}
|
||||
} else {
|
||||
fs.readFile(ROOT_DIR + filename, "utf8", handleEmbed);
|
||||
}
|
||||
|
||||
function handleEmbed(error, data_) {
|
||||
if (error) {
|
||||
return; // Don't bother to include it.
|
||||
}
|
||||
if (settings.minify) {
|
||||
if (type == "JS") {
|
||||
try {
|
||||
data_ = compressJS([data_]);
|
||||
} catch (e) {
|
||||
// Ignore, include uncompresseed, which will break in browser.
|
||||
}
|
||||
} else {
|
||||
data_ = compressCSS([data_]);
|
||||
}
|
||||
}
|
||||
data += 'Ace2Editor.EMBEDED[' + JSON.stringify(filename) + '] = '
|
||||
+ JSON.stringify(data_) + ';\n';
|
||||
callback();
|
||||
}
|
||||
}, function(error) {
|
||||
callback(error, data);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
exports.requireDefinition = requireDefinition;
|
||||
function requireDefinition() {
|
||||
return 'var require = ' + RequireKernel.kernelSource + ';\n';
|
||||
}
|
||||
|
||||
function tarCode(jsFiles, write, callback) {
|
||||
write('require.define({');
|
||||
var initialEntry = true;
|
||||
async.forEach(jsFiles, function (filename, callback){
|
||||
if (filename == 'ace.js') {
|
||||
getAceFile(handleFile);
|
||||
} else {
|
||||
fs.readFile(JS_DIR + filename, "utf8", handleFile);
|
||||
}
|
||||
|
||||
function handleFile(err, data) {
|
||||
if(ERR(err, callback)) return;
|
||||
var srcPath = JSON.stringify('/' + filename);
|
||||
var srcPathAbbv = JSON.stringify('/' + filename.replace(/\.js$/, ''));
|
||||
if (!initialEntry) {
|
||||
write('\n,');
|
||||
} else {
|
||||
initialEntry = false;
|
||||
}
|
||||
write(srcPath + ': ')
|
||||
data = '(function (require, exports, module) {' + data + '})';
|
||||
if (settings.minify) {
|
||||
write(compressJS([data]));
|
||||
} else {
|
||||
write(data);
|
||||
}
|
||||
if (srcPath != srcPathAbbv) {
|
||||
write('\n,' + srcPathAbbv + ': null');
|
||||
}
|
||||
|
||||
callback();
|
||||
}
|
||||
}, function () {
|
||||
write('});\n');
|
||||
callback();
|
||||
});
|
||||
}
|
||||
|
||||
function compressJS(values)
|
||||
{
|
||||
var complete = values.join("\n");
|
||||
var ast = jsp.parse(complete); // parse code and get the initial AST
|
||||
ast = pro.ast_mangle(ast); // get a new AST with mangled names
|
||||
ast = pro.ast_squeeze(ast); // get an AST with compression optimizations
|
||||
return pro.gen_code(ast); // compressed code here
|
||||
}
|
||||
|
||||
function compressCSS(values)
|
||||
{
|
||||
var complete = values.join("\n");
|
||||
return cleanCSS.process(complete);
|
||||
}
|
141
src/node/utils/Settings.js
Normal file
|
@ -0,0 +1,141 @@
|
|||
/**
|
||||
* The Settings Modul reads the settings out of settings.json and provides
|
||||
* this information to the other modules
|
||||
*/
|
||||
|
||||
/*
|
||||
* 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
|
||||
*
|
||||
* 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 fs = require("fs");
|
||||
var os = require("os");
|
||||
var path = require('path');
|
||||
var argv = require('./Cli').argv;
|
||||
var npm = require("npm/lib/npm.js");
|
||||
|
||||
/* Root path of the installation */
|
||||
exports.root = path.normalize(path.join(npm.dir, ".."));
|
||||
|
||||
/**
|
||||
* The IP ep-lite should listen to
|
||||
*/
|
||||
exports.ip = "0.0.0.0";
|
||||
|
||||
/**
|
||||
* The Port ep-lite should listen to
|
||||
*/
|
||||
exports.port = 9001;
|
||||
/*
|
||||
* The Type of the database
|
||||
*/
|
||||
exports.dbType = "dirty";
|
||||
/**
|
||||
* This setting is passed with dbType to ueberDB to set up the database
|
||||
*/
|
||||
exports.dbSettings = { "filename" : path.join(exports.root, "var/dirty.db") };
|
||||
/**
|
||||
* The default Text of a new pad
|
||||
*/
|
||||
exports.defaultPadText = "Welcome to Etherpad Lite!\n\nThis pad text is synchronized as you type, so that everyone viewing this page sees the same text. This allows you to collaborate seamlessly on documents!\n\nEtherpad Lite on Github: http:\/\/j.mp/ep-lite\n";
|
||||
|
||||
/**
|
||||
* A flag that requires any user to have a valid session (via the api) before accessing a pad
|
||||
*/
|
||||
exports.requireSession = false;
|
||||
|
||||
/**
|
||||
* A flag that prevents users from creating new pads
|
||||
*/
|
||||
exports.editOnly = false;
|
||||
|
||||
/**
|
||||
* A flag that shows if minification is enabled or not
|
||||
*/
|
||||
exports.minify = true;
|
||||
|
||||
/**
|
||||
* The path of the abiword executable
|
||||
*/
|
||||
exports.abiword = null;
|
||||
|
||||
/**
|
||||
* The log level of log4js
|
||||
*/
|
||||
exports.loglevel = "INFO";
|
||||
|
||||
/**
|
||||
* Http basic auth, with "user:password" format
|
||||
*/
|
||||
exports.httpAuth = null;
|
||||
|
||||
//checks if abiword is avaiable
|
||||
exports.abiwordAvailable = function()
|
||||
{
|
||||
if(exports.abiword != null)
|
||||
{
|
||||
return os.type().indexOf("Windows") != -1 ? "withoutPDF" : "yes";
|
||||
}
|
||||
else
|
||||
{
|
||||
return "no";
|
||||
}
|
||||
}
|
||||
|
||||
// Discover where the settings file lives
|
||||
var settingsFilename = argv.settings || "settings.json";
|
||||
if (settingsFilename.charAt(0) != '/') {
|
||||
settingsFilename = path.normalize(path.join(root, settingsFilename));
|
||||
}
|
||||
|
||||
//read the settings sync
|
||||
var settingsStr = fs.readFileSync(settingsFilename).toString();
|
||||
|
||||
//remove all comments
|
||||
settingsStr = settingsStr.replace(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/gm,"").replace(/#.*/g,"").replace(/\/\/.*/g,"");
|
||||
|
||||
//try to parse the settings
|
||||
var settings;
|
||||
try
|
||||
{
|
||||
settings = JSON.parse(settingsStr);
|
||||
}
|
||||
catch(e)
|
||||
{
|
||||
console.error("There is a syntax error in your settings.json file");
|
||||
console.error(e.message);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
//loop trough the settings
|
||||
for(var i in settings)
|
||||
{
|
||||
//test if the setting start with a low character
|
||||
if(i.charAt(0).search("[a-z]") !== 0)
|
||||
{
|
||||
console.warn("Settings should start with a low character: '" + i + "'");
|
||||
}
|
||||
|
||||
//we know this setting, so we overwrite it
|
||||
if(exports[i] !== undefined)
|
||||
{
|
||||
exports[i] = settings[i];
|
||||
}
|
||||
//this setting is unkown, output a warning and throw it away
|
||||
else
|
||||
{
|
||||
console.warn("Unkown Setting: '" + i + "'");
|
||||
console.warn("This setting doesn't exist or it was removed");
|
||||
}
|
||||
}
|
24
src/node/utils/common_code.js
Normal file
|
@ -0,0 +1,24 @@
|
|||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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 RequireKernel = require('require-kernel/');
|
||||
var path = require('path');
|
||||
|
||||
var CLIENT_JS_SRC = path.normalize(__dirname + '/../../static/js/');
|
||||
var client_require = RequireKernel.requireForPaths(
|
||||
'file://' + (CLIENT_JS_SRC.charAt(0) == '/' ? '' : '/') + encodeURI(CLIENT_JS_SRC));
|
||||
|
||||
exports.require = client_require;
|
17
src/node/utils/customError.js
Normal file
|
@ -0,0 +1,17 @@
|
|||
/*
|
||||
This helper modules allows us to create different type of errors we can throw
|
||||
*/
|
||||
function customError(message, errorName)
|
||||
{
|
||||
this.name = errorName || "Error";
|
||||
this.message = message;
|
||||
|
||||
var stackParts = new Error().stack.split("\n");
|
||||
stackParts.splice(0,2);
|
||||
stackParts.unshift(this.name + ": " + message);
|
||||
|
||||
this.stack = stackParts.join("\n");
|
||||
}
|
||||
customError.prototype = Error.prototype;
|
||||
|
||||
module.exports = customError;
|
70
src/node/utils/tar.json
Normal file
|
@ -0,0 +1,70 @@
|
|||
{
|
||||
"pad.js": [
|
||||
"jquery.js"
|
||||
, "security.js"
|
||||
, "pad.js"
|
||||
, "ace2_common.js"
|
||||
, "pad_utils.js"
|
||||
, "plugins.js"
|
||||
, "undo-xpopup.js"
|
||||
, "json2.js"
|
||||
, "pad_cookie.js"
|
||||
, "pad_editor.js"
|
||||
, "pad_editbar.js"
|
||||
, "pad_docbar.js"
|
||||
, "pad_modals.js"
|
||||
, "ace.js"
|
||||
, "collab_client.js"
|
||||
, "pad_userlist.js"
|
||||
, "pad_impexp.js"
|
||||
, "pad_savedrevs.js"
|
||||
, "pad_connectionstatus.js"
|
||||
, "chat.js"
|
||||
, "excanvas.js"
|
||||
, "farbtastic.js"
|
||||
, "prefixfree.js"
|
||||
]
|
||||
, "timeslider.js": [
|
||||
"jquery.js"
|
||||
, "security.js"
|
||||
, "plugins.js"
|
||||
, "undo-xpopup.js"
|
||||
, "json2.js"
|
||||
, "colorutils.js"
|
||||
, "draggable.js"
|
||||
, "ace2_common.js"
|
||||
, "pad_utils.js"
|
||||
, "pad_cookie.js"
|
||||
, "pad_editor.js"
|
||||
, "pad_editbar.js"
|
||||
, "pad_docbar.js"
|
||||
, "pad_modals.js"
|
||||
, "pad_savedrevs.js"
|
||||
, "pad_impexp.js"
|
||||
, "AttributePoolFactory.js"
|
||||
, "Changeset.js"
|
||||
, "domline.js"
|
||||
, "linestylefilter.js"
|
||||
, "cssmanager.js"
|
||||
, "broadcast.js"
|
||||
, "broadcast_slider.js"
|
||||
, "broadcast_revisions.js"
|
||||
, "timeslider.js"
|
||||
]
|
||||
, "ace2_inner.js": [
|
||||
"ace2_common.js"
|
||||
, "AttributePoolFactory.js"
|
||||
, "Changeset.js"
|
||||
, "security.js"
|
||||
, "skiplist.js"
|
||||
, "virtual_lines.js"
|
||||
, "cssmanager.js"
|
||||
, "colorutils.js"
|
||||
, "undomodule.js"
|
||||
, "contentcollector.js"
|
||||
, "changesettracker.js"
|
||||
, "linestylefilter.js"
|
||||
, "domline.js"
|
||||
, "ace2_inner.js"
|
||||
]
|
||||
}
|
33
src/package.json
Normal file
|
@ -0,0 +1,33 @@
|
|||
{
|
||||
"name" : "pluginomatic_etherpad-lite",
|
||||
"description" : "A Etherpad based on node.js",
|
||||
"homepage" : "https://github.com/Pita/etherpad-lite",
|
||||
"keywords" : ["etherpad", "realtime", "collaborative", "editor"],
|
||||
"author" : "Peter 'Pita' Martischka <petermartischka@googlemail.com> - Primary Technology Ltd",
|
||||
"contributors" : [
|
||||
{ "name": "John McLear",
|
||||
"name": "Hans Pinckaers",
|
||||
"name": "Robin Buse" }
|
||||
],
|
||||
"dependencies" : {
|
||||
"require-kernel" : "1.0.3",
|
||||
"socket.io" : "0.8.7",
|
||||
"ueberDB" : "0.1.7",
|
||||
"async" : "0.1.15",
|
||||
"express" : "2.5.0",
|
||||
"clean-css" : "0.3.2",
|
||||
"uglify-js" : "1.2.5",
|
||||
"formidable" : "1.0.7",
|
||||
"log4js" : "0.4.1",
|
||||
"jsdom-nocontextifiy" : "0.2.10",
|
||||
"async-stacktrace" : "0.0.2",
|
||||
"npm" : "1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"jshint" : "*"
|
||||
},
|
||||
"engines" : { "node" : ">=0.6.0",
|
||||
"npm" : ">=1.0"
|
||||
},
|
||||
"version" : "1.0.0"
|
||||
}
|
15
src/pluginomatic.json
Normal file
|
@ -0,0 +1,15 @@
|
|||
{
|
||||
"parts": [
|
||||
{ "name": "static", "hooks": { "expressCreateServer": "../hooks/express/static:expressCreateServer" } },
|
||||
{ "name": "specialpages", "hooks": { "expressCreateServer": "../hooks/express/specialpages:expressCreateServer" } },
|
||||
{ "name": "padurlsanitize", "hooks": { "expressCreateServer": "../hooks/express/padurlsanitize:expressCreateServer" } },
|
||||
{ "name": "minified", "hooks": { "expressCreateServer": "../hooks/express/minified:expressCreateServer" } },
|
||||
{ "name": "padreadonly", "hooks": { "expressCreateServer": "../hooks/express/padreadonly:expressCreateServer" } },
|
||||
{ "name": "webaccess", "hooks": { "expressConfigure": "../hooks/express/webaccess:expressConfigure" } },
|
||||
{ "name": "apicalls", "hooks": { "expressCreateServer": "../hooks/express/apicalls:expressCreateServer" } },
|
||||
{ "name": "importexport", "hooks": { "expressCreateServer": "../hooks/express/importexport:expressCreateServer" } },
|
||||
{ "name": "errorhandling", "hooks": { "expressCreateServer": "../hooks/express/errorhandling:expressCreateServer" } },
|
||||
{ "name": "socketio", "hooks": { "expressCreateServer": "../hooks/express/socketio:expressCreateServer" } }
|
||||
|
||||
]
|
||||
}
|
203
src/static/css/iframe_editor.css
Normal file
|
@ -0,0 +1,203 @@
|
|||
|
||||
/* These CSS rules are included in both the outer and inner ACE iframe.
|
||||
Also see inner.css, included only in the inner one.
|
||||
*/
|
||||
html { cursor: text; } /* in Safari, produces text cursor for whole doc (inc. below body) */
|
||||
span { cursor: auto; }
|
||||
|
||||
a { cursor: pointer !important; }
|
||||
|
||||
ul, ol, li {
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
ul { margin-left: 1.5em; }
|
||||
ul ul { margin-left: 0 !important; }
|
||||
ul.list-bullet1 { margin-left: 1.5em; }
|
||||
ul.list-bullet2 { margin-left: 3em; }
|
||||
ul.list-bullet3 { margin-left: 4.5em; }
|
||||
ul.list-bullet4 { margin-left: 6em; }
|
||||
ul.list-bullet5 { margin-left: 7.5em; }
|
||||
ul.list-bullet6 { margin-left: 9em; }
|
||||
ul.list-bullet7 { margin-left: 10.5em; }
|
||||
ul.list-bullet8 { margin-left: 12em; }
|
||||
|
||||
ul { list-style-type: disc; }
|
||||
ul.list-bullet1 { list-style-type: disc; }
|
||||
ul.list-bullet2 { list-style-type: circle; }
|
||||
ul.list-bullet3 { list-style-type: square; }
|
||||
ul.list-bullet4 { list-style-type: disc; }
|
||||
ul.list-bullet5 { list-style-type: circle; }
|
||||
ul.list-bullet6 { list-style-type: square; }
|
||||
ul.list-bullet7 { list-style-type: disc; }
|
||||
ul.list-bullet8 { list-style-type: circle; }
|
||||
|
||||
ol.list-number1 { margin-left: 1.5em; }
|
||||
ol.list-number2 { margin-left: 3em; }
|
||||
ol.list-number3 { margin-left: 4.5em; }
|
||||
ol.list-number4 { margin-left: 6em; }
|
||||
ol.list-number5 { margin-left: 7.5em; }
|
||||
ol.list-number6 { margin-left: 9em; }
|
||||
ol.list-number7 { margin-left: 10.5em; }
|
||||
ol.list-number8 { margin-left: 12em; }
|
||||
|
||||
ol { list-style-type: decimal; }
|
||||
ol.list-number1 { list-style-type: decimal; }
|
||||
ol.list-number2 { list-style-type: lower-latin; }
|
||||
ol.list-number3 { list-style-type: lower-roman; }
|
||||
ol.list-number4 { list-style-type: decimal; }
|
||||
ol.list-number5 { list-style-type: lower-latin; }
|
||||
ol.list-number6 { list-style-type: lower-roman; }
|
||||
ol.list-number7 { list-style-type: decimal; }
|
||||
ol.list-number8 { list-style-type: lower-latin; }
|
||||
|
||||
ul.list-indent1 { margin-left: 1.5em; }
|
||||
ul.list-indent2 { margin-left: 3em; }
|
||||
ul.list-indent3 { margin-left: 4.5em; }
|
||||
ul.list-indent4 { margin-left: 6em; }
|
||||
ul.list-indent5 { margin-left: 7.5em; }
|
||||
ul.list-indent6 { margin-left: 9em; }
|
||||
ul.list-indent7 { margin-left: 10.5em; }
|
||||
ul.list-indent8 { margin-left: 12em; }
|
||||
|
||||
ul.list-indent1 { list-style-type: none; }
|
||||
ul.list-indent2 { list-style-type: none; }
|
||||
ul.list-indent3 { list-style-type: none; }
|
||||
ul.list-indent4 { list-style-type: none; }
|
||||
ul.list-indent5 { list-style-type: none; }
|
||||
ul.list-indent6 { list-style-type: none; }
|
||||
ul.list-indent7 { list-style-type: none; }
|
||||
ul.list-indent8 { list-style-type: none; }
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
#outerdocbody {
|
||||
background-color: #fff;
|
||||
}
|
||||
body.grayedout { background-color: #eee !important }
|
||||
|
||||
#innerdocbody {
|
||||
font-size: 12px; /* overridden by body.style */
|
||||
font-family: monospace; /* overridden by body.style */
|
||||
line-height: 16px; /* overridden by body.style */
|
||||
}
|
||||
|
||||
body.doesWrap {
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
#innerdocbody {
|
||||
padding-top: 1px; /* important for some reason? */
|
||||
padding-right: 10px;
|
||||
padding-bottom: 8px;
|
||||
padding-left: 1px /* prevents characters from looking chopped off in FF3 -- Removed because it added too much whitespace */;
|
||||
overflow: hidden;
|
||||
/* blank 1x1 gif, so that IE8 doesn't consider the body transparent */
|
||||
background-image: url(data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==);
|
||||
}
|
||||
|
||||
#sidediv {
|
||||
font-size: 11px;
|
||||
font-family: monospace;
|
||||
line-height: 16px; /* overridden by sideDiv.style */
|
||||
padding-top: 8px; /* EDIT_BODY_PADDING_TOP */
|
||||
padding-right: 3px; /* LINE_NUMBER_PADDING_RIGHT - 1 */
|
||||
position: absolute;
|
||||
width: 20px; /* MIN_LINEDIV_WIDTH */
|
||||
top: 0;
|
||||
left: 0;
|
||||
cursor: default;
|
||||
color: white;
|
||||
}
|
||||
|
||||
#sidedivinner {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.sidedivdelayed { /* class set after sizes are set */
|
||||
background-color: #eee;
|
||||
color: #888 !important;
|
||||
border-right: 1px solid #999;
|
||||
}
|
||||
.sidedivhidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#outerdocbody iframe {
|
||||
display: block; /* codemirror says it suppresses bugs */
|
||||
position: relative;
|
||||
left: 32px; /* MIN_LINEDIV_WIDTH + LINE_NUMBER_PADDING_RIGHT + EDIT_BODY_PADDING_LEFT */
|
||||
top: 7px; /* EDIT_BODY_PADDING_TOP - 1*/
|
||||
border: 0;
|
||||
width: 1px; /* changed programmatically */
|
||||
height: 1px; /* changed programmatically */
|
||||
}
|
||||
|
||||
#outerdocbody .hotrect {
|
||||
border: 1px solid #999;
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
/* cause "body" area (e.g. where clicks are heard) to grow horizontally with text */
|
||||
body.mozilla, body.safari {
|
||||
display: table-cell;
|
||||
}
|
||||
|
||||
body.doesWrap {
|
||||
display: block !important;
|
||||
}
|
||||
|
||||
.safari div {
|
||||
/* prevents the caret from disappearing on the longest line of the doc */
|
||||
padding-right: 1px;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
#linemetricsdiv {
|
||||
position: absolute;
|
||||
left: -1000px;
|
||||
top: -1000px;
|
||||
color: white;
|
||||
z-index: -1;
|
||||
font-size: 12px; /* overridden by lineMetricsDiv.style */
|
||||
font-family: monospace; /* overridden by lineMetricsDiv.style */
|
||||
}
|
||||
|
||||
#overlaysdiv { position: absolute; left: -1000px; top: -1000px; }
|
||||
|
||||
/* ---------- Used by JavaScript Lexer ---------- */
|
||||
.syntax .c { color: #bd3f00; font-style: italic } /* Comment */
|
||||
.syntax .o { font-weight: bold; } /* Operator */
|
||||
.syntax .p { font-weight: bold; } /* Punctuation */
|
||||
.syntax .k { color: blue; } /* Keyword */
|
||||
.syntax .kc { color: purple } /* Keyword.Constant */
|
||||
.syntax .nx { } /* Name.Other */
|
||||
.syntax .mf { color: purple } /* Literal.Number.Float */
|
||||
.syntax .mh { color: purple } /* Literal.Number.Hex */
|
||||
.syntax .mi { color: purple } /* Literal.Number.Integer */
|
||||
.syntax .sr { color: purple } /* Literal.String.Regex */
|
||||
.syntax .s2 { color: purple } /* Literal.String.Double */
|
||||
.syntax .s1 { color: purple } /* Literal.String.Single */
|
||||
.syntax .sd { color: purple } /* Literal.String.Doc */
|
||||
.syntax .cs { color: #00aa33; font-weight: bold; font-style: italic } /* Comment.Special */
|
||||
.syntax .err { color: #cc0000; font-weight: bold; text-decoration: underline; } /* Error */
|
||||
|
||||
/* css */
|
||||
.syntax .nt { font-weight: bold; } /* tag */
|
||||
.syntax .nc { color: #336; } /* class */
|
||||
.syntax .nf { color: #336; } /* id */
|
||||
.syntax .nd { color: #999; } /* :foo */
|
||||
.syntax .m { color: purple } /* number */
|
||||
.syntax .nb { color: purple } /* built-in */
|
||||
.syntax .cp { color: #bd3f00; } /* !important */
|
||||
|
||||
.syntax .flash { background-color: #adf !important; }
|
||||
.syntax .flashbad { background-color: #f55 !important; }
|
||||
|
||||
|
1264
src/static/css/pad.css
Normal file
106
src/static/css/timeslider.css
Normal file
|
@ -0,0 +1,106 @@
|
|||
#editorcontainerbox {overflow:auto; top:40px;}
|
||||
|
||||
#padcontent {font-size:12px; padding:10px;}
|
||||
|
||||
#timeslider-wrapper {left:0; position:relative; right:0; top:0;}
|
||||
#timeslider-left {background-image:url(../../static/img/timeslider_left.png); height:63px; left:0; position:absolute; width:134px;}
|
||||
#timeslider-right {background-image:url(../../static/img/timeslider_right.png); height:63px; position:absolute; right:0; top:0; width:155px;}
|
||||
#timeslider {background-image:url(../../static/img/timeslider_background.png); height:63px; margin:0 9px;}
|
||||
#timeslider #timeslider-slider {height:61px; left:0; position:absolute; top:1px; width:100%;}
|
||||
#ui-slider-handle {
|
||||
-khtml-user-select:none;
|
||||
-moz-user-select:none;
|
||||
-ms-user-select:none;
|
||||
-webkit-user-select:none;
|
||||
background-image:url(../../static/img/crushed_current_location.png);
|
||||
cursor:pointer;
|
||||
height:61px;
|
||||
left:0;
|
||||
position:absolute;
|
||||
top:0;
|
||||
user-select:none;
|
||||
width:13px;
|
||||
}
|
||||
#ui-slider-bar {
|
||||
-khtml-user-select:none;
|
||||
-moz-user-select:none;
|
||||
-ms-user-select:none;
|
||||
-webkit-user-select:none;
|
||||
cursor:pointer;
|
||||
height:35px;
|
||||
margin-left:5px;
|
||||
margin-right:148px;
|
||||
position:relative;
|
||||
top:20px;
|
||||
user-select:none;
|
||||
}
|
||||
|
||||
#playpause_button, #playpause_button_icon {height:47px; position:absolute; width:47px;}
|
||||
#playpause_button {background-image:url(../../static/img/crushed_button_undepressed.png); right:77px; top:9px;}
|
||||
#playpause_button_icon {background-image:url(../../static/img/play.png); left:0; top:0;}
|
||||
.pause#playpause_button_icon {background-image:url(../../static/img/pause.png);}
|
||||
|
||||
#leftstar, #rightstar, #leftstep, #rightstep
|
||||
{background:url(../../static/img/stepper_buttons.png) 0 0 no-repeat; height:21px; overflow:hidden; position:absolute;}
|
||||
#leftstar {background-position:0 44px; right:34px; top:8px; width:30px;}
|
||||
#rightstar {background-position:29px 44px; right:5px; top:8px; width:29px;}
|
||||
#leftstep {background-position:0 22px; right:34px; top:20px; width:30px;}
|
||||
#rightstep {background-position:29px 22px; right:5px; top:20px; width:29px;}
|
||||
|
||||
#timeslider .star {
|
||||
background-image:url(../../static/img/star.png);
|
||||
cursor:pointer;
|
||||
height:16px;
|
||||
position:absolute;
|
||||
top:40px;
|
||||
width:15px;
|
||||
}
|
||||
|
||||
#timeslider #timer {
|
||||
color:#fff;
|
||||
font-family:Arial, sans-serif;
|
||||
font-size:11px;
|
||||
left:7px;
|
||||
position:absolute;
|
||||
text-align:center;
|
||||
top:9px;
|
||||
width:122px;
|
||||
}
|
||||
|
||||
.topbarcenter, #docbar {display:none;}
|
||||
#padmain {top:30px;}
|
||||
#editbarright {float:right;}
|
||||
#returnbutton {color:#222; font-size:16px; line-height:29px; margin-top:0; padding-right:6px;}
|
||||
#importexport {top:118px;}
|
||||
#importexport .popup {width:185px;}
|
||||
|
||||
/* lists */
|
||||
.list-bullet2, .list-indent2, .list-number2 {margin-left:3em;}
|
||||
.list-bullet3, .list-indent3, .list-number3 {margin-left:4.5em;}
|
||||
.list-bullet4, .list-indent4, .list-number4 {margin-left:6em;}
|
||||
.list-bullet5, .list-indent5, .list-number5 {margin-left:7.5em;}
|
||||
.list-bullet6, .list-indent6, .list-number6 {margin-left:9em;}
|
||||
.list-bullet7, .list-indent7, .list-number7 {margin-left:10.5em;}
|
||||
.list-bullet8, .list-indent8, .list-number8 {margin-left:12em;}
|
||||
|
||||
/* unordered lists */
|
||||
UL {list-style-type:disc; margin-left:1.5em;}
|
||||
UL UL {margin-left:0 !important;}
|
||||
|
||||
.list-bullet2, .list-bullet5, .list-bullet8 {list-style-type:circle;}
|
||||
.list-bullet3, .list-bullet6 {list-style-type:square;}
|
||||
|
||||
.list-indent1, .list-indent2, .list-indent3, .list-indent5, .list-indent5, .list-indent6, .list-indent7, .list-indent8 {list-style-type:none;}
|
||||
|
||||
/* ordered lists */
|
||||
OL {list-style-type:decimal; margin-left:1.5em;}
|
||||
.list-number2, .list-number5, .list-number8 {list-style-type:lower-latin;}
|
||||
.list-number3, .list-number6 {list-style-type:lower-roman;}
|
||||
|
||||
|
||||
|
||||
/* IE 6/7 fixes ################################################################ */
|
||||
* HTML #ui-slider-handle {background-image:url(../../static/img/current_location.gif);}
|
||||
* HTML #timeslider .star {background-image:url(../../static/img/star.gif);}
|
||||
* HTML #playpause_button_icon {background-image:url(../../static/img/play.gif);}
|
||||
* HTML .pause#playpause_button_icon {background-image:url(../../static/img/pause.gif);}
|
8
src/static/custom/css.template
Normal file
|
@ -0,0 +1,8 @@
|
|||
/*
|
||||
custom css files are loaded after core css files. Simply use the same selector to override a style.
|
||||
Example:
|
||||
#editbar LI {border:1px solid #000;}
|
||||
overrides
|
||||
#editbar LI {border:1px solid #d5d5d5;}
|
||||
from pad.css
|
||||
*/
|
6
src/static/custom/js.template
Normal file
|
@ -0,0 +1,6 @@
|
|||
function customStart()
|
||||
{
|
||||
//define your javascript here
|
||||
//jquery is available - except index.js
|
||||
//you can load extra scripts with $.getScript http://api.jquery.com/jQuery.getScript/
|
||||
}
|
BIN
src/static/favicon.ico
Normal file
After Width: | Height: | Size: 1.1 KiB |
BIN
src/static/img/backgrad.gif
Normal file
After Width: | Height: | Size: 697 B |
BIN
src/static/img/connectingbar.gif
Normal file
After Width: | Height: | Size: 11 KiB |
BIN
src/static/img/crushed_button_depressed.png
Normal file
After Width: | Height: | Size: 4 KiB |
BIN
src/static/img/crushed_button_undepressed.png
Normal file
After Width: | Height: | Size: 4.1 KiB |
BIN
src/static/img/crushed_current_location.png
Normal file
After Width: | Height: | Size: 1,009 B |
BIN
src/static/img/etherpad_lite_icons.png
Normal file
After Width: | Height: | Size: 5.4 KiB |
BIN
src/static/img/fileicons.gif
Normal file
After Width: | Height: | Size: 1.6 KiB |
BIN
src/static/img/leftarrow.png
Normal file
After Width: | Height: | Size: 494 B |
BIN
src/static/img/loading.gif
Normal file
After Width: | Height: | Size: 658 B |
BIN
src/static/img/pause.png
Normal file
After Width: | Height: | Size: 2.8 KiB |
BIN
src/static/img/play.png
Normal file
After Width: | Height: | Size: 2.9 KiB |
BIN
src/static/img/roundcorner_left.gif
Normal file
After Width: | Height: | Size: 123 B |
BIN
src/static/img/roundcorner_right.gif
Normal file
After Width: | Height: | Size: 131 B |
BIN
src/static/img/stepper_buttons.png
Normal file
After Width: | Height: | Size: 4.7 KiB |
BIN
src/static/img/timeslider_background.png
Normal file
After Width: | Height: | Size: 182 B |
BIN
src/static/img/timeslider_left.png
Normal file
After Width: | Height: | Size: 686 B |
BIN
src/static/img/timeslider_right.png
Normal file
After Width: | Height: | Size: 517 B |
155
src/static/index.html
Normal file
|
@ -0,0 +1,155 @@
|
|||
<!doctype html>
|
||||
<html>
|
||||
|
||||
<title>Etherpad Lite</title>
|
||||
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
|
||||
|
||||
<style>
|
||||
*{ margin:0;padding:0; }
|
||||
body {
|
||||
background: rgba(0,0,0,.05);
|
||||
color: #333;
|
||||
font: 14px helvetica,sans-serif;
|
||||
background: #ccc;
|
||||
background: -webkit-radial-gradient(circle,#aaa,#eee 60%) center fixed;
|
||||
background: -moz-radial-gradient(circle,#aaa,#eee 60%) center fixed;
|
||||
background: -ms-radial-gradient(circle,#aaa,#eee 60%) center fixed;
|
||||
background: -o-radial-gradient(circle,#aaa,#eee 60%) center fixed;
|
||||
overflow-x: hidden;
|
||||
border-top: 8px solid rgba(51,51,51,.8);
|
||||
}
|
||||
#container {
|
||||
text-shadow: 0 1px 1px #fff;
|
||||
border-top: 1px solid #999;
|
||||
margin-top: 160px;
|
||||
text-align: center;
|
||||
padding: 15px;
|
||||
background: #eee;
|
||||
background: -webkit-linear-gradient(#fff,#ccc);
|
||||
background: -moz-linear-gradient(#fff,#ccc);
|
||||
background: -ms-linear-gradient(#fff,#ccc);
|
||||
background: -o-linear-gradient(#fff,#ccc);
|
||||
opacity: .9;
|
||||
box-shadow: 0px 1px 8px rgba(0,0,0,0.3);
|
||||
}
|
||||
#button {
|
||||
margin: 0 auto;
|
||||
border-radius: 3px;
|
||||
text-align: center;
|
||||
font: 36px verdana,arial,sans-serif;
|
||||
color: white;
|
||||
text-shadow: 0 -1px 0 rgba(0,0,0,.8);
|
||||
height: 70px;
|
||||
line-height: 70px;
|
||||
width: 300px;
|
||||
background: #555;
|
||||
background: -webkit-linear-gradient(#5F5F5F,#565656 50%,#4C4C4C 51%,#373737);
|
||||
background: -moz-linear-gradient(#5F5F5F,#565656 50%,#4C4C4C 51%,#373737);
|
||||
background: -ms-linear-gradient(#5F5F5F,#565656 50%,#4C4C4C 51%,#373737);
|
||||
background: -o-linear-gradient(#5F5F5F,#565656 50%,#4C4C4C 51%,#373737);
|
||||
box-shadow: inset 0 1px 3px rgba(0,0,0,0.9);
|
||||
}
|
||||
#button:hover {
|
||||
cursor: pointer;
|
||||
background: #666;
|
||||
background: -webkit-linear-gradient(#707070,#666666 50%,#5B5B5B 51%,#474747);
|
||||
background: -moz-linear-gradient(#707070,#666666 50%,#5B5B5B 51%,#474747);
|
||||
background: -ms-linear-gradient(#707070,#666666 50%,#5B5B5B 51%,#474747);
|
||||
background: -o-linear-gradient(#707070,#666666 50%,#5B5B5B 51%,#474747);
|
||||
}
|
||||
#button:active {
|
||||
box-shadow: inset 0 1px 12px rgba(0,0,0,0.9);
|
||||
background: #444;
|
||||
}
|
||||
#label {
|
||||
text-align: left;
|
||||
margin: 0 auto;
|
||||
width: 300px;
|
||||
}
|
||||
input {
|
||||
vertical-align: middle;
|
||||
font-weight: bold;
|
||||
font-size: 15px;
|
||||
}
|
||||
input[type="text"] {
|
||||
width: 243px;
|
||||
padding: 10px 47px 10px 10px;
|
||||
background: #fff;
|
||||
border: 1px solid #bbb;
|
||||
outline: none;
|
||||
border-radius: 3px;
|
||||
text-shadow: 0 0 1px #fff;
|
||||
}
|
||||
input[type="submit"] {
|
||||
width: 45px;
|
||||
margin-left: -50px;
|
||||
padding: 8px;
|
||||
}
|
||||
input[type="submit"]::-moz-focus-inner { border: 0 }
|
||||
@-moz-document url-prefix() { input[type="submit"] { padding: 7px } }
|
||||
@media only screen and (min-device-width: 320px) and (max-device-width: 720px) {
|
||||
body {
|
||||
background: #bbb;
|
||||
background: -webkit-linear-gradient(#aaa,#eee 60%) center fixed;
|
||||
height: 100%;
|
||||
}
|
||||
#container {
|
||||
margin-top: 0;
|
||||
text-align: left;
|
||||
}
|
||||
#button, #label {
|
||||
text-align: center;
|
||||
width: 95%;
|
||||
}
|
||||
form {
|
||||
text-align: center;
|
||||
}
|
||||
input[type=text] {
|
||||
width: 75%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<link href="static/custom/index.css" rel="stylesheet">
|
||||
<script src="static/custom/index.js"></script>
|
||||
|
||||
<div id="container">
|
||||
<div id="button" onclick="go2Random()" class="translate">New Pad</div><br><div id="label" class="translate">or create/open a Pad with the name</div>
|
||||
<form action="#" onsubmit="go2Name();return false;">
|
||||
<input type="text" id="padname" autofocus x-webkit-speech>
|
||||
<input type="submit" value="OK">
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function go2Name()
|
||||
{
|
||||
var padname = document.getElementById("padname").value;
|
||||
padname.length > 0 ? window.location = "p/" + padname : alert("Please enter a name")
|
||||
}
|
||||
|
||||
function go2Random()
|
||||
{
|
||||
window.location = "p/" + randomPadName();
|
||||
}
|
||||
|
||||
function randomPadName()
|
||||
{
|
||||
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
||||
var string_length = 10;
|
||||
var randomstring = '';
|
||||
for (var i = 0; i < string_length; i++)
|
||||
{
|
||||
var rnum = Math.floor(Math.random() * chars.length);
|
||||
randomstring += chars.substring(rnum, rnum + 1);
|
||||
}
|
||||
return randomstring;
|
||||
}
|
||||
|
||||
// start the custom js
|
||||
if (typeof customStart == "function") customStart();
|
||||
</script>
|
||||
|
||||
</html>
|
90
src/static/js/AttributePoolFactory.js
Normal file
|
@ -0,0 +1,90 @@
|
|||
/**
|
||||
* This code represents the Attribute Pool Object of the original Etherpad.
|
||||
* 90% of the code is still like in the original Etherpad
|
||||
* Look at https://github.com/ether/pad/blob/master/infrastructure/ace/www/easysync2.js
|
||||
* You can find a explanation what a attribute pool is here:
|
||||
* https://github.com/Pita/etherpad-lite/blob/master/doc/easysync/easysync-notes.txt
|
||||
*/
|
||||
|
||||
/*
|
||||
* Copyright 2009 Google Inc., 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
exports.createAttributePool = function () {
|
||||
var p = {};
|
||||
p.numToAttrib = {}; // e.g. {0: ['foo','bar']}
|
||||
p.attribToNum = {}; // e.g. {'foo,bar': 0}
|
||||
p.nextNum = 0;
|
||||
|
||||
p.putAttrib = function (attrib, dontAddIfAbsent) {
|
||||
var str = String(attrib);
|
||||
if (str in p.attribToNum) {
|
||||
return p.attribToNum[str];
|
||||
}
|
||||
if (dontAddIfAbsent) {
|
||||
return -1;
|
||||
}
|
||||
var num = p.nextNum++;
|
||||
p.attribToNum[str] = num;
|
||||
p.numToAttrib[num] = [String(attrib[0] || ''), String(attrib[1] || '')];
|
||||
return num;
|
||||
};
|
||||
|
||||
p.getAttrib = function (num) {
|
||||
var pair = p.numToAttrib[num];
|
||||
if (!pair) {
|
||||
return pair;
|
||||
}
|
||||
return [pair[0], pair[1]]; // return a mutable copy
|
||||
};
|
||||
|
||||
p.getAttribKey = function (num) {
|
||||
var pair = p.numToAttrib[num];
|
||||
if (!pair) return '';
|
||||
return pair[0];
|
||||
};
|
||||
|
||||
p.getAttribValue = function (num) {
|
||||
var pair = p.numToAttrib[num];
|
||||
if (!pair) return '';
|
||||
return pair[1];
|
||||
};
|
||||
|
||||
p.eachAttrib = function (func) {
|
||||
for (var n in p.numToAttrib) {
|
||||
var pair = p.numToAttrib[n];
|
||||
func(pair[0], pair[1]);
|
||||
}
|
||||
};
|
||||
|
||||
p.toJsonable = function () {
|
||||
return {
|
||||
numToAttrib: p.numToAttrib,
|
||||
nextNum: p.nextNum
|
||||
};
|
||||
};
|
||||
|
||||
p.fromJsonable = function (obj) {
|
||||
p.numToAttrib = obj.numToAttrib;
|
||||
p.nextNum = obj.nextNum;
|
||||
p.attribToNum = {};
|
||||
for (var n in p.numToAttrib) {
|
||||
p.attribToNum[String(p.numToAttrib[n])] = Number(n);
|
||||
}
|
||||
return p;
|
||||
};
|
||||
|
||||
return p;
|
||||
}
|
1968
src/static/js/Changeset.js
Normal file
370
src/static/js/ace.js
Normal file
|
@ -0,0 +1,370 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
// requires: top
|
||||
// requires: plugins
|
||||
// requires: undefined
|
||||
|
||||
Ace2Editor.registry = {
|
||||
nextId: 1
|
||||
};
|
||||
|
||||
var plugins = require('/plugins').plugins;
|
||||
|
||||
function Ace2Editor()
|
||||
{
|
||||
var ace2 = Ace2Editor;
|
||||
|
||||
var editor = {};
|
||||
var info = {
|
||||
editor: editor,
|
||||
id: (ace2.registry.nextId++)
|
||||
};
|
||||
var loaded = false;
|
||||
|
||||
var actionsPendingInit = [];
|
||||
|
||||
function pendingInit(func, optDoNow)
|
||||
{
|
||||
return function()
|
||||
{
|
||||
var that = this;
|
||||
var args = arguments;
|
||||
|
||||
function action()
|
||||
{
|
||||
func.apply(that, args);
|
||||
}
|
||||
if (optDoNow)
|
||||
{
|
||||
optDoNow.apply(that, args);
|
||||
}
|
||||
if (loaded)
|
||||
{
|
||||
action();
|
||||
}
|
||||
else
|
||||
{
|
||||
actionsPendingInit.push(action);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function doActionsPendingInit()
|
||||
{
|
||||
for (var i = 0; i < actionsPendingInit.length; i++)
|
||||
{
|
||||
actionsPendingInit[i]();
|
||||
}
|
||||
actionsPendingInit = [];
|
||||
}
|
||||
|
||||
ace2.registry[info.id] = info;
|
||||
|
||||
editor.importText = pendingInit(function(newCode, undoable)
|
||||
{
|
||||
info.ace_importText(newCode, undoable);
|
||||
});
|
||||
editor.importAText = pendingInit(function(newCode, apoolJsonObj, undoable)
|
||||
{
|
||||
info.ace_importAText(newCode, apoolJsonObj, undoable);
|
||||
});
|
||||
editor.exportText = function()
|
||||
{
|
||||
if (!loaded) return "(awaiting init)\n";
|
||||
return info.ace_exportText();
|
||||
};
|
||||
editor.getFrame = function()
|
||||
{
|
||||
return info.frame || null;
|
||||
};
|
||||
editor.focus = pendingInit(function()
|
||||
{
|
||||
info.ace_focus();
|
||||
});
|
||||
editor.setEditable = pendingInit(function(newVal)
|
||||
{
|
||||
info.ace_setEditable(newVal);
|
||||
});
|
||||
editor.getFormattedCode = function()
|
||||
{
|
||||
return info.ace_getFormattedCode();
|
||||
};
|
||||
editor.setOnKeyPress = pendingInit(function(handler)
|
||||
{
|
||||
info.ace_setOnKeyPress(handler);
|
||||
});
|
||||
editor.setOnKeyDown = pendingInit(function(handler)
|
||||
{
|
||||
info.ace_setOnKeyDown(handler);
|
||||
});
|
||||
editor.setNotifyDirty = pendingInit(function(handler)
|
||||
{
|
||||
info.ace_setNotifyDirty(handler);
|
||||
});
|
||||
|
||||
editor.setProperty = pendingInit(function(key, value)
|
||||
{
|
||||
info.ace_setProperty(key, value);
|
||||
});
|
||||
editor.getDebugProperty = function(prop)
|
||||
{
|
||||
return info.ace_getDebugProperty(prop);
|
||||
};
|
||||
|
||||
editor.setBaseText = pendingInit(function(txt)
|
||||
{
|
||||
info.ace_setBaseText(txt);
|
||||
});
|
||||
editor.setBaseAttributedText = pendingInit(function(atxt, apoolJsonObj)
|
||||
{
|
||||
info.ace_setBaseAttributedText(atxt, apoolJsonObj);
|
||||
});
|
||||
editor.applyChangesToBase = pendingInit(function(changes, optAuthor, apoolJsonObj)
|
||||
{
|
||||
info.ace_applyChangesToBase(changes, optAuthor, apoolJsonObj);
|
||||
});
|
||||
// prepareUserChangeset:
|
||||
// Returns null if no new changes or ACE not ready. Otherwise, bundles up all user changes
|
||||
// to the latest base text into a Changeset, which is returned (as a string if encodeAsString).
|
||||
// If this method returns a truthy value, then applyPreparedChangesetToBase can be called
|
||||
// at some later point to consider these changes part of the base, after which prepareUserChangeset
|
||||
// must be called again before applyPreparedChangesetToBase. Multiple consecutive calls
|
||||
// to prepareUserChangeset will return an updated changeset that takes into account the
|
||||
// latest user changes, and modify the changeset to be applied by applyPreparedChangesetToBase
|
||||
// accordingly.
|
||||
editor.prepareUserChangeset = function()
|
||||
{
|
||||
if (!loaded) return null;
|
||||
return info.ace_prepareUserChangeset();
|
||||
};
|
||||
editor.applyPreparedChangesetToBase = pendingInit(
|
||||
|
||||
function()
|
||||
{
|
||||
info.ace_applyPreparedChangesetToBase();
|
||||
});
|
||||
editor.setUserChangeNotificationCallback = pendingInit(function(callback)
|
||||
{
|
||||
info.ace_setUserChangeNotificationCallback(callback);
|
||||
});
|
||||
editor.setAuthorInfo = pendingInit(function(author, authorInfo)
|
||||
{
|
||||
info.ace_setAuthorInfo(author, authorInfo);
|
||||
});
|
||||
editor.setAuthorSelectionRange = pendingInit(function(author, start, end)
|
||||
{
|
||||
info.ace_setAuthorSelectionRange(author, start, end);
|
||||
});
|
||||
|
||||
editor.getUnhandledErrors = function()
|
||||
{
|
||||
if (!loaded) return [];
|
||||
// returns array of {error: <browser Error object>, time: +new Date()}
|
||||
return info.ace_getUnhandledErrors();
|
||||
};
|
||||
|
||||
editor.callWithAce = pendingInit(function(fn, callStack, normalize)
|
||||
{
|
||||
return info.ace_callWithAce(fn, callStack, normalize);
|
||||
});
|
||||
|
||||
editor.execCommand = pendingInit(function(cmd, arg1)
|
||||
{
|
||||
info.ace_execCommand(cmd, arg1);
|
||||
});
|
||||
editor.replaceRange = pendingInit(function(start, end, text)
|
||||
{
|
||||
info.ace_replaceRange(start, end, text);
|
||||
});
|
||||
|
||||
function sortFilesByEmbeded(files) {
|
||||
var embededFiles = [];
|
||||
var remoteFiles = [];
|
||||
|
||||
if (Ace2Editor.EMBEDED) {
|
||||
for (var i = 0, ii = files.length; i < ii; i++) {
|
||||
var file = files[i];
|
||||
if (Object.prototype.hasOwnProperty.call(Ace2Editor.EMBEDED, file)) {
|
||||
embededFiles.push(file);
|
||||
} else {
|
||||
remoteFiles.push(file);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
remoteFiles = files;
|
||||
}
|
||||
|
||||
return {embeded: embededFiles, remote: remoteFiles};
|
||||
}
|
||||
function pushRequireScriptTo(buffer) {
|
||||
var KERNEL_SOURCE = '../static/js/require-kernel.js';
|
||||
var KERNEL_BOOT = 'require.setRootURI("../minified/");\nrequire.setGlobalKeyPath("require");'
|
||||
if (Ace2Editor.EMBEDED && Ace2Editor.EMBEDED[KERNEL_SOURCE]) {
|
||||
buffer.push('<script type="text/javascript">');
|
||||
buffer.push(Ace2Editor.EMBEDED[KERNEL_SOURCE]);
|
||||
buffer.push(KERNEL_BOOT);
|
||||
buffer.push('<\/script>');
|
||||
}
|
||||
}
|
||||
function pushScriptsTo(buffer) {
|
||||
/* Folling is for packaging regular expression. */
|
||||
/* $$INCLUDE_JS("../static/js/ace2_inner.js"); */
|
||||
var ACE_SOURCE = '../static/js/ace2_inner.js';
|
||||
if (Ace2Editor.EMBEDED && Ace2Editor.EMBEDED[ACE_SOURCE]) {
|
||||
buffer.push('<script type="text/javascript">');
|
||||
buffer.push(Ace2Editor.EMBEDED[ACE_SOURCE]);
|
||||
buffer.push('require("/ace2_inner");');
|
||||
buffer.push('<\/script>');
|
||||
} else {
|
||||
file = ACE_SOURCE;
|
||||
file = file.replace(/^\.\.\/static\/js\//, '../minified/');
|
||||
buffer.push('<script type="application/javascript" src="' + file + '"><\/script>');
|
||||
buffer.push('<script type="text/javascript">');
|
||||
buffer.push('require("/ace2_inner");');
|
||||
buffer.push('<\/script>');
|
||||
}
|
||||
}
|
||||
function pushStyleTagsFor(buffer, files) {
|
||||
var sorted = sortFilesByEmbeded(files);
|
||||
var embededFiles = sorted.embeded;
|
||||
var remoteFiles = sorted.remote;
|
||||
|
||||
if (embededFiles.length > 0) {
|
||||
buffer.push('<style type="text/css">');
|
||||
for (var i = 0, ii = embededFiles.length; i < ii; i++) {
|
||||
var file = embededFiles[i];
|
||||
buffer.push(Ace2Editor.EMBEDED[file].replace(/<\//g, '<\\/'));
|
||||
}
|
||||
buffer.push('<\/style>');
|
||||
}
|
||||
for (var i = 0, ii = remoteFiles.length; i < ii; i++) {
|
||||
var file = remoteFiles[i];
|
||||
buffer.push('<link rel="stylesheet" type="text/css" href="' + file + '"\/>');
|
||||
}
|
||||
}
|
||||
|
||||
editor.destroy = pendingInit(function()
|
||||
{
|
||||
info.ace_dispose();
|
||||
info.frame.parentNode.removeChild(info.frame);
|
||||
delete ace2.registry[info.id];
|
||||
info = null; // prevent IE 6 closure memory leaks
|
||||
});
|
||||
|
||||
editor.init = function(containerId, initialCode, doneFunc)
|
||||
{
|
||||
|
||||
editor.importText(initialCode);
|
||||
|
||||
info.onEditorReady = function()
|
||||
{
|
||||
loaded = true;
|
||||
doActionsPendingInit();
|
||||
doneFunc();
|
||||
};
|
||||
|
||||
(function()
|
||||
{
|
||||
var doctype = "<!doctype html>";
|
||||
|
||||
var iframeHTML = [];
|
||||
|
||||
iframeHTML.push(doctype);
|
||||
iframeHTML.push("<html><head>");
|
||||
|
||||
// For compatability's sake transform in and out.
|
||||
for (var i = 0, ii = iframeHTML.length; i < ii; i++) {
|
||||
iframeHTML[i] = JSON.stringify(iframeHTML[i]);
|
||||
}
|
||||
plugins.callHook("aceInitInnerdocbodyHead", {
|
||||
iframeHTML: iframeHTML
|
||||
});
|
||||
for (var i = 0, ii = iframeHTML.length; i < ii; i++) {
|
||||
iframeHTML[i] = JSON.parse(iframeHTML[i]);
|
||||
}
|
||||
|
||||
// calls to these functions ($$INCLUDE_...) are replaced when this file is processed
|
||||
// and compressed, putting the compressed code from the named file directly into the
|
||||
// source here.
|
||||
// these lines must conform to a specific format because they are passed by the build script:
|
||||
var includedCSS = [];
|
||||
var $$INCLUDE_CSS = function(filename) {includedCSS.push(filename)};
|
||||
$$INCLUDE_CSS("../static/css/iframe_editor.css");
|
||||
$$INCLUDE_CSS("../static/css/pad.css");
|
||||
$$INCLUDE_CSS("../static/custom/pad.css");
|
||||
pushStyleTagsFor(iframeHTML, includedCSS);
|
||||
|
||||
var includedJS = [];
|
||||
var $$INCLUDE_JS = function(filename) {includedJS.push(filename)};
|
||||
pushRequireScriptTo(iframeHTML);
|
||||
// Inject my plugins into my child.
|
||||
iframeHTML.push('\
|
||||
<script type="text/javascript">\
|
||||
require.define("/plugins", null);\n\
|
||||
require.define("/plugins.js", function (require, exports, module) {\
|
||||
module.exports = parent.parent.require("/plugins");\
|
||||
});\
|
||||
</script>\
|
||||
');
|
||||
pushScriptsTo(iframeHTML);
|
||||
|
||||
iframeHTML.push('<style type="text/css" title="dynamicsyntax"></style>');
|
||||
iframeHTML.push('</head><body id="innerdocbody" class="syntax" spellcheck="false"> </body></html>');
|
||||
|
||||
// Expose myself to global for my child frame.
|
||||
var thisFunctionsName = "ChildAccessibleAce2Editor";
|
||||
(function () {return this}())[thisFunctionsName] = Ace2Editor;
|
||||
|
||||
var outerScript = 'editorId = "' + info.id + '"; editorInfo = parent.' + thisFunctionsName + '.registry[editorId]; ' + 'window.onload = function() ' + '{ window.onload = null; setTimeout' + '(function() ' + '{ var iframe = document.createElement("IFRAME"); ' + 'iframe.scrolling = "no"; var outerdocbody = document.getElementById("outerdocbody"); ' + 'iframe.frameBorder = 0; iframe.allowTransparency = true; ' + // for IE
|
||||
'outerdocbody.insertBefore(iframe, outerdocbody.firstChild); ' + 'iframe.ace_outerWin = window; ' + 'readyFunc = function() { editorInfo.onEditorReady(); readyFunc = null; editorInfo = null; }; ' + 'var doc = iframe.contentWindow.document; doc.open(); var text = (' + JSON.stringify(iframeHTML.join('\n')) + ');doc.write(text); doc.close(); ' + '}, 0); }';
|
||||
|
||||
var outerHTML = [doctype, '<html><head>']
|
||||
|
||||
var includedCSS = [];
|
||||
var $$INCLUDE_CSS = function(filename) {includedCSS.push(filename)};
|
||||
$$INCLUDE_CSS("../static/css/iframe_editor.css");
|
||||
$$INCLUDE_CSS("../static/css/pad.css");
|
||||
$$INCLUDE_CSS("../static/custom/pad.css");
|
||||
pushStyleTagsFor(outerHTML, includedCSS);
|
||||
|
||||
// bizarrely, in FF2, a file with no "external" dependencies won't finish loading properly
|
||||
// (throbs busy while typing)
|
||||
outerHTML.push('<link rel="stylesheet" type="text/css" href="data:text/css,"/>', '\x3cscript>\n', outerScript.replace(/<\//g, '<\\/'), '\n\x3c/script>', '</head><body id="outerdocbody"><div id="sidediv"><!-- --></div><div id="linemetricsdiv">x</div><div id="overlaysdiv"><!-- --></div></body></html>');
|
||||
|
||||
var outerFrame = document.createElement("IFRAME");
|
||||
outerFrame.frameBorder = 0; // for IE
|
||||
info.frame = outerFrame;
|
||||
document.getElementById(containerId).appendChild(outerFrame);
|
||||
|
||||
var editorDocument = outerFrame.contentWindow.document;
|
||||
|
||||
editorDocument.open();
|
||||
editorDocument.write(outerHTML.join(''));
|
||||
editorDocument.close();
|
||||
})();
|
||||
};
|
||||
|
||||
return editor;
|
||||
}
|
||||
|
||||
exports.Ace2Editor = Ace2Editor;
|
157
src/static/js/ace2_common.js
Normal file
|
@ -0,0 +1,157 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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 Security = require('/security');
|
||||
|
||||
function isNodeText(node)
|
||||
{
|
||||
return (node.nodeType == 3);
|
||||
}
|
||||
|
||||
function object(o)
|
||||
{
|
||||
var f = function()
|
||||
{};
|
||||
f.prototype = o;
|
||||
return new f();
|
||||
}
|
||||
|
||||
function extend(obj, props)
|
||||
{
|
||||
for (var p in props)
|
||||
{
|
||||
obj[p] = props[p];
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
function forEach(array, func)
|
||||
{
|
||||
for (var i = 0; i < array.length; i++)
|
||||
{
|
||||
var result = func(array[i], i);
|
||||
if (result) break;
|
||||
}
|
||||
}
|
||||
|
||||
function map(array, func)
|
||||
{
|
||||
var result = [];
|
||||
// must remain compatible with "arguments" pseudo-array
|
||||
for (var i = 0; i < array.length; i++)
|
||||
{
|
||||
if (func) result.push(func(array[i], i));
|
||||
else result.push(array[i]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function filter(array, func)
|
||||
{
|
||||
var result = [];
|
||||
// must remain compatible with "arguments" pseudo-array
|
||||
for (var i = 0; i < array.length; i++)
|
||||
{
|
||||
if (func(array[i], i)) result.push(array[i]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function isArray(testObject)
|
||||
{
|
||||
return testObject && typeof testObject === 'object' && !(testObject.propertyIsEnumerable('length')) && typeof testObject.length === 'number';
|
||||
}
|
||||
|
||||
var userAgent = (((function () {return this;})().navigator || {}).userAgent || 'node-js').toLowerCase();
|
||||
|
||||
// Figure out what browser is being used (stolen from jquery 1.2.1)
|
||||
var browser = {
|
||||
version: (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1],
|
||||
safari: /webkit/.test(userAgent),
|
||||
opera: /opera/.test(userAgent),
|
||||
msie: /msie/.test(userAgent) && !/opera/.test(userAgent),
|
||||
mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent),
|
||||
windows: /windows/.test(userAgent),
|
||||
mobile: /mobile/.test(userAgent) || /android/.test(userAgent)
|
||||
};
|
||||
|
||||
|
||||
function getAssoc(obj, name)
|
||||
{
|
||||
return obj["_magicdom_" + name];
|
||||
}
|
||||
|
||||
function setAssoc(obj, name, value)
|
||||
{
|
||||
// note that in IE designMode, properties of a node can get
|
||||
// copied to new nodes that are spawned during editing; also,
|
||||
// properties representable in HTML text can survive copy-and-paste
|
||||
obj["_magicdom_" + name] = value;
|
||||
}
|
||||
|
||||
// "func" is a function over 0..(numItems-1) that is monotonically
|
||||
// "increasing" with index (false, then true). Finds the boundary
|
||||
// between false and true, a number between 0 and numItems inclusive.
|
||||
|
||||
|
||||
function binarySearch(numItems, func)
|
||||
{
|
||||
if (numItems < 1) return 0;
|
||||
if (func(0)) return 0;
|
||||
if (!func(numItems - 1)) return numItems;
|
||||
var low = 0; // func(low) is always false
|
||||
var high = numItems - 1; // func(high) is always true
|
||||
while ((high - low) > 1)
|
||||
{
|
||||
var x = Math.floor((low + high) / 2); // x != low, x != high
|
||||
if (func(x)) high = x;
|
||||
else low = x;
|
||||
}
|
||||
return high;
|
||||
}
|
||||
|
||||
function binarySearchInfinite(expectedLength, func)
|
||||
{
|
||||
var i = 0;
|
||||
while (!func(i)) i += expectedLength;
|
||||
return binarySearch(i, func);
|
||||
}
|
||||
|
||||
function htmlPrettyEscape(str)
|
||||
{
|
||||
return Security.escapeHTML(str).replace(/\r?\n/g, '\\n');
|
||||
}
|
||||
|
||||
exports.isNodeText = isNodeText;
|
||||
exports.object = object;
|
||||
exports.extend = extend;
|
||||
exports.forEach = forEach;
|
||||
exports.map = map;
|
||||
exports.filter = filter;
|
||||
exports.isArray = isArray;
|
||||
exports.browser = browser;
|
||||
exports.getAssoc = getAssoc;
|
||||
exports.setAssoc = setAssoc;
|
||||
exports.binarySearch = binarySearch;
|
||||
exports.binarySearchInfinite = binarySearchInfinite;
|
||||
exports.htmlPrettyEscape = htmlPrettyEscape;
|
||||
exports.map = map;
|
5899
src/static/js/ace2_inner.js
Normal file
774
src/static/js/broadcast.js
Normal file
|
@ -0,0 +1,774 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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 makeCSSManager = require('/cssmanager').makeCSSManager;
|
||||
var domline = require('/domline').domline;
|
||||
var AttribPool = require('/AttributePoolFactory').createAttributePool;
|
||||
var Changeset = require('/Changeset');
|
||||
var linestylefilter = require('/linestylefilter').linestylefilter;
|
||||
var colorutils = require('/colorutils').colorutils;
|
||||
|
||||
// These parameters were global, now they are injected. A reference to the
|
||||
// Timeslider controller would probably be more appropriate.
|
||||
function loadBroadcastJS(socket, sendSocketMsg, fireWhenAllScriptsAreLoaded, BroadcastSlider)
|
||||
{
|
||||
var changesetLoader = undefined;
|
||||
// just in case... (todo: this must be somewhere else in the client code.)
|
||||
// Below Array#map code was direct pasted by AppJet/Etherpad, licence unknown. Possible source: http://www.tutorialspoint.com/javascript/array_map.htm
|
||||
if (!Array.prototype.map)
|
||||
{
|
||||
Array.prototype.map = function(fun /*, thisp*/ )
|
||||
{
|
||||
var len = this.length >>> 0;
|
||||
if (typeof fun != "function") throw new TypeError();
|
||||
|
||||
var res = new Array(len);
|
||||
var thisp = arguments[1];
|
||||
for (var i = 0; i < len; i++)
|
||||
{
|
||||
if (i in this) res[i] = fun.call(thisp, this[i], i, this);
|
||||
}
|
||||
|
||||
return res;
|
||||
};
|
||||
}
|
||||
|
||||
// Below Array#forEach code was direct pasted by AppJet/Etherpad, licence unknown. Possible source: http://www.tutorialspoint.com/javascript/array_foreach.htm
|
||||
if (!Array.prototype.forEach)
|
||||
{
|
||||
Array.prototype.forEach = function(fun /*, thisp*/ )
|
||||
{
|
||||
var len = this.length >>> 0;
|
||||
if (typeof fun != "function") throw new TypeError();
|
||||
|
||||
var thisp = arguments[1];
|
||||
for (var i = 0; i < len; i++)
|
||||
{
|
||||
if (i in this) fun.call(thisp, this[i], i, this);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Below Array#indexOf code was direct pasted by AppJet/Etherpad, licence unknown. Possible source: http://www.tutorialspoint.com/javascript/array_indexof.htm
|
||||
if (!Array.prototype.indexOf)
|
||||
{
|
||||
Array.prototype.indexOf = function(elt /*, from*/ )
|
||||
{
|
||||
var len = this.length >>> 0;
|
||||
|
||||
var from = Number(arguments[1]) || 0;
|
||||
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
|
||||
if (from < 0) from += len;
|
||||
|
||||
for (; from < len; from++)
|
||||
{
|
||||
if (from in this && this[from] === elt) return from;
|
||||
}
|
||||
return -1;
|
||||
};
|
||||
}
|
||||
|
||||
function debugLog()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (window.console) console.log.apply(console, arguments);
|
||||
}
|
||||
catch (e)
|
||||
{
|
||||
if (window.console) console.log("error printing: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
function randomString()
|
||||
{
|
||||
return "_" + Math.floor(Math.random() * 1000000);
|
||||
}
|
||||
|
||||
// for IE
|
||||
if ($.browser.msie)
|
||||
{
|
||||
try
|
||||
{
|
||||
document.execCommand("BackgroundImageCache", false, true);
|
||||
}
|
||||
catch (e)
|
||||
{}
|
||||
}
|
||||
|
||||
var userId = "hiddenUser" + randomString();
|
||||
var socketId;
|
||||
//var socket;
|
||||
var channelState = "DISCONNECTED";
|
||||
|
||||
var appLevelDisconnectReason = null;
|
||||
|
||||
var padContents = {
|
||||
currentRevision: clientVars.revNum,
|
||||
currentTime: clientVars.currentTime,
|
||||
currentLines: Changeset.splitTextLines(clientVars.initialStyledContents.atext.text),
|
||||
currentDivs: null,
|
||||
// to be filled in once the dom loads
|
||||
apool: (new AttribPool()).fromJsonable(clientVars.initialStyledContents.apool),
|
||||
alines: Changeset.splitAttributionLines(
|
||||
clientVars.initialStyledContents.atext.attribs, clientVars.initialStyledContents.atext.text),
|
||||
|
||||
// generates a jquery element containing HTML for a line
|
||||
lineToElement: function(line, aline)
|
||||
{
|
||||
var element = document.createElement("div");
|
||||
var emptyLine = (line == '\n');
|
||||
var domInfo = domline.createDomLine(!emptyLine, true);
|
||||
linestylefilter.populateDomLine(line, aline, this.apool, domInfo);
|
||||
domInfo.prepareForAdd();
|
||||
element.className = domInfo.node.className;
|
||||
element.innerHTML = domInfo.node.innerHTML;
|
||||
element.id = Math.random();
|
||||
return $(element);
|
||||
},
|
||||
|
||||
applySpliceToDivs: function(start, numRemoved, newLines)
|
||||
{
|
||||
// remove spliced-out lines from DOM
|
||||
for (var i = start; i < start + numRemoved && i < this.currentDivs.length; i++)
|
||||
{
|
||||
debugLog("removing", this.currentDivs[i].attr('id'));
|
||||
this.currentDivs[i].remove();
|
||||
}
|
||||
|
||||
// remove spliced-out line divs from currentDivs array
|
||||
this.currentDivs.splice(start, numRemoved);
|
||||
|
||||
var newDivs = [];
|
||||
for (var i = 0; i < newLines.length; i++)
|
||||
{
|
||||
newDivs.push(this.lineToElement(newLines[i], this.alines[start + i]));
|
||||
}
|
||||
|
||||
// grab the div just before the first one
|
||||
var startDiv = this.currentDivs[start - 1] || null;
|
||||
|
||||
// insert the div elements into the correct place, in the correct order
|
||||
for (var i = 0; i < newDivs.length; i++)
|
||||
{
|
||||
if (startDiv)
|
||||
{
|
||||
startDiv.after(newDivs[i]);
|
||||
}
|
||||
else
|
||||
{
|
||||
$("#padcontent").prepend(newDivs[i]);
|
||||
}
|
||||
startDiv = newDivs[i];
|
||||
}
|
||||
|
||||
// insert new divs into currentDivs array
|
||||
newDivs.unshift(0); // remove 0 elements
|
||||
newDivs.unshift(start);
|
||||
this.currentDivs.splice.apply(this.currentDivs, newDivs);
|
||||
return this;
|
||||
},
|
||||
|
||||
// splice the lines
|
||||
splice: function(start, numRemoved, newLinesVA)
|
||||
{
|
||||
var newLines = Array.prototype.slice.call(arguments, 2).map(
|
||||
|
||||
function(s)
|
||||
{
|
||||
return s;
|
||||
});
|
||||
|
||||
// apply this splice to the divs
|
||||
this.applySpliceToDivs(start, numRemoved, newLines);
|
||||
|
||||
// call currentLines.splice, to keep the currentLines array up to date
|
||||
newLines.unshift(numRemoved);
|
||||
newLines.unshift(start);
|
||||
this.currentLines.splice.apply(this.currentLines, arguments);
|
||||
},
|
||||
// returns the contents of the specified line I
|
||||
get: function(i)
|
||||
{
|
||||
return this.currentLines[i];
|
||||
},
|
||||
// returns the number of lines in the document
|
||||
length: function()
|
||||
{
|
||||
return this.currentLines.length;
|
||||
},
|
||||
|
||||
getActiveAuthors: function()
|
||||
{
|
||||
var self = this;
|
||||
var authors = [];
|
||||
var seenNums = {};
|
||||
var alines = self.alines;
|
||||
for (var i = 0; i < alines.length; i++)
|
||||
{
|
||||
Changeset.eachAttribNumber(alines[i], function(n)
|
||||
{
|
||||
if (!seenNums[n])
|
||||
{
|
||||
seenNums[n] = true;
|
||||
if (self.apool.getAttribKey(n) == 'author')
|
||||
{
|
||||
var a = self.apool.getAttribValue(n);
|
||||
if (a)
|
||||
{
|
||||
authors.push(a);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
authors.sort();
|
||||
return authors;
|
||||
}
|
||||
};
|
||||
|
||||
function callCatchingErrors(catcher, func)
|
||||
{
|
||||
try
|
||||
{
|
||||
wrapRecordingErrors(catcher, func)();
|
||||
}
|
||||
catch (e)
|
||||
{ /*absorb*/
|
||||
}
|
||||
}
|
||||
|
||||
function wrapRecordingErrors(catcher, func)
|
||||
{
|
||||
return function()
|
||||
{
|
||||
try
|
||||
{
|
||||
return func.apply(this, Array.prototype.slice.call(arguments));
|
||||
}
|
||||
catch (e)
|
||||
{
|
||||
// caughtErrors.push(e);
|
||||
// caughtErrorCatchers.push(catcher);
|
||||
// caughtErrorTimes.push(+new Date());
|
||||
// console.dir({catcher: catcher, e: e});
|
||||
debugLog(e); // TODO(kroo): added temporary, to catch errors
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function loadedNewChangeset(changesetForward, changesetBackward, revision, timeDelta)
|
||||
{
|
||||
var broadcasting = (BroadcastSlider.getSliderPosition() == revisionInfo.latest);
|
||||
debugLog("broadcasting:", broadcasting, BroadcastSlider.getSliderPosition(), revisionInfo.latest, revision);
|
||||
revisionInfo.addChangeset(revision, revision + 1, changesetForward, changesetBackward, timeDelta);
|
||||
BroadcastSlider.setSliderLength(revisionInfo.latest);
|
||||
if (broadcasting) applyChangeset(changesetForward, revision + 1, false, timeDelta);
|
||||
}
|
||||
|
||||
/*
|
||||
At this point, we must be certain that the changeset really does map from
|
||||
the current revision to the specified revision. Any mistakes here will
|
||||
cause the whole slider to get out of sync.
|
||||
*/
|
||||
|
||||
function applyChangeset(changeset, revision, preventSliderMovement, timeDelta)
|
||||
{
|
||||
// disable the next 'gotorevision' call handled by a timeslider update
|
||||
if (!preventSliderMovement)
|
||||
{
|
||||
goToRevisionIfEnabledCount++;
|
||||
BroadcastSlider.setSliderPosition(revision);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// must mutate attribution lines before text lines
|
||||
Changeset.mutateAttributionLines(changeset, padContents.alines, padContents.apool);
|
||||
}
|
||||
catch (e)
|
||||
{
|
||||
debugLog(e);
|
||||
}
|
||||
|
||||
Changeset.mutateTextLines(changeset, padContents);
|
||||
padContents.currentRevision = revision;
|
||||
padContents.currentTime += timeDelta * 1000;
|
||||
debugLog('Time Delta: ', timeDelta)
|
||||
updateTimer();
|
||||
BroadcastSlider.setAuthors(padContents.getActiveAuthors().map(function(name)
|
||||
{
|
||||
return authorData[name];
|
||||
}));
|
||||
}
|
||||
|
||||
function updateTimer()
|
||||
{
|
||||
var zpad = function(str, length)
|
||||
{
|
||||
str = str + "";
|
||||
while (str.length < length)
|
||||
str = '0' + str;
|
||||
return str;
|
||||
}
|
||||
|
||||
|
||||
|
||||
var date = new Date(padContents.currentTime);
|
||||
var dateFormat = function()
|
||||
{
|
||||
var month = zpad(date.getMonth() + 1, 2);
|
||||
var day = zpad(date.getDate(), 2);
|
||||
var year = (date.getFullYear());
|
||||
var hours = zpad(date.getHours(), 2);
|
||||
var minutes = zpad(date.getMinutes(), 2);
|
||||
var seconds = zpad(date.getSeconds(), 2);
|
||||
return ([month, '/', day, '/', year, ' ', hours, ':', minutes, ':', seconds].join(""));
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
$('#timer').html(dateFormat());
|
||||
|
||||
var revisionDate = ["Saved", ["Jan", "Feb", "March", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"][date.getMonth()], date.getDate() + ",", date.getFullYear()].join(" ")
|
||||
$('#revision_date').html(revisionDate)
|
||||
|
||||
}
|
||||
|
||||
updateTimer();
|
||||
|
||||
function goToRevision(newRevision)
|
||||
{
|
||||
padContents.targetRevision = newRevision;
|
||||
var self = this;
|
||||
var path = revisionInfo.getPath(padContents.currentRevision, newRevision);
|
||||
debugLog('newRev: ', padContents.currentRevision, path);
|
||||
if (path.status == 'complete')
|
||||
{
|
||||
var cs = path.changesets;
|
||||
debugLog("status: complete, changesets: ", cs, "path:", path);
|
||||
var changeset = cs[0];
|
||||
var timeDelta = path.times[0];
|
||||
for (var i = 1; i < cs.length; i++)
|
||||
{
|
||||
changeset = Changeset.compose(changeset, cs[i], padContents.apool);
|
||||
timeDelta += path.times[i];
|
||||
}
|
||||
if (changeset) applyChangeset(changeset, path.rev, true, timeDelta);
|
||||
}
|
||||
else if (path.status == "partial")
|
||||
{
|
||||
debugLog('partial');
|
||||
var sliderLocation = padContents.currentRevision;
|
||||
// callback is called after changeset information is pulled from server
|
||||
// this may never get called, if the changeset has already been loaded
|
||||
var update = function(start, end)
|
||||
{
|
||||
// if we've called goToRevision in the time since, don't goToRevision
|
||||
goToRevision(padContents.targetRevision);
|
||||
};
|
||||
|
||||
// do our best with what we have...
|
||||
var cs = path.changesets;
|
||||
|
||||
var changeset = cs[0];
|
||||
var timeDelta = path.times[0];
|
||||
for (var i = 1; i < cs.length; i++)
|
||||
{
|
||||
changeset = Changeset.compose(changeset, cs[i], padContents.apool);
|
||||
timeDelta += path.times[i];
|
||||
}
|
||||
if (changeset) applyChangeset(changeset, path.rev, true, timeDelta);
|
||||
|
||||
|
||||
if (BroadcastSlider.getSliderLength() > 10000)
|
||||
{
|
||||
var start = (Math.floor((newRevision) / 10000) * 10000); // revision 0 to 10
|
||||
changesetLoader.queueUp(start, 100);
|
||||
}
|
||||
|
||||
if (BroadcastSlider.getSliderLength() > 1000)
|
||||
{
|
||||
var start = (Math.floor((newRevision) / 1000) * 1000); // (start from -1, go to 19) + 1
|
||||
changesetLoader.queueUp(start, 10);
|
||||
}
|
||||
|
||||
start = (Math.floor((newRevision) / 100) * 100);
|
||||
|
||||
changesetLoader.queueUp(start, 1, update);
|
||||
}
|
||||
BroadcastSlider.setAuthors(padContents.getActiveAuthors().map(function(name)
|
||||
{
|
||||
return authorData[name];
|
||||
}));
|
||||
}
|
||||
|
||||
changesetLoader = {
|
||||
running: false,
|
||||
resolved: [],
|
||||
requestQueue1: [],
|
||||
requestQueue2: [],
|
||||
requestQueue3: [],
|
||||
reqCallbacks: [],
|
||||
queueUp: function(revision, width, callback)
|
||||
{
|
||||
if (revision < 0) revision = 0;
|
||||
// if(changesetLoader.requestQueue.indexOf(revision) != -1)
|
||||
// return; // already in the queue.
|
||||
if (changesetLoader.resolved.indexOf(revision + "_" + width) != -1) return; // already loaded from the server
|
||||
changesetLoader.resolved.push(revision + "_" + width);
|
||||
|
||||
var requestQueue = width == 1 ? changesetLoader.requestQueue3 : width == 10 ? changesetLoader.requestQueue2 : changesetLoader.requestQueue1;
|
||||
requestQueue.push(
|
||||
{
|
||||
'rev': revision,
|
||||
'res': width,
|
||||
'callback': callback
|
||||
});
|
||||
if (!changesetLoader.running)
|
||||
{
|
||||
changesetLoader.running = true;
|
||||
setTimeout(changesetLoader.loadFromQueue, 10);
|
||||
}
|
||||
},
|
||||
loadFromQueue: function()
|
||||
{
|
||||
var self = changesetLoader;
|
||||
var requestQueue = self.requestQueue1.length > 0 ? self.requestQueue1 : self.requestQueue2.length > 0 ? self.requestQueue2 : self.requestQueue3.length > 0 ? self.requestQueue3 : null;
|
||||
|
||||
if (!requestQueue)
|
||||
{
|
||||
self.running = false;
|
||||
return;
|
||||
}
|
||||
|
||||
var request = requestQueue.pop();
|
||||
var granularity = request.res;
|
||||
var callback = request.callback;
|
||||
var start = request.rev;
|
||||
var requestID = Math.floor(Math.random() * 100000);
|
||||
|
||||
/*var msg = { "component" : "timeslider",
|
||||
"type":"CHANGESET_REQ",
|
||||
"padId": padId,
|
||||
"token": token,
|
||||
"protocolVersion": 2,
|
||||
"data"
|
||||
{
|
||||
"start": start,
|
||||
"granularity": granularity
|
||||
}};
|
||||
|
||||
socket.send(msg);*/
|
||||
|
||||
sendSocketMsg("CHANGESET_REQ", {
|
||||
"start": start,
|
||||
"granularity": granularity,
|
||||
"requestID": requestID
|
||||
});
|
||||
|
||||
self.reqCallbacks[requestID] = callback;
|
||||
|
||||
/*debugLog("loadinging revision", start, "through ajax");
|
||||
$.getJSON("/ep/pad/changes/" + clientVars.padIdForUrl + "?s=" + start + "&g=" + granularity, function (data, textStatus)
|
||||
{
|
||||
if (textStatus !== "success")
|
||||
{
|
||||
console.log(textStatus);
|
||||
BroadcastSlider.showReconnectUI();
|
||||
}
|
||||
self.handleResponse(data, start, granularity, callback);
|
||||
|
||||
setTimeout(self.loadFromQueue, 10); // load the next ajax function
|
||||
});*/
|
||||
},
|
||||
handleSocketResponse: function(message)
|
||||
{
|
||||
var self = changesetLoader;
|
||||
|
||||
var start = message.data.start;
|
||||
var granularity = message.data.granularity;
|
||||
var callback = self.reqCallbacks[message.data.requestID];
|
||||
delete self.reqCallbacks[message.data.requestID];
|
||||
|
||||
self.handleResponse(message.data, start, granularity, callback);
|
||||
setTimeout(self.loadFromQueue, 10);
|
||||
},
|
||||
handleResponse: function(data, start, granularity, callback)
|
||||
{
|
||||
debugLog("response: ", data);
|
||||
var pool = (new AttribPool()).fromJsonable(data.apool);
|
||||
for (var i = 0; i < data.forwardsChangesets.length; i++)
|
||||
{
|
||||
var astart = start + i * granularity - 1; // rev -1 is a blank single line
|
||||
var aend = start + (i + 1) * granularity - 1; // totalRevs is the most recent revision
|
||||
if (aend > data.actualEndNum - 1) aend = data.actualEndNum - 1;
|
||||
debugLog("adding changeset:", astart, aend);
|
||||
var forwardcs = Changeset.moveOpsToNewPool(data.forwardsChangesets[i], pool, padContents.apool);
|
||||
var backwardcs = Changeset.moveOpsToNewPool(data.backwardsChangesets[i], pool, padContents.apool);
|
||||
revisionInfo.addChangeset(astart, aend, forwardcs, backwardcs, data.timeDeltas[i]);
|
||||
}
|
||||
if (callback) callback(start - 1, start + data.forwardsChangesets.length * granularity - 1);
|
||||
}
|
||||
};
|
||||
|
||||
function handleMessageFromServer()
|
||||
{
|
||||
debugLog("handleMessage:", arguments);
|
||||
var obj = arguments[0]['data'];
|
||||
var expectedType = "COLLABROOM";
|
||||
|
||||
obj = JSON.parse(obj);
|
||||
if (obj['type'] == expectedType)
|
||||
{
|
||||
obj = obj['data'];
|
||||
|
||||
if (obj['type'] == "NEW_CHANGES")
|
||||
{
|
||||
debugLog(obj);
|
||||
var changeset = Changeset.moveOpsToNewPool(
|
||||
obj.changeset, (new AttribPool()).fromJsonable(obj.apool), padContents.apool);
|
||||
|
||||
var changesetBack = Changeset.moveOpsToNewPool(
|
||||
obj.changesetBack, (new AttribPool()).fromJsonable(obj.apool), padContents.apool);
|
||||
|
||||
loadedNewChangeset(changeset, changesetBack, obj.newRev - 1, obj.timeDelta);
|
||||
}
|
||||
else if (obj['type'] == "NEW_AUTHORDATA")
|
||||
{
|
||||
var authorMap = {};
|
||||
authorMap[obj.author] = obj.data;
|
||||
receiveAuthorData(authorMap);
|
||||
BroadcastSlider.setAuthors(padContents.getActiveAuthors().map(function(name)
|
||||
{
|
||||
return authorData[name];
|
||||
}));
|
||||
}
|
||||
else if (obj['type'] == "NEW_SAVEDREV")
|
||||
{
|
||||
var savedRev = obj.savedRev;
|
||||
BroadcastSlider.addSavedRevision(savedRev.revNum, savedRev);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
debugLog("incorrect message type: " + obj['type'] + ", expected " + expectedType);
|
||||
}
|
||||
}
|
||||
|
||||
function handleSocketClosed(params)
|
||||
{
|
||||
debugLog("socket closed!", params);
|
||||
socket = null;
|
||||
|
||||
BroadcastSlider.showReconnectUI();
|
||||
// var reason = appLevelDisconnectReason || params.reason;
|
||||
// var shouldReconnect = params.reconnect;
|
||||
// if (shouldReconnect) {
|
||||
// // determine if this is a tight reconnect loop due to weird connectivity problems
|
||||
// // reconnectTimes.push(+new Date());
|
||||
// var TOO_MANY_RECONNECTS = 8;
|
||||
// var TOO_SHORT_A_TIME_MS = 10000;
|
||||
// if (reconnectTimes.length >= TOO_MANY_RECONNECTS &&
|
||||
// ((+new Date()) - reconnectTimes[reconnectTimes.length-TOO_MANY_RECONNECTS]) <
|
||||
// TOO_SHORT_A_TIME_MS) {
|
||||
// setChannelState("DISCONNECTED", "looping");
|
||||
// }
|
||||
// else {
|
||||
// setChannelState("RECONNECTING", reason);
|
||||
// setUpSocket();
|
||||
// }
|
||||
// }
|
||||
// else {
|
||||
// BroadcastSlider.showReconnectUI();
|
||||
// setChannelState("DISCONNECTED", reason);
|
||||
// }
|
||||
}
|
||||
|
||||
function sendMessage(msg)
|
||||
{
|
||||
socket.postMessage(JSON.stringify(
|
||||
{
|
||||
type: "COLLABROOM",
|
||||
data: msg
|
||||
}));
|
||||
}
|
||||
|
||||
/*function setUpSocket()
|
||||
{
|
||||
// required for Comet
|
||||
if ((!$.browser.msie) && (!($.browser.mozilla && $.browser.version.indexOf("1.8.") == 0)))
|
||||
{
|
||||
document.domain = document.domain; // for comet
|
||||
}
|
||||
|
||||
var success = false;
|
||||
callCatchingErrors("setUpSocket", function ()
|
||||
{
|
||||
appLevelDisconnectReason = null;
|
||||
|
||||
socketId = String(Math.floor(Math.random() * 1e12));
|
||||
socket = new WebSocket(socketId);
|
||||
socket.onmessage = wrapRecordingErrors("socket.onmessage", handleMessageFromServer);
|
||||
socket.onclosed = wrapRecordingErrors("socket.onclosed", handleSocketClosed);
|
||||
socket.onopen = wrapRecordingErrors("socket.onopen", function ()
|
||||
{
|
||||
setChannelState("CONNECTED");
|
||||
var msg = {
|
||||
type: "CLIENT_READY",
|
||||
roomType: 'padview',
|
||||
roomName: 'padview/' + clientVars.viewId,
|
||||
data: {
|
||||
lastRev: clientVars.revNum,
|
||||
userInfo: {
|
||||
userId: userId
|
||||
}
|
||||
}
|
||||
};
|
||||
sendMessage(msg);
|
||||
});
|
||||
// socket.onhiccup = wrapRecordingErrors("socket.onhiccup", handleCometHiccup);
|
||||
// socket.onlogmessage = function(x) {debugLog(x); };
|
||||
socket.connect();
|
||||
success = true;
|
||||
});
|
||||
if (success)
|
||||
{
|
||||
//initialStartConnectTime = +new Date();
|
||||
}
|
||||
else
|
||||
{
|
||||
abandonConnection("initsocketfail");
|
||||
}
|
||||
}*/
|
||||
|
||||
function setChannelState(newChannelState, moreInfo)
|
||||
{
|
||||
if (newChannelState != channelState)
|
||||
{
|
||||
channelState = newChannelState;
|
||||
// callbacks.onChannelStateChange(channelState, moreInfo);
|
||||
}
|
||||
}
|
||||
|
||||
function abandonConnection(reason)
|
||||
{
|
||||
if (socket)
|
||||
{
|
||||
socket.onclosed = function()
|
||||
{};
|
||||
socket.onhiccup = function()
|
||||
{};
|
||||
socket.disconnect();
|
||||
}
|
||||
socket = null;
|
||||
setChannelState("DISCONNECTED", reason);
|
||||
}
|
||||
|
||||
/*window['onloadFuncts'] = [];
|
||||
window.onload = function ()
|
||||
{
|
||||
window['isloaded'] = true;
|
||||
window['onloadFuncts'].forEach(function (funct)
|
||||
{
|
||||
funct();
|
||||
});
|
||||
};*/
|
||||
|
||||
// to start upon window load, just push a function onto this array
|
||||
//window['onloadFuncts'].push(setUpSocket);
|
||||
//window['onloadFuncts'].push(function ()
|
||||
fireWhenAllScriptsAreLoaded.push(function()
|
||||
{
|
||||
// set up the currentDivs and DOM
|
||||
padContents.currentDivs = [];
|
||||
$("#padcontent").html("");
|
||||
for (var i = 0; i < padContents.currentLines.length; i++)
|
||||
{
|
||||
var div = padContents.lineToElement(padContents.currentLines[i], padContents.alines[i]);
|
||||
padContents.currentDivs.push(div);
|
||||
$("#padcontent").append(div);
|
||||
}
|
||||
debugLog(padContents.currentDivs);
|
||||
});
|
||||
|
||||
// this is necessary to keep infinite loops of events firing,
|
||||
// since goToRevision changes the slider position
|
||||
var goToRevisionIfEnabledCount = 0;
|
||||
var goToRevisionIfEnabled = function()
|
||||
{
|
||||
if (goToRevisionIfEnabledCount > 0)
|
||||
{
|
||||
goToRevisionIfEnabledCount--;
|
||||
}
|
||||
else
|
||||
{
|
||||
goToRevision.apply(goToRevision, arguments);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
BroadcastSlider.onSlider(goToRevisionIfEnabled);
|
||||
|
||||
(function()
|
||||
{
|
||||
for (var i = 0; i < clientVars.initialChangesets.length; i++)
|
||||
{
|
||||
var csgroup = clientVars.initialChangesets[i];
|
||||
var start = clientVars.initialChangesets[i].start;
|
||||
var granularity = clientVars.initialChangesets[i].granularity;
|
||||
debugLog("loading changest on startup: ", start, granularity, csgroup);
|
||||
changesetLoader.handleResponse(csgroup, start, granularity, null);
|
||||
}
|
||||
})();
|
||||
|
||||
var dynamicCSS = makeCSSManager('dynamicsyntax');
|
||||
var authorData = {};
|
||||
|
||||
function receiveAuthorData(newAuthorData)
|
||||
{
|
||||
for (var author in newAuthorData)
|
||||
{
|
||||
var data = newAuthorData[author];
|
||||
var bgcolor = typeof data.colorId == "number" ? clientVars.colorPalette[data.colorId] : data.colorId;
|
||||
if (bgcolor && dynamicCSS)
|
||||
{
|
||||
var selector = dynamicCSS.selectorStyle('.' + linestylefilter.getAuthorClassName(author));
|
||||
selector.backgroundColor = bgcolor
|
||||
selector.color = (colorutils.luminosity(colorutils.css2triple(bgcolor)) < 0.5) ? '#ffffff' : '#000000'; //see ace2_inner.js for the other part
|
||||
}
|
||||
authorData[author] = data;
|
||||
}
|
||||
}
|
||||
|
||||
receiveAuthorData(clientVars.historicalAuthorData);
|
||||
|
||||
return changesetLoader;
|
||||
}
|
||||
|
||||
exports.loadBroadcastJS = loadBroadcastJS;
|
128
src/static/js/broadcast_revisions.js
Normal file
|
@ -0,0 +1,128 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
// revision info is a skip list whos entries represent a particular revision
|
||||
// of the document. These revisions are connected together by various
|
||||
// changesets, or deltas, between any two revisions.
|
||||
|
||||
function loadBroadcastRevisionsJS()
|
||||
{
|
||||
function Revision(revNum)
|
||||
{
|
||||
this.rev = revNum;
|
||||
this.changesets = [];
|
||||
}
|
||||
|
||||
Revision.prototype.addChangeset = function(destIndex, changeset, timeDelta)
|
||||
{
|
||||
var changesetWrapper = {
|
||||
deltaRev: destIndex - this.rev,
|
||||
deltaTime: timeDelta,
|
||||
getValue: function()
|
||||
{
|
||||
return changeset;
|
||||
}
|
||||
};
|
||||
this.changesets.push(changesetWrapper);
|
||||
this.changesets.sort(function(a, b)
|
||||
{
|
||||
return (b.deltaRev - a.deltaRev)
|
||||
});
|
||||
}
|
||||
|
||||
revisionInfo = {};
|
||||
revisionInfo.addChangeset = function(fromIndex, toIndex, changeset, backChangeset, timeDelta)
|
||||
{
|
||||
var startRevision = revisionInfo[fromIndex] || revisionInfo.createNew(fromIndex);
|
||||
var endRevision = revisionInfo[toIndex] || revisionInfo.createNew(toIndex);
|
||||
startRevision.addChangeset(toIndex, changeset, timeDelta);
|
||||
endRevision.addChangeset(fromIndex, backChangeset, -1 * timeDelta);
|
||||
}
|
||||
|
||||
revisionInfo.latest = clientVars.totalRevs || -1;
|
||||
|
||||
revisionInfo.createNew = function(index)
|
||||
{
|
||||
revisionInfo[index] = new Revision(index);
|
||||
if (index > revisionInfo.latest)
|
||||
{
|
||||
revisionInfo.latest = index;
|
||||
}
|
||||
|
||||
return revisionInfo[index];
|
||||
}
|
||||
|
||||
// assuming that there is a path from fromIndex to toIndex, and that the links
|
||||
// are laid out in a skip-list format
|
||||
revisionInfo.getPath = function(fromIndex, toIndex)
|
||||
{
|
||||
var changesets = [];
|
||||
var spans = [];
|
||||
var times = [];
|
||||
var elem = revisionInfo[fromIndex] || revisionInfo.createNew(fromIndex);
|
||||
if (elem.changesets.length != 0 && fromIndex != toIndex)
|
||||
{
|
||||
var reverse = !(fromIndex < toIndex)
|
||||
while (((elem.rev < toIndex) && !reverse) || ((elem.rev > toIndex) && reverse))
|
||||
{
|
||||
var couldNotContinue = false;
|
||||
var oldRev = elem.rev;
|
||||
|
||||
for (var i = reverse ? elem.changesets.length - 1 : 0;
|
||||
reverse ? i >= 0 : i < elem.changesets.length;
|
||||
i += reverse ? -1 : 1)
|
||||
{
|
||||
if (((elem.changesets[i].deltaRev < 0) && !reverse) || ((elem.changesets[i].deltaRev > 0) && reverse))
|
||||
{
|
||||
couldNotContinue = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (((elem.rev + elem.changesets[i].deltaRev <= toIndex) && !reverse) || ((elem.rev + elem.changesets[i].deltaRev >= toIndex) && reverse))
|
||||
{
|
||||
var topush = elem.changesets[i];
|
||||
changesets.push(topush.getValue());
|
||||
spans.push(elem.changesets[i].deltaRev);
|
||||
times.push(topush.deltaTime);
|
||||
elem = revisionInfo[elem.rev + elem.changesets[i].deltaRev];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (couldNotContinue || oldRev == elem.rev) break;
|
||||
}
|
||||
}
|
||||
|
||||
var status = 'partial';
|
||||
if (elem.rev == toIndex) status = 'complete';
|
||||
|
||||
return {
|
||||
'fromRev': fromIndex,
|
||||
'rev': elem.rev,
|
||||
'status': status,
|
||||
'changesets': changesets,
|
||||
'spans': spans,
|
||||
'times': times
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
exports.loadBroadcastRevisionsJS = loadBroadcastRevisionsJS;
|
504
src/static/js/broadcast_slider.js
Normal file
|
@ -0,0 +1,504 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
// These parameters were global, now they are injected. A reference to the
|
||||
// Timeslider controller would probably be more appropriate.
|
||||
function loadBroadcastSliderJS(fireWhenAllScriptsAreLoaded)
|
||||
{
|
||||
var BroadcastSlider;
|
||||
|
||||
(function()
|
||||
{ // wrap this code in its own namespace
|
||||
var sliderLength = 1000;
|
||||
var sliderPos = 0;
|
||||
var sliderActive = false;
|
||||
var slidercallbacks = [];
|
||||
var savedRevisions = [];
|
||||
var sliderPlaying = false;
|
||||
|
||||
function disableSelection(element)
|
||||
{
|
||||
element.onselectstart = function()
|
||||
{
|
||||
return false;
|
||||
};
|
||||
element.unselectable = "on";
|
||||
element.style.MozUserSelect = "none";
|
||||
element.style.cursor = "default";
|
||||
}
|
||||
var _callSliderCallbacks = function(newval)
|
||||
{
|
||||
sliderPos = newval;
|
||||
for (var i = 0; i < slidercallbacks.length; i++)
|
||||
{
|
||||
slidercallbacks[i](newval);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
var updateSliderElements = function()
|
||||
{
|
||||
for (var i = 0; i < savedRevisions.length; i++)
|
||||
{
|
||||
var position = parseInt(savedRevisions[i].attr('pos'));
|
||||
savedRevisions[i].css('left', (position * ($("#ui-slider-bar").width() - 2) / (sliderLength * 1.0)) - 1);
|
||||
}
|
||||
$("#ui-slider-handle").css('left', sliderPos * ($("#ui-slider-bar").width() - 2) / (sliderLength * 1.0));
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
var addSavedRevision = function(position, info)
|
||||
{
|
||||
var newSavedRevision = $('<div></div>');
|
||||
newSavedRevision.addClass("star");
|
||||
|
||||
newSavedRevision.attr('pos', position);
|
||||
newSavedRevision.css('position', 'absolute');
|
||||
newSavedRevision.css('left', (position * ($("#ui-slider-bar").width() - 2) / (sliderLength * 1.0)) - 1);
|
||||
$("#timeslider-slider").append(newSavedRevision);
|
||||
newSavedRevision.mouseup(function(evt)
|
||||
{
|
||||
BroadcastSlider.setSliderPosition(position);
|
||||
});
|
||||
savedRevisions.push(newSavedRevision);
|
||||
};
|
||||
|
||||
var removeSavedRevision = function(position)
|
||||
{
|
||||
var element = $("div.star [pos=" + position + "]");
|
||||
savedRevisions.remove(element);
|
||||
element.remove();
|
||||
return element;
|
||||
};
|
||||
|
||||
/* Begin small 'API' */
|
||||
|
||||
function onSlider(callback)
|
||||
{
|
||||
slidercallbacks.push(callback);
|
||||
}
|
||||
|
||||
function getSliderPosition()
|
||||
{
|
||||
return sliderPos;
|
||||
}
|
||||
|
||||
function setSliderPosition(newpos)
|
||||
{
|
||||
newpos = Number(newpos);
|
||||
if (newpos < 0 || newpos > sliderLength) return;
|
||||
$("#ui-slider-handle").css('left', newpos * ($("#ui-slider-bar").width() - 2) / (sliderLength * 1.0));
|
||||
$("a.tlink").map(function()
|
||||
{
|
||||
$(this).attr('href', $(this).attr('thref').replace("%revision%", newpos));
|
||||
});
|
||||
$("#revision_label").html("Version " + newpos);
|
||||
|
||||
if (newpos == 0)
|
||||
{
|
||||
$("#leftstar").css('opacity', .5);
|
||||
$("#leftstep").css('opacity', .5);
|
||||
}
|
||||
else
|
||||
{
|
||||
$("#leftstar").css('opacity', 1);
|
||||
$("#leftstep").css('opacity', 1);
|
||||
}
|
||||
|
||||
if (newpos == sliderLength)
|
||||
{
|
||||
$("#rightstar").css('opacity', .5);
|
||||
$("#rightstep").css('opacity', .5);
|
||||
}
|
||||
else
|
||||
{
|
||||
$("#rightstar").css('opacity', 1);
|
||||
$("#rightstep").css('opacity', 1);
|
||||
}
|
||||
|
||||
sliderPos = newpos;
|
||||
_callSliderCallbacks(newpos);
|
||||
}
|
||||
|
||||
function getSliderLength()
|
||||
{
|
||||
return sliderLength;
|
||||
}
|
||||
|
||||
function setSliderLength(newlength)
|
||||
{
|
||||
sliderLength = newlength;
|
||||
updateSliderElements();
|
||||
}
|
||||
|
||||
// just take over the whole slider screen with a reconnect message
|
||||
|
||||
function showReconnectUI()
|
||||
{
|
||||
if (!clientVars.sliderEnabled || !clientVars.supportsSlider)
|
||||
{
|
||||
$("#padmain, #rightbars").css('top', "130px");
|
||||
$("#timeslider").show();
|
||||
}
|
||||
$('#error').show();
|
||||
}
|
||||
|
||||
function setAuthors(authors)
|
||||
{
|
||||
$("#authorstable").empty();
|
||||
var numAnonymous = 0;
|
||||
var numNamed = 0;
|
||||
authors.forEach(function(author)
|
||||
{
|
||||
if (author.name)
|
||||
{
|
||||
numNamed++;
|
||||
var tr = $('<tr></tr>');
|
||||
var swatchtd = $('<td></td>');
|
||||
var swatch = $('<div class="swatch"></div>');
|
||||
swatch.css('background-color', clientVars.colorPalette[author.colorId]);
|
||||
swatchtd.append(swatch);
|
||||
tr.append(swatchtd);
|
||||
var nametd = $('<td></td>');
|
||||
nametd.text(author.name || "unnamed");
|
||||
tr.append(nametd);
|
||||
$("#authorstable").append(tr);
|
||||
}
|
||||
else
|
||||
{
|
||||
numAnonymous++;
|
||||
}
|
||||
});
|
||||
if (numAnonymous > 0)
|
||||
{
|
||||
var html = "<tr><td colspan=\"2\" style=\"color:#999; padding-left: 10px\">" + (numNamed > 0 ? "...and " : "") + numAnonymous + " unnamed author" + (numAnonymous > 1 ? "s" : "") + "</td></tr>";
|
||||
$("#authorstable").append($(html));
|
||||
}
|
||||
if (authors.length == 0)
|
||||
{
|
||||
$("#authorstable").append($("<tr><td colspan=\"2\" style=\"color:#999; padding-left: 10px\">No Authors</td></tr>"))
|
||||
}
|
||||
}
|
||||
|
||||
BroadcastSlider = {
|
||||
onSlider: onSlider,
|
||||
getSliderPosition: getSliderPosition,
|
||||
setSliderPosition: setSliderPosition,
|
||||
getSliderLength: getSliderLength,
|
||||
setSliderLength: setSliderLength,
|
||||
isSliderActive: function()
|
||||
{
|
||||
return sliderActive;
|
||||
},
|
||||
playpause: playpause,
|
||||
addSavedRevision: addSavedRevision,
|
||||
showReconnectUI: showReconnectUI,
|
||||
setAuthors: setAuthors
|
||||
}
|
||||
|
||||
function playButtonUpdater()
|
||||
{
|
||||
if (sliderPlaying)
|
||||
{
|
||||
if (getSliderPosition() + 1 > sliderLength)
|
||||
{
|
||||
$("#playpause_button_icon").toggleClass('pause');
|
||||
sliderPlaying = false;
|
||||
return;
|
||||
}
|
||||
setSliderPosition(getSliderPosition() + 1);
|
||||
|
||||
setTimeout(playButtonUpdater, 100);
|
||||
}
|
||||
}
|
||||
|
||||
function playpause()
|
||||
{
|
||||
$("#playpause_button_icon").toggleClass('pause');
|
||||
|
||||
if (!sliderPlaying)
|
||||
{
|
||||
if (getSliderPosition() == sliderLength) setSliderPosition(0);
|
||||
sliderPlaying = true;
|
||||
playButtonUpdater();
|
||||
}
|
||||
else
|
||||
{
|
||||
sliderPlaying = false;
|
||||
}
|
||||
}
|
||||
|
||||
// assign event handlers to html UI elements after page load
|
||||
//$(window).load(function ()
|
||||
fireWhenAllScriptsAreLoaded.push(function()
|
||||
{
|
||||
disableSelection($("#playpause_button")[0]);
|
||||
disableSelection($("#timeslider")[0]);
|
||||
|
||||
if (clientVars.sliderEnabled && clientVars.supportsSlider)
|
||||
{
|
||||
$(document).keyup(function(e)
|
||||
{
|
||||
var code = -1;
|
||||
if (!e) var e = window.event;
|
||||
if (e.keyCode) code = e.keyCode;
|
||||
else if (e.which) code = e.which;
|
||||
|
||||
if (code == 37)
|
||||
{ // left
|
||||
if (!e.shiftKey)
|
||||
{
|
||||
setSliderPosition(getSliderPosition() - 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
var nextStar = 0; // default to first revision in document
|
||||
for (var i = 0; i < savedRevisions.length; i++)
|
||||
{
|
||||
var pos = parseInt(savedRevisions[i].attr('pos'));
|
||||
if (pos < getSliderPosition() && nextStar < pos) nextStar = pos;
|
||||
}
|
||||
setSliderPosition(nextStar);
|
||||
}
|
||||
}
|
||||
else if (code == 39)
|
||||
{
|
||||
if (!e.shiftKey)
|
||||
{
|
||||
setSliderPosition(getSliderPosition() + 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
var nextStar = sliderLength; // default to last revision in document
|
||||
for (var i = 0; i < savedRevisions.length; i++)
|
||||
{
|
||||
var pos = parseInt(savedRevisions[i].attr('pos'));
|
||||
if (pos > getSliderPosition() && nextStar > pos) nextStar = pos;
|
||||
}
|
||||
setSliderPosition(nextStar);
|
||||
}
|
||||
}
|
||||
else if (code == 32) playpause();
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
$(window).resize(function()
|
||||
{
|
||||
updateSliderElements();
|
||||
});
|
||||
|
||||
$("#ui-slider-bar").mousedown(function(evt)
|
||||
{
|
||||
setSliderPosition(Math.floor((evt.clientX - $("#ui-slider-bar").offset().left) * sliderLength / 742));
|
||||
$("#ui-slider-handle").css('left', (evt.clientX - $("#ui-slider-bar").offset().left));
|
||||
$("#ui-slider-handle").trigger(evt);
|
||||
});
|
||||
|
||||
// Slider dragging
|
||||
$("#ui-slider-handle").mousedown(function(evt)
|
||||
{
|
||||
this.startLoc = evt.clientX;
|
||||
this.currentLoc = parseInt($(this).css('left'));
|
||||
var self = this;
|
||||
sliderActive = true;
|
||||
$(document).mousemove(function(evt2)
|
||||
{
|
||||
$(self).css('pointer', 'move')
|
||||
var newloc = self.currentLoc + (evt2.clientX - self.startLoc);
|
||||
if (newloc < 0) newloc = 0;
|
||||
if (newloc > ($("#ui-slider-bar").width() - 2)) newloc = ($("#ui-slider-bar").width() - 2);
|
||||
$("#revision_label").html("Version " + Math.floor(newloc * sliderLength / ($("#ui-slider-bar").width() - 2)));
|
||||
$(self).css('left', newloc);
|
||||
if (getSliderPosition() != Math.floor(newloc * sliderLength / ($("#ui-slider-bar").width() - 2))) _callSliderCallbacks(Math.floor(newloc * sliderLength / ($("#ui-slider-bar").width() - 2)))
|
||||
});
|
||||
$(document).mouseup(function(evt2)
|
||||
{
|
||||
$(document).unbind('mousemove');
|
||||
$(document).unbind('mouseup');
|
||||
sliderActive = false;
|
||||
var newloc = self.currentLoc + (evt2.clientX - self.startLoc);
|
||||
if (newloc < 0) newloc = 0;
|
||||
if (newloc > ($("#ui-slider-bar").width() - 2)) newloc = ($("#ui-slider-bar").width() - 2);
|
||||
$(self).css('left', newloc);
|
||||
// if(getSliderPosition() != Math.floor(newloc * sliderLength / ($("#ui-slider-bar").width()-2)))
|
||||
setSliderPosition(Math.floor(newloc * sliderLength / ($("#ui-slider-bar").width() - 2)))
|
||||
self.currentLoc = parseInt($(self).css('left'));
|
||||
});
|
||||
})
|
||||
|
||||
// play/pause toggling
|
||||
$("#playpause_button").mousedown(function(evt)
|
||||
{
|
||||
var self = this;
|
||||
|
||||
$(self).css('background-image', 'url(/static/img/crushed_button_depressed.png)');
|
||||
$(self).mouseup(function(evt2)
|
||||
{
|
||||
$(self).css('background-image', 'url(/static/img/crushed_button_undepressed.png)');
|
||||
$(self).unbind('mouseup');
|
||||
BroadcastSlider.playpause();
|
||||
});
|
||||
$(document).mouseup(function(evt2)
|
||||
{
|
||||
$(self).css('background-image', 'url(/static/img/crushed_button_undepressed.png)');
|
||||
$(document).unbind('mouseup');
|
||||
});
|
||||
});
|
||||
|
||||
// next/prev saved revision and changeset
|
||||
$('.stepper').mousedown(function(evt)
|
||||
{
|
||||
var self = this;
|
||||
var origcss = $(self).css('background-position');
|
||||
if (!origcss)
|
||||
{
|
||||
origcss = $(self).css('background-position-x') + " " + $(self).css('background-position-y');
|
||||
}
|
||||
var origpos = parseInt(origcss.split(" ")[1]);
|
||||
var newpos = (origpos - 43);
|
||||
if (newpos < 0) newpos += 87;
|
||||
|
||||
var newcss = (origcss.split(" ")[0] + " " + newpos + "px");
|
||||
if ($(self).css('opacity') != 1.0) newcss = origcss;
|
||||
|
||||
$(self).css('background-position', newcss)
|
||||
|
||||
$(self).mouseup(function(evt2)
|
||||
{
|
||||
$(self).css('background-position', origcss);
|
||||
$(self).unbind('mouseup');
|
||||
$(document).unbind('mouseup');
|
||||
if ($(self).attr("id") == ("leftstep"))
|
||||
{
|
||||
setSliderPosition(getSliderPosition() - 1);
|
||||
}
|
||||
else if ($(self).attr("id") == ("rightstep"))
|
||||
{
|
||||
setSliderPosition(getSliderPosition() + 1);
|
||||
}
|
||||
else if ($(self).attr("id") == ("leftstar"))
|
||||
{
|
||||
var nextStar = 0; // default to first revision in document
|
||||
for (var i = 0; i < savedRevisions.length; i++)
|
||||
{
|
||||
var pos = parseInt(savedRevisions[i].attr('pos'));
|
||||
if (pos < getSliderPosition() && nextStar < pos) nextStar = pos;
|
||||
}
|
||||
setSliderPosition(nextStar);
|
||||
}
|
||||
else if ($(self).attr("id") == ("rightstar"))
|
||||
{
|
||||
var nextStar = sliderLength; // default to last revision in document
|
||||
for (var i = 0; i < savedRevisions.length; i++)
|
||||
{
|
||||
var pos = parseInt(savedRevisions[i].attr('pos'));
|
||||
if (pos > getSliderPosition() && nextStar > pos) nextStar = pos;
|
||||
}
|
||||
setSliderPosition(nextStar);
|
||||
}
|
||||
});
|
||||
$(document).mouseup(function(evt2)
|
||||
{
|
||||
$(self).css('background-position', origcss);
|
||||
$(self).unbind('mouseup');
|
||||
$(document).unbind('mouseup');
|
||||
});
|
||||
})
|
||||
|
||||
if (clientVars)
|
||||
{
|
||||
if (clientVars.fullWidth)
|
||||
{
|
||||
$("#padpage").css('width', '100%');
|
||||
$("#revision").css('position', "absolute")
|
||||
$("#revision").css('right', "20px")
|
||||
$("#revision").css('top', "20px")
|
||||
$("#padmain").css('left', '0px');
|
||||
$("#padmain").css('right', '197px');
|
||||
$("#padmain").css('width', 'auto');
|
||||
$("#rightbars").css('right', '7px');
|
||||
$("#rightbars").css('margin-right', '0px');
|
||||
$("#timeslider").css('width', 'auto');
|
||||
}
|
||||
|
||||
if (clientVars.disableRightBar)
|
||||
{
|
||||
$("#rightbars").css('display', 'none');
|
||||
$('#padmain').css('width', 'auto');
|
||||
if (clientVars.fullWidth) $("#padmain").css('right', '7px');
|
||||
else $("#padmain").css('width', '860px');
|
||||
$("#revision").css('position', "absolute");
|
||||
$("#revision").css('right', "20px");
|
||||
$("#revision").css('top', "20px");
|
||||
}
|
||||
|
||||
|
||||
if (clientVars.sliderEnabled)
|
||||
{
|
||||
if (clientVars.supportsSlider)
|
||||
{
|
||||
$("#padmain, #rightbars").css('top', "130px");
|
||||
$("#timeslider").show();
|
||||
setSliderLength(clientVars.totalRevs);
|
||||
setSliderPosition(clientVars.revNum);
|
||||
clientVars.savedRevisions.forEach(function(revision)
|
||||
{
|
||||
addSavedRevision(revision.revNum, revision);
|
||||
})
|
||||
}
|
||||
else
|
||||
{
|
||||
// slider is not supported
|
||||
$("#padmain, #rightbars").css('top', "130px");
|
||||
$("#timeslider").show();
|
||||
$("#error").html("The timeslider feature is not supported on this pad. <a href=\"/ep/about/faq#disabledslider\">Why not?</a>");
|
||||
$("#error").show();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (clientVars.supportsSlider)
|
||||
{
|
||||
setSliderLength(clientVars.totalRevs);
|
||||
setSliderPosition(clientVars.revNum);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
})();
|
||||
|
||||
BroadcastSlider.onSlider(function(loc)
|
||||
{
|
||||
$("#viewlatest").html(loc == BroadcastSlider.getSliderLength() ? "Viewing latest content" : "View latest content");
|
||||
})
|
||||
|
||||
return BroadcastSlider;
|
||||
}
|
||||
|
||||
exports.loadBroadcastSliderJS = loadBroadcastSliderJS;
|
213
src/static/js/changesettracker.js
Normal file
|
@ -0,0 +1,213 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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 AttribPool = require('/AttributePoolFactory').createAttributePool;
|
||||
var Changeset = require('/Changeset');
|
||||
|
||||
function makeChangesetTracker(scheduler, apool, aceCallbacksProvider)
|
||||
{
|
||||
|
||||
// latest official text from server
|
||||
var baseAText = Changeset.makeAText("\n");
|
||||
// changes applied to baseText that have been submitted
|
||||
var submittedChangeset = null;
|
||||
// changes applied to submittedChangeset since it was prepared
|
||||
var userChangeset = Changeset.identity(1);
|
||||
// is the changesetTracker enabled
|
||||
var tracking = false;
|
||||
// stack state flag so that when we change the rep we don't
|
||||
// handle the notification recursively. When setting, always
|
||||
// unset in a "finally" block. When set to true, the setter
|
||||
// takes change of userChangeset.
|
||||
var applyingNonUserChanges = false;
|
||||
|
||||
var changeCallback = null;
|
||||
|
||||
var changeCallbackTimeout = null;
|
||||
|
||||
function setChangeCallbackTimeout()
|
||||
{
|
||||
// can call this multiple times per call-stack, because
|
||||
// we only schedule a call to changeCallback if it exists
|
||||
// and if there isn't a timeout already scheduled.
|
||||
if (changeCallback && changeCallbackTimeout === null)
|
||||
{
|
||||
changeCallbackTimeout = scheduler.setTimeout(function()
|
||||
{
|
||||
try
|
||||
{
|
||||
changeCallback();
|
||||
}
|
||||
finally
|
||||
{
|
||||
changeCallbackTimeout = null;
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
}
|
||||
|
||||
var self;
|
||||
return self = {
|
||||
isTracking: function()
|
||||
{
|
||||
return tracking;
|
||||
},
|
||||
setBaseText: function(text)
|
||||
{
|
||||
self.setBaseAttributedText(Changeset.makeAText(text), null);
|
||||
},
|
||||
setBaseAttributedText: function(atext, apoolJsonObj)
|
||||
{
|
||||
aceCallbacksProvider.withCallbacks("setBaseText", function(callbacks)
|
||||
{
|
||||
tracking = true;
|
||||
baseAText = Changeset.cloneAText(atext);
|
||||
if (apoolJsonObj)
|
||||
{
|
||||
var wireApool = (new AttribPool()).fromJsonable(apoolJsonObj);
|
||||
baseAText.attribs = Changeset.moveOpsToNewPool(baseAText.attribs, wireApool, apool);
|
||||
}
|
||||
submittedChangeset = null;
|
||||
userChangeset = Changeset.identity(atext.text.length);
|
||||
applyingNonUserChanges = true;
|
||||
try
|
||||
{
|
||||
callbacks.setDocumentAttributedText(atext);
|
||||
}
|
||||
finally
|
||||
{
|
||||
applyingNonUserChanges = false;
|
||||
}
|
||||
});
|
||||
},
|
||||
composeUserChangeset: function(c)
|
||||
{
|
||||
if (!tracking) return;
|
||||
if (applyingNonUserChanges) return;
|
||||
if (Changeset.isIdentity(c)) return;
|
||||
userChangeset = Changeset.compose(userChangeset, c, apool);
|
||||
|
||||
setChangeCallbackTimeout();
|
||||
},
|
||||
applyChangesToBase: function(c, optAuthor, apoolJsonObj)
|
||||
{
|
||||
if (!tracking) return;
|
||||
|
||||
aceCallbacksProvider.withCallbacks("applyChangesToBase", function(callbacks)
|
||||
{
|
||||
|
||||
if (apoolJsonObj)
|
||||
{
|
||||
var wireApool = (new AttribPool()).fromJsonable(apoolJsonObj);
|
||||
c = Changeset.moveOpsToNewPool(c, wireApool, apool);
|
||||
}
|
||||
|
||||
baseAText = Changeset.applyToAText(c, baseAText, apool);
|
||||
|
||||
var c2 = c;
|
||||
if (submittedChangeset)
|
||||
{
|
||||
var oldSubmittedChangeset = submittedChangeset;
|
||||
submittedChangeset = Changeset.follow(c, oldSubmittedChangeset, false, apool);
|
||||
c2 = Changeset.follow(oldSubmittedChangeset, c, true, apool);
|
||||
}
|
||||
|
||||
var preferInsertingAfterUserChanges = true;
|
||||
var oldUserChangeset = userChangeset;
|
||||
userChangeset = Changeset.follow(c2, oldUserChangeset, preferInsertingAfterUserChanges, apool);
|
||||
var postChange = Changeset.follow(oldUserChangeset, c2, !preferInsertingAfterUserChanges, apool);
|
||||
|
||||
var preferInsertionAfterCaret = true; //(optAuthor && optAuthor > thisAuthor);
|
||||
applyingNonUserChanges = true;
|
||||
try
|
||||
{
|
||||
callbacks.applyChangesetToDocument(postChange, preferInsertionAfterCaret);
|
||||
}
|
||||
finally
|
||||
{
|
||||
applyingNonUserChanges = false;
|
||||
}
|
||||
});
|
||||
},
|
||||
prepareUserChangeset: function()
|
||||
{
|
||||
// If there are user changes to submit, 'changeset' will be the
|
||||
// changeset, else it will be null.
|
||||
var toSubmit;
|
||||
if (submittedChangeset)
|
||||
{
|
||||
// submission must have been canceled, prepare new changeset
|
||||
// that includes old submittedChangeset
|
||||
toSubmit = Changeset.compose(submittedChangeset, userChangeset, apool);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (Changeset.isIdentity(userChangeset)) toSubmit = null;
|
||||
else toSubmit = userChangeset;
|
||||
}
|
||||
|
||||
var cs = null;
|
||||
if (toSubmit)
|
||||
{
|
||||
submittedChangeset = toSubmit;
|
||||
userChangeset = Changeset.identity(Changeset.newLen(toSubmit));
|
||||
|
||||
cs = toSubmit;
|
||||
}
|
||||
var wireApool = null;
|
||||
if (cs)
|
||||
{
|
||||
var forWire = Changeset.prepareForWire(cs, apool);
|
||||
wireApool = forWire.pool.toJsonable();
|
||||
cs = forWire.translated;
|
||||
}
|
||||
|
||||
var data = {
|
||||
changeset: cs,
|
||||
apool: wireApool
|
||||
};
|
||||
return data;
|
||||
},
|
||||
applyPreparedChangesetToBase: function()
|
||||
{
|
||||
if (!submittedChangeset)
|
||||
{
|
||||
// violation of protocol; use prepareUserChangeset first
|
||||
throw new Error("applySubmittedChangesToBase: no submitted changes to apply");
|
||||
}
|
||||
//bumpDebug("applying committed changeset: "+submittedChangeset.encodeToString(false));
|
||||
baseAText = Changeset.applyToAText(submittedChangeset, baseAText, apool);
|
||||
submittedChangeset = null;
|
||||
},
|
||||
setUserChangeNotificationCallback: function(callback)
|
||||
{
|
||||
changeCallback = callback;
|
||||
},
|
||||
hasUncommittedChanges: function()
|
||||
{
|
||||
return !!(submittedChangeset || (!Changeset.isIdentity(userChangeset)));
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
exports.makeChangesetTracker = makeChangesetTracker;
|
162
src/static/js/chat.js
Normal file
|
@ -0,0 +1,162 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copyright 2009 Google Inc., 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
|
||||
*
|
||||
* 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 padutils = require('/pad_utils').padutils;
|
||||
var padcookie = require('/pad_cookie').padcookie;
|
||||
|
||||
var chat = (function()
|
||||
{
|
||||
var isStuck = false;
|
||||
var chatMentions = 0;
|
||||
var title = document.title;
|
||||
var self = {
|
||||
show: function ()
|
||||
{
|
||||
$("#chaticon").hide();
|
||||
$("#chatbox").show();
|
||||
self.scrollDown();
|
||||
chatMentions = 0;
|
||||
document.title = title;
|
||||
},
|
||||
stickToScreen: function(fromInitialCall) // Make chat stick to right hand side of screen
|
||||
{
|
||||
chat.show();
|
||||
if(!isStuck || fromInitialCall) { // Stick it to
|
||||
padcookie.setPref("chatAlwaysVisible", true);
|
||||
$('#chatbox').css({"right":"0px", "top":"36px", "border-radius":"0px", "height":"auto", "border-right":"none", "border-left":"1px solid #ccc", "border-top":"none", "background-color":"#f1f1f1", "width":"185px"});
|
||||
$('#chattext').css({"top":"0px"});
|
||||
$('#editorcontainer').css({"right":"192px", "width":"auto"});
|
||||
isStuck = true;
|
||||
} else { // Unstick it
|
||||
padcookie.setPref("chatAlwaysVisible", false);
|
||||
$('#chatbox').css({"right":"20px", "top":"auto", "border-top-left-radius":"5px", "border-top-right-radius":"5px", "border-right":"1px solid #999", "height":"200px", "border-top":"1px solid #999", "background-color":"#f7f7f7"});
|
||||
$('#chattext').css({"top":"25px"});
|
||||
$('#editorcontainer').css({"right":"0px", "width":"100%"});
|
||||
isStuck = false;
|
||||
}
|
||||
},
|
||||
hide: function ()
|
||||
{
|
||||
$("#chatcounter").text("0");
|
||||
$("#chaticon").show();
|
||||
$("#chatbox").hide();
|
||||
},
|
||||
scrollDown: function()
|
||||
{
|
||||
if($('#chatbox').css("display") != "none")
|
||||
$('#chattext').animate({scrollTop: $('#chattext')[0].scrollHeight}, "slow");
|
||||
},
|
||||
send: function()
|
||||
{
|
||||
var text = $("#chatinput").val();
|
||||
this._pad.collabClient.sendMessage({"type": "CHAT_MESSAGE", "text": text});
|
||||
$("#chatinput").val("");
|
||||
},
|
||||
addMessage: function(msg, increment)
|
||||
{
|
||||
//correct the time
|
||||
msg.time += this._pad.clientTimeOffset;
|
||||
|
||||
//create the time string
|
||||
var minutes = "" + new Date(msg.time).getMinutes();
|
||||
var hours = "" + new Date(msg.time).getHours();
|
||||
if(minutes.length == 1)
|
||||
minutes = "0" + minutes ;
|
||||
if(hours.length == 1)
|
||||
hours = "0" + hours ;
|
||||
var timeStr = hours + ":" + minutes;
|
||||
|
||||
//create the authorclass
|
||||
var authorClass = "author-" + msg.userId.replace(/[^a-y0-9]/g, function(c)
|
||||
{
|
||||
if (c == ".") return "-";
|
||||
return 'z' + c.charCodeAt(0) + 'z';
|
||||
});
|
||||
|
||||
var text = padutils.escapeHtmlWithClickableLinks(msg.text, "_blank");
|
||||
|
||||
/* Performs an action if your name is mentioned */
|
||||
var myName = $('#myusernameedit').val();
|
||||
myName = myName.toLowerCase();
|
||||
var chatText = text.toLowerCase();
|
||||
var wasMentioned = false;
|
||||
if (chatText.indexOf(myName) !== -1 && myName != "undefined"){
|
||||
wasMentioned = true;
|
||||
}
|
||||
/* End of new action */
|
||||
|
||||
var authorName = msg.userName == null ? "unnamed" : padutils.escapeHtml(msg.userName);
|
||||
|
||||
var html = "<p class='" + authorClass + "'><b>" + authorName + ":</b><span class='time " + authorClass + "'>" + timeStr + "</span> " + text + "</p>";
|
||||
$("#chattext").append(html);
|
||||
|
||||
//should we increment the counter??
|
||||
if(increment)
|
||||
{
|
||||
var count = Number($("#chatcounter").text());
|
||||
count++;
|
||||
$("#chatcounter").text(count);
|
||||
// chat throb stuff -- Just make it throw for twice as long
|
||||
if(wasMentioned)
|
||||
{ // If the user was mentioned show for twice as long and flash the browser window
|
||||
if (chatMentions == 0){
|
||||
title = document.title;
|
||||
}
|
||||
$('#chatthrob').html("<b>"+authorName+"</b>" + ": " + text).show().delay(4000).hide(400);
|
||||
chatMentions++;
|
||||
document.title = "("+chatMentions+") " + title;
|
||||
}
|
||||
else
|
||||
{
|
||||
$('#chatthrob').html("<b>"+authorName+"</b>" + ": " + text).show().delay(2000).hide(400);
|
||||
}
|
||||
}
|
||||
|
||||
self.scrollDown();
|
||||
|
||||
},
|
||||
init: function(pad)
|
||||
{
|
||||
this._pad = pad;
|
||||
$("#chatinput").keypress(function(evt)
|
||||
{
|
||||
//if the user typed enter, fire the send
|
||||
if(evt.which == 13)
|
||||
{
|
||||
evt.preventDefault();
|
||||
self.send();
|
||||
}
|
||||
});
|
||||
|
||||
for(var i in clientVars.chatHistory)
|
||||
{
|
||||
this.addMessage(clientVars.chatHistory[i], false);
|
||||
}
|
||||
$("#chatcounter").text(clientVars.chatHistory.length);
|
||||
}
|
||||
}
|
||||
|
||||
return self;
|
||||
}());
|
||||
|
||||
exports.chat = chat;
|
||||
|
713
src/static/js/collab_client.js
Normal file
|
@ -0,0 +1,713 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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 chat = require('/chat').chat;
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
/** 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)
|
||||
{
|
||||
var editor = ace2editor;
|
||||
pad = _pad; // Inject pad to avoid a circular dependency.
|
||||
|
||||
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 = [];
|
||||
|
||||
tellAceAboutHistoricalAuthors(serverVars.historicalAuthorData);
|
||||
tellAceActiveAuthorInfo(initialUserInfo);
|
||||
|
||||
var callbacks = {
|
||||
onUserJoin: function()
|
||||
{},
|
||||
onUserLeave: function()
|
||||
{},
|
||||
onUpdateUserInfo: function()
|
||||
{},
|
||||
onChannelStateChange: function()
|
||||
{},
|
||||
onClientMessage: function()
|
||||
{},
|
||||
onInternalAction: function()
|
||||
{},
|
||||
onConnectionTrouble: function()
|
||||
{},
|
||||
onServerMessage: function()
|
||||
{}
|
||||
};
|
||||
|
||||
$(window).bind("unload", function()
|
||||
{
|
||||
if (getSocket())
|
||||
{
|
||||
setChannelState("DISCONNECTED", "unload");
|
||||
}
|
||||
});
|
||||
if ($.browser.mozilla)
|
||||
{
|
||||
// Prevent "escape" from taking effect and canceling a comet connection;
|
||||
// doesn't work if focus is on an iframe.
|
||||
$(window).bind("keydown", function(evt)
|
||||
{
|
||||
if (evt.which == 27)
|
||||
{
|
||||
evt.preventDefault()
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
editor.setProperty("userAuthor", userId);
|
||||
editor.setBaseAttributedText(serverVars.initialAttributedText, serverVars.apool);
|
||||
editor.setUserChangeNotificationCallback(wrapRecordingErrors("handleUserChanges", handleUserChanges));
|
||||
|
||||
function dmesg(str)
|
||||
{
|
||||
if (typeof window.ajlog == "string") window.ajlog += str + '\n';
|
||||
debugMessages.push(str);
|
||||
}
|
||||
|
||||
function handleUserChanges()
|
||||
{
|
||||
if ((!getSocket()) || channelState == "CONNECTING")
|
||||
{
|
||||
if (channelState == "CONNECTING" && (((+new Date()) - initialStartConnectTime) > 20000))
|
||||
{
|
||||
setChannelState("DISCONNECTED", "initsocketfail");
|
||||
}
|
||||
else
|
||||
{
|
||||
// check again in a bit
|
||||
setTimeout(wrapRecordingErrors("setTimeout(handleUserChanges)", handleUserChanges), 1000);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
var t = (+new Date());
|
||||
|
||||
if (state != "IDLE")
|
||||
{
|
||||
if (state == "COMMITTING" && (t - lastCommitTime) > 20000)
|
||||
{
|
||||
// a commit is taking too long
|
||||
setChannelState("DISCONNECTED", "slowcommit");
|
||||
}
|
||||
else if (state == "COMMITTING" && (t - lastCommitTime) > 5000)
|
||||
{
|
||||
callbacks.onConnectionTrouble("SLOW");
|
||||
}
|
||||
else
|
||||
{
|
||||
// run again in a few seconds, to detect a disconnect
|
||||
setTimeout(wrapRecordingErrors("setTimeout(handleUserChanges)", handleUserChanges), 3000);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
var earliestCommit = lastCommitTime + 500;
|
||||
if (t < earliestCommit)
|
||||
{
|
||||
setTimeout(wrapRecordingErrors("setTimeout(handleUserChanges)", handleUserChanges), earliestCommit - t);
|
||||
return;
|
||||
}
|
||||
|
||||
var sentMessage = false;
|
||||
var userChangesData = editor.prepareUserChangeset();
|
||||
if (userChangesData.changeset)
|
||||
{
|
||||
lastCommitTime = t;
|
||||
state = "COMMITTING";
|
||||
stateMessage = {
|
||||
type: "USER_CHANGES",
|
||||
baseRev: rev,
|
||||
changeset: userChangesData.changeset,
|
||||
apool: userChangesData.apool
|
||||
};
|
||||
stateMessageSocketId = socketId;
|
||||
sendMessage(stateMessage);
|
||||
sentMessage = true;
|
||||
callbacks.onInternalAction("commitPerformed");
|
||||
}
|
||||
|
||||
if (sentMessage)
|
||||
{
|
||||
// run again in a few seconds, to detect a disconnect
|
||||
setTimeout(wrapRecordingErrors("setTimeout(handleUserChanges)", handleUserChanges), 3000);
|
||||
}
|
||||
}
|
||||
|
||||
function getStats()
|
||||
{
|
||||
var stats = {};
|
||||
|
||||
stats.screen = [$(window).width(), $(window).height(), window.screen.availWidth, window.screen.availHeight, window.screen.width, window.screen.height].join(',');
|
||||
stats.ip = serverVars.clientIp;
|
||||
stats.useragent = serverVars.clientAgent;
|
||||
|
||||
return stats;
|
||||
}
|
||||
|
||||
function setUpSocket()
|
||||
{
|
||||
//oldSocketId = String(Math.floor(Math.random()*1e12));
|
||||
//socketId = String(Math.floor(Math.random()*1e12));
|
||||
/*socket = new io.Socket();
|
||||
socket.connect();*/
|
||||
|
||||
//socket.on('connect', function(){
|
||||
hiccupCount = 0;
|
||||
setChannelState("CONNECTED");
|
||||
/*var msg = { type:"CLIENT_READY", roomType:'padpage',
|
||||
roomName:'padpage/'+globalPadId,
|
||||
data: {
|
||||
lastRev:rev,
|
||||
userInfo:userSet[userId],
|
||||
stats: getStats() } };
|
||||
if (oldSocketId) {
|
||||
msg.data.isReconnectOf = oldSocketId;
|
||||
msg.data.isCommitPending = (state == "COMMITTING");
|
||||
}
|
||||
sendMessage(msg);*/
|
||||
doDeferredActions();
|
||||
|
||||
initialStartConnectTime = +new Date();
|
||||
// });
|
||||
/*socket.on('message', function(obj){
|
||||
if(window.console)
|
||||
console.log(obj);
|
||||
handleMessageFromServer(obj);
|
||||
});*/
|
||||
|
||||
/*var success = false;
|
||||
callCatchingErrors("setUpSocket", function() {
|
||||
appLevelDisconnectReason = null;
|
||||
|
||||
var oldSocketId = socketId;
|
||||
socketId = String(Math.floor(Math.random()*1e12));
|
||||
socket = new WebSocket(socketId);
|
||||
socket.onmessage = wrapRecordingErrors("socket.onmessage", handleMessageFromServer);
|
||||
socket.onclosed = wrapRecordingErrors("socket.onclosed", handleSocketClosed);
|
||||
socket.onopen = wrapRecordingErrors("socket.onopen", function() {
|
||||
hiccupCount = 0;
|
||||
setChannelState("CONNECTED");
|
||||
var msg = { type:"CLIENT_READY", roomType:'padpage',
|
||||
roomName:'padpage/'+globalPadId,
|
||||
data: {
|
||||
lastRev:rev,
|
||||
userInfo:userSet[userId],
|
||||
stats: getStats() } };
|
||||
if (oldSocketId) {
|
||||
msg.data.isReconnectOf = oldSocketId;
|
||||
msg.data.isCommitPending = (state == "COMMITTING");
|
||||
}
|
||||
sendMessage(msg);
|
||||
doDeferredActions();
|
||||
});
|
||||
socket.onhiccup = wrapRecordingErrors("socket.onhiccup", handleCometHiccup);
|
||||
socket.onlogmessage = dmesg;
|
||||
socket.connect();
|
||||
success = true;
|
||||
});
|
||||
if (success) {
|
||||
initialStartConnectTime = +new Date();
|
||||
}
|
||||
else {
|
||||
abandonConnection("initsocketfail");
|
||||
}*/
|
||||
}
|
||||
|
||||
var hiccupCount = 0;
|
||||
|
||||
function handleCometHiccup(params)
|
||||
{
|
||||
dmesg("HICCUP (connected:" + ( !! params.connected) + ")");
|
||||
var connectedNow = params.connected;
|
||||
if (!connectedNow)
|
||||
{
|
||||
hiccupCount++;
|
||||
// skip first "cut off from server" notification
|
||||
if (hiccupCount > 1)
|
||||
{
|
||||
setChannelState("RECONNECTING");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
hiccupCount = 0;
|
||||
setChannelState("CONNECTED");
|
||||
}
|
||||
}
|
||||
|
||||
function sendMessage(msg)
|
||||
{
|
||||
getSocket().json.send(
|
||||
{
|
||||
type: "COLLABROOM",
|
||||
component: "pad",
|
||||
data: msg
|
||||
});
|
||||
}
|
||||
|
||||
function wrapRecordingErrors(catcher, func)
|
||||
{
|
||||
return function()
|
||||
{
|
||||
try
|
||||
{
|
||||
return func.apply(this, Array.prototype.slice.call(arguments));
|
||||
}
|
||||
catch (e)
|
||||
{
|
||||
caughtErrors.push(e);
|
||||
caughtErrorCatchers.push(catcher);
|
||||
caughtErrorTimes.push(+new Date());
|
||||
//console.dir({catcher: catcher, e: e});
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function callCatchingErrors(catcher, func)
|
||||
{
|
||||
try
|
||||
{
|
||||
wrapRecordingErrors(catcher, func)();
|
||||
}
|
||||
catch (e)
|
||||
{ /*absorb*/
|
||||
}
|
||||
}
|
||||
|
||||
function handleMessageFromServer(evt)
|
||||
{
|
||||
if (window.console) console.log(evt);
|
||||
|
||||
if (!getSocket()) return;
|
||||
if (!evt.data) return;
|
||||
var wrapper = evt;
|
||||
if (wrapper.type != "COLLABROOM") return;
|
||||
var msg = wrapper.data;
|
||||
if (msg.type == "NEW_CHANGES")
|
||||
{
|
||||
var newRev = msg.newRev;
|
||||
var changeset = msg.changeset;
|
||||
var author = (msg.author || '');
|
||||
var apool = msg.apool;
|
||||
if (newRev != (rev + 1))
|
||||
{
|
||||
dmesg("bad message revision on NEW_CHANGES: " + newRev + " not " + (rev + 1));
|
||||
setChannelState("DISCONNECTED", "badmessage_newchanges");
|
||||
return;
|
||||
}
|
||||
rev = newRev;
|
||||
editor.applyChangesToBase(changeset, author, apool);
|
||||
}
|
||||
else if (msg.type == "ACCEPT_COMMIT")
|
||||
{
|
||||
var newRev = msg.newRev;
|
||||
if (newRev != (rev + 1))
|
||||
{
|
||||
dmesg("bad message revision on ACCEPT_COMMIT: " + newRev + " not " + (rev + 1));
|
||||
setChannelState("DISCONNECTED", "badmessage_acceptcommit");
|
||||
return;
|
||||
}
|
||||
rev = newRev;
|
||||
editor.applyPreparedChangesetToBase();
|
||||
setStateIdle();
|
||||
callCatchingErrors("onInternalAction", function()
|
||||
{
|
||||
callbacks.onInternalAction("commitAcceptedByServer");
|
||||
});
|
||||
callCatchingErrors("onConnectionTrouble", function()
|
||||
{
|
||||
callbacks.onConnectionTrouble("OK");
|
||||
});
|
||||
handleUserChanges();
|
||||
}
|
||||
else if (msg.type == "NO_COMMIT_PENDING")
|
||||
{
|
||||
if (state == "COMMITTING")
|
||||
{
|
||||
// server missed our commit message; abort that commit
|
||||
setStateIdle();
|
||||
handleUserChanges();
|
||||
}
|
||||
}
|
||||
else if (msg.type == "USER_NEWINFO")
|
||||
{
|
||||
var userInfo = msg.userInfo;
|
||||
var id = userInfo.userId;
|
||||
|
||||
if (userSet[id])
|
||||
{
|
||||
userSet[id] = userInfo;
|
||||
callbacks.onUpdateUserInfo(userInfo);
|
||||
dmesgUsers();
|
||||
}
|
||||
else
|
||||
{
|
||||
userSet[id] = userInfo;
|
||||
callbacks.onUserJoin(userInfo);
|
||||
dmesgUsers();
|
||||
}
|
||||
tellAceActiveAuthorInfo(userInfo);
|
||||
}
|
||||
else if (msg.type == "USER_LEAVE")
|
||||
{
|
||||
var userInfo = msg.userInfo;
|
||||
var id = userInfo.userId;
|
||||
if (userSet[id])
|
||||
{
|
||||
delete userSet[userInfo.userId];
|
||||
fadeAceAuthorInfo(userInfo);
|
||||
callbacks.onUserLeave(userInfo);
|
||||
dmesgUsers();
|
||||
}
|
||||
}
|
||||
else if (msg.type == "DISCONNECT_REASON")
|
||||
{
|
||||
appLevelDisconnectReason = msg.reason;
|
||||
}
|
||||
else if (msg.type == "CLIENT_MESSAGE")
|
||||
{
|
||||
callbacks.onClientMessage(msg.payload);
|
||||
}
|
||||
else if (msg.type == "CHAT_MESSAGE")
|
||||
{
|
||||
chat.addMessage(msg, true);
|
||||
}
|
||||
else if (msg.type == "SERVER_MESSAGE")
|
||||
{
|
||||
callbacks.onServerMessage(msg.payload);
|
||||
}
|
||||
}
|
||||
|
||||
function updateUserInfo(userInfo)
|
||||
{
|
||||
userInfo.userId = userId;
|
||||
userSet[userId] = userInfo;
|
||||
tellAceActiveAuthorInfo(userInfo);
|
||||
if (!getSocket()) return;
|
||||
sendMessage(
|
||||
{
|
||||
type: "USERINFO_UPDATE",
|
||||
userInfo: userInfo
|
||||
});
|
||||
}
|
||||
|
||||
function tellAceActiveAuthorInfo(userInfo)
|
||||
{
|
||||
tellAceAuthorInfo(userInfo.userId, userInfo.colorId);
|
||||
}
|
||||
|
||||
function tellAceAuthorInfo(userId, colorId, inactive)
|
||||
{
|
||||
if(typeof colorId == "number")
|
||||
{
|
||||
colorId = clientVars.colorPalette[colorId];
|
||||
}
|
||||
|
||||
var cssColor = colorId;
|
||||
if (inactive)
|
||||
{
|
||||
editor.setAuthorInfo(userId, {
|
||||
bgcolor: cssColor,
|
||||
fade: 0.5
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
editor.setAuthorInfo(userId, {
|
||||
bgcolor: cssColor
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function fadeAceAuthorInfo(userInfo)
|
||||
{
|
||||
tellAceAuthorInfo(userInfo.userId, userInfo.colorId, true);
|
||||
}
|
||||
|
||||
function getConnectedUsers()
|
||||
{
|
||||
return valuesArray(userSet);
|
||||
}
|
||||
|
||||
function tellAceAboutHistoricalAuthors(hadata)
|
||||
{
|
||||
for (var author in hadata)
|
||||
{
|
||||
var data = hadata[author];
|
||||
if (!userSet[author])
|
||||
{
|
||||
tellAceAuthorInfo(author, data.colorId, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function dmesgUsers()
|
||||
{
|
||||
//pad.dmesg($.map(getConnectedUsers(), function(u) { return u.userId.slice(-2); }).join(','));
|
||||
}
|
||||
|
||||
function setChannelState(newChannelState, moreInfo)
|
||||
{
|
||||
if (newChannelState != channelState)
|
||||
{
|
||||
channelState = newChannelState;
|
||||
callbacks.onChannelStateChange(channelState, moreInfo);
|
||||
}
|
||||
}
|
||||
|
||||
function keys(obj)
|
||||
{
|
||||
var array = [];
|
||||
$.each(obj, function(k, v)
|
||||
{
|
||||
array.push(k);
|
||||
});
|
||||
return array;
|
||||
}
|
||||
|
||||
function valuesArray(obj)
|
||||
{
|
||||
var array = [];
|
||||
$.each(obj, function(k, v)
|
||||
{
|
||||
array.push(v);
|
||||
});
|
||||
return array;
|
||||
}
|
||||
|
||||
// We need to present a working interface even before the socket
|
||||
// is connected for the first time.
|
||||
var deferredActions = [];
|
||||
|
||||
function defer(func, tag)
|
||||
{
|
||||
return function()
|
||||
{
|
||||
var that = this;
|
||||
var args = arguments;
|
||||
|
||||
function action()
|
||||
{
|
||||
func.apply(that, args);
|
||||
}
|
||||
action.tag = tag;
|
||||
if (channelState == "CONNECTING")
|
||||
{
|
||||
deferredActions.push(action);
|
||||
}
|
||||
else
|
||||
{
|
||||
action();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function doDeferredActions(tag)
|
||||
{
|
||||
var newArray = [];
|
||||
for (var i = 0; i < deferredActions.length; i++)
|
||||
{
|
||||
var a = deferredActions[i];
|
||||
if ((!tag) || (tag == a.tag))
|
||||
{
|
||||
a();
|
||||
}
|
||||
else
|
||||
{
|
||||
newArray.push(a);
|
||||
}
|
||||
}
|
||||
deferredActions = newArray;
|
||||
}
|
||||
|
||||
function sendClientMessage(msg)
|
||||
{
|
||||
sendMessage(
|
||||
{
|
||||
type: "CLIENT_MESSAGE",
|
||||
payload: msg
|
||||
});
|
||||
}
|
||||
|
||||
function getCurrentRevisionNumber()
|
||||
{
|
||||
return rev;
|
||||
}
|
||||
|
||||
function getMissedChanges()
|
||||
{
|
||||
var obj = {};
|
||||
obj.userInfo = userSet[userId];
|
||||
obj.baseRev = rev;
|
||||
if (state == "COMMITTING" && stateMessage)
|
||||
{
|
||||
obj.committedChangeset = stateMessage.changeset;
|
||||
obj.committedChangesetAPool = stateMessage.apool;
|
||||
obj.committedChangesetSocketId = stateMessageSocketId;
|
||||
editor.applyPreparedChangesetToBase();
|
||||
}
|
||||
var userChangesData = editor.prepareUserChangeset();
|
||||
if (userChangesData.changeset)
|
||||
{
|
||||
obj.furtherChangeset = userChangesData.changeset;
|
||||
obj.furtherChangesetAPool = userChangesData.apool;
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
function setStateIdle()
|
||||
{
|
||||
state = "IDLE";
|
||||
callbacks.onInternalAction("newlyIdle");
|
||||
schedulePerhapsCallIdleFuncs();
|
||||
}
|
||||
|
||||
function callWhenNotCommitting(func)
|
||||
{
|
||||
idleFuncs.push(func);
|
||||
schedulePerhapsCallIdleFuncs();
|
||||
}
|
||||
|
||||
var idleFuncs = [];
|
||||
|
||||
function schedulePerhapsCallIdleFuncs()
|
||||
{
|
||||
setTimeout(function()
|
||||
{
|
||||
if (state == "IDLE")
|
||||
{
|
||||
while (idleFuncs.length > 0)
|
||||
{
|
||||
var f = idleFuncs.shift();
|
||||
f();
|
||||
}
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
|
||||
var self = {
|
||||
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;
|
||||
},
|
||||
updateUserInfo: defer(updateUserInfo),
|
||||
handleMessageFromServer: handleMessageFromServer,
|
||||
getConnectedUsers: getConnectedUsers,
|
||||
sendClientMessage: sendClientMessage,
|
||||
sendMessage: sendMessage,
|
||||
getCurrentRevisionNumber: getCurrentRevisionNumber,
|
||||
getMissedChanges: getMissedChanges,
|
||||
callWhenNotCommitting: callWhenNotCommitting,
|
||||
addHistoricalAuthors: tellAceAboutHistoricalAuthors,
|
||||
setChannelState: setChannelState
|
||||
};
|
||||
|
||||
$(document).ready(setUpSocket);
|
||||
return self;
|
||||
}
|
||||
|
||||
function selectElementContents(elem)
|
||||
{
|
||||
if ($.browser.msie)
|
||||
{
|
||||
var range = document.body.createTextRange();
|
||||
range.moveToElementText(elem);
|
||||
range.select();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (window.getSelection)
|
||||
{
|
||||
var browserSelection = window.getSelection();
|
||||
if (browserSelection)
|
||||
{
|
||||
var range = document.createRange();
|
||||
range.selectNodeContents(elem);
|
||||
browserSelection.removeAllRanges();
|
||||
browserSelection.addRange(range);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
exports.getCollabClient = getCollabClient;
|
||||
exports.selectElementContents = selectElementContents;
|
123
src/static/js/colorutils.js
Normal file
|
@ -0,0 +1,123 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
// DO NOT EDIT THIS FILE, edit infrastructure/ace/www/colorutils.js
|
||||
// THIS FILE IS ALSO SERVED AS CLIENT-SIDE JS
|
||||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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 colorutils = {};
|
||||
|
||||
// "#ffffff" or "#fff" or "ffffff" or "fff" to [1.0, 1.0, 1.0]
|
||||
colorutils.css2triple = function(cssColor)
|
||||
{
|
||||
var sixHex = colorutils.css2sixhex(cssColor);
|
||||
|
||||
function hexToFloat(hh)
|
||||
{
|
||||
return Number("0x" + hh) / 255;
|
||||
}
|
||||
return [hexToFloat(sixHex.substr(0, 2)), hexToFloat(sixHex.substr(2, 2)), hexToFloat(sixHex.substr(4, 2))];
|
||||
}
|
||||
|
||||
// "#ffffff" or "#fff" or "ffffff" or "fff" to "ffffff"
|
||||
colorutils.css2sixhex = function(cssColor)
|
||||
{
|
||||
var h = /[0-9a-fA-F]+/.exec(cssColor)[0];
|
||||
if (h.length != 6)
|
||||
{
|
||||
var a = h.charAt(0);
|
||||
var b = h.charAt(1);
|
||||
var c = h.charAt(2);
|
||||
h = a + a + b + b + c + c;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
// [1.0, 1.0, 1.0] -> "#ffffff"
|
||||
colorutils.triple2css = function(triple)
|
||||
{
|
||||
function floatToHex(n)
|
||||
{
|
||||
var n2 = colorutils.clamp(Math.round(n * 255), 0, 255);
|
||||
return ("0" + n2.toString(16)).slice(-2);
|
||||
}
|
||||
return "#" + floatToHex(triple[0]) + floatToHex(triple[1]) + floatToHex(triple[2]);
|
||||
}
|
||||
|
||||
|
||||
colorutils.clamp = function(v, bot, top)
|
||||
{
|
||||
return v < bot ? bot : (v > top ? top : v);
|
||||
};
|
||||
colorutils.min3 = function(a, b, c)
|
||||
{
|
||||
return (a < b) ? (a < c ? a : c) : (b < c ? b : c);
|
||||
};
|
||||
colorutils.max3 = function(a, b, c)
|
||||
{
|
||||
return (a > b) ? (a > c ? a : c) : (b > c ? b : c);
|
||||
};
|
||||
colorutils.colorMin = function(c)
|
||||
{
|
||||
return colorutils.min3(c[0], c[1], c[2]);
|
||||
};
|
||||
colorutils.colorMax = function(c)
|
||||
{
|
||||
return colorutils.max3(c[0], c[1], c[2]);
|
||||
};
|
||||
colorutils.scale = function(v, bot, top)
|
||||
{
|
||||
return colorutils.clamp(bot + v * (top - bot), 0, 1);
|
||||
};
|
||||
colorutils.unscale = function(v, bot, top)
|
||||
{
|
||||
return colorutils.clamp((v - bot) / (top - bot), 0, 1);
|
||||
};
|
||||
|
||||
colorutils.scaleColor = function(c, bot, top)
|
||||
{
|
||||
return [colorutils.scale(c[0], bot, top), colorutils.scale(c[1], bot, top), colorutils.scale(c[2], bot, top)];
|
||||
}
|
||||
|
||||
colorutils.unscaleColor = function(c, bot, top)
|
||||
{
|
||||
return [colorutils.unscale(c[0], bot, top), colorutils.unscale(c[1], bot, top), colorutils.unscale(c[2], bot, top)];
|
||||
}
|
||||
|
||||
colorutils.luminosity = function(c)
|
||||
{
|
||||
// rule of thumb for RGB brightness; 1.0 is white
|
||||
return c[0] * 0.30 + c[1] * 0.59 + c[2] * 0.11;
|
||||
}
|
||||
|
||||
colorutils.saturate = function(c)
|
||||
{
|
||||
var min = colorutils.colorMin(c);
|
||||
var max = colorutils.colorMax(c);
|
||||
if (max - min <= 0) return [1.0, 1.0, 1.0];
|
||||
return colorutils.unscaleColor(c, min, max);
|
||||
}
|
||||
|
||||
colorutils.blend = function(c1, c2, t)
|
||||
{
|
||||
return [colorutils.scale(t, c1[0], c2[0]), colorutils.scale(t, c1[1], c2[1]), colorutils.scale(t, c1[2], c2[2])];
|
||||
}
|
||||
|
||||
exports.colorutils = colorutils;
|
692
src/static/js/contentcollector.js
Normal file
|
@ -0,0 +1,692 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
// THIS FILE IS ALSO AN APPJET MODULE: etherpad.collab.ace.contentcollector
|
||||
// %APPJET%: import("etherpad.collab.ace.easysync2.Changeset");
|
||||
// %APPJET%: import("etherpad.admin.plugins");
|
||||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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 _MAX_LIST_LEVEL = 8;
|
||||
|
||||
var Changeset = require('/Changeset');
|
||||
var plugins = require('/plugins').plugins;
|
||||
|
||||
function sanitizeUnicode(s)
|
||||
{
|
||||
return s.replace(/[\uffff\ufffe\ufeff\ufdd0-\ufdef\ud800-\udfff]/g, '?');
|
||||
}
|
||||
|
||||
function makeContentCollector(collectStyles, browser, apool, domInterface, className2Author)
|
||||
{
|
||||
browser = browser || {};
|
||||
|
||||
var plugins_ = plugins;
|
||||
|
||||
var dom = domInterface || {
|
||||
isNodeText: function(n)
|
||||
{
|
||||
return (n.nodeType == 3);
|
||||
},
|
||||
nodeTagName: function(n)
|
||||
{
|
||||
return n.tagName;
|
||||
},
|
||||
nodeValue: function(n)
|
||||
{
|
||||
return n.nodeValue;
|
||||
},
|
||||
nodeNumChildren: function(n)
|
||||
{
|
||||
return n.childNodes.length;
|
||||
},
|
||||
nodeChild: function(n, i)
|
||||
{
|
||||
return n.childNodes.item(i);
|
||||
},
|
||||
nodeProp: function(n, p)
|
||||
{
|
||||
return n[p];
|
||||
},
|
||||
nodeAttr: function(n, a)
|
||||
{
|
||||
return n.getAttribute(a);
|
||||
},
|
||||
optNodeInnerHTML: function(n)
|
||||
{
|
||||
return n.innerHTML;
|
||||
}
|
||||
};
|
||||
|
||||
var _blockElems = {
|
||||
"div": 1,
|
||||
"p": 1,
|
||||
"pre": 1,
|
||||
"li": 1
|
||||
};
|
||||
|
||||
function isBlockElement(n)
|
||||
{
|
||||
return !!_blockElems[(dom.nodeTagName(n) || "").toLowerCase()];
|
||||
}
|
||||
|
||||
function textify(str)
|
||||
{
|
||||
return sanitizeUnicode(
|
||||
str.replace(/[\n\r ]/g, ' ').replace(/\xa0/g, ' ').replace(/\t/g, ' '));
|
||||
}
|
||||
|
||||
function getAssoc(node, name)
|
||||
{
|
||||
return dom.nodeProp(node, "_magicdom_" + name);
|
||||
}
|
||||
|
||||
var lines = (function()
|
||||
{
|
||||
var textArray = [];
|
||||
var attribsArray = [];
|
||||
var attribsBuilder = null;
|
||||
var op = Changeset.newOp('+');
|
||||
var self = {
|
||||
length: function()
|
||||
{
|
||||
return textArray.length;
|
||||
},
|
||||
atColumnZero: function()
|
||||
{
|
||||
return textArray[textArray.length - 1] === "";
|
||||
},
|
||||
startNew: function()
|
||||
{
|
||||
textArray.push("");
|
||||
self.flush(true);
|
||||
attribsBuilder = Changeset.smartOpAssembler();
|
||||
},
|
||||
textOfLine: function(i)
|
||||
{
|
||||
return textArray[i];
|
||||
},
|
||||
appendText: function(txt, attrString)
|
||||
{
|
||||
textArray[textArray.length - 1] += txt;
|
||||
//dmesg(txt+" / "+attrString);
|
||||
op.attribs = attrString;
|
||||
op.chars = txt.length;
|
||||
attribsBuilder.append(op);
|
||||
},
|
||||
textLines: function()
|
||||
{
|
||||
return textArray.slice();
|
||||
},
|
||||
attribLines: function()
|
||||
{
|
||||
return attribsArray;
|
||||
},
|
||||
// call flush only when you're done
|
||||
flush: function(withNewline)
|
||||
{
|
||||
if (attribsBuilder)
|
||||
{
|
||||
attribsArray.push(attribsBuilder.toString());
|
||||
attribsBuilder = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
self.startNew();
|
||||
return self;
|
||||
}());
|
||||
var cc = {};
|
||||
|
||||
function _ensureColumnZero(state)
|
||||
{
|
||||
if (!lines.atColumnZero())
|
||||
{
|
||||
cc.startNewLine(state);
|
||||
}
|
||||
}
|
||||
var selection, startPoint, endPoint;
|
||||
var selStart = [-1, -1],
|
||||
selEnd = [-1, -1];
|
||||
var blockElems = {
|
||||
"div": 1,
|
||||
"p": 1,
|
||||
"pre": 1
|
||||
};
|
||||
|
||||
function _isEmpty(node, state)
|
||||
{
|
||||
// consider clean blank lines pasted in IE to be empty
|
||||
if (dom.nodeNumChildren(node) == 0) return true;
|
||||
if (dom.nodeNumChildren(node) == 1 && getAssoc(node, "shouldBeEmpty") && dom.optNodeInnerHTML(node) == " " && !getAssoc(node, "unpasted"))
|
||||
{
|
||||
if (state)
|
||||
{
|
||||
var child = dom.nodeChild(node, 0);
|
||||
_reachPoint(child, 0, state);
|
||||
_reachPoint(child, 1, state);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function _pointHere(charsAfter, state)
|
||||
{
|
||||
var ln = lines.length() - 1;
|
||||
var chr = lines.textOfLine(ln).length;
|
||||
if (chr == 0 && state.listType && state.listType != 'none')
|
||||
{
|
||||
chr += 1; // listMarker
|
||||
}
|
||||
chr += charsAfter;
|
||||
return [ln, chr];
|
||||
}
|
||||
|
||||
function _reachBlockPoint(nd, idx, state)
|
||||
{
|
||||
if (!dom.isNodeText(nd)) _reachPoint(nd, idx, state);
|
||||
}
|
||||
|
||||
function _reachPoint(nd, idx, state)
|
||||
{
|
||||
if (startPoint && nd == startPoint.node && startPoint.index == idx)
|
||||
{
|
||||
selStart = _pointHere(0, state);
|
||||
}
|
||||
if (endPoint && nd == endPoint.node && endPoint.index == idx)
|
||||
{
|
||||
selEnd = _pointHere(0, state);
|
||||
}
|
||||
}
|
||||
cc.incrementFlag = function(state, flagName)
|
||||
{
|
||||
state.flags[flagName] = (state.flags[flagName] || 0) + 1;
|
||||
}
|
||||
cc.decrementFlag = function(state, flagName)
|
||||
{
|
||||
state.flags[flagName]--;
|
||||
}
|
||||
cc.incrementAttrib = function(state, attribName)
|
||||
{
|
||||
if (!state.attribs[attribName])
|
||||
{
|
||||
state.attribs[attribName] = 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
state.attribs[attribName]++;
|
||||
}
|
||||
_recalcAttribString(state);
|
||||
}
|
||||
cc.decrementAttrib = function(state, attribName)
|
||||
{
|
||||
state.attribs[attribName]--;
|
||||
_recalcAttribString(state);
|
||||
}
|
||||
|
||||
function _enterList(state, listType)
|
||||
{
|
||||
var oldListType = state.listType;
|
||||
state.listLevel = (state.listLevel || 0) + 1;
|
||||
if (listType != 'none')
|
||||
{
|
||||
state.listNesting = (state.listNesting || 0) + 1;
|
||||
}
|
||||
state.listType = listType;
|
||||
_recalcAttribString(state);
|
||||
return oldListType;
|
||||
}
|
||||
|
||||
function _exitList(state, oldListType)
|
||||
{
|
||||
state.listLevel--;
|
||||
if (state.listType != 'none')
|
||||
{
|
||||
state.listNesting--;
|
||||
}
|
||||
state.listType = oldListType;
|
||||
_recalcAttribString(state);
|
||||
}
|
||||
|
||||
function _enterAuthor(state, author)
|
||||
{
|
||||
var oldAuthor = state.author;
|
||||
state.authorLevel = (state.authorLevel || 0) + 1;
|
||||
state.author = author;
|
||||
_recalcAttribString(state);
|
||||
return oldAuthor;
|
||||
}
|
||||
|
||||
function _exitAuthor(state, oldAuthor)
|
||||
{
|
||||
state.authorLevel--;
|
||||
state.author = oldAuthor;
|
||||
_recalcAttribString(state);
|
||||
}
|
||||
|
||||
function _recalcAttribString(state)
|
||||
{
|
||||
var lst = [];
|
||||
for (var a in state.attribs)
|
||||
{
|
||||
if (state.attribs[a])
|
||||
{
|
||||
lst.push([a, 'true']);
|
||||
}
|
||||
}
|
||||
if (state.authorLevel > 0)
|
||||
{
|
||||
var authorAttrib = ['author', state.author];
|
||||
if (apool.putAttrib(authorAttrib, true) >= 0)
|
||||
{
|
||||
// require that author already be in pool
|
||||
// (don't add authors from other documents, etc.)
|
||||
lst.push(authorAttrib);
|
||||
}
|
||||
}
|
||||
state.attribString = Changeset.makeAttribsString('+', lst, apool);
|
||||
}
|
||||
|
||||
function _produceListMarker(state)
|
||||
{
|
||||
lines.appendText('*', Changeset.makeAttribsString('+', [
|
||||
['list', state.listType],
|
||||
['insertorder', 'first']
|
||||
], apool));
|
||||
}
|
||||
cc.startNewLine = function(state)
|
||||
{
|
||||
if (state)
|
||||
{
|
||||
var atBeginningOfLine = lines.textOfLine(lines.length() - 1).length == 0;
|
||||
if (atBeginningOfLine && state.listType && state.listType != 'none')
|
||||
{
|
||||
_produceListMarker(state);
|
||||
}
|
||||
}
|
||||
lines.startNew();
|
||||
}
|
||||
cc.notifySelection = function(sel)
|
||||
{
|
||||
if (sel)
|
||||
{
|
||||
selection = sel;
|
||||
startPoint = selection.startPoint;
|
||||
endPoint = selection.endPoint;
|
||||
}
|
||||
};
|
||||
cc.doAttrib = function(state, na)
|
||||
{
|
||||
state.localAttribs = (state.localAttribs || []);
|
||||
state.localAttribs.push(na);
|
||||
cc.incrementAttrib(state, na);
|
||||
};
|
||||
cc.collectContent = function(node, state)
|
||||
{
|
||||
if (!state)
|
||||
{
|
||||
state = {
|
||||
flags: { /*name -> nesting counter*/
|
||||
},
|
||||
localAttribs: null,
|
||||
attribs: { /*name -> nesting counter*/
|
||||
},
|
||||
attribString: ''
|
||||
};
|
||||
}
|
||||
var localAttribs = state.localAttribs;
|
||||
state.localAttribs = null;
|
||||
var isBlock = isBlockElement(node);
|
||||
var isEmpty = _isEmpty(node, state);
|
||||
if (isBlock) _ensureColumnZero(state);
|
||||
var startLine = lines.length() - 1;
|
||||
_reachBlockPoint(node, 0, state);
|
||||
if (dom.isNodeText(node))
|
||||
{
|
||||
var txt = dom.nodeValue(node);
|
||||
var rest = '';
|
||||
var x = 0; // offset into original text
|
||||
if (txt.length == 0)
|
||||
{
|
||||
if (startPoint && node == startPoint.node)
|
||||
{
|
||||
selStart = _pointHere(0, state);
|
||||
}
|
||||
if (endPoint && node == endPoint.node)
|
||||
{
|
||||
selEnd = _pointHere(0, state);
|
||||
}
|
||||
}
|
||||
while (txt.length > 0)
|
||||
{
|
||||
var consumed = 0;
|
||||
if (state.flags.preMode)
|
||||
{
|
||||
var firstLine = txt.split('\n', 1)[0];
|
||||
consumed = firstLine.length + 1;
|
||||
rest = txt.substring(consumed);
|
||||
txt = firstLine;
|
||||
}
|
||||
else
|
||||
{ /* will only run this loop body once */
|
||||
}
|
||||
if (startPoint && node == startPoint.node && startPoint.index - x <= txt.length)
|
||||
{
|
||||
selStart = _pointHere(startPoint.index - x, state);
|
||||
}
|
||||
if (endPoint && node == endPoint.node && endPoint.index - x <= txt.length)
|
||||
{
|
||||
selEnd = _pointHere(endPoint.index - x, state);
|
||||
}
|
||||
var txt2 = txt;
|
||||
if ((!state.flags.preMode) && /^[\r\n]*$/.exec(txt))
|
||||
{
|
||||
// prevents textnodes containing just "\n" from being significant
|
||||
// in safari when pasting text, now that we convert them to
|
||||
// spaces instead of removing them, because in other cases
|
||||
// removing "\n" from pasted HTML will collapse words together.
|
||||
txt2 = "";
|
||||
}
|
||||
var atBeginningOfLine = lines.textOfLine(lines.length() - 1).length == 0;
|
||||
if (atBeginningOfLine)
|
||||
{
|
||||
// newlines in the source mustn't become spaces at beginning of line box
|
||||
txt2 = txt2.replace(/^\n*/, '');
|
||||
}
|
||||
if (atBeginningOfLine && state.listType && state.listType != 'none')
|
||||
{
|
||||
_produceListMarker(state);
|
||||
}
|
||||
lines.appendText(textify(txt2), state.attribString);
|
||||
x += consumed;
|
||||
txt = rest;
|
||||
if (txt.length > 0)
|
||||
{
|
||||
cc.startNewLine(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var tname = (dom.nodeTagName(node) || "").toLowerCase();
|
||||
if (tname == "br")
|
||||
{
|
||||
cc.startNewLine(state);
|
||||
}
|
||||
else if (tname == "script" || tname == "style")
|
||||
{
|
||||
// ignore
|
||||
}
|
||||
else if (!isEmpty)
|
||||
{
|
||||
var styl = dom.nodeAttr(node, "style");
|
||||
var cls = dom.nodeProp(node, "className");
|
||||
|
||||
var isPre = (tname == "pre");
|
||||
if ((!isPre) && browser.safari)
|
||||
{
|
||||
isPre = (styl && /\bwhite-space:\s*pre\b/i.exec(styl));
|
||||
}
|
||||
if (isPre) cc.incrementFlag(state, 'preMode');
|
||||
var oldListTypeOrNull = null;
|
||||
var oldAuthorOrNull = null;
|
||||
if (collectStyles)
|
||||
{
|
||||
plugins_.callHook('collectContentPre', {
|
||||
cc: cc,
|
||||
state: state,
|
||||
tname: tname,
|
||||
styl: styl,
|
||||
cls: cls
|
||||
});
|
||||
if (tname == "b" || (styl && /\bfont-weight:\s*bold\b/i.exec(styl)) || tname == "strong")
|
||||
{
|
||||
cc.doAttrib(state, "bold");
|
||||
}
|
||||
if (tname == "i" || (styl && /\bfont-style:\s*italic\b/i.exec(styl)) || tname == "em")
|
||||
{
|
||||
cc.doAttrib(state, "italic");
|
||||
}
|
||||
if (tname == "u" || (styl && /\btext-decoration:\s*underline\b/i.exec(styl)) || tname == "ins")
|
||||
{
|
||||
cc.doAttrib(state, "underline");
|
||||
}
|
||||
if (tname == "s" || (styl && /\btext-decoration:\s*line-through\b/i.exec(styl)) || tname == "del")
|
||||
{
|
||||
cc.doAttrib(state, "strikethrough");
|
||||
}
|
||||
if (tname == "ul" || tname == "ol")
|
||||
{
|
||||
var type;
|
||||
var rr = cls && /(?:^| )list-([a-z]+[12345678])\b/.exec(cls);
|
||||
type = rr && rr[1] || "bullet" + String(Math.min(_MAX_LIST_LEVEL, (state.listNesting || 0) + 1));
|
||||
oldListTypeOrNull = (_enterList(state, type) || 'none');
|
||||
}
|
||||
else if ((tname == "div" || tname == "p") && cls && cls.match(/(?:^| )ace-line\b/))
|
||||
{
|
||||
oldListTypeOrNull = (_enterList(state, type) || 'none');
|
||||
}
|
||||
if (className2Author && cls)
|
||||
{
|
||||
var classes = cls.match(/\S+/g);
|
||||
if (classes && classes.length > 0)
|
||||
{
|
||||
for (var i = 0; i < classes.length; i++)
|
||||
{
|
||||
var c = classes[i];
|
||||
var a = className2Author(c);
|
||||
if (a)
|
||||
{
|
||||
oldAuthorOrNull = (_enterAuthor(state, a) || 'none');
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var nc = dom.nodeNumChildren(node);
|
||||
for (var i = 0; i < nc; i++)
|
||||
{
|
||||
var c = dom.nodeChild(node, i);
|
||||
cc.collectContent(c, state);
|
||||
}
|
||||
|
||||
if (collectStyles)
|
||||
{
|
||||
plugins_.callHook('collectContentPost', {
|
||||
cc: cc,
|
||||
state: state,
|
||||
tname: tname,
|
||||
styl: styl,
|
||||
cls: cls
|
||||
});
|
||||
}
|
||||
|
||||
if (isPre) cc.decrementFlag(state, 'preMode');
|
||||
if (state.localAttribs)
|
||||
{
|
||||
for (var i = 0; i < state.localAttribs.length; i++)
|
||||
{
|
||||
cc.decrementAttrib(state, state.localAttribs[i]);
|
||||
}
|
||||
}
|
||||
if (oldListTypeOrNull)
|
||||
{
|
||||
_exitList(state, oldListTypeOrNull);
|
||||
}
|
||||
if (oldAuthorOrNull)
|
||||
{
|
||||
_exitAuthor(state, oldAuthorOrNull);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!browser.msie)
|
||||
{
|
||||
_reachBlockPoint(node, 1, state);
|
||||
}
|
||||
if (isBlock)
|
||||
{
|
||||
if (lines.length() - 1 == startLine)
|
||||
{
|
||||
cc.startNewLine(state);
|
||||
}
|
||||
else
|
||||
{
|
||||
_ensureColumnZero(state);
|
||||
}
|
||||
}
|
||||
|
||||
if (browser.msie)
|
||||
{
|
||||
// in IE, a point immediately after a DIV appears on the next line
|
||||
_reachBlockPoint(node, 1, state);
|
||||
}
|
||||
|
||||
state.localAttribs = localAttribs;
|
||||
};
|
||||
// can pass a falsy value for end of doc
|
||||
cc.notifyNextNode = function(node)
|
||||
{
|
||||
// an "empty block" won't end a line; this addresses an issue in IE with
|
||||
// typing into a blank line at the end of the document. typed text
|
||||
// goes into the body, and the empty line div still looks clean.
|
||||
// it is incorporated as dirty by the rule that a dirty region has
|
||||
// to end a line.
|
||||
if ((!node) || (isBlockElement(node) && !_isEmpty(node)))
|
||||
{
|
||||
_ensureColumnZero(null);
|
||||
}
|
||||
};
|
||||
// each returns [line, char] or [-1,-1]
|
||||
var getSelectionStart = function()
|
||||
{
|
||||
return selStart;
|
||||
};
|
||||
var getSelectionEnd = function()
|
||||
{
|
||||
return selEnd;
|
||||
};
|
||||
|
||||
// returns array of strings for lines found, last entry will be "" if
|
||||
// last line is complete (i.e. if a following span should be on a new line).
|
||||
// can be called at any point
|
||||
cc.getLines = function()
|
||||
{
|
||||
return lines.textLines();
|
||||
};
|
||||
|
||||
cc.finish = function()
|
||||
{
|
||||
lines.flush();
|
||||
var lineAttribs = lines.attribLines();
|
||||
var lineStrings = cc.getLines();
|
||||
|
||||
lineStrings.length--;
|
||||
lineAttribs.length--;
|
||||
|
||||
var ss = getSelectionStart();
|
||||
var se = getSelectionEnd();
|
||||
|
||||
function fixLongLines()
|
||||
{
|
||||
// design mode does not deal with with really long lines!
|
||||
var lineLimit = 2000; // chars
|
||||
var buffer = 10; // chars allowed over before wrapping
|
||||
var linesWrapped = 0;
|
||||
var numLinesAfter = 0;
|
||||
for (var i = lineStrings.length - 1; i >= 0; i--)
|
||||
{
|
||||
var oldString = lineStrings[i];
|
||||
var oldAttribString = lineAttribs[i];
|
||||
if (oldString.length > lineLimit + buffer)
|
||||
{
|
||||
var newStrings = [];
|
||||
var newAttribStrings = [];
|
||||
while (oldString.length > lineLimit)
|
||||
{
|
||||
//var semiloc = oldString.lastIndexOf(';', lineLimit-1);
|
||||
//var lengthToTake = (semiloc >= 0 ? (semiloc+1) : lineLimit);
|
||||
lengthToTake = lineLimit;
|
||||
newStrings.push(oldString.substring(0, lengthToTake));
|
||||
oldString = oldString.substring(lengthToTake);
|
||||
newAttribStrings.push(Changeset.subattribution(oldAttribString, 0, lengthToTake));
|
||||
oldAttribString = Changeset.subattribution(oldAttribString, lengthToTake);
|
||||
}
|
||||
if (oldString.length > 0)
|
||||
{
|
||||
newStrings.push(oldString);
|
||||
newAttribStrings.push(oldAttribString);
|
||||
}
|
||||
|
||||
function fixLineNumber(lineChar)
|
||||
{
|
||||
if (lineChar[0] < 0) return;
|
||||
var n = lineChar[0];
|
||||
var c = lineChar[1];
|
||||
if (n > i)
|
||||
{
|
||||
n += (newStrings.length - 1);
|
||||
}
|
||||
else if (n == i)
|
||||
{
|
||||
var a = 0;
|
||||
while (c > newStrings[a].length)
|
||||
{
|
||||
c -= newStrings[a].length;
|
||||
a++;
|
||||
}
|
||||
n += a;
|
||||
}
|
||||
lineChar[0] = n;
|
||||
lineChar[1] = c;
|
||||
}
|
||||
fixLineNumber(ss);
|
||||
fixLineNumber(se);
|
||||
linesWrapped++;
|
||||
numLinesAfter += newStrings.length;
|
||||
|
||||
newStrings.unshift(i, 1);
|
||||
lineStrings.splice.apply(lineStrings, newStrings);
|
||||
newAttribStrings.unshift(i, 1);
|
||||
lineAttribs.splice.apply(lineAttribs, newAttribStrings);
|
||||
}
|
||||
}
|
||||
return {
|
||||
linesWrapped: linesWrapped,
|
||||
numLinesAfter: numLinesAfter
|
||||
};
|
||||
}
|
||||
var wrapData = fixLongLines();
|
||||
|
||||
return {
|
||||
selStart: ss,
|
||||
selEnd: se,
|
||||
linesWrapped: wrapData.linesWrapped,
|
||||
numLinesAfter: wrapData.numLinesAfter,
|
||||
lines: lineStrings,
|
||||
lineAttribs: lineAttribs
|
||||
};
|
||||
}
|
||||
|
||||
return cc;
|
||||
}
|
||||
|
||||
exports.sanitizeUnicode = sanitizeUnicode;
|
||||
exports.makeContentCollector = makeContentCollector;
|
122
src/static/js/cssmanager.js
Normal file
|
@ -0,0 +1,122 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
function makeCSSManager(emptyStylesheetTitle, top)
|
||||
{
|
||||
|
||||
function getSheetByTitle(title, top)
|
||||
{
|
||||
if(top)
|
||||
var allSheets = window.parent.parent.document.styleSheets;
|
||||
else
|
||||
var allSheets = document.styleSheets;
|
||||
|
||||
for (var i = 0; i < allSheets.length; i++)
|
||||
{
|
||||
var s = allSheets[i];
|
||||
if (s.title == title)
|
||||
{
|
||||
return s;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/*function getSheetTagByTitle(title) {
|
||||
var allStyleTags = document.getElementsByTagName("style");
|
||||
for(var i=0;i<allStyleTags.length;i++) {
|
||||
var t = allStyleTags[i];
|
||||
if (t.title == title) {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}*/
|
||||
|
||||
var browserSheet = getSheetByTitle(emptyStylesheetTitle, top);
|
||||
//var browserTag = getSheetTagByTitle(emptyStylesheetTitle);
|
||||
|
||||
|
||||
function browserRules()
|
||||
{
|
||||
return (browserSheet.cssRules || browserSheet.rules);
|
||||
}
|
||||
|
||||
function browserDeleteRule(i)
|
||||
{
|
||||
if (browserSheet.deleteRule) browserSheet.deleteRule(i);
|
||||
else browserSheet.removeRule(i);
|
||||
}
|
||||
|
||||
function browserInsertRule(i, selector)
|
||||
{
|
||||
if (browserSheet.insertRule) browserSheet.insertRule(selector + ' {}', i);
|
||||
else browserSheet.addRule(selector, null, i);
|
||||
}
|
||||
var selectorList = [];
|
||||
|
||||
function indexOfSelector(selector)
|
||||
{
|
||||
for (var i = 0; i < selectorList.length; i++)
|
||||
{
|
||||
if (selectorList[i] == selector)
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function selectorStyle(selector)
|
||||
{
|
||||
var i = indexOfSelector(selector);
|
||||
if (i < 0)
|
||||
{
|
||||
// add selector
|
||||
browserInsertRule(0, selector);
|
||||
selectorList.splice(0, 0, selector);
|
||||
i = 0;
|
||||
}
|
||||
return browserRules().item(i).style;
|
||||
}
|
||||
|
||||
function removeSelectorStyle(selector)
|
||||
{
|
||||
var i = indexOfSelector(selector);
|
||||
if (i >= 0)
|
||||
{
|
||||
browserDeleteRule(i);
|
||||
selectorList.splice(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
selectorStyle: selectorStyle,
|
||||
removeSelectorStyle: removeSelectorStyle,
|
||||
info: function()
|
||||
{
|
||||
return selectorList.length + ":" + browserRules().length;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
exports.makeCSSManager = makeCSSManager;
|
290
src/static/js/domline.js
Normal file
|
@ -0,0 +1,290 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
// THIS FILE IS ALSO AN APPJET MODULE: etherpad.collab.ace.domline
|
||||
// %APPJET%: import("etherpad.admin.plugins");
|
||||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
// requires: top
|
||||
// requires: plugins
|
||||
// requires: undefined
|
||||
|
||||
var Security = require('/security');
|
||||
var plugins = require('/plugins').plugins;
|
||||
var map = require('/ace2_common').map;
|
||||
|
||||
var domline = {};
|
||||
domline.noop = function()
|
||||
{};
|
||||
domline.identity = function(x)
|
||||
{
|
||||
return x;
|
||||
};
|
||||
|
||||
domline.addToLineClass = function(lineClass, cls)
|
||||
{
|
||||
// an "empty span" at any point can be used to add classes to
|
||||
// the line, using line:className. otherwise, we ignore
|
||||
// the span.
|
||||
cls.replace(/\S+/g, function(c)
|
||||
{
|
||||
if (c.indexOf("line:") == 0)
|
||||
{
|
||||
// add class to line
|
||||
lineClass = (lineClass ? lineClass + ' ' : '') + c.substring(5);
|
||||
}
|
||||
});
|
||||
return lineClass;
|
||||
}
|
||||
|
||||
// if "document" is falsy we don't create a DOM node, just
|
||||
// an object with innerHTML and className
|
||||
domline.createDomLine = function(nonEmpty, doesWrap, optBrowser, optDocument)
|
||||
{
|
||||
var result = {
|
||||
node: null,
|
||||
appendSpan: domline.noop,
|
||||
prepareForAdd: domline.noop,
|
||||
notifyAdded: domline.noop,
|
||||
clearSpans: domline.noop,
|
||||
finishUpdate: domline.noop,
|
||||
lineMarker: 0
|
||||
};
|
||||
|
||||
var browser = (optBrowser || {});
|
||||
var document = optDocument;
|
||||
|
||||
if (document)
|
||||
{
|
||||
result.node = document.createElement("div");
|
||||
}
|
||||
else
|
||||
{
|
||||
result.node = {
|
||||
innerHTML: '',
|
||||
className: ''
|
||||
};
|
||||
}
|
||||
|
||||
var html = [];
|
||||
var preHtml, postHtml;
|
||||
var curHTML = null;
|
||||
|
||||
function processSpaces(s)
|
||||
{
|
||||
return domline.processSpaces(s, doesWrap);
|
||||
}
|
||||
var identity = domline.identity;
|
||||
var perTextNodeProcess = (doesWrap ? identity : processSpaces);
|
||||
var perHtmlLineProcess = (doesWrap ? processSpaces : identity);
|
||||
var lineClass = 'ace-line';
|
||||
result.appendSpan = function(txt, cls)
|
||||
{
|
||||
if (cls.indexOf('list') >= 0)
|
||||
{
|
||||
var listType = /(?:^| )list:(\S+)/.exec(cls);
|
||||
var start = /(?:^| )start:(\S+)/.exec(cls);
|
||||
if (listType)
|
||||
{
|
||||
listType = listType[1];
|
||||
start = start?'start="'+Security.escapeHTMLAttribute(start[1])+'"':'';
|
||||
if (listType)
|
||||
{
|
||||
if(listType.indexOf("number") < 0)
|
||||
{
|
||||
preHtml = '<ul class="list-' + Security.escapeHTMLAttribute(listType) + '"><li>';
|
||||
postHtml = '</li></ul>';
|
||||
}
|
||||
else
|
||||
{
|
||||
preHtml = '<ol '+start+' class="list-' + Security.escapeHTMLAttribute(listType) + '"><li>';
|
||||
postHtml = '</li></ol>';
|
||||
}
|
||||
}
|
||||
result.lineMarker += txt.length;
|
||||
return; // don't append any text
|
||||
}
|
||||
}
|
||||
var href = null;
|
||||
var simpleTags = null;
|
||||
if (cls.indexOf('url') >= 0)
|
||||
{
|
||||
cls = cls.replace(/(^| )url:(\S+)/g, function(x0, space, url)
|
||||
{
|
||||
href = url;
|
||||
return space + "url";
|
||||
});
|
||||
}
|
||||
if (cls.indexOf('tag') >= 0)
|
||||
{
|
||||
cls = cls.replace(/(^| )tag:(\S+)/g, function(x0, space, tag)
|
||||
{
|
||||
if (!simpleTags) simpleTags = [];
|
||||
simpleTags.push(tag.toLowerCase());
|
||||
return space + tag;
|
||||
});
|
||||
}
|
||||
|
||||
var extraOpenTags = "";
|
||||
var extraCloseTags = "";
|
||||
|
||||
var plugins_ = plugins;
|
||||
|
||||
map(plugins_.callHook("aceCreateDomLine", {
|
||||
domline: domline,
|
||||
cls: cls
|
||||
}), function(modifier)
|
||||
{
|
||||
cls = modifier.cls;
|
||||
extraOpenTags = extraOpenTags + modifier.extraOpenTags;
|
||||
extraCloseTags = modifier.extraCloseTags + extraCloseTags;
|
||||
});
|
||||
|
||||
if ((!txt) && cls)
|
||||
{
|
||||
lineClass = domline.addToLineClass(lineClass, cls);
|
||||
}
|
||||
else if (txt)
|
||||
{
|
||||
if (href)
|
||||
{
|
||||
if(!~href.indexOf("http")) // if the url doesn't include http or https etc prefix it.
|
||||
{
|
||||
href = "http://"+href;
|
||||
}
|
||||
extraOpenTags = extraOpenTags + '<a href="' + Security.escapeHTMLAttribute(href) + '">';
|
||||
extraCloseTags = '</a>' + extraCloseTags;
|
||||
}
|
||||
if (simpleTags)
|
||||
{
|
||||
simpleTags.sort();
|
||||
extraOpenTags = extraOpenTags + '<' + simpleTags.join('><') + '>';
|
||||
simpleTags.reverse();
|
||||
extraCloseTags = '</' + simpleTags.join('></') + '>' + extraCloseTags;
|
||||
}
|
||||
html.push('<span class="', Security.escapeHTMLAttribute(cls || ''), '">', extraOpenTags, perTextNodeProcess(Security.escapeHTML(txt)), extraCloseTags, '</span>');
|
||||
}
|
||||
};
|
||||
result.clearSpans = function()
|
||||
{
|
||||
html = [];
|
||||
lineClass = ''; // non-null to cause update
|
||||
result.lineMarker = 0;
|
||||
};
|
||||
|
||||
function writeHTML()
|
||||
{
|
||||
var newHTML = perHtmlLineProcess(html.join(''));
|
||||
if (!newHTML)
|
||||
{
|
||||
if ((!document) || (!optBrowser))
|
||||
{
|
||||
newHTML += ' ';
|
||||
}
|
||||
else if (!browser.msie)
|
||||
{
|
||||
newHTML += '<br/>';
|
||||
}
|
||||
}
|
||||
if (nonEmpty)
|
||||
{
|
||||
newHTML = (preHtml || '') + newHTML + (postHtml || '');
|
||||
}
|
||||
html = preHtml = postHtml = null; // free memory
|
||||
if (newHTML !== curHTML)
|
||||
{
|
||||
curHTML = newHTML;
|
||||
result.node.innerHTML = curHTML;
|
||||
}
|
||||
if (lineClass !== null) result.node.className = lineClass;
|
||||
}
|
||||
result.prepareForAdd = writeHTML;
|
||||
result.finishUpdate = writeHTML;
|
||||
result.getInnerHTML = function()
|
||||
{
|
||||
return curHTML || '';
|
||||
};
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
domline.processSpaces = function(s, doesWrap)
|
||||
{
|
||||
if (s.indexOf("<") < 0 && !doesWrap)
|
||||
{
|
||||
// short-cut
|
||||
return s.replace(/ /g, ' ');
|
||||
}
|
||||
var parts = [];
|
||||
s.replace(/<[^>]*>?| |[^ <]+/g, function(m)
|
||||
{
|
||||
parts.push(m);
|
||||
});
|
||||
if (doesWrap)
|
||||
{
|
||||
var endOfLine = true;
|
||||
var beforeSpace = false;
|
||||
// last space in a run is normal, others are nbsp,
|
||||
// end of line is nbsp
|
||||
for (var i = parts.length - 1; i >= 0; i--)
|
||||
{
|
||||
var p = parts[i];
|
||||
if (p == " ")
|
||||
{
|
||||
if (endOfLine || beforeSpace) parts[i] = ' ';
|
||||
endOfLine = false;
|
||||
beforeSpace = true;
|
||||
}
|
||||
else if (p.charAt(0) != "<")
|
||||
{
|
||||
endOfLine = false;
|
||||
beforeSpace = false;
|
||||
}
|
||||
}
|
||||
// beginning of line is nbsp
|
||||
for (var i = 0; i < parts.length; i++)
|
||||
{
|
||||
var p = parts[i];
|
||||
if (p == " ")
|
||||
{
|
||||
parts[i] = ' ';
|
||||
break;
|
||||
}
|
||||
else if (p.charAt(0) != "<")
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (var i = 0; i < parts.length; i++)
|
||||
{
|
||||
var p = parts[i];
|
||||
if (p == " ")
|
||||
{
|
||||
parts[i] = ' ';
|
||||
}
|
||||
}
|
||||
}
|
||||
return parts.join('');
|
||||
};
|
||||
|
||||
exports.domline = domline;
|
197
src/static/js/draggable.js
Normal file
|
@ -0,0 +1,197 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
function makeDraggable(jqueryNodes, eventHandler)
|
||||
{
|
||||
jqueryNodes.each(function()
|
||||
{
|
||||
var node = $(this);
|
||||
var state = {};
|
||||
var inDrag = false;
|
||||
|
||||
function dragStart(evt)
|
||||
{
|
||||
if (inDrag)
|
||||
{
|
||||
return;
|
||||
}
|
||||
inDrag = true;
|
||||
if (eventHandler('dragstart', evt, state) !== false)
|
||||
{
|
||||
$(document).bind('mousemove', dragUpdate);
|
||||
$(document).bind('mouseup', dragEnd);
|
||||
}
|
||||
evt.preventDefault();
|
||||
return false;
|
||||
}
|
||||
|
||||
function dragUpdate(evt)
|
||||
{
|
||||
if (!inDrag)
|
||||
{
|
||||
return;
|
||||
}
|
||||
eventHandler('dragupdate', evt, state);
|
||||
evt.preventDefault();
|
||||
return false;
|
||||
}
|
||||
|
||||
function dragEnd(evt)
|
||||
{
|
||||
if (!inDrag)
|
||||
{
|
||||
return;
|
||||
}
|
||||
inDrag = false;
|
||||
try
|
||||
{
|
||||
eventHandler('dragend', evt, state);
|
||||
}
|
||||
finally
|
||||
{
|
||||
$(document).unbind('mousemove', dragUpdate);
|
||||
$(document).unbind('mouseup', dragEnd);
|
||||
evt.preventDefault();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
node.bind('mousedown', dragStart);
|
||||
});
|
||||
}
|
||||
|
||||
function makeResizableVPane(top, sep, bottom, minTop, minBottom, callback)
|
||||
{
|
||||
if (minTop === undefined) minTop = 0;
|
||||
if (minBottom === undefined) minBottom = 0;
|
||||
|
||||
makeDraggable($(sep), function(eType, evt, state)
|
||||
{
|
||||
if (eType == 'dragstart')
|
||||
{
|
||||
state.startY = evt.pageY;
|
||||
state.topHeight = $(top).height();
|
||||
state.bottomHeight = $(bottom).height();
|
||||
state.minTop = minTop;
|
||||
state.maxTop = (state.topHeight + state.bottomHeight) - minBottom;
|
||||
}
|
||||
else if (eType == 'dragupdate')
|
||||
{
|
||||
var change = evt.pageY - state.startY;
|
||||
|
||||
var topHeight = state.topHeight + change;
|
||||
if (topHeight < state.minTop)
|
||||
{
|
||||
topHeight = state.minTop;
|
||||
}
|
||||
if (topHeight > state.maxTop)
|
||||
{
|
||||
topHeight = state.maxTop;
|
||||
}
|
||||
change = topHeight - state.topHeight;
|
||||
|
||||
var bottomHeight = state.bottomHeight - change;
|
||||
var sepHeight = $(sep).height();
|
||||
|
||||
var totalHeight = topHeight + sepHeight + bottomHeight;
|
||||
topHeight = 100.0 * topHeight / totalHeight;
|
||||
sepHeight = 100.0 * sepHeight / totalHeight;
|
||||
bottomHeight = 100.0 * bottomHeight / totalHeight;
|
||||
|
||||
$(top).css('bottom', 'auto');
|
||||
$(top).css('height', topHeight + "%");
|
||||
$(sep).css('top', topHeight + "%");
|
||||
$(bottom).css('top', (topHeight + sepHeight) + '%');
|
||||
$(bottom).css('height', 'auto');
|
||||
if (callback) callback();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function makeResizableHPane(left, sep, right, minLeft, minRight, sepWidth, sepOffset, callback)
|
||||
{
|
||||
if (minLeft === undefined) minLeft = 0;
|
||||
if (minRight === undefined) minRight = 0;
|
||||
|
||||
makeDraggable($(sep), function(eType, evt, state)
|
||||
{
|
||||
if (eType == 'dragstart')
|
||||
{
|
||||
state.startX = evt.pageX;
|
||||
state.leftWidth = $(left).width();
|
||||
state.rightWidth = $(right).width();
|
||||
state.minLeft = minLeft;
|
||||
state.maxLeft = (state.leftWidth + state.rightWidth) - minRight;
|
||||
}
|
||||
else if (eType == 'dragend' || eType == 'dragupdate')
|
||||
{
|
||||
var change = evt.pageX - state.startX;
|
||||
|
||||
var leftWidth = state.leftWidth + change;
|
||||
if (leftWidth < state.minLeft)
|
||||
{
|
||||
leftWidth = state.minLeft;
|
||||
}
|
||||
if (leftWidth > state.maxLeft)
|
||||
{
|
||||
leftWidth = state.maxLeft;
|
||||
}
|
||||
change = leftWidth - state.leftWidth;
|
||||
|
||||
var rightWidth = state.rightWidth - change;
|
||||
newSepWidth = sepWidth;
|
||||
if (newSepWidth == undefined) newSepWidth = $(sep).width();
|
||||
newSepOffset = sepOffset;
|
||||
if (newSepOffset == undefined) newSepOffset = 0;
|
||||
|
||||
if (change == 0)
|
||||
{
|
||||
if (rightWidth != minRight || state.lastRightWidth == undefined)
|
||||
{
|
||||
state.lastRightWidth = rightWidth;
|
||||
rightWidth = minRight;
|
||||
}
|
||||
else
|
||||
{
|
||||
rightWidth = state.lastRightWidth;
|
||||
state.lastRightWidth = minRight;
|
||||
}
|
||||
change = state.rightWidth - rightWidth;
|
||||
leftWidth = change + state.leftWidth;
|
||||
}
|
||||
|
||||
var totalWidth = leftWidth + newSepWidth + rightWidth;
|
||||
leftWidth = 100.0 * leftWidth / totalWidth;
|
||||
newSepWidth = 100.0 * newSepWidth / totalWidth;
|
||||
newSepOffset = 100.0 * newSepOffset / totalWidth;
|
||||
rightWidth = 100.0 * rightWidth / totalWidth;
|
||||
|
||||
$(left).css('right', 'auto');
|
||||
$(left).css('width', leftWidth + "%");
|
||||
$(sep).css('left', (leftWidth + newSepOffset) + "%");
|
||||
$(right).css('left', (leftWidth + newSepWidth) + '%');
|
||||
$(right).css('width', 'auto');
|
||||
if (callback) callback();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
exports.makeDraggable = makeDraggable;
|
35
src/static/js/excanvas.js
Normal file
|
@ -0,0 +1,35 @@
|
|||
// Copyright 2006 Google Inc.
|
||||
//
|
||||
// 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.
|
||||
document.createElement("canvas").getContext||(function(){var s=Math,j=s.round,F=s.sin,G=s.cos,V=s.abs,W=s.sqrt,k=10,v=k/2;function X(){return this.context_||(this.context_=new H(this))}var L=Array.prototype.slice;function Y(b,a){var c=L.call(arguments,2);return function(){return b.apply(a,c.concat(L.call(arguments)))}}var M={init:function(b){if(/MSIE/.test(navigator.userAgent)&&!window.opera){var a=b||document;a.createElement("canvas");a.attachEvent("onreadystatechange",Y(this.init_,this,a))}},init_:function(b){b.namespaces.g_vml_||
|
||||
b.namespaces.add("g_vml_","urn:schemas-microsoft-com:vml","#default#VML");b.namespaces.g_o_||b.namespaces.add("g_o_","urn:schemas-microsoft-com:office:office","#default#VML");if(!b.styleSheets.ex_canvas_){var a=b.createStyleSheet();a.owningElement.id="ex_canvas_";a.cssText="canvas{display:inline-block;overflow:hidden;text-align:left;width:300px;height:150px}g_vml_\\:*{behavior:url(#default#VML)}g_o_\\:*{behavior:url(#default#VML)}"}var c=b.getElementsByTagName("canvas"),d=0;for(;d<c.length;d++)this.initElement(c[d])},
|
||||
initElement:function(b){if(!b.getContext){b.getContext=X;b.innerHTML="";b.attachEvent("onpropertychange",Z);b.attachEvent("onresize",$);var a=b.attributes;if(a.width&&a.width.specified)b.style.width=a.width.nodeValue+"px";else b.width=b.clientWidth;if(a.height&&a.height.specified)b.style.height=a.height.nodeValue+"px";else b.height=b.clientHeight}return b}};function Z(b){var a=b.srcElement;switch(b.propertyName){case "width":a.style.width=a.attributes.width.nodeValue+"px";a.getContext().clearRect();
|
||||
break;case "height":a.style.height=a.attributes.height.nodeValue+"px";a.getContext().clearRect();break}}function $(b){var a=b.srcElement;if(a.firstChild){a.firstChild.style.width=a.clientWidth+"px";a.firstChild.style.height=a.clientHeight+"px"}}M.init();var N=[],B=0;for(;B<16;B++){var C=0;for(;C<16;C++)N[B*16+C]=B.toString(16)+C.toString(16)}function I(){return[[1,0,0],[0,1,0],[0,0,1]]}function y(b,a){var c=I(),d=0;for(;d<3;d++){var f=0;for(;f<3;f++){var h=0,g=0;for(;g<3;g++)h+=b[d][g]*a[g][f];c[d][f]=
|
||||
h}}return c}function O(b,a){a.fillStyle=b.fillStyle;a.lineCap=b.lineCap;a.lineJoin=b.lineJoin;a.lineWidth=b.lineWidth;a.miterLimit=b.miterLimit;a.shadowBlur=b.shadowBlur;a.shadowColor=b.shadowColor;a.shadowOffsetX=b.shadowOffsetX;a.shadowOffsetY=b.shadowOffsetY;a.strokeStyle=b.strokeStyle;a.globalAlpha=b.globalAlpha;a.arcScaleX_=b.arcScaleX_;a.arcScaleY_=b.arcScaleY_;a.lineScale_=b.lineScale_}function P(b){var a,c=1;b=String(b);if(b.substring(0,3)=="rgb"){var d=b.indexOf("(",3),f=b.indexOf(")",d+
|
||||
1),h=b.substring(d+1,f).split(",");a="#";var g=0;for(;g<3;g++)a+=N[Number(h[g])];if(h.length==4&&b.substr(3,1)=="a")c=h[3]}else a=b;return{color:a,alpha:c}}function aa(b){switch(b){case "butt":return"flat";case "round":return"round";case "square":default:return"square"}}function H(b){this.m_=I();this.mStack_=[];this.aStack_=[];this.currentPath_=[];this.fillStyle=this.strokeStyle="#000";this.lineWidth=1;this.lineJoin="miter";this.lineCap="butt";this.miterLimit=k*1;this.globalAlpha=1;this.canvas=b;
|
||||
var a=b.ownerDocument.createElement("div");a.style.width=b.clientWidth+"px";a.style.height=b.clientHeight+"px";a.style.overflow="hidden";a.style.position="absolute";b.appendChild(a);this.element_=a;this.lineScale_=this.arcScaleY_=this.arcScaleX_=1}var i=H.prototype;i.clearRect=function(){this.element_.innerHTML=""};i.beginPath=function(){this.currentPath_=[]};i.moveTo=function(b,a){var c=this.getCoords_(b,a);this.currentPath_.push({type:"moveTo",x:c.x,y:c.y});this.currentX_=c.x;this.currentY_=c.y};
|
||||
i.lineTo=function(b,a){var c=this.getCoords_(b,a);this.currentPath_.push({type:"lineTo",x:c.x,y:c.y});this.currentX_=c.x;this.currentY_=c.y};i.bezierCurveTo=function(b,a,c,d,f,h){var g=this.getCoords_(f,h),l=this.getCoords_(b,a),e=this.getCoords_(c,d);Q(this,l,e,g)};function Q(b,a,c,d){b.currentPath_.push({type:"bezierCurveTo",cp1x:a.x,cp1y:a.y,cp2x:c.x,cp2y:c.y,x:d.x,y:d.y});b.currentX_=d.x;b.currentY_=d.y}i.quadraticCurveTo=function(b,a,c,d){var f=this.getCoords_(b,a),h=this.getCoords_(c,d),g={x:this.currentX_+
|
||||
0.6666666666666666*(f.x-this.currentX_),y:this.currentY_+0.6666666666666666*(f.y-this.currentY_)};Q(this,g,{x:g.x+(h.x-this.currentX_)/3,y:g.y+(h.y-this.currentY_)/3},h)};i.arc=function(b,a,c,d,f,h){c*=k;var g=h?"at":"wa",l=b+G(d)*c-v,e=a+F(d)*c-v,m=b+G(f)*c-v,r=a+F(f)*c-v;if(l==m&&!h)l+=0.125;var n=this.getCoords_(b,a),o=this.getCoords_(l,e),q=this.getCoords_(m,r);this.currentPath_.push({type:g,x:n.x,y:n.y,radius:c,xStart:o.x,yStart:o.y,xEnd:q.x,yEnd:q.y})};i.rect=function(b,a,c,d){this.moveTo(b,
|
||||
a);this.lineTo(b+c,a);this.lineTo(b+c,a+d);this.lineTo(b,a+d);this.closePath()};i.strokeRect=function(b,a,c,d){var f=this.currentPath_;this.beginPath();this.moveTo(b,a);this.lineTo(b+c,a);this.lineTo(b+c,a+d);this.lineTo(b,a+d);this.closePath();this.stroke();this.currentPath_=f};i.fillRect=function(b,a,c,d){var f=this.currentPath_;this.beginPath();this.moveTo(b,a);this.lineTo(b+c,a);this.lineTo(b+c,a+d);this.lineTo(b,a+d);this.closePath();this.fill();this.currentPath_=f};i.createLinearGradient=function(b,
|
||||
a,c,d){var f=new D("gradient");f.x0_=b;f.y0_=a;f.x1_=c;f.y1_=d;return f};i.createRadialGradient=function(b,a,c,d,f,h){var g=new D("gradientradial");g.x0_=b;g.y0_=a;g.r0_=c;g.x1_=d;g.y1_=f;g.r1_=h;return g};i.drawImage=function(b){var a,c,d,f,h,g,l,e,m=b.runtimeStyle.width,r=b.runtimeStyle.height;b.runtimeStyle.width="auto";b.runtimeStyle.height="auto";var n=b.width,o=b.height;b.runtimeStyle.width=m;b.runtimeStyle.height=r;if(arguments.length==3){a=arguments[1];c=arguments[2];h=g=0;l=d=n;e=f=o}else if(arguments.length==
|
||||
5){a=arguments[1];c=arguments[2];d=arguments[3];f=arguments[4];h=g=0;l=n;e=o}else if(arguments.length==9){h=arguments[1];g=arguments[2];l=arguments[3];e=arguments[4];a=arguments[5];c=arguments[6];d=arguments[7];f=arguments[8]}else throw Error("Invalid number of arguments");var q=this.getCoords_(a,c),t=[];t.push(" <g_vml_:group",' coordsize="',k*10,",",k*10,'"',' coordorigin="0,0"',' style="width:',10,"px;height:",10,"px;position:absolute;");if(this.m_[0][0]!=1||this.m_[0][1]){var E=[];E.push("M11=",
|
||||
this.m_[0][0],",","M12=",this.m_[1][0],",","M21=",this.m_[0][1],",","M22=",this.m_[1][1],",","Dx=",j(q.x/k),",","Dy=",j(q.y/k),"");var p=q,z=this.getCoords_(a+d,c),w=this.getCoords_(a,c+f),x=this.getCoords_(a+d,c+f);p.x=s.max(p.x,z.x,w.x,x.x);p.y=s.max(p.y,z.y,w.y,x.y);t.push("padding:0 ",j(p.x/k),"px ",j(p.y/k),"px 0;filter:progid:DXImageTransform.Microsoft.Matrix(",E.join(""),", sizingmethod='clip');")}else t.push("top:",j(q.y/k),"px;left:",j(q.x/k),"px;");t.push(' ">','<g_vml_:image src="',b.src,
|
||||
'"',' style="width:',k*d,"px;"," height:",k*f,'px;"',' cropleft="',h/n,'"',' croptop="',g/o,'"',' cropright="',(n-h-l)/n,'"',' cropbottom="',(o-g-e)/o,'"'," />","</g_vml_:group>");this.element_.insertAdjacentHTML("BeforeEnd",t.join(""))};i.stroke=function(b){var a=[],c=P(b?this.fillStyle:this.strokeStyle),d=c.color,f=c.alpha*this.globalAlpha;a.push("<g_vml_:shape",' filled="',!!b,'"',' style="position:absolute;width:',10,"px;height:",10,'px;"',' coordorigin="0 0" coordsize="',k*10," ",k*10,'"',' stroked="',
|
||||
!b,'"',' path="');var h={x:null,y:null},g={x:null,y:null},l=0;for(;l<this.currentPath_.length;l++){var e=this.currentPath_[l];switch(e.type){case "moveTo":a.push(" m ",j(e.x),",",j(e.y));break;case "lineTo":a.push(" l ",j(e.x),",",j(e.y));break;case "close":a.push(" x ");e=null;break;case "bezierCurveTo":a.push(" c ",j(e.cp1x),",",j(e.cp1y),",",j(e.cp2x),",",j(e.cp2y),",",j(e.x),",",j(e.y));break;case "at":case "wa":a.push(" ",e.type," ",j(e.x-this.arcScaleX_*e.radius),",",j(e.y-this.arcScaleY_*e.radius),
|
||||
" ",j(e.x+this.arcScaleX_*e.radius),",",j(e.y+this.arcScaleY_*e.radius)," ",j(e.xStart),",",j(e.yStart)," ",j(e.xEnd),",",j(e.yEnd));break}if(e){if(h.x==null||e.x<h.x)h.x=e.x;if(g.x==null||e.x>g.x)g.x=e.x;if(h.y==null||e.y<h.y)h.y=e.y;if(g.y==null||e.y>g.y)g.y=e.y}}a.push(' ">');if(b)if(typeof this.fillStyle=="object"){var m=this.fillStyle,r=0,n={x:0,y:0},o=0,q=1;if(m.type_=="gradient"){var t=m.x1_/this.arcScaleX_,E=m.y1_/this.arcScaleY_,p=this.getCoords_(m.x0_/this.arcScaleX_,m.y0_/this.arcScaleY_),
|
||||
z=this.getCoords_(t,E);r=Math.atan2(z.x-p.x,z.y-p.y)*180/Math.PI;if(r<0)r+=360;if(r<1.0E-6)r=0}else{var p=this.getCoords_(m.x0_,m.y0_),w=g.x-h.x,x=g.y-h.y;n={x:(p.x-h.x)/w,y:(p.y-h.y)/x};w/=this.arcScaleX_*k;x/=this.arcScaleY_*k;var R=s.max(w,x);o=2*m.r0_/R;q=2*m.r1_/R-o}var u=m.colors_;u.sort(function(ba,ca){return ba.offset-ca.offset});var J=u.length,da=u[0].color,ea=u[J-1].color,fa=u[0].alpha*this.globalAlpha,ga=u[J-1].alpha*this.globalAlpha,S=[],l=0;for(;l<J;l++){var T=u[l];S.push(T.offset*q+
|
||||
o+" "+T.color)}a.push('<g_vml_:fill type="',m.type_,'"',' method="none" focus="100%"',' color="',da,'"',' color2="',ea,'"',' colors="',S.join(","),'"',' opacity="',ga,'"',' g_o_:opacity2="',fa,'"',' angle="',r,'"',' focusposition="',n.x,",",n.y,'" />')}else a.push('<g_vml_:fill color="',d,'" opacity="',f,'" />');else{var K=this.lineScale_*this.lineWidth;if(K<1)f*=K;a.push("<g_vml_:stroke",' opacity="',f,'"',' joinstyle="',this.lineJoin,'"',' miterlimit="',this.miterLimit,'"',' endcap="',aa(this.lineCap),
|
||||
'"',' weight="',K,'px"',' color="',d,'" />')}a.push("</g_vml_:shape>");this.element_.insertAdjacentHTML("beforeEnd",a.join(""))};i.fill=function(){this.stroke(true)};i.closePath=function(){this.currentPath_.push({type:"close"})};i.getCoords_=function(b,a){var c=this.m_;return{x:k*(b*c[0][0]+a*c[1][0]+c[2][0])-v,y:k*(b*c[0][1]+a*c[1][1]+c[2][1])-v}};i.save=function(){var b={};O(this,b);this.aStack_.push(b);this.mStack_.push(this.m_);this.m_=y(I(),this.m_)};i.restore=function(){O(this.aStack_.pop(),
|
||||
this);this.m_=this.mStack_.pop()};function ha(b){var a=0;for(;a<3;a++){var c=0;for(;c<2;c++)if(!isFinite(b[a][c])||isNaN(b[a][c]))return false}return true}function A(b,a,c){if(!!ha(a)){b.m_=a;if(c)b.lineScale_=W(V(a[0][0]*a[1][1]-a[0][1]*a[1][0]))}}i.translate=function(b,a){A(this,y([[1,0,0],[0,1,0],[b,a,1]],this.m_),false)};i.rotate=function(b){var a=G(b),c=F(b);A(this,y([[a,c,0],[-c,a,0],[0,0,1]],this.m_),false)};i.scale=function(b,a){this.arcScaleX_*=b;this.arcScaleY_*=a;A(this,y([[b,0,0],[0,a,
|
||||
0],[0,0,1]],this.m_),true)};i.transform=function(b,a,c,d,f,h){A(this,y([[b,a,0],[c,d,0],[f,h,1]],this.m_),true)};i.setTransform=function(b,a,c,d,f,h){A(this,[[b,a,0],[c,d,0],[f,h,1]],true)};i.clip=function(){};i.arcTo=function(){};i.createPattern=function(){return new U};function D(b){this.type_=b;this.r1_=this.y1_=this.x1_=this.r0_=this.y0_=this.x0_=0;this.colors_=[]}D.prototype.addColorStop=function(b,a){a=P(a);this.colors_.push({offset:b,color:a.color,alpha:a.alpha})};function U(){}G_vmlCanvasManager=
|
||||
M;CanvasRenderingContext2D=H;CanvasGradient=D;CanvasPattern=U})();
|
524
src/static/js/farbtastic.js
Normal file
|
@ -0,0 +1,524 @@
|
|||
// Farbtastic 2.0 alpha
|
||||
(function ($) {
|
||||
|
||||
var __debug = false;
|
||||
var __factor = 0.5;
|
||||
|
||||
$.fn.farbtastic = function (options) {
|
||||
$.farbtastic(this, options);
|
||||
return this;
|
||||
};
|
||||
|
||||
$.farbtastic = function (container, options) {
|
||||
var container = $(container)[0];
|
||||
return container.farbtastic || (container.farbtastic = new $._farbtastic(container, options));
|
||||
}
|
||||
|
||||
$._farbtastic = function (container, options) {
|
||||
var fb = this;
|
||||
|
||||
/////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Link to the given element(s) or callback.
|
||||
*/
|
||||
fb.linkTo = function (callback) {
|
||||
// Unbind previous nodes
|
||||
if (typeof fb.callback == 'object') {
|
||||
$(fb.callback).unbind('keyup', fb.updateValue);
|
||||
}
|
||||
|
||||
// Reset color
|
||||
fb.color = null;
|
||||
|
||||
// Bind callback or elements
|
||||
if (typeof callback == 'function') {
|
||||
fb.callback = callback;
|
||||
}
|
||||
else if (typeof callback == 'object' || typeof callback == 'string') {
|
||||
fb.callback = $(callback);
|
||||
fb.callback.bind('keyup', fb.updateValue);
|
||||
if (fb.callback[0].value) {
|
||||
fb.setColor(fb.callback[0].value);
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
fb.updateValue = function (event) {
|
||||
if (this.value && this.value != fb.color) {
|
||||
fb.setColor(this.value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Change color with HTML syntax #123456
|
||||
*/
|
||||
fb.setColor = function (color) {
|
||||
var unpack = fb.unpack(color);
|
||||
if (fb.color != color && unpack) {
|
||||
fb.color = color;
|
||||
fb.rgb = unpack;
|
||||
fb.hsl = fb.RGBToHSL(fb.rgb);
|
||||
fb.updateDisplay();
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Change color with HSL triplet [0..1, 0..1, 0..1]
|
||||
*/
|
||||
fb.setHSL = function (hsl) {
|
||||
fb.hsl = hsl;
|
||||
|
||||
var convertedHSL = [hsl[0]]
|
||||
convertedHSL[1] = hsl[1]*__factor+((1-__factor)/2);
|
||||
convertedHSL[2] = hsl[2]*__factor+((1-__factor)/2);
|
||||
|
||||
fb.rgb = fb.HSLToRGB(convertedHSL);
|
||||
fb.color = fb.pack(fb.rgb);
|
||||
fb.updateDisplay();
|
||||
return this;
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////
|
||||
//excanvas-compatible building of canvases
|
||||
fb._makeCanvas = function(className){
|
||||
var c = document.createElement('canvas');
|
||||
if (!c.getContext) { // excanvas hack
|
||||
c = window.G_vmlCanvasManager.initElement(c);
|
||||
c.getContext(); //this creates the excanvas children
|
||||
}
|
||||
$(c).addClass(className);
|
||||
return c;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the color picker widget.
|
||||
*/
|
||||
fb.initWidget = function () {
|
||||
|
||||
// Insert markup and size accordingly.
|
||||
var dim = {
|
||||
width: options.width,
|
||||
height: options.width
|
||||
};
|
||||
$(container)
|
||||
.html(
|
||||
'<div class="farbtastic" style="position: relative">' +
|
||||
'<div class="farbtastic-solid"></div>' +
|
||||
'</div>'
|
||||
)
|
||||
.children('.farbtastic')
|
||||
.append(fb._makeCanvas('farbtastic-mask'))
|
||||
.append(fb._makeCanvas('farbtastic-overlay'))
|
||||
.end()
|
||||
.find('*').attr(dim).css(dim).end()
|
||||
.find('div>*').css('position', 'absolute');
|
||||
|
||||
// Determine layout
|
||||
fb.radius = (options.width - options.wheelWidth) / 2 - 1;
|
||||
fb.square = Math.floor((fb.radius - options.wheelWidth / 2) * 0.7) - 1;
|
||||
fb.mid = Math.floor(options.width / 2);
|
||||
fb.markerSize = options.wheelWidth * 0.3;
|
||||
fb.solidFill = $('.farbtastic-solid', container).css({
|
||||
width: fb.square * 2 - 1,
|
||||
height: fb.square * 2 - 1,
|
||||
left: fb.mid - fb.square,
|
||||
top: fb.mid - fb.square
|
||||
});
|
||||
|
||||
// Set up drawing context.
|
||||
fb.cnvMask = $('.farbtastic-mask', container);
|
||||
fb.ctxMask = fb.cnvMask[0].getContext('2d');
|
||||
fb.cnvOverlay = $('.farbtastic-overlay', container);
|
||||
fb.ctxOverlay = fb.cnvOverlay[0].getContext('2d');
|
||||
fb.ctxMask.translate(fb.mid, fb.mid);
|
||||
fb.ctxOverlay.translate(fb.mid, fb.mid);
|
||||
|
||||
// Draw widget base layers.
|
||||
fb.drawCircle();
|
||||
fb.drawMask();
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw the color wheel.
|
||||
*/
|
||||
fb.drawCircle = function () {
|
||||
var tm = +(new Date());
|
||||
// Draw a hue circle with a bunch of gradient-stroked beziers.
|
||||
// Have to use beziers, as gradient-stroked arcs don't work.
|
||||
var n = 24,
|
||||
r = fb.radius,
|
||||
w = options.wheelWidth,
|
||||
nudge = 8 / r / n * Math.PI, // Fudge factor for seams.
|
||||
m = fb.ctxMask,
|
||||
angle1 = 0, color1, d1;
|
||||
m.save();
|
||||
m.lineWidth = w / r;
|
||||
m.scale(r, r);
|
||||
// Each segment goes from angle1 to angle2.
|
||||
for (var i = 0; i <= n; ++i) {
|
||||
var d2 = i / n,
|
||||
angle2 = d2 * Math.PI * 2,
|
||||
// Endpoints
|
||||
x1 = Math.sin(angle1), y1 = -Math.cos(angle1);
|
||||
x2 = Math.sin(angle2), y2 = -Math.cos(angle2),
|
||||
// Midpoint chosen so that the endpoints are tangent to the circle.
|
||||
am = (angle1 + angle2) / 2,
|
||||
tan = 1 / Math.cos((angle2 - angle1) / 2),
|
||||
xm = Math.sin(am) * tan, ym = -Math.cos(am) * tan,
|
||||
// New color
|
||||
color2 = fb.pack(fb.HSLToRGB([d2, 1, 0.5]));
|
||||
if (i > 0) {
|
||||
if ($.browser.msie) {
|
||||
// IE's gradient calculations mess up the colors. Correct along the diagonals.
|
||||
var corr = (1 + Math.min(Math.abs(Math.tan(angle1)), Math.abs(Math.tan(Math.PI / 2 - angle1)))) / n;
|
||||
color1 = fb.pack(fb.HSLToRGB([d1 - 0.15 * corr, 1, 0.5]));
|
||||
color2 = fb.pack(fb.HSLToRGB([d2 + 0.15 * corr, 1, 0.5]));
|
||||
// Create gradient fill between the endpoints.
|
||||
var grad = m.createLinearGradient(x1, y1, x2, y2);
|
||||
grad.addColorStop(0, color1);
|
||||
grad.addColorStop(1, color2);
|
||||
m.fillStyle = grad;
|
||||
// Draw quadratic curve segment as a fill.
|
||||
var r1 = (r + w / 2) / r, r2 = (r - w / 2) / r; // inner/outer radius.
|
||||
m.beginPath();
|
||||
m.moveTo(x1 * r1, y1 * r1);
|
||||
m.quadraticCurveTo(xm * r1, ym * r1, x2 * r1, y2 * r1);
|
||||
m.lineTo(x2 * r2, y2 * r2);
|
||||
m.quadraticCurveTo(xm * r2, ym * r2, x1 * r2, y1 * r2);
|
||||
m.fill();
|
||||
}
|
||||
else {
|
||||
// Create gradient fill between the endpoints.
|
||||
var grad = m.createLinearGradient(x1, y1, x2, y2);
|
||||
grad.addColorStop(0, color1);
|
||||
grad.addColorStop(1, color2);
|
||||
m.strokeStyle = grad;
|
||||
// Draw quadratic curve segment.
|
||||
m.beginPath();
|
||||
m.moveTo(x1, y1);
|
||||
m.quadraticCurveTo(xm, ym, x2, y2);
|
||||
m.stroke();
|
||||
}
|
||||
}
|
||||
// Prevent seams where curves join.
|
||||
angle1 = angle2 - nudge; color1 = color2; d1 = d2;
|
||||
}
|
||||
m.restore();
|
||||
__debug && $('body').append('<div>drawCircle '+ (+(new Date()) - tm) +'ms');
|
||||
};
|
||||
|
||||
/**
|
||||
* Draw the saturation/luminance mask.
|
||||
*/
|
||||
fb.drawMask = function () {
|
||||
var tm = +(new Date());
|
||||
|
||||
// Iterate over sat/lum space and calculate appropriate mask pixel values.
|
||||
var size = fb.square * 2, sq = fb.square;
|
||||
function calculateMask(sizex, sizey, outputPixel) {
|
||||
var isx = 1 / sizex, isy = 1 / sizey;
|
||||
for (var y = 0; y <= sizey; ++y) {
|
||||
var l = 1 - y * isy;
|
||||
for (var x = 0; x <= sizex; ++x) {
|
||||
var s = 1 - x * isx;
|
||||
// From sat/lum to alpha and color (grayscale)
|
||||
var a = 1 - 2 * Math.min(l * s, (1 - l) * s);
|
||||
var c = (a > 0) ? ((2 * l - 1 + a) * .5 / a) : 0;
|
||||
|
||||
a = a*__factor+(1-__factor)/2;
|
||||
c = c*__factor+(1-__factor)/2;
|
||||
|
||||
outputPixel(x, y, c, a);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Method #1: direct pixel access (new Canvas).
|
||||
if (fb.ctxMask.getImageData) {
|
||||
// Create half-resolution buffer.
|
||||
var sz = Math.floor(size / 2);
|
||||
var buffer = document.createElement('canvas');
|
||||
buffer.width = buffer.height = sz + 1;
|
||||
var ctx = buffer.getContext('2d');
|
||||
var frame = ctx.getImageData(0, 0, sz + 1, sz + 1);
|
||||
|
||||
var i = 0;
|
||||
calculateMask(sz, sz, function (x, y, c, a) {
|
||||
frame.data[i++] = frame.data[i++] = frame.data[i++] = c * 255;
|
||||
frame.data[i++] = a * 255;
|
||||
});
|
||||
|
||||
ctx.putImageData(frame, 0, 0);
|
||||
fb.ctxMask.drawImage(buffer, 0, 0, sz + 1, sz + 1, -sq, -sq, sq * 2, sq * 2);
|
||||
}
|
||||
// Method #2: drawing commands (old Canvas).
|
||||
else if (!$.browser.msie) {
|
||||
// Render directly at half-resolution
|
||||
var sz = Math.floor(size / 2);
|
||||
calculateMask(sz, sz, function (x, y, c, a) {
|
||||
c = Math.round(c * 255);
|
||||
fb.ctxMask.fillStyle = 'rgba(' + c + ', ' + c + ', ' + c + ', ' + a +')';
|
||||
fb.ctxMask.fillRect(x * 2 - sq - 1, y * 2 - sq - 1, 2, 2);
|
||||
});
|
||||
}
|
||||
// Method #3: vertical DXImageTransform gradient strips (IE).
|
||||
else {
|
||||
var cache_last, cache, w = 6; // Each strip is 6 pixels wide.
|
||||
var sizex = Math.floor(size / w);
|
||||
// 6 vertical pieces of gradient per strip.
|
||||
calculateMask(sizex, 6, function (x, y, c, a) {
|
||||
if (x == 0) {
|
||||
cache_last = cache;
|
||||
cache = [];
|
||||
}
|
||||
c = Math.round(c * 255);
|
||||
a = Math.round(a * 255);
|
||||
// We can only start outputting gradients once we have two rows of pixels.
|
||||
if (y > 0) {
|
||||
var c_last = cache_last[x][0],
|
||||
a_last = cache_last[x][1],
|
||||
color1 = fb.packDX(c_last, a_last),
|
||||
color2 = fb.packDX(c, a),
|
||||
y1 = Math.round(fb.mid + ((y - 1) * .333 - 1) * sq),
|
||||
y2 = Math.round(fb.mid + (y * .333 - 1) * sq);
|
||||
$('<div>').css({
|
||||
position: 'absolute',
|
||||
filter: "progid:DXImageTransform.Microsoft.Gradient(StartColorStr="+ color1 +", EndColorStr="+ color2 +", GradientType=0)",
|
||||
top: y1,
|
||||
height: y2 - y1,
|
||||
// Avoid right-edge sticking out.
|
||||
left: fb.mid + (x * w - sq - 1),
|
||||
width: w - (x == sizex ? Math.round(w / 2) : 0)
|
||||
}).appendTo(fb.cnvMask);
|
||||
}
|
||||
cache.push([c, a]);
|
||||
});
|
||||
}
|
||||
__debug && $('body').append('<div>drawMask '+ (+(new Date()) - tm) +'ms');
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw the selection markers.
|
||||
*/
|
||||
fb.drawMarkers = function () {
|
||||
// Determine marker dimensions
|
||||
var sz = options.width, lw = Math.ceil(fb.markerSize / 4), r = fb.markerSize - lw + 1;
|
||||
var angle = fb.hsl[0] * 6.28,
|
||||
x1 = Math.sin(angle) * fb.radius,
|
||||
y1 = -Math.cos(angle) * fb.radius,
|
||||
x2 = 2 * fb.square * (.5 - fb.hsl[1]),
|
||||
y2 = 2 * fb.square * (.5 - fb.hsl[2]),
|
||||
c1 = fb.invert ? '#fff' : '#000',
|
||||
c2 = fb.invert ? '#000' : '#fff';
|
||||
var circles = [
|
||||
{ x: x1, y: y1, r: r, c: '#000', lw: lw + 1 },
|
||||
{ x: x1, y: y1, r: fb.markerSize, c: '#fff', lw: lw },
|
||||
{ x: x2, y: y2, r: r, c: c2, lw: lw + 1 },
|
||||
{ x: x2, y: y2, r: fb.markerSize, c: c1, lw: lw },
|
||||
];
|
||||
|
||||
// Update the overlay canvas.
|
||||
fb.ctxOverlay.clearRect(-fb.mid, -fb.mid, sz, sz);
|
||||
for (i in circles) {
|
||||
var c = circles[i];
|
||||
fb.ctxOverlay.lineWidth = c.lw;
|
||||
fb.ctxOverlay.strokeStyle = c.c;
|
||||
fb.ctxOverlay.beginPath();
|
||||
fb.ctxOverlay.arc(c.x, c.y, c.r, 0, Math.PI * 2, true);
|
||||
fb.ctxOverlay.stroke();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the markers and styles
|
||||
*/
|
||||
fb.updateDisplay = function () {
|
||||
// Determine whether labels/markers should invert.
|
||||
fb.invert = (fb.rgb[0] * 0.3 + fb.rgb[1] * .59 + fb.rgb[2] * .11) <= 0.6;
|
||||
|
||||
// Update the solid background fill.
|
||||
fb.solidFill.css('backgroundColor', fb.pack(fb.HSLToRGB([fb.hsl[0], 1, 0.5])));
|
||||
|
||||
// Draw markers
|
||||
fb.drawMarkers();
|
||||
|
||||
// Linked elements or callback
|
||||
if (typeof fb.callback == 'object') {
|
||||
// Set background/foreground color
|
||||
$(fb.callback).css({
|
||||
backgroundColor: fb.color,
|
||||
color: fb.invert ? '#fff' : '#000'
|
||||
});
|
||||
|
||||
// Change linked value
|
||||
$(fb.callback).each(function() {
|
||||
if ((typeof this.value == 'string') && this.value != fb.color) {
|
||||
this.value = fb.color;
|
||||
}
|
||||
});
|
||||
}
|
||||
else if (typeof fb.callback == 'function') {
|
||||
fb.callback.call(fb, fb.color);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper for returning coordinates relative to the center.
|
||||
*/
|
||||
fb.widgetCoords = function (event) {
|
||||
return {
|
||||
x: event.pageX - fb.offset.left - fb.mid,
|
||||
y: event.pageY - fb.offset.top - fb.mid
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Mousedown handler
|
||||
*/
|
||||
fb.mousedown = function (event) {
|
||||
// Capture mouse
|
||||
if (!$._farbtastic.dragging) {
|
||||
$(document).bind('mousemove', fb.mousemove).bind('mouseup', fb.mouseup);
|
||||
$._farbtastic.dragging = true;
|
||||
}
|
||||
|
||||
// Update the stored offset for the widget.
|
||||
fb.offset = $(container).offset();
|
||||
|
||||
// Check which area is being dragged
|
||||
var pos = fb.widgetCoords(event);
|
||||
fb.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) > (fb.square + 2);
|
||||
|
||||
// Process
|
||||
fb.mousemove(event);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mousemove handler
|
||||
*/
|
||||
fb.mousemove = function (event) {
|
||||
// Get coordinates relative to color picker center
|
||||
var pos = fb.widgetCoords(event);
|
||||
|
||||
// Set new HSL parameters
|
||||
if (fb.circleDrag) {
|
||||
var hue = Math.atan2(pos.x, -pos.y) / 6.28;
|
||||
fb.setHSL([(hue + 1) % 1, fb.hsl[1], fb.hsl[2]]);
|
||||
}
|
||||
else {
|
||||
var sat = Math.max(0, Math.min(1, -(pos.x / fb.square / 2) + .5));
|
||||
var lum = Math.max(0, Math.min(1, -(pos.y / fb.square / 2) + .5));
|
||||
fb.setHSL([fb.hsl[0], sat, lum]);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mouseup handler
|
||||
*/
|
||||
fb.mouseup = function () {
|
||||
// Uncapture mouse
|
||||
$(document).unbind('mousemove', fb.mousemove);
|
||||
$(document).unbind('mouseup', fb.mouseup);
|
||||
$._farbtastic.dragging = false;
|
||||
}
|
||||
|
||||
/* Various color utility functions */
|
||||
fb.dec2hex = function (x) {
|
||||
return (x < 16 ? '0' : '') + x.toString(16);
|
||||
}
|
||||
|
||||
fb.packDX = function (c, a) {
|
||||
return '#' + fb.dec2hex(a) + fb.dec2hex(c) + fb.dec2hex(c) + fb.dec2hex(c);
|
||||
};
|
||||
|
||||
fb.pack = function (rgb) {
|
||||
var r = Math.round(rgb[0] * 255);
|
||||
var g = Math.round(rgb[1] * 255);
|
||||
var b = Math.round(rgb[2] * 255);
|
||||
return '#' + fb.dec2hex(r) + fb.dec2hex(g) + fb.dec2hex(b);
|
||||
};
|
||||
|
||||
fb.unpack = function (color) {
|
||||
if (color.length == 7) {
|
||||
function x(i) {
|
||||
return parseInt(color.substring(i, i + 2), 16) / 255;
|
||||
}
|
||||
return [ x(1), x(3), x(5) ];
|
||||
}
|
||||
else if (color.length == 4) {
|
||||
function x(i) {
|
||||
return parseInt(color.substring(i, i + 1), 16) / 15;
|
||||
}
|
||||
return [ x(1), x(2), x(3) ];
|
||||
}
|
||||
};
|
||||
|
||||
fb.HSLToRGB = function (hsl) {
|
||||
var m1, m2, r, g, b;
|
||||
var h = hsl[0], s = hsl[1], l = hsl[2];
|
||||
m2 = (l <= 0.5) ? l * (s + 1) : l + s - l * s;
|
||||
m1 = l * 2 - m2;
|
||||
return [
|
||||
this.hueToRGB(m1, m2, h + 0.33333),
|
||||
this.hueToRGB(m1, m2, h),
|
||||
this.hueToRGB(m1, m2, h - 0.33333)
|
||||
];
|
||||
};
|
||||
|
||||
fb.hueToRGB = function (m1, m2, h) {
|
||||
h = (h + 1) % 1;
|
||||
if (h * 6 < 1) return m1 + (m2 - m1) * h * 6;
|
||||
if (h * 2 < 1) return m2;
|
||||
if (h * 3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * 6;
|
||||
return m1;
|
||||
};
|
||||
|
||||
fb.RGBToHSL = function (rgb) {
|
||||
var r = rgb[0], g = rgb[1], b = rgb[2],
|
||||
min = Math.min(r, g, b),
|
||||
max = Math.max(r, g, b),
|
||||
delta = max - min,
|
||||
h = 0,
|
||||
s = 0,
|
||||
l = (min + max) / 2;
|
||||
if (l > 0 && l < 1) {
|
||||
s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l));
|
||||
}
|
||||
if (delta > 0) {
|
||||
if (max == r && max != g) h += (g - b) / delta;
|
||||
if (max == g && max != b) h += (2 + (b - r) / delta);
|
||||
if (max == b && max != r) h += (4 + (r - g) / delta);
|
||||
h /= 6;
|
||||
}
|
||||
return [h, s, l];
|
||||
};
|
||||
|
||||
// Parse options.
|
||||
if (!options.callback) {
|
||||
options = { callback: options };
|
||||
}
|
||||
options = $.extend({
|
||||
width: 300,
|
||||
wheelWidth: (options.width || 300) / 10,
|
||||
callback: null
|
||||
}, options);
|
||||
|
||||
// Initialize.
|
||||
fb.initWidget();
|
||||
|
||||
// Install mousedown handler (the others are set on the document on-demand)
|
||||
$('canvas.farbtastic-overlay', container).mousedown(fb.mousedown);
|
||||
|
||||
// Set linked elements/callback
|
||||
if (options.callback) {
|
||||
fb.linkTo(options.callback);
|
||||
}
|
||||
// Set to gray.
|
||||
fb.setColor('#808080');
|
||||
}
|
||||
|
||||
})(jQuery);
|
9266
src/static/js/jquery.js
vendored
Normal file
473
src/static/js/json2.js
Normal file
|
@ -0,0 +1,473 @@
|
|||
/*
|
||||
http://www.JSON.org/json2.js
|
||||
2011-02-23
|
||||
|
||||
Public Domain.
|
||||
|
||||
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
|
||||
|
||||
See http://www.JSON.org/js.html
|
||||
|
||||
|
||||
This code should be minified before deployment.
|
||||
See http://javascript.crockford.com/jsmin.html
|
||||
|
||||
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
|
||||
NOT CONTROL.
|
||||
|
||||
|
||||
This file creates a global JSON object containing two methods: stringify
|
||||
and parse.
|
||||
|
||||
JSON.stringify(value, replacer, space)
|
||||
value any JavaScript value, usually an object or array.
|
||||
|
||||
replacer an optional parameter that determines how object
|
||||
values are stringified for objects. It can be a
|
||||
function or an array of strings.
|
||||
|
||||
space an optional parameter that specifies the indentation
|
||||
of nested structures. If it is omitted, the text will
|
||||
be packed without extra whitespace. If it is a number,
|
||||
it will specify the number of spaces to indent at each
|
||||
level. If it is a string (such as '\t' or ' '),
|
||||
it contains the characters used to indent at each level.
|
||||
|
||||
This method produces a JSON text from a JavaScript value.
|
||||
|
||||
When an object value is found, if the object contains a toJSON
|
||||
method, its toJSON method will be called and the result will be
|
||||
stringified. A toJSON method does not serialize: it returns the
|
||||
value represented by the name/value pair that should be serialized,
|
||||
or undefined if nothing should be serialized. The toJSON method
|
||||
will be passed the key associated with the value, and this will be
|
||||
bound to the value
|
||||
|
||||
For example, this would serialize Dates as ISO strings.
|
||||
|
||||
Date.prototype.toJSON = function (key) {
|
||||
function f(n) {
|
||||
// Format integers to have at least two digits.
|
||||
return n < 10 ? '0' + n : n;
|
||||
}
|
||||
|
||||
return this.getUTCFullYear() + '-' +
|
||||
f(this.getUTCMonth() + 1) + '-' +
|
||||
f(this.getUTCDate()) + 'T' +
|
||||
f(this.getUTCHours()) + ':' +
|
||||
f(this.getUTCMinutes()) + ':' +
|
||||
f(this.getUTCSeconds()) + 'Z';
|
||||
};
|
||||
|
||||
You can provide an optional replacer method. It will be passed the
|
||||
key and value of each member, with this bound to the containing
|
||||
object. The value that is returned from your method will be
|
||||
serialized. If your method returns undefined, then the member will
|
||||
be excluded from the serialization.
|
||||
|
||||
If the replacer parameter is an array of strings, then it will be
|
||||
used to select the members to be serialized. It filters the results
|
||||
such that only members with keys listed in the replacer array are
|
||||
stringified.
|
||||
|
||||
Values that do not have JSON representations, such as undefined or
|
||||
functions, will not be serialized. Such values in objects will be
|
||||
dropped; in arrays they will be replaced with null. You can use
|
||||
a replacer function to replace those with JSON values.
|
||||
JSON.stringify(undefined) returns undefined.
|
||||
|
||||
The optional space parameter produces a stringification of the
|
||||
value that is filled with line breaks and indentation to make it
|
||||
easier to read.
|
||||
|
||||
If the space parameter is a non-empty string, then that string will
|
||||
be used for indentation. If the space parameter is a number, then
|
||||
the indentation will be that many spaces.
|
||||
|
||||
Example:
|
||||
|
||||
text = JSON.stringify(['e', {pluribus: 'unum'}]);
|
||||
// text is '["e",{"pluribus":"unum"}]'
|
||||
|
||||
|
||||
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
|
||||
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
|
||||
|
||||
text = JSON.stringify([new Date()], function (key, value) {
|
||||
return this[key] instanceof Date ?
|
||||
'Date(' + this[key] + ')' : value;
|
||||
});
|
||||
// text is '["Date(---current time---)"]'
|
||||
|
||||
|
||||
JSON.parse(text, reviver)
|
||||
This method parses a JSON text to produce an object or array.
|
||||
It can throw a SyntaxError exception.
|
||||
|
||||
The optional reviver parameter is a function that can filter and
|
||||
transform the results. It receives each of the keys and values,
|
||||
and its return value is used instead of the original value.
|
||||
If it returns what it received, then the structure is not modified.
|
||||
If it returns undefined then the member is deleted.
|
||||
|
||||
Example:
|
||||
|
||||
// Parse the text. Values that look like ISO date strings will
|
||||
// be converted to Date objects.
|
||||
|
||||
myData = JSON.parse(text, function (key, value) {
|
||||
var a;
|
||||
if (typeof value === 'string') {
|
||||
a =
|
||||
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
|
||||
if (a) {
|
||||
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
|
||||
+a[5], +a[6]));
|
||||
}
|
||||
}
|
||||
return value;
|
||||
});
|
||||
|
||||
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
|
||||
var d;
|
||||
if (typeof value === 'string' &&
|
||||
value.slice(0, 5) === 'Date(' &&
|
||||
value.slice(-1) === ')') {
|
||||
d = new Date(value.slice(5, -1));
|
||||
if (d) {
|
||||
return d;
|
||||
}
|
||||
}
|
||||
return value;
|
||||
});
|
||||
|
||||
|
||||
This is a reference implementation. You are free to copy, modify, or
|
||||
redistribute.
|
||||
*/
|
||||
|
||||
/*jslint evil: true, strict: false, regexp: false */
|
||||
|
||||
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
|
||||
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
|
||||
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
|
||||
lastIndex, length, parse, prototype, push, replace, slice, stringify,
|
||||
test, toJSON, toString, valueOf
|
||||
*/
|
||||
|
||||
|
||||
// Create a JSON object only if one does not already exist. We create the
|
||||
// methods in a closure to avoid creating global variables.
|
||||
var JSON;
|
||||
if (!JSON)
|
||||
{
|
||||
JSON = {};
|
||||
}
|
||||
|
||||
(function()
|
||||
{
|
||||
"use strict";
|
||||
|
||||
function f(n)
|
||||
{
|
||||
// Format integers to have at least two digits.
|
||||
return n < 10 ? '0' + n : n;
|
||||
}
|
||||
|
||||
if (typeof Date.prototype.toJSON !== 'function')
|
||||
{
|
||||
|
||||
Date.prototype.toJSON = function(key)
|
||||
{
|
||||
|
||||
return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null;
|
||||
};
|
||||
|
||||
String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function(key)
|
||||
{
|
||||
return this.valueOf();
|
||||
};
|
||||
}
|
||||
|
||||
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
|
||||
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
|
||||
gap, indent, meta = { // table of character substitutions
|
||||
'\b': '\\b',
|
||||
'\t': '\\t',
|
||||
'\n': '\\n',
|
||||
'\f': '\\f',
|
||||
'\r': '\\r',
|
||||
'"': '\\"',
|
||||
'\\': '\\\\'
|
||||
},
|
||||
rep;
|
||||
|
||||
|
||||
function quote(string)
|
||||
{
|
||||
|
||||
// If the string contains no control characters, no quote characters, and no
|
||||
// backslash characters, then we can safely slap some quotes around it.
|
||||
// Otherwise we must also replace the offending characters with safe escape
|
||||
// sequences.
|
||||
escapable.lastIndex = 0;
|
||||
return escapable.test(string) ? '"' + string.replace(escapable, function(a)
|
||||
{
|
||||
var c = meta[a];
|
||||
return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
|
||||
}) + '"' : '"' + string + '"';
|
||||
}
|
||||
|
||||
|
||||
function str(key, holder)
|
||||
{
|
||||
|
||||
// Produce a string from holder[key].
|
||||
var i, // The loop counter.
|
||||
k, // The member key.
|
||||
v, // The member value.
|
||||
length, mind = gap,
|
||||
partial, value = holder[key];
|
||||
|
||||
// If the value has a toJSON method, call it to obtain a replacement value.
|
||||
if (value && typeof value === 'object' && typeof value.toJSON === 'function')
|
||||
{
|
||||
value = value.toJSON(key);
|
||||
}
|
||||
|
||||
// If we were called with a replacer function, then call the replacer to
|
||||
// obtain a replacement value.
|
||||
if (typeof rep === 'function')
|
||||
{
|
||||
value = rep.call(holder, key, value);
|
||||
}
|
||||
|
||||
// What happens next depends on the value's type.
|
||||
switch (typeof value)
|
||||
{
|
||||
case 'string':
|
||||
return quote(value);
|
||||
|
||||
case 'number':
|
||||
|
||||
// JSON numbers must be finite. Encode non-finite numbers as null.
|
||||
return isFinite(value) ? String(value) : 'null';
|
||||
|
||||
case 'boolean':
|
||||
case 'null':
|
||||
|
||||
// If the value is a boolean or null, convert it to a string. Note:
|
||||
// typeof null does not produce 'null'. The case is included here in
|
||||
// the remote chance that this gets fixed someday.
|
||||
return String(value);
|
||||
|
||||
// If the type is 'object', we might be dealing with an object or an array or
|
||||
// null.
|
||||
case 'object':
|
||||
|
||||
// Due to a specification blunder in ECMAScript, typeof null is 'object',
|
||||
// so watch out for that case.
|
||||
if (!value)
|
||||
{
|
||||
return 'null';
|
||||
}
|
||||
|
||||
// Make an array to hold the partial results of stringifying this object value.
|
||||
gap += indent;
|
||||
partial = [];
|
||||
|
||||
// Is the value an array?
|
||||
if (Object.prototype.toString.apply(value) === '[object Array]')
|
||||
{
|
||||
|
||||
// The value is an array. Stringify every element. Use null as a placeholder
|
||||
// for non-JSON values.
|
||||
length = value.length;
|
||||
for (i = 0; i < length; i += 1)
|
||||
{
|
||||
partial[i] = str(i, value) || 'null';
|
||||
}
|
||||
|
||||
// Join all of the elements together, separated with commas, and wrap them in
|
||||
// brackets.
|
||||
v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']';
|
||||
gap = mind;
|
||||
return v;
|
||||
}
|
||||
|
||||
// If the replacer is an array, use it to select the members to be stringified.
|
||||
if (rep && typeof rep === 'object')
|
||||
{
|
||||
length = rep.length;
|
||||
for (i = 0; i < length; i += 1)
|
||||
{
|
||||
if (typeof rep[i] === 'string')
|
||||
{
|
||||
k = rep[i];
|
||||
v = str(k, value);
|
||||
if (v)
|
||||
{
|
||||
partial.push(quote(k) + (gap ? ': ' : ':') + v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
// Otherwise, iterate through all of the keys in the object.
|
||||
for (k in value)
|
||||
{
|
||||
if (Object.prototype.hasOwnProperty.call(value, k))
|
||||
{
|
||||
v = str(k, value);
|
||||
if (v)
|
||||
{
|
||||
partial.push(quote(k) + (gap ? ': ' : ':') + v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Join all of the member texts together, separated with commas,
|
||||
// and wrap them in braces.
|
||||
v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}';
|
||||
gap = mind;
|
||||
return v;
|
||||
}
|
||||
}
|
||||
|
||||
// If the JSON object does not yet have a stringify method, give it one.
|
||||
if (typeof JSON.stringify !== 'function')
|
||||
{
|
||||
JSON.stringify = function(value, replacer, space)
|
||||
{
|
||||
|
||||
// The stringify method takes a value and an optional replacer, and an optional
|
||||
// space parameter, and returns a JSON text. The replacer can be a function
|
||||
// that can replace values, or an array of strings that will select the keys.
|
||||
// A default replacer method can be provided. Use of the space parameter can
|
||||
// produce text that is more easily readable.
|
||||
var i;
|
||||
gap = '';
|
||||
indent = '';
|
||||
|
||||
// If the space parameter is a number, make an indent string containing that
|
||||
// many spaces.
|
||||
if (typeof space === 'number')
|
||||
{
|
||||
for (i = 0; i < space; i += 1)
|
||||
{
|
||||
indent += ' ';
|
||||
}
|
||||
|
||||
// If the space parameter is a string, it will be used as the indent string.
|
||||
}
|
||||
else if (typeof space === 'string')
|
||||
{
|
||||
indent = space;
|
||||
}
|
||||
|
||||
// If there is a replacer, it must be a function or an array.
|
||||
// Otherwise, throw an error.
|
||||
rep = replacer;
|
||||
if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number'))
|
||||
{
|
||||
throw new Error('JSON.stringify');
|
||||
}
|
||||
|
||||
// Make a fake root object containing our value under the key of ''.
|
||||
// Return the result of stringifying the value.
|
||||
return str('', {
|
||||
'': value
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
// If the JSON object does not yet have a parse method, give it one.
|
||||
if (typeof JSON.parse !== 'function')
|
||||
{
|
||||
JSON.parse = function(text, reviver)
|
||||
{
|
||||
|
||||
// The parse method takes a text and an optional reviver function, and returns
|
||||
// a JavaScript value if the text is a valid JSON text.
|
||||
var j;
|
||||
|
||||
function walk(holder, key)
|
||||
{
|
||||
|
||||
// The walk method is used to recursively walk the resulting structure so
|
||||
// that modifications can be made.
|
||||
var k, v, value = holder[key];
|
||||
if (value && typeof value === 'object')
|
||||
{
|
||||
for (k in value)
|
||||
{
|
||||
if (Object.prototype.hasOwnProperty.call(value, k))
|
||||
{
|
||||
v = walk(value, k);
|
||||
if (v !== undefined)
|
||||
{
|
||||
value[k] = v;
|
||||
}
|
||||
else
|
||||
{
|
||||
delete value[k];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return reviver.call(holder, key, value);
|
||||
}
|
||||
|
||||
|
||||
// Parsing happens in four stages. In the first stage, we replace certain
|
||||
// Unicode characters with escape sequences. JavaScript handles many characters
|
||||
// incorrectly, either silently deleting them, or treating them as line endings.
|
||||
text = String(text);
|
||||
cx.lastIndex = 0;
|
||||
if (cx.test(text))
|
||||
{
|
||||
text = text.replace(cx, function(a)
|
||||
{
|
||||
return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
|
||||
});
|
||||
}
|
||||
|
||||
// In the second stage, we run the text against regular expressions that look
|
||||
// for non-JSON patterns. We are especially concerned with '()' and 'new'
|
||||
// because they can cause invocation, and '=' because it can cause mutation.
|
||||
// But just to be safe, we want to reject all unexpected forms.
|
||||
// We split the second stage into 4 regexp operations in order to work around
|
||||
// crippling inefficiencies in IE's and Safari's regexp engines. First we
|
||||
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
|
||||
// replace all simple value tokens with ']' characters. Third, we delete all
|
||||
// open brackets that follow a colon or comma or that begin the text. Finally,
|
||||
// we look to see that the remaining characters are only whitespace or ']' or
|
||||
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
|
||||
if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, '')))
|
||||
{
|
||||
|
||||
// In the third stage we use the eval function to compile the text into a
|
||||
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
|
||||
// in JavaScript: it can begin a block or an object literal. We wrap the text
|
||||
// in parens to eliminate the ambiguity.
|
||||
j = eval('(' + text + ')');
|
||||
|
||||
// In the optional fourth stage, we recursively walk the new structure, passing
|
||||
// each name/value pair to a reviver function for possible transformation.
|
||||
return typeof reviver === 'function' ? walk(
|
||||
{
|
||||
'': j
|
||||
}, '') : j;
|
||||
}
|
||||
|
||||
// If the text is not JSON parseable, then a SyntaxError is thrown.
|
||||
throw new SyntaxError('JSON.parse');
|
||||
};
|
||||
}
|
||||
}());
|
||||
|
||||
module.exports = JSON;
|
345
src/static/js/linestylefilter.js
Normal file
|
@ -0,0 +1,345 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
// THIS FILE IS ALSO AN APPJET MODULE: etherpad.collab.ace.linestylefilter
|
||||
// %APPJET%: import("etherpad.collab.ace.easysync2.Changeset");
|
||||
// %APPJET%: import("etherpad.admin.plugins");
|
||||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
// requires: easysync2.Changeset
|
||||
// requires: top
|
||||
// requires: plugins
|
||||
// requires: undefined
|
||||
|
||||
var Changeset = require('/Changeset');
|
||||
var plugins = require('/plugins').plugins;
|
||||
var map = require('/ace2_common').map;
|
||||
|
||||
var linestylefilter = {};
|
||||
|
||||
linestylefilter.ATTRIB_CLASSES = {
|
||||
'bold': 'tag:b',
|
||||
'italic': 'tag:i',
|
||||
'underline': 'tag:u',
|
||||
'strikethrough': 'tag:s'
|
||||
};
|
||||
|
||||
linestylefilter.getAuthorClassName = function(author)
|
||||
{
|
||||
return "author-" + author.replace(/[^a-y0-9]/g, function(c)
|
||||
{
|
||||
if (c == ".") return "-";
|
||||
return 'z' + c.charCodeAt(0) + 'z';
|
||||
});
|
||||
};
|
||||
|
||||
// lineLength is without newline; aline includes newline,
|
||||
// but may be falsy if lineLength == 0
|
||||
linestylefilter.getLineStyleFilter = function(lineLength, aline, textAndClassFunc, apool)
|
||||
{
|
||||
|
||||
var plugins_ = plugins;
|
||||
|
||||
if (lineLength == 0) return textAndClassFunc;
|
||||
|
||||
var nextAfterAuthorColors = textAndClassFunc;
|
||||
|
||||
var authorColorFunc = (function()
|
||||
{
|
||||
var lineEnd = lineLength;
|
||||
var curIndex = 0;
|
||||
var extraClasses;
|
||||
var leftInAuthor;
|
||||
|
||||
function attribsToClasses(attribs)
|
||||
{
|
||||
var classes = '';
|
||||
Changeset.eachAttribNumber(attribs, function(n)
|
||||
{
|
||||
var key = apool.getAttribKey(n);
|
||||
if (key)
|
||||
{
|
||||
var value = apool.getAttribValue(n);
|
||||
if (value)
|
||||
{
|
||||
if (key == 'author')
|
||||
{
|
||||
classes += ' ' + linestylefilter.getAuthorClassName(value);
|
||||
}
|
||||
else if (key == 'list')
|
||||
{
|
||||
classes += ' list:' + value;
|
||||
}
|
||||
else if (key == 'start')
|
||||
{
|
||||
classes += ' start:' + value;
|
||||
}
|
||||
else if (linestylefilter.ATTRIB_CLASSES[key])
|
||||
{
|
||||
classes += ' ' + linestylefilter.ATTRIB_CLASSES[key];
|
||||
}
|
||||
else
|
||||
{
|
||||
classes += plugins_.callHookStr("aceAttribsToClasses", {
|
||||
linestylefilter: linestylefilter,
|
||||
key: key,
|
||||
value: value
|
||||
}, " ", " ", "");
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
return classes.substring(1);
|
||||
}
|
||||
|
||||
var attributionIter = Changeset.opIterator(aline);
|
||||
var nextOp, nextOpClasses;
|
||||
|
||||
function goNextOp()
|
||||
{
|
||||
nextOp = attributionIter.next();
|
||||
nextOpClasses = (nextOp.opcode && attribsToClasses(nextOp.attribs));
|
||||
}
|
||||
goNextOp();
|
||||
|
||||
function nextClasses()
|
||||
{
|
||||
if (curIndex < lineEnd)
|
||||
{
|
||||
extraClasses = nextOpClasses;
|
||||
leftInAuthor = nextOp.chars;
|
||||
goNextOp();
|
||||
while (nextOp.opcode && nextOpClasses == extraClasses)
|
||||
{
|
||||
leftInAuthor += nextOp.chars;
|
||||
goNextOp();
|
||||
}
|
||||
}
|
||||
}
|
||||
nextClasses();
|
||||
|
||||
return function(txt, cls)
|
||||
{
|
||||
while (txt.length > 0)
|
||||
{
|
||||
if (leftInAuthor <= 0)
|
||||
{
|
||||
// prevent infinite loop if something funny's going on
|
||||
return nextAfterAuthorColors(txt, cls);
|
||||
}
|
||||
var spanSize = txt.length;
|
||||
if (spanSize > leftInAuthor)
|
||||
{
|
||||
spanSize = leftInAuthor;
|
||||
}
|
||||
var curTxt = txt.substring(0, spanSize);
|
||||
txt = txt.substring(spanSize);
|
||||
nextAfterAuthorColors(curTxt, (cls && cls + " ") + extraClasses);
|
||||
curIndex += spanSize;
|
||||
leftInAuthor -= spanSize;
|
||||
if (leftInAuthor == 0)
|
||||
{
|
||||
nextClasses();
|
||||
}
|
||||
}
|
||||
};
|
||||
})();
|
||||
return authorColorFunc;
|
||||
};
|
||||
|
||||
linestylefilter.getAtSignSplitterFilter = function(lineText, textAndClassFunc)
|
||||
{
|
||||
var at = /@/g;
|
||||
at.lastIndex = 0;
|
||||
var splitPoints = null;
|
||||
var execResult;
|
||||
while ((execResult = at.exec(lineText)))
|
||||
{
|
||||
if (!splitPoints)
|
||||
{
|
||||
splitPoints = [];
|
||||
}
|
||||
splitPoints.push(execResult.index);
|
||||
}
|
||||
|
||||
if (!splitPoints) return textAndClassFunc;
|
||||
|
||||
return linestylefilter.textAndClassFuncSplitter(textAndClassFunc, splitPoints);
|
||||
};
|
||||
|
||||
linestylefilter.getRegexpFilter = function(regExp, tag)
|
||||
{
|
||||
return function(lineText, textAndClassFunc)
|
||||
{
|
||||
regExp.lastIndex = 0;
|
||||
var regExpMatchs = null;
|
||||
var splitPoints = null;
|
||||
var execResult;
|
||||
while ((execResult = regExp.exec(lineText)))
|
||||
{
|
||||
if (!regExpMatchs)
|
||||
{
|
||||
regExpMatchs = [];
|
||||
splitPoints = [];
|
||||
}
|
||||
var startIndex = execResult.index;
|
||||
var regExpMatch = execResult[0];
|
||||
regExpMatchs.push([startIndex, regExpMatch]);
|
||||
splitPoints.push(startIndex, startIndex + regExpMatch.length);
|
||||
}
|
||||
|
||||
if (!regExpMatchs) return textAndClassFunc;
|
||||
|
||||
function regExpMatchForIndex(idx)
|
||||
{
|
||||
for (var k = 0; k < regExpMatchs.length; k++)
|
||||
{
|
||||
var u = regExpMatchs[k];
|
||||
if (idx >= u[0] && idx < u[0] + u[1].length)
|
||||
{
|
||||
return u[1];
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
var handleRegExpMatchsAfterSplit = (function()
|
||||
{
|
||||
var curIndex = 0;
|
||||
return function(txt, cls)
|
||||
{
|
||||
var txtlen = txt.length;
|
||||
var newCls = cls;
|
||||
var regExpMatch = regExpMatchForIndex(curIndex);
|
||||
if (regExpMatch)
|
||||
{
|
||||
newCls += " " + tag + ":" + regExpMatch;
|
||||
}
|
||||
textAndClassFunc(txt, newCls);
|
||||
curIndex += txtlen;
|
||||
};
|
||||
})();
|
||||
|
||||
return linestylefilter.textAndClassFuncSplitter(handleRegExpMatchsAfterSplit, splitPoints);
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
linestylefilter.REGEX_WORDCHAR = /[\u0030-\u0039\u0041-\u005A\u0061-\u007A\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0100-\u1FFF\u3040-\u9FFF\uF900-\uFDFF\uFE70-\uFEFE\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFDC]/;
|
||||
linestylefilter.REGEX_URLCHAR = new RegExp('(' + /[-:@a-zA-Z0-9_.,~%+\/\\?=&#;()$]/.source + '|' + linestylefilter.REGEX_WORDCHAR.source + ')');
|
||||
linestylefilter.REGEX_URL = new RegExp(/(?:(?:https?|s?ftp|ftps|file|smb|afp|nfs|(x-)?man|gopher|txmt):\/\/|mailto:|www\.)/.source + linestylefilter.REGEX_URLCHAR.source + '*(?![:.,;])' + linestylefilter.REGEX_URLCHAR.source, 'g');
|
||||
linestylefilter.getURLFilter = linestylefilter.getRegexpFilter(
|
||||
linestylefilter.REGEX_URL, 'url');
|
||||
|
||||
linestylefilter.textAndClassFuncSplitter = function(func, splitPointsOpt)
|
||||
{
|
||||
var nextPointIndex = 0;
|
||||
var idx = 0;
|
||||
|
||||
// don't split at 0
|
||||
while (splitPointsOpt && nextPointIndex < splitPointsOpt.length && splitPointsOpt[nextPointIndex] == 0)
|
||||
{
|
||||
nextPointIndex++;
|
||||
}
|
||||
|
||||
function spanHandler(txt, cls)
|
||||
{
|
||||
if ((!splitPointsOpt) || nextPointIndex >= splitPointsOpt.length)
|
||||
{
|
||||
func(txt, cls);
|
||||
idx += txt.length;
|
||||
}
|
||||
else
|
||||
{
|
||||
var splitPoints = splitPointsOpt;
|
||||
var pointLocInSpan = splitPoints[nextPointIndex] - idx;
|
||||
var txtlen = txt.length;
|
||||
if (pointLocInSpan >= txtlen)
|
||||
{
|
||||
func(txt, cls);
|
||||
idx += txt.length;
|
||||
if (pointLocInSpan == txtlen)
|
||||
{
|
||||
nextPointIndex++;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (pointLocInSpan > 0)
|
||||
{
|
||||
func(txt.substring(0, pointLocInSpan), cls);
|
||||
idx += pointLocInSpan;
|
||||
}
|
||||
nextPointIndex++;
|
||||
// recurse
|
||||
spanHandler(txt.substring(pointLocInSpan), cls);
|
||||
}
|
||||
}
|
||||
}
|
||||
return spanHandler;
|
||||
};
|
||||
|
||||
linestylefilter.getFilterStack = function(lineText, textAndClassFunc, browser)
|
||||
{
|
||||
var func = linestylefilter.getURLFilter(lineText, textAndClassFunc);
|
||||
|
||||
var plugins_ = plugins;
|
||||
|
||||
var hookFilters = plugins_.callHook("aceGetFilterStack", {
|
||||
linestylefilter: linestylefilter,
|
||||
browser: browser
|
||||
});
|
||||
map(hookFilters, function(hookFilter)
|
||||
{
|
||||
func = hookFilter(lineText, func);
|
||||
});
|
||||
|
||||
if (browser !== undefined && browser.msie)
|
||||
{
|
||||
// IE7+ will take an e-mail address like <foo@bar.com> and linkify it to foo@bar.com.
|
||||
// We then normalize it back to text with no angle brackets. It's weird. So always
|
||||
// break spans at an "at" sign.
|
||||
func = linestylefilter.getAtSignSplitterFilter(
|
||||
lineText, func);
|
||||
}
|
||||
return func;
|
||||
};
|
||||
|
||||
// domLineObj is like that returned by domline.createDomLine
|
||||
linestylefilter.populateDomLine = function(textLine, aline, apool, domLineObj)
|
||||
{
|
||||
// remove final newline from text if any
|
||||
var text = textLine;
|
||||
if (text.slice(-1) == '\n')
|
||||
{
|
||||
text = text.substring(0, text.length - 1);
|
||||
}
|
||||
|
||||
function textAndClassFunc(tokenText, tokenClass)
|
||||
{
|
||||
domLineObj.appendSpan(tokenText, tokenClass);
|
||||
}
|
||||
|
||||
var func = linestylefilter.getFilterStack(text, textAndClassFunc);
|
||||
func = linestylefilter.getLineStyleFilter(text.length, aline, func, apool);
|
||||
func(text, '');
|
||||
};
|
||||
|
||||
exports.linestylefilter = linestylefilter;
|
974
src/static/js/pad.js
Normal file
|
@ -0,0 +1,974 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copyright 2009 Google Inc., 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/* global $, window */
|
||||
|
||||
var socket;
|
||||
|
||||
// These jQuery things should create local references, but for now `require()`
|
||||
// assigns to the global `$` and augments it with plugins.
|
||||
require('/jquery');
|
||||
require('/farbtastic');
|
||||
require('/excanvas');
|
||||
JSON = require('/json2');
|
||||
require('/undo-xpopup');
|
||||
require('/prefixfree');
|
||||
|
||||
var chat = require('/chat').chat;
|
||||
var getCollabClient = require('/collab_client').getCollabClient;
|
||||
var padconnectionstatus = require('/pad_connectionstatus').padconnectionstatus;
|
||||
var padcookie = require('/pad_cookie').padcookie;
|
||||
var paddocbar = require('/pad_docbar').paddocbar;
|
||||
var padeditbar = require('/pad_editbar').padeditbar;
|
||||
var padeditor = require('/pad_editor').padeditor;
|
||||
var padimpexp = require('/pad_impexp').padimpexp;
|
||||
var padmodals = require('/pad_modals').padmodals;
|
||||
var padsavedrevs = require('/pad_savedrevs').padsavedrevs;
|
||||
var paduserlist = require('/pad_userlist').paduserlist;
|
||||
var padutils = require('/pad_utils').padutils;
|
||||
|
||||
var createCookie = require('/pad_utils').createCookie;
|
||||
var readCookie = require('/pad_utils').readCookie;
|
||||
var randomString = require('/pad_utils').randomString;
|
||||
|
||||
function getParams()
|
||||
{
|
||||
var params = getUrlVars()
|
||||
var showControls = params["showControls"];
|
||||
var showChat = params["showChat"];
|
||||
var userName = params["userName"];
|
||||
var showLineNumbers = params["showLineNumbers"];
|
||||
var useMonospaceFont = params["useMonospaceFont"];
|
||||
var IsnoColors = params["noColors"];
|
||||
var hideQRCode = params["hideQRCode"];
|
||||
var rtl = params["rtl"];
|
||||
var alwaysShowChat = params["alwaysShowChat"];
|
||||
|
||||
if(IsnoColors)
|
||||
{
|
||||
if(IsnoColors == "true")
|
||||
{
|
||||
settings.noColors = true;
|
||||
$('#clearAuthorship').hide();
|
||||
}
|
||||
}
|
||||
if(showControls)
|
||||
{
|
||||
if(showControls == "false")
|
||||
{
|
||||
$('#editbar').hide();
|
||||
$('#editorcontainer').css({"top":"0px"});
|
||||
}
|
||||
}
|
||||
if(showChat)
|
||||
{
|
||||
if(showChat == "false")
|
||||
{
|
||||
$('#chaticon').hide();
|
||||
}
|
||||
}
|
||||
if(showLineNumbers)
|
||||
{
|
||||
if(showLineNumbers == "false")
|
||||
{
|
||||
settings.LineNumbersDisabled = true;
|
||||
}
|
||||
}
|
||||
if(useMonospaceFont)
|
||||
{
|
||||
if(useMonospaceFont == "true")
|
||||
{
|
||||
settings.useMonospaceFontGlobal = true;
|
||||
}
|
||||
}
|
||||
if(userName)
|
||||
{
|
||||
// If the username is set as a parameter we should set a global value that we can call once we have initiated the pad.
|
||||
settings.globalUserName = decodeURIComponent(userName);
|
||||
}
|
||||
if(hideQRCode)
|
||||
{
|
||||
$('#qrcode').hide();
|
||||
}
|
||||
if(rtl)
|
||||
{
|
||||
if(rtl == "true")
|
||||
{
|
||||
settings.rtlIsTrue = true
|
||||
}
|
||||
}
|
||||
if(alwaysShowChat)
|
||||
{
|
||||
if(alwaysShowChat == "true")
|
||||
{
|
||||
chat.stickToScreen();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getUrlVars()
|
||||
{
|
||||
var vars = [], hash;
|
||||
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
|
||||
for(var i = 0; i < hashes.length; i++)
|
||||
{
|
||||
hash = hashes[i].split('=');
|
||||
vars.push(hash[0]);
|
||||
vars[hash[0]] = hash[1];
|
||||
}
|
||||
return vars;
|
||||
}
|
||||
|
||||
function savePassword()
|
||||
{
|
||||
//set the password cookie
|
||||
createCookie("password",$("#passwordinput").val(),null,document.location.pathname);
|
||||
//reload
|
||||
document.location=document.location;
|
||||
}
|
||||
|
||||
function handshake()
|
||||
{
|
||||
var loc = document.location;
|
||||
//get the correct port
|
||||
var port = loc.port == "" ? (loc.protocol == "https:" ? 443 : 80) : loc.port;
|
||||
//create the url
|
||||
var url = loc.protocol + "//" + loc.hostname + ":" + port + "/";
|
||||
//find out in which subfolder we are
|
||||
var resource = loc.pathname.substr(1, loc.pathname.indexOf("/p/")) + "socket.io";
|
||||
//connect
|
||||
socket = pad.socket = io.connect(url, {
|
||||
resource: resource,
|
||||
'max reconnection attempts': 3
|
||||
});
|
||||
|
||||
function sendClientReady(isReconnect)
|
||||
{
|
||||
var padId = document.location.pathname.substring(document.location.pathname.lastIndexOf("/") + 1);
|
||||
padId = decodeURIComponent(padId); // unescape neccesary due to Safari and Opera interpretation of spaces
|
||||
|
||||
if(!isReconnect)
|
||||
document.title = padId.replace(/_+/g, ' ') + " | " + document.title;
|
||||
|
||||
var token = readCookie("token");
|
||||
if (token == null)
|
||||
{
|
||||
token = "t." + randomString();
|
||||
createCookie("token", token, 60);
|
||||
}
|
||||
|
||||
var sessionID = readCookie("sessionID");
|
||||
var password = readCookie("password");
|
||||
|
||||
var msg = {
|
||||
"component": "pad",
|
||||
"type": "CLIENT_READY",
|
||||
"padId": padId,
|
||||
"sessionID": sessionID,
|
||||
"password": password,
|
||||
"token": token,
|
||||
"protocolVersion": 2
|
||||
};
|
||||
|
||||
//this is a reconnect, lets tell the server our revisionnumber
|
||||
if(isReconnect == true)
|
||||
{
|
||||
msg.client_rev=pad.collabClient.getCurrentRevisionNumber();
|
||||
msg.reconnect=true;
|
||||
}
|
||||
|
||||
socket.json.send(msg);
|
||||
};
|
||||
|
||||
var disconnectTimeout;
|
||||
|
||||
socket.once('connect', function () {
|
||||
sendClientReady(false);
|
||||
});
|
||||
|
||||
socket.on('reconnect', function () {
|
||||
//reconnect is before the timeout, lets stop the timeout
|
||||
if(disconnectTimeout)
|
||||
{
|
||||
clearTimeout(disconnectTimeout);
|
||||
}
|
||||
|
||||
pad.collabClient.setChannelState("CONNECTED");
|
||||
sendClientReady(true);
|
||||
});
|
||||
|
||||
socket.on('disconnect', function () {
|
||||
function disconnectEvent()
|
||||
{
|
||||
pad.collabClient.setChannelState("DISCONNECTED", "reconnect_timeout");
|
||||
}
|
||||
|
||||
pad.collabClient.setChannelState("RECONNECTING");
|
||||
|
||||
disconnectTimeout = setTimeout(disconnectEvent, 10000);
|
||||
});
|
||||
|
||||
var receivedClientVars = false;
|
||||
var initalized = false;
|
||||
|
||||
socket.on('message', function(obj)
|
||||
{
|
||||
//the access was not granted, give the user a message
|
||||
if(!receivedClientVars && obj.accessStatus)
|
||||
{
|
||||
if(obj.accessStatus == "deny")
|
||||
{
|
||||
$("#editorloadingbox").html("<b>You do not have permission to access this pad</b>");
|
||||
}
|
||||
else if(obj.accessStatus == "needPassword")
|
||||
{
|
||||
$("#editorloadingbox").html("<b>You need a password to access this pad</b><br>" +
|
||||
"<input id='passwordinput' type='password' name='password'>"+
|
||||
"<button type='button' onclick=\"" + padutils.escapeHtml('require('+JSON.stringify(module.id)+").savePassword()") + "\">ok</button>");
|
||||
}
|
||||
else if(obj.accessStatus == "wrongPassword")
|
||||
{
|
||||
$("#editorloadingbox").html("<b>You're password was wrong</b><br>" +
|
||||
"<input id='passwordinput' type='password' name='password'>"+
|
||||
"<button type='button' onclick=\"" + padutils.escapeHtml('require('+JSON.stringify(module.id)+").savePassword()") + "\">ok</button>");
|
||||
}
|
||||
}
|
||||
|
||||
//if we haven't recieved the clientVars yet, then this message should it be
|
||||
else if (!receivedClientVars)
|
||||
{
|
||||
//log the message
|
||||
if (window.console) console.log(obj);
|
||||
|
||||
receivedClientVars = true;
|
||||
|
||||
//set some client vars
|
||||
clientVars = obj;
|
||||
clientVars.userAgent = "Anonymous";
|
||||
clientVars.collab_client_vars.clientAgent = "Anonymous";
|
||||
|
||||
//initalize the pad
|
||||
pad._afterHandshake();
|
||||
initalized = true;
|
||||
|
||||
// If the LineNumbersDisabled value is set to true then we need to hide the Line Numbers
|
||||
if (settings.LineNumbersDisabled == true)
|
||||
{
|
||||
pad.changeViewOption('showLineNumbers', false);
|
||||
}
|
||||
|
||||
// If the noColors value is set to true then we need to hide the backround colors on the ace spans
|
||||
if (settings.noColors == true)
|
||||
{
|
||||
pad.changeViewOption('noColors', true);
|
||||
}
|
||||
|
||||
if (settings.rtlIsTrue == true)
|
||||
{
|
||||
pad.changeViewOption('rtl', true);
|
||||
}
|
||||
|
||||
// If the Monospacefont value is set to true then change it to monospace.
|
||||
if (settings.useMonospaceFontGlobal == true)
|
||||
{
|
||||
pad.changeViewOption('useMonospaceFont', true);
|
||||
}
|
||||
// if the globalUserName value is set we need to tell the server and the client about the new authorname
|
||||
if (settings.globalUserName !== false)
|
||||
{
|
||||
pad.notifyChangeName(settings.globalUserName); // Notifies the server
|
||||
pad.myUserInfo.name = settings.globalUserName;
|
||||
$('#myusernameedit').attr({"value":settings.globalUserName}); // Updates the current users UI
|
||||
}
|
||||
}
|
||||
//This handles every Message after the clientVars
|
||||
else
|
||||
{
|
||||
//this message advices the client to disconnect
|
||||
if (obj.disconnect)
|
||||
{
|
||||
padconnectionstatus.disconnected(obj.disconnect);
|
||||
socket.disconnect();
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
pad.collabClient.handleMessageFromServer(obj);
|
||||
}
|
||||
}
|
||||
});
|
||||
// Bind the colorpicker
|
||||
var fb = $('#colorpicker').farbtastic({ callback: '#mycolorpickerpreview', width: 220});
|
||||
}
|
||||
|
||||
var pad = {
|
||||
// don't access these directly from outside this file, except
|
||||
// for debugging
|
||||
collabClient: null,
|
||||
myUserInfo: null,
|
||||
diagnosticInfo: {},
|
||||
initTime: 0,
|
||||
clientTimeOffset: null,
|
||||
preloadedImages: false,
|
||||
padOptions: {},
|
||||
|
||||
// these don't require init; clientVars should all go through here
|
||||
getPadId: function()
|
||||
{
|
||||
return clientVars.padId;
|
||||
},
|
||||
getClientIp: function()
|
||||
{
|
||||
return clientVars.clientIp;
|
||||
},
|
||||
getIsProPad: function()
|
||||
{
|
||||
return clientVars.isProPad;
|
||||
},
|
||||
getColorPalette: function()
|
||||
{
|
||||
return clientVars.colorPalette;
|
||||
},
|
||||
getDisplayUserAgent: function()
|
||||
{
|
||||
return padutils.uaDisplay(clientVars.userAgent);
|
||||
},
|
||||
getIsDebugEnabled: function()
|
||||
{
|
||||
return clientVars.debugEnabled;
|
||||
},
|
||||
getPrivilege: function(name)
|
||||
{
|
||||
return clientVars.accountPrivs[name];
|
||||
},
|
||||
getUserIsGuest: function()
|
||||
{
|
||||
return clientVars.userIsGuest;
|
||||
},
|
||||
//
|
||||
getUserId: function()
|
||||
{
|
||||
return pad.myUserInfo.userId;
|
||||
},
|
||||
getUserName: function()
|
||||
{
|
||||
return pad.myUserInfo.name;
|
||||
},
|
||||
sendClientMessage: function(msg)
|
||||
{
|
||||
pad.collabClient.sendClientMessage(msg);
|
||||
},
|
||||
|
||||
init: function()
|
||||
{
|
||||
padutils.setupGlobalExceptionHandler();
|
||||
|
||||
$(document).ready(function()
|
||||
{
|
||||
// start the custom js
|
||||
if (typeof customStart == "function") customStart();
|
||||
getParams();
|
||||
handshake();
|
||||
});
|
||||
|
||||
$(window).unload(function()
|
||||
{
|
||||
pad.dispose();
|
||||
});
|
||||
},
|
||||
_afterHandshake: function()
|
||||
{
|
||||
pad.clientTimeOffset = new Date().getTime() - clientVars.serverTimestamp;
|
||||
|
||||
//initialize the chat
|
||||
chat.init(this);
|
||||
pad.initTime = +(new Date());
|
||||
pad.padOptions = clientVars.initialOptions;
|
||||
|
||||
if ((!$.browser.msie) && (!($.browser.mozilla && $.browser.version.indexOf("1.8.") == 0)))
|
||||
{
|
||||
document.domain = document.domain; // for comet
|
||||
}
|
||||
|
||||
// for IE
|
||||
if ($.browser.msie)
|
||||
{
|
||||
try
|
||||
{
|
||||
doc.execCommand("BackgroundImageCache", false, true);
|
||||
}
|
||||
catch (e)
|
||||
{}
|
||||
}
|
||||
|
||||
// order of inits is important here:
|
||||
padcookie.init(clientVars.cookiePrefsToSet, this);
|
||||
|
||||
$("#widthprefcheck").click(pad.toggleWidthPref);
|
||||
// $("#sidebarcheck").click(pad.togglewSidebar);
|
||||
|
||||
pad.myUserInfo = {
|
||||
userId: clientVars.userId,
|
||||
name: clientVars.userName,
|
||||
ip: pad.getClientIp(),
|
||||
colorId: clientVars.userColor,
|
||||
userAgent: pad.getDisplayUserAgent()
|
||||
};
|
||||
|
||||
if (clientVars.specialKey)
|
||||
{
|
||||
pad.myUserInfo.specialKey = clientVars.specialKey;
|
||||
if (clientVars.specialKeyTranslation)
|
||||
{
|
||||
$("#specialkeyarea").html("mode: " + String(clientVars.specialKeyTranslation).toUpperCase());
|
||||
}
|
||||
}
|
||||
paddocbar.init(
|
||||
{
|
||||
isTitleEditable: pad.getIsProPad(),
|
||||
initialTitle: clientVars.initialTitle,
|
||||
initialPassword: clientVars.initialPassword,
|
||||
guestPolicy: pad.padOptions.guestPolicy
|
||||
}, this);
|
||||
padimpexp.init(this);
|
||||
padsavedrevs.init(clientVars.initialRevisionList, this);
|
||||
|
||||
padeditor.init(postAceInit, pad.padOptions.view || {}, this);
|
||||
|
||||
paduserlist.init(pad.myUserInfo, this);
|
||||
// padchat.init(clientVars.chatHistory, pad.myUserInfo);
|
||||
padconnectionstatus.init();
|
||||
padmodals.init(this);
|
||||
|
||||
pad.collabClient = getCollabClient(padeditor.ace, clientVars.collab_client_vars, pad.myUserInfo, {
|
||||
colorPalette: pad.getColorPalette()
|
||||
}, pad);
|
||||
pad.collabClient.setOnUserJoin(pad.handleUserJoin);
|
||||
pad.collabClient.setOnUpdateUserInfo(pad.handleUserUpdate);
|
||||
pad.collabClient.setOnUserLeave(pad.handleUserLeave);
|
||||
pad.collabClient.setOnClientMessage(pad.handleClientMessage);
|
||||
pad.collabClient.setOnServerMessage(pad.handleServerMessage);
|
||||
pad.collabClient.setOnChannelStateChange(pad.handleChannelStateChange);
|
||||
pad.collabClient.setOnInternalAction(pad.handleCollabAction);
|
||||
|
||||
function postAceInit()
|
||||
{
|
||||
padeditbar.init();
|
||||
setTimeout(function()
|
||||
{
|
||||
padeditor.ace.focus();
|
||||
}, 0);
|
||||
}
|
||||
},
|
||||
dispose: function()
|
||||
{
|
||||
padeditor.dispose();
|
||||
},
|
||||
notifyChangeName: function(newName)
|
||||
{
|
||||
pad.myUserInfo.name = newName;
|
||||
pad.collabClient.updateUserInfo(pad.myUserInfo);
|
||||
//padchat.handleUserJoinOrUpdate(pad.myUserInfo);
|
||||
},
|
||||
notifyChangeColor: function(newColorId)
|
||||
{
|
||||
pad.myUserInfo.colorId = newColorId;
|
||||
pad.collabClient.updateUserInfo(pad.myUserInfo);
|
||||
//padchat.handleUserJoinOrUpdate(pad.myUserInfo);
|
||||
},
|
||||
notifyChangeTitle: function(newTitle)
|
||||
{
|
||||
pad.collabClient.sendClientMessage(
|
||||
{
|
||||
type: 'padtitle',
|
||||
title: newTitle,
|
||||
changedBy: pad.myUserInfo.name || "unnamed"
|
||||
});
|
||||
},
|
||||
notifyChangePassword: function(newPass)
|
||||
{
|
||||
pad.collabClient.sendClientMessage(
|
||||
{
|
||||
type: 'padpassword',
|
||||
password: newPass,
|
||||
changedBy: pad.myUserInfo.name || "unnamed"
|
||||
});
|
||||
},
|
||||
changePadOption: function(key, value)
|
||||
{
|
||||
var options = {};
|
||||
options[key] = value;
|
||||
pad.handleOptionsChange(options);
|
||||
pad.collabClient.sendClientMessage(
|
||||
{
|
||||
type: 'padoptions',
|
||||
options: options,
|
||||
changedBy: pad.myUserInfo.name || "unnamed"
|
||||
});
|
||||
},
|
||||
changeViewOption: function(key, value)
|
||||
{
|
||||
var options = {
|
||||
view: {}
|
||||
};
|
||||
options.view[key] = value;
|
||||
pad.handleOptionsChange(options);
|
||||
},
|
||||
handleOptionsChange: function(opts)
|
||||
{
|
||||
// opts object is a full set of options or just
|
||||
// some options to change
|
||||
if (opts.view)
|
||||
{
|
||||
if (!pad.padOptions.view)
|
||||
{
|
||||
pad.padOptions.view = {};
|
||||
}
|
||||
for (var k in opts.view)
|
||||
{
|
||||
pad.padOptions.view[k] = opts.view[k];
|
||||
}
|
||||
padeditor.setViewOptions(pad.padOptions.view);
|
||||
}
|
||||
if (opts.guestPolicy)
|
||||
{
|
||||
// order important here
|
||||
pad.padOptions.guestPolicy = opts.guestPolicy;
|
||||
paddocbar.setGuestPolicy(opts.guestPolicy);
|
||||
}
|
||||
},
|
||||
getPadOptions: function()
|
||||
{
|
||||
// caller shouldn't mutate the object
|
||||
return pad.padOptions;
|
||||
},
|
||||
isPadPublic: function()
|
||||
{
|
||||
return (!pad.getIsProPad()) || (pad.getPadOptions().guestPolicy == 'allow');
|
||||
},
|
||||
suggestUserName: function(userId, name)
|
||||
{
|
||||
pad.collabClient.sendClientMessage(
|
||||
{
|
||||
type: 'suggestUserName',
|
||||
unnamedId: userId,
|
||||
newName: name
|
||||
});
|
||||
},
|
||||
handleUserJoin: function(userInfo)
|
||||
{
|
||||
paduserlist.userJoinOrUpdate(userInfo);
|
||||
//padchat.handleUserJoinOrUpdate(userInfo);
|
||||
},
|
||||
handleUserUpdate: function(userInfo)
|
||||
{
|
||||
paduserlist.userJoinOrUpdate(userInfo);
|
||||
//padchat.handleUserJoinOrUpdate(userInfo);
|
||||
},
|
||||
handleUserLeave: function(userInfo)
|
||||
{
|
||||
paduserlist.userLeave(userInfo);
|
||||
//padchat.handleUserLeave(userInfo);
|
||||
},
|
||||
handleClientMessage: function(msg)
|
||||
{
|
||||
if (msg.type == 'suggestUserName')
|
||||
{
|
||||
if (msg.unnamedId == pad.myUserInfo.userId && msg.newName && !pad.myUserInfo.name)
|
||||
{
|
||||
pad.notifyChangeName(msg.newName);
|
||||
paduserlist.setMyUserInfo(pad.myUserInfo);
|
||||
}
|
||||
}
|
||||
else if (msg.type == 'chat')
|
||||
{
|
||||
//padchat.receiveChat(msg);
|
||||
}
|
||||
else if (msg.type == 'padtitle')
|
||||
{
|
||||
paddocbar.changeTitle(msg.title);
|
||||
}
|
||||
else if (msg.type == 'padpassword')
|
||||
{
|
||||
paddocbar.changePassword(msg.password);
|
||||
}
|
||||
else if (msg.type == 'newRevisionList')
|
||||
{
|
||||
padsavedrevs.newRevisionList(msg.revisionList);
|
||||
}
|
||||
else if (msg.type == 'revisionLabel')
|
||||
{
|
||||
padsavedrevs.newRevisionList(msg.revisionList);
|
||||
}
|
||||
else if (msg.type == 'padoptions')
|
||||
{
|
||||
var opts = msg.options;
|
||||
pad.handleOptionsChange(opts);
|
||||
}
|
||||
else if (msg.type == 'guestanswer')
|
||||
{
|
||||
// someone answered a prompt, remove it
|
||||
paduserlist.removeGuestPrompt(msg.guestId);
|
||||
}
|
||||
},
|
||||
editbarClick: function(cmd)
|
||||
{
|
||||
if (padeditbar)
|
||||
{
|
||||
padeditbar.toolbarClick(cmd);
|
||||
}
|
||||
},
|
||||
dmesg: function(m)
|
||||
{
|
||||
if (pad.getIsDebugEnabled())
|
||||
{
|
||||
var djs = $('#djs').get(0);
|
||||
var wasAtBottom = (djs.scrollTop - (djs.scrollHeight - $(djs).height()) >= -20);
|
||||
$('#djs').append('<p>' + m + '</p>');
|
||||
if (wasAtBottom)
|
||||
{
|
||||
djs.scrollTop = djs.scrollHeight;
|
||||
}
|
||||
}
|
||||
},
|
||||
handleServerMessage: function(m)
|
||||
{
|
||||
if (m.type == 'NOTICE')
|
||||
{
|
||||
if (m.text)
|
||||
{
|
||||
alertBar.displayMessage(function(abar)
|
||||
{
|
||||
abar.find("#servermsgdate").html(" (" + padutils.simpleDateTime(new Date) + ")");
|
||||
abar.find("#servermsgtext").html(m.text);
|
||||
});
|
||||
}
|
||||
if (m.js)
|
||||
{
|
||||
window['ev' + 'al'](m.js);
|
||||
}
|
||||
}
|
||||
else if (m.type == 'GUEST_PROMPT')
|
||||
{
|
||||
paduserlist.showGuestPrompt(m.userId, m.displayName);
|
||||
}
|
||||
},
|
||||
handleChannelStateChange: function(newState, message)
|
||||
{
|
||||
var oldFullyConnected = !! padconnectionstatus.isFullyConnected();
|
||||
var wasConnecting = (padconnectionstatus.getStatus().what == 'connecting');
|
||||
if (newState == "CONNECTED")
|
||||
{
|
||||
padconnectionstatus.connected();
|
||||
}
|
||||
else if (newState == "RECONNECTING")
|
||||
{
|
||||
padconnectionstatus.reconnecting();
|
||||
}
|
||||
else if (newState == "DISCONNECTED")
|
||||
{
|
||||
pad.diagnosticInfo.disconnectedMessage = message;
|
||||
pad.diagnosticInfo.padId = pad.getPadId();
|
||||
pad.diagnosticInfo.socket = {};
|
||||
|
||||
//we filter non objects from the socket object and put them in the diagnosticInfo
|
||||
//this ensures we have no cyclic data - this allows us to stringify the data
|
||||
for(var i in socket.socket)
|
||||
{
|
||||
var value = socket.socket[i];
|
||||
var type = typeof value;
|
||||
|
||||
if(type == "string" || type == "number")
|
||||
{
|
||||
pad.diagnosticInfo.socket[i] = value;
|
||||
}
|
||||
}
|
||||
|
||||
pad.asyncSendDiagnosticInfo();
|
||||
if (typeof window.ajlog == "string")
|
||||
{
|
||||
window.ajlog += ("Disconnected: " + message + '\n');
|
||||
}
|
||||
padeditor.disable();
|
||||
padeditbar.disable();
|
||||
paddocbar.disable();
|
||||
padimpexp.disable();
|
||||
|
||||
padconnectionstatus.disconnected(message);
|
||||
}
|
||||
var newFullyConnected = !! padconnectionstatus.isFullyConnected();
|
||||
if (newFullyConnected != oldFullyConnected)
|
||||
{
|
||||
pad.handleIsFullyConnected(newFullyConnected, wasConnecting);
|
||||
}
|
||||
},
|
||||
handleIsFullyConnected: function(isConnected, isInitialConnect)
|
||||
{
|
||||
// load all images referenced from CSS, one at a time,
|
||||
// starting one second after connection is first established.
|
||||
if (isConnected && !pad.preloadedImages)
|
||||
{
|
||||
window.setTimeout(function()
|
||||
{
|
||||
if (!pad.preloadedImages)
|
||||
{
|
||||
pad.preloadImages();
|
||||
pad.preloadedImages = true;
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
padsavedrevs.handleIsFullyConnected(isConnected);
|
||||
|
||||
// pad.determineSidebarVisibility(isConnected && !isInitialConnect);
|
||||
pad.determineChatVisibility(isConnected && !isInitialConnect);
|
||||
|
||||
},
|
||||
/* determineSidebarVisibility: function(asNowConnectedFeedback)
|
||||
{
|
||||
if (pad.isFullyConnected())
|
||||
{
|
||||
var setSidebarVisibility = padutils.getCancellableAction("set-sidebar-visibility", function()
|
||||
{
|
||||
// $("body").toggleClass('hidesidebar', !! padcookie.getPref('hideSidebar'));
|
||||
});
|
||||
window.setTimeout(setSidebarVisibility, asNowConnectedFeedback ? 3000 : 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
padutils.cancelActions("set-sidebar-visibility");
|
||||
$("body").removeClass('hidesidebar');
|
||||
}
|
||||
},
|
||||
*/
|
||||
determineChatVisibility: function(asNowConnectedFeedback){
|
||||
var chatVisCookie = padcookie.getPref('chatAlwaysVisible');
|
||||
if(chatVisCookie){ // if the cookie is set for chat always visible
|
||||
chat.stickToScreen(true); // stick it to the screen
|
||||
$('#options-stickychat').prop("checked", true); // set the checkbox to on
|
||||
}
|
||||
else{
|
||||
$('#options-stickychat').prop("checked", false); // set the checkbox for off
|
||||
}
|
||||
},
|
||||
handleCollabAction: function(action)
|
||||
{
|
||||
if (action == "commitPerformed")
|
||||
{
|
||||
padeditbar.setSyncStatus("syncing");
|
||||
}
|
||||
else if (action == "newlyIdle")
|
||||
{
|
||||
padeditbar.setSyncStatus("done");
|
||||
}
|
||||
},
|
||||
hideServerMessage: function()
|
||||
{
|
||||
alertBar.hideMessage();
|
||||
},
|
||||
asyncSendDiagnosticInfo: function()
|
||||
{
|
||||
window.setTimeout(function()
|
||||
{
|
||||
$.ajax(
|
||||
{
|
||||
type: 'post',
|
||||
url: '/ep/pad/connection-diagnostic-info',
|
||||
data: {
|
||||
diagnosticInfo: JSON.stringify(pad.diagnosticInfo)
|
||||
},
|
||||
success: function()
|
||||
{},
|
||||
error: function()
|
||||
{}
|
||||
});
|
||||
}, 0);
|
||||
},
|
||||
forceReconnect: function()
|
||||
{
|
||||
$('form#reconnectform input.padId').val(pad.getPadId());
|
||||
pad.diagnosticInfo.collabDiagnosticInfo = pad.collabClient.getDiagnosticInfo();
|
||||
$('form#reconnectform input.diagnosticInfo').val(JSON.stringify(pad.diagnosticInfo));
|
||||
$('form#reconnectform input.missedChanges').val(JSON.stringify(pad.collabClient.getMissedChanges()));
|
||||
$('form#reconnectform').submit();
|
||||
},
|
||||
toggleWidthPref: function()
|
||||
{
|
||||
var newValue = !padcookie.getPref('fullWidth');
|
||||
padcookie.setPref('fullWidth', newValue);
|
||||
$("#widthprefcheck").toggleClass('widthprefchecked', !! newValue).toggleClass('widthprefunchecked', !newValue);
|
||||
pad.handleWidthChange();
|
||||
},
|
||||
/*
|
||||
toggleSidebar: function()
|
||||
{
|
||||
var newValue = !padcookie.getPref('hideSidebar');
|
||||
padcookie.setPref('hideSidebar', newValue);
|
||||
$("#sidebarcheck").toggleClass('sidebarchecked', !newValue).toggleClass('sidebarunchecked', !! newValue);
|
||||
pad.determineSidebarVisibility();
|
||||
},
|
||||
*/
|
||||
handleWidthChange: function()
|
||||
{
|
||||
var isFullWidth = padcookie.getPref('fullWidth');
|
||||
if (isFullWidth)
|
||||
{
|
||||
$("body").addClass('fullwidth').removeClass('limwidth').removeClass('squish1width').removeClass('squish2width');
|
||||
}
|
||||
else
|
||||
{
|
||||
$("body").addClass('limwidth').removeClass('fullwidth');
|
||||
|
||||
var pageWidth = $(window).width();
|
||||
$("body").toggleClass('squish1width', (pageWidth < 912 && pageWidth > 812)).toggleClass('squish2width', (pageWidth <= 812));
|
||||
}
|
||||
},
|
||||
// this is called from code put into a frame from the server:
|
||||
handleImportExportFrameCall: function(callName, varargs)
|
||||
{
|
||||
padimpexp.handleFrameCall.call(padimpexp, callName, Array.prototype.slice.call(arguments, 1));
|
||||
},
|
||||
callWhenNotCommitting: function(f)
|
||||
{
|
||||
pad.collabClient.callWhenNotCommitting(f);
|
||||
},
|
||||
getCollabRevisionNumber: function()
|
||||
{
|
||||
return pad.collabClient.getCurrentRevisionNumber();
|
||||
},
|
||||
isFullyConnected: function()
|
||||
{
|
||||
return padconnectionstatus.isFullyConnected();
|
||||
},
|
||||
addHistoricalAuthors: function(data)
|
||||
{
|
||||
if (!pad.collabClient)
|
||||
{
|
||||
window.setTimeout(function()
|
||||
{
|
||||
pad.addHistoricalAuthors(data);
|
||||
}, 1000);
|
||||
}
|
||||
else
|
||||
{
|
||||
pad.collabClient.addHistoricalAuthors(data);
|
||||
}
|
||||
},
|
||||
preloadImages: function()
|
||||
{
|
||||
var images = ["../static/img/connectingbar.gif"];
|
||||
|
||||
function loadNextImage()
|
||||
{
|
||||
if (images.length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var img = new Image();
|
||||
img.src = images.shift();
|
||||
if (img.complete)
|
||||
{
|
||||
scheduleLoadNextImage();
|
||||
}
|
||||
else
|
||||
{
|
||||
$(img).bind('error load onreadystatechange', scheduleLoadNextImage);
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleLoadNextImage()
|
||||
{
|
||||
window.setTimeout(loadNextImage, 0);
|
||||
}
|
||||
scheduleLoadNextImage();
|
||||
}
|
||||
};
|
||||
|
||||
var alertBar = (function()
|
||||
{
|
||||
|
||||
var animator = padutils.makeShowHideAnimator(arriveAtAnimationState, false, 25, 400);
|
||||
|
||||
function arriveAtAnimationState(state)
|
||||
{
|
||||
if (state == -1)
|
||||
{
|
||||
$("#alertbar").css('opacity', 0).css('display', 'block');
|
||||
}
|
||||
else if (state == 0)
|
||||
{
|
||||
$("#alertbar").css('opacity', 1);
|
||||
}
|
||||
else if (state == 1)
|
||||
{
|
||||
$("#alertbar").css('opacity', 0).css('display', 'none');
|
||||
}
|
||||
else if (state < 0)
|
||||
{
|
||||
$("#alertbar").css('opacity', state + 1);
|
||||
}
|
||||
else if (state > 0)
|
||||
{
|
||||
$("#alertbar").css('opacity', 1 - state);
|
||||
}
|
||||
}
|
||||
|
||||
var self = {
|
||||
displayMessage: function(setupFunc)
|
||||
{
|
||||
animator.show();
|
||||
setupFunc($("#alertbar"));
|
||||
},
|
||||
hideMessage: function()
|
||||
{
|
||||
animator.hide();
|
||||
}
|
||||
};
|
||||
return self;
|
||||
}());
|
||||
|
||||
function init() {
|
||||
return pad.init();
|
||||
}
|
||||
|
||||
var settings = {
|
||||
LineNumbersDisabled: false
|
||||
, noColors: false
|
||||
, useMonospaceFontGlobal: false
|
||||
, globalUserName: false
|
||||
, hideQRCode: false
|
||||
, rtlIsTrue: false
|
||||
};
|
||||
|
||||
pad.settings = settings;
|
||||
|
||||
exports.settings = settings;
|
||||
exports.createCookie = createCookie;
|
||||
exports.readCookie = readCookie;
|
||||
exports.randomString = randomString;
|
||||
exports.getParams = getParams;
|
||||
exports.getUrlVars = getUrlVars;
|
||||
exports.savePassword = savePassword;
|
||||
exports.handshake = handshake;
|
||||
exports.pad = pad;
|
||||
exports.init = init;
|
||||
exports.alertBar = alertBar;
|
91
src/static/js/pad_connectionstatus.js
Normal file
|
@ -0,0 +1,91 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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 padmodals = require('/pad_modals').padmodals;
|
||||
|
||||
var padconnectionstatus = (function()
|
||||
{
|
||||
|
||||
var status = {
|
||||
what: 'connecting'
|
||||
};
|
||||
|
||||
var self = {
|
||||
init: function()
|
||||
{
|
||||
$('button#forcereconnect').click(function()
|
||||
{
|
||||
window.location.reload();
|
||||
});
|
||||
},
|
||||
connected: function()
|
||||
{
|
||||
status = {
|
||||
what: 'connected'
|
||||
};
|
||||
padmodals.hideModal(500);
|
||||
},
|
||||
reconnecting: function()
|
||||
{
|
||||
status = {
|
||||
what: 'reconnecting'
|
||||
};
|
||||
$("#connectionbox").get(0).className = 'modaldialog cboxreconnecting';
|
||||
padmodals.showModal("#connectionbox", 500);
|
||||
},
|
||||
disconnected: function(msg)
|
||||
{
|
||||
if(status.what == "disconnected")
|
||||
return;
|
||||
|
||||
status = {
|
||||
what: 'disconnected',
|
||||
why: msg
|
||||
};
|
||||
var k = String(msg).toLowerCase(); // known reason why
|
||||
if (!(k == 'userdup' || k == 'deleted' || k == 'looping' || k == 'slowcommit' || k == 'initsocketfail' || k == 'unauth'))
|
||||
{
|
||||
k = 'unknown';
|
||||
}
|
||||
|
||||
var cls = 'modaldialog cboxdisconnected cboxdisconnected_' + k;
|
||||
$("#connectionbox").get(0).className = cls;
|
||||
padmodals.showModal("#connectionbox", 500);
|
||||
|
||||
$('button#forcereconnect').click(function()
|
||||
{
|
||||
window.location.reload();
|
||||
});
|
||||
},
|
||||
isFullyConnected: function()
|
||||
{
|
||||
return status.what == 'connected';
|
||||
},
|
||||
getStatus: function()
|
||||
{
|
||||
return status;
|
||||
}
|
||||
};
|
||||
return self;
|
||||
}());
|
||||
|
||||
exports.padconnectionstatus = padconnectionstatus;
|
133
src/static/js/pad_cookie.js
Normal file
|
@ -0,0 +1,133 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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 padcookie = (function()
|
||||
{
|
||||
function getRawCookie()
|
||||
{
|
||||
// returns null if can't get cookie text
|
||||
if (!document.cookie)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
// look for (start of string OR semicolon) followed by whitespace followed by prefs=(something);
|
||||
var regexResult = document.cookie.match(/(?:^|;)\s*prefs=([^;]*)(?:;|$)/);
|
||||
if ((!regexResult) || (!regexResult[1]))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return regexResult[1];
|
||||
}
|
||||
|
||||
function setRawCookie(safeText)
|
||||
{
|
||||
var expiresDate = new Date();
|
||||
expiresDate.setFullYear(3000);
|
||||
document.cookie = ('prefs=' + safeText + ';expires=' + expiresDate.toGMTString());
|
||||
}
|
||||
|
||||
function parseCookie(text)
|
||||
{
|
||||
// returns null if can't parse cookie.
|
||||
try
|
||||
{
|
||||
var cookieData = JSON.parse(unescape(text));
|
||||
return cookieData;
|
||||
}
|
||||
catch (e)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function stringifyCookie(data)
|
||||
{
|
||||
return escape(JSON.stringify(data));
|
||||
}
|
||||
|
||||
function saveCookie()
|
||||
{
|
||||
if (!inited)
|
||||
{
|
||||
return;
|
||||
}
|
||||
setRawCookie(stringifyCookie(cookieData));
|
||||
|
||||
if (pad.getIsProPad() && (!getRawCookie()) && (!alreadyWarnedAboutNoCookies))
|
||||
{
|
||||
alert("Warning: it appears that your browser does not have cookies enabled." + " EtherPad uses cookies to keep track of unique users for the purpose" + " of putting a quota on the number of active users. Using EtherPad without " + " cookies may fill up your server's user quota faster than expected.");
|
||||
alreadyWarnedAboutNoCookies = true;
|
||||
}
|
||||
}
|
||||
|
||||
var wasNoCookie = true;
|
||||
var cookieData = {};
|
||||
var alreadyWarnedAboutNoCookies = false;
|
||||
var inited = false;
|
||||
|
||||
var pad = undefined;
|
||||
var self = {
|
||||
init: function(prefsToSet, _pad)
|
||||
{
|
||||
pad = _pad;
|
||||
|
||||
var rawCookie = getRawCookie();
|
||||
if (rawCookie)
|
||||
{
|
||||
var cookieObj = parseCookie(rawCookie);
|
||||
if (cookieObj)
|
||||
{
|
||||
wasNoCookie = false; // there was a cookie
|
||||
delete cookieObj.userId;
|
||||
delete cookieObj.name;
|
||||
delete cookieObj.colorId;
|
||||
cookieData = cookieObj;
|
||||
}
|
||||
}
|
||||
|
||||
for (var k in prefsToSet)
|
||||
{
|
||||
cookieData[k] = prefsToSet[k];
|
||||
}
|
||||
|
||||
inited = true;
|
||||
saveCookie();
|
||||
},
|
||||
wasNoCookie: function()
|
||||
{
|
||||
return wasNoCookie;
|
||||
},
|
||||
getPref: function(prefName)
|
||||
{
|
||||
return cookieData[prefName];
|
||||
},
|
||||
setPref: function(prefName, value)
|
||||
{
|
||||
cookieData[prefName] = value;
|
||||
saveCookie();
|
||||
}
|
||||
};
|
||||
return self;
|
||||
}());
|
||||
|
||||
exports.padcookie = padcookie;
|
466
src/static/js/pad_docbar.js
Normal file
|
@ -0,0 +1,466 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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 padutils = require('/pad_utils').padutils;
|
||||
|
||||
var paddocbar = (function()
|
||||
{
|
||||
var isTitleEditable = false;
|
||||
var isEditingTitle = false;
|
||||
var isEditingPassword = false;
|
||||
var enabled = false;
|
||||
|
||||
function getPanelOpenCloseAnimator(panelName, panelHeight)
|
||||
{
|
||||
var wrapper = $("#" + panelName + "-wrapper");
|
||||
var openingClass = "docbar" + panelName + "-opening";
|
||||
var openClass = "docbar" + panelName + "-open";
|
||||
var closingClass = "docbar" + panelName + "-closing";
|
||||
|
||||
function setPanelState(action)
|
||||
{
|
||||
$("#docbar").removeClass(openingClass).removeClass(openClass).
|
||||
removeClass(closingClass);
|
||||
if (action != "closed")
|
||||
{
|
||||
$("#docbar").addClass("docbar" + panelName + "-" + action);
|
||||
}
|
||||
}
|
||||
|
||||
function openCloseAnimate(state)
|
||||
{
|
||||
function pow(x)
|
||||
{
|
||||
x = 1 - x;
|
||||
x *= x * x;
|
||||
return 1 - x;
|
||||
}
|
||||
|
||||
if (state == -1)
|
||||
{
|
||||
// startng to open
|
||||
setPanelState("opening");
|
||||
wrapper.css('height', '0');
|
||||
}
|
||||
else if (state < 0)
|
||||
{
|
||||
// opening
|
||||
var height = Math.round(pow(state + 1) * (panelHeight - 1)) + 'px';
|
||||
wrapper.css('height', height);
|
||||
}
|
||||
else if (state == 0)
|
||||
{
|
||||
// open
|
||||
setPanelState("open");
|
||||
wrapper.css('height', panelHeight - 1);
|
||||
}
|
||||
else if (state < 1)
|
||||
{
|
||||
// closing
|
||||
setPanelState("closing");
|
||||
var height = Math.round((1 - pow(state)) * (panelHeight - 1)) + 'px';
|
||||
wrapper.css('height', height);
|
||||
}
|
||||
else if (state == 1)
|
||||
{
|
||||
// closed
|
||||
setPanelState("closed");
|
||||
wrapper.css('height', '0');
|
||||
}
|
||||
}
|
||||
|
||||
return padutils.makeShowHideAnimator(openCloseAnimate, false, 25, 500);
|
||||
}
|
||||
|
||||
|
||||
var currentPanel = null;
|
||||
|
||||
function setCurrentPanel(newCurrentPanel)
|
||||
{
|
||||
if (currentPanel != newCurrentPanel)
|
||||
{
|
||||
currentPanel = newCurrentPanel;
|
||||
padutils.cancelActions("hide-docbar-panel");
|
||||
}
|
||||
}
|
||||
var panels;
|
||||
|
||||
function changePassword(newPass)
|
||||
{
|
||||
if ((newPass || null) != (self.password || null))
|
||||
{
|
||||
self.password = (newPass || null);
|
||||
pad.notifyChangePassword(newPass);
|
||||
}
|
||||
self.renderPassword();
|
||||
}
|
||||
|
||||
var pad = undefined;
|
||||
var self = {
|
||||
title: null,
|
||||
password: null,
|
||||
init: function(opts, _pad)
|
||||
{
|
||||
pad = _pad;
|
||||
|
||||
panels = {
|
||||
impexp: {
|
||||
animator: getPanelOpenCloseAnimator("impexp", 160)
|
||||
},
|
||||
savedrevs: {
|
||||
animator: getPanelOpenCloseAnimator("savedrevs", 79)
|
||||
},
|
||||
options: {
|
||||
animator: getPanelOpenCloseAnimator("options", 114)
|
||||
},
|
||||
security: {
|
||||
animator: getPanelOpenCloseAnimator("security", 130)
|
||||
}
|
||||
};
|
||||
|
||||
isTitleEditable = opts.isTitleEditable;
|
||||
self.title = opts.initialTitle;
|
||||
self.password = opts.initialPassword;
|
||||
|
||||
$("#docbarimpexp").click(function()
|
||||
{
|
||||
self.togglePanel("impexp");
|
||||
});
|
||||
$("#docbarsavedrevs").click(function()
|
||||
{
|
||||
self.togglePanel("savedrevs");
|
||||
});
|
||||
$("#docbaroptions").click(function()
|
||||
{
|
||||
self.togglePanel("options");
|
||||
});
|
||||
$("#docbarsecurity").click(function()
|
||||
{
|
||||
self.togglePanel("security");
|
||||
});
|
||||
|
||||
$("#docbarrenamelink").click(self.editTitle);
|
||||
$("#padtitlesave").click(function()
|
||||
{
|
||||
self.closeTitleEdit(true);
|
||||
});
|
||||
$("#padtitlecancel").click(function()
|
||||
{
|
||||
self.closeTitleEdit(false);
|
||||
});
|
||||
padutils.bindEnterAndEscape($("#padtitleedit"), function()
|
||||
{
|
||||
$("#padtitlesave").trigger('click');
|
||||
}, function()
|
||||
{
|
||||
$("#padtitlecancel").trigger('click');
|
||||
});
|
||||
|
||||
$("#options-close").click(function()
|
||||
{
|
||||
self.setShownPanel(null);
|
||||
});
|
||||
$("#security-close").click(function()
|
||||
{
|
||||
self.setShownPanel(null);
|
||||
});
|
||||
|
||||
if (pad.getIsProPad())
|
||||
{
|
||||
self.initPassword();
|
||||
}
|
||||
|
||||
enabled = true;
|
||||
self.render();
|
||||
|
||||
// public/private
|
||||
$("#security-access input").bind("change click", function(evt)
|
||||
{
|
||||
pad.changePadOption('guestPolicy', $("#security-access input[name='padaccess']:checked").val());
|
||||
});
|
||||
self.setGuestPolicy(opts.guestPolicy);
|
||||
},
|
||||
setGuestPolicy: function(newPolicy)
|
||||
{
|
||||
$("#security-access input[value='" + newPolicy + "']").attr("checked", "checked");
|
||||
self.render();
|
||||
},
|
||||
initPassword: function()
|
||||
{
|
||||
self.renderPassword();
|
||||
$("#password-clearlink").click(function()
|
||||
{
|
||||
changePassword(null);
|
||||
});
|
||||
$("#password-setlink, #password-display").click(function()
|
||||
{
|
||||
self.enterPassword();
|
||||
});
|
||||
$("#password-cancellink").click(function()
|
||||
{
|
||||
self.exitPassword(false);
|
||||
});
|
||||
$("#password-savelink").click(function()
|
||||
{
|
||||
self.exitPassword(true);
|
||||
});
|
||||
padutils.bindEnterAndEscape($("#security-passwordedit"), function()
|
||||
{
|
||||
self.exitPassword(true);
|
||||
}, function()
|
||||
{
|
||||
self.exitPassword(false);
|
||||
});
|
||||
},
|
||||
enterPassword: function()
|
||||
{
|
||||
isEditingPassword = true;
|
||||
$("#security-passwordedit").val(self.password || '');
|
||||
self.renderPassword();
|
||||
$("#security-passwordedit").focus().select();
|
||||
},
|
||||
exitPassword: function(accept)
|
||||
{
|
||||
isEditingPassword = false;
|
||||
if (accept)
|
||||
{
|
||||
changePassword($("#security-passwordedit").val());
|
||||
}
|
||||
else
|
||||
{
|
||||
self.renderPassword();
|
||||
}
|
||||
},
|
||||
renderPassword: function()
|
||||
{
|
||||
if (isEditingPassword)
|
||||
{
|
||||
$("#password-nonedit").hide();
|
||||
$("#password-inedit").show();
|
||||
}
|
||||
else
|
||||
{
|
||||
$("#password-nonedit").toggleClass('nopassword', !self.password);
|
||||
$("#password-setlink").html(self.password ? "Change..." : "Set...");
|
||||
if (self.password)
|
||||
{
|
||||
$("#password-display").html(self.password.replace(/./g, '•'));
|
||||
}
|
||||
else
|
||||
{
|
||||
$("#password-display").html("None");
|
||||
}
|
||||
$("#password-inedit").hide();
|
||||
$("#password-nonedit").show();
|
||||
}
|
||||
},
|
||||
togglePanel: function(panelName)
|
||||
{
|
||||
if (panelName in panels)
|
||||
{
|
||||
if (currentPanel == panelName)
|
||||
{
|
||||
self.setShownPanel(null);
|
||||
}
|
||||
else
|
||||
{
|
||||
self.setShownPanel(panelName);
|
||||
}
|
||||
}
|
||||
},
|
||||
setShownPanel: function(panelName)
|
||||
{
|
||||
function animateHidePanel(panelName, next)
|
||||
{
|
||||
var delay = 0;
|
||||
if (panelName == 'options' && isEditingPassword)
|
||||
{
|
||||
// give user feedback that the password they've
|
||||
// typed in won't actually take effect
|
||||
self.exitPassword(false);
|
||||
delay = 500;
|
||||
}
|
||||
|
||||
window.setTimeout(function()
|
||||
{
|
||||
panels[panelName].animator.hide();
|
||||
if (next)
|
||||
{
|
||||
next();
|
||||
}
|
||||
}, delay);
|
||||
}
|
||||
|
||||
if (!panelName)
|
||||
{
|
||||
if (currentPanel)
|
||||
{
|
||||
animateHidePanel(currentPanel);
|
||||
setCurrentPanel(null);
|
||||
}
|
||||
}
|
||||
else if (panelName in panels)
|
||||
{
|
||||
if (currentPanel != panelName)
|
||||
{
|
||||
if (currentPanel)
|
||||
{
|
||||
animateHidePanel(currentPanel, function()
|
||||
{
|
||||
panels[panelName].animator.show();
|
||||
setCurrentPanel(panelName);
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
panels[panelName].animator.show();
|
||||
setCurrentPanel(panelName);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
isPanelShown: function(panelName)
|
||||
{
|
||||
if (!panelName)
|
||||
{
|
||||
return !currentPanel;
|
||||
}
|
||||
else
|
||||
{
|
||||
return (panelName == currentPanel);
|
||||
}
|
||||
},
|
||||
changeTitle: function(newTitle)
|
||||
{
|
||||
self.title = newTitle;
|
||||
self.render();
|
||||
},
|
||||
editTitle: function()
|
||||
{
|
||||
if (!enabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
$("#padtitleedit").val(self.title);
|
||||
isEditingTitle = true;
|
||||
self.render();
|
||||
$("#padtitleedit").focus().select();
|
||||
},
|
||||
closeTitleEdit: function(accept)
|
||||
{
|
||||
if (!enabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (accept)
|
||||
{
|
||||
var newTitle = $("#padtitleedit").val();
|
||||
if (newTitle)
|
||||
{
|
||||
newTitle = newTitle.substring(0, 80);
|
||||
self.title = newTitle;
|
||||
|
||||
pad.notifyChangeTitle(newTitle);
|
||||
}
|
||||
}
|
||||
|
||||
isEditingTitle = false;
|
||||
self.render();
|
||||
},
|
||||
changePassword: function(newPass)
|
||||
{
|
||||
if (newPass)
|
||||
{
|
||||
self.password = newPass;
|
||||
}
|
||||
else
|
||||
{
|
||||
self.password = null;
|
||||
}
|
||||
self.renderPassword();
|
||||
},
|
||||
render: function()
|
||||
{
|
||||
if (isEditingTitle)
|
||||
{
|
||||
$("#docbarpadtitle").hide();
|
||||
$("#docbarrenamelink").hide();
|
||||
$("#padtitleedit").show();
|
||||
$("#padtitlebuttons").show();
|
||||
if (!enabled)
|
||||
{
|
||||
$("#padtitleedit").attr('disabled', 'disabled');
|
||||
}
|
||||
else
|
||||
{
|
||||
$("#padtitleedit").removeAttr('disabled');
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$("#padtitleedit").hide();
|
||||
$("#padtitlebuttons").hide();
|
||||
|
||||
var titleSpan = $("#docbarpadtitle span");
|
||||
titleSpan.html(padutils.escapeHtml(self.title));
|
||||
$("#docbarpadtitle").attr('title', (pad.isPadPublic() ? "Public Pad: " : "") + self.title);
|
||||
$("#docbarpadtitle").show();
|
||||
|
||||
if (isTitleEditable)
|
||||
{
|
||||
var titleRight = $("#docbarpadtitle").position().left + $("#docbarpadtitle span").position().left + Math.min($("#docbarpadtitle").width(), $("#docbarpadtitle span").width());
|
||||
$("#docbarrenamelink").css('left', titleRight + 10).show();
|
||||
}
|
||||
|
||||
if (pad.isPadPublic())
|
||||
{
|
||||
$("#docbar").addClass("docbar-public");
|
||||
}
|
||||
else
|
||||
{
|
||||
$("#docbar").removeClass("docbar-public");
|
||||
}
|
||||
}
|
||||
},
|
||||
disable: function()
|
||||
{
|
||||
enabled = false;
|
||||
self.render();
|
||||
},
|
||||
handleResizePage: function()
|
||||
{
|
||||
// Side-step circular reference. This should be injected.
|
||||
var padsavedrevs = require('/pad_savedrevs').padsavedrevs;
|
||||
padsavedrevs.handleResizePage();
|
||||
},
|
||||
hideLaterIfNoOtherInteraction: function()
|
||||
{
|
||||
return padutils.getCancellableAction('hide-docbar-panel', function()
|
||||
{
|
||||
self.setShownPanel(null);
|
||||
});
|
||||
}
|
||||
};
|
||||
return self;
|
||||
}());
|
||||
|
||||
exports.paddocbar = paddocbar;
|
256
src/static/js/pad_editbar.js
Normal file
|
@ -0,0 +1,256 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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 padutils = require('/pad_utils').padutils;
|
||||
var padeditor = require('/pad_editor').padeditor;
|
||||
var padsavedrevs = require('/pad_savedrevs').padsavedrevs;
|
||||
|
||||
function indexOf(array, value) {
|
||||
for (var i = 0, ii = array.length; i < ii; i++) {
|
||||
if (array[i] == value) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
var padeditbar = (function()
|
||||
{
|
||||
|
||||
var syncAnimation = (function()
|
||||
{
|
||||
var SYNCING = -100;
|
||||
var DONE = 100;
|
||||
var state = DONE;
|
||||
var fps = 25;
|
||||
var step = 1 / fps;
|
||||
var T_START = -0.5;
|
||||
var T_FADE = 1.0;
|
||||
var T_GONE = 1.5;
|
||||
var animator = padutils.makeAnimationScheduler(function()
|
||||
{
|
||||
if (state == SYNCING || state == DONE)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else if (state >= T_GONE)
|
||||
{
|
||||
state = DONE;
|
||||
$("#syncstatussyncing").css('display', 'none');
|
||||
$("#syncstatusdone").css('display', 'none');
|
||||
return false;
|
||||
}
|
||||
else if (state < 0)
|
||||
{
|
||||
state += step;
|
||||
if (state >= 0)
|
||||
{
|
||||
$("#syncstatussyncing").css('display', 'none');
|
||||
$("#syncstatusdone").css('display', 'block').css('opacity', 1);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
state += step;
|
||||
if (state >= T_FADE)
|
||||
{
|
||||
$("#syncstatusdone").css('opacity', (T_GONE - state) / (T_GONE - T_FADE));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}, step * 1000);
|
||||
return {
|
||||
syncing: function()
|
||||
{
|
||||
state = SYNCING;
|
||||
$("#syncstatussyncing").css('display', 'block');
|
||||
$("#syncstatusdone").css('display', 'none');
|
||||
},
|
||||
done: function()
|
||||
{
|
||||
state = T_START;
|
||||
animator.scheduleAnimation();
|
||||
}
|
||||
};
|
||||
}());
|
||||
|
||||
var self = {
|
||||
init: function()
|
||||
{
|
||||
$("#editbar .editbarbutton").attr("unselectable", "on"); // for IE
|
||||
$("#editbar").removeClass("disabledtoolbar").addClass("enabledtoolbar");
|
||||
},
|
||||
isEnabled: function()
|
||||
{
|
||||
// return !$("#editbar").hasClass('disabledtoolbar');
|
||||
return true;
|
||||
},
|
||||
disable: function()
|
||||
{
|
||||
$("#editbar").addClass('disabledtoolbar').removeClass("enabledtoolbar");
|
||||
},
|
||||
toolbarClick: function(cmd)
|
||||
{
|
||||
if (self.isEnabled())
|
||||
{
|
||||
if(cmd == "showusers")
|
||||
{
|
||||
self.toogleDropDown("users");
|
||||
}
|
||||
else if (cmd == 'settings')
|
||||
{
|
||||
self.toogleDropDown("settingsmenu");
|
||||
}
|
||||
else if (cmd == 'embed')
|
||||
{
|
||||
self.setEmbedLinks();
|
||||
$('#linkinput').focus().select();
|
||||
self.toogleDropDown("embed");
|
||||
}
|
||||
else if (cmd == 'import_export')
|
||||
{
|
||||
self.toogleDropDown("importexport");
|
||||
}
|
||||
else if (cmd == 'save')
|
||||
{
|
||||
padsavedrevs.saveNow();
|
||||
}
|
||||
else
|
||||
{
|
||||
padeditor.ace.callWithAce(function(ace)
|
||||
{
|
||||
if (cmd == 'bold' || cmd == 'italic' || cmd == 'underline' || cmd == 'strikethrough') ace.ace_toggleAttributeOnSelection(cmd);
|
||||
else if (cmd == 'undo' || cmd == 'redo') ace.ace_doUndoRedo(cmd);
|
||||
else if (cmd == 'insertunorderedlist') ace.ace_doInsertUnorderedList();
|
||||
else if (cmd == 'insertorderedlist') ace.ace_doInsertOrderedList();
|
||||
else if (cmd == 'indent')
|
||||
{
|
||||
if (!ace.ace_doIndentOutdent(false))
|
||||
{
|
||||
ace.ace_doInsertUnorderedList();
|
||||
}
|
||||
}
|
||||
else if (cmd == 'outdent')
|
||||
{
|
||||
ace.ace_doIndentOutdent(true);
|
||||
}
|
||||
else if (cmd == 'clearauthorship')
|
||||
{
|
||||
if ((!(ace.ace_getRep().selStart && ace.ace_getRep().selEnd)) || ace.ace_isCaret())
|
||||
{
|
||||
if (window.confirm("Clear authorship colors on entire document?"))
|
||||
{
|
||||
ace.ace_performDocumentApplyAttributesToCharRange(0, ace.ace_getRep().alltext.length, [
|
||||
['author', '']
|
||||
]);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ace.ace_setAttributeOnSelection('author', '');
|
||||
}
|
||||
}
|
||||
}, cmd, true);
|
||||
}
|
||||
}
|
||||
if(padeditor.ace) padeditor.ace.focus();
|
||||
},
|
||||
toogleDropDown: function(moduleName)
|
||||
{
|
||||
var modules = ["settingsmenu", "importexport", "embed", "users"];
|
||||
|
||||
//hide all modules
|
||||
if(moduleName == "none")
|
||||
{
|
||||
$("#editbar ul#menu_right > li").removeClass("selected");
|
||||
for(var i=0;i<modules.length;i++)
|
||||
{
|
||||
//skip the userlist
|
||||
if(modules[i] == "users")
|
||||
continue;
|
||||
|
||||
var module = $("#" + modules[i]);
|
||||
|
||||
if(module.css('display') != "none")
|
||||
{
|
||||
module.slideUp("fast");
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var nth_child = indexOf(modules, moduleName) + 1;
|
||||
if (nth_child > 0 && nth_child <= 3) {
|
||||
$("#editbar ul#menu_right li:not(:nth-child(" + nth_child + "))").removeClass("selected");
|
||||
$("#editbar ul#menu_right li:nth-child(" + nth_child + ")").toggleClass("selected");
|
||||
}
|
||||
//hide all modules that are not selected and show the selected one
|
||||
for(var i=0;i<modules.length;i++)
|
||||
{
|
||||
var module = $("#" + modules[i]);
|
||||
|
||||
if(module.css('display') != "none")
|
||||
{
|
||||
module.slideUp("fast");
|
||||
}
|
||||
else if(modules[i]==moduleName)
|
||||
{
|
||||
module.slideDown("fast");
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
setSyncStatus: function(status)
|
||||
{
|
||||
if (status == "syncing")
|
||||
{
|
||||
syncAnimation.syncing();
|
||||
}
|
||||
else if (status == "done")
|
||||
{
|
||||
syncAnimation.done();
|
||||
}
|
||||
},
|
||||
setEmbedLinks: function()
|
||||
{
|
||||
if ($('#readonlyinput').is(':checked'))
|
||||
{
|
||||
var basePath = document.location.href.substring(0, document.location.href.indexOf("/p/"));
|
||||
var readonlyLink = basePath + "/ro/" + clientVars.readOnlyId;
|
||||
$('#embedinput').val("<iframe src='" + readonlyLink + "?showControls=true&showChat=true&showLineNumbers=true&useMonospaceFont=false' width=600 height=400>");
|
||||
$('#linkinput').val(readonlyLink);
|
||||
$('#embedreadonlyqr').attr("src","https://chart.googleapis.com/chart?chs=200x200&cht=qr&chld=H|0&chl=" + readonlyLink);
|
||||
}
|
||||
else
|
||||
{
|
||||
var padurl = window.location.href.split("?")[0];
|
||||
$('#embedinput').val("<iframe src='" + padurl + "?showControls=true&showChat=true&showLineNumbers=true&useMonospaceFont=false' width=600 height=400>");
|
||||
$('#linkinput').val(padurl);
|
||||
$('#embedreadonlyqr').attr("src","https://chart.googleapis.com/chart?chs=200x200&cht=qr&chld=H|0&chl=" + padurl);
|
||||
}
|
||||
}
|
||||
};
|
||||
return self;
|
||||
}());
|
||||
|
||||
exports.padeditbar = padeditbar;
|
162
src/static/js/pad_editor.js
Normal file
|
@ -0,0 +1,162 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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 padcookie = require('/pad_cookie').padcookie;
|
||||
var padutils = require('/pad_utils').padutils;
|
||||
|
||||
var padeditor = (function()
|
||||
{
|
||||
var Ace2Editor = undefined;
|
||||
var pad = undefined;
|
||||
var settings = undefined;
|
||||
var self = {
|
||||
ace: null,
|
||||
// this is accessed directly from other files
|
||||
viewZoom: 100,
|
||||
init: function(readyFunc, initialViewOptions, _pad)
|
||||
{
|
||||
Ace2Editor = require('/ace').Ace2Editor;
|
||||
pad = _pad;
|
||||
settings = pad.settings;
|
||||
|
||||
function aceReady()
|
||||
{
|
||||
$("#editorloadingbox").hide();
|
||||
if (readyFunc)
|
||||
{
|
||||
readyFunc();
|
||||
}
|
||||
}
|
||||
|
||||
self.ace = new Ace2Editor();
|
||||
self.ace.init("editorcontainer", "", aceReady);
|
||||
self.ace.setProperty("wraps", true);
|
||||
if (pad.getIsDebugEnabled())
|
||||
{
|
||||
self.ace.setProperty("dmesg", pad.dmesg);
|
||||
}
|
||||
self.initViewOptions();
|
||||
self.setViewOptions(initialViewOptions);
|
||||
|
||||
// view bar
|
||||
self.initViewZoom();
|
||||
$("#viewbarcontents").show();
|
||||
},
|
||||
initViewOptions: function()
|
||||
{
|
||||
padutils.bindCheckboxChange($("#options-linenoscheck"), function()
|
||||
{
|
||||
pad.changeViewOption('showLineNumbers', padutils.getCheckbox($("#options-linenoscheck")));
|
||||
});
|
||||
padutils.bindCheckboxChange($("#options-colorscheck"), function()
|
||||
{
|
||||
pad.changeViewOption('showAuthorColors', padutils.getCheckbox("#options-colorscheck"));
|
||||
});
|
||||
$("#viewfontmenu").change(function()
|
||||
{
|
||||
pad.changeViewOption('useMonospaceFont', $("#viewfontmenu").val() == 'monospace');
|
||||
});
|
||||
},
|
||||
setViewOptions: function(newOptions)
|
||||
{
|
||||
function getOption(key, defaultValue)
|
||||
{
|
||||
var value = String(newOptions[key]);
|
||||
if (value == "true") return true;
|
||||
if (value == "false") return false;
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
self.ace.setProperty("showsauthorcolors", !settings.noColors);
|
||||
|
||||
self.ace.setProperty("rtlIsTrue", settings.rtlIsTrue);
|
||||
|
||||
var v;
|
||||
|
||||
v = getOption('showLineNumbers', true);
|
||||
self.ace.setProperty("showslinenumbers", v);
|
||||
padutils.setCheckbox($("#options-linenoscheck"), v);
|
||||
|
||||
v = getOption('showAuthorColors', true);
|
||||
self.ace.setProperty("showsauthorcolors", v);
|
||||
padutils.setCheckbox($("#options-colorscheck"), v);
|
||||
|
||||
v = getOption('useMonospaceFont', false);
|
||||
self.ace.setProperty("textface", (v ? "monospace" : "Arial, sans-serif"));
|
||||
$("#viewfontmenu").val(v ? "monospace" : "normal");
|
||||
},
|
||||
initViewZoom: function()
|
||||
{
|
||||
var viewZoom = Number(padcookie.getPref('viewZoom'));
|
||||
if ((!viewZoom) || isNaN(viewZoom))
|
||||
{
|
||||
viewZoom = 100;
|
||||
}
|
||||
self.setViewZoom(viewZoom);
|
||||
$("#viewzoommenu").change(function(evt)
|
||||
{
|
||||
// strip initial 'z' from val
|
||||
self.setViewZoom(Number($("#viewzoommenu").val().substring(1)));
|
||||
});
|
||||
},
|
||||
setViewZoom: function(percent)
|
||||
{
|
||||
if (!(percent >= 50 && percent <= 1000))
|
||||
{
|
||||
// percent is out of sane range or NaN (which fails comparisons)
|
||||
return;
|
||||
}
|
||||
|
||||
self.viewZoom = percent;
|
||||
$("#viewzoommenu").val('z' + percent);
|
||||
|
||||
var baseSize = 13;
|
||||
self.ace.setProperty('textsize', Math.round(baseSize * self.viewZoom / 100));
|
||||
|
||||
padcookie.setPref('viewZoom', percent);
|
||||
},
|
||||
dispose: function()
|
||||
{
|
||||
if (self.ace)
|
||||
{
|
||||
self.ace.destroy();
|
||||
self.ace = null;
|
||||
}
|
||||
},
|
||||
disable: function()
|
||||
{
|
||||
if (self.ace)
|
||||
{
|
||||
self.ace.setProperty("grayedOut", true);
|
||||
self.ace.setEditable(false);
|
||||
}
|
||||
},
|
||||
restoreRevisionText: function(dataFromServer)
|
||||
{
|
||||
pad.addHistoricalAuthors(dataFromServer.historicalAuthorData);
|
||||
self.ace.importAText(dataFromServer.atext, dataFromServer.apool, true);
|
||||
}
|
||||
};
|
||||
return self;
|
||||
}());
|
||||
|
||||
exports.padeditor = padeditor;
|
333
src/static/js/pad_impexp.js
Normal file
|
@ -0,0 +1,333 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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 paddocbar = require('/pad_docbar').paddocbar;
|
||||
|
||||
var padimpexp = (function()
|
||||
{
|
||||
|
||||
///// import
|
||||
var currentImportTimer = null;
|
||||
var hidePanelCall = null;
|
||||
|
||||
function addImportFrames()
|
||||
{
|
||||
$("#import .importframe").remove();
|
||||
var iframe = $('<iframe style="display: none;" name="importiframe" class="importframe"></iframe>');
|
||||
$('#import').append(iframe);
|
||||
}
|
||||
|
||||
function fileInputUpdated()
|
||||
{
|
||||
$('#importformfilediv').addClass('importformenabled');
|
||||
$('#importsubmitinput').removeAttr('disabled');
|
||||
$('#importmessagefail').fadeOut("fast");
|
||||
$('#importarrow').show();
|
||||
$('#importarrow').animate(
|
||||
{
|
||||
paddingLeft: "0px"
|
||||
}, 500).animate(
|
||||
{
|
||||
paddingLeft: "10px"
|
||||
}, 150, 'swing').animate(
|
||||
{
|
||||
paddingLeft: "0px"
|
||||
}, 150, 'swing').animate(
|
||||
{
|
||||
paddingLeft: "10px"
|
||||
}, 150, 'swing').animate(
|
||||
{
|
||||
paddingLeft: "0px"
|
||||
}, 150, 'swing').animate(
|
||||
{
|
||||
paddingLeft: "10px"
|
||||
}, 150, 'swing').animate(
|
||||
{
|
||||
paddingLeft: "0px"
|
||||
}, 150, 'swing');
|
||||
}
|
||||
|
||||
function fileInputSubmit()
|
||||
{
|
||||
$('#importmessagefail').fadeOut("fast");
|
||||
var ret = window.confirm("Importing a file will overwrite the current text of the pad." + " Are you sure you want to proceed?");
|
||||
if (ret)
|
||||
{
|
||||
hidePanelCall = paddocbar.hideLaterIfNoOtherInteraction();
|
||||
currentImportTimer = window.setTimeout(function()
|
||||
{
|
||||
if (!currentImportTimer)
|
||||
{
|
||||
return;
|
||||
}
|
||||
currentImportTimer = null;
|
||||
importFailed("Request timed out.");
|
||||
}, 25000); // time out after some number of seconds
|
||||
$('#importsubmitinput').attr(
|
||||
{
|
||||
disabled: true
|
||||
}).val("Importing...");
|
||||
window.setTimeout(function()
|
||||
{
|
||||
$('#importfileinput').attr(
|
||||
{
|
||||
disabled: true
|
||||
});
|
||||
}, 0);
|
||||
$('#importarrow').stop(true, true).hide();
|
||||
$('#importstatusball').show();
|
||||
|
||||
$("#import .importframe").load(function()
|
||||
{
|
||||
importDone();
|
||||
});
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
function importFailed(msg)
|
||||
{
|
||||
importErrorMessage(msg);
|
||||
importDone();
|
||||
addImportFrames();
|
||||
}
|
||||
|
||||
function importDone()
|
||||
{
|
||||
$('#importsubmitinput').removeAttr('disabled').val("Import Now");
|
||||
window.setTimeout(function()
|
||||
{
|
||||
$('#importfileinput').removeAttr('disabled');
|
||||
}, 0);
|
||||
$('#importstatusball').hide();
|
||||
importClearTimeout();
|
||||
}
|
||||
|
||||
function importClearTimeout()
|
||||
{
|
||||
if (currentImportTimer)
|
||||
{
|
||||
window.clearTimeout(currentImportTimer);
|
||||
currentImportTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function importErrorMessage(msg)
|
||||
{
|
||||
function showError(fade)
|
||||
{
|
||||
$('#importmessagefail').html('<strong style="color: red">Import failed:</strong> ' + (msg || 'Please try a different file.'))[(fade ? "fadeIn" : "show")]();
|
||||
}
|
||||
|
||||
if ($('#importexport .importmessage').is(':visible'))
|
||||
{
|
||||
$('#importmessagesuccess').fadeOut("fast");
|
||||
$('#importmessagefail').fadeOut("fast", function()
|
||||
{
|
||||
showError(true);
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
showError();
|
||||
}
|
||||
}
|
||||
|
||||
function importSuccessful(token)
|
||||
{
|
||||
$.ajax(
|
||||
{
|
||||
type: 'post',
|
||||
url: '/ep/pad/impexp/import2',
|
||||
data: {
|
||||
token: token,
|
||||
padId: pad.getPadId()
|
||||
},
|
||||
success: importApplicationSuccessful,
|
||||
error: importApplicationFailed,
|
||||
timeout: 25000
|
||||
});
|
||||
addImportFrames();
|
||||
}
|
||||
|
||||
function importApplicationFailed(xhr, textStatus, errorThrown)
|
||||
{
|
||||
importErrorMessage("Error during conversion.");
|
||||
importDone();
|
||||
}
|
||||
|
||||
function importApplicationSuccessful(data, textStatus)
|
||||
{
|
||||
if (data.substr(0, 2) == "ok")
|
||||
{
|
||||
if ($('#importexport .importmessage').is(':visible'))
|
||||
{
|
||||
$('#importexport .importmessage').hide();
|
||||
}
|
||||
$('#importmessagesuccess').html('<strong style="color: green">Import successful!</strong>').show();
|
||||
$('#importformfilediv').hide();
|
||||
window.setTimeout(function()
|
||||
{
|
||||
$('#importmessagesuccess').fadeOut("slow", function()
|
||||
{
|
||||
$('#importformfilediv').show();
|
||||
});
|
||||
if (hidePanelCall)
|
||||
{
|
||||
hidePanelCall();
|
||||
}
|
||||
}, 3000);
|
||||
}
|
||||
else if (data.substr(0, 4) == "fail")
|
||||
{
|
||||
importErrorMessage("Couldn't update pad contents. This can happen if your web browser has \"cookies\" disabled.");
|
||||
}
|
||||
else if (data.substr(0, 4) == "msg:")
|
||||
{
|
||||
importErrorMessage(data.substr(4));
|
||||
}
|
||||
importDone();
|
||||
}
|
||||
|
||||
///// export
|
||||
|
||||
function cantExport()
|
||||
{
|
||||
var type = $(this);
|
||||
if (type.hasClass("exporthrefpdf"))
|
||||
{
|
||||
type = "PDF";
|
||||
}
|
||||
else if (type.hasClass("exporthrefdoc"))
|
||||
{
|
||||
type = "Microsoft Word";
|
||||
}
|
||||
else if (type.hasClass("exporthrefodt"))
|
||||
{
|
||||
type = "OpenDocument";
|
||||
}
|
||||
else
|
||||
{
|
||||
type = "this file";
|
||||
}
|
||||
alert("Exporting as " + type + " format is disabled. Please contact your" + " system administrator for details.");
|
||||
return false;
|
||||
}
|
||||
|
||||
/////
|
||||
var pad = undefined;
|
||||
var self = {
|
||||
init: function(_pad)
|
||||
{
|
||||
pad = _pad;
|
||||
|
||||
//get /p/padname
|
||||
var pad_root_path = new RegExp(/.*\/p\/[^\/]+/).exec(document.location.pathname)
|
||||
//get http://example.com/p/padname
|
||||
var pad_root_url = document.location.href.replace(document.location.pathname, pad_root_path)
|
||||
|
||||
// build the export links
|
||||
$("#exporthtmla").attr("href", pad_root_path + "/export/html");
|
||||
$("#exportplaina").attr("href", pad_root_path + "/export/txt");
|
||||
$("#exportwordlea").attr("href", pad_root_path + "/export/wordle");
|
||||
$("#exportdokuwikia").attr("href", pad_root_path + "/export/dokuwiki");
|
||||
|
||||
//hide stuff thats not avaible if abiword is disabled
|
||||
if(clientVars.abiwordAvailable == "no")
|
||||
{
|
||||
$("#exportworda").remove();
|
||||
$("#exportpdfa").remove();
|
||||
$("#exportopena").remove();
|
||||
$("#importexport").css({"height":"115px"});
|
||||
$("#importexportline").css({"height":"115px"});
|
||||
$("#import").html("Import is not available. To enable import please install abiword");
|
||||
}
|
||||
else if(clientVars.abiwordAvailable == "withoutPDF")
|
||||
{
|
||||
$("#exportpdfa").remove();
|
||||
|
||||
$("#exportworda").attr("href", pad_root_path + "/export/doc");
|
||||
$("#exportopena").attr("href", pad_root_path + "/export/odt");
|
||||
|
||||
$("#importexport").css({"height":"142px"});
|
||||
$("#importexportline").css({"height":"142px"});
|
||||
|
||||
$("#importform").attr('action', pad_root_url + "/import");
|
||||
}
|
||||
else
|
||||
{
|
||||
$("#exportworda").attr("href", pad_root_path + "/export/doc");
|
||||
$("#exportpdfa").attr("href", pad_root_path + "/export/pdf");
|
||||
$("#exportopena").attr("href", pad_root_path + "/export/odt");
|
||||
|
||||
$("#importform").attr('action', pad_root_path + "/import");
|
||||
}
|
||||
|
||||
$("#impexp-close").click(function()
|
||||
{
|
||||
paddocbar.setShownPanel(null);
|
||||
});
|
||||
|
||||
addImportFrames();
|
||||
$("#importfileinput").change(fileInputUpdated);
|
||||
$('#importform').submit(fileInputSubmit);
|
||||
$('.disabledexport').click(cantExport);
|
||||
},
|
||||
handleFrameCall: function(callName, argsArray)
|
||||
{
|
||||
if (callName == 'importFailed')
|
||||
{
|
||||
importFailed(argsArray[0]);
|
||||
}
|
||||
else if (callName == 'importSuccessful')
|
||||
{
|
||||
importSuccessful(argsArray[0]);
|
||||
}
|
||||
},
|
||||
disable: function()
|
||||
{
|
||||
$("#impexp-disabled-clickcatcher").show();
|
||||
$("#import").css('opacity', 0.5);
|
||||
$("#impexp-export").css('opacity', 0.5);
|
||||
},
|
||||
enable: function()
|
||||
{
|
||||
$("#impexp-disabled-clickcatcher").hide();
|
||||
$("#import").css('opacity', 1);
|
||||
$("#impexp-export").css('opacity', 1);
|
||||
},
|
||||
export2Wordle: function()
|
||||
{
|
||||
var padUrl = $('#exportwordlea').attr('href').replace(/\/wordle$/, '/txt')
|
||||
|
||||
$.get(padUrl, function(data)
|
||||
{
|
||||
$('.result').html(data);
|
||||
$('#text').html(data);
|
||||
$('#wordlepost').submit();
|
||||
});
|
||||
}
|
||||
};
|
||||
return self;
|
||||
}());
|
||||
|
||||
exports.padimpexp = padimpexp;
|
374
src/static/js/pad_modals.js
Normal file
|
@ -0,0 +1,374 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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 padutils = require('/pad_utils').padutils;
|
||||
var paddocbar = require('/pad_docbar').paddocbar;
|
||||
|
||||
var padmodals = (function()
|
||||
{
|
||||
|
||||
/*var clearFeedbackEmail = function() {};
|
||||
function clearFeedback() {
|
||||
clearFeedbackEmail();
|
||||
$("#feedbackbox-message").val('');
|
||||
}
|
||||
|
||||
var sendingFeedback = false;
|
||||
function setSendingFeedback(v) {
|
||||
v = !! v;
|
||||
if (sendingFeedback != v) {
|
||||
sendingFeedback = v;
|
||||
if (v) {
|
||||
$("#feedbackbox-send").css('opacity', 0.75);
|
||||
}
|
||||
else {
|
||||
$("#feedbackbox-send").css('opacity', 1);
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
var sendingInvite = false;
|
||||
|
||||
function setSendingInvite(v)
|
||||
{
|
||||
v = !! v;
|
||||
if (sendingInvite != v)
|
||||
{
|
||||
sendingInvite = v;
|
||||
if (v)
|
||||
{
|
||||
$(".sharebox-send").css('opacity', 0.75);
|
||||
}
|
||||
else
|
||||
{
|
||||
$("#sharebox-send").css('opacity', 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var clearShareBoxTo = function()
|
||||
{};
|
||||
|
||||
function clearShareBox()
|
||||
{
|
||||
clearShareBoxTo();
|
||||
}
|
||||
|
||||
var pad = undefined;
|
||||
var self = {
|
||||
init: function(_pad)
|
||||
{
|
||||
pad = _pad;
|
||||
|
||||
self.initFeedback();
|
||||
self.initShareBox();
|
||||
},
|
||||
initFeedback: function()
|
||||
{
|
||||
/*var emailField = $("#feedbackbox-email");
|
||||
clearFeedbackEmail =
|
||||
padutils.makeFieldLabeledWhenEmpty(emailField, '(your email address)').clear;
|
||||
clearFeedback();*/
|
||||
|
||||
$("#feedbackbox-hide").click(function()
|
||||
{
|
||||
self.hideModal();
|
||||
});
|
||||
/*$("#feedbackbox-send").click(function() {
|
||||
self.sendFeedbackEmail();
|
||||
});*/
|
||||
|
||||
$("#feedbackbutton").click(function()
|
||||
{
|
||||
self.showFeedback();
|
||||
});
|
||||
},
|
||||
initShareBox: function()
|
||||
{
|
||||
$("#sharebutton").click(function()
|
||||
{
|
||||
self.showShareBox();
|
||||
});
|
||||
$("#sharebox-hide").click(function()
|
||||
{
|
||||
self.hideModal();
|
||||
});
|
||||
$("#sharebox-send").click(function()
|
||||
{
|
||||
self.sendInvite();
|
||||
});
|
||||
|
||||
$("#sharebox-url").click(function()
|
||||
{
|
||||
$("#sharebox-url").focus().select();
|
||||
});
|
||||
|
||||
clearShareBoxTo = padutils.makeFieldLabeledWhenEmpty($("#sharebox-to"), "(email addresses)").clear;
|
||||
clearShareBox();
|
||||
|
||||
$("#sharebox-subject").val(self.getDefaultShareBoxSubjectForName(pad.getUserName()));
|
||||
$("#sharebox-message").val(self.getDefaultShareBoxMessageForName(pad.getUserName()));
|
||||
|
||||
$("#sharebox-stripe .setsecurity").click(function()
|
||||
{
|
||||
self.hideModal();
|
||||
paddocbar.setShownPanel('security');
|
||||
});
|
||||
},
|
||||
getDefaultShareBoxMessageForName: function(name)
|
||||
{
|
||||
return (name || "Somebody") + " has shared an EtherPad document with you." + "\n\n" + "View it here:\n\n" + padutils.escapeHtml($(".sharebox-url").val() + "\n");
|
||||
},
|
||||
getDefaultShareBoxSubjectForName: function(name)
|
||||
{
|
||||
return (name || "Somebody") + " invited you to an EtherPad document";
|
||||
},
|
||||
relayoutWithBottom: function(px)
|
||||
{
|
||||
$("#modaloverlay").height(px);
|
||||
$("#sharebox").css('left', Math.floor(($(window).width() - $("#sharebox").outerWidth()) / 2));
|
||||
$("#feedbackbox").css('left', Math.floor(($(window).width() - $("#feedbackbox").outerWidth()) / 2));
|
||||
},
|
||||
showFeedback: function()
|
||||
{
|
||||
self.showModal("#feedbackbox");
|
||||
},
|
||||
showShareBox: function()
|
||||
{
|
||||
// when showing the dialog, if it still says "Somebody" invited you
|
||||
// then we fill in the updated username if there is one;
|
||||
// otherwise, we don't touch it, perhaps the user is happy with it
|
||||
var msgbox = $("#sharebox-message");
|
||||
if (msgbox.val() == self.getDefaultShareBoxMessageForName(null))
|
||||
{
|
||||
msgbox.val(self.getDefaultShareBoxMessageForName(pad.getUserName()));
|
||||
}
|
||||
var subjBox = $("#sharebox-subject");
|
||||
if (subjBox.val() == self.getDefaultShareBoxSubjectForName(null))
|
||||
{
|
||||
subjBox.val(self.getDefaultShareBoxSubjectForName(pad.getUserName()));
|
||||
}
|
||||
|
||||
if (pad.isPadPublic())
|
||||
{
|
||||
$("#sharebox-stripe").get(0).className = 'sharebox-stripe-public';
|
||||
}
|
||||
else
|
||||
{
|
||||
$("#sharebox-stripe").get(0).className = 'sharebox-stripe-private';
|
||||
}
|
||||
|
||||
self.showModal("#sharebox", 500);
|
||||
$("#sharebox-url").focus().select();
|
||||
},
|
||||
showModal: function(modalId, duration)
|
||||
{
|
||||
$(".modaldialog").hide();
|
||||
$(modalId).show().css(
|
||||
{
|
||||
'opacity': 0
|
||||
}).animate(
|
||||
{
|
||||
'opacity': 1
|
||||
}, duration);
|
||||
$("#modaloverlay").show().css(
|
||||
{
|
||||
'opacity': 0
|
||||
}).animate(
|
||||
{
|
||||
'opacity': 1
|
||||
}, duration);
|
||||
},
|
||||
hideModal: function(duration)
|
||||
{
|
||||
padutils.cancelActions('hide-feedbackbox');
|
||||
padutils.cancelActions('hide-sharebox');
|
||||
$("#sharebox-response").hide();
|
||||
$(".modaldialog").animate(
|
||||
{
|
||||
'opacity': 0
|
||||
}, duration, function()
|
||||
{
|
||||
$("#modaloverlay").hide();
|
||||
});
|
||||
$("#modaloverlay").animate(
|
||||
{
|
||||
'opacity': 0
|
||||
}, duration, function()
|
||||
{
|
||||
$("#modaloverlay").hide();
|
||||
});
|
||||
},
|
||||
hideFeedbackLaterIfNoOtherInteraction: function()
|
||||
{
|
||||
return padutils.getCancellableAction('hide-feedbackbox', function()
|
||||
{
|
||||
self.hideModal();
|
||||
});
|
||||
},
|
||||
hideShareboxLaterIfNoOtherInteraction: function()
|
||||
{
|
||||
return padutils.getCancellableAction('hide-sharebox', function()
|
||||
{
|
||||
self.hideModal();
|
||||
});
|
||||
},
|
||||
/* sendFeedbackEmail: function() {
|
||||
if (sendingFeedback) {
|
||||
return;
|
||||
}
|
||||
var message = $("#feedbackbox-message").val();
|
||||
if (! message) {
|
||||
return;
|
||||
}
|
||||
var email = ($("#feedbackbox-email").hasClass('editempty') ? '' :
|
||||
$("#feedbackbox-email").val());
|
||||
var padId = pad.getPadId();
|
||||
var username = pad.getUserName();
|
||||
setSendingFeedback(true);
|
||||
$("#feedbackbox-response").html("Sending...").get(0).className = '';
|
||||
$("#feedbackbox-response").show();
|
||||
$.ajax({
|
||||
type: 'post',
|
||||
url: '/ep/pad/feedback',
|
||||
data: {
|
||||
feedback: message,
|
||||
padId: padId,
|
||||
username: username,
|
||||
email: email
|
||||
},
|
||||
success: success,
|
||||
error: error
|
||||
});
|
||||
var hideCall = self.hideFeedbackLaterIfNoOtherInteraction();
|
||||
function success(msg) {
|
||||
setSendingFeedback(false);
|
||||
clearFeedback();
|
||||
$("#feedbackbox-response").html("Thanks for your feedback").get(0).className = 'goodresponse';
|
||||
$("#feedbackbox-response").show();
|
||||
window.setTimeout(function() {
|
||||
$("#feedbackbox-response").fadeOut('slow', function() {
|
||||
hideCall();
|
||||
});
|
||||
}, 1500);
|
||||
}
|
||||
function error(e) {
|
||||
setSendingFeedback(false);
|
||||
$("#feedbackbox-response").html("Could not send feedback. Please email us at feedback"+"@"+"etherpad.com instead.").get(0).className = 'badresponse';
|
||||
$("#feedbackbox-response").show();
|
||||
}
|
||||
},*/
|
||||
sendInvite: function()
|
||||
{
|
||||
if (sendingInvite)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (!pad.isFullyConnected())
|
||||
{
|
||||
displayErrorMessage("Error: Connection to the server is down or flaky.");
|
||||
return;
|
||||
}
|
||||
var message = $("#sharebox-message").val();
|
||||
if (!message)
|
||||
{
|
||||
displayErrorMessage("Please enter a message body before sending.");
|
||||
return;
|
||||
}
|
||||
var emails = ($("#sharebox-to").hasClass('editempty') ? '' : $("#sharebox-to").val()) || '';
|
||||
// find runs of characters that aren't obviously non-email punctuation
|
||||
var emailArray = emails.match(/[^\s,:;<>\"\'\/\(\)\[\]{}]+/g) || [];
|
||||
if (emailArray.length == 0)
|
||||
{
|
||||
displayErrorMessage('Please enter at least one "To:" address.');
|
||||
$("#sharebox-to").focus().select();
|
||||
return;
|
||||
}
|
||||
for (var i = 0; i < emailArray.length; i++)
|
||||
{
|
||||
var addr = emailArray[i];
|
||||
if (!addr.match(/^[\w\.\_\+\-]+\@[\w\_\-]+\.[\w\_\-\.]+$/))
|
||||
{
|
||||
displayErrorMessage('"' + padutils.escapeHtml(addr) + '" does not appear to be a valid email address.');
|
||||
return;
|
||||
}
|
||||
}
|
||||
var subject = $("#sharebox-subject").val();
|
||||
if (!subject)
|
||||
{
|
||||
subject = self.getDefaultShareBoxSubjectForName(pad.getUserName());
|
||||
$("#sharebox-subject").val(subject); // force the default subject
|
||||
}
|
||||
|
||||
var padId = pad.getPadId();
|
||||
var username = pad.getUserName();
|
||||
setSendingInvite(true);
|
||||
$("#sharebox-response").html("Sending...").get(0).className = '';
|
||||
$("#sharebox-response").show();
|
||||
$.ajax(
|
||||
{
|
||||
type: 'post',
|
||||
url: '/ep/pad/emailinvite',
|
||||
data: {
|
||||
message: message,
|
||||
toEmails: emailArray.join(','),
|
||||
subject: subject,
|
||||
username: username,
|
||||
padId: padId
|
||||
},
|
||||
success: success,
|
||||
error: error
|
||||
});
|
||||
var hideCall = self.hideShareboxLaterIfNoOtherInteraction();
|
||||
|
||||
function success(msg)
|
||||
{
|
||||
setSendingInvite(false);
|
||||
$("#sharebox-response").html("Email invitation sent!").get(0).className = 'goodresponse';
|
||||
$("#sharebox-response").show();
|
||||
window.setTimeout(function()
|
||||
{
|
||||
$("#sharebox-response").fadeOut('slow', function()
|
||||
{
|
||||
hideCall();
|
||||
});
|
||||
}, 1500);
|
||||
}
|
||||
|
||||
function error(e)
|
||||
{
|
||||
setSendingFeedback(false);
|
||||
$("#sharebox-response").html("An error occurred; no email was sent.").get(0).className = 'badresponse';
|
||||
$("#sharebox-response").show();
|
||||
}
|
||||
|
||||
function displayErrorMessage(msgHtml)
|
||||
{
|
||||
$("#sharebox-response").html(msgHtml).get(0).className = 'badresponse';
|
||||
$("#sharebox-response").show();
|
||||
}
|
||||
}
|
||||
};
|
||||
return self;
|
||||
}());
|
||||
|
||||
exports.padmodals = padmodals;
|
526
src/static/js/pad_savedrevs.js
Normal file
|
@ -0,0 +1,526 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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 padutils = require('/pad_utils').padutils;
|
||||
var paddocbar = require('/pad_docbar').paddocbar;
|
||||
|
||||
var padsavedrevs = (function()
|
||||
{
|
||||
|
||||
function reversedCopy(L)
|
||||
{
|
||||
var L2 = L.slice();
|
||||
L2.reverse();
|
||||
return L2;
|
||||
}
|
||||
|
||||
function makeRevisionBox(revisionInfo, rnum)
|
||||
{
|
||||
var box = $('<div class="srouterbox">' + '<div class="srinnerbox">' + '<a href="javascript:void(0)" class="srname"><!-- --></a>' + '<div class="sractions"><a class="srview" href="javascript:void(0)" target="_blank">view</a> | <a class="srrestore" href="javascript:void(0)">restore</a></div>' + '<div class="srtime"><!-- --></div>' + '<div class="srauthor"><!-- --></div>' + '<img class="srtwirly" src="static/img/misc/status-ball.gif">' + '</div></div>');
|
||||
setBoxLabel(box, revisionInfo.label);
|
||||
setBoxTimestamp(box, revisionInfo.timestamp);
|
||||
box.find(".srauthor").html("by " + padutils.escapeHtml(revisionInfo.savedBy));
|
||||
var viewLink = '/ep/pad/view/' + pad.getPadId() + '/' + revisionInfo.id;
|
||||
box.find(".srview").attr('href', viewLink);
|
||||
var restoreLink = 'javascript:void(require('+JSON.stringify(module.id)+').padsavedrevs.restoreRevision(' + JSON.stringify(rnum) + ');';
|
||||
box.find(".srrestore").attr('href', restoreLink);
|
||||
box.find(".srname").click(function(evt)
|
||||
{
|
||||
editRevisionLabel(rnum, box);
|
||||
});
|
||||
return box;
|
||||
}
|
||||
|
||||
function setBoxLabel(box, label)
|
||||
{
|
||||
box.find(".srname").html(padutils.escapeHtml(label)).attr('title', label);
|
||||
}
|
||||
|
||||
function setBoxTimestamp(box, timestamp)
|
||||
{
|
||||
box.find(".srtime").html(padutils.escapeHtml(
|
||||
padutils.timediff(new Date(timestamp))));
|
||||
}
|
||||
|
||||
function getNthBox(n)
|
||||
{
|
||||
return $("#savedrevisions .srouterbox").eq(n);
|
||||
}
|
||||
|
||||
function editRevisionLabel(rnum, box)
|
||||
{
|
||||
var input = $('<input type="text" class="srnameedit"/>');
|
||||
box.find(".srnameedit").remove(); // just in case
|
||||
var label = box.find(".srname");
|
||||
input.width(label.width());
|
||||
input.height(label.height());
|
||||
input.css('top', label.position().top);
|
||||
input.css('left', label.position().left);
|
||||
label.after(input);
|
||||
label.css('opacity', 0);
|
||||
|
||||
function endEdit()
|
||||
{
|
||||
input.remove();
|
||||
label.css('opacity', 1);
|
||||
}
|
||||
var rev = currentRevisionList[rnum];
|
||||
var oldLabel = rev.label;
|
||||
input.blur(function()
|
||||
{
|
||||
var newLabel = input.val();
|
||||
if (newLabel && newLabel != oldLabel)
|
||||
{
|
||||
relabelRevision(rnum, newLabel);
|
||||
}
|
||||
endEdit();
|
||||
});
|
||||
input.val(rev.label).focus().select();
|
||||
padutils.bindEnterAndEscape(input, function onEnter()
|
||||
{
|
||||
input.blur();
|
||||
}, function onEscape()
|
||||
{
|
||||
input.val('').blur();
|
||||
});
|
||||
}
|
||||
|
||||
function relabelRevision(rnum, newLabel)
|
||||
{
|
||||
var rev = currentRevisionList[rnum];
|
||||
$.ajax(
|
||||
{
|
||||
type: 'post',
|
||||
url: '/ep/pad/saverevisionlabel',
|
||||
data: {
|
||||
userId: pad.getUserId(),
|
||||
padId: pad.getPadId(),
|
||||
revId: rev.id,
|
||||
newLabel: newLabel
|
||||
},
|
||||
success: success,
|
||||
error: error
|
||||
});
|
||||
|
||||
function success(text)
|
||||
{
|
||||
var newRevisionList = JSON.parse(text);
|
||||
self.newRevisionList(newRevisionList);
|
||||
pad.sendClientMessage(
|
||||
{
|
||||
type: 'revisionLabel',
|
||||
revisionList: reversedCopy(currentRevisionList),
|
||||
savedBy: pad.getUserName(),
|
||||
newLabel: newLabel
|
||||
});
|
||||
}
|
||||
|
||||
function error(e)
|
||||
{
|
||||
alert("Oops! There was an error saving that revision label. Please try again later.");
|
||||
}
|
||||
}
|
||||
|
||||
var currentRevisionList = [];
|
||||
|
||||
function setRevisionList(newRevisionList, noAnimation)
|
||||
{
|
||||
// deals with changed labels and new added revisions
|
||||
for (var i = 0; i < currentRevisionList.length; i++)
|
||||
{
|
||||
var a = currentRevisionList[i];
|
||||
var b = newRevisionList[i];
|
||||
if (b.label != a.label)
|
||||
{
|
||||
setBoxLabel(getNthBox(i), b.label);
|
||||
}
|
||||
}
|
||||
for (var j = currentRevisionList.length; j < newRevisionList.length; j++)
|
||||
{
|
||||
var newBox = makeRevisionBox(newRevisionList[j], j);
|
||||
$("#savedrevs-scrollinner").append(newBox);
|
||||
newBox.css('left', j * REVISION_BOX_WIDTH);
|
||||
}
|
||||
var newOnes = (newRevisionList.length > currentRevisionList.length);
|
||||
currentRevisionList = newRevisionList;
|
||||
if (newOnes)
|
||||
{
|
||||
setDesiredScroll(getMaxScroll());
|
||||
if (noAnimation)
|
||||
{
|
||||
setScroll(desiredScroll);
|
||||
}
|
||||
|
||||
if (!noAnimation)
|
||||
{
|
||||
var nameOfLast = currentRevisionList[currentRevisionList.length - 1].label;
|
||||
displaySavedTip(nameOfLast);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function refreshRevisionList()
|
||||
{
|
||||
for (var i = 0; i < currentRevisionList.length; i++)
|
||||
{
|
||||
var r = currentRevisionList[i];
|
||||
var box = getNthBox(i);
|
||||
setBoxTimestamp(box, r.timestamp);
|
||||
}
|
||||
}
|
||||
|
||||
var savedTipAnimator = padutils.makeShowHideAnimator(function(state)
|
||||
{
|
||||
if (state == -1)
|
||||
{
|
||||
$("#revision-notifier").css('opacity', 0).css('display', 'block');
|
||||
}
|
||||
else if (state == 0)
|
||||
{
|
||||
$("#revision-notifier").css('opacity', 1);
|
||||
}
|
||||
else if (state == 1)
|
||||
{
|
||||
$("#revision-notifier").css('opacity', 0).css('display', 'none');
|
||||
}
|
||||
else if (state < 0)
|
||||
{
|
||||
$("#revision-notifier").css('opacity', 1);
|
||||
}
|
||||
else if (state > 0)
|
||||
{
|
||||
$("#revision-notifier").css('opacity', 1 - state);
|
||||
}
|
||||
}, false, 25, 300);
|
||||
|
||||
function displaySavedTip(text)
|
||||
{
|
||||
$("#revision-notifier .name").html(padutils.escapeHtml(text));
|
||||
savedTipAnimator.show();
|
||||
padutils.cancelActions("hide-revision-notifier");
|
||||
var hideLater = padutils.getCancellableAction("hide-revision-notifier", function()
|
||||
{
|
||||
savedTipAnimator.hide();
|
||||
});
|
||||
window.setTimeout(hideLater, 3000);
|
||||
}
|
||||
|
||||
var REVISION_BOX_WIDTH = 120;
|
||||
var curScroll = 0; // distance between left of revisions and right of view
|
||||
var desiredScroll = 0;
|
||||
|
||||
function getScrollWidth()
|
||||
{
|
||||
return REVISION_BOX_WIDTH * currentRevisionList.length;
|
||||
}
|
||||
|
||||
function getViewportWidth()
|
||||
{
|
||||
return $("#savedrevs-scrollouter").width();
|
||||
}
|
||||
|
||||
function getMinScroll()
|
||||
{
|
||||
return Math.min(getViewportWidth(), getScrollWidth());
|
||||
}
|
||||
|
||||
function getMaxScroll()
|
||||
{
|
||||
return getScrollWidth();
|
||||
}
|
||||
|
||||
function setScroll(newScroll)
|
||||
{
|
||||
curScroll = newScroll;
|
||||
$("#savedrevs-scrollinner").css('right', newScroll);
|
||||
updateScrollArrows();
|
||||
}
|
||||
|
||||
function setDesiredScroll(newDesiredScroll, dontUpdate)
|
||||
{
|
||||
desiredScroll = Math.min(getMaxScroll(), Math.max(getMinScroll(), newDesiredScroll));
|
||||
if (!dontUpdate)
|
||||
{
|
||||
updateScroll();
|
||||
}
|
||||
}
|
||||
|
||||
function updateScroll()
|
||||
{
|
||||
updateScrollArrows();
|
||||
scrollAnimator.scheduleAnimation();
|
||||
}
|
||||
|
||||
function updateScrollArrows()
|
||||
{
|
||||
$("#savedrevs-scrollleft").toggleClass("disabledscrollleft", desiredScroll <= getMinScroll());
|
||||
$("#savedrevs-scrollright").toggleClass("disabledscrollright", desiredScroll >= getMaxScroll());
|
||||
}
|
||||
var scrollAnimator = padutils.makeAnimationScheduler(function()
|
||||
{
|
||||
setDesiredScroll(desiredScroll, true); // re-clamp
|
||||
if (Math.abs(desiredScroll - curScroll) < 1)
|
||||
{
|
||||
setScroll(desiredScroll);
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
setScroll(curScroll + (desiredScroll - curScroll) * 0.5);
|
||||
return true;
|
||||
}
|
||||
}, 50, 2);
|
||||
|
||||
var isSaving = false;
|
||||
|
||||
function setIsSaving(v)
|
||||
{
|
||||
isSaving = v;
|
||||
rerenderButton();
|
||||
}
|
||||
|
||||
function haveReachedRevLimit()
|
||||
{
|
||||
var mv = pad.getPrivilege('maxRevisions');
|
||||
return (!(mv < 0 || mv > currentRevisionList.length));
|
||||
}
|
||||
|
||||
function rerenderButton()
|
||||
{
|
||||
if (isSaving || (!pad.isFullyConnected()) || haveReachedRevLimit())
|
||||
{
|
||||
$("#savedrevs-savenow").css('opacity', 0.75);
|
||||
}
|
||||
else
|
||||
{
|
||||
$("#savedrevs-savenow").css('opacity', 1);
|
||||
}
|
||||
}
|
||||
|
||||
var scrollRepeatTimer = null;
|
||||
var scrollStartTime = 0;
|
||||
|
||||
function setScrollRepeatTimer(dir)
|
||||
{
|
||||
clearScrollRepeatTimer();
|
||||
scrollStartTime = +new Date;
|
||||
scrollRepeatTimer = window.setTimeout(function f()
|
||||
{
|
||||
if (!scrollRepeatTimer)
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.scroll(dir);
|
||||
var scrollTime = (+new Date) - scrollStartTime;
|
||||
var delay = (scrollTime > 2000 ? 50 : 300);
|
||||
scrollRepeatTimer = window.setTimeout(f, delay);
|
||||
}, 300);
|
||||
$(document).bind('mouseup', clearScrollRepeatTimer);
|
||||
}
|
||||
|
||||
function clearScrollRepeatTimer()
|
||||
{
|
||||
if (scrollRepeatTimer)
|
||||
{
|
||||
window.clearTimeout(scrollRepeatTimer);
|
||||
scrollRepeatTimer = null;
|
||||
}
|
||||
$(document).unbind('mouseup', clearScrollRepeatTimer);
|
||||
}
|
||||
|
||||
var pad = undefined;
|
||||
var self = {
|
||||
init: function(initialRevisions, _pad)
|
||||
{
|
||||
pad = _pad;
|
||||
self.newRevisionList(initialRevisions, true);
|
||||
|
||||
$("#savedrevs-savenow").click(function()
|
||||
{
|
||||
self.saveNow();
|
||||
});
|
||||
$("#savedrevs-scrollleft").mousedown(function()
|
||||
{
|
||||
self.scroll('left');
|
||||
setScrollRepeatTimer('left');
|
||||
});
|
||||
$("#savedrevs-scrollright").mousedown(function()
|
||||
{
|
||||
self.scroll('right');
|
||||
setScrollRepeatTimer('right');
|
||||
});
|
||||
$("#savedrevs-close").click(function()
|
||||
{
|
||||
paddocbar.setShownPanel(null);
|
||||
});
|
||||
|
||||
// update "saved n minutes ago" times
|
||||
window.setInterval(function()
|
||||
{
|
||||
refreshRevisionList();
|
||||
}, 60 * 1000);
|
||||
},
|
||||
restoreRevision: function(rnum)
|
||||
{
|
||||
var rev = currentRevisionList[rnum];
|
||||
var warning = ("Restoring this revision will overwrite the current" + " text of the pad. " + "Are you sure you want to continue?");
|
||||
var hidePanel = paddocbar.hideLaterIfNoOtherInteraction();
|
||||
var box = getNthBox(rnum);
|
||||
if (confirm(warning))
|
||||
{
|
||||
box.find(".srtwirly").show();
|
||||
$.ajax(
|
||||
{
|
||||
type: 'get',
|
||||
url: '/ep/pad/getrevisionatext',
|
||||
data: {
|
||||
padId: pad.getPadId(),
|
||||
revId: rev.id
|
||||
},
|
||||
success: success,
|
||||
error: error
|
||||
});
|
||||
}
|
||||
|
||||
function success(resultJson)
|
||||
{
|
||||
untwirl();
|
||||
var result = JSON.parse(resultJson);
|
||||
padeditor.restoreRevisionText(result);
|
||||
window.setTimeout(function()
|
||||
{
|
||||
hidePanel();
|
||||
}, 0);
|
||||
}
|
||||
|
||||
function error(e)
|
||||
{
|
||||
untwirl();
|
||||
alert("Oops! There was an error retreiving the text (revNum= " + rev.revNum + "; padId=" + pad.getPadId());
|
||||
}
|
||||
|
||||
function untwirl()
|
||||
{
|
||||
box.find(".srtwirly").hide();
|
||||
}
|
||||
},
|
||||
showReachedLimit: function()
|
||||
{
|
||||
alert("Sorry, you do not have privileges to save more than " + pad.getPrivilege('maxRevisions') + " revisions.");
|
||||
},
|
||||
newRevisionList: function(lst, noAnimation)
|
||||
{
|
||||
// server gives us list with newest first;
|
||||
// we want chronological order
|
||||
var L = reversedCopy(lst);
|
||||
setRevisionList(L, noAnimation);
|
||||
rerenderButton();
|
||||
},
|
||||
saveNow: function()
|
||||
{
|
||||
if (isSaving)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (!pad.isFullyConnected())
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (haveReachedRevLimit())
|
||||
{
|
||||
self.showReachedLimit();
|
||||
return;
|
||||
}
|
||||
setIsSaving(true);
|
||||
var savedBy = pad.getUserName() || "unnamed";
|
||||
pad.callWhenNotCommitting(submitSave);
|
||||
|
||||
function submitSave()
|
||||
{
|
||||
$.ajax(
|
||||
{
|
||||
type: 'post',
|
||||
url: '/ep/pad/saverevision',
|
||||
data: {
|
||||
padId: pad.getPadId(),
|
||||
savedBy: savedBy,
|
||||
savedById: pad.getUserId(),
|
||||
revNum: pad.getCollabRevisionNumber()
|
||||
},
|
||||
success: success,
|
||||
error: error
|
||||
});
|
||||
}
|
||||
|
||||
function success(text)
|
||||
{
|
||||
setIsSaving(false);
|
||||
var newRevisionList = JSON.parse(text);
|
||||
self.newRevisionList(newRevisionList);
|
||||
pad.sendClientMessage(
|
||||
{
|
||||
type: 'newRevisionList',
|
||||
revisionList: newRevisionList,
|
||||
savedBy: savedBy
|
||||
});
|
||||
}
|
||||
|
||||
function error(e)
|
||||
{
|
||||
setIsSaving(false);
|
||||
alert("Oops! The server failed to save the revision. Please try again later.");
|
||||
}
|
||||
},
|
||||
handleResizePage: function()
|
||||
{
|
||||
updateScrollArrows();
|
||||
},
|
||||
handleIsFullyConnected: function(isConnected)
|
||||
{
|
||||
rerenderButton();
|
||||
},
|
||||
scroll: function(dir)
|
||||
{
|
||||
var minScroll = getMinScroll();
|
||||
var maxScroll = getMaxScroll();
|
||||
if (dir == 'left')
|
||||
{
|
||||
if (desiredScroll > minScroll)
|
||||
{
|
||||
var n = Math.floor((desiredScroll - 1 - minScroll) / REVISION_BOX_WIDTH);
|
||||
setDesiredScroll(Math.max(0, n) * REVISION_BOX_WIDTH + minScroll);
|
||||
}
|
||||
}
|
||||
else if (dir == 'right')
|
||||
{
|
||||
if (desiredScroll < maxScroll)
|
||||
{
|
||||
var n = Math.floor((maxScroll - desiredScroll - 1) / REVISION_BOX_WIDTH);
|
||||
setDesiredScroll(maxScroll - Math.max(0, n) * REVISION_BOX_WIDTH);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
return self;
|
||||
}());
|
||||
|
||||
exports.padsavedrevs = padsavedrevs;
|
814
src/static/js/pad_userlist.js
Normal file
|
@ -0,0 +1,814 @@
|
|||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* 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 padutils = require('/pad_utils').padutils;
|
||||
|
||||
var myUserInfo = {};
|
||||
|
||||
var colorPickerOpen = false;
|
||||
var colorPickerSetup = false;
|
||||
var previousColorId = 0;
|
||||
|
||||
|
||||
var paduserlist = (function()
|
||||
{
|
||||
|
||||
var rowManager = (function()
|
||||
{
|
||||
// The row manager handles rendering rows of the user list and animating
|
||||
// their insertion, removal, and reordering. It manipulates TD height
|
||||
// and TD opacity.
|
||||
|
||||
function nextRowId()
|
||||
{
|
||||
return "usertr" + (nextRowId.counter++);
|
||||
}
|
||||
nextRowId.counter = 1;
|
||||
// objects are shared; fields are "domId","data","animationStep"
|
||||
var rowsFadingOut = []; // unordered set
|
||||
var rowsFadingIn = []; // unordered set
|
||||
var rowsPresent = []; // in order
|
||||
var ANIMATION_START = -12; // just starting to fade in
|
||||
var ANIMATION_END = 12; // just finishing fading out
|
||||
|
||||
|
||||
function getAnimationHeight(step, power)
|
||||
{
|
||||
var a = Math.abs(step / 12);
|
||||
if (power == 2) a = a * a;
|
||||
else if (power == 3) a = a * a * a;
|
||||
else if (power == 4) a = a * a * a * a;
|
||||
else if (power >= 5) a = a * a * a * a * a;
|
||||
return Math.round(26 * (1 - a));
|
||||
}
|
||||
var OPACITY_STEPS = 6;
|
||||
|
||||
var ANIMATION_STEP_TIME = 20;
|
||||
var LOWER_FRAMERATE_FACTOR = 2;
|
||||
var scheduleAnimation = padutils.makeAnimationScheduler(animateStep, ANIMATION_STEP_TIME, LOWER_FRAMERATE_FACTOR).scheduleAnimation;
|
||||
|
||||
var NUMCOLS = 4;
|
||||
|
||||
// we do lots of manipulation of table rows and stuff that JQuery makes ok, despite
|
||||
// IE's poor handling when manipulating the DOM directly.
|
||||
|
||||
function getEmptyRowHtml(height)
|
||||
{
|
||||
return '<td colspan="' + NUMCOLS + '" style="border:0;height:' + height + 'px"><!-- --></td>';
|
||||
}
|
||||
|
||||
function isNameEditable(data)
|
||||
{
|
||||
return (!data.name) && (data.status != 'Disconnected');
|
||||
}
|
||||
|
||||
function replaceUserRowContents(tr, height, data)
|
||||
{
|
||||
var tds = getUserRowHtml(height, data).match(/<td.*?<\/td>/gi);
|
||||
if (isNameEditable(data) && tr.find("td.usertdname input:enabled").length > 0)
|
||||
{
|
||||
// preserve input field node
|
||||
for (var i = 0; i < tds.length; i++)
|
||||
{
|
||||
var oldTd = $(tr.find("td").get(i));
|
||||
if (!oldTd.hasClass('usertdname'))
|
||||
{
|
||||
oldTd.replaceWith(tds[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
tr.html(tds.join(''));
|
||||
}
|
||||
return tr;
|
||||
}
|
||||
|
||||
function getUserRowHtml(height, data)
|
||||
{
|
||||
var nameHtml;
|
||||
var isGuest = (data.id.charAt(0) != 'p');
|
||||
if (data.name)
|
||||
{
|
||||
nameHtml = padutils.escapeHtml(data.name);
|
||||
if (isGuest && pad.getIsProPad())
|
||||
{
|
||||
nameHtml += ' (Guest)';
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
nameHtml = '<input type="text" class="editempty newinput" value="unnamed" ' + (isNameEditable(data) ? '' : 'disabled="disabled" ') + '/>';
|
||||
}
|
||||
|
||||
return ['<td style="height:', height, 'px" class="usertdswatch"><div class="swatch" style="background:' + data.color + '"> </div></td>', '<td style="height:', height, 'px" class="usertdname">', nameHtml, '</td>', '<td style="height:', height, 'px" class="usertdstatus">', padutils.escapeHtml(data.status), '</td>', '<td style="height:', height, 'px" class="activity">', padutils.escapeHtml(data.activity), '</td>'].join('');
|
||||
}
|
||||
|
||||
function getRowHtml(id, innerHtml)
|
||||
{
|
||||
return '<tr id="' + id + '">' + innerHtml + '</tr>';
|
||||
}
|
||||
|
||||
function rowNode(row)
|
||||
{
|
||||
return $("#" + row.domId);
|
||||
}
|
||||
|
||||
function handleRowData(row)
|
||||
{
|
||||
if (row.data && row.data.status == 'Disconnected')
|
||||
{
|
||||
row.opacity = 0.5;
|
||||
}
|
||||
else
|
||||
{
|
||||
delete row.opacity;
|
||||
}
|
||||
}
|
||||
|
||||
function handleRowNode(tr, data)
|
||||
{
|
||||
if (data.titleText)
|
||||
{
|
||||
var titleText = data.titleText;
|
||||
window.setTimeout(function()
|
||||
{
|
||||
/* tr.attr('title', titleText)*/
|
||||
}, 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
tr.removeAttr('title');
|
||||
}
|
||||
}
|
||||
|
||||
function handleOtherUserInputs()
|
||||
{
|
||||
// handle 'INPUT' elements for naming other unnamed users
|
||||
$("#otheruserstable input.newinput").each(function()
|
||||
{
|
||||
var input = $(this);
|
||||
var tr = input.closest("tr");
|
||||
if (tr.length > 0)
|
||||
{
|
||||
var index = tr.parent().children().index(tr);
|
||||
if (index >= 0)
|
||||
{
|
||||
var userId = rowsPresent[index].data.id;
|
||||
rowManagerMakeNameEditor($(this), userId);
|
||||
}
|
||||
}
|
||||
}).removeClass('newinput');
|
||||
}
|
||||
|
||||
// animationPower is 0 to skip animation, 1 for linear, 2 for quadratic, etc.
|
||||
|
||||
|
||||
function insertRow(position, data, animationPower)
|
||||
{
|
||||
position = Math.max(0, Math.min(rowsPresent.length, position));
|
||||
animationPower = (animationPower === undefined ? 4 : animationPower);
|
||||
|
||||
var domId = nextRowId();
|
||||
var row = {
|
||||
data: data,
|
||||
animationStep: ANIMATION_START,
|
||||
domId: domId,
|
||||
animationPower: animationPower
|
||||
};
|
||||
handleRowData(row);
|
||||
rowsPresent.splice(position, 0, row);
|
||||
var tr;
|
||||
if (animationPower == 0)
|
||||
{
|
||||
tr = $(getRowHtml(domId, getUserRowHtml(getAnimationHeight(0), data)));
|
||||
row.animationStep = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
rowsFadingIn.push(row);
|
||||
tr = $(getRowHtml(domId, getEmptyRowHtml(getAnimationHeight(ANIMATION_START))));
|
||||
}
|
||||
handleRowNode(tr, data);
|
||||
if (position == 0)
|
||||
{
|
||||
$("table#otheruserstable").prepend(tr);
|
||||
}
|
||||
else
|
||||
{
|
||||
rowNode(rowsPresent[position - 1]).after(tr);
|
||||
}
|
||||
|
||||
if (animationPower != 0)
|
||||
{
|
||||
scheduleAnimation();
|
||||
}
|
||||
|
||||
handleOtherUserInputs();
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
function updateRow(position, data)
|
||||
{
|
||||
var row = rowsPresent[position];
|
||||
if (row)
|
||||
{
|
||||
row.data = data;
|
||||
handleRowData(row);
|
||||
if (row.animationStep == 0)
|
||||
{
|
||||
// not currently animating
|
||||
var tr = rowNode(row);
|
||||
replaceUserRowContents(tr, getAnimationHeight(0), row.data).find("td").css('opacity', (row.opacity === undefined ? 1 : row.opacity));
|
||||
handleRowNode(tr, data);
|
||||
handleOtherUserInputs();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function removeRow(position, animationPower)
|
||||
{
|
||||
animationPower = (animationPower === undefined ? 4 : animationPower);
|
||||
var row = rowsPresent[position];
|
||||
if (row)
|
||||
{
|
||||
rowsPresent.splice(position, 1); // remove
|
||||
if (animationPower == 0)
|
||||
{
|
||||
rowNode(row).remove();
|
||||
}
|
||||
else
|
||||
{
|
||||
row.animationStep = -row.animationStep; // use symmetry
|
||||
row.animationPower = animationPower;
|
||||
rowsFadingOut.push(row);
|
||||
scheduleAnimation();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// newPosition is position after the row has been removed
|
||||
|
||||
|
||||
function moveRow(oldPosition, newPosition, animationPower)
|
||||
{
|
||||
animationPower = (animationPower === undefined ? 1 : animationPower); // linear is best
|
||||
var row = rowsPresent[oldPosition];
|
||||
if (row && oldPosition != newPosition)
|
||||
{
|
||||
var rowData = row.data;
|
||||
removeRow(oldPosition, animationPower);
|
||||
insertRow(newPosition, rowData, animationPower);
|
||||
}
|
||||
}
|
||||
|
||||
function animateStep()
|
||||
{
|
||||
// animation must be symmetrical
|
||||
for (var i = rowsFadingIn.length - 1; i >= 0; i--)
|
||||
{ // backwards to allow removal
|
||||
var row = rowsFadingIn[i];
|
||||
var step = ++row.animationStep;
|
||||
var animHeight = getAnimationHeight(step, row.animationPower);
|
||||
var node = rowNode(row);
|
||||
var baseOpacity = (row.opacity === undefined ? 1 : row.opacity);
|
||||
if (step <= -OPACITY_STEPS)
|
||||
{
|
||||
node.find("td").height(animHeight);
|
||||
}
|
||||
else if (step == -OPACITY_STEPS + 1)
|
||||
{
|
||||
node.html(getUserRowHtml(animHeight, row.data)).find("td").css('opacity', baseOpacity * 1 / OPACITY_STEPS);
|
||||
handleRowNode(node, row.data);
|
||||
}
|
||||
else if (step < 0)
|
||||
{
|
||||
node.find("td").css('opacity', baseOpacity * (OPACITY_STEPS - (-step)) / OPACITY_STEPS).height(animHeight);
|
||||
}
|
||||
else if (step == 0)
|
||||
{
|
||||
// set HTML in case modified during animation
|
||||
node.html(getUserRowHtml(animHeight, row.data)).find("td").css('opacity', baseOpacity * 1).height(animHeight);
|
||||
handleRowNode(node, row.data);
|
||||
rowsFadingIn.splice(i, 1); // remove from set
|
||||
}
|
||||
}
|
||||
for (var i = rowsFadingOut.length - 1; i >= 0; i--)
|
||||
{ // backwards to allow removal
|
||||
var row = rowsFadingOut[i];
|
||||
var step = ++row.animationStep;
|
||||
var node = rowNode(row);
|
||||
var animHeight = getAnimationHeight(step, row.animationPower);
|
||||
var baseOpacity = (row.opacity === undefined ? 1 : row.opacity);
|
||||
if (step < OPACITY_STEPS)
|
||||
{
|
||||
node.find("td").css('opacity', baseOpacity * (OPACITY_STEPS - step) / OPACITY_STEPS).height(animHeight);
|
||||
}
|
||||
else if (step == OPACITY_STEPS)
|
||||
{
|
||||
node.html(getEmptyRowHtml(animHeight));
|
||||
}
|
||||
else if (step <= ANIMATION_END)
|
||||
{
|
||||
node.find("td").height(animHeight);
|
||||
}
|
||||
else
|
||||
{
|
||||
rowsFadingOut.splice(i, 1); // remove from set
|
||||
node.remove();
|
||||
}
|
||||
}
|
||||
|
||||
handleOtherUserInputs();
|
||||
|
||||
return (rowsFadingIn.length > 0) || (rowsFadingOut.length > 0); // is more to do
|
||||
}
|
||||
|
||||
var self = {
|
||||
insertRow: insertRow,
|
||||
removeRow: removeRow,
|
||||
moveRow: moveRow,
|
||||
updateRow: updateRow
|
||||
};
|
||||
return self;
|
||||
}()); ////////// rowManager
|
||||
var otherUsersInfo = [];
|
||||
var otherUsersData = [];
|
||||
|
||||
function rowManagerMakeNameEditor(jnode, userId)
|
||||
{
|
||||
setUpEditable(jnode, function()
|
||||
{
|
||||
var existingIndex = findExistingIndex(userId);
|
||||
if (existingIndex >= 0)
|
||||
{
|
||||
return otherUsersInfo[existingIndex].name || '';
|
||||
}
|
||||
else
|
||||
{
|
||||
return '';
|
||||
}
|
||||
}, function(newName)
|
||||
{
|
||||
if (!newName)
|
||||
{
|
||||
jnode.addClass("editempty");
|
||||
jnode.val("unnamed");
|
||||
}
|
||||
else
|
||||
{
|
||||
jnode.attr('disabled', 'disabled');
|
||||
pad.suggestUserName(userId, newName);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function findExistingIndex(userId)
|
||||
{
|
||||
var existingIndex = -1;
|
||||
for (var i = 0; i < otherUsersInfo.length; i++)
|
||||
{
|
||||
if (otherUsersInfo[i].userId == userId)
|
||||
{
|
||||
existingIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return existingIndex;
|
||||
}
|
||||
|
||||
function setUpEditable(jqueryNode, valueGetter, valueSetter)
|
||||
{
|
||||
jqueryNode.bind('focus', function(evt)
|
||||
{
|
||||
var oldValue = valueGetter();
|
||||
if (jqueryNode.val() !== oldValue)
|
||||
{
|
||||
jqueryNode.val(oldValue);
|
||||
}
|
||||
jqueryNode.addClass("editactive").removeClass("editempty");
|
||||
});
|
||||
jqueryNode.bind('blur', function(evt)
|
||||
{
|
||||
var newValue = jqueryNode.removeClass("editactive").val();
|
||||
valueSetter(newValue);
|
||||
});
|
||||
padutils.bindEnterAndEscape(jqueryNode, function onEnter()
|
||||
{
|
||||
jqueryNode.blur();
|
||||
}, function onEscape()
|
||||
{
|
||||
jqueryNode.val(valueGetter()).blur();
|
||||
});
|
||||
jqueryNode.removeAttr('disabled').addClass('editable');
|
||||
}
|
||||
|
||||
function updateInviteNotice()
|
||||
{
|
||||
if (otherUsersInfo.length == 0)
|
||||
{
|
||||
$("#otheruserstable").hide();
|
||||
$("#nootherusers").show();
|
||||
}
|
||||
else
|
||||
{
|
||||
$("#nootherusers").hide();
|
||||
$("#otheruserstable").show();
|
||||
}
|
||||
}
|
||||
|
||||
var knocksToIgnore = {};
|
||||
var guestPromptFlashState = 0;
|
||||
var guestPromptFlash = padutils.makeAnimationScheduler(
|
||||
|
||||
function()
|
||||
{
|
||||
var prompts = $("#guestprompts .guestprompt");
|
||||
if (prompts.length == 0)
|
||||
{
|
||||
return false; // no more to do
|
||||
}
|
||||
|
||||
guestPromptFlashState = 1 - guestPromptFlashState;
|
||||
if (guestPromptFlashState)
|
||||
{
|
||||
prompts.css('background', '#ffa');
|
||||
}
|
||||
else
|
||||
{
|
||||
prompts.css('background', '#ffe');
|
||||
}
|
||||
|
||||
return true;
|
||||
}, 1000);
|
||||
|
||||
var pad = undefined;
|
||||
var self = {
|
||||
init: function(myInitialUserInfo, _pad)
|
||||
{
|
||||
pad = _pad;
|
||||
|
||||
self.setMyUserInfo(myInitialUserInfo);
|
||||
|
||||
$("#otheruserstable tr").remove();
|
||||
|
||||
if (pad.getUserIsGuest())
|
||||
{
|
||||
$("#myusernameedit").addClass('myusernameedithoverable');
|
||||
setUpEditable($("#myusernameedit"), function()
|
||||
{
|
||||
return myUserInfo.name || '';
|
||||
}, function(newValue)
|
||||
{
|
||||
myUserInfo.name = newValue;
|
||||
pad.notifyChangeName(newValue);
|
||||
// wrap with setTimeout to do later because we get
|
||||
// a double "blur" fire in IE...
|
||||
window.setTimeout(function()
|
||||
{
|
||||
self.renderMyUserInfo();
|
||||
}, 0);
|
||||
});
|
||||
}
|
||||
|
||||
// color picker
|
||||
$("#myswatchbox").click(showColorPicker);
|
||||
$("#mycolorpicker .pickerswatchouter").click(function()
|
||||
{
|
||||
$("#mycolorpicker .pickerswatchouter").removeClass('picked');
|
||||
$(this).addClass('picked');
|
||||
});
|
||||
$("#mycolorpickersave").click(function()
|
||||
{
|
||||
closeColorPicker(true);
|
||||
});
|
||||
$("#mycolorpickercancel").click(function()
|
||||
{
|
||||
closeColorPicker(false);
|
||||
});
|
||||
//
|
||||
},
|
||||
setMyUserInfo: function(info)
|
||||
{
|
||||
//translate the colorId
|
||||
if(typeof info.colorId == "number")
|
||||
{
|
||||
info.colorId = clientVars.colorPalette[info.colorId];
|
||||
}
|
||||
|
||||
myUserInfo = $.extend(
|
||||
{}, info);
|
||||
|
||||
self.renderMyUserInfo();
|
||||
},
|
||||
userJoinOrUpdate: function(info)
|
||||
{
|
||||
if ((!info.userId) || (info.userId == myUserInfo.userId))
|
||||
{
|
||||
// not sure how this would happen
|
||||
return;
|
||||
}
|
||||
|
||||
var userData = {};
|
||||
userData.color = typeof info.colorId == "number" ? clientVars.colorPalette[info.colorId] : info.colorId;
|
||||
userData.name = info.name;
|
||||
userData.status = '';
|
||||
userData.activity = '';
|
||||
userData.id = info.userId;
|
||||
// Firefox ignores \n in title text; Safari does a linebreak
|
||||
userData.titleText = [info.userAgent || '', info.ip || ''].join(' \n');
|
||||
|
||||
var existingIndex = findExistingIndex(info.userId);
|
||||
|
||||
var numUsersBesides = otherUsersInfo.length;
|
||||
if (existingIndex >= 0)
|
||||
{
|
||||
numUsersBesides--;
|
||||
}
|
||||
var newIndex = padutils.binarySearch(numUsersBesides, function(n)
|
||||
{
|
||||
if (existingIndex >= 0 && n >= existingIndex)
|
||||
{
|
||||
// pretend existingIndex isn't there
|
||||
n++;
|
||||
}
|
||||
var infoN = otherUsersInfo[n];
|
||||
var nameN = (infoN.name || '').toLowerCase();
|
||||
var nameThis = (info.name || '').toLowerCase();
|
||||
var idN = infoN.userId;
|
||||
var idThis = info.userId;
|
||||
return (nameN > nameThis) || (nameN == nameThis && idN > idThis);
|
||||
});
|
||||
|
||||
if (existingIndex >= 0)
|
||||
{
|
||||
// update
|
||||
if (existingIndex == newIndex)
|
||||
{
|
||||
otherUsersInfo[existingIndex] = info;
|
||||
otherUsersData[existingIndex] = userData;
|
||||
rowManager.updateRow(existingIndex, userData);
|
||||
}
|
||||
else
|
||||
{
|
||||
otherUsersInfo.splice(existingIndex, 1);
|
||||
otherUsersData.splice(existingIndex, 1);
|
||||
otherUsersInfo.splice(newIndex, 0, info);
|
||||
otherUsersData.splice(newIndex, 0, userData);
|
||||
rowManager.updateRow(existingIndex, userData);
|
||||
rowManager.moveRow(existingIndex, newIndex);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
otherUsersInfo.splice(newIndex, 0, info);
|
||||
otherUsersData.splice(newIndex, 0, userData);
|
||||
rowManager.insertRow(newIndex, userData);
|
||||
}
|
||||
|
||||
updateInviteNotice();
|
||||
|
||||
self.updateNumberOfOnlineUsers();
|
||||
},
|
||||
updateNumberOfOnlineUsers: function()
|
||||
{
|
||||
var online = 1; // you are always online!
|
||||
for (var i = 0; i < otherUsersData.length; i++)
|
||||
{
|
||||
if (otherUsersData[i].status == "")
|
||||
{
|
||||
online++;
|
||||
}
|
||||
}
|
||||
$("#online_count").text(online);
|
||||
|
||||
return online;
|
||||
},
|
||||
userLeave: function(info)
|
||||
{
|
||||
var existingIndex = findExistingIndex(info.userId);
|
||||
if (existingIndex >= 0)
|
||||
{
|
||||
var userData = otherUsersData[existingIndex];
|
||||
userData.status = 'Disconnected';
|
||||
rowManager.updateRow(existingIndex, userData);
|
||||
if (userData.leaveTimer)
|
||||
{
|
||||
window.clearTimeout(userData.leaveTimer);
|
||||
}
|
||||
// set up a timer that will only fire if no leaves,
|
||||
// joins, or updates happen for this user in the
|
||||
// next N seconds, to remove the user from the list.
|
||||
var thisUserId = info.userId;
|
||||
var thisLeaveTimer = window.setTimeout(function()
|
||||
{
|
||||
var newExistingIndex = findExistingIndex(thisUserId);
|
||||
if (newExistingIndex >= 0)
|
||||
{
|
||||
var newUserData = otherUsersData[newExistingIndex];
|
||||
if (newUserData.status == 'Disconnected' && newUserData.leaveTimer == thisLeaveTimer)
|
||||
{
|
||||
otherUsersInfo.splice(newExistingIndex, 1);
|
||||
otherUsersData.splice(newExistingIndex, 1);
|
||||
rowManager.removeRow(newExistingIndex);
|
||||
updateInviteNotice();
|
||||
}
|
||||
}
|
||||
}, 8000); // how long to wait
|
||||
userData.leaveTimer = thisLeaveTimer;
|
||||
}
|
||||
updateInviteNotice();
|
||||
|
||||
self.updateNumberOfOnlineUsers();
|
||||
},
|
||||
showGuestPrompt: function(userId, displayName)
|
||||
{
|
||||
if (knocksToIgnore[userId])
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var encodedUserId = padutils.encodeUserId(userId);
|
||||
|
||||
var actionName = 'hide-guest-prompt-' + encodedUserId;
|
||||
padutils.cancelActions(actionName);
|
||||
|
||||
var box = $("#guestprompt-" + encodedUserId);
|
||||
if (box.length == 0)
|
||||
{
|
||||
// make guest prompt box
|
||||
box = $('<div id="'+padutils.escapeHtml('guestprompt-' + encodedUserId) + '" class="guestprompt"><div class="choices"><a href="' + padutils.escapeHtml('javascript:void(require('+JSON.stringify(module.id)+').paduserlist.answerGuestPrompt(' + JSON.stringify(encodedUserId) + ',false))')+'">Deny</a> <a href="' + padutils.escapeHtml('javascript:void(require('+JSON.stringify(module.id)+').paduserlist.answerGuestPrompt(' + JSON.stringify(encodedUserId) + ',true))') + '">Approve</a></div><div class="guestname"><strong>Guest:</strong> ' + padutils.escapeHtml(displayName) + '</div></div>');
|
||||
$("#guestprompts").append(box);
|
||||
}
|
||||
else
|
||||
{
|
||||
// update display name
|
||||
box.find(".guestname").html('<strong>Guest:</strong> ' + padutils.escapeHtml(displayName));
|
||||
}
|
||||
var hideLater = padutils.getCancellableAction(actionName, function()
|
||||
{
|
||||
self.removeGuestPrompt(userId);
|
||||
});
|
||||
window.setTimeout(hideLater, 15000); // time-out with no knock
|
||||
guestPromptFlash.scheduleAnimation();
|
||||
},
|
||||
removeGuestPrompt: function(userId)
|
||||
{
|
||||
var box = $("#guestprompt-" + padutils.encodeUserId(userId));
|
||||
// remove ID now so a new knock by same user gets new, unfaded box
|
||||
box.removeAttr('id').fadeOut("fast", function()
|
||||
{
|
||||
box.remove();
|
||||
});
|
||||
|
||||
knocksToIgnore[userId] = true;
|
||||
window.setTimeout(function()
|
||||
{
|
||||
delete knocksToIgnore[userId];
|
||||
}, 5000);
|
||||
},
|
||||
answerGuestPrompt: function(encodedUserId, approve)
|
||||
{
|
||||
var guestId = padutils.decodeUserId(encodedUserId);
|
||||
|
||||
var msg = {
|
||||
type: 'guestanswer',
|
||||
authId: pad.getUserId(),
|
||||
guestId: guestId,
|
||||
answer: (approve ? "approved" : "denied")
|
||||
};
|
||||
pad.sendClientMessage(msg);
|
||||
|
||||
self.removeGuestPrompt(guestId);
|
||||
},
|
||||
renderMyUserInfo: function()
|
||||
{
|
||||
if (myUserInfo.name)
|
||||
{
|
||||
$("#myusernameedit").removeClass("editempty").val(
|
||||
myUserInfo.name);
|
||||
}
|
||||
else
|
||||
{
|
||||
$("#myusernameedit").addClass("editempty").val("Enter your name");
|
||||
}
|
||||
if (colorPickerOpen)
|
||||
{
|
||||
$("#myswatchbox").addClass('myswatchboxunhoverable').removeClass('myswatchboxhoverable');
|
||||
}
|
||||
else
|
||||
{
|
||||
$("#myswatchbox").addClass('myswatchboxhoverable').removeClass('myswatchboxunhoverable');
|
||||
}
|
||||
|
||||
$("#myswatch").css({'background-color': myUserInfo.colorId});
|
||||
|
||||
if ($.browser.msie && parseInt($.browser.version) <= 8) {
|
||||
$("#usericon").css({'box-shadow': 'inset 0 0 30px ' + myUserInfo.colorId,'background-color': myUserInfo.colorId});
|
||||
}
|
||||
else
|
||||
{
|
||||
$("#usericon").css({'box-shadow': 'inset 0 0 30px ' + myUserInfo.colorId});
|
||||
}
|
||||
}
|
||||
};
|
||||
return self;
|
||||
}());
|
||||
|
||||
function getColorPickerSwatchIndex(jnode)
|
||||
{
|
||||
// return Number(jnode.get(0).className.match(/\bn([0-9]+)\b/)[1])-1;
|
||||
return $("#colorpickerswatches li").index(jnode);
|
||||
}
|
||||
|
||||
function closeColorPicker(accept)
|
||||
{
|
||||
if (accept)
|
||||
{
|
||||
var newColor = $("#mycolorpickerpreview").css("background-color");
|
||||
var parts = newColor.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
|
||||
// parts now should be ["rgb(0, 70, 255", "0", "70", "255"]
|
||||
delete (parts[0]);
|
||||
for (var i = 1; i <= 3; ++i) {
|
||||
parts[i] = parseInt(parts[i]).toString(16);
|
||||
if (parts[i].length == 1) parts[i] = '0' + parts[i];
|
||||
}
|
||||
var newColor = "#" +parts.join(''); // "0070ff"
|
||||
|
||||
myUserInfo.colorId = newColor;
|
||||
pad.notifyChangeColor(newColor);
|
||||
paduserlist.renderMyUserInfo();
|
||||
}
|
||||
else
|
||||
{
|
||||
//pad.notifyChangeColor(previousColorId);
|
||||
//paduserlist.renderMyUserInfo();
|
||||
}
|
||||
|
||||
colorPickerOpen = false;
|
||||
$("#mycolorpicker").fadeOut("fast");
|
||||
}
|
||||
|
||||
function showColorPicker()
|
||||
{
|
||||
previousColorId = myUserInfo.colorId;
|
||||
|
||||
if (!colorPickerOpen)
|
||||
{
|
||||
var palette = pad.getColorPalette();
|
||||
|
||||
if (!colorPickerSetup)
|
||||
{
|
||||
var colorsList = $("#colorpickerswatches")
|
||||
for (var i = 0; i < palette.length; i++)
|
||||
{
|
||||
|
||||
var li = $('<li>', {
|
||||
style: 'background: ' + palette[i] + ';'
|
||||
});
|
||||
|
||||
li.appendTo(colorsList);
|
||||
|
||||
li.bind('click', function(event)
|
||||
{
|
||||
$("#colorpickerswatches li").removeClass('picked');
|
||||
$(event.target).addClass("picked");
|
||||
|
||||
var newColorId = getColorPickerSwatchIndex($("#colorpickerswatches .picked"));
|
||||
pad.notifyChangeColor(newColorId);
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
colorPickerSetup = true;
|
||||
}
|
||||
|
||||
$("#mycolorpicker").fadeIn();
|
||||
colorPickerOpen = true;
|
||||
|
||||
$("#colorpickerswatches li").removeClass('picked');
|
||||
$($("#colorpickerswatches li")[myUserInfo.colorId]).addClass("picked"); //seems weird
|
||||
}
|
||||
}
|
||||
|
||||
exports.paduserlist = paduserlist;
|