forked from ether/ep_comments_page
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
333 lines (287 loc) · 12.4 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
'use strict';
const AttributePool = require('ep_etherpad-lite/static/js/AttributePool');
const Changeset = require('ep_etherpad-lite/static/js/Changeset');
const eejs = require('ep_etherpad-lite/node/eejs/');
const settings = require('ep_etherpad-lite/node/utils/Settings');
const {Formidable} = require('formidable');
const commentManager = require('./commentManager');
const apiUtils = require('./apiUtils');
const _ = require('underscore');
const padMessageHandler = require('ep_etherpad-lite/node/handler/PadMessageHandler');
const readOnlyManager = require('ep_etherpad-lite/node/db/ReadOnlyManager.js');
let io;
exports.exportEtherpadAdditionalContent = (hookName, context, callback) => callback(['comments']);
exports.padRemove = async (hookName, context) => {
await Promise.all([
commentManager.deleteCommentReplies(context.padID),
commentManager.deleteComments(context.padID),
]);
};
exports.padCopy = async (hookName, context) => {
await Promise.all([
commentManager.copyComments(context.originalPad.id, context.destinationID),
commentManager.copyCommentReplies(context.originalPad.id, context.destinationID),
]);
};
exports.handleMessageSecurity = async (hookName, ctx) => {
// ctx.client was renamed to ctx.socket in newer versions of Etherpad. Fall back to ctx.client in
// case this plugin is installed on an older version of Etherpad.
const {message, socket = ctx.client} = ctx;
const {type: mtype, data: {type: dtype, apool, changeset} = {}} = message;
if (mtype !== 'COLLABROOM') return;
if (dtype !== 'USER_CHANGES') return;
// Nothing needs to be done if the user already has write access.
if (!padMessageHandler.sessioninfos[socket.id].readonly) return;
const pool = new AttributePool().fromJsonable(apool);
const cs = Changeset.unpack(changeset);
const opIter = Changeset.opIterator(cs.ops);
while (opIter.hasNext()) {
const op = opIter.next();
// Only operations that manipulate the 'comment' attribute on existing text are allowed.
if (op.opcode !== '=') return;
const forbiddenAttrib = new Error();
try {
Changeset.eachAttribNumber(op.attribs, (n) => {
// Use an exception to break out of the iteration early.
if (pool.getAttribKey(n) !== 'comment') throw forbiddenAttrib;
});
} catch (err) {
if (err !== forbiddenAttrib) throw err;
return;
}
}
return true;
};
exports.socketio = (hookName, args, cb) => {
io = args.io.of('/comment');
io.on('connection', (socket) => {
const handler = (fn) => (...args) => {
const respond = args.pop();
(async () => await fn(...args))().then(
(val) => respond(null, val),
(err) => respond({name: err.name, message: err.message}));
};
// Join the rooms
socket.on('getComments', handler(async (data) => {
const {padId} = await readOnlyManager.getIds(data.padId);
// Put read-only and read-write users in the same socket.io "room" so that they can see each
// other's updates.
socket.join(padId);
return await commentManager.getComments(padId);
}));
socket.on('getCommentReplies', handler(async (data) => {
const {padId} = await readOnlyManager.getIds(data.padId);
return await commentManager.getCommentReplies(padId);
}));
// On add events
socket.on('addComment', handler(async (data) => {
const {padId} = await readOnlyManager.getIds(data.padId);
const content = data.comment;
const [commentId, comment] = await commentManager.addComment(padId, content);
if (commentId != null && comment != null) {
socket.broadcast.to(padId).emit('pushAddComment', commentId, comment);
return [commentId, comment];
}
}));
socket.on('deleteComment', handler(async (data) => {
const {padId} = await readOnlyManager.getIds(data.padId);
await commentManager.deleteComment(padId, data.commentId, data.authorId);
socket.broadcast.to(padId).emit('commentDeleted', data.commentId);
}));
socket.on('revertChange', handler(async (data) => {
const {padId} = await readOnlyManager.getIds(data.padId);
// Broadcast to all other users that this change was accepted.
// Note that commentId here can either be the commentId or replyId..
await commentManager.changeAcceptedState(padId, data.commentId, false);
socket.broadcast.to(padId).emit('changeReverted', data.commentId);
}));
socket.on('acceptChange', handler(async (data) => {
const {padId} = await readOnlyManager.getIds(data.padId);
// Broadcast to all other users that this change was accepted.
// Note that commentId here can either be the commentId or replyId..
await commentManager.changeAcceptedState(padId, data.commentId, true);
socket.broadcast.to(padId).emit('changeAccepted', data.commentId);
}));
socket.on('bulkAddComment', handler(async (padId, data) => {
padId = (await readOnlyManager.getIds(padId)).padId;
const [commentIds, comments] = await commentManager.bulkAddComments(padId, data);
socket.broadcast.to(padId).emit('pushAddCommentInBulk');
return _.object(commentIds, comments); // {c-123:data, c-124:data}
}));
socket.on('bulkAddCommentReplies', handler(async (padId, data) => {
padId = (await readOnlyManager.getIds(padId)).padId;
const [repliesId, replies] = await commentManager.bulkAddCommentReplies(padId, data);
socket.broadcast.to(padId).emit('pushAddCommentReply', repliesId, replies);
return _.zip(repliesId, replies);
}));
socket.on('updateCommentText', handler(async (data) => {
const {commentId, commentText, authorId} = data;
const {padId} = await readOnlyManager.getIds(data.padId);
await commentManager.changeCommentText(padId, commentId, commentText, authorId);
socket.broadcast.to(padId).emit('textCommentUpdated', commentId, commentText);
}));
socket.on('updateComment', handler(async (data) => {
const {commentId, commentText, authorId, changeFrom, changeTo, changeAcceptedState} = data;
const {padId} = await readOnlyManager.getIds(data.padId);
await commentManager.changeComment(padId, commentId, commentText, changeFrom, changeTo, authorId, changeAcceptedState); // eslint-disable max-len
socket.broadcast.to(padId).emit('commentUpdated', commentId, commentText, changeFrom, changeTo); // eslint-disable max-len
}));
socket.on('addCommentReply', handler(async (data) => {
const {padId} = await readOnlyManager.getIds(data.padId);
const [replyId, reply] = await commentManager.addCommentReply(padId, data);
reply.replyId = replyId;
socket.broadcast.to(padId).emit('pushAddCommentReply', replyId, reply);
return [replyId, reply];
}));
});
return cb();
};
exports.eejsBlock_dd_insert = (hookName, args, cb) => {
args.content += eejs.require('ep_comments_page/templates/menuButtons.ejs');
return cb();
};
exports.eejsBlock_mySettings = (hookName, args, cb) => {
args.content += eejs.require('ep_comments_page/templates/settings.ejs');
return cb();
};
exports.padInitToolbar = (hookName, args, cb) => {
const toolbar = args.toolbar;
const button = toolbar.button({
command: 'addComment',
localizationId: 'ep_comments_page.add_comment.title',
class: 'buttonicon buttonicon-comment-medical',
});
toolbar.registerButton('addComment', button);
return cb();
};
exports.eejsBlock_editbarMenuLeft = (hookName, args, cb) => {
// check if custom button is used
if (JSON.stringify(settings.toolbar).indexOf('addComment') > -1) {
return cb();
}
args.content += eejs.require('ep_comments_page/templates/commentBarButtons.ejs');
return cb();
};
exports.eejsBlock_scripts = (hookName, args, cb) => {
args.content += eejs.require('ep_comments_page/templates/comments.html');
args.content += eejs.require('ep_comments_page/templates/commentIcons.html');
return cb();
};
exports.eejsBlock_styles = (hookName, args, cb) => {
args.content += eejs.require('ep_comments_page/templates/styles.html');
return cb();
};
exports.clientVars = (hook, context, cb) => {
const displayCommentAsIcon =
settings.ep_comments_page ? settings.ep_comments_page.displayCommentAsIcon : false;
const highlightSelectedText =
settings.ep_comments_page ? settings.ep_comments_page.highlightSelectedText : false;
return cb({
displayCommentAsIcon,
highlightSelectedText,
});
};
exports.expressCreateServer = (hookName, args, callback) => {
args.app.get('/p/:pad/:rev?/comments', async (req, res) => {
const fields = req.query;
// check the api key
if (!apiUtils.validateApiKey(fields, res)) return;
// sanitize pad id before continuing
const padIdReceived = (await readOnlyManager.getIds(apiUtils.sanitizePadId(req))).padId;
let data;
try {
data = await commentManager.getComments(padIdReceived);
} catch (err) {
console.error(err.stack ? err.stack : err.toString());
res.json({code: 2, message: 'internal error', data: null});
return;
}
if (data == null) return;
res.json({code: 0, message: 'ok', data});
});
args.app.post('/p/:pad/:rev?/comments', async (req, res) => {
const fields = await new Promise((resolve, reject) => {
new Formidable().parse(req, (err, fields) => err ? reject(err) : resolve(fields));
});
// check the api key
if (!apiUtils.validateApiKey(fields, res)) return;
// check required fields from comment data
if (!apiUtils.validateRequiredFields(fields, ['data'], res)) return;
// sanitize pad id before continuing
const padIdReceived = (await readOnlyManager.getIds(apiUtils.sanitizePadId(req))).padId;
// create data to hold comment information:
let data;
try {
data = JSON.parse(fields.data);
} catch (err) {
res.json({code: 1, message: 'data must be a JSON', data: null});
return;
}
let commentIds, comments;
try {
[commentIds, comments] = await commentManager.bulkAddComments(padIdReceived, data);
} catch (err) {
console.error(err.stack ? err.stack : err.toString());
res.json({code: 2, message: 'internal error', data: null});
return;
}
if (commentIds == null) return;
for (let i = 0; i < commentIds.length; i++) {
io.to(padIdReceived).emit('pushAddComment', commentIds[i], comments[i]);
}
res.json({code: 0, message: 'ok', commentIds});
});
args.app.get('/p/:pad/:rev?/commentReplies', async (req, res) => {
// it's the same thing as the formidable's fields
const fields = req.query;
// check the api key
if (!apiUtils.validateApiKey(fields, res)) return;
// sanitize pad id before continuing
const padIdReceived = (await readOnlyManager.getIds(apiUtils.sanitizePadId(req))).padId;
// call the route with the pad id sanitized
let data;
try {
data = await commentManager.getCommentReplies(padIdReceived);
} catch (err) {
console.error(err.stack ? err.stack : err.toString());
res.json({code: 2, message: 'internal error', data: null});
return;
}
if (data == null) return;
res.json({code: 0, message: 'ok', data});
});
args.app.post('/p/:pad/:rev?/commentReplies', async (req, res) => {
const fields = await new Promise((resolve, reject) => {
new Formidable().parse(req, (err, fields) => err ? reject(err) : resolve(fields));
});
// check the api key
if (!apiUtils.validateApiKey(fields, res)) return;
// check required fields from comment data
if (!apiUtils.validateRequiredFields(fields, ['data'], res)) return;
// sanitize pad id before continuing
const padIdReceived = (await readOnlyManager.getIds(apiUtils.sanitizePadId(req))).padId;
// create data to hold comment reply information:
let data;
try {
data = JSON.parse(fields.data);
} catch (err) {
res.json({code: 1, message: 'data must be a JSON', data: null});
return;
}
let replyIds, replies;
try {
[replyIds, replies] = await commentManager.bulkAddCommentReplies(padIdReceived, data);
} catch (err) {
console.error(err.stack ? err.stack : err.toString());
res.json({code: 2, message: 'internal error', data: null});
return;
}
if (replyIds == null) return;
for (let i = 0; i < replyIds.length; i++) {
replies[i].replyId = replyIds[i];
io.to(padIdReceived).emit('pushAddCommentReply', replyIds[i], replies[i]);
}
res.json({code: 0, message: 'ok', replyIds});
});
return callback();
};