2017-03-14 05:02:43 +00:00
|
|
|
'use strict'
|
2017-03-08 10:45:51 +00:00
|
|
|
// realtime
|
|
|
|
// external modules
|
2019-05-06 19:15:33 +00:00
|
|
|
const cookie = require('cookie')
|
|
|
|
const cookieParser = require('cookie-parser')
|
|
|
|
const url = require('url')
|
|
|
|
const randomcolor = require('randomcolor')
|
|
|
|
const Chance = require('chance')
|
|
|
|
const chance = new Chance()
|
|
|
|
const moment = require('moment')
|
2017-03-08 10:45:51 +00:00
|
|
|
|
2019-04-23 11:50:08 +00:00
|
|
|
const get = require('lodash/get')
|
|
|
|
|
2017-03-08 10:45:51 +00:00
|
|
|
// core
|
2019-05-06 19:15:33 +00:00
|
|
|
const config = require('./config')
|
|
|
|
const logger = require('./logger')
|
|
|
|
const history = require('./history')
|
|
|
|
const models = require('./models')
|
2017-03-08 10:45:51 +00:00
|
|
|
|
|
|
|
// ot
|
2019-05-06 19:15:33 +00:00
|
|
|
const ot = require('./ot')
|
2017-03-08 10:45:51 +00:00
|
|
|
|
2019-05-27 07:19:53 +00:00
|
|
|
const { ProcessQueue } = require('./processQueue')
|
2019-05-06 19:15:33 +00:00
|
|
|
const { RealtimeClientConnection } = require('./realtimeClientConnection')
|
|
|
|
const { UpdateDirtyNoteJob } = require('./realtimeUpdateDirtyNoteJob')
|
2019-05-10 10:17:13 +00:00
|
|
|
const { CleanDanglingUserJob } = require('./realtimeCleanDanglingUserJob')
|
2019-05-10 11:10:00 +00:00
|
|
|
const { SaveRevisionJob } = require('./realtimeSaveRevisionJob')
|
2019-05-06 09:49:08 +00:00
|
|
|
|
2017-03-08 10:45:51 +00:00
|
|
|
// public
|
2019-05-06 19:15:33 +00:00
|
|
|
const realtime = {
|
2017-03-08 10:45:51 +00:00
|
|
|
io: null,
|
|
|
|
onAuthorizeSuccess: onAuthorizeSuccess,
|
|
|
|
onAuthorizeFail: onAuthorizeFail,
|
|
|
|
secure: secure,
|
|
|
|
connection: connection,
|
|
|
|
getStatus: getStatus,
|
2017-04-12 17:57:55 +00:00
|
|
|
isReady: isReady,
|
|
|
|
maintenance: true
|
2015-06-01 10:04:25 +00:00
|
|
|
}
|
|
|
|
|
2019-05-10 11:10:00 +00:00
|
|
|
const disconnectProcessQueue = new ProcessQueue(2000, 500)
|
|
|
|
const updateDirtyNoteJob = new UpdateDirtyNoteJob(realtime)
|
|
|
|
const cleanDanglingUserJob = new CleanDanglingUserJob(realtime)
|
|
|
|
const saveRevisionJob = new SaveRevisionJob(realtime)
|
|
|
|
|
2019-05-15 08:25:20 +00:00
|
|
|
// TODO: test it
|
2017-03-08 10:45:51 +00:00
|
|
|
function onAuthorizeSuccess (data, accept) {
|
|
|
|
accept()
|
2015-06-01 10:04:25 +00:00
|
|
|
}
|
|
|
|
|
2019-05-15 08:25:20 +00:00
|
|
|
// TODO: test it
|
2017-03-08 10:45:51 +00:00
|
|
|
function onAuthorizeFail (data, message, error, accept) {
|
|
|
|
accept() // accept whether authorize or not to allow anonymous usage
|
|
|
|
}
|
|
|
|
|
2019-05-15 08:25:20 +00:00
|
|
|
// TODO: test it
|
2017-03-08 10:45:51 +00:00
|
|
|
// secure the origin by the cookie
|
|
|
|
function secure (socket, next) {
|
|
|
|
try {
|
|
|
|
var handshakeData = socket.request
|
|
|
|
if (handshakeData.headers.cookie) {
|
|
|
|
handshakeData.cookie = cookie.parse(handshakeData.headers.cookie)
|
2018-03-07 14:17:35 +00:00
|
|
|
handshakeData.sessionID = cookieParser.signedCookie(handshakeData.cookie[config.sessionName], config.sessionSecret)
|
2017-03-08 10:45:51 +00:00
|
|
|
if (handshakeData.sessionID &&
|
2019-05-27 06:55:25 +00:00
|
|
|
handshakeData.cookie[config.sessionName] &&
|
|
|
|
handshakeData.cookie[config.sessionName] !== handshakeData.sessionID) {
|
|
|
|
if (config.debug) {
|
|
|
|
logger.info('AUTH success cookie: ' + handshakeData.sessionID)
|
|
|
|
}
|
2017-03-08 10:45:51 +00:00
|
|
|
return next()
|
|
|
|
} else {
|
|
|
|
next(new Error('AUTH failed: Cookie is invalid.'))
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
next(new Error('AUTH failed: No cookie transmitted.'))
|
2015-05-04 07:53:29 +00:00
|
|
|
}
|
2017-03-08 10:45:51 +00:00
|
|
|
} catch (ex) {
|
|
|
|
next(new Error('AUTH failed:' + JSON.stringify(ex)))
|
|
|
|
}
|
2015-05-04 07:53:29 +00:00
|
|
|
}
|
|
|
|
|
2019-05-27 07:19:53 +00:00
|
|
|
// TODO: only use in `updateDirtyNote`
|
2019-05-15 08:25:20 +00:00
|
|
|
// TODO: test it
|
2017-03-08 10:45:51 +00:00
|
|
|
function emitCheck (note) {
|
|
|
|
var out = {
|
|
|
|
title: note.title,
|
|
|
|
updatetime: note.updatetime,
|
|
|
|
lastchangeuser: note.lastchangeuser,
|
|
|
|
lastchangeuserprofile: note.lastchangeuserprofile,
|
|
|
|
authors: note.authors,
|
|
|
|
authorship: note.authorship
|
|
|
|
}
|
|
|
|
realtime.io.to(note.id).emit('check', out)
|
2015-07-11 04:43:08 +00:00
|
|
|
}
|
|
|
|
|
2017-03-08 10:45:51 +00:00
|
|
|
// actions
|
|
|
|
var users = {}
|
|
|
|
var notes = {}
|
2019-05-06 19:15:33 +00:00
|
|
|
|
2019-05-27 07:19:53 +00:00
|
|
|
disconnectProcessQueue.start()
|
2019-05-10 11:10:00 +00:00
|
|
|
updateDirtyNoteJob.start()
|
|
|
|
cleanDanglingUserJob.start()
|
|
|
|
saveRevisionJob.start()
|
2019-05-06 19:15:33 +00:00
|
|
|
|
|
|
|
function disconnectSocketOnNote (note) {
|
|
|
|
note.socks.forEach((sock) => {
|
|
|
|
if (sock) {
|
|
|
|
sock.emit('delete')
|
|
|
|
setImmediate(() => {
|
|
|
|
sock.disconnect(true)
|
2017-03-08 10:45:51 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
})
|
2019-05-06 19:15:33 +00:00
|
|
|
}
|
2017-03-08 10:45:51 +00:00
|
|
|
|
|
|
|
function updateNote (note, callback) {
|
2019-05-15 06:33:09 +00:00
|
|
|
_updateNoteAsync(note).then(_note => {
|
|
|
|
callback(null, _note)
|
|
|
|
}).catch((err) => {
|
|
|
|
logger.error(err)
|
|
|
|
return callback(err, null)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
function findNoteByIdAsync (id) {
|
|
|
|
return models.Note.findOne({
|
2017-03-08 10:45:51 +00:00
|
|
|
where: {
|
2019-05-15 06:33:09 +00:00
|
|
|
id: id
|
2017-03-08 10:45:51 +00:00
|
|
|
}
|
2019-05-15 06:33:09 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
function updateHistoryForEveryUserCollaborateNote (note) {
|
|
|
|
// update history to every user in this note
|
|
|
|
const tempUsers = Object.assign({}, note.tempUsers)
|
|
|
|
note.tempUsers = {}
|
|
|
|
// update history should async function, but in there return values is not matter
|
|
|
|
Object.keys(tempUsers).forEach(function (key) {
|
|
|
|
exports.updateHistory(key, note, tempUsers[key])
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
async function getUserProfileByIdAsync (id) {
|
|
|
|
const user = await models.User.findOne({
|
|
|
|
where: {
|
|
|
|
id: id
|
2017-03-08 10:45:51 +00:00
|
|
|
}
|
|
|
|
})
|
2019-05-15 06:33:09 +00:00
|
|
|
if (!user) return null
|
|
|
|
return models.User.getProfile(user)
|
|
|
|
}
|
|
|
|
|
|
|
|
class UserNotFoundException extends Error {
|
|
|
|
constructor () {
|
|
|
|
super('user not found')
|
|
|
|
this.name = this.constructor.name
|
|
|
|
Error.captureStackTrace(this, this.constructor)
|
|
|
|
}
|
2016-11-16 05:58:59 +00:00
|
|
|
}
|
2017-03-08 10:45:51 +00:00
|
|
|
|
2019-05-15 06:33:09 +00:00
|
|
|
async function getLastChangeUserProfileAsync (currentLastChangeUserId, lastChangeUserIdInDatabase, lastChangeUserProfileInDatabase) {
|
|
|
|
if (!currentLastChangeUserId) return null
|
|
|
|
if (currentLastChangeUserId === lastChangeUserIdInDatabase) return lastChangeUserProfileInDatabase
|
|
|
|
const profile = await getUserProfileByIdAsync(currentLastChangeUserId)
|
|
|
|
if (!profile) {
|
|
|
|
throw new UserNotFoundException()
|
|
|
|
}
|
|
|
|
return profile
|
|
|
|
}
|
|
|
|
|
|
|
|
function buildNoteUpdateData (note) {
|
|
|
|
const body = note.server.document
|
|
|
|
const title = note.title = models.Note.parseNoteTitle(body)
|
|
|
|
return {
|
2017-03-08 10:45:51 +00:00
|
|
|
title: title,
|
|
|
|
content: body,
|
|
|
|
authorship: note.authorship,
|
|
|
|
lastchangeuserId: note.lastchangeuser,
|
|
|
|
lastchangeAt: Date.now()
|
|
|
|
}
|
2016-11-16 05:58:59 +00:00
|
|
|
}
|
2017-03-08 10:45:51 +00:00
|
|
|
|
2019-05-15 06:33:09 +00:00
|
|
|
async function _updateNoteAsync (note) {
|
|
|
|
let noteModel = await findNoteByIdAsync(note.id)
|
|
|
|
if (!noteModel) return null
|
|
|
|
|
|
|
|
updateHistoryForEveryUserCollaborateNote(note)
|
|
|
|
|
|
|
|
try {
|
|
|
|
note.lastchangeuserprofile = await getLastChangeUserProfileAsync(
|
|
|
|
note.lastchangeuser,
|
|
|
|
noteModel.lastchangeuserId,
|
|
|
|
noteModel.lastchangeuserprofile
|
|
|
|
)
|
|
|
|
} catch (err) {
|
|
|
|
if (err instanceof UserNotFoundException) {
|
|
|
|
return null
|
|
|
|
}
|
|
|
|
throw err
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!note || !note.server) return null
|
|
|
|
noteModel = await noteModel.update(buildNoteUpdateData(note))
|
|
|
|
saveRevisionJob.setSaverSleep(false)
|
|
|
|
return noteModel
|
|
|
|
}
|
2017-03-08 10:45:51 +00:00
|
|
|
|
2019-05-15 08:25:20 +00:00
|
|
|
// TODO: test it
|
2017-03-08 10:45:51 +00:00
|
|
|
function getStatus (callback) {
|
|
|
|
models.Note.count().then(function (notecount) {
|
|
|
|
var distinctaddresses = []
|
|
|
|
var regaddresses = []
|
|
|
|
var distinctregaddresses = []
|
|
|
|
Object.keys(users).forEach(function (key) {
|
|
|
|
var user = users[key]
|
|
|
|
if (!user) return
|
|
|
|
let found = false
|
|
|
|
for (let i = 0; i < distinctaddresses.length; i++) {
|
|
|
|
if (user.address === distinctaddresses[i]) {
|
|
|
|
found = true
|
|
|
|
break
|
2016-06-17 08:09:33 +00:00
|
|
|
}
|
2017-03-08 10:45:51 +00:00
|
|
|
}
|
|
|
|
if (!found) {
|
|
|
|
distinctaddresses.push(user.address)
|
|
|
|
}
|
|
|
|
if (user.login) {
|
|
|
|
regaddresses.push(user.address)
|
|
|
|
let found = false
|
|
|
|
for (let i = 0; i < distinctregaddresses.length; i++) {
|
|
|
|
if (user.address === distinctregaddresses[i]) {
|
|
|
|
found = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (!found) {
|
|
|
|
distinctregaddresses.push(user.address)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
models.User.count().then(function (regcount) {
|
2018-11-14 13:10:14 +00:00
|
|
|
// eslint-disable-next-line standard/no-callback-literal
|
2017-03-08 10:45:51 +00:00
|
|
|
return callback ? callback({
|
|
|
|
onlineNotes: Object.keys(notes).length,
|
|
|
|
onlineUsers: Object.keys(users).length,
|
|
|
|
distinctOnlineUsers: distinctaddresses.length,
|
|
|
|
notesCount: notecount,
|
|
|
|
registeredUsers: regcount,
|
|
|
|
onlineRegisteredUsers: regaddresses.length,
|
|
|
|
distinctOnlineRegisteredUsers: distinctregaddresses.length,
|
|
|
|
isConnectionBusy: isConnectionBusy,
|
|
|
|
connectionSocketQueueLength: connectionSocketQueue.length,
|
2019-05-27 07:19:53 +00:00
|
|
|
isDisconnectBusy: disconnectProcessQueue.lock,
|
|
|
|
disconnectSocketQueueLength: disconnectProcessQueue.queue.length
|
2017-03-08 10:45:51 +00:00
|
|
|
}) : null
|
2016-04-20 10:03:55 +00:00
|
|
|
}).catch(function (err) {
|
2017-03-08 10:45:51 +00:00
|
|
|
return logger.error('count user failed: ' + err)
|
|
|
|
})
|
|
|
|
}).catch(function (err) {
|
|
|
|
return logger.error('count note failed: ' + err)
|
|
|
|
})
|
2015-05-04 07:53:29 +00:00
|
|
|
}
|
|
|
|
|
2019-05-15 08:25:20 +00:00
|
|
|
// TODO: test it
|
2017-03-08 10:45:51 +00:00
|
|
|
function isReady () {
|
|
|
|
return realtime.io &&
|
|
|
|
Object.keys(notes).length === 0 && Object.keys(users).length === 0 &&
|
|
|
|
connectionSocketQueue.length === 0 && !isConnectionBusy &&
|
2019-05-27 07:19:53 +00:00
|
|
|
disconnectProcessQueue.queue.length === 0 && !disconnectProcessQueue.lock
|
2016-06-17 08:09:33 +00:00
|
|
|
}
|
|
|
|
|
2019-04-23 11:50:08 +00:00
|
|
|
function parseUrl (data) {
|
|
|
|
try {
|
|
|
|
if (url.URL) {
|
|
|
|
return new url.URL(data)
|
|
|
|
} else {
|
|
|
|
// fallback legacy api
|
|
|
|
// eslint-disable-next-line
|
|
|
|
return url.parse(data)
|
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
}
|
|
|
|
return null
|
|
|
|
}
|
|
|
|
|
2017-03-08 10:45:51 +00:00
|
|
|
function extractNoteIdFromSocket (socket) {
|
2019-04-23 11:50:08 +00:00
|
|
|
function extractNoteIdFromReferer (referer) {
|
|
|
|
if (referer) {
|
|
|
|
const hostUrl = parseUrl(referer)
|
|
|
|
if (!hostUrl) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if (config.urlPath) {
|
|
|
|
return hostUrl.pathname.slice(config.urlPath.length + 1, hostUrl.pathname.length).split('/')[1]
|
|
|
|
}
|
|
|
|
return hostUrl.pathname.split('/')[1]
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2017-09-13 12:48:39 +00:00
|
|
|
if (!socket || !socket.handshake) {
|
2017-03-08 10:45:51 +00:00
|
|
|
return false
|
|
|
|
}
|
2019-04-23 11:50:08 +00:00
|
|
|
|
|
|
|
if (get(socket, 'handshake.query.noteId')) {
|
|
|
|
return decodeURIComponent(socket.handshake.query.noteId)
|
|
|
|
}
|
|
|
|
|
|
|
|
const referer = get(socket, 'handshake.headers.referer')
|
|
|
|
if (referer) {
|
2017-09-13 12:48:39 +00:00
|
|
|
// this part is only for backward compatibility only; current code
|
|
|
|
// should be using noteId query parameter instead.
|
2019-04-23 11:50:08 +00:00
|
|
|
return extractNoteIdFromReferer(referer)
|
2017-03-08 10:45:51 +00:00
|
|
|
}
|
2019-04-23 11:50:08 +00:00
|
|
|
|
|
|
|
return false
|
2016-04-20 10:03:55 +00:00
|
|
|
}
|
|
|
|
|
2017-03-08 10:45:51 +00:00
|
|
|
function parseNoteIdFromSocket (socket, callback) {
|
|
|
|
var noteId = extractNoteIdFromSocket(socket)
|
|
|
|
if (!noteId) {
|
|
|
|
return callback(null, null)
|
|
|
|
}
|
|
|
|
models.Note.parseNoteId(noteId, function (err, id) {
|
|
|
|
if (err || !id) return callback(err, id)
|
|
|
|
return callback(null, id)
|
|
|
|
})
|
2015-05-04 07:53:29 +00:00
|
|
|
}
|
|
|
|
|
2019-05-15 08:25:20 +00:00
|
|
|
// TODO: test it
|
2017-03-08 10:45:51 +00:00
|
|
|
function emitOnlineUsers (socket) {
|
|
|
|
var noteId = socket.noteId
|
|
|
|
if (!noteId || !notes[noteId]) return
|
|
|
|
var users = []
|
|
|
|
Object.keys(notes[noteId].users).forEach(function (key) {
|
|
|
|
var user = notes[noteId].users[key]
|
2019-05-27 06:55:25 +00:00
|
|
|
if (user) {
|
|
|
|
users.push(buildUserOutData(user))
|
|
|
|
}
|
2017-03-08 10:45:51 +00:00
|
|
|
})
|
|
|
|
var out = {
|
|
|
|
users: users
|
|
|
|
}
|
|
|
|
realtime.io.to(noteId).emit('online users', out)
|
2015-06-01 10:04:25 +00:00
|
|
|
}
|
|
|
|
|
2019-05-15 08:25:20 +00:00
|
|
|
// TODO: test it
|
2017-03-08 10:45:51 +00:00
|
|
|
function emitUserStatus (socket) {
|
|
|
|
var noteId = socket.noteId
|
|
|
|
var user = users[socket.id]
|
|
|
|
if (!noteId || !notes[noteId] || !user) return
|
|
|
|
var out = buildUserOutData(user)
|
|
|
|
socket.broadcast.to(noteId).emit('user status', out)
|
2015-07-01 16:10:20 +00:00
|
|
|
}
|
|
|
|
|
2019-05-15 08:25:20 +00:00
|
|
|
// TODO: test it
|
2017-03-08 10:45:51 +00:00
|
|
|
function emitRefresh (socket) {
|
|
|
|
var noteId = socket.noteId
|
|
|
|
if (!noteId || !notes[noteId]) return
|
|
|
|
var note = notes[noteId]
|
|
|
|
var out = {
|
|
|
|
title: note.title,
|
2018-03-07 14:17:35 +00:00
|
|
|
docmaxlength: config.documentMaxLength,
|
2017-03-08 10:45:51 +00:00
|
|
|
owner: note.owner,
|
|
|
|
ownerprofile: note.ownerprofile,
|
|
|
|
lastchangeuser: note.lastchangeuser,
|
|
|
|
lastchangeuserprofile: note.lastchangeuserprofile,
|
|
|
|
authors: note.authors,
|
|
|
|
authorship: note.authorship,
|
|
|
|
permission: note.permission,
|
|
|
|
createtime: note.createtime,
|
|
|
|
updatetime: note.updatetime
|
|
|
|
}
|
|
|
|
socket.emit('refresh', out)
|
2015-05-04 07:53:29 +00:00
|
|
|
}
|
|
|
|
|
2019-05-15 08:25:20 +00:00
|
|
|
// TODO: test it
|
2017-03-08 10:45:51 +00:00
|
|
|
function isDuplicatedInSocketQueue (queue, socket) {
|
|
|
|
for (var i = 0; i < queue.length; i++) {
|
|
|
|
if (queue[i] && queue[i].id === socket.id) {
|
|
|
|
return true
|
2016-10-10 12:25:48 +00:00
|
|
|
}
|
2017-03-08 10:45:51 +00:00
|
|
|
}
|
|
|
|
return false
|
2016-10-10 12:25:48 +00:00
|
|
|
}
|
|
|
|
|
2019-05-15 08:25:20 +00:00
|
|
|
// TODO: test it
|
2017-03-08 10:45:51 +00:00
|
|
|
function clearSocketQueue (queue, socket) {
|
|
|
|
for (var i = 0; i < queue.length; i++) {
|
|
|
|
if (!queue[i] || queue[i].id === socket.id) {
|
|
|
|
queue.splice(i, 1)
|
|
|
|
i--
|
2015-09-27 03:43:33 +00:00
|
|
|
}
|
2017-03-08 10:45:51 +00:00
|
|
|
}
|
2015-09-27 03:43:33 +00:00
|
|
|
}
|
|
|
|
|
2019-05-15 08:25:20 +00:00
|
|
|
// TODO: test it
|
2017-03-08 10:45:51 +00:00
|
|
|
function connectNextSocket () {
|
|
|
|
setTimeout(function () {
|
|
|
|
isConnectionBusy = false
|
|
|
|
if (connectionSocketQueue.length > 0) {
|
|
|
|
startConnection(connectionSocketQueue[0])
|
|
|
|
}
|
|
|
|
}, 1)
|
2016-07-05 08:11:18 +00:00
|
|
|
}
|
|
|
|
|
2019-05-15 08:25:20 +00:00
|
|
|
// TODO: test it
|
2017-03-08 10:45:51 +00:00
|
|
|
function interruptConnection (socket, noteId, socketId) {
|
|
|
|
if (notes[noteId]) delete notes[noteId]
|
|
|
|
if (users[socketId]) delete users[socketId]
|
2019-05-27 06:55:25 +00:00
|
|
|
if (socket) {
|
|
|
|
clearSocketQueue(connectionSocketQueue, socket)
|
|
|
|
} else {
|
|
|
|
connectionSocketQueue.shift()
|
|
|
|
}
|
2017-03-08 10:45:51 +00:00
|
|
|
connectNextSocket()
|
2016-07-30 03:10:43 +00:00
|
|
|
}
|
|
|
|
|
2017-03-08 10:45:51 +00:00
|
|
|
function checkViewPermission (req, note) {
|
|
|
|
if (note.permission === 'private') {
|
2019-05-27 06:55:25 +00:00
|
|
|
if (req.user && req.user.logged_in && req.user.id === note.owner) {
|
|
|
|
return true
|
|
|
|
} else {
|
|
|
|
return false
|
|
|
|
}
|
2017-03-08 10:45:51 +00:00
|
|
|
} else if (note.permission === 'limited' || note.permission === 'protected') {
|
2019-05-27 06:55:25 +00:00
|
|
|
if (req.user && req.user.logged_in) {
|
|
|
|
return true
|
|
|
|
} else {
|
|
|
|
return false
|
|
|
|
}
|
2017-03-08 10:45:51 +00:00
|
|
|
} else {
|
|
|
|
return true
|
|
|
|
}
|
2017-01-16 15:47:53 +00:00
|
|
|
}
|
|
|
|
|
2017-03-08 10:45:51 +00:00
|
|
|
var isConnectionBusy = false
|
|
|
|
var connectionSocketQueue = []
|
|
|
|
|
2019-05-15 08:25:20 +00:00
|
|
|
// TODO: test it
|
2017-03-08 10:45:51 +00:00
|
|
|
function finishConnection (socket, noteId, socketId) {
|
|
|
|
// if no valid info provided will drop the client
|
|
|
|
if (!socket || !notes[noteId] || !users[socketId]) {
|
|
|
|
return interruptConnection(socket, noteId, socketId)
|
|
|
|
}
|
|
|
|
// check view permission
|
|
|
|
if (!checkViewPermission(socket.request, notes[noteId])) {
|
|
|
|
interruptConnection(socket, noteId, socketId)
|
|
|
|
return failConnection(403, 'connection forbidden', socket)
|
|
|
|
}
|
|
|
|
let note = notes[noteId]
|
|
|
|
let user = users[socketId]
|
|
|
|
// update user color to author color
|
|
|
|
if (note.authors[user.userid]) {
|
|
|
|
user.color = users[socket.id].color = note.authors[user.userid].color
|
|
|
|
}
|
|
|
|
note.users[socket.id] = user
|
|
|
|
note.socks.push(socket)
|
|
|
|
note.server.addClient(socket)
|
|
|
|
note.server.setName(socket, user.name)
|
|
|
|
note.server.setColor(socket, user.color)
|
|
|
|
|
|
|
|
// update user note history
|
|
|
|
updateHistory(user.userid, note)
|
|
|
|
|
|
|
|
emitOnlineUsers(socket)
|
|
|
|
emitRefresh(socket)
|
|
|
|
|
|
|
|
// clear finished socket in queue
|
|
|
|
clearSocketQueue(connectionSocketQueue, socket)
|
|
|
|
// seek for next socket
|
|
|
|
connectNextSocket()
|
|
|
|
|
|
|
|
if (config.debug) {
|
|
|
|
let noteId = socket.noteId
|
|
|
|
logger.info('SERVER connected a client to [' + noteId + ']:')
|
|
|
|
logger.info(JSON.stringify(user))
|
|
|
|
// logger.info(notes);
|
|
|
|
getStatus(function (data) {
|
|
|
|
logger.info(JSON.stringify(data))
|
|
|
|
})
|
|
|
|
}
|
2015-05-04 07:53:29 +00:00
|
|
|
}
|
|
|
|
|
2019-05-15 08:25:20 +00:00
|
|
|
// TODO: test it
|
2017-03-08 10:45:51 +00:00
|
|
|
function startConnection (socket) {
|
|
|
|
if (isConnectionBusy) return
|
|
|
|
isConnectionBusy = true
|
|
|
|
|
|
|
|
var noteId = socket.noteId
|
|
|
|
if (!noteId) {
|
|
|
|
return failConnection(404, 'note id not found', socket)
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!notes[noteId]) {
|
|
|
|
var include = [{
|
|
|
|
model: models.User,
|
|
|
|
as: 'owner'
|
|
|
|
}, {
|
|
|
|
model: models.User,
|
|
|
|
as: 'lastchangeuser'
|
|
|
|
}, {
|
|
|
|
model: models.Author,
|
|
|
|
as: 'authors',
|
|
|
|
include: [{
|
|
|
|
model: models.User,
|
|
|
|
as: 'user'
|
|
|
|
}]
|
|
|
|
}]
|
2017-01-10 02:02:37 +00:00
|
|
|
|
2017-03-08 10:45:51 +00:00
|
|
|
models.Note.findOne({
|
|
|
|
where: {
|
|
|
|
id: noteId
|
|
|
|
},
|
|
|
|
include: include
|
|
|
|
}).then(function (note) {
|
|
|
|
if (!note) {
|
|
|
|
return failConnection(404, 'note not found', socket)
|
|
|
|
}
|
|
|
|
var owner = note.ownerId
|
|
|
|
var ownerprofile = note.owner ? models.User.getProfile(note.owner) : null
|
|
|
|
|
|
|
|
var lastchangeuser = note.lastchangeuserId
|
|
|
|
var lastchangeuserprofile = note.lastchangeuser ? models.User.getProfile(note.lastchangeuser) : null
|
|
|
|
|
|
|
|
var body = note.content
|
|
|
|
var createtime = note.createdAt
|
|
|
|
var updatetime = note.lastchangeAt
|
|
|
|
var server = new ot.EditorSocketIOServer(body, [], noteId, ifMayEdit, operationCallback)
|
|
|
|
|
|
|
|
var authors = {}
|
|
|
|
for (var i = 0; i < note.authors.length; i++) {
|
|
|
|
var author = note.authors[i]
|
|
|
|
var profile = models.User.getProfile(author.user)
|
2018-05-25 14:15:10 +00:00
|
|
|
if (profile) {
|
|
|
|
authors[author.userId] = {
|
|
|
|
userid: author.userId,
|
|
|
|
color: author.color,
|
|
|
|
photo: profile.photo,
|
|
|
|
name: profile.name
|
|
|
|
}
|
2017-03-08 10:45:51 +00:00
|
|
|
}
|
|
|
|
}
|
2015-05-04 07:53:29 +00:00
|
|
|
|
2017-03-08 10:45:51 +00:00
|
|
|
notes[noteId] = {
|
|
|
|
id: noteId,
|
|
|
|
alias: note.alias,
|
|
|
|
title: note.title,
|
|
|
|
owner: owner,
|
|
|
|
ownerprofile: ownerprofile,
|
|
|
|
permission: note.permission,
|
|
|
|
lastchangeuser: lastchangeuser,
|
|
|
|
lastchangeuserprofile: lastchangeuserprofile,
|
|
|
|
socks: [],
|
|
|
|
users: {},
|
|
|
|
tempUsers: {},
|
|
|
|
createtime: moment(createtime).valueOf(),
|
|
|
|
updatetime: moment(updatetime).valueOf(),
|
|
|
|
server: server,
|
|
|
|
authors: authors,
|
|
|
|
authorship: note.authorship
|
|
|
|
}
|
2016-04-20 10:03:55 +00:00
|
|
|
|
2017-03-08 10:45:51 +00:00
|
|
|
return finishConnection(socket, noteId, socket.id)
|
|
|
|
}).catch(function (err) {
|
|
|
|
return failConnection(500, err, socket)
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
return finishConnection(socket, noteId, socket.id)
|
|
|
|
}
|
2015-05-04 07:53:29 +00:00
|
|
|
}
|
|
|
|
|
2019-05-15 08:25:20 +00:00
|
|
|
// TODO: test it
|
2017-03-08 10:45:51 +00:00
|
|
|
function failConnection (code, err, socket) {
|
|
|
|
logger.error(err)
|
|
|
|
// clear error socket in queue
|
|
|
|
clearSocketQueue(connectionSocketQueue, socket)
|
|
|
|
connectNextSocket()
|
|
|
|
// emit error info
|
|
|
|
socket.emit('info', {
|
|
|
|
code: code
|
|
|
|
})
|
|
|
|
return socket.disconnect(true)
|
2016-04-20 10:03:55 +00:00
|
|
|
}
|
|
|
|
|
2019-05-27 07:19:53 +00:00
|
|
|
function queueForDisconnect (socket) {
|
|
|
|
disconnectProcessQueue.push(socket.id, async function () {
|
|
|
|
if (users[socket.id]) {
|
|
|
|
delete users[socket.id]
|
2015-05-04 07:53:29 +00:00
|
|
|
}
|
2019-05-27 07:19:53 +00:00
|
|
|
const noteId = socket.noteId
|
|
|
|
const note = notes[noteId]
|
|
|
|
if (note) {
|
|
|
|
// delete user in users
|
|
|
|
if (note.users[socket.id]) {
|
|
|
|
delete note.users[socket.id]
|
2017-03-08 10:45:51 +00:00
|
|
|
}
|
2019-05-27 07:19:53 +00:00
|
|
|
// remove sockets in the note socks
|
|
|
|
let index
|
|
|
|
do {
|
|
|
|
index = note.socks.indexOf(socket)
|
|
|
|
if (index !== -1) {
|
|
|
|
note.socks.splice(index, 1)
|
|
|
|
}
|
|
|
|
} while (index !== -1)
|
|
|
|
// remove note in notes if no user inside
|
|
|
|
if (Object.keys(note.users).length === 0) {
|
|
|
|
if (note.server.isDirty) {
|
|
|
|
exports.updateNote(note, function (err, _note) {
|
|
|
|
if (err) return logger.error('disconnect note failed: ' + err)
|
|
|
|
// clear server before delete to avoid memory leaks
|
|
|
|
note.server.document = ''
|
|
|
|
note.server.operations = []
|
|
|
|
delete note.server
|
|
|
|
delete notes[noteId]
|
|
|
|
})
|
|
|
|
} else {
|
2017-03-08 10:45:51 +00:00
|
|
|
delete note.server
|
|
|
|
delete notes[noteId]
|
2019-05-27 07:19:53 +00:00
|
|
|
}
|
2017-03-08 10:45:51 +00:00
|
|
|
}
|
2015-05-04 07:53:29 +00:00
|
|
|
}
|
2019-05-27 07:19:53 +00:00
|
|
|
exports.emitOnlineUsers(socket)
|
|
|
|
})
|
2015-05-04 07:53:29 +00:00
|
|
|
}
|
|
|
|
|
2017-03-08 10:45:51 +00:00
|
|
|
function buildUserOutData (user) {
|
|
|
|
var out = {
|
|
|
|
id: user.id,
|
|
|
|
login: user.login,
|
|
|
|
userid: user.userid,
|
|
|
|
photo: user.photo,
|
|
|
|
color: user.color,
|
|
|
|
cursor: user.cursor,
|
|
|
|
name: user.name,
|
|
|
|
idle: user.idle,
|
|
|
|
type: user.type
|
|
|
|
}
|
|
|
|
return out
|
2015-06-01 10:04:25 +00:00
|
|
|
}
|
|
|
|
|
2019-05-15 08:25:20 +00:00
|
|
|
// TODO: test it
|
2017-03-08 10:45:51 +00:00
|
|
|
function updateUserData (socket, user) {
|
|
|
|
// retrieve user data from passport
|
|
|
|
if (socket.request.user && socket.request.user.logged_in) {
|
|
|
|
var profile = models.User.getProfile(socket.request.user)
|
|
|
|
user.photo = profile.photo
|
|
|
|
user.name = profile.name
|
|
|
|
user.userid = socket.request.user.id
|
|
|
|
user.login = true
|
|
|
|
} else {
|
|
|
|
user.userid = null
|
|
|
|
user.name = 'Guest ' + chance.last()
|
|
|
|
user.login = false
|
|
|
|
}
|
2015-06-01 10:04:25 +00:00
|
|
|
}
|
2015-05-04 07:53:29 +00:00
|
|
|
|
2019-05-15 08:25:20 +00:00
|
|
|
function canEditNote(notePermission, noteOwnerId, currentUserId) {
|
|
|
|
switch (notePermission) {
|
2017-03-08 10:45:51 +00:00
|
|
|
case 'freely':
|
2019-05-15 08:25:20 +00:00
|
|
|
return true
|
2019-05-27 06:55:25 +00:00
|
|
|
case 'editable':
|
|
|
|
case 'limited':
|
2017-03-08 10:45:51 +00:00
|
|
|
// only login user can change
|
2019-05-15 08:25:20 +00:00
|
|
|
return !!currentUserId
|
2019-05-27 06:55:25 +00:00
|
|
|
case 'locked':
|
|
|
|
case 'private':
|
|
|
|
case 'protected':
|
2017-03-08 10:45:51 +00:00
|
|
|
// only owner can change
|
2019-05-15 08:25:20 +00:00
|
|
|
return noteOwnerId === currentUserId
|
2017-03-08 10:45:51 +00:00
|
|
|
}
|
2019-05-15 08:25:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function ifMayEdit (socket, callback) {
|
|
|
|
const note = getNoteFromNotePool(socket.noteId)
|
|
|
|
if (!note) return
|
|
|
|
const mayEdit = canEditNote(note.permission, note.owner, socket.request.user.id)
|
2017-03-08 10:45:51 +00:00
|
|
|
// if user may edit and this is a text operation
|
|
|
|
if (socket.origin === 'operation' && mayEdit) {
|
|
|
|
// save for the last change user id
|
|
|
|
if (socket.request.user && socket.request.user.logged_in) {
|
|
|
|
note.lastchangeuser = socket.request.user.id
|
|
|
|
} else {
|
|
|
|
note.lastchangeuser = null
|
2015-07-11 04:43:08 +00:00
|
|
|
}
|
2017-03-08 10:45:51 +00:00
|
|
|
}
|
|
|
|
return callback(mayEdit)
|
2015-07-11 04:43:08 +00:00
|
|
|
}
|
|
|
|
|
2019-05-15 08:25:20 +00:00
|
|
|
// TODO: test it
|
2017-03-08 10:45:51 +00:00
|
|
|
function operationCallback (socket, operation) {
|
|
|
|
var noteId = socket.noteId
|
|
|
|
if (!noteId || !notes[noteId]) return
|
|
|
|
var note = notes[noteId]
|
|
|
|
var userId = null
|
|
|
|
// save authors
|
|
|
|
if (socket.request.user && socket.request.user.logged_in) {
|
|
|
|
var user = users[socket.id]
|
|
|
|
if (!user) return
|
|
|
|
userId = socket.request.user.id
|
|
|
|
if (!note.authors[userId]) {
|
|
|
|
models.Author.findOrCreate({
|
|
|
|
where: {
|
|
|
|
noteId: noteId,
|
|
|
|
userId: userId
|
|
|
|
},
|
|
|
|
defaults: {
|
|
|
|
noteId: noteId,
|
|
|
|
userId: userId,
|
|
|
|
color: user.color
|
|
|
|
}
|
|
|
|
}).spread(function (author, created) {
|
|
|
|
if (author) {
|
|
|
|
note.authors[author.userId] = {
|
|
|
|
userid: author.userId,
|
|
|
|
color: author.color,
|
|
|
|
photo: user.photo,
|
|
|
|
name: user.name
|
|
|
|
}
|
2016-07-30 03:21:38 +00:00
|
|
|
}
|
2017-03-08 10:45:51 +00:00
|
|
|
}).catch(function (err) {
|
|
|
|
return logger.error('operation callback failed: ' + err)
|
|
|
|
})
|
2016-07-30 03:21:38 +00:00
|
|
|
}
|
2017-03-08 10:45:51 +00:00
|
|
|
note.tempUsers[userId] = Date.now()
|
|
|
|
}
|
|
|
|
// save authorship - use timer here because it's an O(n) complexity algorithm
|
|
|
|
setImmediate(function () {
|
|
|
|
note.authorship = models.Note.updateAuthorshipByOperation(operation, userId, note.authorship)
|
|
|
|
})
|
2017-02-03 13:47:38 +00:00
|
|
|
}
|
2017-02-03 13:39:08 +00:00
|
|
|
|
2019-05-15 08:25:20 +00:00
|
|
|
// TODO: test it
|
2017-03-08 10:45:51 +00:00
|
|
|
function updateHistory (userId, note, time) {
|
2018-02-26 08:43:29 +00:00
|
|
|
var noteId = note.alias ? note.alias : models.Note.encodeNoteId(note.id)
|
2017-03-08 10:45:51 +00:00
|
|
|
if (note.server) history.updateHistory(userId, noteId, note.server.document, time)
|
2016-07-30 03:21:38 +00:00
|
|
|
}
|
|
|
|
|
2019-05-24 04:41:53 +00:00
|
|
|
function getUserPool () {
|
|
|
|
return users
|
|
|
|
}
|
|
|
|
|
|
|
|
function getUserFromUserPool (userId) {
|
|
|
|
return users[userId]
|
|
|
|
}
|
|
|
|
|
|
|
|
function getNotePool () {
|
|
|
|
return notes
|
|
|
|
}
|
|
|
|
|
|
|
|
function getNoteFromNotePool (noteId) {
|
|
|
|
return notes[noteId]
|
|
|
|
}
|
|
|
|
|
2019-05-15 08:25:20 +00:00
|
|
|
// TODO: test it
|
2017-03-08 10:45:51 +00:00
|
|
|
function connection (socket) {
|
2017-04-12 17:57:55 +00:00
|
|
|
if (realtime.maintenance) return
|
2019-05-24 04:41:53 +00:00
|
|
|
exports.parseNoteIdFromSocket(socket, function (err, noteId) {
|
2017-03-08 10:45:51 +00:00
|
|
|
if (err) {
|
2019-05-24 04:41:53 +00:00
|
|
|
return exports.failConnection(500, err, socket)
|
2017-03-08 10:45:51 +00:00
|
|
|
}
|
|
|
|
if (!noteId) {
|
2019-05-24 04:41:53 +00:00
|
|
|
return exports.failConnection(404, 'note id not found', socket)
|
2017-03-08 10:45:51 +00:00
|
|
|
}
|
2016-10-10 12:25:48 +00:00
|
|
|
|
2018-01-16 07:51:24 +00:00
|
|
|
if (isDuplicatedInSocketQueue(connectionSocketQueue, socket)) return
|
2017-03-08 10:45:51 +00:00
|
|
|
|
|
|
|
// store noteId in this socket session
|
|
|
|
socket.noteId = noteId
|
|
|
|
|
|
|
|
// initialize user data
|
|
|
|
// random color
|
|
|
|
var color = randomcolor()
|
|
|
|
// make sure color not duplicated or reach max random count
|
|
|
|
if (notes[noteId]) {
|
|
|
|
var randomcount = 0
|
|
|
|
var maxrandomcount = 10
|
|
|
|
var found = false
|
|
|
|
do {
|
2018-01-16 07:51:24 +00:00
|
|
|
Object.keys(notes[noteId].users).forEach(function (userId) {
|
|
|
|
if (notes[noteId].users[userId].color === color) {
|
2017-03-08 10:45:51 +00:00
|
|
|
found = true
|
|
|
|
}
|
|
|
|
})
|
|
|
|
if (found) {
|
|
|
|
color = randomcolor()
|
|
|
|
randomcount++
|
2016-04-20 10:03:55 +00:00
|
|
|
}
|
2017-03-08 10:45:51 +00:00
|
|
|
} while (found && randomcount < maxrandomcount)
|
|
|
|
}
|
|
|
|
// create user data
|
|
|
|
users[socket.id] = {
|
|
|
|
id: socket.id,
|
|
|
|
address: socket.handshake.headers['x-forwarded-for'] || socket.handshake.address,
|
|
|
|
'user-agent': socket.handshake.headers['user-agent'],
|
|
|
|
color: color,
|
|
|
|
cursor: null,
|
|
|
|
login: false,
|
|
|
|
userid: null,
|
|
|
|
name: null,
|
|
|
|
idle: false,
|
|
|
|
type: null
|
|
|
|
}
|
2019-05-24 04:41:53 +00:00
|
|
|
exports.updateUserData(socket, users[socket.id])
|
2017-03-08 10:45:51 +00:00
|
|
|
|
|
|
|
// start connection
|
|
|
|
connectionSocketQueue.push(socket)
|
2019-05-24 04:41:53 +00:00
|
|
|
exports.startConnection(socket)
|
2017-03-08 10:45:51 +00:00
|
|
|
})
|
|
|
|
|
2019-05-06 09:49:08 +00:00
|
|
|
const socketClient = new RealtimeClientConnection(socket)
|
2019-05-24 04:41:53 +00:00
|
|
|
socketClient.registerEventHandler()
|
2015-05-04 07:53:29 +00:00
|
|
|
}
|
|
|
|
|
2019-05-15 08:25:20 +00:00
|
|
|
// TODO: test it
|
2019-05-27 07:19:53 +00:00
|
|
|
function terminate () {
|
|
|
|
disconnectProcessQueue.stop()
|
|
|
|
updateDirtyNoteJob.stop()
|
|
|
|
}
|
|
|
|
|
2019-04-23 11:50:08 +00:00
|
|
|
exports = module.exports = realtime
|
|
|
|
exports.extractNoteIdFromSocket = extractNoteIdFromSocket
|
2019-05-24 04:41:53 +00:00
|
|
|
exports.parseNoteIdFromSocket = parseNoteIdFromSocket
|
|
|
|
exports.updateNote = updateNote
|
|
|
|
exports.failConnection = failConnection
|
|
|
|
exports.isDuplicatedInSocketQueue = isDuplicatedInSocketQueue
|
|
|
|
exports.updateUserData = updateUserData
|
|
|
|
exports.startConnection = startConnection
|
|
|
|
exports.emitRefresh = emitRefresh
|
|
|
|
exports.emitUserStatus = emitUserStatus
|
2019-05-24 10:05:16 +00:00
|
|
|
exports.emitOnlineUsers = emitOnlineUsers
|
2019-05-06 07:14:40 +00:00
|
|
|
exports.checkViewPermission = checkViewPermission
|
2019-05-06 09:49:08 +00:00
|
|
|
exports.getNoteFromNotePool = getNoteFromNotePool
|
|
|
|
exports.getUserFromUserPool = getUserFromUserPool
|
|
|
|
exports.buildUserOutData = buildUserOutData
|
2019-05-06 19:15:33 +00:00
|
|
|
exports.getNotePool = getNotePool
|
|
|
|
exports.emitCheck = emitCheck
|
|
|
|
exports.disconnectSocketOnNote = disconnectSocketOnNote
|
2019-05-27 07:19:53 +00:00
|
|
|
exports.queueForDisconnect = queueForDisconnect
|
|
|
|
exports.terminate = terminate
|
|
|
|
exports.getUserPool = getUserPool
|
2019-05-15 06:33:09 +00:00
|
|
|
exports.updateHistory = updateHistory
|
2019-05-15 08:25:20 +00:00
|
|
|
exports.ifMayEdit = ifMayEdit
|
2019-05-27 07:19:53 +00:00
|
|
|
exports.disconnectProcessQueue = disconnectProcessQueue
|
2019-05-24 04:41:53 +00:00
|
|
|
exports.notes = notes
|
|
|
|
exports.users = users
|
2019-05-10 11:10:00 +00:00
|
|
|
exports.saveRevisionJob = saveRevisionJob
|