-
Notifications
You must be signed in to change notification settings - Fork 326
/
Copy pathscript.js
526 lines (441 loc) · 15.8 KB
/
script.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
'use strict';
// Define some pseudo module globals
var isPro = require('../libs/debug').isPro;
var isDev = require('../libs/debug').isDev;
var isDbg = require('../libs/debug').isDbg;
//
var async = require('async');
var _ = require('underscore');
var sanitizeHtml = require('sanitize-html');
var htmlWhitelistLink = require('../libs/htmlWhitelistLink.json');
var Discussion = require('../models/discussion').Discussion;
var Group = require('../models/group').Group;
var Script = require('../models/script').Script;
var Vote = require('../models/vote').Vote;
var scriptStorage = require('./scriptStorage');
var addScriptToGroups = require('./group').addScriptToGroups;
var flagLib = require('../libs/flag');
var removeLib = require('../libs/remove');
var modelQuery = require('../libs/modelQuery');
var modelParser = require('../libs/modelParser');
var countTask = require('../libs/tasks').countTask;
var pageMetadata = require('../libs/templateHelpers').pageMetadata;
// Let controllers know this is a `new` route
exports.new = function (aController) {
return (function (aReq, aRes, aNext) {
aReq.params.isNew = true;
aController(aReq, aRes, aNext);
});
};
// Let controllers know this is a `lib` route
exports.lib = function (aController) {
return (function (aReq, aRes, aNext) {
aReq.params.isLib = true;
aController(aReq, aRes, aNext);
});
};
var getScriptPageTasks = function (aOptions) {
var tasks = [];
// Shortcuts
var script = aOptions.script;
var authedUser = aOptions.authedUser;
// Temporaries
var htmlStub = null;
//--- Tasks
// Show the number of open issues
var scriptOpenIssueCountQuery = Discussion.find({ category: scriptStorage
.caseInsensitive(script.issuesCategorySlug), open: {$ne: false} });
tasks.push(countTask(scriptOpenIssueCountQuery, aOptions, 'issueCount'));
// Show the groups the script belongs to
tasks.push(function (aCallback) {
script.hasGroups = false;
script.groups = [];
Group.find({
_scriptIds: script._id
}, function (aErr, aScriptGroupList) {
if (aErr) return aCallback(aErr);
aScriptGroupList = _.map(aScriptGroupList, modelParser.parseGroup);
script.hasGroups = aScriptGroupList.length > 0;
script.groups = aScriptGroupList;
aCallback();
});
});
// Show homepages of the script
if (script.meta.homepageURL) {
if (typeof script.meta.homepageURL === 'string') {
htmlStub = '<a href="' + script.meta.homepageURL + '"></a>';
if (htmlStub === sanitizeHtml(htmlStub, htmlWhitelistLink)) {
aOptions.script.homepages = [{
url: script.meta.homepageURL,
text: decodeURI(script.meta.homepageURL),
hasNoFollow: !/^(?:https?:\/\/)?openuserjs\.org\//i.test(script.meta.homepageURL)
}];
}
} else {
aOptions.script.homepages = [];
script.meta.homepageURL.forEach(function (aHomepage) {
htmlStub = '<a href="' + aHomepage + '"></a>';
if (htmlStub === sanitizeHtml(htmlStub, htmlWhitelistLink)) {
aOptions.script.homepages.unshift({
url: aHomepage,
text: decodeURI(aHomepage),
hasNoFollow: !/^(?:https?:\/\/)?openuserjs\.org/i.test(aHomepage)
});
}
});
}
}
// Show copyrights of the script
if (script.meta.copyright) {
if (typeof script.meta.copyright === 'string') {
aOptions.script.copyrights = [{ name: script.meta.copyright }];
} else {
aOptions.script.copyrights = [];
script.meta.copyright.forEach(function (aCopyright) {
aOptions.script.copyrights.unshift({ name: aCopyright });
});
}
}
// Show licensings of the script
if (script.meta.license) {
if (typeof script.meta.license === 'string') {
aOptions.script.licenses = [{ name: script.meta.license }];
} else {
aOptions.script.licenses = [];
script.meta.license.forEach(function (aLicense) {
aOptions.script.licenses.unshift({ name: aLicense });
});
}
} else if (!script.isLib) {
aOptions.script.licenses = [{ name: 'MIT License (Expat)' }];
}
// Show collaborators of the script
if (script.meta.oujs && script.meta.oujs.author && script.meta.oujs.collaborator) {
aOptions.hasCollab = true;
if (typeof script.meta.oujs.collaborator === 'string') {
aOptions.script.collaborators = [{ url: encodeURIComponent(script.meta.oujs.collaborator), text: script.meta.oujs.collaborator }];
} else {
aOptions.script.collaborators = [];
script.meta.oujs.collaborator.forEach(function (aCollaborator) {
aOptions.script.collaborators.unshift({ url: encodeURIComponent(aCollaborator), text: aCollaborator });
});
}
}
// Show which libraries hosted on the site a script uses
if (!script.isLib && script.uses && script.uses.length > 0) {
script.usesLibs = true;
script.libs = [];
tasks.push(function (aCallback) {
Script.find({
installName: { $in: script.uses }
}, function (aErr, aScriptLibraryList) {
if (aErr) return aCallback(aErr);
script.libs = aScriptLibraryList;
script.libs = _.map(script.libs, modelParser.parseScript);
aCallback();
});
});
} else if (script.isLib) {
script.isUsed = false;
script.usedBy = [];
tasks.push(function (aCallback) {
Script.find({
uses: script.installName
}, function (aErr, aLibraryScriptList) {
if (aErr) return aCallback(aErr);
script.isUsed = aLibraryScriptList.length > 0;
script.usedBy = aLibraryScriptList;
script.usedBy = _.map(script.usedBy, modelParser.parseScript);
aCallback();
});
});
}
// Setup the voting UI
tasks.push(function (aCallback) {
var voteUrl = '/vote' + script.scriptPageUrl;
aOptions.voteUpUrl = voteUrl + '/up';
aOptions.voteDownUrl = voteUrl + '/down';
aOptions.unvoteUrl = voteUrl + '/unvote';
aOptions.voteable = false;
aOptions.votedUp = false;
aOptions.votedDown = false;
// Can't vote when not logged in or when user owns the script.
if (!authedUser || aOptions.isOwner) {
aCallback();
return;
}
Vote.findOne({
_scriptId: script._id,
_userId: authedUser._id
}, function (aErr, aVoteModel) {
aOptions.voteable = !script.isOwner;
if (aVoteModel) {
if (aVoteModel.vote) {
aOptions.votedUp = true;
} else {
aOptions.votedDown = true;
}
}
aCallback();
});
});
// Setup the flagging UI
tasks.push(function (aCallback) {
var flagUrl = '/flag' + (script.isLib ? '/libs/' : '/scripts/') + script.installNameSlug;
// Can't flag when not logged in or when user owns the script.
if (!authedUser || aOptions.isOwner) {
aCallback();
return;
}
flagLib.flaggable(Script, script, authedUser,
function (aCanFlag, aAuthor, aFlag) {
if (aFlag) {
flagUrl += '/unflag';
aOptions.flagged = true;
aOptions.canFlag = true;
} else {
aOptions.canFlag = aCanFlag;
}
aOptions.flagUrl = flagUrl;
aCallback();
});
});
// Set up the removal UI
tasks.push(function (aCallback) {
// Can't remove when not logged in or when user owns the script.
if (!authedUser || aOptions.isOwner) {
aCallback();
return;
}
removeLib.removeable(Script, script, authedUser,
function (aCanRemove, author) {
aOptions.canRemove = aCanRemove;
aOptions.flags = script.flags || 0;
aOptions.removeUrl = '/remove' + (script.isLib ? '/libs/' : '/scripts/') + script.installNameSlug;
if (!aCanRemove) { return aCallback(); }
flagLib.getThreshold(Script, script, author,
function (aThreshold) {
aOptions.threshold = aThreshold;
aCallback();
});
});
});
return tasks;
};
var setupScriptSidePanel = function (aOptions) {
// Shortcuts
var authedUser = aOptions.authedUser;
// User
if (aOptions.isOwner) {
aOptions.authorTools = {};
}
// Mod
if (authedUser && authedUser.isMod) {
//aOptions.authorTools = {}; // TODO: Support moderator edits on scripts?
aOptions.modTools = {};
}
// Admin
if (authedUser && authedUser.isAdmin) {
aOptions.adminTools = {};
}
};
// View a detailed description of a script
// This is the most intensive page to render on the site
exports.view = function (aReq, aRes, aNext) {
var authedUser = aReq.session.user;
var installNameSlug = scriptStorage.getInstallName(aReq);
var isLib = aReq.params.isLib;
Script.findOne({
installName: scriptStorage
.caseInsensitive(installNameSlug + (isLib ? '.js' : '.user.js'))
}, function (aErr, aScriptData) {
function preRender() {
if (script.groups) {
pageMetadata(options, ['About', script.name, (script.isLib ? 'Libraries' : 'Scripts')],
script.meta.description, _.pluck(script.groups, 'name'));
}
}
function render() { aRes.render('pages/scriptPage', options); }
function asyncComplete() { preRender(); render(); }
//---
if (aErr || !aScriptData) { return aNext(); }
var options = {};
var tasks = [];
// Session
authedUser = options.authedUser = modelParser.parseUser(authedUser);
options.isMod = authedUser && authedUser.isMod;
options.isAdmin = authedUser && authedUser.isAdmin;
// Script
var script = options.script = modelParser.parseScript(aScriptData);
options.isOwner = authedUser && authedUser._id == script._authorId;
modelParser.renderScript(script);
script.installNameSlug = installNameSlug;
script.scriptPermalinkInstallPageUrl = 'http://' + aReq.get('host') + script.scriptInstallPageUrl;
// Page metadata
pageMetadata(options, ['About', script.name, (script.isLib ? 'Libraries' : 'Scripts')],
script.meta.description);
options.isScriptPage = true;
// SearchBar
options.searchBarPlaceholder = modelQuery.scriptListQueryDefaults.searchBarPlaceholder;
options.searchBarFormAction = modelQuery.scriptListQueryDefaults.searchBarFormAction;
// SideBar
setupScriptSidePanel(options);
//--- Tasks
tasks = tasks.concat(getScriptPageTasks(options));
//---
async.parallel(tasks, asyncComplete);
});
};
// route to edit a script
exports.edit = function (aReq, aRes, aNext) {
var authedUser = aReq.session.user;
// Support routes lacking the :username. TODO: Remove this functionality.
aReq.params.username = authedUser.name.toLowerCase();
var installNameSlug = scriptStorage.getInstallName(aReq);
var isLib = aReq.params.isLib;
Script.findOne({
installName: scriptStorage
.caseInsensitive(installNameSlug + (isLib ? '.js' : '.user.js'))
}, function (aErr, aScriptData) {
function preRender() {
var groupNameList = (options.script.groups || []).map(function (aGroup) {
return aGroup.name;
});
options.groupNameListJSON = JSON.stringify(groupNameList);
}
function render() { aRes.render('pages/scriptEditMetadataPage', options); }
function asyncComplete() { preRender(); render(); }
// ---
if (aErr || !aScriptData) { return aNext(); }
//
var options = {};
var tasks = [];
// Session
authedUser = options.authedUser = modelParser.parseUser(authedUser);
options.isMod = authedUser && authedUser.isMod;
options.isAdmin = authedUser && authedUser.isAdmin;
// Page metadata
var script = options.script = modelParser.parseScript(aScriptData);
options.isOwner = authedUser && authedUser._id == script._authorId;
pageMetadata(options, ['Edit', script.name, (script.isLib ? 'Libraries' : 'Scripts')],
script.name);
// If authed user is not the script author.
if (!options.isOwner) { return aNext(); }
// SearchBar
options.searchBarPlaceholder = modelQuery.scriptListQueryDefaults.searchBarPlaceholder;
options.searchBarFormAction = modelQuery.scriptListQueryDefaults.searchBarFormAction;
if (aReq.body.remove) {
// POST
scriptStorage.deleteScript(aScriptData.installName, function () {
aRes.redirect(authedUser.userScriptListPageUrl);
});
} else if (typeof aReq.body.about !== 'undefined') {
// POST
aScriptData.about = aReq.body.about;
var scriptGroups = (aReq.body.groups || "");
scriptGroups = scriptGroups.split(/,/);
addScriptToGroups(aScriptData, scriptGroups, function () {
aRes.redirect(script.scriptPageUrl);
});
} else {
// GET
options.script = script;
tasks = tasks.concat(getScriptPageTasks(options));
tasks.push(function (aCallback) {
aCallback();
});
// Groups
options.canCreateGroup = (!script._groupId).toString();
async.parallel(tasks, asyncComplete);
}
});
};
// Script voting
exports.vote = function (aReq, aRes, aNext) {
var isLib = aReq.params.isLib;
var installName = scriptStorage.getInstallName(aReq)
+ (isLib ? '.js' : '.user.js');
var vote = aReq.params.vote;
var authedUser = aReq.session.user;
var url = aReq._parsedUrl.pathname.split('/');
var unvote = false;
if (url.length > 5) { url.pop(); }
url.shift();
url.shift();
url = '/' + url.join('/');
if (vote === 'up') {
vote = true;
} else if (vote === 'down') {
vote = false;
} else if (vote === 'unvote') {
unvote = true;
} else {
return aRes.redirect(url);
}
Script.findOne({ installName: scriptStorage.caseInsensitive(installName) },
function (aErr, aScript) {
if (aErr || !aScript) { return aRes.redirect(url); }
Vote.findOne({ _scriptId: aScript._id, _userId: authedUser._id },
function (aErr, aVoteModel) {
var oldVote = null;
var votes = aScript.votes || 0;
var flags = 0;
function saveScript() {
if (!flags) {
return aScript.save(function (aErr, aScript) { aRes.redirect(url); });
}
flagLib.getAuthor(aScript, function (aAuthor) {
flagLib.saveContent(Script, aScript, aAuthor, flags,
function (aFlagged) {
aRes.redirect(url);
});
});
}
if (!aScript.rating) { aScript.rating = 0; }
if (!aScript.votes) { aScript.votes = 0; }
if (authedUser._id == aScript._authorId || (!aVoteModel && unvote)) {
return aRes.redirect(url);
} else if (!aVoteModel) {
aVoteModel = new Vote({
vote: vote,
_scriptId: aScript._id,
_userId: authedUser._id
});
aScript.rating += vote ? 1 : -1;
aScript.votes = votes + 1;
if (vote) { flags = -1; }
} else if (unvote) {
oldVote = aVoteModel.vote;
return aVoteModel.remove(function () {
aScript.rating += oldVote ? -1 : 1;
aScript.votes = votes <= 0 ? 0 : votes - 1;
if (oldVote) { flags = 1; }
saveScript();
});
} else if (aVoteModel.vote !== vote) {
aVoteModel.vote = vote;
aScript.rating += vote ? 2 : -2;
flags = vote ? -1 : 1;
}
aVoteModel.save(saveScript);
}
);
}
);
};
// Script flagging
exports.flag = function (aReq, aRes, aNext) {
var isLib = aReq.params.isLib;
var installName = scriptStorage.getInstallName(aReq);
var unflag = aReq.params.unflag;
Script.findOne({ installName: scriptStorage
.caseInsensitive(installName + (isLib ? '.js' : '.user.js')) },
function (aErr, aScript) {
var fn = flagLib[unflag && unflag === 'unflag' ? 'unflag' : 'flag'];
if (aErr || !aScript) { return aNext(); }
fn(Script, aScript, aReq.session.user, function (aFlagged) { // NOTE: Inline function here
aRes.redirect((isLib ? '/libs/' : '/scripts/') + encodeURI(installName));
});
}
);
};