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
|
2020-01-04 22:14:03 +00:00
|
|
|
const config = require('../config')
|
|
|
|
const logger = require('../logger')
|
2020-01-04 22:30:23 +00:00
|
|
|
const history = require('../history')
|
2020-01-04 22:14:03 +00:00
|
|
|
const models = require('../models')
|
2017-03-08 10:45:51 +00:00
|
|
|
|
|
|
|
// ot
|
2020-01-04 22:14:03 +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-20 08:04:35 +00:00
|
|
|
const connectProcessQueue = new ProcessQueue({})
|
|
|
|
const disconnectProcessQueue = new ProcessQueue({})
|
2019-05-10 11:10:00 +00:00
|
|
|
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-20 08:04:35 +00:00
|
|
|
function getNotePool () {
|
|
|
|
return notes
|
|
|
|
}
|
|
|
|
|
|
|
|
function isNoteExistsInPool (noteId) {
|
|
|
|
return !!notes[noteId]
|
|
|
|
}
|
|
|
|
|
|
|
|
function addNote (note) {
|
|
|
|
if (exports.isNoteExistsInPool(note.id)) return false
|
|
|
|
notes[note.id] = note
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
function getNotePoolSize () {
|
|
|
|
return Object.keys(notes).length
|
|
|
|
}
|
|
|
|
|
2019-05-24 03:40:16 +00:00
|
|
|
function deleteNoteFromPool (noteId) {
|
2019-05-20 08:04:35 +00:00
|
|
|
delete notes[noteId]
|
|
|
|
}
|
|
|
|
|
2019-05-24 03:40:16 +00:00
|
|
|
function deleteAllNoteFromPool () {
|
2019-05-20 08:04:35 +00:00
|
|
|
Object.keys(notes).forEach(noteId => {
|
|
|
|
delete notes[noteId]
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
function getNoteFromNotePool (noteId) {
|
|
|
|
return notes[noteId]
|
|
|
|
}
|
|
|
|
|
|
|
|
function getUserPool () {
|
|
|
|
return users
|
|
|
|
}
|
|
|
|
|
|
|
|
function getUserFromUserPool (userId) {
|
|
|
|
return users[userId]
|
|
|
|
}
|
|
|
|
|
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
|
2020-01-04 21:59:57 +00:00
|
|
|
function getStatus () {
|
|
|
|
return 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
|
2017-03-08 10:45:51 +00:00
|
|
|
let found = false
|
2020-01-04 21:59:57 +00:00
|
|
|
for (let i = 0; i < distinctaddresses.length; i++) {
|
|
|
|
if (user.address === distinctaddresses[i]) {
|
2017-03-08 10:45:51 +00:00
|
|
|
found = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (!found) {
|
2020-01-04 21:59:57 +00:00
|
|
|
distinctaddresses.push(user.address)
|
2017-03-08 10:45:51 +00:00
|
|
|
}
|
2020-01-04 21:59:57 +00:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
return models.User.count()
|
|
|
|
.then(function (regcount) {
|
|
|
|
return {
|
|
|
|
onlineNotes: Object.keys(notes).length,
|
|
|
|
onlineUsers: Object.keys(users).length,
|
|
|
|
distinctOnlineUsers: distinctaddresses.length,
|
|
|
|
notesCount: notecount,
|
|
|
|
registeredUsers: regcount,
|
|
|
|
onlineRegisteredUsers: regaddresses.length,
|
|
|
|
distinctOnlineRegisteredUsers: distinctregaddresses.length,
|
|
|
|
isConnectionBusy: connectProcessQueue.lock,
|
|
|
|
connectionSocketQueueLength: connectProcessQueue.queue.length,
|
|
|
|
isDisconnectBusy: disconnectProcessQueue.lock,
|
|
|
|
disconnectSocketQueueLength: disconnectProcessQueue.queue.length
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.catch(function (err) {
|
2020-05-16 19:25:20 +00:00
|
|
|
logger.error('count user failed: ' + err)
|
|
|
|
return Promise.reject(new Error('count user failed: ' + err))
|
2020-01-04 21:59:57 +00:00
|
|
|
})
|
2016-04-20 10:03:55 +00:00
|
|
|
}).catch(function (err) {
|
2020-05-16 19:25:20 +00:00
|
|
|
logger.error('count note failed: ' + err)
|
|
|
|
return Promise.reject(new Error('count note failed: ' + err))
|
2017-03-08 10:45:51 +00:00
|
|
|
})
|
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 &&
|
2019-05-20 08:04:35 +00:00
|
|
|
connectProcessQueue.queue.length === 0 && !connectProcessQueue.lock &&
|
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
|
|
|
}
|
|
|
|
|
2019-05-23 10:40:07 +00:00
|
|
|
async function parseNoteIdFromSocketAsync (socket) {
|
|
|
|
const noteId = extractNoteIdFromSocket(socket)
|
2017-03-08 10:45:51 +00:00
|
|
|
if (!noteId) {
|
2019-05-23 10:40:07 +00:00
|
|
|
return null
|
2017-03-08 10:45:51 +00:00
|
|
|
}
|
2015-05-04 07:53:29 +00:00
|
|
|
|
2019-05-20 08:04:35 +00:00
|
|
|
return new Promise((resolve, reject) => {
|
2019-05-23 10:40:07 +00:00
|
|
|
models.Note.parseNoteId(noteId, function (err, id) {
|
|
|
|
if (err) {
|
|
|
|
reject(err)
|
|
|
|
}
|
|
|
|
if (!id) {
|
|
|
|
resolve(null)
|
|
|
|
}
|
2019-05-20 08:04:35 +00:00
|
|
|
resolve(id)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
2019-05-15 08:25:20 +00:00
|
|
|
// TODO: test it
|
2019-05-20 08:04:35 +00:00
|
|
|
async function fetchFullNoteAsync (noteId) {
|
|
|
|
return models.Note.findOne({
|
|
|
|
where: {
|
|
|
|
id: noteId
|
|
|
|
},
|
|
|
|
include: [{
|
2017-03-08 10:45:51 +00:00
|
|
|
model: models.User,
|
|
|
|
as: 'owner'
|
|
|
|
}, {
|
|
|
|
model: models.User,
|
|
|
|
as: 'lastchangeuser'
|
|
|
|
}, {
|
|
|
|
model: models.Author,
|
|
|
|
as: 'authors',
|
|
|
|
include: [{
|
|
|
|
model: models.User,
|
|
|
|
as: 'user'
|
|
|
|
}]
|
|
|
|
}]
|
2019-05-20 08:04:35 +00:00
|
|
|
})
|
|
|
|
}
|
2017-01-10 02:02:37 +00:00
|
|
|
|
2019-05-20 08:04:35 +00:00
|
|
|
function buildAuthorProfilesFromNote (noteAuthors) {
|
|
|
|
const authors = {}
|
|
|
|
noteAuthors.forEach((author) => {
|
|
|
|
const profile = models.User.getProfile(author.user)
|
|
|
|
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
|
|
|
}
|
2019-05-20 08:04:35 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
return authors
|
|
|
|
}
|
2015-05-04 07:53:29 +00:00
|
|
|
|
2019-05-20 08:04:35 +00:00
|
|
|
function makeNewServerNote (note) {
|
|
|
|
const authors = buildAuthorProfilesFromNote(note.authors)
|
2016-04-20 10:03:55 +00:00
|
|
|
|
2019-05-20 08:04:35 +00:00
|
|
|
return {
|
|
|
|
id: note.id,
|
|
|
|
alias: note.alias,
|
|
|
|
title: note.title,
|
|
|
|
owner: note.ownerId,
|
|
|
|
ownerprofile: note.owner ? models.User.getProfile(note.owner) : null,
|
|
|
|
permission: note.permission,
|
|
|
|
lastchangeuser: note.lastchangeuserId,
|
|
|
|
lastchangeuserprofile: note.lastchangeuser ? models.User.getProfile(note.lastchangeuser) : null,
|
|
|
|
socks: [],
|
|
|
|
users: {},
|
|
|
|
tempUsers: {},
|
|
|
|
createtime: moment(note.createdAt).valueOf(),
|
|
|
|
updatetime: moment(note.lastchangeAt).valueOf(),
|
|
|
|
server: new ot.EditorSocketIOServer(note.content, [], note.id, ifMayEdit, operationCallback),
|
|
|
|
authors: authors,
|
|
|
|
authorship: note.authorship
|
2017-03-08 10:45:51 +00:00
|
|
|
}
|
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)
|
|
|
|
// 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
|
2019-08-01 03:24:02 +00:00
|
|
|
user.name = 'Guest ' + chance.animal()
|
2017-03-08 10:45:51 +00:00
|
|
|
user.login = false
|
|
|
|
}
|
2015-06-01 10:04:25 +00:00
|
|
|
}
|
2015-05-04 07:53:29 +00:00
|
|
|
|
2019-05-20 08:04:35 +00:00
|
|
|
function canEditNote (notePermission, noteOwnerId, currentUserId) {
|
2019-05-15 08:25:20 +00:00
|
|
|
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 03:40:16 +00:00
|
|
|
function getUniqueColorPerNote (noteId, maxAttempt = 10) {
|
2019-05-20 08:04:35 +00:00
|
|
|
// random color
|
|
|
|
let color = randomcolor()
|
|
|
|
if (!notes[noteId]) return color
|
2019-05-24 04:41:53 +00:00
|
|
|
|
2019-05-20 08:04:35 +00:00
|
|
|
const maxrandomcount = maxAttempt
|
|
|
|
let randomAttemp = 0
|
|
|
|
let found = false
|
|
|
|
do {
|
|
|
|
Object.keys(notes[noteId].users).forEach(userId => {
|
|
|
|
if (notes[noteId].users[userId].color === color) {
|
|
|
|
found = true
|
|
|
|
}
|
2019-05-24 03:40:16 +00:00
|
|
|
})
|
2019-05-20 08:04:35 +00:00
|
|
|
if (found) {
|
|
|
|
color = randomcolor()
|
|
|
|
randomAttemp++
|
|
|
|
}
|
|
|
|
} while (found && randomAttemp < maxrandomcount)
|
|
|
|
return color
|
2019-05-24 04:41:53 +00:00
|
|
|
}
|
|
|
|
|
2019-05-20 08:04:35 +00:00
|
|
|
function queueForConnect (socket) {
|
|
|
|
connectProcessQueue.push(socket.id, async function () {
|
|
|
|
try {
|
|
|
|
const noteId = await exports.parseNoteIdFromSocketAsync(socket)
|
|
|
|
if (!noteId) {
|
|
|
|
return exports.failConnection(404, 'note id not found', socket)
|
|
|
|
}
|
|
|
|
// store noteId in this socket session
|
|
|
|
socket.noteId = noteId
|
|
|
|
// initialize user data
|
|
|
|
// random color
|
|
|
|
var color = getUniqueColorPerNote(noteId)
|
|
|
|
// 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
|
|
|
|
}
|
|
|
|
exports.updateUserData(socket, users[socket.id])
|
|
|
|
try {
|
|
|
|
if (!isNoteExistsInPool(noteId)) {
|
|
|
|
const note = await fetchFullNoteAsync(noteId)
|
|
|
|
if (!note) {
|
|
|
|
logger.error('note not found')
|
|
|
|
// emit error info
|
|
|
|
socket.emit('info', {
|
|
|
|
code: 404
|
|
|
|
})
|
|
|
|
return socket.disconnect(true)
|
|
|
|
}
|
|
|
|
getNotePool()[noteId] = makeNewServerNote(note)
|
|
|
|
}
|
|
|
|
// if no valid info provided will drop the client
|
|
|
|
if (!socket || !notes[noteId] || !users[socket.id]) {
|
|
|
|
if (notes[noteId]) delete notes[noteId]
|
|
|
|
if (users[socket.id]) delete users[socket.id]
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// check view permission
|
|
|
|
if (!exports.checkViewPermission(socket.request, notes[noteId])) {
|
|
|
|
if (notes[noteId]) delete notes[noteId]
|
|
|
|
if (users[socket.id]) delete users[socket.id]
|
|
|
|
logger.error('connection forbidden')
|
|
|
|
// emit error info
|
|
|
|
socket.emit('info', {
|
|
|
|
code: 403
|
|
|
|
})
|
|
|
|
return socket.disconnect(true)
|
|
|
|
}
|
2019-08-01 17:01:34 +00:00
|
|
|
const note = notes[noteId]
|
|
|
|
const user = users[socket.id]
|
2019-05-20 08:04:35 +00:00
|
|
|
// 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)
|
2019-05-24 04:41:53 +00:00
|
|
|
|
2019-05-20 08:04:35 +00:00
|
|
|
// update user note history
|
|
|
|
exports.updateHistory(user.userid, note)
|
2016-10-10 12:25:48 +00:00
|
|
|
|
2019-05-20 08:04:35 +00:00
|
|
|
exports.emitOnlineUsers(socket)
|
|
|
|
exports.emitRefresh(socket)
|
2017-03-08 10:45:51 +00:00
|
|
|
|
2019-05-20 08:04:35 +00:00
|
|
|
const socketClient = new RealtimeClientConnection(socket)
|
|
|
|
socketClient.registerEventHandler()
|
2017-03-08 10:45:51 +00:00
|
|
|
|
2019-05-20 08:04:35 +00:00
|
|
|
if (config.debug) {
|
2019-08-01 17:01:34 +00:00
|
|
|
const noteId = socket.noteId
|
2019-05-20 08:04:35 +00:00
|
|
|
logger.info('SERVER connected a client to [' + noteId + ']:')
|
|
|
|
logger.info(JSON.stringify(user))
|
2020-05-16 19:25:20 +00:00
|
|
|
getStatus().then(function (data) {
|
2019-05-20 08:04:35 +00:00
|
|
|
logger.info(JSON.stringify(data))
|
|
|
|
})
|
2016-04-20 10:03:55 +00:00
|
|
|
}
|
2019-05-20 08:04:35 +00:00
|
|
|
} catch (err) {
|
|
|
|
logger.error(err)
|
|
|
|
// emit error info
|
|
|
|
socket.emit('info', {
|
|
|
|
code: 500
|
|
|
|
})
|
|
|
|
return socket.disconnect(true)
|
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
return exports.failConnection(500, err, socket)
|
2017-03-08 10:45:51 +00:00
|
|
|
}
|
|
|
|
})
|
2019-05-20 08:04:35 +00:00
|
|
|
}
|
2017-03-08 10:45:51 +00:00
|
|
|
|
2019-05-20 08:04:35 +00:00
|
|
|
function connection (socket) {
|
|
|
|
if (realtime.maintenance) return
|
|
|
|
queueForConnect(socket)
|
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()
|
2019-05-20 08:04:35 +00:00
|
|
|
connectProcessQueue.stop()
|
2019-05-27 07:19:53 +00:00
|
|
|
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.updateNote = updateNote
|
|
|
|
exports.failConnection = failConnection
|
|
|
|
exports.updateUserData = updateUserData
|
|
|
|
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.getUserFromUserPool = getUserFromUserPool
|
|
|
|
exports.buildUserOutData = buildUserOutData
|
2019-05-06 19:15:33 +00:00
|
|
|
exports.emitCheck = emitCheck
|
|
|
|
exports.disconnectSocketOnNote = disconnectSocketOnNote
|
2019-05-27 07:19:53 +00:00
|
|
|
exports.queueForDisconnect = queueForDisconnect
|
|
|
|
exports.terminate = terminate
|
2019-05-15 06:33:09 +00:00
|
|
|
exports.updateHistory = updateHistory
|
2019-05-15 08:25:20 +00:00
|
|
|
exports.ifMayEdit = ifMayEdit
|
2019-05-20 08:04:35 +00:00
|
|
|
exports.parseNoteIdFromSocketAsync = parseNoteIdFromSocketAsync
|
2019-05-27 07:19:53 +00:00
|
|
|
exports.disconnectProcessQueue = disconnectProcessQueue
|
2019-05-24 04:41:53 +00:00
|
|
|
exports.users = users
|
2019-05-20 08:04:35 +00:00
|
|
|
exports.getUserPool = getUserPool
|
|
|
|
|
|
|
|
exports.notes = notes
|
|
|
|
exports.getNotePool = getNotePool
|
|
|
|
exports.getNotePoolSize = getNotePoolSize
|
|
|
|
exports.isNoteExistsInPool = isNoteExistsInPool
|
|
|
|
exports.addNote = addNote
|
|
|
|
exports.getNoteFromNotePool = getNoteFromNotePool
|
|
|
|
exports.deleteNoteFromPool = deleteNoteFromPool
|
|
|
|
exports.deleteAllNoteFromPool = deleteAllNoteFromPool
|
|
|
|
|
2019-05-10 11:10:00 +00:00
|
|
|
exports.saveRevisionJob = saveRevisionJob
|