Merge pull request #358 from davidmehren/more-types

More type annotations
This commit is contained in:
Sheogorath 2020-05-17 15:05:51 +02:00 committed by GitHub
commit 241c418ea7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 72 additions and 89 deletions

View file

@ -4,6 +4,6 @@ import { User } from './models'
declare module 'express' { declare module 'express' {
export interface Request { export interface Request {
user?: User; user?: User;
flash (type: string, msg: string): any; flash (type: string, msg?: string): any;
} }
} }

View file

@ -113,7 +113,7 @@ export class Note extends Model<Note> {
@Column(DataType.TEXT) @Column(DataType.TEXT)
get title (): string { get title (): string {
return processData(this.getDataValue('title'), '') return this.getDataValue('title') ?? ''
} }
set title (value: string) { set title (value: string) {
@ -122,7 +122,7 @@ export class Note extends Model<Note> {
@Column(DataType.TEXT({ length: 'long' })) @Column(DataType.TEXT({ length: 'long' }))
get content (): string { get content (): string {
return processData(this.getDataValue('content'), '') return this.getDataValue('content') ?? ''
} }
set content (value: string) { set content (value: string) {

View file

@ -81,7 +81,7 @@ export class Revision extends Model<Revision> {
@Column(DataType.TEXT({ length: 'long' })) @Column(DataType.TEXT({ length: 'long' }))
get patch (): string { get patch (): string {
return processData(this.getDataValue('patch'), '') return this.getDataValue('patch') ?? ''
} }
set patch (value: string) { set patch (value: string) {
@ -90,7 +90,7 @@ export class Revision extends Model<Revision> {
@Column(DataType.TEXT({ length: 'long' })) @Column(DataType.TEXT({ length: 'long' }))
get lastContent (): string { get lastContent (): string {
return processData(this.getDataValue('lastContent'), '') return this.getDataValue('lastContent') ?? ''
} }
set lastContent (value: string) { set lastContent (value: string) {
@ -99,7 +99,7 @@ export class Revision extends Model<Revision> {
@Column(DataType.TEXT({ length: 'long' })) @Column(DataType.TEXT({ length: 'long' }))
get content (): string { get content (): string {
return processData(this.getDataValue('content'), '') return this.getDataValue('content') ?? ''
} }
set content (value: string) { set content (value: string) {

View file

@ -1,5 +1,6 @@
import { EventEmitter } from 'events' import { EventEmitter } from 'events'
import { logger } from '../logger' import { logger } from '../logger'
import { SocketWithNoteId } from '../realtime'
import Selection from './selection' import Selection from './selection'
import Server from './server' import Server from './server'
import TextOperation from './text-operation' import TextOperation from './text-operation'
@ -8,7 +9,7 @@ import WrappedOperation from './wrapped-operation'
export class EditorSocketIOServer extends Server { export class EditorSocketIOServer extends Server {
private readonly users: {} private readonly users: {}
private readonly docId: any private readonly docId: any
private mayWrite: any private mayWrite: (socket: SocketWithNoteId, originIsOperation: boolean, callback: (mayEdit: boolean) => void) => void
constructor (document, operations, docId, mayWrite, operationCallback) { constructor (document, operations, docId, mayWrite, operationCallback) {
super(document, operations) super(document, operations)
@ -16,7 +17,7 @@ export class EditorSocketIOServer extends Server {
EventEmitter.call(this) EventEmitter.call(this)
this.users = {} this.users = {}
this.docId = docId this.docId = docId
this.mayWrite = mayWrite || function (_, cb) { this.mayWrite = mayWrite || function (_, originIsOperation, cb) {
cb(true) cb(true)
} }
this.operationCallback = operationCallback this.operationCallback = operationCallback
@ -32,8 +33,7 @@ export class EditorSocketIOServer extends Server {
} }
socket.emit('doc', docOut) socket.emit('doc', docOut)
socket.on('operation', function (revision, operation, selection) { socket.on('operation', function (revision, operation, selection) {
socket.origin = 'operation' self.mayWrite(socket, true, function (mayWrite) {
self.mayWrite(socket, function (mayWrite) {
if (!mayWrite) { if (!mayWrite) {
logger.info("User doesn't have the right to edit.") logger.info("User doesn't have the right to edit.")
return return
@ -59,8 +59,7 @@ export class EditorSocketIOServer extends Server {
self.onGetOperations(socket, base, head) self.onGetOperations(socket, base, head)
}) })
socket.on('selection', function (obj) { socket.on('selection', function (obj) {
socket.origin = 'selection' self.mayWrite(socket, false, function (mayWrite) {
self.mayWrite(socket, function (mayWrite) {
if (!mayWrite) { if (!mayWrite) {
logger.info("User doesn't have the right to edit.") logger.info("User doesn't have the right to edit.")
return return

View file

@ -1,17 +1,19 @@
import { Author, Note, Revision, User } from './models' import async from 'async'
import Chance from 'chance'
import ot from './ot' import cookie from 'cookie'
import { History } from './history' import cookieParser from 'cookie-parser'
import { logger } from './logger'
import { config } from './config'
import moment from 'moment' import moment from 'moment'
import randomcolor from 'randomcolor' import randomcolor from 'randomcolor'
import async from 'async' import { Socket } from 'socket.io'
import cookieParser from 'cookie-parser' import { config } from './config'
import cookie from 'cookie'
import Chance from 'chance' import { History } from './history'
import { logger } from './logger'
import { Author, Note, Revision, User } from './models'
import { EditorSocketIOServer } from './ot/editor-socketio-server' import { EditorSocketIOServer } from './ot/editor-socketio-server'
export type SocketWithNoteId = Socket & { noteId: string }
const chance = new Chance() const chance = new Chance()
/* eslint-disable @typescript-eslint/no-use-before-define */ /* eslint-disable @typescript-eslint/no-use-before-define */
@ -27,18 +29,18 @@ const realtime: any = {
} }
/* eslint-enable @typescript-eslint/no-use-before-define */ /* eslint-enable @typescript-eslint/no-use-before-define */
const disconnectSocketQueue: any = [] const disconnectSocketQueue: SocketWithNoteId[] = []
function onAuthorizeSuccess (data, accept) { function onAuthorizeSuccess (data, accept): void {
accept() accept()
} }
function onAuthorizeFail (data, message, error, accept) { function onAuthorizeFail (data, message, error, accept): void {
accept() // accept whether authorize or not to allow anonymous usage accept() // accept whether authorize or not to allow anonymous usage
} }
// secure the origin by the cookie // secure the origin by the cookie
function secure (socket, next) { function secure (socket: Socket, next: (err?: any) => void): void {
try { try {
const handshakeData = socket.request const handshakeData = socket.request
if (handshakeData.headers.cookie) { if (handshakeData.headers.cookie) {
@ -60,7 +62,7 @@ function secure (socket, next) {
} }
} }
function emitCheck (note) { function emitCheck (note): void {
const out = { const out = {
title: note.title, title: note.title,
updatetime: note.updatetime, updatetime: note.updatetime,
@ -78,7 +80,7 @@ const notes = {}
let saverSleep = false let saverSleep = false
function finishUpdateNote (note, _note, callback) { function finishUpdateNote (note: any, _note: Note, callback: any) {
if (!note || !note.server) return callback(null, null) if (!note || !note.server) return callback(null, null)
const body = note.server.document const body = note.server.document
const title = note.title = Note.parseNoteTitle(body) const title = note.title = Note.parseNoteTitle(body)
@ -98,12 +100,12 @@ function finishUpdateNote (note, _note, callback) {
}) })
} }
function updateHistory (userId, note, time?) { function updateHistory (userId, note, time?): void {
const noteId = note.alias ? note.alias : Note.encodeNoteId(note.id) const noteId = note.alias ? note.alias : Note.encodeNoteId(note.id)
if (note.server) History.updateHistory(userId, noteId, note.server.document, time) if (note.server) History.updateHistory(userId, noteId, note.server.document, time)
} }
function updateNote (note, callback) { function updateNote (note: any, callback: (err, note) => any): any {
Note.findOne({ Note.findOne({
where: { where: {
id: note.id id: note.id
@ -193,11 +195,10 @@ setInterval(function () {
}) })
}, 60000 * 5) }, 60000 * 5)
let isConnectionBusy let isConnectionBusy: boolean
let isDisconnectBusy: boolean
const connectionSocketQueue: any = [] const connectionSocketQueue: SocketWithNoteId[] = []
let isDisconnectBusy
function getStatus (callback) { function getStatus (callback) {
Note.count().then(function (notecount) { Note.count().then(function (notecount) {
@ -254,14 +255,14 @@ function getStatus (callback) {
}) })
} }
function isReady () { function isReady (): boolean {
return realtime.io && return realtime.io &&
Object.keys(notes).length === 0 && Object.keys(users).length === 0 && Object.keys(notes).length === 0 && Object.keys(users).length === 0 &&
connectionSocketQueue.length === 0 && !isConnectionBusy && connectionSocketQueue.length === 0 && !isConnectionBusy &&
disconnectSocketQueue.length === 0 && !isDisconnectBusy disconnectSocketQueue.length === 0 && !isDisconnectBusy
} }
function extractNoteIdFromSocket (socket) { function extractNoteIdFromSocket (socket): string | boolean {
if (!socket || !socket.handshake) { if (!socket || !socket.handshake) {
return false return false
} }
@ -272,7 +273,7 @@ function extractNoteIdFromSocket (socket) {
} }
} }
function parseNoteIdFromSocket (socket, callback) { function parseNoteIdFromSocket (socket, callback: (err, noteId) => void): void {
const noteId = extractNoteIdFromSocket(socket) const noteId = extractNoteIdFromSocket(socket)
if (!noteId) { if (!noteId) {
return callback(null, null) return callback(null, null)
@ -298,7 +299,7 @@ function buildUserOutData (user) {
return out return out
} }
function emitOnlineUsers (socket) { function emitOnlineUsers (socket: SocketWithNoteId): void {
const noteId = socket.noteId const noteId = socket.noteId
if (!noteId || !notes[noteId]) return if (!noteId || !notes[noteId]) return
const users: any[] = [] const users: any[] = []
@ -314,7 +315,7 @@ function emitOnlineUsers (socket) {
realtime.io.to(noteId).emit('online users', out) realtime.io.to(noteId).emit('online users', out)
} }
function emitUserStatus (socket) { function emitUserStatus (socket: SocketWithNoteId): void {
const noteId = socket.noteId const noteId = socket.noteId
const user = users[socket.id] const user = users[socket.id]
if (!noteId || !notes[noteId] || !user) return if (!noteId || !notes[noteId] || !user) return
@ -322,7 +323,7 @@ function emitUserStatus (socket) {
socket.broadcast.to(noteId).emit('user status', out) socket.broadcast.to(noteId).emit('user status', out)
} }
function emitRefresh (socket) { function emitRefresh (socket: SocketWithNoteId): void {
const noteId = socket.noteId const noteId = socket.noteId
if (!noteId || !notes[noteId]) return if (!noteId || !notes[noteId]) return
const note = notes[noteId] const note = notes[noteId]
@ -342,7 +343,7 @@ function emitRefresh (socket) {
socket.emit('refresh', out) socket.emit('refresh', out)
} }
function isDuplicatedInSocketQueue (queue, socket) { function isDuplicatedInSocketQueue (queue: Socket[], socket: Socket): boolean {
for (let i = 0; i < queue.length; i++) { for (let i = 0; i < queue.length; i++) {
if (queue[i] && queue[i].id === socket.id) { if (queue[i] && queue[i].id === socket.id) {
return true return true
@ -351,7 +352,7 @@ function isDuplicatedInSocketQueue (queue, socket) {
return false return false
} }
function clearSocketQueue (queue, socket) { function clearSocketQueue (queue: Socket[], socket: Socket): void {
for (let i = 0; i < queue.length; i++) { for (let i = 0; i < queue.length; i++) {
if (!queue[i] || queue[i].id === socket.id) { if (!queue[i] || queue[i].id === socket.id) {
queue.splice(i, 1) queue.splice(i, 1)
@ -360,7 +361,7 @@ function clearSocketQueue (queue, socket) {
} }
} }
function connectNextSocket () { function connectNextSocket (): void {
setTimeout(function () { setTimeout(function () {
isConnectionBusy = false isConnectionBusy = false
if (connectionSocketQueue.length > 0) { if (connectionSocketQueue.length > 0) {
@ -371,19 +372,19 @@ function connectNextSocket () {
}, 1) }, 1)
} }
function failConnection (code, err, socket) { function failConnection (errorCode: number, errorMessage: string, socket: Socket): void {
logger.error(err) logger.error(errorMessage)
// clear error socket in queue // clear error socket in queue
clearSocketQueue(connectionSocketQueue, socket) clearSocketQueue(connectionSocketQueue, socket)
connectNextSocket() connectNextSocket()
// emit error info // emit error info
socket.emit('info', { socket.emit('info', {
code: code code: errorCode
}) })
return socket.disconnect(true) socket.disconnect(true)
} }
function interruptConnection (socket, noteId, socketId) { function interruptConnection (socket: Socket, noteId: string, socketId): void {
if (notes[noteId]) delete notes[noteId] if (notes[noteId]) delete notes[noteId]
if (users[socketId]) delete users[socketId] if (users[socketId]) delete users[socketId]
if (socket) { if (socket) {
@ -394,25 +395,17 @@ function interruptConnection (socket, noteId, socketId) {
connectNextSocket() connectNextSocket()
} }
function checkViewPermission (req, note) { function checkViewPermission (req, note): boolean {
if (note.permission === 'private') { if (note.permission === 'private') {
if (req.user && req.user.logged_in && req.user.id === note.owner) { return !!(req.user?.logged_in && req.user.id === note.owner)
return true
} else {
return false
}
} else if (note.permission === 'limited' || note.permission === 'protected') { } else if (note.permission === 'limited' || note.permission === 'protected') {
if (req.user && req.user.logged_in) { return !!(req.user?.logged_in)
return true
} else {
return false
}
} else { } else {
return true return true
} }
} }
function finishConnection (socket, noteId, socketId) { function finishConnection (socket: SocketWithNoteId, noteId: string, socketId: string): void {
// if no valid info provided will drop the client // if no valid info provided will drop the client
if (!socket || !notes[noteId] || !users[socketId]) { if (!socket || !notes[noteId] || !users[socketId]) {
return interruptConnection(socket, noteId, socketId) return interruptConnection(socket, noteId, socketId)
@ -456,7 +449,7 @@ function finishConnection (socket, noteId, socketId) {
} }
} }
function ifMayEdit (socket, callback) { function ifMayEdit (socket: SocketWithNoteId, originIsOperation: boolean, callback: (mayEdit: boolean) => void): void {
const noteId = socket.noteId const noteId = socket.noteId
if (!noteId || !notes[noteId]) return if (!noteId || !notes[noteId]) return
const note = notes[noteId] const note = notes[noteId]
@ -482,7 +475,7 @@ function ifMayEdit (socket, callback) {
break break
} }
// if user may edit and this is a text operation // if user may edit and this is a text operation
if (socket.origin === 'operation' && mayEdit) { if (originIsOperation && mayEdit) {
// save for the last change user id // save for the last change user id
if (socket.request.user && socket.request.user.logged_in) { if (socket.request.user && socket.request.user.logged_in) {
note.lastchangeuser = socket.request.user.id note.lastchangeuser = socket.request.user.id
@ -493,7 +486,7 @@ function ifMayEdit (socket, callback) {
return callback(mayEdit) return callback(mayEdit)
} }
function operationCallback (socket, operation) { function operationCallback (socket: SocketWithNoteId, operation): void {
const noteId = socket.noteId const noteId = socket.noteId
if (!noteId || !notes[noteId]) return if (!noteId || !notes[noteId]) return
const note = notes[noteId] const note = notes[noteId]
@ -524,7 +517,7 @@ function operationCallback (socket, operation) {
} }
} }
}).catch(function (err) { }).catch(function (err) {
return logger.error('operation callback failed: ' + err) logger.error('operation callback failed: ' + err)
}) })
} }
note.tempUsers[userId] = Date.now() note.tempUsers[userId] = Date.now()
@ -535,11 +528,11 @@ function operationCallback (socket, operation) {
}) })
} }
function startConnection (socket) { function startConnection (socket: SocketWithNoteId): void {
if (isConnectionBusy) return if (isConnectionBusy) return
isConnectionBusy = true isConnectionBusy = true
const noteId = socket.noteId const noteId: string = socket.noteId
if (!noteId) { if (!noteId) {
return failConnection(404, 'note id not found', socket) return failConnection(404, 'note id not found', socket)
} }
@ -625,7 +618,7 @@ function startConnection (socket) {
isConnectionBusy = false isConnectionBusy = false
isDisconnectBusy = false isDisconnectBusy = false
function disconnect (socket) { function disconnect (socket: SocketWithNoteId): void {
if (isDisconnectBusy) return if (isDisconnectBusy) return
isDisconnectBusy = true isDisconnectBusy = true
@ -712,7 +705,7 @@ setInterval(function () {
}) })
}, 60000) }, 60000)
function updateUserData (socket, user) { function updateUserData (socket: Socket, user): void {
// retrieve user data from passport // retrieve user data from passport
if (socket.request.user && socket.request.user.logged_in) { if (socket.request.user && socket.request.user.logged_in) {
const profile = User.getProfile(socket.request.user) const profile = User.getProfile(socket.request.user)
@ -727,7 +720,7 @@ function updateUserData (socket, user) {
} }
} }
function connection (socket) { function connection (socket: SocketWithNoteId): void {
if (realtime.maintenance) return if (realtime.maintenance) return
parseNoteIdFromSocket(socket, function (err, noteId) { parseNoteIdFromSocket(socket, function (err, noteId) {
if (err) { if (err) {
@ -947,7 +940,7 @@ function connection (socket) {
// when a new client disconnect // when a new client disconnect
socket.on('disconnect', function () { socket.on('disconnect', function () {
if (isDuplicatedInSocketQueue(socket, disconnectSocketQueue)) return if (isDuplicatedInSocketQueue(disconnectSocketQueue, socket)) return
disconnectSocketQueue.push(socket) disconnectSocketQueue.push(socket)
disconnect(socket) disconnect(socket)
}) })

View file

@ -1,8 +1,8 @@
import { logger } from './logger'
import { realtime } from './realtime'
import { config } from './config'
import fs from 'fs' import fs from 'fs'
import { config } from './config'
import { logger } from './logger'
import { Revision } from './models' import { Revision } from './models'
import { realtime } from './realtime'
export function getImageMimeType (imagePath: string): string | undefined { export function getImageMimeType (imagePath: string): string | undefined {
const fileExtension = /[^.]+$/.exec(imagePath) const fileExtension = /[^.]+$/.exec(imagePath)
@ -33,21 +33,11 @@ export function stripNullByte (value: string): string {
return value ? value.replace(/\u0000/g, '') : value return value ? value.replace(/\u0000/g, '') : value
} }
export function processData (data, _default, process?) { export function processData<T> (data: T, _default: T, process?: (T) => T): T | undefined {
if (data === undefined) return data if (data === undefined) return undefined
else if (process) { else if (data === null) return _default
if (data === null) { else if (process) return process(data)
return _default else return data
} else {
return process(data)
}
} else {
if (data === null) {
return _default
} else {
return data
}
}
} }
export function handleTermSignals (io): void { export function handleTermSignals (io): void {
@ -65,7 +55,8 @@ export function handleTermSignals (io): void {
if (config.path) { if (config.path) {
// ToDo: add a proper error handler // ToDo: add a proper error handler
// eslint-disable-next-line @typescript-eslint/no-empty-function // eslint-disable-next-line @typescript-eslint/no-empty-function
fs.unlink(config.path, (_) => {}) fs.unlink(config.path, (_) => {
})
} }
const checkCleanTimer = setInterval(function () { const checkCleanTimer = setInterval(function () {
if (realtime.isReady()) { if (realtime.isReady()) {