forked from OpenUserJS/OpenUserJS.org
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
546 lines (460 loc) · 16.6 KB
/
Copy pathscript.js
File metadata and controls
546 lines (460 loc) · 16.6 KB
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
var fs = require('fs');
var formidable = require('formidable');
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 modelsList = require('../libs/modelsList');
var modelQuery = require('../libs/modelQuery');
var modelParser = require('../libs/modelParser');
var countTask = require('../libs/tasks').countTask;
// Let script controllers know this is a lib route
exports.lib = function (controller) {
return (function (req, res, next) {
req.route.params.isLib = true;
controller(req, res, next);
});
};
// Display which scripts use a library hosted on the site
/*exports.useLib = function (req, res, next) {
var installName = req.route.params.shift() + '/'
+ req.route.params.shift();
var user = req.session.user;
var options = { username: user ? user.name : '' };
Script.findOne({ installName: installName + '.js' }, function (err, lib) {
if (err || !lib) { return next(); }
options.title = 'Scripts that use <a href="/libs/' + installName + '">'
+ lib.name + '</a>';
modelsList.listScripts({ uses: lib.installName },
req.route.params, '/use/lib/' + installName,
function (scriptsList) {
options.scriptsList = scriptsList;
res.render('group', options);
});
});
};*/
var getScriptPageTasks = function (options) {
var tasks = [];
// Shortcuts
var script = options.script;
var authedUser = options.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, options, 'issueCount'));
// Show collaborators of the script
if (script.meta.author && script.meta.collaborator) {
options.hasCollab = true;
if (typeof script.meta.collaborator === 'string') {
options.script.collaborators = [{ url: encodeURIComponent(script.meta.collaborator), text: script.meta.collaborator }];
} else {
options.script.collaborators = [];
script.meta.collaborator.forEach(function (collaborator) {
options.script.collaborators.push({ url: encodeURIComponent(collaborator), text: collaborator });
});
}
}
// Show licensings of the script
if (script.meta.license) {
if (typeof script.meta.license === 'string') {
options.script.licenses = [{ name: script.meta.license }];
} else {
options.script.licenses = [];
script.meta.license.forEach(function (license) {
options.script.licenses.push({ name: license });
});
}
} else if (!script.isLib) {
options.script.meta.licenses = [{ name: 'MIT License (Expat)' }];
}
// 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)) {
options.script.homepages = [{
url: script.meta.homepageURL,
text: decodeURI(script.meta.homepageURL),
hasNoFollow: !/^(?:https?:\/\/)?openuserjs\.org\//i.test(script.meta.homepageURL)
}];
}
} else {
options.script.homepages = [];
script.meta.homepageURL.forEach(function (homepage) {
htmlStub = '<a href="' + homepage + '"></a>';
if (htmlStub === sanitizeHtml(htmlStub, htmlWhitelistLink)) {
options.script.homepages.push({
url: homepage,
text: decodeURI(homepage),
hasNoFollow: !/^(?:https?:\/\/)?openuserjs\.org/i.test(homepage)
});
}
});
}
}
// Show the groups the script belongs to
tasks.push(function (callback) {
script.hasGroups = false;
script.groups = [];
Group.find({
_scriptIds: script._id
}, function (err, scriptGroupList) {
if (err) return callback(err);
scriptGroupList = _.map(scriptGroupList, modelParser.parseGroup);
script.hasGroups = scriptGroupList.length > 0;
script.groups = scriptGroupList;
callback();
});
});
// 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 (callback) {
Script.find({
installName: { $in: script.uses }
}, function (err, scriptLibraryList) {
if (err) return callback(err);
script.libs = scriptLibraryList;
script.libs = _.map(script.libs, modelParser.parseScript);
callback();
});
});
} else if (script.isLib) {
script.isUsed = false;
script.usedBy = [];
tasks.push(function (callback) {
Script.find({
uses: script.installName
}, function (err, libraryScriptList) {
if (err) return callback(err);
script.isUsed = libraryScriptList.length > 0;
script.usedBy = libraryScriptList;
script.usedBy = _.map(script.usedBy, modelParser.parseScript);
callback();
});
});
}
// Setup the voting UI
tasks.push(function (callback) {
var voteUrl = '/vote' + script.scriptPageUrl;
options.voteUpUrl = voteUrl + '/up';
options.voteDownUrl = voteUrl + '/down';
options.unvoteUrl = voteUrl + '/unvote';
options.voteable = false;
options.votedUp = false;
options.votedDown = false;
// Can't vote when not logged in or when user owns the script.
if (!authedUser || options.isOwner) {
callback();
return;
}
Vote.findOne({
_scriptId: script._id,
_userId: authedUser._id
}, function (err, voteModel) {
options.voteable = !script.isOwner;
if (voteModel) {
if (voteModel.vote) {
options.votedUp = true;
} else {
options.votedDown = true;
}
}
callback();
});
});
// Setup the flagging UI
tasks.push(function (callback) {
var flagUrl = '/flag' + (script.isLib ? '/libs/' : '/scripts/') + script.installNameSlug;
// Can't flag when not logged in or when user owns the script.
if (!authedUser || options.isOwner) {
callback();
return;
}
flagLib.flaggable(Script, script, authedUser,
function (canFlag, author, flag) {
if (flag) {
flagUrl += '/unflag';
options.flagged = true;
options.canFlag = true;
} else {
options.canFlag = canFlag;
}
options.flagUrl = flagUrl;
callback();
});
});
// Set up the removal UI
tasks.push(function (callback) {
// Can't remove when not logged in or when user owns the script.
if (!authedUser || options.isOwner) {
callback();
return;
}
removeLib.removeable(Script, script, authedUser,
function (canRemove, author) {
options.canRemove = canRemove;
options.flags = script.flags || 0;
options.removeUrl = '/remove' + (script.isLib ? '/libs/' : '/scripts/') + script.installNameSlug;
if (!canRemove) { return callback(); }
flagLib.getThreshold(Script, script, author,
function (threshold) {
options.threshold = threshold;
callback();
});
});
});
return tasks;
};
var setupScriptSidePanel = function (options) {
// Shortcuts
var script = options.script;
var authedUser = options.authedUser;
// User
if (options.isOwner) {
options.authorTools = {};
}
// Mod
if (authedUser && authedUser.isMod) {
//options.authorTools = {}; // TODO: Support moderator edits on scripts?
options.modTools = {};
}
// Admin
if (authedUser && authedUser.isAdmin) {
options.adminTools = {};
}
};
// View a detailed description of a script
// This is the most intensive page to render on the site
exports.view = function (req, res, next) {
var authedUser = req.session.user;
var installNameSlug = scriptStorage.getInstallName(req);
var scriptAuthor = req.route.params.username;
var scriptNameSlug = req.route.params.scriptname;
var isLib = req.route.params.isLib;
Script.findOne({
installName: scriptStorage
.caseInsensitive(installNameSlug + (isLib ? '.js' : '.user.js'))
}, function (err, scriptData) {
if (err || !scriptData) { return next(); }
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(scriptData);
options.isOwner = authedUser && authedUser._id == script._authorId;
modelParser.renderScript(script);
script.installNameSlug = installNameSlug;
script.scriptPermalinkInstallPageUrl = 'http://' + req.get('host') + script.scriptInstallPageUrl;
// Metadata
options.title = script.name + ' | OpenUserJS.org';
options.pageMetaDescription = script.meta.description ? script.meta.description : null;
options.isScriptPage = true;
// SearchBar
options.searchBarPlaceholder = modelQuery.scriptListQueryDefaults.searchBarPlaceholder;
options.searchBarFormAction = modelQuery.scriptListQueryDefaults.searchBarFormAction;
// SideBar
setupScriptSidePanel(options);
//--- Tasks
tasks = tasks.concat(getScriptPageTasks(options));
//---
function preRender() {
var pageMetaKeywords = ['userscript', 'greasemonkey'];
if (script.groups)
pageMetaKeywords.concat(_.pluck(script.groups, 'name'));
options.pageMetaKeywords = pageMetaKeywords.join(', ');
};
function render() { res.render('pages/scriptPage', options); }
function asyncComplete() { preRender(); render(); }
async.parallel(tasks, asyncComplete);
});
};
// route to edit a script
exports.edit = function (req, res, next) {
var authedUser = req.session.user;
if (!authedUser) { return res.redirect('/login'); }
// Support routes lacking the :username. TODO: Remove this functionality.
req.route.params.username = authedUser.name.toLowerCase();
var installNameSlug = scriptStorage.getInstallName(req);
var scriptAuthor = req.route.params.username;
var scriptNameSlug = req.route.params.scriptname;
var isLib = req.route.params.isLib;
Script.findOne({
installName: scriptStorage
.caseInsensitive(installNameSlug + (isLib ? '.js' : '.user.js'))
}, function (err, scriptData) {
if (err || !scriptData) { return next(); }
//
var options = {};
var tasks = [];
// Session
authedUser = options.authedUser = modelParser.parseUser(authedUser);
options.isMod = authedUser && authedUser.isMod;
options.isAdmin = authedUser && authedUser.isAdmin;
//
var script = options.script = modelParser.parseScript(scriptData);
options.isOwner = authedUser && authedUser._id == script._authorId;
options.title = 'Edit Metadata: ' + script.name + ' | OpenUserJS.org';
// If authed user is not the script author.
if (!options.isOwner) { return next(); }
// SearchBar
options.searchBarPlaceholder = modelQuery.scriptListQueryDefaults.searchBarPlaceholder;
options.searchBarFormAction = modelQuery.scriptListQueryDefaults.searchBarFormAction;
var baseUrl = script && script.isLib ? '/libs/' : '/scripts/';
if (req.body.remove) {
// POST
scriptStorage.deleteScript(scriptData.installName, function () {
res.redirect(authedUser.userScriptListPageUrl);
});
} else if (typeof req.body.about !== 'undefined') {
// POST
scriptData.about = req.body.about;
var scriptGroups = (req.body.groups || "");
scriptGroups = scriptGroups.split(/,/);
addScriptToGroups(scriptData, scriptGroups, function () {
res.redirect(script.scriptPageUrl);
});
} else {
// GET
options.script = script;
tasks = tasks.concat(getScriptPageTasks(options));
tasks.push(function (callback) {
callback();
});
// Groups
options.canCreateGroup = (!script._groupId).toString();
function preRender() {
var groupNameList = (options.script.groups || []).map(function (group) {
return group.name;
});
options.groupNameListJSON = JSON.stringify(groupNameList);
};
function render() { res.render('pages/scriptEditMetadataPage', options); }
function asyncComplete() { preRender(); render(); }
async.parallel(tasks, asyncComplete);
// Group.find({ _scriptIds: script._id }, 'name', function (err, groups) {
// var groupsArr = (groups || []).map(function (group) {
// return group.name;
// });
// res.render('scriptEdit', {
// title: script.name,
// name: script.name,
// install: (script.isLib ? '/libs/src/' : '/install/')
// + script.installName,
// source: baseUrl + installName + '/source',
// about: script.about,
// groups: JSON.stringify(groupsArr),
// canCreateGroup: (!script._groupId).toString(),
// isLib: script.isLib,
// username: user ? user.name : null
// });
// });
}
});
};
// Script voting
exports.vote = function (req, res, next) {
var isLib = req.route.params.isLib;
var installName = scriptStorage.getInstallName(req)
+ (isLib ? '.js' : '.user.js');
var vote = req.route.params.vote;
var user = req.session.user;
var url = req._parsedUrl.pathname.split('/');
var unvote = false;
if (!user) { return res.redirect('/login'); }
if (url.length > 5) { url.pop(); }
url.shift();
url.shift();
url = '/' + url.join('/');
url = encodeURI(url);
if (vote === 'up') {
vote = true;
} else if (vote === 'down') {
vote = false;
} else if (vote === 'unvote') {
unvote = true;
} else {
return res.redirect(url);
}
Script.findOne({ installName: scriptStorage.caseInsensitive(installName) },
function (err, script) {
if (err || !script) { return res.redirect(url); }
Vote.findOne({ _scriptId: script._id, _userId: user._id },
function (err, voteModel) {
var oldVote = null;
var votes = script.votes || 0;
var flags = 0;
function saveScript() {
if (!flags) {
return script.save(function (err, script) { res.redirect(url); });
}
flagLib.getAuthor(script, function (author) {
flagLib.saveContent(Script, script, author, flags,
function (flagged) {
res.redirect(url);
});
});
}
if (!script.rating) { script.rating = 0; }
if (!script.votes) { script.votes = 0; }
if (user._id == script._authorId || (!voteModel && unvote)) {
return res.redirect(url);
} else if (!voteModel) {
voteModel = new Vote({
vote: vote,
_scriptId: script._id,
_userId: user._id
});
script.rating += vote ? 1 : -1;
script.votes = votes + 1;
if (vote) { flags = -1; }
} else if (unvote) {
oldVote = voteModel.vote;
return voteModel.remove(function () {
script.rating += oldVote ? -1 : 1;
script.votes = votes <= 0 ? 0 : votes - 1;
if (oldVote) { flags = 1; }
saveScript();
});
} else if (voteModel.vote !== vote) {
voteModel.vote = vote;
script.rating += vote ? 2 : -2;
flags = vote ? -1 : 1;
}
voteModel.save(saveScript);
}
);
}
);
};
// Script flagging
exports.flag = function (req, res, next) {
var isLib = req.route.params.isLib;
var installName = scriptStorage.getInstallName(req);
var unflag = req.route.params.unflag;
Script.findOne({ installName: scriptStorage
.caseInsensitive(installName + (isLib ? '.js' : '.user.js')) },
function (err, script) {
var fn = flagLib[unflag && unflag === 'unflag' ? 'unflag' : 'flag'];
if (err || !script) { return next(); }
fn(Script, script, req.session.user, function (flagged) {
res.redirect((isLib ? '/libs/' : '/scripts/') + encodeURI(installName));
});
}
);
};